Commit graph

870 commits

Author SHA1 Message Date
François Mockers 14e23f117e convert slice doc link to intra-doc links 2021-03-09 21:26:07 +01:00
Mara 232caad395
Rollup merge of #82764 - m-ou-se:map-try-insert, r=Amanieu
Add {BTreeMap,HashMap}::try_insert

`{BTreeMap,HashMap}::insert(key, new_val)` returns `Some(old_val)` if the key was already in the map. It's often useful to assert no duplicate values are inserted.

We experimented with `map.insert(key, val).unwrap_none()` (https://github.com/rust-lang/rust/issues/62633), but decided that that's not the kind of method we'd like to have on `Option`s.

`insert` always succeeds because it replaces the old value if it exists. One could argue that `insert()` is never the right method for panicking on duplicates, since already handles that case by replacing the value, only allowing you to panic after that already happened.

This PR adds a `try_insert` method that instead returns a `Result::Err` when the key already exists. This error contains both the `OccupiedEntry` and the value that was supposed to be inserted. This means that unwrapping that result gives more context:
```rust
    map.insert(10, "world").unwrap_none();
    // thread 'main' panicked at 'called `Option::unwrap_none()` on a `Some` value: "hello"', src/main.rs:8:29
```

```rust
    map.try_insert(10, "world").unwrap();
    // thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value:
    // OccupiedError { key: 10, old_value: "hello", new_value: "world" }', src/main.rs:6:33
```

It also allows handling the failure in any other way, as you have full access to the `OccupiedEntry` and the value.

`try_insert` returns a reference to the value in case of success, making it an alternative to `.entry(key).or_insert(value)`.

r? ```@Amanieu```

Fixes https://github.com/rust-lang/rfcs/issues/3092
2021-03-05 10:57:22 +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 eddd4f0501 Add tracking issue for map_try_insert. 2021-03-04 16:54:28 +01:00
Mara Bos d85d82ab22 Implement Error for OccupiedError. 2021-03-04 15:58:50 +01:00
Mara Bos 69d95e232a Improve Debug implementations of OccupiedError. 2021-03-04 15:58:50 +01:00
Mara Bos 09cbcdc2c3 Add BTreeMap::try_insert and btree_map::OccupiedError. 2021-03-04 15:58:50 +01:00
Yuki Okushi 290117f7d9
Rollup merge of #82564 - WaffleLapkin:revert_spare_mut, r=RalfJung
Revert `Vec::spare_capacity_mut` impl to prevent pointers invalidation

The implementation was changed in #79015.

Later it was [pointed out](https://github.com/rust-lang/rust/issues/81944#issuecomment-782849785) that the implementation invalidates pointers to the buffer (initialized elements) by creating a unique reference to the buffer. This PR reverts the implementation.

r? ```@RalfJung```
2021-03-04 20:01:06 +09:00
Waffle Lapkin 950f12119e
Update library/alloc/src/vec/mod.rs
Co-authored-by: Ralf Jung <post@ralfj.de>
2021-03-03 20:04:20 +03:00
Ryan Levick 3a86184777 Fix ui-full-deps suite 2021-03-03 11:22:49 +01:00
Yuki Okushi 46f9253098
Rollup merge of #82439 - ssomers:btree_fix_unsafety, r=Mark-Simulacrum
BTree: fix untrue safety

Fix needless and missing `unsafe` tags.

r? ````@Mark-Simulacrum````
2021-03-03 16:27:39 +09:00
Waffle a1835bcb01 Make Vec::split_at_spare_mut impl safer & simplier 2021-03-03 01:04:20 +03:00
Waffle 9c4e3af39d Add test that Vec::spare_capacity_mut doesn't invalidate pointers 2021-03-03 01:00:59 +03: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 efb9ee2df5
Rollup merge of #82578 - camsteffen:diag-items, r=oli-obk
Add some diagnostic items for Clippy
2021-03-01 11:25:07 -05:00
Joshua Nelson 57c568a918
Rollup merge of #81210 - ssomers:btree_fix_node_size_test, r=Mark-Simulacrum
BTreeMap: correct node size test case for choices of B

r? `@Mark-Simulacrum`
2021-03-01 11:24:58 -05:00
Cameron Steffen eada4d1c45 Add diagnostic items 2021-03-01 09:04:11 -06:00
bors 05c300144c Auto merge of #82440 - ssomers:btree_fix_casts, r=Mark-Simulacrum
BTree: no longer define impossible casts

Casts to leaf to internal only make sense when the original has a chance of being the thing it's cast to.

r? `@Mark-Simulacrum`
2021-03-01 05:39:01 +00:00
bors 3b150b7a8f Auto merge of #81094 - ssomers:btree_drainy_refactor_3, r=Mark-Simulacrum
BTreeMap: split up range_search into two stages

`range_search` expects the caller to pass the same root twice and starts searching a node for both bounds of a range. It's not very clear that in the early iterations, it searches twice in the same node. This PR splits that search up in an initial `find_leaf_edges_spanning_range` that postpones aliasing until the last second, and a second phase for continuing the search for the range in the each subtree independently (`find_lower_bound_edge` & `find_upper_bound_edge`), which greatly helps for use in #81075. It also moves those functions over to the search module.

r? `@Mark-Simulacrum`
2021-03-01 02:48:29 +00:00
Waffle 2f04a793ae Revert Vec::spare_capacity_mut impl to prevent pointers invalidation 2021-02-27 00:27:34 +03:00
Guillaume Gomez 0db8349fff
Rollup merge of #81940 - jhpratt:stabilize-str_split_once, r=m-ou-se
Stabilize str_split_once

Closes #74773
2021-02-26 15:52:29 +01:00
Joshua Nelson 9a75f4fed1 Convert primitives to use intra-doc links 2021-02-25 20:31:53 -05:00
Miguel Ojeda eefec8abda library: Normalize safety-for-unsafe-block comments
Almost all safety comments are of the form `// SAFETY:`,
so normalize the rest and fix a few of them that should
have been a `/// # Safety` section instead.

Furthermore, make `tidy` only allow the uppercase form. While
currently `tidy` only checks `core`, it is a good idea to prevent
`core` from drifting to non-uppercase comments, so that later
we can start checking `alloc` etc. too.

Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2021-02-24 06:13:42 +01:00
Dylan DPC 547b3adfe4
Rollup merge of #82113 - m-ou-se:panic-format-lint, r=estebank
Improve non_fmt_panic lint.

This change:
- fixes the span used by this lint in the case the panic argument is a single macro expansion (e.g. `panic!(a!())`);
- adds a suggestion for `panic!(format!(..))` to remove `format!()` instead of adding `"{}", ` or using `panic_any` like it does now; and
- fixes the incorrect suggestion to replace `panic![123]` by `panic_any(123]`.

Fixes #82109.
Fixes #82110.
Fixes #82111.

Example output:
```
warning: panic message is not a string literal
 --> src/main.rs:8:12
  |
8 |     panic!(format!("error: {}", "oh no"));
  |            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  |
  = note: `#[warn(non_fmt_panic)]` on by default
  = note: this is no longer accepted in Rust 2021
  = note: the panic!() macro supports formatting, so there's no need for the format!() macro here
help: remove the `format!(..)` macro call
  |
8 |     panic!("error: {}", "oh no");
  |           --                  --

```

r? `@estebank`
2021-02-23 16:10:21 +01:00
Stein Somers 986a183337 BTree: fix untrue safety 2021-02-23 11:44:10 +01:00
Stein Somers 794561c391 BTree: no longer define impossible casts 2021-02-23 11:39:03 +01:00
Stein Somers deebb63cc8 BTree: split off reusable components from range_search 2021-02-23 10:15:51 +01:00
bors cd64446196 Auto merge of #82076 - jyn514:update-bootstrap, r=Mark-Simulacrum
Update the bootstrap compiler

This updates the bootstrap compiler, notably leaving out a change to enable semicolon in macro expressions lint, because stdarch still depends on the old behavior.
2021-02-23 07:19:41 +00:00
bors a4e595db8f Auto merge of #82430 - Dylan-DPC:rollup-nu4kfyc, r=Dylan-DPC
Rollup of 12 pull requests

Successful merges:

 - #79423 (Enable smart punctuation)
 - #81154 (Improve design of `assert_len`)
 - #81235 (Improve suggestion for tuple struct pattern matching errors.)
 - #81769 (Suggest `return`ing tail expressions that match return type)
 - #81837 (Slight perf improvement on char::to_ascii_lowercase)
 - #81969 (Avoid `cfg_if` in `std::os`)
 - #81984 (Make WASI's `hard_link` behavior match other platforms.)
 - #82091 (use PlaceRef abstractions more consistently)
 - #82128 (add diagnostic items for OsString/PathBuf/Owned as well as to_vec on slice)
 - #82166 (add s390x-unknown-linux-musl target)
 - #82234 (Remove query parameters when skipping search results)
 - #82255 (Make `treat_err_as_bug` Option<NonZeroUsize>)

Failed merges:

r? `@ghost`
`@rustbot` modify labels: rollup
2021-02-23 04:31:32 +00:00
Dylan DPC b8d4354099
Rollup merge of #82128 - anall:feature/add_diagnostic_items, r=davidtwco
add diagnostic items for OsString/PathBuf/Owned as well as to_vec on slice

This is adding diagnostic items to be used by rust-lang/rust-clippy#6730, but my understanding is the clippy-side change does need to be done over there since I am adding a new clippy feature.

Add diagnostic items to the following types:
  OsString (os_string_type)
  PathBuf (path_buf_type)
  Owned (to_owned_trait)

As well as the to_vec method on slice/[T]
2021-02-23 02:51:51 +01:00
Dylan DPC 72e6d51583
Rollup merge of #81154 - dylni:improve-design-of-assert-len, r=KodrAus
Improve design of `assert_len`

It was discussed in the [tracking issue](https://github.com/rust-lang/rust/issues/76393#issuecomment-761765448) that `assert_len`'s name and usage are confusing. This PR improves them based on a suggestion by ``@scottmcm`` in that issue.

I also improved the documentation to make it clearer when you might want to use this method.

Old example:

```rust
let range = range.assert_len(slice.len());
```

New example:

```rust
let range = range.ensure_subset_of(..slice.len());
```

Fixes #81157
2021-02-23 02:51:43 +01:00
bors b02a6193b3 Auto merge of #81937 - ssomers:btree_drainy_refactor_9b, r=Mark-Simulacrum
BTree: move more shared iterator code into navigate.rs

The functions in navigate.rs only exist to support iterators, and these look easier on my eyes if there is a shared `struct` with the recurring pair of handles.

r? `@Mark-Simulacrum`
2021-02-23 00:30:37 +00:00
bors a15f484b91 Auto merge of #81362 - ssomers:btree_drainy_refactor_8, r=Mark-Simulacrum
BTreeMap: gather and decompose reusable tree fixing functions

This is kind of pushing it as a standalone refactor, probably only useful for #81075 (or similar).
r? `@Mark-Simulacrum`
2021-02-22 17:56:43 +00:00
Stein Somers d9daedd433 BTreeMap: correct tests for alternative choices of B 2021-02-21 19:06:46 +01:00
Yuki Okushi 56ae3fb2f0
Rollup merge of #81706 - SkiFire13:document-binaryheap-unsafe, r=Mark-Simulacrum
Document BinaryHeap unsafe functions

`BinaryHeap` contains some private safe functions but that are actually unsafe to call. This PR marks them `unsafe` and documents all the `unsafe` function calls inside them.

While doing this I might also have found a bug: some "SAFETY" comments in `sift_down_range` and `sift_down_to_bottom` are valid only if you assume that `child` doesn't overflow. However it may overflow if `end > isize::MAX` which can be true for ZSTs (but I think only for them). I guess the easiest fix would be to skip any sifting if `mem::size_of::<T> == 0`.

Probably conflicts with #81127 but solving the eventual merge conflict should be pretty easy.
2021-02-21 15:26:40 +09:00
Yuki Okushi 3219a100fa
Rollup merge of #81300 - ssomers:btree_cleanup_leak_tests, r=Mark-Simulacrum
BTree: share panicky test code & test panic during clear, clone

Bases almost all tests of panic on the same, richer definition, and extends it to cloning to test panic during clone.

r? ```@Mark-Simulacrum```
2021-02-21 15:26:36 +09:00
Joshua Nelson 3733275854 Update the bootstrap compiler
Note this does not change `core::derive` since it was merged after the
beta bump.
2021-02-20 17:19:30 -05:00
Giacomo Stevanato 3ec1a28418 Add FIXME for safety comments that are invalid when T is a ZST 2021-02-20 15:44:17 -05:00
Giacomo Stevanato 9b4e61255c Document BinaryHeap unsafe functions 2021-02-20 15:44:17 -05:00
Andrea Nall 67fcaaaa7a a few more diagnostic items 2021-02-16 02:32:21 +00:00
Andrea Nall c6bb62810a requested/proposed changes 2021-02-15 22:59:47 +00:00
Tomasz Miąsko dc3304c341 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-02-15 17:36:29 +01:00
Jonas Schievink c7ebc590da
Rollup merge of #82060 - taiki-e:typo, r=m-ou-se
Fix typos in BTreeSet::{first, last} docs

map -> set
2021-02-15 16:06:56 +01:00
Stein Somers 342aa694f9 BTree: move more shared iterator code into navigate.rs 2021-02-15 10:56:22 +01:00
Andrea Nall 5ef202520f add diagnostic items
Add diagnostic items to the following types:
  OsString (os_string_type)
  PathBuf (path_buf_type)
  Owned (to_owned_trait)

As well as the to_vec method on slice/[T]
2021-02-15 02:27:28 +00:00
Mara Bos daa371d189 Only define rustc_diagnostic_item format_macro in not(test). 2021-02-14 20:03:13 +01:00
Mara Bos a428ab17ab Improve suggestion for panic!(format!(..)). 2021-02-14 18:52:47 +01:00
Dylan DPC 4e888bf403
Rollup merge of #81919 - ssomers:btree_cleanup_comments, r=Mark-Simulacrum
BTreeMap: fix internal comments

Salvaged from #81372

r? `@Mark-Simulacrum`
2021-02-14 16:54:49 +01:00
bors b86674e7cc Auto merge of #81956 - ssomers:btree_post_75200, r=Mark-Simulacrum
BTree: remove outdated traces of coercions

The introduction of `marker::ValMut` (#75200) meant iterators no longer see mutable keys but their code still pretends it does. And settle on the majority style `Some(unsafe {…})` over `unsafe { Some(…) }`.

r? `@Mark-Simulacrum`
2021-02-14 04:53:24 +00:00