Commit Graph

9669 Commits

Author SHA1 Message Date
Dylan DPC
d056ea8828
Rollup merge of #103153 - ChrisDenton:leak-oom, r=m-ou-se
Allow `Vec::leak` when using `no_global_oom_handling`

As [the documentation notes](https://doc.rust-lang.org/std/vec/struct.Vec.html#method.leak), `Vec::leak` hasn't allocated since 1.57.

cc `@Ericson2314` in case I'm missing something.
2022-10-19 14:05:53 +05:30
Dylan DPC
f4afb9d9ec
Rollup merge of #103127 - SUPERCILEX:inline-const-uninit, r=scottmcm
Make transpose const and inline

r? `@scottmcm`

- These should have been const from the beginning since we're never going to do more than a transmute.
- Inline these always because that's what every other method in MaybeUninit which simply casts does. :) Ok, but a stronger justification is that because we're taking in arrays by `self`, not inlining would defeat the whole purpose of using `MaybeUninit` due to the copying.
2022-10-19 14:05:52 +05:30
bors
84365fff0a Auto merge of #103225 - matthiaskrgr:rollup-1zkv87y, r=matthiaskrgr
Rollup of 4 pull requests

Successful merges:

 - #103166 (Optimize `slice_iter.copied().next_chunk()`)
 - #103176 (Fix `TyKind::is_simple_path`)
 - #103178 (Partially fix `src/test/run-make/coverage-reports` when cross-compiling)
 - #103198 (Update cargo)

Failed merges:

r? `@ghost`
`@rustbot` modify labels: rollup
2022-10-19 05:41:14 +00:00
Matthias Krüger
d6eb7bca09
Rollup merge of #103166 - the8472:copied-next-chunk, r=m-ou-se
Optimize `slice_iter.copied().next_chunk()`

```
OLD:
test iter::bench_copied_array_chunks                               ... bench:         371 ns/iter (+/- 7)
NEW:
test iter::bench_copied_array_chunks                               ... bench:          31 ns/iter (+/- 0)
```

The default `next_chunk` implementation suffers from having to assemble the array byte by byte via `next()`, checking the `Option<&T>` and then dereferencing `&T`. The specialization copies the chunk directly from the slice.
2022-10-19 07:15:30 +02:00
The 8472
873a18e221 specialize slice_iter.copied().next_chunk() 2022-10-19 00:02:00 +02:00
Matthias Krüger
18431b66ce
Rollup merge of #102507 - scottmcm:more-binary-search-docs, r=m-ou-se
More slice::partition_point examples

After seeing the discussion of `binary_search` vs `partition_point` in #101999, I thought some more example code could be helpful.
2022-10-18 21:18:46 +02:00
Matthias Krüger
d2644e538c
Rollup merge of #101889 - tspiteri:redoc-uint-adc-sbb, r=m-ou-se
doc: rewrite doc for uint::{carrying_add,borrowing_sub}

Reword the documentation for bigint helper methods `uint::{carrying_add,borrowing_sub}` (#85532).

The examples were also rewritten to demonstrate how the methods can be used in bignum arithmetic. No loops are used in the examples, but the variable names were chosen to include indices so that it is clear how this can be used in a loop if required.

Also, previously `carrying_add` had an example to say that if the input carry is false, the method is equivalent to `overflowing_add`. While the note was kept, the example was removed and an extra note was added to make sure this equivalence is not assumed for signed integers as well.
2022-10-18 21:18:46 +02:00
est31
d89fb1dee5 Stabilize proc_macro::Span::source_text
Splits proc_macro::Span::source_text into a new feature gate and stabilizes it.
2022-10-18 17:13:41 +02:00
bors
e94827e5b0 Auto merge of #103188 - JohnTitor:rollup-pwilam1, r=JohnTitor
Rollup of 6 pull requests

Successful merges:

 - #103023 (Adding `fuchsia-ignore` and `needs-unwind` to compiler test cases)
 - #103142 (Make diagnostic for unsatisfied `Termination` bounds more precise)
 - #103154 (Fix typo in `ReverseSearcher` docs)
 - #103159 (Remove the redundant `Some(try_opt!(..))` in `checked_pow`)
 - #103163 (Remove all uses of array_assume_init)
 - #103168 (Stabilize asm_sym)

Failed merges:

r? `@ghost`
`@rustbot` modify labels: rollup
2022-10-18 13:35:43 +00:00
Yuki Okushi
b411b8861c
Rollup merge of #103163 - SUPERCILEX:uninit-array-assume2, r=scottmcm
Remove all uses of array_assume_init

See https://github.com/rust-lang/rust/pull/103134#discussion_r997462733

r? `@scottmcm`
2022-10-18 21:21:32 +09:00
Yuki Okushi
e04bbcb9b1
Rollup merge of #103159 - cuviper:check_pow-final-try_opt, r=Mark-Simulacrum
Remove the redundant `Some(try_opt!(..))` in `checked_pow`

The final return value doesn't need to be tried at all -- we can just
return the checked option directly. The optimizer can probably figure
this out anyway, but there's no need to make it work here.
2022-10-18 21:21:31 +09:00
Yuki Okushi
ba643786b8
Rollup merge of #103154 - H4x5:reverse-searcher-typo, r=Mark-Simulacrum
Fix typo in `ReverseSearcher` docs
2022-10-18 21:21:31 +09:00
Yuki Okushi
472a8742a6
Rollup merge of #103142 - fmease:fix-103052, r=oli-obk
Make diagnostic for unsatisfied `Termination` bounds more precise

Don't blindly emit a diagnostic claiming that “*`main` has an invalid return type*” if we encounter a type that should but doesn't implement `std::process::Termination` and isn't actually the return type of the program entry `main`.

Fixes #103052.

``@rustbot`` label A-diagnostics T-compiler T-libs
r? diagnostics
2022-10-18 21:21:30 +09:00
bors
21b246587c Auto merge of #103075 - SUPERCILEX:miri-metadata, r=thomcc
Support DirEntry metadata calls in miri

This should work as it uses lstat64 which is supported here: ~d9ad25ee4b/src/shims/unix/macos/foreign_items.rs (L42~) just noticed that's macos, linux would be using statx: 86f0e63b21/src/shims/unix/linux/foreign_items.rs (L112)

The failing syscall is `dirfd`, so maybe that should actually be added to the shims?
2022-10-18 10:54:53 +00:00
The 8472
963d6f757c add a benchmark for slice_iter.copied().array_chunks() 2022-10-17 23:40:21 +02:00
Alex Saveau
55d71c61b8
Remove all uses of array_assume_init
Signed-off-by: Alex Saveau <saveau.alexandre@gmail.com>
2022-10-17 13:03:54 -07:00
bors
06f049a355 Auto merge of #101837 - scottmcm:box-array-from-vec, r=m-ou-se
Add `Box<[T; N]>: TryFrom<Vec<T>>`

We have `[T; N]: TryFrom<Vec<T>>` (#76310) and `Box<[T; N]>: TryFrom<Box<[T]>>`, but not this combination.

`vec.into_boxed_slice().try_into()` isn't quite a replacement for this, as that'll reallocate unnecessarily in the error case.

**Insta-stable, so needs an FCP**

(I tried to make this work with `, A`, but that's disallowed because of `#[fundamental]` https://github.com/rust-lang/rust/issues/29635#issuecomment-1247598385)
2022-10-17 19:46:04 +00:00
Josh Stone
d7fd1d57ec Remove the redundant Some(try_opt!(..)) in checked_pow
The final return value doesn't need to be tried at all -- we can just
return the checked option directly. The optimizer can probably figure
this out anyway, but there's no need to make it work here.
2022-10-17 11:21:50 -07:00
Sky
9a7e527e28
Fix typo in ReverseSearcher docs 2022-10-17 13:14:15 -04:00
Chris Denton
913393a0f7
Allow Vec::leak with no_global_oom_handling 2022-10-17 17:12:32 +01:00
León Orell Valerian Liehr
684df4d24e
Make diagnostic for unsatisfied Termination bounds more precise 2022-10-17 12:08:46 +02:00
David Tolnay
0bb6eb1526
Eliminate 280-byte memset from ReadDir iterator 2022-10-16 23:43:35 -07:00
Thayne McCombs
63a7fdf61b Fix types in documentation for Alignment::as_usize and Alignmnet::as_nonzero 2022-10-16 23:44:06 -06:00
Alex Saveau
1a1ebb080f
Make transpose const and inline
Signed-off-by: Alex Saveau <saveau.alexandre@gmail.com>
2022-10-16 17:51:38 -07:00
Matthias Krüger
0602d6484b
Rollup merge of #103109 - RalfJung:phantom-data-impl, r=thomcc
PhantomData: inline a macro that is used only once

I suspect this macro used to have more uses, but right now it just obfuscates the code.
2022-10-16 22:36:06 +02:00
Matthias Krüger
bdfc262742
Rollup merge of #103102 - H4x5:len_utf16_docs, r=scottmcm
Clarify the possible return values of `len_utf16`

`char::len_utf16` always return 1 or 2. Clarify this in the docs, in the same way as `char::len_utf8`.
2022-10-16 22:36:06 +02:00
Matthias Krüger
e31ae4f9c0
Rollup merge of #103087 - phimuemue:btreemap_append_doc, r=Mark-Simulacrum
Documentation BTreeMap::append's behavior for already existing keys

`BTreeMap::append` overwrites existing values with new ones. This commit adds explicit documentation for that.
2022-10-16 22:36:05 +02:00
Alex Saveau
727335878d
Support DirEntry metadata calls in miri
Signed-off-by: Alex Saveau <saveau.alexandre@gmail.com>
2022-10-16 12:14:27 -07:00
Sky
a6372525ce
Clarify the possible return values of len_utf16 2022-10-16 11:06:19 -04:00
Ralf Jung
73d655e9c2 remove redundant Send impls for references
also move them next to the trait they are implementing
2022-10-16 11:34:24 +02:00
Ralf Jung
ddd5e983d1 PhantomData: inline a macro that is used only once 2022-10-16 10:37:51 +02:00
Yuki Okushi
166f664037
Rollup merge of #102023 - SUPERCILEX:maybeuninit-transpose, r=scottmcm
Add MaybeUninit array transpose From impls

See discussion in https://github.com/rust-lang/rust/pull/101179 and https://github.com/rust-lang/rust/issues/96097. I believe this solution offers the simplest implementation with minimal future API regret.

`@RalfJung` mind doing a correctness review?
2022-10-16 11:41:12 +09:00
Yuki Okushi
cbc0a73c95
Rollup merge of #101717 - Pointerbender:unsafecell-memory-layout, r=Amanieu
Add documentation about the memory layout of `UnsafeCell<T>`

The documentation for `UnsafeCell<T>` currently does not make any promises about its memory layout. This PR adds this documentation, namely that the memory layout of `UnsafeCell<T>` is the same as the memory layout of its inner `T`.

# Use case
Without this layout promise, the following cast would not be legally possible:

```rust
fn example<T>(ptr: *mut T) -> *const UnsafeCell<T> {
  ptr as *const UnsafeCell<T>
}
```

A use case where this can come up involves FFI. If Rust receives a pointer over a FFI boundary which provides shared read-write access (with some form of custom synchronization), and this pointer is managed by some Rust struct with lifetime `'a`, then it would greatly simplify its (internal) API and safety contract if a `&'a UnsafeCell<T>` can be created from a raw FFI pointer `*mut T`. A lot of safety checks can be done when receiving the pointer for the first time through FFI (non-nullness, alignment, initialize uninit bytes, etc.) and these properties can then be encoded into the `&UnsafeCell<T>` type. Without this documentation guarantee, this is not legal today outside of the standard library.

# Caveats
Casting in the opposite direction is still not valid, even with this documentation change:

```rust
fn example2<T>(ptr: &UnsafeCell<T>) -> &mut T {
  let t = ptr as *const UnsafeCell<T> as *mut T;
  unsafe { &mut *t }
}
```

This is because the only legal way to obtain a mutable pointer to the contents of the shared reference is through [`UnsafeCell::get`](https://doc.rust-lang.org/std/cell/struct.UnsafeCell.html#method.get) and [`UnsafeCell::raw_get`](https://doc.rust-lang.org/std/cell/struct.UnsafeCell.html#method.raw_get). Although there might be a desire to also make this legal at some point in the future, that part is outside the scope of this PR. Also see this relevant [Zulip thread](https://rust-lang.zulipchat.com/#narrow/stream/136281-t-lang.2Fwg-unsafe-code-guidelines/topic/transmuting.20.26.20-.3E.20.26mut).

# Alternatives
Instead of adding a new documentation promise, it's also possible to add a new method to `UnsafeCell<T>` with signature `pub fn from_ptr_bikeshed(ptr: *mut T) -> *const UnsafeCell<T>` which indirectly only allows one-way casting to `*const UnsafeCell<T>`.
2022-10-16 11:41:12 +09:00
Alex Saveau
393434c29e
Add MaybeUninit array transpose impls
Signed-off-by: Alex Saveau <saveau.alexandre@gmail.com>
2022-10-15 15:57:19 -07:00
bors
ddc7fd9837 Auto merge of #100579 - joboet:sync_mutex_everywhere, r=thomcc
std: use `sync::Mutex` for internal statics

Since `sync::Mutex` is now `const`-constructible, it can be used for internal statics, removing the need for `sys_common::StaticMutex`. This adds some extra allocations on platforms which need to box their mutexes (currently SGX and some UNIX), but these will become unnecessary with the lock improvements tracked in #93740.

I changed the program argument implementation on Hermit, it does not need `Mutex` but can use atomics like some UNIX systems (ping `@mkroening` `@stlankes).`
2022-10-15 22:49:30 +00:00
Scott McMurray
5b9a02a87d More slice::partition_point examples 2022-10-15 14:03:56 -07:00
Ryan Lopopolo
95040a70d7
Stabilize duration_checked_float
Tracking issue:

- https://github.com/rust-lang/rust/issues/83400
2022-10-15 12:02:13 -07:00
philipp
4854e37dbc Documentation BTreeMap::append's behavior for already existing keys 2022-10-15 17:47:07 +02:00
Dylan DPC
cbe5e7bc62
Rollup merge of #102773 - joboet:apple_parker, r=thomcc
Use semaphores for thread parking on Apple platforms

Currently we use a mutex-condvar pair for thread parking on Apple systems. Unfortunately, `pthread_cond_timedwait` uses the real-time clock for measuring time, which causes problems when the system time changes. The parking implementation in this PR uses a semaphore instead, which measures monotonic time by default, avoiding these issues. As a further benefit, this has the potential to improve performance a bit, since `unpark` does not need to wait for a lock to be released.

Since the Mach semaphores are poorly documented (I could not find availability or stability guarantees for instance), this uses a [dispatch semaphore](https://developer.apple.com/documentation/dispatch/dispatch_semaphore?language=objc) instead. While it adds a layer of indirection (it uses Mach semaphores internally), the overhead is probably negligible.

Tested on macOS 12.5.

r? ``````@thomcc``````
2022-10-15 15:45:30 +05:30
bors
8154955321 Auto merge of #98033 - joshtriplett:is-terminal-fd-handle, r=thomcc
Add `IsTerminal` trait to determine if a descriptor or handle is a terminal

The UNIX implementation uses `isatty`. The Windows implementation uses
the same logic the `atty` crate uses, including the hack needed to
detect msys terminals.

Implement this trait for `Stdin`/`Stdout`/`Stderr`/`File` on all
platforms. On Unix, implement it for `BorrowedFd`/`OwnedFd`. On Windows,
implement it for `BorrowedHandle`/`OwnedHandle`.

Based on https://github.com/rust-lang/rust/pull/91121

Co-authored-by: Matt Wilkinson <mattwilki17@gmail.com>
2022-10-15 01:42:28 +00:00
Josh Triplett
97d438cd31 Use Align8 to avoid misalignment if the allocator or Vec doesn't align allocations 2022-10-15 00:35:39 +01:00
Josh Triplett
6a79da9ab7 Rewrite FILE_NAME_INFO handling to avoid enlarging slice reference
Rather than referencing a slice's pointer and then creating a new slice
with a longer length, offset from the base structure pointer instead.
This makes some choices of Rust semantics happier.
2022-10-15 00:35:39 +01:00
Josh Triplett
e25fe564d1 Make is_terminal fail fast if a process has no console at all
If a process has no console, it'll have NULL in place of a console
handle, so return early with `false` in that case without making any OS
calls.
2022-10-15 00:35:38 +01:00
Josh Triplett
326ef470a8 Add IsTerminal trait to determine if a descriptor or handle is a terminal
The UNIX and WASI implementations use `isatty`. The Windows
implementation uses the same logic the `atty` crate uses, including the
hack needed to detect msys terminals.

Implement this trait for `File` and for `Stdin`/`Stdout`/`Stderr` and
their locked counterparts on all platforms. On UNIX and WASI, implement
it for `BorrowedFd`/`OwnedFd`. On Windows, implement it for
`BorrowedHandle`/`OwnedHandle`.

Based on https://github.com/rust-lang/rust/pull/91121

Co-authored-by: Matt Wilkinson <mattwilki17@gmail.com>
2022-10-15 00:35:38 +01:00
bors
8147e6e427 Auto merge of #103069 - matthiaskrgr:rollup-xxsx6sk, r=matthiaskrgr
Rollup of 9 pull requests

Successful merges:

 - #102092 (refactor: use grep -E/-F instead of fgrep/egrep)
 - #102781 (Improved documentation for `std::io::Error`)
 - #103017 (Avoid dropping TLS Key on sgx)
 - #103039 (checktools: fix comments)
 - #103045 (Remove leading newlines from integer primitive doc examples)
 - #103047 (Update browser-ui-test version to fix some flaky tests)
 - #103054 (Clean up rust-logo rustdoc GUI test)
 - #103059 (Fix `Duration::{try_,}from_secs_f{32,64}(-0.0)`)
 - #103067 (More alphabetical sorting)

Failed merges:

r? `@ghost`
`@rustbot` modify labels: rollup
2022-10-14 22:56:53 +00:00
Matthias Krüger
a96f1a8a1e
Rollup merge of #103067 - Nilstrieb:tidy-likes-the-alphabet, r=jackh726
More alphabetical sorting

Sort and enforce a few more things. The biggest change here is sorting all target features.
2022-10-14 23:43:46 +02:00
Matthias Krüger
03a521b4fe
Rollup merge of #103059 - beetrees:duration-from-negative-zero, r=thomcc
Fix `Duration::{try_,}from_secs_f{32,64}(-0.0)`

Make `Duration::{try_,}from_secs_f{32,64}(-0.0)` return `Duration::ZERO` (as they did before #90247) instead of erroring/panicking.

I'll update this PR to remove the `#![feature(duration_checked_float)]` if #102271 is merged before this PR.

Tracking issue for `try_from_secs_f{32,64}`: #83400
2022-10-14 23:43:46 +02:00
Matthias Krüger
1a5d8a5c59
Rollup merge of #103045 - lukas-code:blank-lines, r=GuillaumeGomez
Remove leading newlines from integer primitive doc examples

fixes https://github.com/rust-lang/rust/issues/103043

```@rustbot``` label +A-docs
2022-10-14 23:43:44 +02:00
Matthias Krüger
d47b755683
Rollup merge of #103017 - fortanix:raoul/sgx_tls_fix, r=ChrisDenton
Avoid dropping TLS Key on sgx

#102655 reenabled dropping thread local `Key` on every platform ([library/std/src/sys_common/thread_local_key.rs](fa0ca783f8 (diff-5cb9acf9e243f35c975fa9fbac4885519dc104626bc03610dfa7a20bc79641ceL237-R215))). That's causing problems at least for sgx.

cc: `@jethrogb` `@ChrisDenton`
2022-10-14 23:43:43 +02:00
Matthias Krüger
fbb0c31544
Rollup merge of #102781 - StackOverflowExcept1on:master, r=joshtriplett
Improved documentation for `std::io::Error`
2022-10-14 23:43:43 +02:00
bors
bf15a9e526 Auto merge of #101030 - woppopo:const_location, r=scottmcm
Constify `Location` methods

Tracking issue: #102911

Example: https://play.rust-lang.org/?version=nightly&mode=debug&edition=2021&gist=4789884c2f16ec4fb0e0405d86b794f5
2022-10-14 20:15:51 +00:00
nils
b00cb04037
Sort target features alphabetically 2022-10-14 22:01:18 +02:00
nils
3c0062641d
Add some tidy-alphabetical 2022-10-14 21:18:03 +02:00
bors
5819f419a7 Auto merge of #102783 - RalfJung:tls, r=thomcc
sync thread_local key conditions exactly with what the macro uses

This makes the `cfg` in `mod.rs` syntactically the same as those in `local.rs`.

I don't think this should actually change anything, but seems better to be consistent?
I looked into this due to https://github.com/rust-lang/rust/issues/102549, but this PR would make it *less* likely that `__OsLocalKeyInner` is going to get provided, so this cannot help with that issue.

r? `@thomcc`
2022-10-14 16:43:46 +00:00
Raoul Strackx
c46185bea0 Bugfix: keep TLS data in sync 2022-10-14 17:07:18 +02:00
beetrees
c9948f5c5f
Fix Duration::{try_,}from_secs_f{32,64}(-0.0) 2022-10-14 16:07:09 +01:00
bors
ee1c3b385b Auto merge of #102529 - colinba:master, r=joshtriplett
Detect and reject out-of-range integers in format string literals

Until now out-of-range integers in format string literals were silently ignored. They wrapped around to zero at usize::MAX, producing unexpected results.

When using debug builds of rustc, such integers in format string literals even cause an 'attempt to add with overflow' panic in rustc.

Fix this by producing an error diagnostic for integers in format string literals which do not fit into usize.

Fixes #102528
2022-10-14 13:41:40 +00:00
Josh Triplett
f95e853222
Tweak grammar 2022-10-14 12:17:07 +01:00
Dylan DPC
77064b7f0a
Rollup merge of #103018 - Rageking8:more-dupe-word-typos, r=TaKO8Ki
More dupe word typos

I only picked those changes (from the regex search) that I am pretty certain doesn't change meaning and is just a typo fix. Do correct me if any fix is undesirable and I can revert those. Thanks.
2022-10-14 16:19:15 +05:30
Dylan DPC
b03bece6f3
Rollup merge of #102847 - joshtriplett:bugfix-impl-fd-traits-for-io-types, r=m-ou-se
impl AsFd and AsRawFd for io::{Stdin, Stdout, Stderr}, not the sys versions

https://github.com/rust-lang/rust/pull/100892 implemented AsFd for the
sys versions, rather than for the public types. Change the
implementations to apply to the public types.
2022-10-14 16:19:12 +05:30
Lukas Markeffsky
b8bb40664c remove leading newlines from integer primitive doc examples 2022-10-14 12:14:29 +02:00
Rageking8
7122abaddf more dupe word typos 2022-10-14 12:57:56 +08:00
bors
6b3ede3f7b Auto merge of #103009 - Dylan-DPC:rollup-9c2tng6, r=Dylan-DPC
Rollup of 6 pull requests

Successful merges:

 - #102765 (Suggest `==` to the first expr which has `ExprKind::Assign` kind)
 - #102854 (openbsd: don't reallocate a guard page on the stack.)
 - #102904 (Print return-position `impl Trait` in trait verbosely if `-Zverbose`)
 - #102947 (Sort elaborated existential predicates in `object_ty_for_trait`)
 - #102956 (Use `full_res` instead of `expect_full_res`)
 - #102999 (Delay `is_intrinsic` query until after we've determined the callee is a function)

Failed merges:

r? `@ghost`
`@rustbot` modify labels: rollup
2022-10-13 14:59:39 +00:00
Dylan DPC
376c81c94a
Rollup merge of #102854 - semarie:openbsd-immutablestack, r=m-ou-se
openbsd: don't reallocate a guard page on the stack.

the kernel currently enforce that a stack is immutable. calling mmap(2) or  mprotect(2) to change it will result in EPERM, which generate a panic!().

so just do like for Linux, and trust the kernel to do the right thing.
2022-10-13 18:19:19 +05:30
Ralf Jung
594838d132 smarter way to avoid 'unused' warning when building for tests 2022-10-13 14:09:08 +02:00
Ralf Jung
600ac6959a sync thread_local key conditions exactly with what the macro uses 2022-10-13 14:09:08 +02:00
bors
4891d57f7a Auto merge of #102919 - luojia65:update-stdarch, r=Amanieu
library: update stdarch submodule

It has been one month since we update `stdarch`  submodule into main branch Rust, it includes various fixes in code and more neat documents. This pull request also adds missing features to ensure we can build latest stdarch submodule.

The documents after this pull request:
<details>

![图片](https://user-images.githubusercontent.com/40385009/195123337-a6c4cfaa-a7b9-4574-b524-c43683e6540c.png)
</details>

Comparing to current nightly:
<details>

![图片](https://user-images.githubusercontent.com/40385009/195123430-e047cff1-a925-4d2d-ae1c-da9769383a9c.png)
</details>

r? `@Amanieu`
2022-10-13 12:03:46 +00:00
joboet
2d2c9e4493
std: use sync::Mutex for internal statics 2022-10-13 12:55:14 +02:00
bors
fa0ca783f8 Auto merge of #102655 - joboet:windows_tls_opt, r=ChrisDenton
Optimize TLS on Windows

This implements the suggestion in the current TLS code to embed the linked list of destructors in the `StaticKey` structure to save allocations. Additionally, locking is avoided when no destructor needs to be run. By using one Windows-provided `Once` per key instead of a global lock, locking is more finely-grained (this unblocks #100579).
2022-10-13 06:49:29 +00:00
Tomoaki Kawada
76bec177bc kmc-solid: Handle errors returned by SOLID_FS_ReadDir 2022-10-13 15:10:23 +09:00
bors
3cf5fc58d5 Auto merge of #102995 - JohnTitor:rollup-yomkwge, r=JohnTitor
Rollup of 7 pull requests

Successful merges:

 - #102641 (Support casting boxes to dyn*)
 - #102836 (rustc_target: Fix json target specs using LLD linker flavors in link args)
 - #102949 (should-skip-this: add missing backslash)
 - #102967 (Add test for issue 102964)
 - #102971 (tidy: error if a lang feature is already present)
 - #102974 (Fix small word dupe typos)
 - #102980 (rustdoc: merge separate `.item-info` CSS)

Failed merges:

r? `@ghost`
`@rustbot` modify labels: rollup
2022-10-13 03:33:40 +00:00
luojia65
59fea7ecf4 library: update stdarch submodule
add feature target_feature_11 and riscv_target_feature
2022-10-13 09:41:16 +08:00
Yuki Okushi
0ace46f98c
Rollup merge of #102974 - Rageking8:fix-small-word-dupe-typos, r=JohnTitor
Fix small word dupe typos
2022-10-13 09:41:27 +09:00
bors
2a9217601c Auto merge of #102372 - abrown:issue-102157, r=thomcc
Allow compiling the `wasm32-wasi` std library with atomics

The issue #102157 demonstrates how currently the `-Z build-std` option will fail when re-compiling the standard library with `RUSTFLAGS` like `RUSTFLAGS="-C target-feature=+atomics,+bulk-memory -C link-args=--shared-memory"`. This change attempts to resolve those build issues by depending on the the WebAssembly `futex` module and providing an implementation for `env_lock`. Fixes #102157.
2022-10-13 00:37:28 +00:00
Pointerbender
ddd119b2fe expand documentation on type conversion w.r.t. UnsafeCell 2022-10-12 23:34:13 +02:00
Rageking8
d1982bd0af fix small word dupe typos 2022-10-13 00:53:46 +08:00
bors
538f118da1 Auto merge of #102732 - RalfJung:assert_unsafe_precondition2, r=bjorn3
nicer errors from assert_unsafe_precondition

This makes the errors shown by cargo-careful nicer, and since `panic_no_unwind` is `nounwind noreturn` it hopefully doesn't have bad codegen impact. Thanks to `@bjorn3` for the hint!

Would be nice if we could somehow supply our own (static) message to print, currently it always prints `panic in a function that cannot unwind`. But still, this is better than before.
2022-10-12 14:39:43 +00:00
Markus Reiter
36dbb07daf
Update docs for CStr::from_ptr. 2022-10-12 13:46:20 +02:00
Markus Reiter
328f81713c
Make CStr::from_ptr const. 2022-10-12 13:01:30 +02:00
bors
50f6d337c6 Auto merge of #102460 - flba-eb:fix_85261_prevent_alloc_after_fork, r=thomcc
Prevent UB in child process after calling libc::fork

After calling libc::fork, the child process tried to access a TLS variable when processing a panic. This caused a memory allocation which is UB in the child.
To prevent this from happening, the panic handler will not access the TLS variable in case `panic::always_abort` was called before.

Fixes #85261 (not only on Android systems, but also on Linux/QNX with TLS disabled, see issue for more details)

Main drawbacks of this fix:
* Panic messages can incorrectly omit `core::panic::PanicInfo` struct in case several panics (of multiple threads) occur at the same time. The handler cannot distinguish between multiple panics in different threads or recursive ones in the same thread, but the message will contain a hint about the uncertainty.
* `panic_count::increase()` will be a bit slower as it has an additional `if`, but this should be irrelevant as it is only called in case of a panic.
2022-10-12 10:51:31 +00:00
bors
e6ce5627a9 Auto merge of #102948 - Dylan-DPC:rollup-j8h74rb, r=Dylan-DPC
Rollup of 8 pull requests

Successful merges:

 - #102110 (Migrate rustc_passes diagnostics)
 - #102187 (Use correct location for type tests in promoted constants)
 - #102239 (Move style guide to rust-lang/rust)
 - #102578 (Panic for invalid arguments of `{integer primitive}::ilog{,2,10}` in all modes)
 - #102811 (Use memset to initialize readbuf)
 - #102890 (Check representability in adt_sized_constraint)
 - #102913 (unify `IsPattern` and `IsImport` enum in `show_candidates`)
 - #102924 (rustdoc: remove unused classes from sidebar links)

Failed merges:

r? `@ghost`
`@rustbot` modify labels: rollup
2022-10-12 06:57:24 +00:00
Dylan DPC
658169b7db
Rollup merge of #102811 - the8472:bufread-memset, r=m-ou-se
Use memset to initialize readbuf

The write loop was found to be slow in #102727

The proper fix is in #102760 but this might still help debug builds and code running under miri by using the write_bytes intrinsic instead of writing one byte at a time.
2022-10-12 11:11:25 +05:30
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
bors
2b91cbe2d4 Auto merge of #102692 - nnethercote:TokenStreamBuilder, r=Aaron1011
Remove `TokenStreamBuilder`

`TokenStreamBuilder` is used to combine multiple token streams. It can be removed, leaving the code a little simpler and a little faster.

r? `@Aaron1011`
2022-10-12 03:46:16 +00:00
Ralf Jung
38c78a9ac1 reorder panicking.rs to put main entry points at the top 2022-10-11 22:47:31 +02:00
Ralf Jung
b61e742a39 use panic_fmt_nounwind for assert_unsafe_precondition 2022-10-11 22:47:31 +02:00
Ralf Jung
66282cb47d add panic_fmt_nounwind for panicing without unwinding, and use it for panic_no_unwind 2022-10-11 22:47:31 +02:00
Ralf Jung
2b50cd1877 rename rustc_allocator_nounwind to rustc_nounwind 2022-10-11 22:47:31 +02:00
Andrew Brown
95b0b2d349 fix: return type of single-threaded dummy lock must be droppable 2022-10-11 11:42:44 -07:00
Matthias Krüger
ccde95f489
Rollup merge of #102869 - azdavis:master, r=joshtriplett
Add basename and dirname aliases

Users might be used to the POSIX names of these functions. In fact, here's a [blog post][1] about this very thing.

[1]: https://boinkor.net/2019/07/basename-and-dirname-in-rust/
2022-10-11 18:59:49 +02:00
Matthias Krüger
1b1223df9f
Rollup merge of #102685 - nbdd0121:unwind, r=m-ou-se
Interpret EH actions properly

The EH actions stored in the LSDA follows the format of GCC except table (even for LLVM-generated code). An missing action in the table is the encoding for `Terminate`, see https://github.com/gcc-mirror/gcc/blob/master/libstdc%2B%2B-v3/libsupc%2B%2B/eh_personality.cc#L522-L526.

The currently code interprets it as `None`, as a workaround for #35011, an issue that seems to occur in LLVM 3.7 and not after 3.9. These are very old versions of LLVM and we don't support them anymore, so remove this workaround and interpret them properly.

Note that LLVM currently does not emit any `Terminate` actions, but GCC does. Although GCC backend currently doesn't do unwinding, removing it preemptively would prevent future developers from wasting time to figure out what's wrong.

``@rustbot`` label: +T-compiler
2022-10-11 18:59:49 +02:00
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
51320b3a16
Rollup merge of #102227 - devnexen:solarish_get_path, r=m-ou-se
fs::get_path solarish version.

similar to linux, albeit there is no /proc/self notion on solaris
 based system thus flattening the difference for simplification sake.
2022-10-11 18:59:47 +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
Matthias Krüger
cadb37a8c7
Rollup merge of #101727 - est31:stabilize_map_first_last, r=m-ou-se
Stabilize map_first_last

Stabilizes the following functions:

```Rust
impl<T> BTreeSet<T> {
    pub fn first(&self) -> Option<&T> where T: Ord;
    pub fn last(&self) -> Option<&T> where T: Ord;
    pub fn pop_first(&mut self) -> Option<T> where T: Ord;
    pub fn pop_last(&mut self) -> Option<T> where T: Ord;
}

impl<K, V> BTreeMap<K, V> {
    pub fn first_key_value(&self) -> Option<(&K, &V)> where K: Ord;
    pub fn last_key_value(&self) -> Option<(&K, &V)> where K: Ord;
    pub fn first_entry(&mut self) -> Option<OccupiedEntry<'_, K, V>> where K: Ord;
    pub fn last_entry(&mut self) -> Option<OccupiedEntry<'_, K, V>> where K: Ord;
    pub fn pop_first(&mut self) -> Option<(K, V)> where K: Ord;
    pub fn pop_last(&mut self) -> Option<(K, V)> where K: Ord;
}
```

Closes #62924

~~Blocked on the [FCP](https://github.com/rust-lang/rust/issues/62924#issuecomment-1179489929) finishing.~~ Edit: It finished!
2022-10-11 18:59:46 +02:00
Yuki Okushi
b380518691
Rollup merge of #102625 - Rageking8:fix-backtrace-small-typo, r=m-ou-se
fix backtrace small typo
2022-10-11 18:37:54 +09:00
Yuki Okushi
919d6bf446
Rollup merge of #102589 - RalfJung:scoped-threads-dangling, r=m-ou-se
scoped threads: pass closure through MaybeUninit to avoid invalid dangling references

The `main` function defined here looks roughly like this, if it were written as a more explicit stand-alone function:
```rust
// Not showing all the `'lifetime` tracking, the point is that
// this closure might live shorter than `thread`.
fn thread(control: ..., closure: impl FnOnce() + 'lifetime) {
    closure();
    control.signal_done();
    // A lot of time can pass here.
}
```
Note that `thread` continues to run even after `signal_done`! Now consider what happens if the `closure` captures a reference of lifetime `'lifetime`:
- The type of `closure` is a struct (the implicit unnameable closure type) with a `&'lifetime mut T` field. References passed to a function are marked with `dereferenceable`, which is LLVM speak for *this reference will remain live for the entire duration of this function*.
- The closure runs, `signal_done` runs. Then -- potentially -- this thread gets scheduled away and the main thread runs, seeing the signal and returning to the user. Now `'lifetime` ends and the memory the reference points to might be deallocated.
- Now we have UB! The reference that as passed to `thread` with the promise of remaining live for the entire duration of the function, actually got deallocated while the function still runs. Oops.

Long-term I think we should be able to use `ManuallyDrop` to fix this without `unsafe`, or maybe a new `MaybeDangling` type. I am working on an RFC for that. But in the mean time it'd be nice to fix this so that Miri with `-Zmiri-retag-fields` (which is needed for "full enforcement" of all the LLVM flags we generate) stops erroring on scoped threads.

Fixes https://github.com/rust-lang/rust/issues/101983
r? `@m-ou-se`
2022-10-11 18:37:54 +09:00
Yuki Okushi
e0954cadc8
Rollup merge of #102412 - joboet:dont_panic, r=m-ou-se
Never panic in `thread::park` and `thread::park_timeout`

fixes #102398

`@rustbot` label +T-libs +T-libs-api
2022-10-11 18:37:53 +09:00
Yuki Okushi
387df55f26
Rollup merge of #102277 - mgeisler:rwlock, r=m-ou-se
Consistently write `RwLock`

Before the documentation sometimes referred to an "rwlock" and sometimes to "`RwLock`".
2022-10-11 18:37:52 +09: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
woppopo
a53e3acca9 Change tracking issue from #76156 to #102911 2022-10-11 06:40:37 +00:00
Ariel Davis
d1762d7a96 Do not alias for fs 2022-10-10 17:05:59 -07:00
bors
a6b7274a46 Auto merge of #102596 - scottmcm:option-bool-calloc, r=Mark-Simulacrum
Do the `calloc` optimization for `Option<bool>`

Inspired by <https://old.reddit.com/r/rust/comments/xtiqj8/why_is_this_functional_version_faster_than_my_for/iqqy37b/>.
2022-10-10 18:42:40 +00:00
Andrew Brown
9530ba0fe2 Implement env_lock with RwLock
Copying the approach of the Unix target, this change uses the standard
`RwLock` to protect against concurrent access of libc's environment.
This locking is only enabled when WebAssembly's `atomics` feature is
also enabled.
2022-10-10 09:01:42 -07:00
Andrew Brown
da638b3a9f Allow compiling the wasm32-wasi std library with atomics
The issue #102157 demonstrates how currently the `-Z build-std` option
will fail when re-compiling the standard library with `RUSTFLAGS` like
`RUSTFLAGS="-C target-feature=+atomics,+bulk-memory -C
link-args=--shared-memory"`. This change attempts to resolve those build
issues by depending on the the WebAssembly `futex` module and providing
an implementation for `env_lock`. Fixes #102157.
2022-10-10 08:58:09 -07:00
Josh Triplett
ef68327de7 Consolidate AsFd instances for stdio types into library/std/src/os/fd/owned.rs 2022-10-10 14:47:22 +01: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
302bf31826
Rollup merge of #102794 - dtolnay:termination, r=thomcc
Make tests capture the error printed by a Result return

An error returned by tests previously would get written directly to stderr, instead of to the capture buffer set up by the test harness. This PR makes it write to the capture buffer so that it can be integrated as part of the test output by build tools such as `buck test`, since being able to read the error message returned by a test is pretty critical to debugging why the test failed.

<br>

**Before:**

```rust
// tests/test.rs

#[test]
fn test() -> Result<(), &'static str> {
    println!("STDOUT");
    eprintln!("STDERR");
    Err("RESULT")
}
```

```console
$ cargo build --test test
$ target/debug/deps/test-???????????????? -Z unstable-options --format=json
{ "type": "suite", "event": "started", "test_count": 1 }
{ "type": "test", "event": "started", "name": "test" }
Error: "RESULT"
{ "type": "test", "name": "test", "event": "failed", "stdout": "STDOUT\nSTDERR\n" }
{ "type": "suite", "event": "failed", "passed": 0, "failed": 1, "ignored": 0, "measured": 0, "filtered_out": 0, "exec_time": 0.00040313 }
```

**After:**

```console
$ target/debug/deps/test-???????????????? -Z unstable-options --format=json
{ "type": "suite", "event": "started", "test_count": 1 }
{ "type": "test", "event": "started", "name": "test" }
{ "type": "test", "name": "test", "event": "failed", "stdout": "STDOUT\nSTDERR\nError: \"RESULT\"" }
{ "type": "suite", "event": "failed", "passed": 0, "failed": 1, "ignored": 0, "measured": 0, "filtered_out": 0, "exec_time": 0.000261894 }
```
2022-10-10 13:43:41 +05:30
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
Ariel Davis
61519b8cf1 Add basename and dirname aliases 2022-10-09 21:44:44 -07:00
Yuki Okushi
6d35efe03a
Rollup merge of #102862 - scottmcm:more-alignment-traits, r=thomcc
From<Alignment> for usize & NonZeroUsize

Since you mentioned these two in https://github.com/rust-lang/rust/pull/102072#issuecomment-1272390033,
r? ``@thomcc``

Tracking Issue: https://github.com/rust-lang/rust/issues/102070
2022-10-10 10:23:06 +09:00
Scott McMurray
0718aeceb3 From<Alignment> for usize & NonZeroUsize 2022-10-09 15:44:49 -07:00
bors
1a7c203e7f Auto merge of #89123 - the8472:push_in_capacity, r=amanieu
add Vec::push_within_capacity - fallible, does not allocate

This method can serve several purposes. It

* is fallible
* guarantees that items in Vec aren't moved
* allows loops that do `reserve` and `push` separately to avoid pulling in the allocation machinery a second time in the `push` part which should make things easier on the optimizer
* eases the path towards `ArrayVec` a bit since - compared to `push()` - there are fewer questions around how it should be implemented

I haven't named it `try_push` because that should probably occupy a middle ground that will still try to reserve and only return an error in the unlikely OOM case.

resolves #84649
2022-10-09 21:02:33 +00:00
Pointerbender
9c37c801ad expand documentation on type conversion w.r.t. UnsafeCell 2022-10-09 22:32:23 +02:00
bors
81f3919303 Auto merge of #102850 - JohnTitor:rollup-lze1w03, r=JohnTitor
Rollup of 8 pull requests

Successful merges:

 - #101118 (fs::get_mode enable getting the data via fcntl/F_GETFL on major BSD)
 - #102072 (Add `ptr::Alignment` type)
 - #102799 (rustdoc: remove hover gap in file picker)
 - #102820 (Show let-else suggestion on stable.)
 - #102829 (rename `ImplItemKind::TyAlias` to `ImplItemKind::Type`)
 - #102831 (Don't use unnormalized type in `Ty::fn_sig` call in rustdoc `clean_middle_ty`)
 - #102834 (Remove unnecessary `lift`/`lift_to_tcx` calls from rustdoc)
 - #102838 (remove cfg(bootstrap) from Miri)

Failed merges:

r? `@ghost`
`@rustbot` modify labels: rollup
2022-10-09 18:15:26 +00:00
Josh Triplett
88bb4e4bda impl AsFd for io::{Stdin, Stdout, Stderr}, not the sys versions
https://github.com/rust-lang/rust/pull/100892 implemented AsFd for the
sys versions, rather than for the public types. Change the
implementations to apply to the public types.
2022-10-09 19:01:56 +01:00
Sébastien Marie
b3c21efa8a openbsd: don't reallocate a guard page on the stack.
the kernel currently enforce that a stack is immutable. calling mmap(2) or 
mprotect(2) to change it will result in EPERM, which generate a panic!().

so just do like for Linux, and trust the kernel to do the right thing.
2022-10-09 16:45:04 +00: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
Yuki Okushi
d0f1cf5de7
Rollup merge of #101118 - devnexen:fs_getmode_bsd, r=Mark-Simulacrum
fs::get_mode enable getting the data via fcntl/F_GETFL on major BSD

supporting this flag.
2022-10-10 00:09:39 +09:00
bors
1b225414f3 Auto merge of #93668 - SUPERCILEX:path_alloc, r=joshtriplett
Reduce CString allocations in std as much as possible

Currently, every operation involving paths in `fs` allocates memory to hold the path before sending it through the syscall. This PR instead uses a stack allocation (chosen size is somewhat arbitrary) when the path is short before falling back to heap allocations for long paths.

Benchmarks show that the stack allocation is ~2x faster for short paths:

```
test sys::unix::fd::tests::bench_heap_path_alloc                  ... bench:          34 ns/iter (+/- 2)
test sys::unix::fd::tests::bench_stack_path_alloc                 ... bench:          15 ns/iter (+/- 1)
```

For long paths, I couldn't find any measurable difference.

---

I'd be surprised if I was the first to think of this, so I didn't fully flush out the PR. If this change is desirable, I'll make use of `run_with_cstr` across all platforms in every fs method (currently just unix open for testing). I also added an `impl From<FromBytesWithNulError>` which is presumably a no-no (or at least needs to be done in another PR).

---

Also see https://github.com/nix-rust/nix/pull/1655 with a bunch of discussion where I'm doing something similar.
2022-10-09 15:07:10 +00: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
joboet
d457801354
std: optimize TLS on Windows 2022-10-08 20:19:21 +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
The 8472
b9e4a1cf26 use memset to initialize a readbuf 2022-10-08 14:40:19 +02:00
woppopo
f0b8167a4e Fix test (location_const_file) 2022-10-08 11:48:53 +00:00
joboet
c320ab98ff
std: do not use dispatch semaphore under miri (yet) 2022-10-08 09:12:06 +02:00
joboet
b4c8a7b952
std: remove unused linker attribute 2022-10-08 09:07:28 +02:00
bors
a688a0305f Auto merge of #99505 - joboet:futex_once, r=thomcc
std: use futex in `Once`

Now that we have efficient locks, let's optimize the rest of `sync` as well. This PR adds a futex-based implementation for `Once`, which drastically simplifies the implementation compared to the generic version, which is provided as fallback for platforms without futex (Windows only supports them on newer versions, so it uses the fallback for now).

Instead of storing a linked list of waiters, the new implementation adds another state (`QUEUED`), which is set when there are waiting threads. These now use `futex_wait` on that state and are woken by the running thread when it finishes and notices the `QUEUED` state, thereby avoiding unnecessary calls to `futex_wake_all`.
2022-10-08 03:50:07 +00:00
David Tolnay
293f662ca9
Make tests capture the error printed by a Result return 2022-10-07 18:25:32 -07: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
fe4200365e
Rollup merge of #102760 - saethlin:dont-reinit-buffer, r=Mark-Simulacrum
Avoid repeated re-initialization of the BufReader buffer

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

We accidentally removed this in https://github.com/rust-lang/rust/pull/98748. It looks so redundant. But it isn't.

The default `Read::read_buf` will defensively initialize the whole buffer, if any of it is indicated to be uninitialized. In uses where reads from the wrapped `Read` impl completely fill the `BufReader`, `initialized` and `filled` are the same, and this extra member isn't required. But in the reported issue, the `BufReader` wraps a `Read` impl which will _never_ fill the whole buffer. So the default `Read::read_buf` implementation repeatedly re-initializes the extra space in the buffer.

This adds back the extra `initialized` member, which ensures that the default `Read::read_buf` only zero-initialized the buffer once, and I've tried to add a comment which explains this whole situation.
2022-10-07 22:05:31 +05:30
Dylan DPC
e461e94165
Rollup merge of #102475 - RalfJung:unsafe, r=dtolnay
unsafe keyword: trait examples and unsafe_op_in_unsafe_fn update

Having a safe `fn` in an `unsafe trait` vs an `unsafe fn` in a safe `trait` are pretty different situations, but the distinction is subtle and can confuse even seasoned Rust developers. So let's have explicit examples of both. I also removed the existing `unsafe trait` example since it was rather strange.

Also the `unsafe_op_in_unsafe_fn` lint can help disentangle the two sides of `unsafe`, so update the docs to account for that.
2022-10-07 22:05:30 +05:30
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
c30dcff97a review feedback 2022-10-07 15:21:47 +02:00
StackOverflowExcept1on
4cf30c0022
Improved documentation for std::io::Error 2022-10-07 15:42:05 +03:00
Ralf Jung
6f6433428f add a few more assert_unsafe_precondition 2022-10-07 14:35:12 +02:00
joboet
5d0211dc03
std: use futex in Once 2022-10-07 12:12:36 +02:00
Thom Chiovoloni
2618f7ae04
Don't needless link to libresolv on Darwin in libstd 2022-10-06 20:35:58 -07:00
Ben Kimock
95ae993bd8 Avoid defensive re-initialization of the BufReader buffer 2022-10-06 23:31:57 -04:00
joboet
0ad4dd494a
std: add thread parking tests 2022-10-06 22:46:47 +02:00
joboet
99182dd805
std: use semaphore for thread parking on Apple platforms 2022-10-06 22:46:15 +02:00
bors
0ca356586f Auto merge of #102741 - matthiaskrgr:rollup-63no5tz, r=matthiaskrgr
Rollup of 5 pull requests

Successful merges:

 - #98496 (make `compare_const_impl` a query and use it in `instance.rs`)
 - #102680 (Fix overconstrained Send impls in btree internals)
 - #102718 (Fix `opaque_hidden_inferred_bound` lint ICE)
 - #102725 (Remove `-Ztime`)
 - #102736 (Migrate search input color to CSS variable)

Failed merges:

r? `@ghost`
`@rustbot` modify labels: rollup
2022-10-06 19:55:48 +00:00
Matthias Krüger
e77e0200ae
Rollup merge of #102680 - dtolnay:btreesend, r=thomcc
Fix overconstrained Send impls in btree internals

Fixes https://github.com/dtolnay/async-trait/issues/215.

Minimal repro:

```rust
use std::collections::btree_map::Iter;

fn require_send<T: Send>(_: T) {}

fn main() {
    require_send(async {
        let _iter = None::<Iter<(), &()>>;
        async {}.await;
    });
}
```

```console
error: higher-ranked lifetime error
 --> src/main.rs:6:5
  |
6 | /     require_send(async {
7 | |         let _iter = None::<Iter<(), &()>>;
8 | |         async {}.await;
9 | |     });
  | |______^
  |
  = note: could not prove `impl Future<Output = ()>: Send`
```

Not-quite-so-minimal repro:

```rust
use std::collections::BTreeMap;
use std::future::Future;

fn spawn<T: Future + Send>(_: T) {}

async fn f() {
    let map = BTreeMap::<u32, Box<dyn Send + Sync>>::new();
    for _ in &map {
        async {}.await;
    }
}

fn main() {
    spawn(f());
}
```

```console
error: higher-ranked lifetime error
  --> src/main.rs:14:5
   |
14 |     spawn(f());
   |     ^^^^^^^^^^
   |
   = note: could not prove `impl Future<Output = ()>: Send`
```

I am not familiar with the btree internals, but it seems clear to me that the `async fn f` above should return a Send future. Using HashMap instead of BTreeMap in that code makes it already return a Send future.

The _"higher-ranked lifetime error"_ message may be a regression in Rust 1.63. Using older compilers the error message was more detailed:

```console
error: implementation of `Send` is not general enough
  --> src/main.rs:14:5
   |
14 |     spawn(f());
   |     ^^^^^ implementation of `Send` is not general enough
   |
   = note: `Send` would have to be implemented for the type `alloc::collections::btree::node::NodeRef<alloc::collections::btree::node::marker::Immut<'0>, u32, Box<(dyn Send + Sync + '1)>, alloc::collections::btree::node::marker::LeafOrInternal>`, for any two lifetimes `'0` and `'1`...
   = note: ...but `Send` is actually implemented for the type `alloc::collections::btree::node::NodeRef<alloc::collections::btree::node::marker::Immut<'2>, u32, Box<dyn Send + Sync>, alloc::collections::btree::node::marker::LeafOrInternal>`, for some specific lifetime `'2`

error: implementation of `Send` is not general enough
  --> src/main.rs:14:5
   |
14 |     spawn(f());
   |     ^^^^^ implementation of `Send` is not general enough
   |
   = note: `Send` would have to be implemented for the type `alloc::collections::btree::node::NodeRef<alloc::collections::btree::node::marker::Immut<'0>, u32, Box<(dyn Send + Sync + '1)>, alloc::collections::btree::node::marker::Leaf>`, for any two lifetimes `'0` and `'1`...
   = note: ...but `Send` is actually implemented for the type `alloc::collections::btree::node::NodeRef<alloc::collections::btree::node::marker::Immut<'2>, u32, Box<dyn Send + Sync>, alloc::collections::btree::node::marker::Leaf>`, for some specific lifetime `'2`
```
2022-10-06 16:29:44 +02:00
bors
2d46584fae Auto merge of #99497 - vladimir-ea:stdlib_os_api_watchos, r=thomcc
Standard library OS support for Apple WatchOS

This PR was split from https://github.com/rust-lang/rust/pull/98101
2022-10-06 12:14:21 +00:00
Ralf Jung
17d78c4ef9 poll_fn and Unpin: fix pinning 2022-10-06 13:51:10 +02:00
Florian Bartels
9a97cc8ca5 Fix whitespace 2022-10-06 09:55:32 +02:00
Florian Bartels
8e70c82f57 Prevent UB in child process after calling libc::fork
After calling libc::fork, the child process tried to access
a TLS variable when processing a panic. This caused
a memory allocation which is UB in the child.
To prevent this from happening, the panic handler will
not access the TLS variable in case `panic::always_abort`
was called before.
2022-10-06 09:02:22 +02:00
Matthias Krüger
6d8cea63db
Rollup merge of #102693 - BlackHoleFox:revert-apple-entropy-changes, r=thomcc
Revert "Use getentropy when possible on all Apple platforms"

Per https://github.com/rust-lang/rust/issues/102643, This reverts commit 3fc35b5b93 to avoid breaking any Rust on iOS users.

Closes https://github.com/rust-lang/rust/issues/102643
2022-10-06 07:07:36 +02:00
David Tolnay
4fdd0d9675
Fix overconstrained Send impls in btree internals 2022-10-05 12:16:32 -07:00
David Tolnay
fa863414fe
Add regression test for lifetimes in alloc internals autotraits
Currently pretty much all of the btree_map and btree_set ones fail, as
well as linked_list::DrainFilter.

    error: higher-ranked lifetime error
      --> library/alloc/tests/autotraits.rs:38:5
       |
    38 | /     require_send_sync(async {
    39 | |         let _v = None::<alloc::collections::btree_map::Iter<'_, &u32, &u32>>;
    40 | |         async {}.await;
    41 | |     });
       | |______^
       |
       = note: could not prove `impl Future<Output = ()>: Send`

    error: implementation of `Send` is not general enough
      --> library/alloc/tests/autotraits.rs:56:5
       |
    56 | /     require_send_sync(async {
    57 | |         let _v = None::<
    58 | |             alloc::collections::btree_map::DrainFilter<
    59 | |                 '_,
    ...  |
    65 | |         async {}.await;
    66 | |     });
       | |______^ implementation of `Send` is not general enough
       |
       = note: `Send` would have to be implemented for the type `&'0 u32`, for any lifetime `'0`...
       = note: ...but `Send` is actually implemented for the type `&'1 u32`, for some specific lifetime `'1`

    error: implementation of `Send` is not general enough
      --> library/alloc/tests/autotraits.rs:68:5
       |
    68 | /     require_send_sync(async {
    69 | |         let _v = None::<alloc::collections::btree_map::Entry<'_, &u32, &u32>>;
    70 | |         async {}.await;
    71 | |     });
       | |______^ implementation of `Send` is not general enough
       |
       = note: `Send` would have to be implemented for the type `&'0 u32`, for any lifetime `'0`...
       = note: ...but `Send` is actually implemented for the type `&'1 u32`, for some specific lifetime `'1`

    error: higher-ranked lifetime error
      --> library/alloc/tests/autotraits.rs:88:5
       |
    88 | /     require_send_sync(async {
    89 | |         let _v = None::<alloc::collections::btree_map::Iter<'_, &u32, &u32>>;
    90 | |         async {}.await;
    91 | |     });
       | |______^
       |
       = note: could not prove `impl Future<Output = ()>: Send`

    error: implementation of `Send` is not general enough
      --> library/alloc/tests/autotraits.rs:93:5
       |
    93 | /     require_send_sync(async {
    94 | |         let _v = None::<alloc::collections::btree_map::IterMut<'_, &u32, &u32>>;
    95 | |         async {}.await;
    96 | |     });
       | |______^ implementation of `Send` is not general enough
       |
       = note: `Send` would have to be implemented for the type `&'0 u32`, for any lifetime `'0`...
       = note: ...but `Send` is actually implemented for the type `&'1 u32`, for some specific lifetime `'1`

    error: higher-ranked lifetime error
       --> library/alloc/tests/autotraits.rs:98:5
        |
    98  | /     require_send_sync(async {
    99  | |         let _v = None::<alloc::collections::btree_map::Keys<'_, &u32, &u32>>;
    100 | |         async {}.await;
    101 | |     });
        | |______^
        |
        = note: could not prove `impl Future<Output = ()>: Send`

    error: implementation of `Send` is not general enough
       --> library/alloc/tests/autotraits.rs:103:5
        |
    103 | /     require_send_sync(async {
    104 | |         let _v = None::<alloc::collections::btree_map::OccupiedEntry<'_, &u32, &u32>>;
    105 | |         async {}.await;
    106 | |     });
        | |______^ implementation of `Send` is not general enough
        |
        = note: `Send` would have to be implemented for the type `&'0 u32`, for any lifetime `'0`...
        = note: ...but `Send` is actually implemented for the type `&'1 u32`, for some specific lifetime `'1`

    error: implementation of `Send` is not general enough
       --> library/alloc/tests/autotraits.rs:108:5
        |
    108 | /     require_send_sync(async {
    109 | |         let _v = None::<alloc::collections::btree_map::OccupiedError<'_, &u32, &u32>>;
    110 | |         async {}.await;
    111 | |     });
        | |______^ implementation of `Send` is not general enough
        |
        = note: `Send` would have to be implemented for the type `&'0 u32`, for any lifetime `'0`...
        = note: ...but `Send` is actually implemented for the type `&'1 u32`, for some specific lifetime `'1`

    error: higher-ranked lifetime error
       --> library/alloc/tests/autotraits.rs:113:5
        |
    113 | /     require_send_sync(async {
    114 | |         let _v = None::<alloc::collections::btree_map::Range<'_, &u32, &u32>>;
    115 | |         async {}.await;
    116 | |     });
        | |______^
        |
        = note: could not prove `impl Future<Output = ()>: Send`

    error: implementation of `Send` is not general enough
       --> library/alloc/tests/autotraits.rs:118:5
        |
    118 | /     require_send_sync(async {
    119 | |         let _v = None::<alloc::collections::btree_map::RangeMut<'_, &u32, &u32>>;
    120 | |         async {}.await;
    121 | |     });
        | |______^ implementation of `Send` is not general enough
        |
        = note: `Send` would have to be implemented for the type `&'0 u32`, for any lifetime `'0`...
        = note: ...but `Send` is actually implemented for the type `&'1 u32`, for some specific lifetime `'1`

    error: implementation of `Send` is not general enough
       --> library/alloc/tests/autotraits.rs:123:5
        |
    123 | /     require_send_sync(async {
    124 | |         let _v = None::<alloc::collections::btree_map::VacantEntry<'_, &u32, &u32>>;
    125 | |         async {}.await;
    126 | |     });
        | |______^ implementation of `Send` is not general enough
        |
        = note: `Send` would have to be implemented for the type `&'0 u32`, for any lifetime `'0`...
        = note: ...but `Send` is actually implemented for the type `&'1 u32`, for some specific lifetime `'1`

    error: higher-ranked lifetime error
       --> library/alloc/tests/autotraits.rs:128:5
        |
    128 | /     require_send_sync(async {
    129 | |         let _v = None::<alloc::collections::btree_map::Values<'_, &u32, &u32>>;
    130 | |         async {}.await;
    131 | |     });
        | |______^
        |
        = note: could not prove `impl Future<Output = ()>: Send`

    error: implementation of `Send` is not general enough
       --> library/alloc/tests/autotraits.rs:133:5
        |
    133 | /     require_send_sync(async {
    134 | |         let _v = None::<alloc::collections::btree_map::ValuesMut<'_, &u32, &u32>>;
    135 | |         async {}.await;
    136 | |     });
        | |______^ implementation of `Send` is not general enough
        |
        = note: `Send` would have to be implemented for the type `&'0 u32`, for any lifetime `'0`...
        = note: ...but `Send` is actually implemented for the type `&'1 u32`, for some specific lifetime `'1`

    error: higher-ranked lifetime error
       --> library/alloc/tests/autotraits.rs:146:5
        |
    146 | /     require_send_sync(async {
    147 | |         let _v = None::<alloc::collections::btree_set::Difference<'_, &u32>>;
    148 | |         async {}.await;
    149 | |     });
        | |______^
        |
        = note: could not prove `impl Future<Output = ()>: Send`

    error: implementation of `Send` is not general enough
       --> library/alloc/tests/autotraits.rs:151:5
        |
    151 | /     require_send_sync(async {
    152 | |         let _v = None::<alloc::collections::btree_set::DrainFilter<'_, &u32, fn(&&u32) -> bool>>;
    153 | |         async {}.await;
    154 | |     });
        | |______^ implementation of `Send` is not general enough
        |
        = note: `Send` would have to be implemented for the type `&'0 u32`, for any lifetime `'0`...
        = note: ...but `Send` is actually implemented for the type `&'1 u32`, for some specific lifetime `'1`

    error: higher-ranked lifetime error
       --> library/alloc/tests/autotraits.rs:156:5
        |
    156 | /     require_send_sync(async {
    157 | |         let _v = None::<alloc::collections::btree_set::Intersection<'_, &u32>>;
    158 | |         async {}.await;
    159 | |     });
        | |______^
        |
        = note: could not prove `impl Future<Output = ()>: Send`

    error: higher-ranked lifetime error
       --> library/alloc/tests/autotraits.rs:166:5
        |
    166 | /     require_send_sync(async {
    167 | |         let _v = None::<alloc::collections::btree_set::Iter<'_, &u32>>;
    168 | |         async {}.await;
    169 | |     });
        | |______^
        |
        = note: could not prove `impl Future<Output = ()>: Send`

    error: higher-ranked lifetime error
       --> library/alloc/tests/autotraits.rs:171:5
        |
    171 | /     require_send_sync(async {
    172 | |         let _v = None::<alloc::collections::btree_set::Range<'_, &u32>>;
    173 | |         async {}.await;
    174 | |     });
        | |______^
        |
        = note: could not prove `impl Future<Output = ()>: Send`

    error: higher-ranked lifetime error
       --> library/alloc/tests/autotraits.rs:176:5
        |
    176 | /     require_send_sync(async {
    177 | |         let _v = None::<alloc::collections::btree_set::SymmetricDifference<'_, &u32>>;
    178 | |         async {}.await;
    179 | |     });
        | |______^
        |
        = note: could not prove `impl Future<Output = ()>: Send`

    error: higher-ranked lifetime error
       --> library/alloc/tests/autotraits.rs:181:5
        |
    181 | /     require_send_sync(async {
    182 | |         let _v = None::<alloc::collections::btree_set::Union<'_, &u32>>;
    183 | |         async {}.await;
    184 | |     });
        | |______^
        |
        = note: could not prove `impl Future<Output = ()>: Send`

    error: future cannot be sent between threads safely
       --> library/alloc/tests/autotraits.rs:243:23
        |
    243 |       require_send_sync(async {
        |  _______________________^
    244 | |         let _v =
    245 | |             None::<alloc::collections::linked_list::DrainFilter<'_, &u32, fn(&mut &u32) -> bool>>;
    246 | |         async {}.await;
    247 | |     });
        | |_____^ future created by async block is not `Send`
        |
        = help: within `impl Future<Output = ()>`, the trait `Send` is not implemented for `NonNull<std::collections::linked_list::Node<&u32>>`
    note: future is not `Send` as this value is used across an await
       --> library/alloc/tests/autotraits.rs:246:17
        |
    244 |         let _v =
        |             -- has type `Option<std::collections::linked_list::DrainFilter<'_, &u32, for<'a, 'b> fn(&'a mut &'b u32) -> bool>>` which is not `Send`
    245 |             None::<alloc::collections::linked_list::DrainFilter<'_, &u32, fn(&mut &u32) -> bool>>;
    246 |         async {}.await;
        |                 ^^^^^^ await occurs here, with `_v` maybe used later
    247 |     });
        |     - `_v` is later dropped here
    note: required by a bound in `require_send_sync`
       --> library/alloc/tests/autotraits.rs:3:25
        |
    3   | fn require_send_sync<T: Send + Sync>(_: T) {}
        |                         ^^^^ required by this bound in `require_send_sync`

    error: future cannot be shared between threads safely
       --> library/alloc/tests/autotraits.rs:243:23
        |
    243 |       require_send_sync(async {
        |  _______________________^
    244 | |         let _v =
    245 | |             None::<alloc::collections::linked_list::DrainFilter<'_, &u32, fn(&mut &u32) -> bool>>;
    246 | |         async {}.await;
    247 | |     });
        | |_____^ future created by async block is not `Sync`
        |
        = help: within `impl Future<Output = ()>`, the trait `Sync` is not implemented for `NonNull<std::collections::linked_list::Node<&u32>>`
    note: future is not `Sync` as this value is used across an await
       --> library/alloc/tests/autotraits.rs:246:17
        |
    244 |         let _v =
        |             -- has type `Option<std::collections::linked_list::DrainFilter<'_, &u32, for<'a, 'b> fn(&'a mut &'b u32) -> bool>>` which is not `Sync`
    245 |             None::<alloc::collections::linked_list::DrainFilter<'_, &u32, fn(&mut &u32) -> bool>>;
    246 |         async {}.await;
        |                 ^^^^^^ await occurs here, with `_v` maybe used later
    247 |     });
        |     - `_v` is later dropped here
    note: required by a bound in `require_send_sync`
       --> library/alloc/tests/autotraits.rs:3:32
        |
    3   | fn require_send_sync<T: Send + Sync>(_: T) {}
        |                                ^^^^ required by this bound in `require_send_sync`
2022-10-05 12:15:17 -07:00
BlackHoleFox
a955ef2c8c Revert "Use getentropy when possible on all Apple platforms"
This reverts commit 3fc35b5b93.
2022-10-05 00:48:22 -05:00
Michael Howell
4025e95113
Rollup merge of #102574 - aDotInTheVoid:const_collections_with_hasher, r=oli-obk,fee1-dead
Make Hash{Set,Map}::with_hasher unstably const

Makes  [`HashMap::with_hasher`](https://doc.rust-lang.org/stable/std/collections/hash_map/struct.HashMap.html#method.with_hasher) and [`HashSet::with_hasher`](https://doc.rust-lang.org/stable/std/collections/hash_set/struct.HashSet.html#method.with_hasher) `const`.

This allows

```rust
static GlobalState: Mutex<HashMap<i32, i32, SomeHasher>> = Mutex::new(HashMap::with_hasher(SomeHasher::new()))
```

Tracking issue: #102575
2022-10-04 20:45:12 -07:00
Nicholas Nethercote
ed6f4813bb A tiny fix for define_client_side.
The return type can only appear once.
2022-10-05 13:10:28 +11:00
Gary Guo
8bda13367e Interpret EH actions properly
The EH actions stored in the LSDA follows the format of GCC except table
(even for LLVM-generated code). An missing action in the table is the
encoding for `Terminate`, see [1].

The currently code interprets it as `None`, as a workaround for #35011,
an issue that seems to occur in LLVM 3.7 and not after 3.9. These are
very old versions of LLVM and we don't support them anymore, so remove
this workaround and interpret them properly.

Note that LLVM currently does not emit any `Terminate` actions, but GCC
does. Although GCC backend currently doesn't do unwinding, removing it
preemptively would prevent future developers from wasting time to figure
out what's wrong.

[1]: https://github.com/gcc-mirror/gcc/blob/master/libstdc%2B%2B-v3/libsupc%2B%2B/eh_personality.cc#L522-L526
2022-10-05 03:09:43 +01:00
bors
d4846f9d03 Auto merge of #101768 - sunfishcode:sunfishcode/wasi-stdio-lock-asfd, r=joshtriplett
Add `AsFd` implementations for stdio lock types on WASI.

This mirrors the implementations on Unix platforms, and also mirrors the existing `AsRawFd` impls.

This is similar to #100892, but is for the `*Lock` types.
2022-10-04 23:22:16 +00: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
f24d00d8b3
Rollup merge of #101642 - SkiFire13:fix-inplace-collection-leak, r=the8472
Fix in-place collection leak when remaining element destructor panic

Fixes #101628

cc `@the8472`

I went for the drop guard route, placing it immediately before the `forget_allocation_drop_remaining` call and after the comment, as to signal they are closely related.

I also updated the test to check for the leak, though the only change really needed was removing the leak clean up for miri since now that's no longer leaked.
2022-10-04 16:11:01 +05:30
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
Rageking8
9fb509e884 fix backtrace small typo 2022-10-04 15:19:21 +08: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
Matthias Krüger
2110d2de5a
Rollup merge of #99216 - duarten:master, r=joshtriplett
docs: be less harsh in wording for Vec::from_raw_parts

In particular, be clear that it is sound to specify memory not
originating from a previous `Vec` allocation. That is already suggested
in other parts of the documentation about zero-alloc conversions to Box<[T]>.

Incorporate a constraint from `slice::from_raw_parts` that was missing
but needs to be fulfilled, since a `Vec` can be converted into a slice.

Fixes https://github.com/rust-lang/rust/issues/98780.
2022-10-03 20:58:53 +02:00
Matthias Krüger
098e8b7357
Rollup merge of #98218 - kpreid:nostdarc, r=joshtriplett
Document the conditional existence of `alloc::sync` and `alloc::task`.

`alloc` declares

```rust
#[cfg(target_has_atomic = "ptr")]
pub mod sync;
```

but there is no public documentation of this condition. This PR fixes that, so that users of `alloc` can understand how to make their code compile everywhere `alloc` does, if they are writing a library with impls for `Arc`.

The wording is copied from `std::sync::atomic::AtomicPtr`, with additional advice on how to `#[cfg]` for it.

I feel quite uncertain about whether the paragraph I added to `Arc`'s documentation should actually be there, as it is a distraction for anyone using `std`. On the other hand, maybe more reminders that no_std exists would benefit the ecosystem.

Note: `target_has_atomic` is [stabilized](https://github.com/rust-lang/rust/issues/32976) but [not yet documented in the reference](https://github.com/rust-lang/reference/pull/1171).
2022-10-03 20:58:53 +02:00
Giacomo Stevanato
1750c7bdd3 Clarify documentation 2022-10-03 20:23:54 +02:00
Alex Saveau
86974b83af
Reduce CString allocations in std as much as possible
Signed-off-by: Alex Saveau <saveau.alexandre@gmail.com>
2022-10-03 11:13:17 -07: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
Josh Triplett
905ebc31b1 Add SAFETY comments for AsFd implementations on stdin/stdout/stderr 2022-10-03 08:30:58 -07:00
Dan Gohman
625ebf603d Add stability attributes. 2022-10-03 08:30:55 -07:00
Ralf Jung
78b577c065 scoped threads: pass closure through MaybeUninit to avoid invalid dangling references 2022-10-03 15:35:29 +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
Scott McMurray
31cd0aa823 Do the calloc optimization for Option<bool>
Inspired by <https://old.reddit.com/r/rust/comments/xtiqj8/why_is_this_functional_version_faster_than_my_for/iqqy37b/>.
2022-10-02 12:26:58 -07:00
bors
39323a5877 Auto merge of #102586 - Dylan-DPC:rollup-g107h6z, r=Dylan-DPC
Rollup of 5 pull requests

Successful merges:

 - #100451 (Do not panic when a test function returns Result::Err.)
 - #102098 (Use fetch_update in sync::Weak::upgrade)
 - #102538 (Give `def_span` the same SyntaxContext as `span_with_body`.)
 - #102556 (Make `feature(const_btree_len)` implied by `feature(const_btree_new)`)
 - #102566 (Add a known-bug test for #102498)

Failed merges:

r? `@ghost`
`@rustbot` modify labels: rollup
2022-10-02 15:31:06 +00:00
Dylan DPC
890a327c86
Rollup merge of #102556 - WaffleLapkin:implied_by_btree_new, r=Mark-Simulacrum
Make `feature(const_btree_len)` implied by `feature(const_btree_new)`

...this should fix code that used the old feature that was changed in #102197

cc ```@davidtwco``` it seems like tidy doesn't check `implied_by`, should it?
2022-10-02 20:42:22 +05:30
Dylan DPC
ed9740846b
Rollup merge of #102098 - xfix:weak-upgrade-fetch-update, r=Mark-Simulacrum
Use fetch_update in sync::Weak::upgrade

Using `fetch_update` makes it more clear that it's CAS loop then manually implementing one.
2022-10-02 20:42:21 +05:30
Dylan DPC
13f47f608e
Rollup merge of #100451 - hovinen:no-panic-on-result-err-in-test, r=Mark-Simulacrum
Do not panic when a test function returns Result::Err.

Rust's test library allows test functions to return a `Result`, so that the test is deemed to have failed if the function returns a `Result::Err` variant. Currently, this works by having `Result` implement the `Termination` trait and asserting in assert_test_result that `Termination::report()` indicates successful completion. This turns a `Result::Err` into a panic, which is caught and unwound in the test library.

This approach is problematic in certain environments where one wishes to save on both binary size and compute resources when running tests by:

 * Compiling all code with `--panic=abort` to avoid having to generate unwinding tables, and
 * Running most tests in-process to avoid the overhead of spawning new processes.

This change removes the intermediate panic step and passes a `Result::Err` directly through to the test runner.

To do this, it modifies `assert_test_result` to return a `Result<(), String>` where the `Err` variant holds what was previously the panic message. It changes the types in the `TestFn` enum to return `Result<(), String>`.

This tries to minimise the changes to benchmark tests, so it calls `unwrap()` on the `Result` returned by `assert_test_result`, effectively keeping the same behaviour as before.

Some questions for reviewers:

 * Does the change to the return types in the enum `TestFn` constitute a breaking change for the library API? Namely, the enum definition is public but the test library indicates that "Currently, not much of this is meant for users" and most of the library API appears to be marked unstable.
 * Is there a way to test this change, i.e., to test that no panic occurs if a test returns `Result::Err`?
 * Is there a shorter, more idiomatic way to fold `Result<Result<T,E>,E>` into a `Result<T,E>` than the `fold_err` function I added?
2022-10-02 20:42:20 +05:30
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
Nixon Enraght-Moony
346a49fe48 Make Hash{Set,Map}::with_hasher unstably const 2022-10-02 13:07:13 +01: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
Matthias Krüger
649c09996f
Rollup merge of #102313 - anirudh24seven:update_sleep_ms_doc, r=Mark-Simulacrum
Update docs so that deprecated method points to relevant method

The docs for the deprecated 'park_timeout_ms' method suggests that the user 'use park_timeout' method instead (at https://doc.rust-lang.org/std/thread/index.html).

Making a similar change so that the docs for the deprecated `sleep_ms` method suggest that the user `use sleep` method instead.
2022-10-02 03:16:38 +02:00
Maybe Waffle
da78c1fd43 Make feature(const_btree_len) implied by feature(const_btree_new) 2022-10-01 22:40:04 +00:00
Cameron Steffen
4f12de0660 Change feature name to is_some_and 2022-10-01 11:45:52 -05:00