Readd track_caller to Result::from_residual
This is a followup on https://github.com/rust-lang/rust/issues/87401 in and an attempt to move the issue towards resolution.
As part of the overhaul of the Try trait we removed the ability for errors to grab location information during propagation via `?` with the builtin `std::result::Result`. The previously linked issue has a fair bit of discussion into the reasons for and against the usage of `#[track_caller]` on the `FromResidual` impl on `Result` that I will do my best to summarize.
---
### For
- https://github.com/rust-lang/rust/issues/87401#issuecomment-915053533: Difficulties with using non `std::result::Result` like types
- https://github.com/rust-lang/rust/issues/87401#issuecomment-978355102: Inconsistency with functionality provided for recoverable (Result) and non-recoverable errors (panic), where panic provides a location and Result does not, pushing some users towards using panic
### Against
- https://github.com/rust-lang/rust/issues/84277#issuecomment-885322833: concern that this will bloat callers that never use this data
---
Personally, I want to quantify the performance / bloat impact of re-adding this attribute, and fully evaluate the pros and cons before deciding if I need to switch `eyre` to have a custom `Result` type, which would also mean I need `try_trait_v2` to be stabilized, cc `@scottmcm.` If the performance impact is minor enough in the general case I think I would prefer that the default `Result` type has the ability to track location information for consistency with `panic` error reporting, and leave it to applications that need particularly high performance to handle the micro optimizations of introducing their own efficient custom Result type or matching manually.
Alternatively, I wonder if the performance penalty on code that doesn't use the location information on `FromResidual` could be mitigated via new optimizations.
Stabilize `iter::zip`
Hello all!
As the tracking issue (#83574) for `iter::zip` completed the final commenting period without any concerns being raised, I hereby submit this stabilization PR on the issue.
As the pull request that introduced the feature (#82917) states, the `iter::zip` function is a shorter way to zip two iterators. As it's generally a quality-of-life/ergonomic improvement, it has been integrated into the codebase without any trouble, and has been
used in many places across the rust compiler and standard library since March without any issues.
For more details, I would refer to `@cuviper's` original PR, or the [function's documentation](https://doc.rust-lang.org/std/iter/fn.zip.html).
Tweak errors coming from `for`-loop, `?` and `.await` desugaring
* Suggest removal of `.await` on non-`Future` expression
* Keep track of obligations introduced by desugaring
* Remove span pointing at method for obligation errors coming from desugaring
* Point at called local sync `fn` and suggest making it `async`
```
error[E0277]: `()` is not a future
--> $DIR/unnecessary-await.rs:9:10
|
LL | boo().await;
| -----^^^^^^ `()` is not a future
| |
| this call returns `()`
|
= help: the trait `Future` is not implemented for `()`
help: do not `.await` the expression
|
LL - boo().await;
LL + boo();
|
help: alternatively, consider making `fn boo` asynchronous
|
LL | async fn boo () {}
| +++++
```
Fix#66731.
Stabilize asm! and global_asm!
Tracking issue: #72016
It's been almost 2 years since the original [RFC](https://github.com/rust-lang/rfcs/pull/2850) was posted and we're finally ready to stabilize this feature!
The main changes in this PR are:
- Removing `asm!` and `global_asm!` from the prelude as per the decision in #87228.
- Stabilizing the `asm` and `global_asm` features.
- Removing the unstable book pages for `asm` and `global_asm`. The contents are moved to the [reference](https://github.com/rust-lang/reference/pull/1105) and [rust by example](https://github.com/rust-lang/rust-by-example/pull/1483).
- All links to these pages have been removed to satisfy the link checker. In a later PR these will be replaced with links to the reference or rust by example.
- Removing the automatic suggestion for using `llvm_asm!` instead of `asm!` if you're still using the old syntax, since it doesn't work anymore with `asm!` no longer being in the prelude. This only affects code that predates the old LLVM-style `asm!` being renamed to `llvm_asm!`.
- Updating `stdarch` and `compiler-builtins`.
- Updating all the tests.
r? `@joshtriplett`
This'll still go via slices eventually for large arrays, but this way slice comparisons to short arrays can use the same memcmp-avoidance tricks.
Added some tests for all the combinations to make sure I didn't accidentally infinitely-recurse something.
Make split_inclusive() on an empty slice yield an empty output
`[].split_inclusive()` currently yields a single, empty slice. That's
different from `"".split_inslusive()`, which yields no output at
all. I think that makes the slice version harder to use.
The case where I ran into this bug was when writing code for
generating a diff between two slices of bytes. I wanted to prefix
removed lines with "-" and a added lines with "+". Due to
`split_inclusive()`'s current behavior, that means that my code prints
just a "-" or "+" for empty files. I suspect most existing callers
have similar "bugs" (which would be fixed by this patch).
Closes#89716.
add BinaryHeap::try_reserve and BinaryHeap::try_reserve_exact
`try_reserve` of many collections were stablized in https://github.com/rust-lang/rust/pull/87993 in 1.57.0. Add `try_reserve` for the rest collections such as `BinaryHeap` should be not controversial.
Use spare_capacity_mut instead of invalid unchecked indexing when joining str
This is a fix for https://github.com/rust-lang/rust/issues/91574
I think in general I'd prefer to see this code implemented with raw pointers or `MaybeUninit::write_slice`, but there's existing code in here based on copying from slice to slice, so converting everything from `&[T]` to `&[MaybeUninit<T>]` is less disruptive.
BTree: improve public descriptions and comments
BTreeSet has always used the term "value" next to and meaning the same thing as "elements" (in the mathematical sense but also used for key-value pairs in BTreeMap), while in the BTreeMap sense these "values" are known as "keys" and definitely not "values". Today I had enough of that.
r? `@Mark-Simulacrum`
Stabilize `ControlFlow::{is_break, is_continue}`
The type itself was stabilized in 1.55, but using it is not ergonomic without these helper functions. Stabilize them.
r? rust-lang/libs-api
They are also removed from the prelude as per the decision in
https://github.com/rust-lang/rust/issues/87228.
stdarch and compiler-builtins are updated to work with the new, stable
asm! and global_asm! macros.
Btree: assert more API compatibility
Introducing a member such as `BTreeSet::min()` would silently break compatibility if no code calls the existing `BTreeSet::min(set)`. `BTreeSet` is the only btree class silently bringing in stable members, apart from many occurrences of `#[derive(Debug)]` on iterators.
r? `@Mark-Simulacrum`
Make certain panicky stdlib functions behave better under panic_immediate_abort
The stdlib has a `panic_immediate_abort` feature that turns panics into immediate aborts, without any formatting/display logic. This feature was [introduced](https://github.com/rust-lang/rust/pull/55011) primarily for codesize-constrained situations.
Unfortunately, this win doesn't quite propagate to `Result::expect()` and `Result::unwrap()`, while the formatting machinery is reduced, `expect()` and `unwrap()` both call `unwrap_failed("msg", &err)` which has a signature of `fn unwrap_failed(msg: &str, error: &dyn fmt::Debug)` and is `#[inline(never)]`. This means that `unwrap_failed` will unconditionally construct a `dyn Debug` trait object even though the object is never used in the function.
Constructing a trait object (even if you never call a method on it!) forces rust to include the vtable and any dependencies. This means that in `panic_immediate_abort` mode, calling expect/unwrap on a Result will pull in a whole bunch of formatting code for the error type even if it's completely unused.
This PR swaps out the function with one that won't require a trait object such that it won't force the inclusion of vtables in the code. It also gates off `#[inline(never)]` in a bunch of other places where allowing the inlining of an abort may be useful (this kind of thing is already done elsewhere in the stdlib).
I don't know how to write a test for this; we don't really seem to have any tests for `panic_immediate_abort` anyway so perhaps it's fine as is.
Minor improvements to `future::join!`'s implementation
This is a follow-up from #91645, regarding [some remarks I made](https://rust-lang.zulipchat.com/#narrow/stream/187312-wg-async-foundations/topic/join!/near/264293660).
Mainly:
- it hides the recursive munching through a private `macro`, to avoid leaking such details (a corollary is getting rid of the need to use ``@`` to disambiguate);
- it uses a `match` binding, _outside_ the `async move` block, to better match the semantics from function-like syntax;
- it pre-pins the future before calling into `poll_fn`, since `poll_fn`, alone, cannot guarantee that its capture does not move (to clarify: I believe the previous code was sound, thanks to the outer layer of `async`. But I find it clearer / more robust to refactorings this way 🙂).
- it uses `@ibraheemdev's` very neat `.ready()?`;
- it renames `Took` to `Taken` for consistency with `Done` (tiny nit 😄).
~~TODO~~Done:
- [x] Add unit tests to enforce the function-like `:value` semantics are respected.
r? `@nrc`
Add spin_loop hint for RISC-V architecture
This commit uses the PAUSE instruction (https://github.com/rust-lang/stdarch/pull/1262) to implement RISC-V spin loop, and updates `stdarch` submodule to use the merged PAUSE instruction.
Rollup of 11 pull requests
Successful merges:
- #91668 (Remove the match on `ErrorKind::Other`)
- #91678 (Add tests fixed by #90023)
- #91679 (Move core/stream/stream/mod.rs to core/stream/stream.rs)
- #91681 (fix typo in `intrinsics::raw_eq` docs)
- #91686 (Fix `Vec::reserve_exact` documentation)
- #91697 (Delete Utf8Lossy::from_str)
- #91706 (Add unstable book entries for parts of asm that are not being stabilized)
- #91709 (Replace iterator-based set construction by *Set::From<[T; N]>)
- #91716 (Improve x.py logging and defaults a bit more)
- #91747 (Add pierwill to .mailmap)
- #91755 (Fix since attribute for const_linked_list_new feature)
Failed merges:
r? `@ghost`
`@rustbot` modify labels: rollup
Replace iterator-based set construction by *Set::From<[T; N]>
This uses the array-based construction for `BtreeSet`s and `HashSet`s instead of first creating an iterator. I could also replace the `let mut a = Set::new(); a.insert(...);` fragments if desired.
Delete Utf8Lossy::from_str
This whole type is marked as being for str internals only, but this constructor is never used by str internals. If you had a &str already and wanted to lossy display it or iterate its lossy utf8 chunks, you would simply not use Utf8Lossy because the whole &str is known to be one contiguous valid utf8 chunk.
If code really does need to obtain a value of type &Utf8Lossy somewhere, and has only a &str, `Utf8Lossy::from_bytes(s.as_bytes())` remains available. As currently implemented, there is no performance penalty relative to `from_str` i.e. the Utf8Lossy does not "remember" that it was constructed using `from_str` to bypass later utf8 decoding.
Fix `Vec::reserve_exact` documentation
The documentation previously said the new capacity cannot overflow `usize`, but in fact it cannot exceed `isize::MAX`.
Update documentation to use `from()` to initialize `HashMap`s and `BTreeMap`s
As of Rust 1.56, `HashMap` and `BTreeMap` both have associated `from()` functions. I think using these in the documentation cleans things up a bit. It allows us to remove some of the `mut`s and avoids the Initialize-Then-Modify anti-pattern.
adjust const_eval_select documentation
"The Rust compiler assumes" indicates that this is language UB, but [I don't think that is a good idea](https://rust-lang.zulipchat.com/#narrow/stream/146212-t-compiler.2Fconst-eval/topic/const_eval_select.20assumptions). This UB would be very hard to test for and looks like a way-too-big footgun. ``@oli-obk`` suggested this is meant to be more like "library UB", so I tried to adjust the docs accordingly.
I also removed all references to "referential transparency". That is a rather vague concept used to mean many different things, and I honestly have no idea what exactly is meant by it in this specific instance. But I assume ``@fee1-dead`` had in their mind a property that all `const fn` code upholds, so by demanding that the runtime code and the const-time code are *observably equivalent*, whatever that property is would also be enforced here.
Cc ``@rust-lang/wg-const-eval``
Fix incorrect stability attributes
These two instances were caught in #90356, but that PR isn't going to be merged. I've extracted these to ensure it's still correct.
``@rustbot`` label: +A-stability +C-cleanup +S-waiting-on-review
This is a follow-up from #91645, regarding [some remarks I made](https://rust-lang.zulipchat.com/#narrow/stream/187312-wg-async-foundations/topic/join!/near/264293660).
Mainly:
- it hides the recursive munching through a private `macro`, to avoid leaking such details (a corollary is getting rid of the need to use `@` to disambiguate);
- it uses a `match` binding, _outside_ the `async move` block, to better match the semantics from function-like syntax;
- it pre-pins the future before calling into `poll_fn`, since `poll_fn`, alone, cannot guarantee that its capture does not move;
- it uses `.ready()?` since it's such a neat pattern;
- it renames `Took` to `Taken` for consistency with `Done`.
replace vec::Drain drop loops with drop_in_place
The `Drain::drop` implementation came up in https://github.com/rust-lang/rust/pull/82185#issuecomment-789584796 as potentially interfering with other optimization work due its widespread use somewhere in `println!`
`@rustbot` label T-libs-impl
Implement most of RFC 2930, providing the ReadBuf abstraction
This replaces the `Initializer` abstraction for permitting reading into uninitialized buffers, closing #42788.
This leaves several APIs described in the RFC out of scope for the initial implementation:
* read_buf_vectored
* `ReadBufs`
Closes#42788, by removing the relevant APIs.
Rollup of 6 pull requests
Successful merges:
- #87599 (Implement concat_bytes!)
- #89999 (Update std::env::temp_dir to use GetTempPath2 on Windows when available.)
- #90796 (Remove the reg_thumb register class for asm! on ARM)
- #91042 (Use Vec extend instead of repeated pushes on several places)
- #91634 (Do not attempt to suggest help for overly malformed struct/function call)
- #91685 (Install llvm tools to sysroot when assembling local toolchain)
Failed merges:
r? `@ghost`
`@rustbot` modify labels: rollup
Update std::env::temp_dir to use GetTempPath2 on Windows when available.
As a security measure, Windows 11 introduces a new temporary directory API, GetTempPath2.
When the calling process is running as SYSTEM, a separate temporary directory
will be returned inaccessible to non-SYSTEM processes. For non-SYSTEM processes
the behavior will be the same as before.
This can help mitigate against attacks such as this one:
https://medium.com/csis-techblog/cve-2020-1088-yet-another-arbitrary-delete-eop-a00b97d8c3e2
Compatibility risk: Software which relies on temporary files to communicate between SYSTEM and non-SYSTEM
processes may be affected by this change. In many cases, such patterns may be vulnerable to the very
attacks the new API was introduced to harden against.
I'm unclear on the Rust project's tolerance for such change-of-behavior in the standard library. If anything,
this PR is meant to raise awareness of the issue and hopefully start the conversation.
How tested: Taking the example code from the documentation and running it through psexec (from SysInternals) on
Win10 and Win11.
On Win10:
C:\test>psexec -s C:\test\main.exe
<...>
Temporary directory: C:\WINDOWS\TEMP\
On Win11:
C:\test>psexec -s C:\test\main.exe
<...>
Temporary directory: C:\Windows\SystemTemp\
Implement concat_bytes!
This implements the unstable `concat_bytes!` macro, which has tracking issue #87555. It can be used like:
```rust
#![feature(concat_bytes)]
fn main() {
assert_eq!(concat_bytes!(), &[]);
assert_eq!(concat_bytes!(b'A', b"BC", [68, b'E', 70]), b"ABCDEF");
}
```
If strings or characters are used where byte strings or byte characters are required, it suggests adding a `b` prefix. If a number is used outside of an array it suggests arrayifying it. If a boolean is used it suggests replacing it with the numeric value of that number. Doubly nested arrays of bytes are disallowed.