Emit errors/warns on some wrong uses of rustdoc attributes
This PR adds a few diagnostics:
- error if conflicting `#[doc(inline)]`/`#[doc(no_inline)]` are found
- introduce the `invalid_doc_attributes` lint (warn-by-default) which triggers:
- if a crate-level attribute is used on a non-`crate` item
- if `#[doc(inline)]`/`#[doc(no_inline)]` is used on a non-`use` item
The code could probably be improved but I wanted to get feedback first. Also, some of those changes could be considered breaking changes, so I don't know what the procedure would be? ~~And finally, for the warnings, they are currently hard warnings, maybe it would be better to introduce a lint?~~ (EDIT: introduced the `invalid_doc_attributes` lint)
Closes#80275.
r? `@jyn514`
Provide io::Seek::rewind
Using `Seek::seek` is slightly clumsy because of the need to write (or import) `std::io::SeekFrom` to get at `SeekStart`. C already has `rewind` (although with broken error handling); we should have it too.
I'm motivated to do this because I've just found myself copy-pasting my 5-line extension trait between projects.
That the example ends up using `OpenOptions` makes this look like a niche use case, but it is very common to rewind temporary files. `tempfile` isn't available for use in this example or it would have looked shorter and more natural.
If this gets a positive reception I will open a tracking issue and update the feature gate.
Make unchecked_{add,sub,mul} inherent methods unstably const
The intrinsics are marked as being stably const (even though they're not stable by nature of being intrinsics), but the currently-unstable inherent versions are not marked as const. This fixes this inconsistency. Split out of #85017,
r? `@oli-obk`
Bump stdarch submodule
Major changes:
- More AVX-512 intrinsics.
- More ARM & AArch64 NEON intrinsics.
- Updated unstable WASM intrinsics to latest draft standards.
- Intrinsics that previously used `#[rustc_args_required_const]` now use const generics. See #83167 for more details.
- `std_detect` is now a separate crate instead of a submodule of `std`.
fork fails there. The failure message is confusing: so c.status()
returns an Err, the closure panics, and the test thinks the panic was
propagated from inside the child.
Signed-off-by: Ian Jackson <ijackson@chiark.greenend.org.uk>
Co-authored-by: Mara Bos <m-ou.se@m-ou.se>
Rearrange SGX split module files
In #75979 several inlined modules were split out into multiple files.
This PR keeps the multiple files but moves a few things around to
organize things in a coherent way.
Cleanup of `wasm`
Some more cleanup of `sys`, this time `wasm`
- Reuse `unsupported::args` (functionally equivalent implementation, just an empty iterator).
- Split out `atomics` implementation of `wasm::thread`, the non-`atomics` implementation is reused from `unsupported`.
- Move all of the `atomics` code to a separate directory `wasm/atomics`.
````@rustbot```` label: +T-libs-impl
r? ````@m-ou-se````
In #75979 several inlined modules were split out into multiple files.
This PR keeps the multiple files but moves a few things around to
organize things in a coherent way.
This tests that we can indeed safely panic after fork, both
a raw libc::fork and in a Command pre_exec hook.
Signed-off-by: Ian Jackson <ijackson@chiark.greenend.org.uk>
Co-authored-by: Mara Bos <m-ou.se@m-ou.se>
This is safe (does not involve heap allocation) but we don't yet have
a test to ensure that stays true. That will come in a moment.
Signed-off-by: Ian Jackson <ijackson@chiark.greenend.org.uk>
Co-authored-by: Mara Bos <m-ou.se@m-ou.se>
Unwinding after fork() in the child is UB on some platforms, because
on those (including musl) malloc can be UB in the child of a
multithreaded program, and unwinding must box for the payload.
Even if it's safe, unwinding past fork() in the child causes whatever
traps the unwind to return twice. This is very strange and clearly
not desirable. With the default behaviour of the thread library, this
can even result in a panic in the child being transformed into zero
exit status (ie, success) as seen in the parent!
Fixes#79740.
Signed-off-by: Ian Jackson <ijackson@chiark.greenend.org.uk>
We must change the atomic read on panic entry to `Acquire`, to pick up
a possible an `always_panic` on another thread.
We add `count` to the names of panic_count::get and ::is_zaero,
because now there is another reason why panic ought to maybe abort.
Renaming these ensures that we have checked every call site to ensure
that they don't need further adjustment.
Signed-off-by: Ian Jackson <ijackson@chiark.greenend.org.uk>
Co-authored-by: Mara Bos <m-ou.se@m-ou.se>
Disallows `#![feature(no_coverage)]` on stable and beta (using standard crate-level gating)
Fixes: #84836
Removes the function-level feature gating solution originally implemented, and solves the same problem using `allow_internal_unstable`, so normal crate-level feature gating mechanism can still be used (which disallows the feature on stable and beta).
I tested this, building the compiler with and without `CFG_DISABLE_UNSTABLE_FEATURES=1`
With unstable features disabled, I get the expected result as shown here:
```shell
$ ./build/x86_64-unknown-linux-gnu/stage1/bin/rustc src/test/run-make-fulldeps/coverage/no_cov_crate.rs
error[E0554]: `#![feature]` may not be used on the dev release channel
--> src/test/run-make-fulldeps/coverage/no_cov_crate.rs:2:1
|
2 | #![feature(no_coverage)]
| ^^^^^^^^^^^^^^^^^^^^^^^^
error: aborting due to previous error
For more information about this error, try `rustc --explain E0554`.
```
r? ````@Mark-Simulacrum````
cc: ````@tmandry```` ````@wesleywiser````
Allow using `core::` in intra-doc links within core itself
I came up with this idea ages ago, but rustdoc used to ICE on it. Now it doesn't.
Helps with https://github.com/rust-lang/rust/issues/73445. Doesn't fix it completely since `extern crate self as std;` in std still gives strange errors.
Stablize {HashMap,BTreeMap}::into_{keys,values}
I would propose to stabilize `{HashMap,BTreeMap}::into_{keys,values}`( aka. `map_into_keys_values`).
Closes#75294.
For certain sorts of systems, programming, it's deemed essential that
all allocation failures be explicitly handled where they occur. For
example, see Linus Torvald's opinion in [1]. Merely not calling global
panic handlers, or always `try_reserving` first (for vectors), is not
deemed good enough, because the mere presence of the global OOM handlers
is burdens static analysis.
One option for these projects to use rust would just be to skip `alloc`,
rolling their own allocation abstractions. But this would, in my
opinion be a real shame. `alloc` has a few `try_*` methods already, and
we could easily have more. Features like custom allocator support also
demonstrate and existing to support diverse use-cases with the same
abstractions.
A natural way to add such a feature flag would a Cargo feature, but
there are currently uncertainties around how std library crate's Cargo
features may or not be stable, so to avoid any risk of stabilizing by
mistake we are going with a more low-level "raw cfg" token, which
cannot be interacted with via Cargo alone.
Note also that since there is no notion of "default cfg tokens" outside
of Cargo features, we have to invert the condition from
`global_oom_handling` to to `not(no_global_oom_handling)`. This breaks
the monotonicity that would be important for a Cargo feature (i.e.
turning on more features should never break compatibility), but it
doesn't matter for raw cfg tokens which are not intended to be
"constraint solved" by Cargo or anything else.
To support this use-case we create a new feature, "global-oom-handling",
on by default, and put the global OOM handler infra and everything else
it that depends on it behind it. By default, nothing is changed, but
users concerned about global handling can make sure it is disabled, and
be confident that all OOM handling is local and explicit.
For this first iteration, non-flat collections are outright disabled.
`Vec` and `String` don't yet have `try_*` allocation methods, but are
kept anyways since they can be oom-safely created "from parts", and we
hope to add those `try_` methods in the future.
[1]: https://lore.kernel.org/lkml/CAHk-=wh_sNLoz84AUUzuqXEsYH35u=8HV3vK-jbRbJ_B-JjGrg@mail.gmail.com/
Rollup of 11 pull requests
Successful merges:
- #83553 (Update `ptr` docs with regards to `ptr::addr_of!`)
- #84183 (Update RELEASES.md for 1.52.0)
- #84709 (Add doc alias for `chdir` to `std::env::set_current_dir`)
- #84803 (Reduce duplication in `impl_dep_tracking_hash` macros)
- #84808 (Account for unsatisfied bounds in E0599)
- #84843 (use else if in std library )
- #84865 (rustbuild: Pass a `threads` flag that works to windows-gnu lld)
- #84878 (Clarify documentation for `[T]::contains`)
- #84882 (platform-support: Center the contents of the `std` and `host` columns)
- #84903 (Remove `rustc_middle::mir::interpret::CheckInAllocMsg::NullPointerTest`)
- #84913 (Do not ICE on invalid const param)
Failed merges:
r? `@ghost`
`@rustbot` modify labels: rollup
Clarify documentation for `[T]::contains`
Change the documentation to correctly characterize when the suggested alternative to `contains` applies, and correctly explain why it works.
Fixes#84877
Add doc alias for `chdir` to `std::env::set_current_dir`
Searching for `chdir` in the Rust documentation produces no useful
results.
I wrote some code recently that called `libc::chdir` and manually
handled errors, because I didn't realize that the safe
`std::env::set_current_dir` existed. I searched for `chdir` and
`change_dir` and `change_directory` (the latter two based on the
precedent of unabbreviating set by `create_dir`), and I also read
through `std::fs` expecting to potentially find it there. Given that
none of those led to `std::env::set_current_dir`, I think that provides
sufficient justification to add this specific alias.
Update `ptr` docs with regards to `ptr::addr_of!`
This updates the documentation since `ptr::addr_of!` and `ptr::addr_of_mut!` are now stable. One might remove the distinction between the sections `# On packed structs` and `# Examples`, as the old section on packed structs was primarily to prevent users of doing undefined behavior, which is not necessary anymore.
Technically there is now wrong/outdated documentation on stable, but I don't think this is worth a point release 😉Fixes#83509.
``````````@rustbot`````````` modify labels: T-doc
using allow_internal_unstable (as recommended)
Fixes: #84836
```shell
$ ./build/x86_64-unknown-linux-gnu/stage1/bin/rustc src/test/run-make-fulldeps/coverage/no_cov_crate.rs
error[E0554]: `#![feature]` may not be used on the dev release channel
--> src/test/run-make-fulldeps/coverage/no_cov_crate.rs:2:1
|
2 | #![feature(no_coverage)]
| ^^^^^^^^^^^^^^^^^^^^^^^^
error: aborting due to previous error
For more information about this error, try `rustc --explain E0554`.
```
Move all `sys::ext` modules to `os`
This PR moves all `sys::ext` modules to `os`, centralizing the location of all `os` code and simplifying the dependencies between `os` and `sys`.
Because this also removes all uses `cfg_if!` on publicly exported items, where after #81969 there were still a few left, this should properly work around https://github.com/rust-analyzer/rust-analyzer/issues/6038.
`@rustbot` label: +T-libs-impl
This updates the documentation since `ptr::addr_of!` and
`ptr::addr_of_mut!` are now stable. One might remove the distinction
between the sections `# On packed structs` and `# Examples`, as the old
section on packed structs was primarily to prevent users of doing unde-
fined behavior, which is not necessary anymore.
There is also a new section in "how to obtain a pointer", which referen-
ces the `ptr::addr_of!` macros.
This commit contains squashed commits from code review.
Co-authored-by: Joshua Nelson <joshua@yottadb.com>
Co-authored-by: Mara Bos <m-ou.se@m-ou.se>
Co-authored-by: Soveu <marx.tomasz@gmail.com>
Co-authored-by: Ralf Jung <post@ralfj.de>
Replace 'NULL' with 'null'
This replaces occurrences of "NULL" with "null" in docs, comments, and compiler error/lint messages. This is for the sake of consistency, as the lowercase "null" is already the dominant form in Rust. The all-caps NULL looks like the C macro (or SQL keyword), which seems out of place in a Rust context, given that NULL does not exist in the Rust language or standard library (instead having [`ptr::null()`](https://doc.rust-lang.org/stable/std/ptr/fn.null.html)).
Rollup of 6 pull requests
Successful merges:
- #84072 (Allow setting `target_family` to multiple values, and implement `target_family="wasm"`)
- #84744 (Add ErrorKind::OutOfMemory)
- #84784 (Add help message to suggest const for unused type param)
- #84811 (RustDoc: Fix bounds linking trait.Foo instead of traitalias.Foo)
- #84818 (suggestion for unit enum variant when matched with a patern)
- #84832 (Do not print visibility in external traits)
Failed merges:
r? `@ghost`
`@rustbot` modify labels: rollup
i8 and u8::to_string() specialisation (far less asm).
Take 2. Around 1/6th of the assembly to without specialisation.
https://godbolt.org/z/bzz8Mq
(partially fixes#73533 )
[Arm64] use isb instruction instead of yield in spin loops
On arm64 we have seen on several databases that ISB (instruction synchronization
barrier) is better to use than yield in a spin loop. The yield instruction is a
nop. The isb instruction puts the processor to sleep for some short time. isb
is a good equivalent to the pause instruction on x86.
Below is an experiment that shows the effects of yield and isb on Arm64 and the
time of a pause instruction on x86 Intel processors. The micro-benchmarks use
https://github.com/google/benchmark.git
```
$ cat a.cc
static void BM_scalar_increment(benchmark::State& state) {
int i = 0;
for (auto _ : state)
benchmark::DoNotOptimize(i++);
}
BENCHMARK(BM_scalar_increment);
static void BM_yield(benchmark::State& state) {
for (auto _ : state)
asm volatile("yield"::);
}
BENCHMARK(BM_yield);
static void BM_isb(benchmark::State& state) {
for (auto _ : state)
asm volatile("isb"::);
}
BENCHMARK(BM_isb);
BENCHMARK_MAIN();
$ g++ -o run a.cc -O2 -lbenchmark -lpthread
$ ./run
--------------------------------------------------------------
Benchmark Time CPU Iterations
--------------------------------------------------------------
AWS Graviton2 (Neoverse-N1) processor:
BM_scalar_increment 0.485 ns 0.485 ns 1000000000
BM_yield 0.400 ns 0.400 ns 1000000000
BM_isb 13.2 ns 13.2 ns 52993304
AWS Graviton (A-72) processor:
BM_scalar_increment 0.897 ns 0.874 ns 801558633
BM_yield 0.877 ns 0.875 ns 800002377
BM_isb 13.0 ns 12.7 ns 55169412
Apple Arm64 M1 processor:
BM_scalar_increment 0.315 ns 0.315 ns 1000000000
BM_yield 0.313 ns 0.313 ns 1000000000
BM_isb 9.06 ns 9.06 ns 77259282
```
```
static void BM_pause(benchmark::State& state) {
for (auto _ : state)
asm volatile("pause"::);
}
BENCHMARK(BM_pause);
Intel Skylake processor:
BM_scalar_increment 0.295 ns 0.295 ns 1000000000
BM_pause 41.7 ns 41.7 ns 16780553
```
Tested on Graviton2 aarch64-linux with `./x.py test`.
Be stricter about rejecting LLVM reserved registers in asm!
LLVM will silently produce incorrect code if these registers are used as operands.
cc `@rust-lang/wg-inline-asm`
Add std::os::unix::fs::chroot to change the root directory of the current process
This is a straightforward wrapper that uses the existing helpers for C
string handling and errno handling.
Having this available is convenient for UNIX utility programs written in
Rust, and avoids having to call the unsafe `libc::chroot` directly and
handle errors manually, in a program that may otherwise be entirely safe
code.
Reuse `sys::unix::cmath` on other platforms
Reuse `sys::unix::cmath` on all non-`windows` platforms.
`unix` is chosen as the canonical location instead of `unsupported` or `common` because `unsupported` doesn't make sense semantically and `common` is reserved for code that is supported on all platforms. Also `unix` is already the home of some non-`windows` code that is technically not exclusive to `unix` like `unix::path`.
This is a straightforward wrapper that uses the existing helpers for C
string handling and errno handling.
Having this available is convenient for UNIX utility programs written in
Rust, and avoids having to call the unsafe `libc::chroot` directly and
handle errors manually, in a program that may otherwise be entirely safe
code.
Drop alias `reduce` for `fold` - we have a `reduce` function
Searching for "reduce" currently puts the `reduce` alias for `fold`
above the actual `reduce` function. The `reduce` function already has a
cross-reference for `fold`, and vice versa.
Link between std::env::{var, var_os} and std::env::{vars, vars_os}
In #84551 I linked between `std::env::{args, args_os}` and this PR does the same but for `std::env::{var, var_os}` and `std::env::{vars, vars_os}`. Now all of `std::env::{var, var_os, vars, vars_os, args, args_os}` should each mention their `_os` or non-`_os` equivalent in the docs so that you can easily navigate between them.
Minor grammar tweaks for readability to btree internals
I was reading through the btree implementation and I noticed some grammar that could be improved in Node.rs so here is what I think would be a minor improvement.
Point out that behavior might be switched on 2015 and 2018 too one day
Reword documentation to make it clear that behaviour can be switched on older editions too, one day in the future. It doesn't *have* to be switched, but I think it's good to have it as an option and re-evaluate it a few months/years down the line when e.g. the crates that showed up in crater were broken by different changes in the language already.
cc #25725, #65819, #66145, #84147 , and https://github.com/rust-lang/rust/issues/84133#issuecomment-818005314
On arm64 we have seen on several databases that ISB (instruction synchronization
barrier) is better to use than yield in a spin loop. The yield instruction is a
nop. The isb instruction puts the processor to sleep for some short time. isb
is a good equivalent to the pause instruction on x86.
Below is an experiment that shows the effects of yield and isb on Arm64 and the
time of a pause instruction on x86 Intel processors. The micro-benchmarks use
https://github.com/google/benchmark.git
$ cat a.cc
static void BM_scalar_increment(benchmark::State& state) {
int i = 0;
for (auto _ : state)
benchmark::DoNotOptimize(i++);
}
BENCHMARK(BM_scalar_increment);
static void BM_yield(benchmark::State& state) {
for (auto _ : state)
asm volatile("yield"::);
}
BENCHMARK(BM_yield);
static void BM_isb(benchmark::State& state) {
for (auto _ : state)
asm volatile("isb"::);
}
BENCHMARK(BM_isb);
BENCHMARK_MAIN();
$ g++ -o run a.cc -O2 -lbenchmark -lpthread
$ ./run
--------------------------------------------------------------
Benchmark Time CPU Iterations
--------------------------------------------------------------
AWS Graviton2 (Neoverse-N1) processor:
BM_scalar_increment 0.485 ns 0.485 ns 1000000000
BM_yield 0.400 ns 0.400 ns 1000000000
BM_isb 13.2 ns 13.2 ns 52993304
AWS Graviton (A-72) processor:
BM_scalar_increment 0.897 ns 0.874 ns 801558633
BM_yield 0.877 ns 0.875 ns 800002377
BM_isb 13.0 ns 12.7 ns 55169412
Apple Arm64 M1 processor:
BM_scalar_increment 0.315 ns 0.315 ns 1000000000
BM_yield 0.313 ns 0.313 ns 1000000000
BM_isb 9.06 ns 9.06 ns 77259282
static void BM_pause(benchmark::State& state) {
for (auto _ : state)
asm volatile("pause"::);
}
BENCHMARK(BM_pause);
Intel Skylake processor:
BM_scalar_increment 0.295 ns 0.295 ns 1000000000
BM_pause 41.7 ns 41.7 ns 16780553
Tested on Graviton2 aarch64-linux with `./x.py test`.
Searching for "reduce" currently puts the `reduce` alias for `fold`
above the actual `reduce` function. The `reduce` function already has a
cross-reference for `fold`, and vice versa.
use correct feature flag for impl-block-level trait bounds on const fn
I am not sure what that special hack was needed for, but it doesn't seem needed any more...
This removes the last use of the `const_fn` feature flag -- Cc https://github.com/rust-lang/rust/issues/84510
r? `@oli-obk`
Remove `DropGuard` in `sys::windows::process` and use `StaticMutex` instead
`StaticMutex` is a mutex that when locked provides a guard that unlocks the mutex again when dropped, thus provides the exact same functionality as `DropGuard`. `StaticMutex` is used in more places, and is thus preferred over an ad-hoc construct like `DropGuard`.
````@rustbot```` label: +T-libs-impl
Simplify `Mutex::into_inner`
Thanks to #77147, `Mutex` do not implement `Drop` directly, so the old unsafe implementation of `into_inner` is not relevant anymore.
Adds feature-gated `#[no_coverage]` function attribute, to fix derived Eq `0` coverage issue #83601
Derived Eq no longer shows uncovered
The Eq trait has a special hidden function. MIR `InstrumentCoverage`
would add this function to the coverage map, but it is never called, so
the `Eq` trait would always appear uncovered.
Fixes: #83601
The fix required creating a new function attribute `no_coverage` to mark
functions that should be ignored by `InstrumentCoverage` and the
coverage `mapgen` (during codegen).
Adding a `no_coverage` feature gate with tracking issue #84605.
r? `@tmandry`
cc: `@wesleywiser`
The Eq trait has a special hidden function. MIR `InstrumentCoverage`
would add this function to the coverage map, but it is never called, so
the `Eq` trait would always appear uncovered.
Fixes: #83601
The fix required creating a new function attribute `no_coverage` to mark
functions that should be ignored by `InstrumentCoverage` and the
coverage `mapgen` (during codegen).
While testing, I also noticed two other issues:
* spanview debug file output ICEd on a function with no body. The
workaround for this is included in this PR.
* `assert_*!()` macro coverage can appear covered if followed by another
`assert_*!()` macro. Normally they appear uncovered. I submitted a new
Issue #84561, and added a coverage test to demonstrate this issue.
Reuse modules on `hermit`
Reuse the following modules on `hermit`:
- `unix::path` (contents identical)
- `unsupported::io` (contents identical)
- `unsupported::thread_local_key` (contents functionally identical, only changes are the panic error messages)
`@rustbot` label: +T-libs-impl
Add the `try_trait_v2` library basics
No compiler changes as part of this -- just new unstable traits and impls thereof.
The goal here is to add the things that aren't going to break anything, to keep the feature implementation simpler in the next PR.
(Draft since the FCP won't end until Saturday, but I was feeling optimistic today -- and had forgotten that FCP was 10 days, not 7 days.)
Unify the docs of std::env::{args_os, args} more
I noticed that `args_os` was missing some information and I thought it should mention `args` for when you want more safety just like how `args` mentions `args_os` if you don't want it to panic on invalid Unicode.
Stabilize Duration::MAX
Following the suggested direction from https://github.com/rust-lang/rust/issues/76416#issuecomment-817278338, this PR proposes that `Duration::MAX` should have been part of the `duration_saturating_ops` feature flag all along, having been
0. heavily referenced by that feature flag
1. an odd duck next to most of `duration_constants`, as I expressed in https://github.com/rust-lang/rust/issues/57391#issuecomment-717681193
2. introduced in #76114 which added `duration_saturating_ops`
and accordingly should be folded into `duration_saturating_ops` and therefore stabilized.
r? `@m-ou-se`
Remove slice diagnostic item
...because it is unusally placed on an impl and is redundant with a lang item.
Depends on rust-lang/rust-clippy#7074 (next clippy sync). ~I expect clippy tests to fail in the meantime.~ Nope tests passed...
CC `@flip1995`
Get rid of is_min_const_fn
This removes the last trace of the min_const_fn mechanism by making the unsafety checker agnostic about whether something is a min or "non-min" const fn. It seems this distinction was used to disallow some features inside `const fn`, but that is the responsibility of the const checker, not of the unsafety checker. No test seems to even notice this change in the unsafety checker so I guess we are good...
r? `@oli-obk`
Cc https://github.com/rust-lang/rust/issues/84510
Inline most raw socket, fd and handle conversions
Now that file descriptor types on Unix have niches, it is advantageous for user libraries which provide file descriptor wrappers (e.g. `Socket` from socket2) to store a `File` internally instead of a `RawFd`, so that the niche can be taken advantage of. However, doing so will currently result in worse performance as `IntoRawFd`, `FromRawFd` and `AsRawFd` are not inlined. This change adds `#[inline]` to those methods on std types that wrap file descriptors, handles or sockets.
move core::hint::black_box under its own feature gate
The `black_box` function had its own RFC and is tracked separately from the `test` feature at https://github.com/rust-lang/rust/issues/64102. Let's reflect this in the feature gate.
To avoid breaking all the benchmarks, libtest's `test::black_box` is a wrapping definition, not a reexport -- this means it is still under the `test` feature gate.
Cautiously add IntoIterator for arrays by value
Add the attribute described in #84133, `#[rustc_skip_array_during_method_dispatch]`, which effectively hides a trait from method dispatch when the receiver type is an array.
Then cherry-pick `IntoIterator for [T; N]` from #65819 and gate it with that attribute. Arrays can now be used as `IntoIterator` normally, but `array.into_iter()` has edition-dependent behavior, returning `slice::Iter` for 2015 and 2018 editions, or `array::IntoIter` for 2021 and later.
r? `@nikomatsakis`
cc `@LukasKalbertodt` `@rust-lang/libs`
Rework `init` and `cleanup`
This PR reworks the code in `std` that runs before and after `main` and centralizes this code respectively in the functions `init` and `cleanup` in both `sys_common` and `sys`. This makes is easy to see what code is executed during initialization and cleanup on each platform just by looking at e.g. `sys::windows::init`.
Full list of changes:
- new module `rt` in `sys_common` to contain `init` and `cleanup` and the runtime macros.
- `at_exit` and the mechanism to register exit handlers has been completely removed. In practice this was only used for closing sockets on windows and flushing stdout, which have been moved to `cleanup`.
- <s>On windows `alloc` and `net` initialization is now done in `init`, this saves a runtime check in every allocation and network use.</s>
Duration is used in std to represent a difference between two Instants.
As such, it has to at least contain that span of time in it. However,
Instant can vary by platform. Thus, we should explain the impl of
Duration::MAX is sensitive to these vagaries of the platform.
further split up const_fn feature flag
This continues the work on splitting up `const_fn` into separate feature flags:
* `const_fn_trait_bound` for `const fn` with trait bounds
* `const_fn_unsize` for unsizing coercions in `const fn` (looks like only `dyn` unsizing is still guarded here)
I don't know if there are even any things left that `const_fn` guards... at least libcore and liballoc do not need it any more.
`@oli-obk` are you currently able to do reviews?
Explicitly implement `!Send` and `!Sync` for `sys::{Args, Env}`
Remove the field `_dont_send_or_sync_me: PhantomData<*mut ()>` in favor of an explicit implementation of `!Send` and `!Sync`.
Mention FusedIterator case in Iterator::fuse doc
Using `fuse` on an iterator that incorrectly implements
`FusedIterator` does not fuse the iterator. This commit adds a
note about this in the documentation of this method to increase
awareness about this potential issue (esp. when relying on fuse
in unsafe code).
Closes#83969
implement `TrustedRandomAccess` for `Take` iterator adapter
`TrustedRandomAccess` requires the iterator length to fit within `usize`. `take(n)` only constrains the upper bound of an iterator. So if the inner is `TrustedRandomAccess` (which already implies a finite length) then so can be `Take`.
```````@rustbot``````` label T-libs-impl
Move `sys_common::poison` to `sync::poison`
`sys_common` should not contain publicly exported types, only platform-independent abstractions on top of `sys`, which `sys_common::poison` is not. There is thus no reason for the module to not live under `sync`.
Part of #84187.
Remove duplicated fn(Box<[T]>) -> Vec<T>
`<[T]>::into_vec()` does the same thing as `Vec::from::<Box<[T]>>()`, so they can be implemented in terms of each other. This was the previous implementation of `Vec::from()`, but was changed in #78461. I'm not sure what the rationale was for that change, but it seems preferable to maintain a single implementation.
Improve `Iterator::by_ref` example
I split the example into two: one that fails to compile, and one that
works. I also made them identical except for the addition of `by_ref`
so we don't confuse readers with random differences.
cc `@steveklabnik,` who is the one that added the previous version of this example
Using `fuse` on an iterator that incorrectly implements
`FusedIterator` does not fuse the iterator. This commit adds a
note about this in the documentation of this method to increase
awareness about this potential issue (esp. when relying on fuse
in unsafe code).
Added CharIndices::offset function
The CharIndices iterator has a field internally called front_offset, that I think would be very useful to have access to.
You can already do something like ``char_indices.next().map(|(offset, _)| offset)``, but that is wordy, in addition to not handling the case where the iterator has ended, where you'd want the offset to be equal to the length.
I'm very new to the open source world and the rust repository, so I'm sorry if I missed a step or did something weird.
Improve rebuilding behaviour of BinaryHeap::retain.
This changes `BinaryHeap::retain` such that it doesn't always fully rebuild the heap, but only rebuilds the parts for which that's necessary.
This makes use of the fact that retain gives out `&T`s and not `&mut T`s.
Retaining every element or removing only elements at the end results in no rebuilding at all. Retaining most elements results in only reordering the elements that got moved (those after the first removed element), using the same logic as was already used for `append`.
cc `@KodrAus` `@sfackler` - We briefly discussed this possibility in the meeting last week while we talked about stabilization of this function (#71503).
Rollup of 7 pull requests
Successful merges:
- #84343 (Remove `ScopeTree::closure_tree`)
- #84376 (Uses flex to fix formatting of h1 at any width)
- #84377 (Followup to #83944)
- #84396 (Update LLVM submodule)
- #84402 (Move `sys_common::rwlock::StaticRWLock` etc. to `sys::unix::rwlock`)
- #84404 (Check for intrinsics before coercing to a function pointer)
- #84413 (Remove `sys::args::Args::inner_debug` and use `Debug` instead)
Failed merges:
r? `@ghost`
`@rustbot` modify labels: rollup
Remove `sys::args::Args::inner_debug` and use `Debug` instead
This removes the method `sys::args::Args::inner_debug` on all platforms and implements `Debug` for `Args` instead.
I believe this creates a more natural API for the different platforms under `sys`: export a type `Args: Debug + Iterator + ...` vs. `Args: Iterator + ...` and with a method `inner_debug`.
Move `sys_common::rwlock::StaticRWLock` etc. to `sys::unix::rwlock`
This moves `sys_common::rwlock::StaticRwLock`, `RWLockReadGuard` and `RWLockWriteGuard` to `sys::unix::rwlock`. They are already `#[cfg(unix)]` and don't need to be in `sys_common`.
Implement indexing slices with pairs of core::ops::Bound<usize>
Closes#49976.
I am not sure about code duplication between `check_range` and `into_maybe_range`. Should be former implemented in terms of the latter? Also this PR doesn't address code duplication between `impl SliceIndex for Range*`.
Format `Struct { .. }` on one line even with `{:#?}`.
The result of `debug_struct("A").finish_non_exhaustive()` before this change:
```
A {
..
}
```
And after this change:
```
A { .. }
```
If there's any fields, the result stays unchanged:
```
A {
field: value,
..
}
fix 'const-stable since' for NonZeroU*::new_unchecked
For the unsigned `NonZero` types, `new_unchecked` was const-stable from the start with https://github.com/rust-lang/rust/pull/50808. Fix the docs to accurately reflect that.
I think this `since` is also incorrect:
```rust
#[stable(feature = "from_nonzero", since = "1.31.0")]
impl From<$Ty> for $Int {
```
The signed nonzero types were only stabilized in 1.34, so that `From` impl certainly didn't exist before. But I had enough of digging through git histories after I figured out when `new_unchecked` became const-stable...^^
Replace `Void` in `sys` with never type
This PR replaces several occurrences in `sys` of the type `enum Void {}` with the Rust never type (`!`).
The name `Void` is unfortunate because in other languages (C etc.) it refers to a unit type, not an uninhabited type.
Note that the previous stabilization of the never type was reverted, however all uses here are implementation details and not publicly visible.
Move `sys::vxworks` code to `sys::unix`
Follow-up to #77666, `sys::vxworks` is almost identical to `sys::unix`, the only differences are the `rand`, `thread_local_dtor`, and `process` implementation. Since `vxworks` is `target_family = unix` anyway, there is no reason for the code not to live inside of `sys::unix` like all the other unix-OSes.
e41f378f82/compiler/rustc_target/src/spec/vxworks_base.rs (L12)
``@rustbot`` label: +T-libs-impl
Replace all `fmt.pad` with `debug_struct`
This replaces any occurrence of:
- `f.pad("X")` with `f.debug_struct("X").finish()`
- `f.pad("X { .. }")` with `f.debug_struct("X").finish_non_exhaustive()`
This is in line with existing formatting code such as
1255053067/library/std/src/sync/mpsc/mod.rs (L1470-L1475)
Add `Unsupported` to `std::io::ErrorKind`
I noticed a significant portion of the uses of `ErrorKind::Other` in std is for unsupported operations.
The notion that a specific operation is not available on a target (and will thus never succeed) seems semantically distinct enough from just "an unspecified error occurred", which is why I am proposing to add the variant `Unsupported` to `std::io::ErrorKind`.
**Implementation**:
The following variant will be added to `std::io::ErrorKind`:
```rust
/// This operation is unsupported on this platform.
Unsupported
```
`std::io::ErrorKind::Unsupported` is an error returned when a given operation is not supported on a platform, and will thus never succeed; there is no way for the software to recover. It will be used instead of `Other` where appropriate, e.g. on wasm for file and network operations.
`decode_error_kind` will be updated to decode operating system errors to `Unsupported`:
- Unix and VxWorks: `libc::ENOSYS`
- Windows: `c::ERROR_CALL_NOT_IMPLEMENTED`
- WASI: `wasi::ERRNO_NOSYS`
**Stability**:
This changes the kind of error returned by some functions on some platforms, which I think is not covered by the stability guarantees of the std? User code could depend on this behavior, expecting `ErrorKind::Other`, however the docs already mention:
> Errors that are `Other` now may move to a different or a new `ErrorKind` variant in the future. It is not recommended to match an error against `Other` and to expect any additional characteristics, e.g., a specific `Error::raw_os_error` return value.
The most recent variant added to `ErrorKind` was `UnexpectedEof` in `1.6.0` (almost 5 years ago), but `ErrorKind` is marked as `#[non_exhaustive]` and the docs warn about exhaustively matching on it, so adding a new variant per se should not be a breaking change.
The variant `Unsupported` itself could be marked as `#[unstable]`, however, because this PR also immediately uses this new variant and changes the errors returned by functions I'm inclined to agree with the others in this thread that the variant should be insta-stabilized.
Deprecate the core::raw / std::raw module
It only contains the `TraitObject` struct which exposes components of wide pointer. Pointer metadata APIs are designed to replace this: https://github.com/rust-lang/rust/issues/81513
Add some #[inline(always)] to arithmetic methods of integers
I tried to add it only to methods which return results of intrinsics and don't have any branching.
Branching could made performance of debug builds (`-Copt-level=0`) worse.
Main goal of changes is allowing wider optimizations in `-Copt-level=1`.
Closes: https://github.com/rust-lang/rust/issues/75598
r? `@nagisa`
No compiler changes as part of this -- just new unstable traits and impls thereof.
The goal here is to add the things that aren't going to break anything, to keep the feature implementation simpler in the next PR.
std: Add a variant of thread locals with const init
This commit adds a variant of the `thread_local!` macro as a new
`thread_local_const_init!` macro which requires that the initialization
expression is constant (e.g. could be stuck into a `const` if so
desired). This form of thread local allows for a more efficient
implementation of `LocalKey::with` both if the value has a destructor
and if it doesn't. If the value doesn't have a destructor then `with`
should desugar to exactly as-if you use `#[thread_local]` given
sufficient inlining.
The purpose of this new form of thread locals is to precisely be
equivalent to `#[thread_local]` on platforms where possible for values
which fit the bill (those without destructors). This should help close
the gap in performance between `thread_local!`, which is safe, relative
to `#[thread_local]`, which is not easy to use in a portable fashion.
This commit adds a variant of the `thread_local!` macro as a new
`thread_local_const_init!` macro which requires that the initialization
expression is constant (e.g. could be stuck into a `const` if so
desired). This form of thread local allows for a more efficient
implementation of `LocalKey::with` both if the value has a destructor
and if it doesn't. If the value doesn't have a destructor then `with`
should desugar to exactly as-if you use `#[thread_local]` given
sufficient inlining.
The purpose of this new form of thread locals is to precisely be
equivalent to `#[thread_local]` on platforms where possible for values
which fit the bill (those without destructors). This should help close
the gap in performance between `thread_local!`, which is safe, relative
to `#[thread_local]`, which is not easy to use in a portable fashion.