Add `AsyncFn` family of traits
I'm proposing to add a new family of `async`hronous `Fn`-like traits to the standard library for experimentation purposes.
## Why do we need new traits?
On the user side, it is useful to be able to express `AsyncFn` trait bounds natively via the parenthesized sugar syntax, i.e. `x: impl AsyncFn(&str) -> String` when experimenting with async-closure code.
This also does not preclude `AsyncFn` becoming something else like a trait alias if a more fundamental desugaring (which can take many[^1] different[^2] forms) comes around. I think we should be able to play around with `AsyncFn` well before that, though.
I'm also not proposing stabilization of these trait names any time soon (we may even want to instead express them via new syntax, like `async Fn() -> ..`), but I also don't think we need to introduce an obtuse bikeshedding name, since `AsyncFn` just makes sense.
## The lending problem: why not add a more fundamental primitive of `LendingFn`/`LendingFnMut`?
Firstly, for `async` closures to be as flexible as possible, they must be allowed to return futures which borrow from the async closure's captures. This can be done by introducing `LendingFn`/`LendingFnMut` traits, or (equivalently) by adding a new generic associated type to `FnMut` which allows the return type to capture lifetimes from the `&mut self` argument of the trait. This was proposed in one of [Niko's blog posts](https://smallcultfollowing.com/babysteps/blog/2023/05/09/giving-lending-and-async-closures/).
Upon further experimentation, for the purposes of closure type- and borrow-checking, I've come to the conclusion that it's significantly harder to teach the compiler how to handle *general* lending closures which may borrow from their captures. This is, because unlike `Fn`/`FnMut`, the `LendingFn`/`LendingFnMut` traits don't form a simple "inheritance" hierarchy whose top trait is `FnOnce`.
```mermaid
flowchart LR
Fn
FnMut
FnOnce
LendingFn
LendingFnMut
Fn -- isa --> FnMut
FnMut -- isa --> FnOnce
LendingFn -- isa --> LendingFnMut
Fn -- isa --> LendingFn
FnMut -- isa --> LendingFnMut
```
For example:
```
fn main() {
let s = String::from("hello, world");
let f = move || &s;
let x = f(); // This borrows `f` for some lifetime `'1` and returns `&'1 String`.
```
That trait hierarchy means that in general for "lending" closures, like `f` above, there's not really a meaningful return type for `<typeof(f) as FnOnce>::Output` -- it can't return `&'static str`, for example.
### Special-casing this problem:
By splitting out these traits manually, and making sure that each trait has its own associated future type, we side-step the issue of having to answer the questions of a general `LendingFn`/`LendingFnMut` implementation, since the compiler knows how to generate built-in implementations for first-class constructs like async closures, including the required future types for the (by-move) `AsyncFnOnce` and (by-ref) `AsyncFnMut`/`AsyncFn` trait implementations.
[^1]: For example, with trait transformers, we may eventually be able to write: `trait AsyncFn = async Fn;`
[^2]: For example, via the introduction of a more fundamental "`LendingFn`" trait, plus a [special desugaring with augmented trait aliases](https://rust-lang.zulipchat.com/#narrow/stream/213817-t-lang/topic/Lending.20closures.20and.20Fn*.28.29.20-.3E.20impl.20Trait/near/408471480).
Replacement of #114390: Add new intrinsic `is_var_statically_known` and optimize pow for powers of two
This adds a new intrinsic `is_val_statically_known` that lowers to [``@llvm.is.constant.*`](https://llvm.org/docs/LangRef.html#llvm-is-constant-intrinsic).` It also applies the intrinsic in the int_pow methods to recognize and optimize the idiom `2isize.pow(x)`. See #114390 for more discussion.
While I have extended the scope of the power of two optimization from #114390, I haven't added any new uses for the intrinsic. That can be done in later pull requests.
Note: When testing or using the library, be sure to use `--stage 1` or higher. Otherwise, the intrinsic will be a noop and the doctests will be skipped. If you are trying out edits, you may be interested in [`--keep-stage 0`](https://rustc-dev-guide.rust-lang.org/building/suggested.html#faster-builds-with---keep-stage).
Fixes#47234Resolves#114390
`@Centri3`
Add a new `wasm32-wasi-preview2` target
This is the initial implementation of the MCP https://github.com/rust-lang/compiler-team/issues/694 creating a new tier 3 target `wasm32-wasi-preview2`. That MCP has been seconded and will most likely be approved in a little over a week from now. For more information on the need for this target, please read the [MCP](https://github.com/rust-lang/compiler-team/issues/694).
There is one aspect of this PR that will become insta-stable once these changes reach a stable compiler:
* A new `target_family` named `wasi` is introduced. This target family incorporates all wasi targets including `wasm32-wasi` and its derivative `wasm32-wasi-preview1-threads`. The difference between `target_family = wasi` and `target_os = wasi` will become much clearer when `wasm32-wasi` is renamed to `wasm32-wasi-preview1` and the `target_os` becomes `wasm32-wasi-preview1`. You can read about this target rename in [this MCP](https://github.com/rust-lang/compiler-team/issues/695) which has also been seconded and will hopefully be officially approved soon.
Additional technical details include:
* Both `std::sys::wasi_preview2` and `std::os::wasi_preview2` have been created and mostly use `#[path]` annotations on their submodules to reach into the existing `wasi` (soon to be `wasi_preview1`) modules. Over time the differences between `wasi_preview1` and `wasi_preview2` will grow and most like all `#[path]` based module aliases will fall away.
* Building `wasi-preview2` relies on a [`wasi-sdk`](https://github.com/WebAssembly/wasi-sdk) in the same way that `wasi-preview1` does (one must include a `wasi-root` path in the `Config.toml` pointing to sysroot included in the wasi-sdk). The target should build against [wasi-sdk v21](https://github.com/WebAssembly/wasi-sdk/releases/tag/wasi-sdk-21) without modifications. However, the wasi-sdk itself is growing [preview2 support](https://github.com/WebAssembly/wasi-sdk/pull/370) so this might shift rapidly. We will be following along quickly to make sure that building the target remains possible as the wasi-sdk changes.
* This requires a [patch to libc](https://github.com/rylev/rust-libc/tree/wasm32-wasi-preview2) that we'll need to land in conjunction with this change. Until that patch lands the target won't actually build.
Add `NonZero*::count_ones`
This PR adds the following APIs to the standard library:
```rust
impl NonZero* {
pub const fn count_ones(self) -> NonZeroU32;
}
```
This is potentially interesting, given that `count_ones` can't ever return 0.
r? libs-api
Rollup of 9 pull requests
Successful merges:
- #112806 (Small code improvements in `collect_intra_doc_links.rs`)
- #119766 (Split tait and impl trait in assoc items logic)
- #120139 (Do not normalize closure signature when building `FnOnce` shim)
- #120160 (Manually implement derived `NonZero` traits.)
- #120171 (Fix assume and assert in jump threading)
- #120183 (Add `#[coverage(off)]` to closures introduced by `#[test]` and `#[bench]`)
- #120195 (add several resolution test cases)
- #120259 (Split Diagnostics for Uncommon Codepoints: Add List to Display Characters Involved)
- #120261 (Provide structured suggestion to use trait objects in some cases of `if` arm type divergence)
r? `@ghost`
`@rustbot` modify labels: rollup
Add `#[coverage(off)]` to closures introduced by `#[test]` and `#[bench]`
These closures are an internal implementation detail of the `#[test]` and `#[bench]` attribute macros, so from a user perspective there is no reason to instrument them for coverage.
Skipping them makes coverage reports slightly cleaner, and will also allow other changes to span processing during coverage instrumentation, without having to worry about how they affect the `#[test]` macro.
The `#[coverage(off)]` attribute has no effect when `-Cinstrument-coverage` is not used.
Fixes#120046.
---
Note that this PR has no effect on the user-written function that has the `#[test]` attribute attached to it. That function will still be instrumented as normal.
Manually implement derived `NonZero` traits.
Step 3 as mentioned in https://github.com/rust-lang/rust/pull/100428#pullrequestreview-1767139731.
Manually implement the traits that would cause “borrow of layout constrained field with interior mutability” errors when switching to `NonZero<T>`.
r? ```@dtolnay```
Use `Self` in `NonZero*` implementations.
This slightly reduces the size of the eventual diff when making these generic, since this can be merged independently.
riscv32im-risc0-zkvm-elf: add target
This pull request adds RISC Zero's Zero Knowledge Virtual Machine (zkVM) as a target for rust. The zkVM used to produce proofs of execution of RISC-V ELF binaries. In order to do this, the target will execute the ELF to generate a receipt containing the output of the computation along with a cryptographic seal. This receipt can be verified to ensure the integrity of the computation and its result. This target is implemented as software only; it has no hardware implementation.
## Tier 3 target policy:
Here is a copy of the tier 3 target policy:
> Tier 3 target policy:
>
> At this tier, the Rust project provides no official support for a target, so we
> place minimal requirements on the introduction of targets.
>
> A proposed new tier 3 target must be reviewed and approved by a member of the
> compiler team based on these requirements. The reviewer may choose to gauge
> broader compiler team consensus via a [[Major Change Proposal (MCP)](https://forge.rust-lang.org/compiler/mcp.html)](https://forge.rust-lang.org/compiler/mcp.html).
>
> A proposed target or target-specific patch that substantially changes code
> shared with other targets (not just target-specific code) must be reviewed and
> approved by the appropriate team for that shared code before acceptance.
>
> - A tier 3 target must have a designated developer or developers (the "target
> maintainers") on record to be CCed when issues arise regarding the target.
> (The mechanism to track and CC such developers may evolve over time.)
The maintainers are named in the target description file
> - Targets must use naming consistent with any existing targets; for instance, a
> target for the same CPU or OS as an existing Rust target should use the same
> name for that CPU or OS. Targets should normally use the same names and
> naming conventions as used elsewhere in the broader ecosystem beyond Rust
> (such as in other toolchains), unless they have a very good reason to
> diverge. Changing the name of a target can be highly disruptive, especially
> once the target reaches a higher tier, so getting the name right is important
> even for a tier 3 target.
> - Target names should not introduce undue confusion or ambiguity unless
> absolutely necessary to maintain ecosystem compatibility. For example, if
> the name of the target makes people extremely likely to form incorrect
> beliefs about what it targets, the name should be changed or augmented to
> disambiguate it.
> - If possible, use only letters, numbers, dashes and underscores for the name.
> Periods (`.`) are known to cause issues in Cargo.
>
We understand.
> - Tier 3 targets may have unusual requirements to build or use, but must not
> create legal issues or impose onerous legal terms for the Rust project or for
> Rust developers or users.
> - The target must not introduce license incompatibilities.
We understand and will not introduce incompatibilities. All of our code that we publish is licensed under Apache-2.0.
> - Anything added to the Rust repository must be under the standard Rust license (`MIT OR Apache-2.0`).
We understand. We are open to either license for the Rust repository.
> - The target must not cause the Rust tools or libraries built for any other
> host (even when supporting cross-compilation to the target) to depend
> on any new dependency less permissive than the Rust licensing policy. This
> applies whether the dependency is a Rust crate that would require adding
> new license exceptions (as specified by the `tidy` tool in the
> rust-lang/rust repository), or whether the dependency is a native library
> or binary. In other words, the introduction of the target must not cause a
> user installing or running a version of Rust or the Rust tools to be
> subject to any new license requirements.
We understand. The runtime libraries and the execution environment and software associated with this environment uses `Apache-2.0` so this should not be an issue.
> - Compiling, linking, and emitting functional binaries, libraries, or other
> code for the target (whether hosted on the target itself or cross-compiling
> from another target) must not depend on proprietary (non-FOSS) libraries.
> Host tools built for the target itself may depend on the ordinary runtime
> libraries supplied by the platform and commonly used by other applications
> built for the target, but those libraries must not be required for code
> generation for the target; cross-compilation to the target must not require
> such libraries at all. For instance, `rustc` built for the target may
> depend on a common proprietary C runtime library or console output library,
> but must not depend on a proprietary code generation library or code
> optimization library. Rust's license permits such combinations, but the
> Rust project has no interest in maintaining such combinations within the
> scope of Rust itself, even at tier 3.
We understand. We only depend on FOSS libraries. Dependencies such as runtime libraries for this target are licensed as `Apache-2.0`.
> - "onerous" here is an intentionally subjective term. At a minimum, "onerous"
> legal/licensing terms include but are *not* limited to: non-disclosure
> requirements, non-compete requirements, contributor license agreements
> (CLAs) or equivalent, "non-commercial"/"research-only"/etc terms,
> requirements conditional on the employer or employment of any particular
> Rust developers, revocable terms, any requirements that create liability
> for the Rust project or its developers or users, or any requirements that
> adversely affect the livelihood or prospects of the Rust project or its
> developers or users.
There are no such terms present
> - Neither this policy nor any decisions made regarding targets shall create any
> binding agreement or estoppel by any party. If any member of an approving
> Rust team serves as one of the maintainers of a target, or has any legal or
> employment requirement (explicit or implicit) that might affect their
> decisions regarding a target, they must recuse themselves from any approval
> decisions regarding the target's tier status, though they may otherwise
> participate in discussions.
I am not the reviewer of this pull request
> - This requirement does not prevent part or all of this policy from being
> cited in an explicit contract or work agreement (e.g. to implement or
> maintain support for a target). This requirement exists to ensure that a
> developer or team responsible for reviewing and approving a target does not
> face any legal threats or obligations that would prevent them from freely
> exercising their judgment in such approval, even if such judgment involves
> subjective matters or goes beyond the letter of these requirements.
We understand.
> - Tier 3 targets should attempt to implement as much of the standard libraries
> as possible and appropriate (`core` for most targets, `alloc` for targets
> that can support dynamic memory allocation, `std` for targets with an
> operating system or equivalent layer of system-provided functionality), but
> may leave some code unimplemented (either unavailable or stubbed out as
> appropriate), whether because the target makes it impossible to implement or
> challenging to implement. The authors of pull requests are not obligated to
> avoid calling any portions of the standard library on the basis of a tier 3
> target not implementing those portions.
The target implements core and alloc. And std support is currently experimental as some functionalities in std are either a) not applicable to our target or b) more work in research and experimentation needs to be done. For more information about the characteristics of this target, please refer to the target description file.
> - The target must provide documentation for the Rust community explaining how
> to build for the target, using cross-compilation if possible. If the target
> supports running binaries, or running tests (even if they do not pass), the
> documentation must explain how to run such binaries or tests for the target,
> using emulation if possible or dedicated hardware if necessary.
See file target description file
> - Tier 3 targets must not impose burden on the authors of pull requests, or
> other developers in the community, to maintain the target. In particular,
> do not post comments (automated or manual) on a PR that derail or suggest a
> block on the PR based on a tier 3 target. Do not send automated messages or
> notifications (via any medium, including via ``@`)` to a PR author or others
> involved with a PR regarding a tier 3 target, unless they have opted into
> such messages.
We understand.
> - Backlinks such as those generated by the issue/PR tracker when linking to
> an issue or PR are not considered a violation of this policy, within
> reason. However, such messages (even on a separate repository) must not
> generate notifications to anyone involved with a PR who has not requested
> such notifications.
We understand.
> - Patches adding or updating tier 3 targets must not break any existing tier 2
> or tier 1 target, and must not knowingly break another tier 3 target without
> approval of either the compiler team or the maintainers of the other tier 3
> target.
> - In particular, this may come up when working on closely related targets,
> such as variations of the same architecture with different features. Avoid
> introducing unconditional uses of features that another variation of the
> target may not have; use conditional compilation or runtime detection, as
> appropriate, to let each target run code supported by that target.
We understand.
> If a tier 3 target stops meeting these requirements, or the target maintainers
> no longer have interest or time, or the target shows no signs of activity and
> has not built for some time, or removing the target would improve the quality
> of the Rust codebase, we may post a PR to remove it; any such PR will be CCed
> to the target maintainers (and potentially other people who have previously
> worked on the target), to check potential interest in improving the situation.
We understand.
Use `assert_unchecked` instead of `assume` intrinsic in the standard library
Now that a public wrapper for the `assume` intrinsic exists, we can use it in the standard library.
CC #119131
Revert stabilization of trait_upcasting feature
Reverts #118133
This reverts commit 6d2b84b3ed, reversing changes made to 73bc12199e.
The feature has a soundness bug:
* #120222
It is unclear to me whether we'll actually want to destabilize, but I thought it was still prudent to open the PR for easy destabilization once we get there.
Document `Token{Stream,Tree}::Display` more thoroughly.
To expressly warn against the kind of proc macro implementation that was broken in #119875.
r? ``@petrochenkov``
Consolidate logic around resolving built-in coroutine trait impls
Deduplicates a lot of code. Requires defining a new lang item for `Coroutine::resume` for consistency, but it seems not harmful at worst, and potentially later useful at best.
r? oli-obk
Fix tty detection for msys2's `/dev/ptmx`
Our "true negative" detection assumes that if at least one std handle is a Windows console then no other handle will be a msys2 tty pipe. This turns out to be a faulty assumption in the case of redirection to `/dev/ptmx` in an msys2 shell. Maybe this is an msys2 bug but in any case we should try to make it work.
An alternative to this would be to replace the "true negative" detection with an attempt to detect if we're in an msys environment (e.g. by sniffing environment variables) but that seems like it'd be flaky too.
Fixes#119658
Rollup of 10 pull requests
Successful merges:
- #117910 (Refactor uses of `objc_msgSend` to no longer have clashing definitions)
- #118639 (Undeprecate lint `unstable_features` and make use of it in the compiler)
- #119801 (Fix deallocation with wrong allocator in (A)Rc::from_box_in)
- #120058 (bootstrap: improvements for compiler builds)
- #120059 (Make generic const type mismatches not hide trait impls from the trait solver)
- #120097 (Report unreachable subpatterns consistently)
- #120137 (Validate AggregateKind types in MIR)
- #120164 (`maybe_lint_impl_trait`: separate `is_downgradable` from `is_object_safe`)
- #120181 (Allow any `const` expression blocks in `thread_local!`)
- #120218 (rustfmt: Check that a token can begin a nonterminal kind before parsing it as a macro arg)
r? `@ghost`
`@rustbot` modify labels: rollup
Co-authored-by: Frank Laub <flaub@risc0.com>
Co-authored-by: nils <nils@risc0.com>
Co-authored-by: Victor Graf <victor@risczero.com>
Co-authored-by: weikengchen <w.k@berkeley.edu>
This also adds changes in the rust test suite in order to get a few of them to
pass.
Co-authored-by: Frank Laub <flaub@risc0.com>
Co-authored-by: Urgau <3616612+Urgau@users.noreply.github.com>
Allow any `const` expression blocks in `thread_local!`
This PR contains a rebase of the macro change from #116392, together with adding a test under library/std/tests.
Testing this feature by making the documentation's example code needlessly more complicated was not appropriate as pointed out in https://github.com/rust-lang/rust/pull/116392#pullrequestreview-1753097757.
Without the macro change, this new test would fail to build as follows:
```console
error: no rules expected the token `let`
--> library/std/tests/thread.rs:26:13
|
26 | let value = 1;
| ^^^ no rules expected this token in macro call
|
note: while trying to match meta-variable `$init:expr`
--> library/std/src/thread/local.rs:189:69
|
189 | ($(#[$attr:meta])* $vis:vis static $name:ident: $t:ty = const { $init:expr }; $($rest:tt)*) => (
| ^^^^^^^^^^
```
Closes#116392.
Fix deallocation with wrong allocator in (A)Rc::from_box_in
Deallocate the `Box` with the original allocator (via `&A`), not `Global`.
Fixes#119749
<details> <summary>Example code with error and Miri output</summary>
(Note that this UB is not observable on stable, because the only usable allocator on stable is `Global` anyway.)
Code ([playground link](https://play.rust-lang.org/?version=nightly&mode=debug&edition=2021&gist=96193c2c6a1912d7f669fbbe39174b09)):
```rs
#![feature(allocator_api)]
use std::alloc::System;
// uncomment one of these
use std::rc::Rc;
//use std::sync::Arc as Rc;
fn main() {
let x: Box<[u32], System> = Box::new_in([1,2,3], System);
let _: Rc<[u32], System> = Rc::from(x);
}
```
Miri output:
```rs
error: Undefined Behavior: deallocating alloc904, which is C heap memory, using Rust heap deallocation operation
--> /playground/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/alloc.rs:117:14
|
117 | unsafe { __rust_dealloc(ptr, layout.size(), layout.align()) }
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ deallocating alloc904, which is C heap memory, using Rust heap deallocation operation
|
= help: this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior
= help: see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information
= note: BACKTRACE:
= note: inside `std::alloc::dealloc` at /playground/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/alloc.rs:117:14: 117:64
= note: inside `<std::alloc::Global as std::alloc::Allocator>::deallocate` at /playground/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/alloc.rs:254:22: 254:51
= note: inside `<std::boxed::Box<std::mem::ManuallyDrop<[u32]>> as std::ops::Drop>::drop` at /playground/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/boxed.rs:1244:17: 1244:66
= note: inside `std::ptr::drop_in_place::<std::boxed::Box<std::mem::ManuallyDrop<[u32]>>> - shim(Some(std::boxed::Box<std::mem::ManuallyDrop<[u32]>>))` at /playground/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/ptr/mod.rs:507:1: 507:56
= note: inside `std::mem::drop::<std::boxed::Box<std::mem::ManuallyDrop<[u32]>>>` at /playground/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/mem/mod.rs:992:24: 992:25
= note: inside `std::rc::Rc::<[u32], std::alloc::System>::from_box_in` at /playground/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/rc.rs:1928:13: 1928:22
= note: inside `<std::rc::Rc<[u32], std::alloc::System> as std::convert::From<std::boxed::Box<[u32], std::alloc::System>>>::from` at /playground/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/rc.rs:2504:9: 2504:27
note: inside `main`
--> src/main.rs:10:32
|
10 | let _: Rc<[u32], System> = Rc::from(x);
| ^^^^^^^^^^^
note: some details are omitted, run with `MIRIFLAGS=-Zmiri-backtrace=full` for a verbose backtrace
error: aborting due to 1 previous error
```
</details>
Refactor uses of `objc_msgSend` to no longer have clashing definitions
This is very similar to what Apple's own headers encourage you to do (cast the function pointer before use instead of making new declarations).
Additionally, I'm documenting a few of the memory management rules we're following, ensuring that the `args` function doesn't leak memory (if you wrap it in an autorelease pool).
Motivation is to avoid issues with clashing definitions, like described in https://github.com/rust-lang/rust/issues/12707#issuecomment-1570735643 and https://github.com/rust-lang/rust/issues/46188#issuecomment-1288058453, CC ``@bjorn3.``
std::net: bind update for using backlog as `-1` too.
Albeit not documented, macOs also support negative value for the backlog argument.
ref: 2ff845c2e0/bsd/kern/uipc_socket.c (L1061)
xous: misc fixes + add network support
This patchset makes several fixes to Xous support. Additionally, this patch adds networking support.
Many of these fixes are the result of the recent patch to get `unwinding` support merged. As a result of this patch, we can now run rust tests. As a result of these tests, we now have 729 tests passing:
```
failures:
env::tests::test
env::tests::test_self_exe_path
env::tests::vars_debug
env::tests::vars_os_debug
os::raw::tests::same
path::tests::test_push
path::tests::test_set_file_name
time::tests::since_epoch
test result: FAILED. 729 passed; 8 failed; 1 ignored; 0 measured; 0 filtered out; finished in 214.54s
```
In the course of fixing several tests and getting the test sequence to reliably run, several issues were found. This patchset fixes those issues.
Our "true negative" detection assumes that if at least one std handle is a Windows console then no other handle will be a msys2 tty pipe. This turns out to be a faulty assumption in the case of `/dev/ptmx`.
Rollup of 9 pull requests
Successful merges:
- #118714 ( Explanation that fields are being used when deriving `(Partial)Ord` on enums)
- #119710 (Improve `let_underscore_lock`)
- #119726 (Tweak Library Integer Division Docs)
- #119746 (rustdoc: hide modals when resizing the sidebar)
- #119986 (Fix error counting)
- #120194 (Shorten `#[must_use]` Diagnostic Message for `Option::is_none`)
- #120200 (Correct the anchor of an URL in an error message)
- #120203 (Replace `#!/bin/bash` with `#!/usr/bin/env bash` in rust-installer tests)
- #120212 (Give nnethercote more reviews)
r? `@ghost`
`@rustbot` modify labels: rollup
Shorten `#[must_use]` Diagnostic Message for `Option::is_none`
This shortens the `#[must_use]` diagnostics displayed, in light of the [review comment](https://github.com/rust-lang/rust/pull/62431/files#r300819839) on when this was originally added.
Tweak Library Integer Division Docs
Improved the documentation and diagnostics related to panicking in the division-like methods in std:
* For signed methods that can overflow, clarified "results in overflow" to "self is -1 and rhs is Self::MIN." This is more concise than saying "results in overflow" and then explaining how it could overflow.
* For floor/ceil_div, corrected the documentation and made it more like the documentation in other methods.
* For signed methods that can overflow, explicitly mention that they are not affected by compiler flags.
* Removed all unused rustc_inherit_overflow_checks attributes. The non-division-like operations will never overflow.
* Added track_caller attributes to all methods that can panic. The panic messages will always be correct. For example, division methods all have / before %.
* Edited the saturating_div documentation to be consistent with similar methods.
Explanation that fields are being used when deriving `(Partial)Ord` on enums
When deriving `std::cmp::Ord` or `std::cmp::PartialOrd` on enums, their fields are compared if the variants are equal.
This means that the last assertion in the following snipped panics.
```rust
use std::cmp::{PartialEq, Eq, PartialOrd, Ord};
#[derive(PartialEq, Eq, PartialOrd, Ord)]
enum Sizes {
Small(usize),
Big(usize),
}
fn main() {
let a = Sizes::Big(3);
let b = Sizes::Big(5);
let c = Sizes::Small(10);
assert!( c < a);
assert_eq!(a, c);
}
```
This is more often expected behavior than not, and can be easily circumvented, as discussed in [this thread](https://users.rust-lang.org/t/how-to-sort-enum-variants/52291/4).
But it is addressed nowhere in the documentation, yet.
So I stumbled across this, as I personally did not expect fields being used in `PartialOrd`.
I added the explanation to the documentation.
Add `#[track_caller]` to the "From implies Into" impl
This pr implements what was mentioned in https://github.com/rust-lang/rust/issues/77474#issuecomment-1074480790
This follows from my URLO https://users.rust-lang.org/t/104497
```rust
#![allow(warnings)]
fn main() {
// Gives a good location
let _: Result<(), Loc> = dbg!(Err::<(), _>(()).map_err(|e| e.into()));
// still doesn't work, gives location of `FnOnce::call_once()`
let _: Result<(), Loc> = dbg!(Err::<(), _>(()).map_err(Into::into));
}
#[derive(Debug)]
pub struct Loc {
pub l: &'static std::panic::Location<'static>,
}
impl From<()> for Loc {
#[track_caller]
fn from(_: ()) -> Self {
Loc {
l: std::panic::Location::caller(),
}
}
}
```
Document some alternatives to `Vec::split_off`
One of the discussion points that came up in #119917 is that some people use `Vec::split_off` in cases where they probably shouldn't, because the alternatives (like `mem::take`) are hard to discover.
This PR adds some suggestions to the documentation of `split_off` that should point people towards alternatives that might be more appropriate for their use-case.
I've deliberately tried to keep these changes as simple and uncontroversial as possible, so that they don't depend on how the team decides to handle the concerns raised in #119917. That's why I haven't touched the existing documentation for `split_off`, and haven't added links to `split_off` to the documentation of other methods.
fix: Drop guard was deallocating with the incorrect size
InPlaceDstBufDrop holds onto the allocation before the shrinking happens which means it must deallocate the destination elements but the source allocation.
Thanks `@cuviper` for spotting this.