Commit graph

1691 commits

Author SHA1 Message Date
Dylan DPC
689978c176
Rollup merge of #80733 - steffahn:prettify_pin_links, r=jyn514
Improve links in inline code in `core::pin`.

## Context

So I recently opened #80720. That PR uses HTML-based `<code>foo</code>` syntax in place of `` `foo` `` for some inline code. It looks like usage of `<code>` tags in doc comments is without precedent in the standard library, but the HTML-based syntax has an important advantage:

You can write something like
```
<code>[Box]<[Option]\<T>></code>
```
which becomes: <code>[Box]<[Option]\<T>></code>, whereas with ordinary backtick syntax, you cannot create links for a substring of an inline code block.

## Problem
I recalled (from my own experience) that a way to partially work around this limitation is to do something like
```
[`Box`]`<`[`Option`]`<T>>`
```
which looks like this: [`Box`]`<`[`Option`]`<T>>` _(admitted, it looks even worse on GitHub than in `rustdoc`’s CSS)_.

[Box]: https://doc.rust-lang.org/std/boxed/struct.Box.html "Box"
[`Box`]: https://doc.rust-lang.org/std/boxed/struct.Box.html "Box"
[Option]: https://doc.rust-lang.org/std/option/enum.Option.html "Option"
[`Option`]: https://doc.rust-lang.org/std/option/enum.Option.html "Option"
[Pin]: https://doc.rust-lang.org/std/pin/struct.Pin.html "Pin"
[&mut]: https://doc.rust-lang.org/std/primitive.reference.html "mutable reference"

So I searched the standard library and found that e.g. the [std::pin](https://doc.rust-lang.org/std/pin/index.html) module documentation uses this hack/workaround quite a bit, with types like <code>[Pin]<[Box]\<T>></code> or <code>[Pin]<[&mut] T>></code>. Although the way they look like in this sentence is what I would like them to look like, not what they currently look.

### Status Quo

Here’s a screenshot of what it currently looks like:
![Screenshot_20210105_202751](https://user-images.githubusercontent.com/3986214/103692608-4a978780-4f98-11eb-9451-e13622b2e3c0.png)

With a few HTML-style code blocks, we can fix all the spacing issues in the above screenshot that are due usage of this hack/workaround of putting multiple code blocks right next to each other being used.

### after d3915c555e:
![Screenshot_20210105_202932](https://user-images.githubusercontent.com/3986214/103692688-6f8bfa80-4f98-11eb-9be5-9b370eaef644.png)

There’s still a problem of inconsistency. Especially in a sentence such as
> A [`Pin<P>`][Pin] where `P: Deref` should be considered as a "`P`-style pointer" to _[...]_

looks weird with the variable `P` having different colors (and `Deref` has a different color from before where it was a link, too). Or compare the difference of <code>[Pin]<[Box]\<T>></code> vs [`Box<T>`][Box] where one time the variable is part of the link and the other time it isn’t.

_Note: Color differences show even **more strongly** when the ayu theme is used, while they are a bit less prominent in the light theme than they are in the dark theme, which is the one used for these screenshots._

This is why I’ve added the next commit
### after ceaeb249a3
![Screenshot_20210105_203113](https://user-images.githubusercontent.com/3986214/103693496-ab738f80-4f99-11eb-942d-29dace459734.png)
pulling all the type parameters out of their links, and also the last commit with clearly visible changes
### after 87ac118ba3
![Screenshot_20210105_203252](https://user-images.githubusercontent.com/3986214/103693625-e5dd2c80-4f99-11eb-91b7-470c37934e7e.png)
where more links are added, removing e.g. the inconsistency with `Deref`’s color in e.g. `P: Deref` that I already mentioned above.

## Discussion

I am aware that this PR may very well be overkill. If for now only the first commit (plus the fix for the `Drop` link in e65385fbfa, the link titles 684edf7a70 as far as they apply, and a few of the line-break changes) are wanted, I can reduce this PR to just those changes. I personally find the rendered result with all these changes very nice though. On the other hand, all these `<code>` tags are not very nice in the source code, I’ll admit.

Perhaps alternative solutions could be preferred, such as `rustdoc` support for merging subsequent inline code blocks so that all the cases that currently use workarounds rendered as [`Box`]`<`[`Option`]`<T>>` automatically become <code>[Box]<[Option]\<T>></code> without any need for further changes. Even in this case, having a properly formatted, better looking example in the standard library docs could help motivate such a change to `rustdoc` by prodiving an example of the expected results and also the already existing alternative (i.e. using `<code>`). On the other hand, `` [`Box`]`<`[`Option`]`<T>>` `` isn’t particularly nice-looking source code either. I’m not even sure if I wouldn’t actually find the version `<code>[Box]<[Option]\<T>></code>` cleaner to read.

`@rustbot` modify labels: T-doc, T-rustdoc
2021-04-08 20:29:54 +02:00
The8472
37a5b515e9 implement TrustedRandomAccess for Take iterator adapter 2021-04-08 10:28:22 +02:00
Dylan DPC
a113240b91
Rollup merge of #83689 - estebank:cool-bears-hot-tip, r=davidtwco
Add more info for common trait resolution and async/await errors

* Suggest `Pin::new`/`Box::new`/`Arc::new`/`Box::pin` in more cases
* Point at `impl` and type defs introducing requirements on E0277
2021-04-08 01:01:43 +02:00
bors
ef2ef926a5 Auto merge of #81047 - glittershark:stabilize-cmp-min-max-by, r=kodraus
Stabilize cmp_min_max_by

I would like to propose cmp::{min_by, min_by_key, max_by, max_by_key}
for stabilization.

These are relatively simple and seemingly uncontroversial functions and
have been unchanged in unstable for a while now.

Closes: #64460
2021-04-07 18:02:21 +00:00
lukaslueg
cfe43f9733
Update library/core/src/iter/traits/iterator.rs
Co-authored-by: Yuki Okushi <jtitor@2k36.org>
2021-04-07 18:02:46 +02:00
lukaslueg
4c850f3783
Update library/core/src/iter/traits/iterator.rs
Co-authored-by: Yuki Okushi <jtitor@2k36.org>
2021-04-07 18:02:39 +02:00
Griffin Smith
462f86da9a Stabilize cmp_min_max_by
I would like to propose cmp::{min_by, min_by_key, max_by, max_by_key}
for stabilization.

These are relatively simple and seemingly uncontroversial functions and
have been unchanged in unstable for a while now.
2021-04-07 10:29:04 -04:00
Esteban Küber
dc71166037 Always mention Box::pin when dealing with !Unpin 2021-04-06 19:55:45 -07:00
Aliénore Bouttefeux
389100921a add lint deref_nullptr 2021-04-06 22:01:00 +02:00
lukaslueg
72796a7c36
Merge branch 'master' into stab_peek_mut 2021-04-06 18:23:21 +02:00
lukaslueg
7f32fda78c
Update library/core/src/iter/adapters/peekable.rs
Co-authored-by: Alexander Ronald Altman <alexanderaltman@me.com>
2021-04-06 18:16:02 +02:00
Joshua Nelson
ef4e5b9ecb Rename non_autolinks -> bare_urls 2021-04-05 04:13:34 -04:00
TrolledWoods
fa1624cf13
Added tracking issue number 2021-04-05 09:18:00 +02:00
bors
58e7189650 Auto merge of #83858 - joshtriplett:unsafe-cell-always-inline, r=Mark-Simulacrum
Use `#[inline(always)]` on trivial UnsafeCell methods

UnsafeCell is the standard building block for shared mutable data
structures. UnsafeCell should add zero overhead compared to using raw
pointers directly.

Some reports suggest that debug builds, or even builds at opt-level 1,
may not always be inlining its methods. Mark the methods as
`#[inline(always)]`, since once inlined the methods should result in no
actual code other than field accesses.
2021-04-05 06:21:14 +00:00
bors
b1b0a1597c Auto merge of #83819 - AngelicosPhosphoros:issue-73338-fix-partial-eq-impl, r=Mark-Simulacrum
Optimize jumps in PartialOrd le

Closes https://github.com/rust-lang/rust/issues/73338
This change stops default implementation of `le()` method of PartialOrd from generating jumps.
2021-04-05 03:55:09 +00:00
bors
015d2bc3fe Auto merge of #83864 - Dylan-DPC:rollup-78an86n, r=Dylan-DPC
Rollup of 7 pull requests

Successful merges:

 - #80525 (wasm64 support)
 - #83019 (core: disable `ptr::swap_nonoverlapping_one`'s block optimization on SPIR-V.)
 - #83717 (rustdoc: Separate filter-empty-string out into its own function)
 - #83807 (Tests: Remove redundant `ignore-tidy-linelength` annotations)
 - #83815 (ptr::addr_of documentation improvements)
 - #83820 (Remove attribute `#[link_args]`)
 - #83841 (Allow clobbering unsupported registers in asm!)

Failed merges:

r? `@ghost`
`@rustbot` modify labels: rollup
2021-04-05 01:26:57 +00:00
bors
35aa636159 Auto merge of #83530 - Mark-Simulacrum:bootstrap-bump, r=Mark-Simulacrum
Bump bootstrap to 1.52 beta

This includes the standard bump, but also a workaround for new cargo behavior around clearing out the doc directory when the rustdoc version changes.
2021-04-04 22:45:56 +00:00
Dylan DPC
fbe89e20e8
Rollup merge of #83815 - RalfJung:addr_of, r=kennytm
ptr::addr_of documentation improvements

While writing https://github.com/rust-lang/reference/pull/1001 I figured I could also improve the docs here a bit.
2021-04-05 00:24:32 +02:00
Dylan DPC
4e3f471499
Rollup merge of #83019 - eddyb:spirv-no-block-swap, r=nagisa
core: disable `ptr::swap_nonoverlapping_one`'s block optimization on SPIR-V.

SPIR-V primarily supports what it calls the "Logical addressing model" (and AFAIK for graphical shaders it's the only option), and what that implies is that there is no "memory" to uniformly address at some byte/word level, and that you can't really talk about values having a "raw representation" in terms of sequences of bytes. Therefore, the "block"-wise swapping optimization employed by `ptr::swap_nonoverlapping_one` (where a "block" is 32 bytes, currently), is fundamentally incompatible with SPIR-V "memory".

As such, [Rust-GPU](https://github.com/EmbarkStudios/rust-gpu/)'s `rustc_codegen_spirv` backend cannot currently allow the use of `ptr::swap_nonoverlapping_one` - but that comes at a great price, since it's the building block of `mem::{swap,replace}`, and those in turn are used by e.g. `Option::take` and `Range`'s `Iterator` implementation (the latter blocking the use of `for i in 0..n` loops).

There's 4 options I can see in terms of supporting `ptr::swap_nonoverlapping_one` in `rustc_codegen_spirv`:
* legalize the block-wise swap loop back into swapping whole values, for SPIR-V
  * this is made borderline impossible by the fact that the size of the state "on the stack" is a block, and has to be expanded back to the appropriate size of the value being swapped, so in practice this would have to effectively pattern-match on the exact shape of the block-wise swapping algorithm, as a roundabout way of "patching `core::ptr` on the fly"
* (**this PR**) disable the block-wise swap optimization altogether when `#[cfg(target_arch = "spirv")`
  * I've tested it and it does in fact allow compiling `for i in 0..n` loops, which was my primary motivation
  * main downside IMO is the fact that `core` now acknowledges an out-of-tree backend
    * as a counterpoint, any attempt to compile Rust to SPIR-V would run into this problem, one way or another
* only enable the block-wise swap optimization on targets where it's been empirically proven to be an improvement
  * would avoid any surprises in terms of potentially-broken/inefficient codegen, in general
  * however, it may be universally applicable (thanks to caches), even if the optimal block size could differ
* move low-level swapping into an intrinsic, where the backend can choose any optimization approach it wants
  * this also has an impact on MIR optimizations (cc ``@rust-lang/wg-mir-opt)`` - which currently cannot hope to make sense of e.g. `Option::take` despite it being effectively `_0 = *_1;` `*_1 = None;` `return;`
  * long-term this is my preferred approach, and I can start working on it if that's desired, but I wanted to confirm that this swapping optimization is the final blocker for [Rust-GPU](https://github.com/EmbarkStudios/rust-gpu/) supporting e.g. range `for` loops

r? ``@nagisa`` cc ``@rust-lang/libs``
2021-04-05 00:24:29 +02:00
Eduard-Mihai Burtescu
bc6af97ed0 core: disable ptr::swap_nonoverlapping_one's block optimization on SPIR-V. 2021-04-04 22:26:27 +03:00
Eduard-Mihai Burtescu
3c3d3ddde9 core: rearrange ptr::swap_nonoverlapping_one's cases (no functional changes). 2021-04-04 22:26:00 +03:00
Mark Rousskov
b3a4f91b8d Bump cfgs 2021-04-04 14:57:05 -04:00
Josh Triplett
37498a19de Use #[inline(always)] on trivial UnsafeCell methods
UnsafeCell is the standard building block for shared mutable data
structures. UnsafeCell should add zero overhead compared to using raw
pointers directly.

Some reports suggest that debug builds, or even builds at opt-level 1,
may not always be inlining its methods. Mark the methods as
`#[inline(always)]`, since once inlined the methods should result in no
actual code other than field accesses.
2021-04-04 11:55:13 -07:00
AngelicosPhosphoros
ed0d8fa3e8 Optimize PartialOrd le
Closes https://github.com/rust-lang/rust/issues/73338
This change stops default implementation of `le()` method from generating jumps.
2021-04-04 20:37:48 +03:00
Ralf Jung
b577d7ef25
fix typo
Co-authored-by: kennytm <kennytm@gmail.com>
2021-04-04 19:32:54 +02:00
Dylan DPC
869726d335
Rollup merge of #81619 - SkiFire13:resultshunt-inplace, r=the8472
Implement `SourceIterator` and `InPlaceIterable` for `ResultShunt`
2021-04-04 19:19:59 +02:00
Ralf Jung
5d1747bf07
rely on intra-doc links
Co-authored-by: Yuki Okushi <jtitor@2k36.org>
2021-04-04 11:24:25 +02:00
Ralf Jung
b93137a24e explain that even addr_of cannot deref a NULL ptr 2021-04-03 19:26:54 +02:00
Ralf Jung
a4a6bdd337 addr_of_mut: add example for creating a pointer to uninit data 2021-04-03 19:25:11 +02:00
bors
5662d9343f Auto merge of #80965 - camelid:rename-doc-spotlight, r=jyn514
Rename `#[doc(spotlight)]` to `#[doc(notable_trait)]`

Fixes #80936.

"spotlight" is not a very specific or self-explaining name.
Additionally, the dialog that it triggers is called "Notable traits".
So, "notable trait" is a better name.

* Rename `#[doc(spotlight)]` to `#[doc(notable_trait)]`
* Rename `#![feature(doc_spotlight)]` to `#![feature(doc_notable_trait)]`
* Update documentation
* Improve documentation

r? `@Manishearth`
2021-04-02 07:04:58 +00:00
Jacob Hughes
58218f6c27 Remove T: Debug bound on UnsafeCell Debug impl 2021-03-31 12:11:36 -04:00
Dylan DPC
5b67543c98
Rollup merge of #83579 - RalfJung:ptr-arithmetic, r=dtolnay
Improve pointer arithmetic docs

* Add slightly more detailed definition of "allocated object" to the module docs, and link it from everywhere.
* Clarify the "remains attached" wording a bit (at least I hope this is clearer).
* Remove the sentence about using integer arithmetic; this seems to confuse people even if it is technically correct.

As usual, the edit needs to be done in a dozen places to remain consistent, I hope I got them all.
2021-03-30 11:34:26 +02:00
Dylan DPC
ad2a80e412
Rollup merge of #83571 - a1phyr:feature_const_slice_first_last, r=dtolnay
Constantify some slice methods

Tracking issue: #83570

This PR constantifies the following functions under feature `const_slice_first_last`:
- `slice::first`
- `slice::split_first`
- `slice::last`
- `slice::split_last`

Blocking on `#![feature(const_mut_refs)]`:
- `slice::first_mut`
- `slice::split_first_mut`
- `slice::last_mut`
- `slice::split_last_mut`
2021-03-30 11:34:25 +02:00
Dylan DPC
9ab5f7db30
Rollup merge of #83568 - RalfJung:uninit_array, r=dtolnay
update comment at MaybeUninit::uninit_array

https://github.com/rust-lang/rust/issues/49147 is closed; this now instead needs inline const expressions (#76001).
2021-03-30 11:34:23 +02:00
ltdk
c20ba9cdae Add escape_default method to u8 and [u8] 2021-03-28 17:38:25 -04:00
bors
1df20569dd Auto merge of #81354 - SkiFire13:binary-search-assume, r=nagisa
Instruct LLVM that binary_search returns a valid index

This allows removing bound checks when the return value of `binary_search` is used to index into the slice it was call on. I also added a codegen test for this, not sure if it's the right thing to do (I didn't find anything on the dev guide), but it felt so.
2021-03-28 03:51:22 +00:00
Dylan DPC
b2e254318d
Rollup merge of #82917 - cuviper:iter-zip, r=m-ou-se
Add function core::iter::zip

This makes it a little easier to `zip` iterators:

```rust
for (x, y) in zip(xs, ys) {}
// vs.
for (x, y) in xs.into_iter().zip(ys) {}
```

You can `zip(&mut xs, &ys)` for the conventional `iter_mut()` and
`iter()`, respectively. This can also support arbitrary nesting, where
it's easier to see the item layout than with arbitrary `zip` chains:

```rust
for ((x, y), z) in zip(zip(xs, ys), zs) {}
for (x, (y, z)) in zip(xs, zip(ys, zs)) {}
// vs.
for ((x, y), z) in xs.into_iter().zip(ys).zip(xz) {}
for (x, (y, z)) in xs.into_iter().zip((ys.into_iter().zip(xz)) {}
```

It may also format more nicely, especially when the first iterator is a
longer chain of methods -- for example:

```rust
    iter::zip(
        trait_ref.substs.types().skip(1),
        impl_trait_ref.substs.types().skip(1),
    )
    // vs.
    trait_ref
        .substs
        .types()
        .skip(1)
        .zip(impl_trait_ref.substs.types().skip(1))
```

This replaces the tuple-pair `IntoIterator` in #78204.
There is prior art for the utility of this in [`itertools::zip`].

[`itertools::zip`]: https://docs.rs/itertools/0.10.0/itertools/fn.zip.html
2021-03-27 20:37:07 +01:00
Dylan DPC
ebea9d948f
Rollup merge of #82626 - lcnr:encode_with_shorthandb, r=estebank
update array missing `IntoIterator` msg

fixes #82602

r? ```@estebank``` do you know whether we can use the expr span in `rustc_on_unimplemented`? The label isn't too great rn
2021-03-27 20:37:06 +01:00
Dylan DPC
a900677eb9
Rollup merge of #82525 - RalfJung:unaligned-ref-warn, r=petrochenkov
make unaligned_references future-incompat lint warn-by-default

and also remove the safe_packed_borrows lint that it replaces.

`std::ptr::addr_of!` has hit beta now and will hit stable in a month, so I propose we start fixing https://github.com/rust-lang/rust/issues/27060 for real: creating a reference to a field of a packed struct needs to eventually become a hard error; this PR makes it a warn-by-default future-incompat lint. (The lint already existed, this just raises its default level.) At the same time I removed the corresponding code from unsafety checking; really there's no reason an `unsafe` block should make any difference here.

For references to packed fields outside `unsafe` blocks, this means `unaligned_refereces` replaces the previous `safe_packed_borrows` warning with a link to https://github.com/rust-lang/rust/issues/82523 (and no more talk about unsafe blocks making any difference). So behavior barely changes, the warning is just worded differently. For references to packed fields inside `unsafe` blocks, this PR shows a new future-incompat warning.

Closes https://github.com/rust-lang/rust/issues/46043 because that lint no longer exists.
2021-03-27 20:37:05 +01:00
Ralf Jung
4f03f94863 clarify 'remains attached', and remove recommendation to use integer arithmetic 2021-03-27 19:31:43 +01:00
Ralf Jung
b5d71bfb0f add definition of 'allocated object', and link it from relevant method docs 2021-03-27 19:26:10 +01:00
Josh Stone
f0a6052d62 Add the tracking issue for #![feature(iter_zip)] 2021-03-27 10:14:54 -07:00
Ralf Jung
fb4f48e032 make unaligned_refereces future-incompat lint warn-by-default, and remove the safe_packed_borrows lint that it replaces 2021-03-27 16:59:37 +01:00
Benoît du Garreau
6327e46d8c Constantify some slice methods 2021-03-27 15:48:26 +01:00
Ralf Jung
5cfc98fb7f update comment at MaybeUninit::uninit_array 2021-03-27 14:58:23 +01:00
bors
1010038814 Auto merge of #83245 - the8472:generalize-slice-fill, r=m-ou-se
Generalize and inline slice::fill specializations

This makes the memset specialization applicable to more types. And since the code now lives in a generic method it is also eligible for cross-crate inlining which  should fix #83235
2021-03-27 13:25:16 +00:00
bors
aef11409b4 Auto merge of #78618 - workingjubilee:ieee754-fmt, r=m-ou-se
Add IEEE 754 compliant fmt/parse of -0, infinity, NaN

This pull request improves the Rust float formatting/parsing libraries to comply with IEEE 754's formatting expectations around certain special values, namely signed zero, the infinities, and NaN. It also adds IEEE 754 compliance tests that, while less stringent in certain places than many of the existing flt2dec/dec2flt capability tests, are intended to serve as the beginning of a roadmap to future compliance with the standard. Some relevant documentation is also adjusted with clarifying remarks.

This PR follows from discussion in https://github.com/rust-lang/rfcs/issues/1074, and closes #24623.

The most controversial change here is likely to be that -0 is now printed as -0. Allow me to explain: While there appears to be community support for an opt-in toggle of printing floats as if they exist in the naively expected domain of numbers, i.e. not the extended reals (where floats live), IEEE 754-2019 is clear that a float converted to a string should be capable of being transformed into the original floating point bit-pattern when it satisfies certain conditions (namely, when it is an actual numeric value i.e. not a NaN and the original and destination float width are the same). -0 is given special attention here as a value that should have its sign preserved. In addition, the vast majority of other programming languages not only output `-0` but output `-0.0` here.

While IEEE 754 offers a broad leeway in how to handle producing what it calls a "decimal character sequence", it is clear that the operations a language provides should be capable of round tripping, and it is confusing to advertise the f32 and f64 types as binary32 and binary64 yet have the most basic way of producing a string and then reading it back into a floating point number be non-conformant with the standard. Further, existing documentation suggested that e.g. -0 would be printed with -0 regardless of the presence of the `+` fmt character, but it prints "+0" instead if given such (which was what led to the opening of #24623).

There are other parsing and formatting issues for floating point numbers which prevent Rust from complying with the standard, as well as other well-documented challenges on the arithmetic level, but I hope that this can be the beginning of motion towards solving those challenges.
2021-03-27 10:40:16 +00:00
lcnr
addc51a85f update array missing IntoIterator msg 2021-03-26 21:09:13 +01:00
Lukas Lueg
abcbe54575 Stabilize peekable_peek_mut
Resolves #78302

Update peekable.rs

Update library/core/src/iter/traits/iterator.rs

Co-authored-by: Ashley Mannix <kodraus@hey.com>
2021-03-26 17:41:14 +01:00
Josh Stone
3b1f5e3462 Use iter::zip in library/ 2021-03-26 09:32:29 -07:00
Josh Stone
b362958453 Add function core::iter::zip
This makes it a little easier to `zip` iterators:

```rust
for (x, y) in zip(xs, ys) {}
// vs.
for (x, y) in xs.into_iter().zip(ys) {}
```

You can `zip(&mut xs, &ys)` for the conventional `iter_mut()` and
`iter()`, respectively. This can also support arbitrary nesting, where
it's easier to see the item layout than with arbitrary `zip` chains:

```rust
for ((x, y), z) in zip(zip(xs, ys), zs) {}
for (x, (y, z)) in zip(xs, zip(ys, zs)) {}
// vs.
for ((x, y), z) in xs.into_iter().zip(ys).zip(xz) {}
for (x, (y, z)) in xs.into_iter().zip((ys.into_iter().zip(xz)) {}
```

It may also format more nicely, especially when the first iterator is a
longer chain of methods -- for example:

```rust
    iter::zip(
        trait_ref.substs.types().skip(1),
        impl_trait_ref.substs.types().skip(1),
    )
    // vs.
    trait_ref
        .substs
        .types()
        .skip(1)
        .zip(impl_trait_ref.substs.types().skip(1))
```

This replaces the tuple-pair `IntoIterator` in rust-lang/rust#78204.
There is prior art for the utility of this in [`itertools::zip`].

[`itertools::zip`]: https://docs.rs/itertools/0.10.0/itertools/fn.zip.html
2021-03-26 09:32:10 -07:00
Ömer Sinan Ağacan
819247f179 Update char::escape_debug_ext to handle different escapes in strings vs. chars
Fixes #83046

The program

    fn main() {
        println!("{:?}", '"');
        println!("{:?}", "'");
    }

would previously print

    '\"'
    "\'"

With this patch it now prints:

    '"'
    "'"
2021-03-26 11:23:51 +03:00
bors
6e17a5c5fd Auto merge of #83387 - cuviper:min-llvm-10, r=nagisa
Update the minimum external LLVM to 10

r? `@nikic`
2021-03-25 13:11:18 +00:00
bors
bba40880c0 Auto merge of #82565 - m-ou-se:ununstabilize-bits, r=kennytm
Revert reverting of stabilizing integer::BITS.

Now that `lexical-core` has an updated version that won't break with this stabilization, let's try to stabilize this again.

See https://github.com/rust-lang/rust/issues/81654#issuecomment-778564715

Tracking issue with FCP: https://github.com/rust-lang/rust/issues/76904
2021-03-25 10:29:58 +00:00
Yuki Okushi
ee34453a10
Rollup merge of #83440 - fee1-dead:core-cell-intralink, r=jyn514
Use intra-doc link in core::cell

``@rustbot`` label T-doc A-intra-doc-links

r? ``@jyn514``
2021-03-25 09:07:31 +09:00
Yuki Okushi
921a82007a
Rollup merge of #83421 - faern:add-into-err, r=joshtriplett
Add Result::into_err where the Ok variant is the never type

Equivalent of #66045 but for the inverse situation where `T: Into<!>` rather than `E: Into<!>`.

I'm using the same feature gate name. I can't see why one of these methods would be OK to stabilize but not the other.

Tracking issue: #61695
2021-03-25 09:07:28 +09:00
Yuki Okushi
29e64e913a
Rollup merge of #83349 - m-ou-se:unwrap-none, r=dtolnay
Remove Option::{unwrap_none, expect_none}.

This removes `Option::unwrap_none` and `Option::expect_none` since we're not going to stabilize them, see https://github.com/rust-lang/rust/issues/62633.

Closes #62633
2021-03-25 09:07:26 +09:00
Yuki Okushi
a6ababb162
Rollup merge of #83041 - guswynn:stable_debug_struct, r=m-ou-se
stabilize debug_non_exhaustive

tracking issue: https://github.com/rust-lang/rust/issues/67364

but it is still an open question whether the other `Debug*` struct's should have a similar method. I would guess that would best be put underneath a new feature gate, as this one seems uncontroversial enough to stabilize as is
2021-03-25 09:07:24 +09:00
Mara Bos
b1fac3a5e1
Bump debug_non_exhaustive stabilization to 1.53. 2021-03-24 22:54:04 +01:00
Mara Bos
bacd5226b7 Bump int_bits_const stable version to 1.53. 2021-03-24 22:34:38 +01:00
Mara Bos
81932be5e7 Revert "Revert stabilizing integer::BITS." 2021-03-24 22:34:36 +01:00
Deadbeef
c0fe54fedd
Use intra-doc link in core::cell 2021-03-24 21:42:49 +08:00
Linus Färnstrand
3bf076e76b Add test for Result::into_err 2021-03-23 21:41:50 +01:00
Linus Färnstrand
593f9293b9 Add Result::into_err where the Ok variant can never happen 2021-03-23 21:24:26 +01:00
bors
9b6339e4b9 Auto merge of #82271 - Aaron1011:debug-refcell, r=m-ou-se
Add `debug-refcell` feature to libcore

See https://rust-lang.zulipchat.com/#narrow/stream/131828-t-compiler/topic/Attaching.20backtraces.20to.20RefCell/near/226273614
for some background discussion

This PR adds a new off-by-default feature `debug-refcell` to libcore.
When enabled, this feature stores additional debugging information in
`RefCell`. This information is included in the panic message when
`borrow()` or `borrow_mut()` panics, to make it easier to track down the
source of the issue.

Currently, we store the caller location for the earliest active borrow.
This has a number of advantages:
* There is only a constant amount of overhead per `RefCell`
* We don't need any heap memory, so it can easily be implemented in core
* Since we are storing the *earliest* active borrow, we don't need any
  extra logic in the `Drop` implementation for `Ref` and `RefMut`

Limitations:
* We only store the caller location, not a full `Backtrace`. Until
  we get support for `Backtrace` in libcore, this is the best tha we can
do.
* The captured location is only displayed when `borrow()` or
  `borrow_mut()` panics. If a crate calls `try_borrow().unwrap()`
  or `try_borrow_mut().unwrap()`, this extra information will be lost.

To make testing easier, I've enabled the `debug-refcell` feature by
default. I'm not sure how to write a test for this feature - we would
need to rebuild core from the test framework, and create a separate
sysroot.

Since this feature will be off-by-default, users will need to use
`xargo` or `cargo -Z build-std` to enable this feature. For users using
a prebuilt standard library, this feature will be disabled with zero
overhead.

I've created a simple test program:

```rust
use std::cell::RefCell;

fn main() {
    let _ = std::panic::catch_unwind(|| {
        let val = RefCell::new(true);
        let _first = val.borrow();
        let _second = val.borrow();
        let _third = val.borrow_mut();
    });

    let _ = std::panic::catch_unwind(|| {
        let val  = RefCell::new(true);
        let first = val.borrow_mut();
        drop(first);

        let _second = val.borrow_mut();

        let _thid = val.borrow();
    });
}
```

which produces the following output:

```
thread 'main' panicked at 'already borrowed: BorrowMutError at refcell_test.rs:6:26', refcell_test.rs:8:26
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
thread 'main' panicked at 'already mutably borrowed: BorrowError at refcell_test.rs:16:27', refcell_test.rs:18:25
```
2021-03-23 04:49:47 +00:00
Jubilee Young
74db93ed2d Preserve signed zero on roundtrip
This commit removes the previous mechanism of differentiating
between "Debug" and "Display" formattings for the sign of -0 so as
to comply with the IEEE 754 standard's requirements on external
character sequences preserving various attributes of a floating
point representation.

In addition, numerous tests are fixed.
2021-03-22 17:02:09 -07:00
Jubilee Young
588cc644ad Add ability to read NaN/Infinity 2021-03-22 17:02:08 -07:00
Jubilee Young
fc9b234928 Add IEEE754 tests 2021-03-22 17:02:06 -07:00
Josh Stone
fcb37cb7d6 Fix asm! from AT&T to Intel syntax 2021-03-22 13:12:53 -07:00
bors
5d04957a4b Auto merge of #79278 - mark-i-m:stabilize-or-pattern, r=nikomatsakis
Stabilize or_patterns (RFC 2535, 2530, 2175)

closes #54883

This PR stabilizes the or_patterns feature in Rust 1.53.

This is blocked on the following (in order):
- [x] The crater run in https://github.com/rust-lang/rust/pull/78935#issuecomment-731564021
- [x] The resolution of the unresolved questions and a second crater run (https://github.com/rust-lang/rust/pull/78935#issuecomment-735412705)
    - It looks like we will need to pursue some sort of edition-based transition for `:pat`.
- [x] Nomination and discussion by T-lang
- [x] Implement new behavior for `:pat` based on consensus (https://github.com/rust-lang/rust/pull/80100).
- [ ] An FCP on stabilization

EDIT: Stabilization report is in https://github.com/rust-lang/rust/pull/79278#issuecomment-772815177
2021-03-22 19:48:27 +00:00
Josh Stone
7d872f538e Update the minimum external LLVM to 10 2021-03-22 11:33:43 -07:00
Aaron Hill
a23273e82c
Add debug-refcell feature to libcore
See https://rust-lang.zulipchat.com/#narrow/stream/131828-t-compiler/topic/Attaching.20backtraces.20to.20RefCell/near/226273614
for some background discussion

This PR adds a new off-by-default feature `debug-refcell` to libcore.
When enabled, this feature stores additional debugging information in
`RefCell`. This information is included in the panic message when
`borrow()` or `borrow_mut()` panics, to make it easier to track down the
source of the issue.

Currently, we store the caller location for the earliest active borrow.
This has a number of advantages:
* There is only a constant amount of overhead per `RefCell`
* We don't need any heap memory, so it can easily be implemented in core
* Since we are storing the *earliest* active borrow, we don't need any
  extra logic in the `Drop` implementation for `Ref` and `RefMut`

Limitations:
* We only store the caller location, not a full `Backtrace`. Until
  we get support for `Backtrace` in libcore, this is the best tha we can
do.
* The captured location is only displayed when `borrow()` or
  `borrow_mut()` panics. If a crate calls `try_borrow().unwrap()`
  or `try_borrow_mut().unwrap()`, this extra information will be lost.

To make testing easier, I've enabled the `debug-refcell` feature by
default. I'm not sure how to write a test for this feature - we would
need to rebuild core from the test framework, and create a separate
sysroot.

Since this feature will be off-by-default, users will need to use
`xargo` or `cargo -Z build-std` to enable this feature. For users using
a prebuilt standard library, this feature will be disabled with zero
overhead.

I've created a simple test program:

```rust
use std::cell::RefCell;

fn main() {
    let _ = std::panic::catch_unwind(|| {
        let val = RefCell::new(true);
        let _first = val.borrow();
        let _second = val.borrow();
        let _third = val.borrow_mut();
    });

    let _ = std::panic::catch_unwind(|| {
        let val  = RefCell::new(true);
        let first = val.borrow_mut();
        drop(first);

        let _second = val.borrow_mut();

        let _thid = val.borrow();
    });
}
```

which produces the following output:

```
thread 'main' panicked at 'already borrowed: BorrowMutError { location: Location { file: "refcell_test.rs", line: 6, col: 26 } }', refcell_test.rs:8:26
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
thread 'main' panicked at 'already mutably borrowed: BorrowError { location: Location { file: "refcell_test.rs", line: 16, col: 27 } }', refcell_test.rs:18:25
```
2021-03-22 12:39:54 -04:00
Dylan DPC
ce06787548
Rollup merge of #83372 - eggyal:split-inclusive, r=Mark-Simulacrum
SplitInclusive is public API
2021-03-22 15:21:31 +01:00
Dylan DPC
f441c2a9a0
Rollup merge of #83272 - kornelski:takedocs, r=dtolnay
Clarify non-exact length in the Iterator::take documentation

There's an example which demonstrates incomplete length case, but it'd be best to explain it right from the start.
2021-03-22 15:21:26 +01:00
Dylan DPC
83faac9da4
Rollup merge of #82683 - jturner314:int-div-rem-doc-panic, r=nikomatsakis
Document panicking cases for integer division and remainder

This PR documents the cases when integer division and remainder operations panic. These operations panic in two cases: division by zero and overflow.

It's surprising that these operations always panic on overflow, unlike most other arithmetic operations, which panic on overflow only when `debug_assertions` is enabled. The panic on overflow for the remainder is also surprising because a return value of `0` would be reasonable in this case. ("Overflow" occurs only for `MIN % -1`.) Since the panics on overflow are somewhat surprising, they should be documented.

I guess it's worth asking: is panic on overflow (even when `debug_assertions` is disabled) the intended behavior? If not, what's the best way forward?
2021-03-22 15:21:24 +01:00
Dylan DPC
7bf8f82f72
Rollup merge of #82374 - clehner:licenses, r=joshtriplett
Add license metadata for std dependencies

These five crates are in the dependency tree of `std` but lack license metadata:
- `alloc`
- `core`
- `panic_abort`
- `panic_unwind`
- `unwind`

Querying the dependency tree of `std` is a useful thing to be able to do, since these crates will typically be linked into Rust binaries. Tools show the license fields missing, as seen in https://github.com/rust-lang/rust/issues/67014#issuecomment-782704534. This PR adds the license field for the five crates, based on the license of the `std` package and this repo as a whole. I also added the `repository` and `descriptions` fields, since those seem useful. For `description`, I copied text from top-level comments for the respective modules - except for `unwind` which has none.

I also note that https://github.com/rust-lang/rust/pull/73530 attempted to add license metadata for all crates in this repo, but was rejected because there was question about some of them. I hope that this smaller change, focusing only on the runtime dependencies, will be easier to review.

cc `@Mark-Simulacrum` `@Lokathor`
2021-03-22 15:21:23 +01:00
bors
7f82ddb875 Auto merge of #82680 - jturner314:div_euclid-docs, r=JohnTitor
Fix inequality in docs for div_euclid

This commit fixes the statement of the inequality that the Euclidean remainder satisfies. (The remainder is guaranteed to be less than abs(rhs), not rhs.) It also rewords the documentation to make it a little easier to read.

(You might wonder why I've written `abs(rhs)` instead of `rhs.abs()`. Two reasons: first, the `rem_euclid` docs use `abs(rhs)` instead of `rhs.abs()`, and second, the absolute value here is the mathematical absolute value, not the the `.abs()` operation which may overflow.)
2021-03-22 09:37:50 +00:00
Alan Egerton
fe957350c7
SplitInclusive is public API 2021-03-22 09:07:52 +00:00
Dylan DPC
34285def87
Rollup merge of #82771 - emilio:iter-mut-as-slice, r=m-ou-se
slice: Stabilize IterMut::as_slice.

Much like #72584.

As per #58957 there's no blocker for this, and I wanted to use this
today :-)

Closes #58957
2021-03-22 02:20:30 +01:00
Dylan DPC
29a53e6e69
Rollup merge of #81607 - the8472:trustedrandomaccess-all-the-things, r=m-ou-se
Implement TrustedLen and TrustedRandomAccess for Range<integer>, array::IntoIter, VecDequeue's iterators

This should make some `FromIterator` and `.zip()` specializations applicable in a few more cases.

``@rustbot`` label libs-impl
2021-03-22 02:20:26 +01:00
Dylan DPC
ad8aa185df
Rollup merge of #80771 - thomcc:nonnull-refmut, r=dtolnay
Make NonNull::as_ref (and friends) return refs with unbound lifetimes

# Rationale:

1. The documentation for all of these functions claims that this is what the functions already do, as they all come with this comment:

    > You must enforce Rust's aliasing rules, *since the returned lifetime 'a is arbitrarily chosen* and does not necessarily reflect the actual lifetime of the data...

    So I think it's just a bug that they weren't this way already. Note that had it not been for this part, I wouldn't be making this PR, so if we decide we won't take this change, I'll follow it up with a docs PR to fix this.

2. This is how the equivalent raw pointer functions behave.

    They also take `self` and not `&self`/`&mut self`, but that can't be changed compatibly at this point. This is the next best thing.

3. Without this fix, often code that uses these methods will find it has to expand the lifetime of the result.

    (I can't speak for others but even in unsafe-heavy code, needing to do this unexpectedly is a huge red flag -- if Rust thinks something should have a specific lifetime, I assume it's for a reason)

### Can this cause existing code to be unsound?

I'm confident this can't cause new unsoundness since the reference exists for at most its lifetime, but you get a borrow checker error if you do something that would require/allow the reference to exist past its lifetime.

Additionally, the aliasing rules of a reference only applies while the reference exists.

This *must* be the case, as it is required by the rules used by safe code. (That said, the documentation in this file sort of contradicts it, but I think it's just ambiguity between the lifetime `'a` in `&'a T` and lifetime of the `&'a T` reference itself...)

We are increasing the lifetime of these references, but they should already have hard bounds on that lifetime, or they'd have borrow checker errors.

(CC ``@RalfJung`` because I have gone and done the mistake where I say something definitive about aliasing in Rust which is honestly outside the group of things I should make definitive comments about).

# Caveats

1. This is insta-stable (except for on the unstable functions ofc). I don't think there's any other alternative.

2. I don't believe this is a breaking change in practice. In theory someone could be assigning `NonNull::as_ref` to a function pointer of type `fn(&NonNull<T>) -> &T`. Now they'd need to use a slightly different function pointer type which is (probably) incompatible. This seems pathological, but I guess crater could be used if there are concerns.

3. This has no tests. The old version didn't either that I saw. I could add some stuff that fails to compile without it, if that would be useful.

4. Sometimes the NLL borrow checker gives up and decides lifetimes live till the end of the scope, as opposed to the range where they're used. If this change can cause this to happen more, then my soundness rationale is wrong, and it's likely breaking.

    In practice this seems super unlikely.

Anyway. That was a lot of typing.

Fixes https://github.com/rust-lang/rust/issues/80183
2021-03-22 02:20:24 +01:00
Mara Bos
2bd7c1b5de Bump slice_iter_mut_as_slice stable version. 2021-03-21 23:01:28 +01:00
The8472
08a1dd287d implement TrustedRandomAccess for array::IntoIter 2021-03-21 20:43:48 +01:00
The8472
895d7a9a09 implement TrustedRandomAccess for Ranges over int types 2021-03-21 20:43:48 +01:00
bors
f82664191d Auto merge of #83053 - oli-obk:const_stab_version, r=m-ou-se
Fix const stability `since` versions.

fixes #82085

r? `@m-ou-se`
2021-03-21 16:21:39 +00:00
Camelid
49ccc3f320 Remove redundant second example 2021-03-20 14:09:38 -07:00
bors
eb9ec31168 Auto merge of #82919 - bstrie:stabchar, r=dtolnay
Stabilize `assoc_char_funcs` and `assoc_char_consts`

Stabilizes the following associated items on `char`:

* [`char::MAX`](https://doc.rust-lang.org/std/primitive.char.html#associatedconstant.MAX)
* [`char::REPLACEMENT_CHARACTER`](https://doc.rust-lang.org/std/primitive.char.html#associatedconstant.REPLACEMENT_CHARACTER)
* [`char::UNICODE_VERSION`](https://doc.rust-lang.org/std/primitive.char.html#associatedconstant.UNICODE_VERSION)
* [`char::decode_utf16`](https://doc.rust-lang.org/std/primitive.char.html#method.decode_utf16)
* [`char::from_u32`](https://doc.rust-lang.org/std/primitive.char.html#method.from_u32)
* [`char::from_u32_unchecked`](https://doc.rust-lang.org/std/primitive.char.html#method.from_u32_unchecked)
* [`char::from_digit`](https://doc.rust-lang.org/std/primitive.char.html#method.from_digit)

Closes #71763.
2021-03-20 06:36:42 +00:00
bstrie
567f0e1a39
Stabilize assoc_char_funcs and assoc_char_consts 2021-03-19 20:35:08 -07:00
mark
553ceb0791 core/std/alloc: stabilize or_patterns 2021-03-19 19:45:42 -05:00
Dylan DPC
2cc5d72792
Rollup merge of #83254 - jfrimmel:panic_output-stream, r=m-ou-se,joshtriplett
Include output stream in `panic!()` documentation

Fixes #83252.
2021-03-19 23:01:38 +01:00
Dylan DPC
f7febc8865
Rollup merge of #82570 - WaffleLapkin:split_whitespace_as_str, r=m-ou-se
Add `as_str` method for split whitespace str iterators

This PR adds `as_str` methods to `SplitWhitespace` and `SplitAsciiWhitespace`
str iterators. The methods return the remainder, similar to `as_str` methods on
`Chars` and other split iterators. This PR is a continuation of https://github.com/rust-lang/rust/pull/75265, which added `as_str` for all other str split iterators.

The feature gate for new methods is `#![feature(str_split_whitespace_as_str)]`.

`SplitWhitespace` and `SplitAsciiWhitespace` use iterators under the hood, so to implement `as_str` it's required to either
1. Make fields of some iterators `pub(crate)`
2. Add getter methods (like `into_inner`, `inner`, `inner_mut`...) to some (all) iterators
3. Completely rewrite `SplitWhitespace` and `SplitAsciiWhitespace`

This PR uses the 1. approach since it's easier to implement and requires fewer changes (and no changes to the public API). If you think that's not the right way, please, tell me.

r? `@m-ou-se`
2021-03-19 23:01:35 +01:00
Dylan DPC
99f411d438
Rollup merge of #83270 - steffahn:missing_word_in_skip_while_doc, r=joshtriplett
Fix typo/inaccuracy in the documentation of Iterator::skip_while

One of the examples used to say “this leads to a possibly confusing situation, where the type of the closure is a double reference” while _actually_ referring to the type of the closure _argument_.

This PR just changes a single word in documentation.

`````@rustbot````` modify labels: A-iterators, T-doc, T-lang
2021-03-19 15:03:29 +01:00
J. Frimmel
19bd0669b4
Apply suggestions from code review
Co-authored-by: Josh Triplett <josh@joshtriplett.org>
2021-03-18 21:15:19 +01:00
Kornel
6cfdc385a1 Expand documentation of Iterator::take and skip 2021-03-18 20:07:29 +00:00
Frank Steffahn
99b2054fe5 Fix typo/inaccuracy in the documentation of Iterator::skip_while
One of the examples used to say “this leads to a possibly confusing situation,
where the type of the closure is a double reference” while _actually_ referring to
the type of the closure _argument_.
2021-03-18 18:58:22 +01:00
Julian Frimmel
d5e45b50cd Incorporate review feedback #2 2021-03-18 15:15:28 +01:00
Julian Frimmel
61e5d549b4 Add more information about panicking
This includes the description of the default `std` behavior and mentions
the `panic::set_hook()` function.
2021-03-18 14:24:13 +01:00
Julian Frimmel
55d9e0f601 Include output stream in panic!() documentation 2021-03-18 09:52:21 +01:00
bors
2aafe452b8 Auto merge of #82868 - petrochenkov:bto, r=estebank
Report missing cases of `bare_trait_objects`

Fixes https://github.com/rust-lang/rust/issues/65371
2021-03-18 05:27:26 +00:00
Dylan DPC
c99200fa53
Rollup merge of #82434 - jyn514:hash, r=JohnTitor
Add more links between hash and btree collections

- Link from `core::hash` to `HashMap` and `HashSet`
- Link from HashMap and HashSet to the module-level documentation on
  when to use the collection
- Link from several collections to Wikipedia articles on the general
  concept

See also https://github.com/rust-lang/rust/pull/81989#issuecomment-783920840.
2021-03-18 00:28:07 +01:00
The8472
d7fdd90655 add bench 2021-03-18 00:25:20 +01:00
The8472
dd166da8f8 generalize slice::fill specialization for byte-sized items
This should also improve cross-crate inlining since the method is generic
2021-03-18 00:25:20 +01:00
Vadim Petrochenkov
dac96d45af Fix use of bare trait objects everywhere 2021-03-18 02:18:58 +03:00
bors
36f1f04f18 Auto merge of #82122 - bstrie:dep4real, r=dtolnay
Deprecate `intrinsics::drop_in_place` and `collections::Bound`, which accidentally weren't deprecated

Fixes #82080.

I've taken the liberty of updating the `since` values to 1.52, since an unobservable deprecation isn't much of a deprecation (even the detailed release notes never bothered to mention these deprecations).

As mentioned in the issue I'm *pretty* sure that using a type alias for `Bound` is semantically equivalent to the re-export; [the reference implies](https://doc.rust-lang.org/reference/items/type-aliases.html) that type aliases only observably differ from types when used on unit structs or tuple structs, whereas `Bound` is an enum.
2021-03-17 19:39:03 +00:00
Joshua Nelson
a7491d932f
fix whitespace
Co-authored-by: Yuki Okushi <huyuumi.dev@gmail.com>
2021-03-17 09:27:34 -04:00
bors
0ce0fedb67 Auto merge of #81358 - mcastorina:to-upper-lower-speed, r=joshtriplett
Add a check for ASCII characters in to_upper and to_lower

This extra check has better performance. See discussion here:
https://internals.rust-lang.org/t/to-upper-speed/13896

Thanks to `@gilescope` for helping discover and test this.
2021-03-17 11:17:18 +00:00
Yuki Okushi
39af66f651
Rollup merge of #83160 - m-ou-se:deprecate-rustc-serialize-derives, r=petrochenkov
Deprecate RustcEncodable and RustcDecodable.

We can't remove the `RustcEncodable` and `RustcDecodable` derive macros from the prelude, but we can deprecate them.
2021-03-16 23:54:00 +09:00
Camelid
34c6cee397 Rename #[doc(spotlight)] to #[doc(notable_trait)]
"spotlight" is not a very specific or self-explaining name.
Additionally, the dialog that it triggers is called "Notable traits".
So, "notable trait" is a better name.

* Rename `#[doc(spotlight)]` to `#[doc(notable_trait)]`
* Rename `#![feature(doc_spotlight)]` to `#![feature(doc_notable_trait)]`
* Update documentation
* Improve documentation
2021-03-15 13:59:54 -07:00
Albin Hedman
db9a53b5d7
Constify mem::transmute_copy 2021-03-15 20:45:57 +01:00
Albin Hedman
45988ee438
Constify mem::replace and ptr::replace 2021-03-15 20:45:43 +01:00
Albin Hedman
64e2248794
Constify mem::swap and ptr::swap[_nonoverlapping] 2021-03-15 20:45:22 +01:00
Albin Hedman
62cf244563
Constify copy_to and copy_from 2021-03-15 20:45:20 +01:00
Mara Bos
924e522d16 Deprecate RustcEncodable and RustcDecodable. 2021-03-15 20:16:16 +01:00
Oli Scherer
6f3635d87b Fix const stability since versions. 2021-03-15 14:39:18 +00:00
Mara Bos
8dc0ae24bc Remove Option::{unwrap_none, expect_none}. 2021-03-14 12:54:34 +01:00
Motoki Ikeda
71a784d763 Fix a typo in swap_nonoverlapping_bytes 2021-03-14 16:32:15 +09:00
Yuki Okushi
f8206ac63d
Rollup merge of #83081 - hyd-dev:assert-message, r=m-ou-se
Fix panic message of `assert_failed_inner`

cc https://github.com/rust-lang/rust/pull/79100#discussion_r593731020

r? ``@m-ou-se``
2021-03-14 13:07:37 +09:00
Yuki Okushi
54546a893d
Rollup merge of #83066 - Seppel3210:master, r=joshtriplett
Add `reverse` search alias for Iterator::rev()

When searching for "reverse" in rustdoc you can't find the rev method on Iterator so here is a search alias for that.
2021-03-14 13:07:35 +09:00
Yuki Okushi
6caa350503
Rollup merge of #81465 - joshtriplett:duration-formatting-documentation, r=m-ou-se
Add documentation about formatting `Duration` values

Explain why Duration has a Debug impl but not a Display impl, and
mention the use of Unicode.
2021-03-14 13:07:27 +09:00
Josh Triplett
8fd2f0c81f Add documentation about formatting Duration values
Explain why Duration has a Debug impl but not a Display impl, and
mention the use of Unicode.
2021-03-13 13:06:30 -08:00
bors
acca818928 Auto merge of #83064 - cjgillot:fhash, r=jackh726
Tweaks to stable hashing
2021-03-13 20:21:40 +00:00
hyd-dev
bc8093ed55
Fix panic message of assert_failed_inner 2021-03-13 18:50:43 +08:00
Sebastian Widua
f201746625 Add reverse search alias for Iterator::rev() 2021-03-13 10:07:01 +01:00
bors
46a934a1dc Auto merge of #83022 - m-ou-se:mem-replace-no-swap, r=nagisa
Don't implement mem::replace with mem::swap.

`swap` is a complicated operation, so this changes the implementation of `replace` to use `read` and `write` instead.

See https://github.com/rust-lang/rust/pull/83019.

I wrote there:

> Implementing the simpler operation (replace) with the much more complicated operation (swap) doesn't make a whole lot of sense. `replace` is just read+write, and the primitive for moving out of a `&mut`. `swap` is for doing that to *two* `&mut` at the same time, which is both more niche and more complicated (as shown by `swap_nonoverlapping_bytes`).

This could be especially interesting for `Option<VeryLargeStruct>::take()`, since swapping such a large structure with `swap_nonoverlapping_bytes` is going to be much less efficient than `ptr::write()`'ing a `None`.

But also for small values where `swap` just reads/writes using temporary variable, this makes a `replace` or `take` operation simpler:
![image](https://user-images.githubusercontent.com/783247/110839393-c7e6bd80-82a3-11eb-97b7-28acb14deffd.png)
2021-03-12 23:27:23 +00:00
Gus Wynn
b8e498162e
Update library/core/src/fmt/builders.rs
Co-authored-by: Yuki Okushi <huyuumi.dev@gmail.com>
2021-03-12 08:52:26 -08:00
Yuki Okushi
16ce4f7513
Rollup merge of #82950 - mockersf:slice-intra-doc-link, r=jyn514
convert slice doc link to intra-doc links

Continuing where #80189 stopped, with `core::slice`.

I had an issue with two dead links in my doc when implementing `Deref<Target = [T]>` for one of my type. This means that [`binary_search_by_key`](https://doc.rust-lang.org/nightly/std/primitive.slice.html#method.binary_search_by_key) was available, but not [`sort_by_key`](https://doc.rust-lang.org/nightly/std/primitive.slice.html#method.sort_by_key) even though it was linked in it's doc (same issue with [`as_ptr`](https://doc.rust-lang.org/nightly/std/primitive.slice.html#method.as_ptr) and [`as_mut_pbr`](https://doc.rust-lang.org/nightly/std/primitive.slice.html#method.as_mut_ptr)). It becomes available if I implement `DerefMut`, as it needs an `&mut self`.

<details>
  <summary>Code that will have dead links in its doc</summary>

```rust
pub struct A;
pub struct B;

impl std::ops::Deref for B{
    type Target = [A];

    fn deref(&self) -> &Self::Target {
        &A
    }
}
```
</details>

I removed the link to `sort_by_key` from `binary_search_by_key` doc as I didn't find a nice way to have a live link:
- `binary_search_by_key` is in `core`
- `sort_by_key` is in `alloc`
- intra-doc link `slice::sort_by_key` doesn't work, as `alloc` is not available when `core` is being build (the warning can't be ignored: ```error[E0710]: an unknown tool name found in scoped lint: `rustdoc::broken_intra_doc_links` ```)
- keeping the link as an anchor `#method.sort_by_key` meant a dead link
- an absolute link would work but doesn't feel right...
2021-03-12 08:55:15 +09:00
Yuki Okushi
2f0bbc0d1d
Rollup merge of #80385 - camelid:clarify-cell-replace-docs, r=Mark-Simulacrum
Clarify what `Cell::replace` returns
2021-03-12 08:55:09 +09:00
Gus Wynn
73ddfa0eea stabilize debug_non_exhaustive 2021-03-11 15:17:44 -08:00
Mara Bos
bf27819f37 Don't implement mem::replace with mem::swap. 2021-03-11 19:04:47 +01:00
Camille GILLOT
84bf599bac Add inlining. 2021-03-11 12:24:43 +01:00
François Mockers
232b9f1641 apply review 2021-03-10 18:32:55 +01:00
François Mockers
0d07153507 add back sort_by_key link, allow linter and add comment 2021-03-10 18:18:28 +01:00
Dylan DPC
e58313248a
Rollup merge of #82977 - camsteffen:opt-get-insert-def, r=m-ou-se
Rename `Option::get_or_default` to `get_or_insert_default`

...as [suggested](https://github.com/rust-lang/rust/issues/82901#issuecomment-793548515) by `@m-ou-se.` In hindsight this seems rather obvious, at least to me.

r? `@joshtriplett`
2021-03-10 17:55:47 +01:00
Dylan DPC
759204ffc4
Rollup merge of #82217 - m-ou-se:edition-prelude, r=nikomatsakis
Edition-specific preludes

This changes `{std,core}::prelude` to export edition-specific preludes under `rust_2015`, `rust_2018` and `rust_2021`. (As suggested in https://github.com/rust-lang/rust/issues/51418#issuecomment-395630382.) For now they all just re-export `v1::*`, but this allows us to add things to the 2021edition prelude soon.

This also changes the compiler to make the automatically injected prelude import dependent on the selected edition.

cc `@rust-lang/libs` `@djc`
2021-03-10 17:55:38 +01:00
Cameron Steffen
b0514a6a0a Rename Option::get_or_insert_default 2021-03-10 09:07:16 -06:00
bstrie
49aa79ec11 Deprecate items that accidentally weren't deprecated
Fixes #82080
2021-03-09 19:09:20 -05:00
Yuki Okushi
1c3fea2f8c
Rollup merge of #82849 - camsteffen:option-get-or-default, r=joshtriplett
Add Option::get_or_default

Tracking issue: #82901

The original issue is #55042, which was closed, but for an invalid reason (see discussion there). Opening this to reconsider (I hope that's okay). It seems like the only gap for `Option` being "entry-like".

I ran into a need for this method where I had a `Vec<Option<MyData>>` and wanted to do `vec[n].get_or_default().my_data_method()`. Using an `Option` as an inner component of a data structure is probably where the need for this will normally arise.
2021-03-10 08:01:32 +09:00
Yuki Okushi
c46f948a80
Rollup merge of #79208 - LeSeulArtichaut:stable-unsafe_op_in_unsafe_fn, r=nikomatsakis
Stabilize `unsafe_op_in_unsafe_fn` lint

This makes it possible to override the level of the `unsafe_op_in_unsafe_fn`, as proposed in https://github.com/rust-lang/rust/issues/71668#issuecomment-729770896.

Tracking issue: #71668
r? ```@nikomatsakis``` cc ```@SimonSapin``` ```@RalfJung```

# Stabilization report

This is a stabilization report for `#![feature(unsafe_block_in_unsafe_fn)]`.

## Summary

Currently, the body of unsafe functions is an unsafe block, i.e. you can perform unsafe operations inside.

The `unsafe_op_in_unsafe_fn` lint, stabilized here, can be used to change this behavior, so performing unsafe operations in unsafe functions requires an unsafe block.

For now, the lint is allow-by-default, which means that this PR does not change anything without overriding the lint level.

For more information, see [RFC 2585](https://github.com/rust-lang/rfcs/blob/master/text/2585-unsafe-block-in-unsafe-fn.md)

### Example

```rust
// An `unsafe fn` for demonstration purposes.
// Calling this is an unsafe operation.
unsafe fn unsf() {}

// #[allow(unsafe_op_in_unsafe_fn)] by default,
// the behavior of `unsafe fn` is unchanged
unsafe fn allowed() {
    // Here, no `unsafe` block is needed to
    // perform unsafe operations...
    unsf();

    // ...and any `unsafe` block is considered
    // unused and is warned on by the compiler.
    unsafe {
        unsf();
    }
}

#[warn(unsafe_op_in_unsafe_fn)]
unsafe fn warned() {
    // Removing this `unsafe` block will
    // cause the compiler to emit a warning.
    // (Also, no "unused unsafe" warning will be emitted here.)
    unsafe {
        unsf();
    }
}

#[deny(unsafe_op_in_unsafe_fn)]
unsafe fn denied() {
    // Removing this `unsafe` block will
    // cause a compilation error.
    // (Also, no "unused unsafe" warning will be emitted here.)
    unsafe {
        unsf();
    }
}
```
2021-03-10 08:01:25 +09:00
François Mockers
14e23f117e convert slice doc link to intra-doc links 2021-03-09 21:26:07 +01:00
Mara Bos
0083e6c989
Rollup merge of #81879 - imbrem:make-reverse-repr-transparent, r=m-ou-se
Added #[repr(transparent)] to core::cmp::Reverse

I found casting from an `&T` to an `&Reverse<T>` potentially useful, but found that `Reverse` was not `#[repr(transparent)]`, so after asking about it [on Reddit](https://www.reddit.com/r/rust/comments/le60uv/make_stdcmpreverse_reprtransparent_and_add_a/), I decided to go ahead and make a pull request which simply adds the attribute to the struct.
2021-03-09 09:05:19 +00:00
Mara Bos
2d3ba78561
Rollup merge of #82888 - Daggy1234:patch-1, r=joshtriplett
Grammar Fixes

Found typo's in the array rustdoc. Pr'ed a fix!
2021-03-08 20:09:07 +01:00
Cameron Steffen
7e3ebe76ee Add Option::get_or_default 2021-03-08 09:24:10 -06:00
Arnav Jindal
655155caa0
Update library/core/src/array/mod.rs
Co-authored-by: Yuki Okushi <huyuumi.dev@gmail.com>
2021-03-08 20:28:30 +05:30
Dylan DPC
9c310571a8
Rollup merge of #82682 - petrochenkov:cfgeval, r=Aaron1011
Implement built-in attribute macro `#[cfg_eval]` + some refactoring

This PR implements a built-in attribute macro `#[cfg_eval]` as it was suggested in https://github.com/rust-lang/rust/pull/79078 to avoid `#[derive()]` without arguments being abused as a way to configure input for other attributes.

The macro is used for eagerly expanding all `#[cfg]` and `#[cfg_attr]` attributes in its input ("fully configuring" the input).
The effect is identical to effect of `#[derive(Foo, Bar)]` which also fully configures its input before passing it to macros `Foo` and `Bar`, but unlike `#[derive]` `#[cfg_eval]` can be applied to any syntax nodes supporting macro attributes, not only certain items.

`cfg_eval` was the first name suggested in https://github.com/rust-lang/rust/pull/79078, but other alternatives are also possible, e.g. `cfg_expand`.

```rust
#[cfg_eval]
#[my_attr] // Receives `struct S {}` as input, the field is configured away by `#[cfg_eval]`
struct S {
    #[cfg(FALSE)]
    field: u8,
}
```

Tracking issue: https://github.com/rust-lang/rust/issues/82679
2021-03-08 13:13:23 +01:00
Arnav Jindal
2aa28ad4f0
Grammar Fixes 2021-03-08 11:49:26 +05:30
Yuki Okushi
6220e00ea9
Rollup merge of #82837 - RalfJung:maybe-uninit, r=dtolnay
tweak MaybeUninit docs

Explain what "(no) fixed value" means.
2021-03-07 10:41:22 +09:00
Yuki Okushi
05a2366e82
Rollup merge of #82751 - RalfJung:offset_from, r=dtolnay
improve offset_from docs

`@thomcc` pointed out that the current docs leave it kind of unclear how one can satisfy the "no wrapping around `isize` or the address space" requirement of `offset_from`, so make the docs clearer about that.

FWIW, I don't think I entirely agree with that second paragraph about large objects (that I left mostly unchanged here). LLVM, to my knowledge, fundamentally assumes that all allocations fit into an `isize::MAX`. So in that sense creating a larger allocation is simply UB. I would expect a guarantee that Rust heap allocation methods will never return allocations larger than `isize::MAX` (or rather, Rust heap allocation methods should require that the `Layout` is no larger than `isize::MAX`). However, I cannot find any such requirement documented currently. Large allocations are not mentioned at all in the allocator docs, which is quite surprising -- even if we say that such allocations are not insta-UB (which I think is incompatible with LLVM), they are still extremely footgunny since `ptr::offset`/`ptr::add` do not support offsetting by more than `isize::MAX` bytes.

Furthermore, the allocator docs don't even say anything about allocations wrapping around the address space. But that is certainly something allocators must ensure never happens; we cannot expect clients to defend against this.

Cc `@rust-lang/wg-allocators`
2021-03-07 10:41:16 +09:00
Yuki Okushi
817e58f38d
Rollup merge of #82592 - Lonami:patch-1, r=RalfJung
Improve transmute docs with further clarifications

Closes #82493.

Please let me know if any of the new wording sounds off, English is not my mother tongue.
2021-03-07 10:41:12 +09:00
Yuki Okushi
1d5b2dc945
Rollup merge of #82292 - SkiFire13:fix-issue-82291, r=m-ou-se
Prevent specialized ZipImpl from calling `__iterator_get_unchecked` twice with the same index

Fixes #82291

It's open for review, but conflicts with #82289, wait before merging. The conflict involves only the new test, so it should be rather trivial to fix.
2021-03-07 10:41:10 +09:00
Yuki Okushi
0adc196521
Rollup merge of #82130 - jhpratt:const-option-result, r=RalfJung
Make some Option, Result methods unstably const

The following methods are now unstably const:

- Option::transpose
- Option::flatten
- Result::flatten

While some methods for could likely be made `const` in the future, nearly all of them require something to be dropped at compile-time, which isn't currently supported. The functions listed above should have a trivial path to stabilization.
2021-03-07 10:41:09 +09:00
Vadim Petrochenkov
5dad6c2575 Implement built-in attribute macro #[cfg_eval] 2021-03-06 23:03:19 +03:00
Jacob Pratt
79c2b75e88
Make some Option, Result methods unstably const
The following functions are now unstably const:

- Option::transpose
- Option::flatten
- Result::transpose
2021-03-06 14:17:49 -05:00
Ralf Jung
b75154897b tweak MaybeUninit docs 2021-03-06 16:59:39 +01:00
Lonami
fbc17410b2 Improve transmute docs with further clarifications
Closes #82493.
2021-03-06 16:01:01 +01:00
Giacomo Stevanato
f43c02236d Instruct LLVM that binary_search_by returns a valid index 2021-03-06 11:29:53 +01:00
bors
caca2121ff Auto merge of #74024 - Folyd:master, r=m-ou-se
Improve slice.binary_search_by()'s best-case performance to O(1)

This PR aimed to improve the [slice.binary_search_by()](https://doc.rust-lang.org/std/primitive.slice.html#method.binary_search_by)'s best-case performance to O(1).

# Noticed

I don't know why the docs of `binary_search_by` said `"If there are multiple matches, then any one of the matches could be returned."`, but the implementation isn't the same thing. Actually, it returns the **last one** if multiple matches found.

Then we got two options:

## If returns the last one is the correct or desired result

Then I can rectify the docs and revert my changes.

## If the docs are correct or desired result

Then my changes can be merged after fully reviewed.

However, if my PR gets merged, another issue raised: this could be a **breaking change** since if multiple matches found, the returning order no longer the last one instead of it could be any one.

For example:
```rust
let mut s = vec![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
let num = 1;
let idx = s.binary_search(&num);
s.insert(idx, 2);

// Old implementations
assert_eq!(s, [0, 1, 1, 1, 1, 2, 2, 3, 5, 8, 13, 21, 34, 42, 55]);

// New implementations
assert_eq!(s, [0, 1, 1, 1, 2, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]);
```

# Benchmarking

**Old implementations**
```sh
$ ./x.py bench --stage 1 library/libcore
test slice::binary_search_l1           ... bench:          59 ns/iter (+/- 4)
test slice::binary_search_l1_with_dups ... bench:          59 ns/iter (+/- 3)
test slice::binary_search_l2           ... bench:          76 ns/iter (+/- 5)
test slice::binary_search_l2_with_dups ... bench:          77 ns/iter (+/- 17)
test slice::binary_search_l3           ... bench:         183 ns/iter (+/- 23)
test slice::binary_search_l3_with_dups ... bench:         185 ns/iter (+/- 19)
```

**New implementations (1)**

Implemented by this PR.
```rust
if cmp == Equal {
    return Ok(mid);
} else if cmp == Less {
    base = mid
}
```
```sh
$ ./x.py bench --stage 1 library/libcore
test slice::binary_search_l1           ... bench:          58 ns/iter (+/- 2)
test slice::binary_search_l1_with_dups ... bench:          37 ns/iter (+/- 4)
test slice::binary_search_l2           ... bench:          76 ns/iter (+/- 3)
test slice::binary_search_l2_with_dups ... bench:          57 ns/iter (+/- 6)
test slice::binary_search_l3           ... bench:         200 ns/iter (+/- 30)
test slice::binary_search_l3_with_dups ... bench:         157 ns/iter (+/- 6)

$ ./x.py bench --stage 1 library/libcore
test slice::binary_search_l1           ... bench:          59 ns/iter (+/- 8)
test slice::binary_search_l1_with_dups ... bench:          37 ns/iter (+/- 2)
test slice::binary_search_l2           ... bench:          77 ns/iter (+/- 2)
test slice::binary_search_l2_with_dups ... bench:          57 ns/iter (+/- 2)
test slice::binary_search_l3           ... bench:         198 ns/iter (+/- 21)
test slice::binary_search_l3_with_dups ... bench:         158 ns/iter (+/- 11)

```

**New implementations (2)**

Suggested by `@nbdd0121` in [comment](https://github.com/rust-lang/rust/pull/74024#issuecomment-665430239).
```rust
base = if cmp == Greater { base } else { mid };
if cmp == Equal { break }
```

```sh
$ ./x.py bench --stage 1 library/libcore
test slice::binary_search_l1           ... bench:          59 ns/iter (+/- 7)
test slice::binary_search_l1_with_dups ... bench:          37 ns/iter (+/- 5)
test slice::binary_search_l2           ... bench:          75 ns/iter (+/- 3)
test slice::binary_search_l2_with_dups ... bench:          56 ns/iter (+/- 3)
test slice::binary_search_l3           ... bench:         195 ns/iter (+/- 15)
test slice::binary_search_l3_with_dups ... bench:         151 ns/iter (+/- 7)

$ ./x.py bench --stage 1 library/libcore
test slice::binary_search_l1           ... bench:          57 ns/iter (+/- 2)
test slice::binary_search_l1_with_dups ... bench:          38 ns/iter (+/- 2)
test slice::binary_search_l2           ... bench:          77 ns/iter (+/- 11)
test slice::binary_search_l2_with_dups ... bench:          57 ns/iter (+/- 4)
test slice::binary_search_l3           ... bench:         194 ns/iter (+/- 15)
test slice::binary_search_l3_with_dups ... bench:         151 ns/iter (+/- 18)

```

I run some benchmarking testings against on two implementations. The new implementation has a lot of improvement in duplicates cases, while in `binary_search_l3` case, it's a little bit slower than the old one.
2021-03-05 20:12:13 +00:00
Giacomo Stevanato
c1bfb9a78d Add relevant test 2021-03-05 19:09:23 +01:00
Giacomo Stevanato
2371914a05 Prevent Zip specialization from calling __iterator_get_unchecked twice with the same index after calling next_back 2021-03-05 19:03:32 +01:00
Mara
2cd1f79aa1
Rollup merge of #82773 - mgacek8:feature/add_diagnostic_item_to_Default_trait, r=oli-obk
Add diagnostic item to `Default` trait

This PR adds diagnostic item to `Default` trait to be used by rust-lang/rust-clippy#6562 issue.
Also fixes the obsolete path to the `symbols.rs` file in the comment.
2021-03-05 10:57:24 +01:00
Mara
04045cc83f
Rollup merge of #82770 - m-ou-se:assert-match, r=joshtriplett
Add assert_matches macro.

This adds `assert_matches!(expression, pattern)`.

Unlike the other asserts, this one ~~consumes the expression~~ may consume the expression, to be able to match the pattern. (It could add a `&` implicitly, but that's noticable in the pattern, and will make a consuming guard impossible.)

See https://github.com/rust-lang/rust/issues/62633#issuecomment-790737853

This re-uses the same `left: .. right: ..` output as the `assert_eq` and `assert_ne` macros, but with the pattern as the right part:

assert_eq:
```
assertion failed: `(left == right)`
  left: `Some("asdf")`,
 right: `None`
```
assert_matches:
```
assertion failed: `(left matches right)`
  left: `Ok("asdf")`,
 right: `Err(_)`
```

cc ```@cuviper```
2021-03-05 10:57:23 +01:00
Mara
ee796c6523
Rollup merge of #82289 - SkiFire13:fix-issue-82282, r=m-ou-se
Fix underflow in specialized ZipImpl::size_hint

Fixes #82282
2021-03-05 10:57:19 +01:00
Mara
20887b7ebf
Rollup merge of #81939 - kper:fixing-81584-allocate-in-iter, r=davidtwco
Add suggestion `.collect()` for iterators in iterators

Closes #81584

```
error[E0515]: cannot return value referencing function parameter `y`
 --> main3.rs:4:38
  |
4 | ...                   .map(|y| y.iter().map(|x| x + 1))
  |                                -^^^^^^^^^^^^^^^^^^^^^^
  |                                |
  |                                returns a value referencing data owned by the current function
  |                                `y` is borrowed here
  |                                help: Maybe use `.collect()` to allocate the iterator
```

Added the suggestion: `help: Maybe use `.collect()` to allocate the iterator`
2021-03-05 10:57:18 +01:00
Mara
e6a6df5daa
Rollup merge of #80723 - rylev:noop-lint-pass, r=estebank
Implement NOOP_METHOD_CALL lint

Implements the beginnings of https://github.com/rust-lang/lang-team/issues/67 - a lint for detecting noop method calls (e.g, calling `<&T as Clone>::clone()` when `T: !Clone`).

This PR does not fully realize the vision and has a few limitations that need to be addressed either before merging or in subsequent PRs:
* [ ] No UFCS support
* [ ] The warning message is pretty plain
* [ ] Doesn't work for `ToOwned`

The implementation uses [`Instance::resolve`](https://doc.rust-lang.org/nightly/nightly-rustc/rustc_middle/ty/instance/struct.Instance.html#method.resolve) which is normally later in the compiler. It seems that there are some invariants that this function relies on that we try our best to respect. For instance, it expects substitutions to have happened, which haven't yet performed, but we check first for `needs_subst` to ensure we're dealing with a monomorphic type.

Thank you to ```@davidtwco,``` ```@Aaron1011,``` and ```@wesleywiser``` for helping me at various points through out this PR ❤️.
2021-03-05 10:57:14 +01:00
Mara Bos
80fcdef3b5 Add tracking issue for assert_matches. 2021-03-04 21:33:31 +01:00
Emilio Cobos Álvarez
5176f677f5 slice: Stabilize IterMut::as_slice.
Much like #72584.

As per #58957 there's no blocker for this, and I wanted to use this
today :-)
2021-03-04 19:36:54 +01:00
Mara Bos
f223affd7a Don't consume the expression in assert_matches!()'s failure case. 2021-03-04 19:36:36 +01:00
Mateusz Gacek
a5951d4b23 Add diagnostic item to Default trait
Required to resolve #6562 rust-clippy issue.
2021-03-04 10:14:48 -08:00
Mara Bos
5bd1204fc2 Fix assert_matches doc examples. 2021-03-04 18:41:43 +01:00
Mara Bos
0a8e401188 Add debug_assert_matches macro. 2021-03-04 18:12:33 +01:00
Mara Bos
cfce60ea37 Allow for multiple patterns and a guard in assert_matches. 2021-03-04 18:12:26 +01:00
Mara Bos
eb18746bc6 Add assert_matches!(expr, pat). 2021-03-04 18:07:20 +01:00
Yuki Okushi
f898aa3f5b
Rollup merge of #80527 - jyn514:rustdoc-lints, r=GuillaumeGomez
Make rustdoc lints a tool lint instead of built-in

- Rename `broken_intra_doc_links` to `rustdoc::broken_intra_doc_links` (and similar for other rustdoc lints; I don't expect any others to be used frequently, though).
- Ensure that the old lint names still work and give deprecation errors
- Register lints even when running doctests
- Move lint machinery into a separate file
- Add `declare_rustdoc_lint!` macro

Unblocks https://github.com/rust-lang/rust/pull/80300, https://github.com/rust-lang/rust/pull/79816, https://github.com/rust-lang/rust/pull/80965. Makes the strangeness in https://github.com/rust-lang/rust/pull/77364 more apparent to the end user (note that `missing_docs` is *not* moved to rustdoc in this PR). Closes https://github.com/rust-lang/rust/issues/78786.

## Current status

This is blocked on #82620 (see https://github.com/rust-lang/rust/pull/80527#issuecomment-787401519)
2021-03-04 20:01:01 +09:00
Ralf Jung
ebe0407dbf improve offset_from docs 2021-03-04 10:05:51 +01:00
Giacomo Stevanato
aeb4ea739e Remove useless comparison since now self.index <= self.len is an invariant 2021-03-03 21:19:31 +01:00
Giacomo Stevanato
8b9ac4d415 Add test for underflow in specialized Zip's size_hint 2021-03-03 21:16:08 +01:00
Giacomo Stevanato
66a260617a Increment self.len in specialized ZipImpl to avoid underflow in size_hint 2021-03-03 21:16:07 +01:00
bors
939b14334d Auto merge of #82704 - RalfJung:miri-atomic-minmax, r=oli-obk
enable atomic_min/max tests in Miri

Thanks to `@henryboisdequin` and `@GregBowyer,` Miri now supports these intrinsics. :)
Also includes the necessary Miri update.
2021-03-03 11:05:01 +00:00
Ryan Levick
1999a3147f Fix borrow and deref 2021-03-03 11:23:29 +01:00
Ryan Levick
da3995f0ec Remove lint pass on borrow and deref 2021-03-03 11:23:14 +01:00
Ryan Levick
d3b49c2ed2 Only allow new lint when not bootstrapping - since beta doesn't know about the lint 2021-03-03 11:22:50 +01:00
Ryan Levick
ee65416f0d Fix core tests 2021-03-03 11:22:49 +01:00
Ryan Levick
a6d926d80d Fix tests 2021-03-03 11:22:44 +01:00
Ryan Levick
f49ed7a6b7 Add tests and support two more noop methods 2021-03-03 11:22:17 +01:00
Ryan Levick
040735c110 First version of noop-lint 2021-03-03 11:22:16 +01:00
Peter Kehl
d4763dac9e FloatToInit: Replacing round_unchecked_to --> to_int_unchecked
FloatToInit docs: Replacing round_unchecked_to with
to_int_unchecked. Bug #82709.
2021-03-02 12:38:22 -08:00
Ralf Jung
dc685f6815 enable atomic_min/max tests in Miri 2021-03-02 19:58:55 +01:00
bors
795a934b51 Auto merge of #82043 - tmiasko:may-have-side-effect, r=kennytm
Turn may_have_side_effect into an associated constant

The `may_have_side_effect` is an implementation detail of `TrustedRandomAccess`
trait. It describes if obtaining an iterator element may have side effects. It
is currently implemented as an associated function.

Turn `may_have_side_effect` into an associated constant. This makes the
value immediately available to the optimizer.
2021-03-02 16:08:32 +00:00
Yuki Okushi
bc5669eef8
Rollup merge of #80189 - jyn514:convert-primitives, r=poliorcetics
Convert primitives in the standard library to intra-doc links

Blocked on https://github.com/rust-lang/rust/pull/80181. I forgot that this needs to wait for the beta bump so the standard library can be documented with `doc --stage 0`.

Notably I didn't convert `core::slice` because it's like 50 links and I got scared 😨
2021-03-02 21:23:12 +09:00
Joshua Nelson
cc62018e61 Rename rustdoc lints to be a tool lint instead of built-in.
- Rename `broken_intra_doc_links` to `rustdoc::broken_intra_doc_links`
- Ensure that the old lint names still work and give deprecation errors
- Register lints even when running doctests

  Otherwise, all `rustdoc::` lints would be ignored.

- Register all existing lints as removed

  This unfortunately doesn't work with `register_renamed` because tool
  lints have not yet been registered when rustc is running. For similar
  reasons, `check_backwards_compat` doesn't work either. Call
  `register_removed` directly instead.

- Fix fallout

  + Rustdoc lints for compiler/
  + Rustdoc lints for library/

Note that this does *not* suggest `rustdoc::broken_intra_doc_links` for
`rustdoc::intra_doc_link_resolution_failure`, since there was no time
when the latter was valid.
2021-03-01 19:29:15 -05:00
Guillaume Gomez
9a0ac7cb5f
Rollup merge of #82676 - dtolnay:powers, r=Mark-Simulacrum
Change twice used large const table to static

This table is used twice in core::num::dec2flt::algorithm::power_of_ten. According to the semantics of const, a separate huge definition of the table is inlined at both places.

5233edcf1c/library/core/src/num/dec2flt/algorithm.rs (L16-L22)

Theoretically this gets cleaned up by optimization passes, but in practice I am experiencing a miscompile from LTO on this code. Making the table a static, which would only be defined a single time and not require attention from LTO, eliminates the miscompile and seems semantically more appropriate anyway. A separate bug report on the LTO bug is forthcoming.

Original addition of `const` is from #27307.
2021-03-02 00:50:11 +01:00
Jim Turner
b45855032b Document panicking cases for integer remainder
The panic when the right operand is `0` is expected, but the
overflow-related panic (which occurs only for `MIN % -1`) is somewhat
surprising for two reasons: a return value of `0` would be reasonable
in this case, and, for most arithmetic operations, overflow results in
panic only when `debug_assertions` is enabled. As a result, it's
helpful to document this behavior.
2021-03-01 17:13:50 -05:00
Jim Turner
9278b4c672 Document panicking cases for integer division
The panic on division by zero is expected, but the panic on overflow
is somewhat surprising (since most arithmetic operations panic on
overflow only when `debug_assertions` is enabled). As a result, it's
helpful to document this behavior.
2021-03-01 17:13:50 -05:00
Jim Turner
77c0a48b7e Fix inequality in docs for div_euclid
This commit fixes the statement of the inequality that the Euclidean
remainder satisfies. (The remainder is guaranteed to be less than
abs(rhs), not rhs.) It also rewords the documentation to make it a
little easier to read.
2021-03-01 15:54:00 -05:00
David Tolnay
bd51dea693
Change twice used large const table to static
This table is used twice in core::num::dec2flt::algorithm::power_of_ten.
According to the semantics of const, a separate huge definition of the
table is inlined at both places.

    fn power_of_ten(e: i16) -> Fp {
        assert!(e >= table::MIN_E);
        let i = e - table::MIN_E;
        let sig = table::POWERS.0[i as usize];
        let exp = table::POWERS.1[i as usize];
        Fp { f: sig, e: exp }
    }

Theoretically this gets cleaned up by optimization passes, but in
practice I am experiencing a miscompile from LTO on this code. Making
the table a static, which would only be defined a single time and not
require attention from LTO, eliminates the miscompile and seems
semantically more appropriate anyway. A separate bug report on the LTO
bug is forthcoming.
2021-03-01 10:41:16 -08:00
Vytautas Astrauskas
cdfff98394 Try to clarify GlobalAlloc::realloc documentation comment. 2021-02-28 14:30:26 +01:00
bors
ec7f8d94df Auto merge of #81874 - tesuji:spec_slice_fill, r=matthewjasper
Specialize slice::fill with Copy type and u8/i8/bool

I don't expect rustperf could measure any perf improvements with this changes
since `slice::fill` is newly added.

Godbolt link for this change: <https://rust.godbolt.org/z/r3fzee>.

r? `@matthewjasper` since this patch added new specialization.
2021-02-27 14:54:31 +00:00
Folyd
3eb5bee242 Fix binary_search_by() overflow issue in ZST case 2021-02-27 22:11:44 +08:00
John Hörnvall
907eab8e62 Added feature flag to doc test 2021-02-27 13:33:55 +01:00
John Hörnvall
772543aeff Removed trailing whitespace 2021-02-27 13:10:00 +01:00
John Hörnvall
5b9905b0f3 Added CharIndices::offset function 2021-02-27 12:45:18 +01:00