Commit Graph

4029 Commits

Author SHA1 Message Date
Dylan DPC
d8091f8991
Rollup merge of #102578 - lukas-code:ilog-panic, r=m-ou-se
Panic for invalid arguments of `{integer primitive}::ilog{,2,10}` in all modes

Decision made in https://github.com/rust-lang/rust/issues/100422#issuecomment-1245864700

resolves https://github.com/rust-lang/rust/issues/100422

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

r? `@m-ou-se`
2022-10-12 11:11:25 +05:30
Matthias Krüger
d10b47ef69
Rollup merge of #102445 - jmillikin:cstr-is-empty, r=Mark-Simulacrum
Add `is_empty()` method to `core::ffi::CStr`.

ACP: https://github.com/rust-lang/libs-team/issues/106

Tracking issue: https://github.com/rust-lang/rust/issues/102444
2022-10-11 18:59:48 +02:00
Matthias Krüger
d13f7aef70
Rollup merge of #101774 - Riolku:atomic-update-aba, r=m-ou-se
Warn about safety of `fetch_update`

Specifically as it relates to the ABA problem.

`fetch_update` is a useful function, and one that isn't provided by, say, C++. However, this does not mean the function is magic. It is implemented in terms of `compare_exchange_weak`, and in particular, suffers from the ABA problem. See the following code, which is a naive implementation of `pop` in a lock-free queue:

```rust
fn pop(&self) -> Option<i32> {
    self.front.fetch_update(Ordering::Relaxed, Ordering::Acquire, |front| {
        if front == ptr::null_mut() {
            None
        }
        else {
            Some(unsafe { (*front).next })
        }
    }.ok()
}
```

This code is unsound if called from multiple threads because of the ABA problem. Specifically, suppose nodes are allocated with `Box`. Suppose the following sequence happens:

```
Initial: Queue is X -> Y.

Thread A: Starts popping, is pre-empted.
Thread B: Pops successfully, twice, leaving the queue empty.
Thread C: Pushes, and `Box` returns X (very common for allocators)
Thread A: Wakes up, sees the head is still X, and stores Y as the new head.
```

But `Y` is deallocated. This is undefined behaviour.

Adding a note about this problem to `fetch_update` should hopefully prevent users from being misled, and also, a link to this common problem is, in my opinion, an improvement to our docs on atomics.
2022-10-11 18:59:46 +02:00
Yuki Okushi
ff903bbb71
Rollup merge of #102258 - cjgillot:core-kappa, r=m-ou-se
Remove unused variable in float formatting.
2022-10-11 18:37:52 +09:00
bors
0265a3e93b Auto merge of #96711 - emilio:inline-slice-clone, r=nikic
slice: #[inline] a couple iterator methods.

The one I care about and actually saw in the wild not getting inlined is
clone(). We ended up doing a whole function call for something that just
copies two pointers.

I ended up marking as_slice / as_ref as well because make_slice is
inline(always) itself, and is also the kind of think that can kill
performance in hot loops if you expect it to get inlined. But happy to
undo those.
2022-10-10 12:09:21 +00:00
Dylan DPC
7e16f9f1ea
Rollup merge of #99696 - WaffleLapkin:uplift, r=fee1-dead
Uplift `clippy::for_loops_over_fallibles` lint into rustc

This PR, as the title suggests, uplifts [`clippy::for_loops_over_fallibles`] lint into rustc. This lint warns for code like this:
```rust
for _ in Some(1) {}
for _ in Ok::<_, ()>(1) {}
```
i.e. directly iterating over `Option` and `Result` using `for` loop.

There are a number of suggestions that this PR adds (on top of what clippy suggested):
1. If the argument (? is there a better name for that expression) of a `for` loop is a `.next()` call, then we can suggest removing it (or rather replacing with `.by_ref()` to allow iterator being used later)
   ```rust
    for _ in iter.next() {}
    // turns into
    for _ in iter.by_ref() {}
    ```
2. (otherwise) We can suggest using `while let`, this is useful for non-iterator, iterator-like things like [async] channels
   ```rust
   for _ in rx.recv() {}
   // turns into
   while let Some(_) = rx.recv() {}
   ```
3. If the argument type is `Result<impl IntoIterator, _>` and the body has a `Result<_, _>` type, we can suggest using `?`
   ```rust
   for _ in f() {}
   // turns into
   for _ in f()? {}
   ```
4. To preserve the original behavior and clear intent, we can suggest using `if let`
   ```rust
   for _ in f() {}
   // turns into
   if let Some(_) = f() {}
   ```
(P.S. `Some` and `Ok` are interchangeable depending on the type)

I still feel that the lint wording/look is somewhat off, so I'll be happy to hear suggestions (on how to improve suggestions :D)!

Resolves #99272

[`clippy::for_loops_over_fallibles`]: https://rust-lang.github.io/rust-clippy/master/index.html#for_loops_over_fallibles
2022-10-10 13:43:40 +05:30
Scott McMurray
0718aeceb3 From<Alignment> for usize & NonZeroUsize 2022-10-09 15:44:49 -07:00
Yuki Okushi
38db483af7
Rollup merge of #102072 - scottmcm:ptr-alignment-type, r=thomcc
Add `ptr::Alignment` type

Essentially no new code here, just exposing the previously-`pub(crate)` `ValidAlign` type under the name from the ACP.

ACP: https://github.com/rust-lang/libs-team/issues/108
Tracking Issue: https://github.com/rust-lang/rust/issues/102070

r? ``@ghost``
2022-10-10 00:09:40 +09:00
Maybe Waffle
7434b9f0d1 fixup lint name 2022-10-09 13:07:21 +00:00
Maybe Waffle
75ae20a42f allow for_loop_over_fallibles in a core test 2022-10-09 13:07:20 +00:00
Michael Howell
c58886d428
Rollup merge of #102812 - est31:remove_lazy, r=dtolnay
Remove empty core::lazy and std::lazy

PR #98165 with commits 7c360dc117 and c1a2db3372 has moved all of the components of these modules into different places, namely {std,core}::sync and {std,core}::cell. The empty modules remained. As they are unstable, we can simply remove them.
2022-10-08 18:15:01 -07:00
Matthias Krüger
e6f6ad0576
Rollup merge of #99880 - compiler-errors:escape-ascii-is-not-exact-size-iterator, r=thomcc
`EscapeAscii` is not an `ExactSizeIterator`

Fixes #99878

Do we want/need `EscapeAscii` to be an `ExactSizeIterator`? I guess we could precompute the length of the output if so?
2022-10-08 23:32:02 +02:00
bors
8796e7a9cf Auto merge of #102315 - RalfJung:assert_unsafe_precondition, r=thomcc
add a few more assert_unsafe_precondition

Add debug-assertion checking for `ptr.read()`, `ptr.write(_)`, and `unreachable_unchecked.`

This is quite useful for [cargo-careful](https://github.com/RalfJung/cargo-careful).
2022-10-08 17:59:45 +00:00
est31
4d9d7bf312 Remove empty core::lazy and std::lazy
PR #98165 with commits 7c360dc117 and c1a2db3372
has moved all of the components of these modules into different places,
namely {std,core}::sync and {std,core}::cell. The empty
modules remained. As they are unstable, we can simply remove them.
2022-10-08 15:55:15 +02:00
bors
8b0c05d9ad Auto merge of #102091 - RalfJung:const_err, r=oli-obk
make const_err a hard error

This lint has been deny-by-default with future incompat wording since [Rust 1.51](https://github.com/rust-lang/rust/pull/80394) and the stable release of this week starts showing it in cargo's future compat reports. I can't wait to finally get rid of at least some of the mess in our const-err-reporting-code. ;)

r? `@oli-obk`
Fixes https://github.com/rust-lang/rust/issues/71800
Fixes https://github.com/rust-lang/rust/issues/100114
2022-10-07 20:50:51 +00:00
Dylan DPC
2592609574
Rollup merge of #102300 - scottmcm:simpler-fold-closures, r=Mark-Simulacrum
Use a macro to not have to copy-paste `ConstFnMutClosure::new(&mut fold, NeverShortCircuit::wrap_mut_2_imp)).0` everywhere

Also use that macro to replace a bunch of places that had custom closure-wrappers.

+35 -114 sounds good to me.
2022-10-07 22:05:29 +05:30
Ralf Jung
fd59d44f58 make const_err a hard error 2022-10-07 18:08:49 +02:00
Ralf Jung
6f6433428f add a few more assert_unsafe_precondition 2022-10-07 14:35:12 +02:00
Matthias Krüger
f55fef165e
Rollup merge of #102647 - oli-obk:tilde_const_bounds, r=fee1-dead
Only allow ~const bounds for traits with #[const_trait]

r? `@fee1-dead`
2022-10-04 18:26:39 +02:00
Dylan DPC
c1d4003506
Rollup merge of #101189 - daxpedda:ready-into-inner, r=joshtriplett
Implement `Ready::into_inner()`

Tracking issue: #101196.

This implements a method to unwrap the value inside a `Ready` outside an async context.
See https://docs.rs/futures/0.3.24/futures/future/struct.Ready.html#method.into_inner for previous work.

This was discussed in [Zulip beforehand](https://rust-lang.zulipchat.com/#narrow/stream/219381-t-libs/topic/.60Ready.3A.3Ainto_inner.28.29.60):
> An example I'm hitting right now:
I have a cross-platform library that provides a functions that returns a `Future`. The only reason why it returns a `Future` is because the WASM platform requires it, but the native doesn't, to make a cross-platform API that is equal for all I just return a `Ready` on the native targets.
>
> Now I would like to expose native-only functions that aren't async, that users can use to avoid having to deal with async when they are targeting native. With `into_inner` that's easily solvable now.
>
> I want to point out that some internal restructuring could be used to solve that problem too, but in this case it's not that simple, the library uses internal traits that return the `Future` already and playing around with that would introduce unnecessary `cfg` in a lot more places. So it is really only a quality-of-life feature.
2022-10-04 16:11:00 +05:30
Oli Scherer
33bcea8f61 Only allow ~const bounds for traits with #[const_trait] 2022-10-04 08:06:54 +00:00
Matthias Krüger
17c65826d3
Rollup merge of #102628 - H4x5:master, r=scottmcm
Change the parameter name of From::from to `value`

The `From` trait is currently defined as:
```rust
pub trait From<T>: Sized {
    fn from(_: T) -> Self;
}
```

The name of the argument is `_`. I am proposing to change it to `value`, ie.
```rust
pub trait From<T>: Sized {
    fn from(value: T) -> Self;
}
```

This would be more consistent with the `TryFrom`, which looks like this:
```rust
pub trait TryFrom<T>: Sized {
    type Error;
    fn try_from(value: T) -> Result<Self, Self::Error>;
}
```

The reason for this proposal is twofold:
1. Consistency with the rest of the standard library. The `TryFrom` trait uses `value`, and no `From` implementation uses the default name (as it is quite useless).
2. When generating trait implementations with rust-analyzer/IntelliJ, the parameter name is copied, and it always has to be changed.

Optionally, another name like `x` could be used. I only propose `value` for consistency with `TryFrom`.

Changing parameter names is not a breaking change.

Note: this was originally posted as an internals thread [here](https://internals.rust-lang.org/t/change-the-argument-name-of-from-from/17480)
2022-10-04 06:14:12 +02:00
bors
1f1defc2f6 Auto merge of #99099 - Stargateur:phantomdata_debug, r=joshtriplett
Add T to PhantomData impl Debug

This add debug information for `PhantomData`, I believe it's make sense to add this to debug impl of `PhantomData` since `T` is what define what is the `PhantomData` just write `"PhantomData"` is not very useful for debugging.

Alternative:

* `PhantomData::<{}>`
* `PhantomData { t: "str_type" }`

`@rustbot` label +T-libs-api -T-libs
2022-10-04 00:56:14 +00:00
bors
f83e0266cf Auto merge of #102632 - matthiaskrgr:rollup-h8s3zmo, r=matthiaskrgr
Rollup of 7 pull requests

Successful merges:

 - #98218 (Document the conditional existence of `alloc::sync` and `alloc::task`.)
 - #99216 (docs: be less harsh in wording for Vec::from_raw_parts)
 - #99460 (docs: Improve AsRef / AsMut docs on blanket impls)
 - #100470 (Tweak `FpCategory` example order.)
 - #101040 (Fix `#[derive(Default)]` on a generic `#[default]` enum adding unnecessary `Default` bounds)
 - #101308 (introduce `{char, u8}::is_ascii_octdigit`)
 - #102486 (Add diagnostic struct for const eval error in `rustc_middle`)

Failed merges:

r? `@ghost`
`@rustbot` modify labels: rollup
2022-10-03 20:22:18 +00:00
Matthias Krüger
a5488826a9
Rollup merge of #101308 - nerdypepper:feature/is-ascii-octdigit, r=joshtriplett
introduce `{char, u8}::is_ascii_octdigit`

This feature adds two new APIs: `char::is_ascii_octdigit` and `u8::is_ascii_octdigit`, under the feature gate `is_ascii_octdigit`. These methods are shorthands for `char::is_digit(self, 8)` and `u8::is_digit(self, 8)`:

```rust
// core::char

impl char {
    pub fn is_ascii_octdigit(self) -> bool;
}

// core::num

impl u8 {
    pub fn is_ascii_octdigit(self) -> bool;
}
```

---

Couple of things I need help understanding:

- `const`ness: have I used the right attribute in this case?
- is there a way to run the tests for `core::char` alone, instead of `./x.py test library/core`?
2022-10-03 20:58:56 +02:00
Matthias Krüger
c7f1b8e41d
Rollup merge of #100470 - reitermarkus:patch-1, r=joshtriplett
Tweak `FpCategory` example order.

Follow same order for variable declarations and assertions.
2022-10-03 20:58:55 +02:00
Matthias Krüger
eedb51210c
Rollup merge of #99460 - JanBeh:PR_asref_asmut_docs, r=joshtriplett
docs: Improve AsRef / AsMut docs on blanket impls

There are several issues with the current state of `AsRef` and `AsMut` as [discussed here on IRLO](https://internals.rust-lang.org/t/semantics-of-asref/17016). See also #39397, #45742, #73390, #98905, and the FIXMEs [here](https://github.com/rust-lang/rust/blob/1.62.0/library/core/src/convert/mod.rs#L509-L515) and [here](https://github.com/rust-lang/rust/blob/1.62.0/library/core/src/convert/mod.rs#L530-L536). These issues are difficult to fix. This PR aims to update the documentation to better reflect the status-quo and to give advice on how `AsRef` and `AsMut` should be used.

In particular:

- Explicitly mention that `AsRef` and `AsMut` do not auto-dereference generally for all dereferencable types (but only if inner type is a shared and/or mutable reference)
- Give advice to not use `AsRef` or `AsMut` for the sole purpose of dereferencing
- Suggest providing a transitive `AsRef` or `AsMut` implementation for types which implement `Deref`
- Add new section "Reflexivity" in documentation comments for `AsRef` and `AsMut`
- Provide better example for `AsMut`
- Added heading "Relation to `Borrow`" in `AsRef`'s docs to improve structure
2022-10-03 20:58:54 +02:00
H4x5
8dcecdb487
Change the parameter name of From::from to value 2022-10-03 13:36:57 -04:00
Matthias Krüger
3374a7d6f8
Rollup merge of #102607 - WaffleLapkin:docky_docky_slice_from_ptr_range, r=joshtriplett
Improve documentation of `slice::{from_ptr_range, from_ptr_range_mut}`

Document panic conditions (`T` is a ZST) and sync docs of shared/unique version.

cc `@wx-csy`
2022-10-03 19:12:18 +02:00
Matthias Krüger
cdd0ba8f41
Rollup merge of #102569 - eduardosm:from_str-example, r=joshtriplett
Improve `FromStr` example

The `from_str` implementation from the example had an `unwrap` that would make it panic on invalid input strings. Instead of panicking, it nows returns an error to better reflect the intented behavior of the `FromStr` trait.
2022-10-03 19:12:17 +02:00
Maybe Waffle
2cd5fafd25 Sync docs of slice::{from_ptr_range, from_ptr_range_mut} 2022-10-03 00:44:50 +00:00
Maybe Waffle
bc1216e046 Document when slice::from_ptr_range[_mut] panic 2022-10-03 00:41:54 +00:00
Lukas Markeffsky
b7dae8a5e2 remove unneeded attributes 2022-10-02 15:15:40 +02:00
bors
91931ec2fc Auto merge of #98354 - camsteffen:is-some-and-by-value, r=m-ou-se
Change `is_some_and` to take by value

Consistent with other function-accepting `Option` methods.

Tracking issue: #93050

r? `@m-ou-se`
2022-10-02 12:48:15 +00:00
Lukas Markeffsky
6acc29f88b add tests for panicking integer logarithms 2022-10-02 14:25:36 +02:00
Lukas Markeffsky
69cafc0699 always panic for invalid integer logarithm 2022-10-02 14:24:56 +02:00
bors
756e7be5eb Auto merge of #102548 - nikic:inline-cell-replace, r=scottmcm
Mark Cell::replace() as #[inline]

Giving this a try based on https://github.com/rust-lang/rust/issues/102539#issuecomment-1264398807.
2022-10-02 09:53:07 +00:00
Eduardo Sánchez Muñoz
9c7c232a50 Improve FromStr example
The `from_str` implementation from the example had an `unwrap` that would make it panic on invalid input strings. Instead of panicking, it nows returns an error to better reflect the intented behavior of the `FromStr` trait.
2022-10-02 11:32:56 +02:00
bors
c2590e6e89 Auto merge of #102535 - scottmcm:optimize-split-at-partition-point, r=thomcc
Tell LLVM that `partition_point` returns a valid fencepost

This was already done for a successful `binary_search`, but this way `partition_point` can get similar optimizations.

Demonstration that nightly can't do this optimization today, and leaves in the panicking path: <https://play.rust-lang.org/?version=nightly&mode=release&edition=2021&gist=e1074cd2faf5f68e49cffd728ded243a>

r? `@thomcc`
2022-10-02 07:11:15 +00:00
Matthias Krüger
baba8391c3
Rollup merge of #102405 - hkBst:patch-3, r=Mark-Simulacrum
Remove a FIXME whose code got moved away in #62883.

Remove a FIXME whose code got moved away in https://github.com/rust-lang/rust/pull/62883.
2022-10-02 03:16:39 +02:00
Cameron Steffen
4f12de0660 Change feature name to is_some_and 2022-10-01 11:45:52 -05:00
Cameron Steffen
2f83134e37 Change is_some_and to take by value 2022-10-01 11:45:52 -05:00
Nikita Popov
49eaa0f6ac Mark Cell::replace() as #[inline] 2022-10-01 17:30:54 +02:00
Scott McMurray
c7af338e6f Tell LLVM that partition_point returns a valid fencepost
This was already done for a successful `binary_search`, but this way `partition_point` can get similar optimizations.
2022-09-30 23:39:15 -07:00
bors
877877a19a Auto merge of #102520 - matthiaskrgr:rollup-7nreat0, r=matthiaskrgr
Rollup of 6 pull requests

Successful merges:

 - #102276 (Added more const_closure functionality)
 - #102382 (Manually order `DefId` on 64-bit big-endian)
 - #102421 (remove the unused :: between trait and type to give user correct diag…)
 - #102495 (Reinstate `hir-stats.rs` test for stage 1.)
 - #102505 (rustdoc: remove no-op CSS `h3.variant, .sub-variant h4 { border-bottom: none }`)
 - #102506 (Specify `DynKind::Dyn`)

Failed merges:

r? `@ghost`
`@rustbot` modify labels: rollup
2022-09-30 17:47:57 +00:00
onestacked
10739d475e Add back ConstFnMutClosure::new, fix formatting 2022-09-30 17:41:01 +02:00
onestacked
9a641a533c Fixed Documentation for wrap_mut_2_imp 2022-09-30 17:16:59 +02:00
onestacked
b73241aa5b Added more const_closure functionality. 2022-09-30 17:16:59 +02:00
beetrees
e409ce2159
Fix integer overflow in format!("{:.0?}", Duration::MAX) 2022-09-29 23:06:22 +01:00
Dylan DPC
34f02c3e8d
Rollup merge of #102452 - granolocks:grammar-tweak, r=thomcc
fix minor ungrammatical sentence

This fixes an innocuous ungrammatical sentence in example code in the  `TryFrom` documentation.
2022-09-29 18:13:21 +05:30