Fix ntdll linkage issues on Windows UWP platforms
See discussion: https://github.com/rust-lang/rust/issues/112265#issuecomment-1575479683
Static loading `ntdll` functions does not work for UWP programs, which will end up link errors complaining about missing symbols, or failure to pass the WACK tests. The breakage was introduced in #108262.
This PR basically reverts part of the changes in #108262 for UWP only, and fixes some lint suggestions.
Uplift `clippy::cmp_nan` lint
This PR aims at uplifting the `clippy::cmp_nan` lint into rustc.
## `invalid_nan_comparisons`
~~(deny-by-default)~~ (warn-by-default)
The `invalid_nan_comparisons` lint checks comparison with `f32::NAN` or `f64::NAN` as one of the operand.
### Example
```rust,compile_fail
let a = 2.3f32;
if a == f32::NAN {}
```
### Explanation
NaN does not compare meaningfully to anything – not even itself – so those comparisons are always false.
-----
Mostly followed the instructions for uplifting a clippy lint described here: https://github.com/rust-lang/rust/pull/99696#pullrequestreview-1134072751
`@rustbot` label: +I-lang-nominated
r? compiler
Rollup of 3 pull requests
Successful merges:
- #112260 (Improve document of `unsafe_code` lint)
- #112429 ([rustdoc] List matching impls on type aliases)
- #112442 (Deduplicate identical region constraints in new solver)
r? `@ghost`
`@rustbot` modify labels: rollup
Uplift `clippy::undropped_manually_drops` lint
This PR aims at uplifting the `clippy::undropped_manually_drops` lint.
## `undropped_manually_drops`
(warn-by-default)
The `undropped_manually_drops` lint check for calls to `std::mem::drop` with a value of `std::mem::ManuallyDrop` which doesn't drop.
### Example
```rust
struct S;
drop(std::mem::ManuallyDrop::new(S));
```
### Explanation
`ManuallyDrop` does not drop it's inner value so calling `std::mem::drop` will not drop the inner value of the `ManuallyDrop` either.
-----
Mostly followed the instructions for uplifting an clippy lint described here: https://github.com/rust-lang/rust/pull/99696#pullrequestreview-1134072751
`@rustbot` label: +I-lang-nominated
r? compiler
-----
For Clippy:
changelog: Moves: Uplifted `clippy::undropped_manually_drops` into rustc
Avoid unwind across `extern "C"` in `thread_local::fast_local`
This is a minimal fix for #112285, in case we want a simple patch that can be easily to backported if that's desirable.
*(Note: I have another broader cleanup which I've mostly omitted from here to avoid clutter, except for the `Cell` change, which isn't needed to fix UB, but simplifies safety comments).*
The only tier-1 target that this occurs on in a way that seems likely to cause problems in practice linux-gnu, although I believe some folks care about that platform somewhat 😉. I'm unsure how big of an issue this is. I've seen stuff like this behave quite badly, but there's a number of reasons to think this might actually be "fine in practice".
I've hedged my bets and assumed we'll backport this at least to beta but my feeling is that there's not enough evidence this is a problem worth backporting further than that.
### More details
This issue seems to have existed since `thread_local!`'s `const` init functionality was added. It occurs if you have a `const`-initialized thread local for a type that `needs_drop`, the drop panics, and you're on a target with support for static thread locals. In this case, we will end up defining an `extern "C"` function in the user crate rather than in libstd, and because the user crate will not have `#![feature(c_unwind)]` enabled, their panic will not be caught by an auto-inserted abort guard.
In practice, the actual situation where problems are likely[^ub] is somewhat narrower.
On most targets with static thread locals, we manage the TLS dtor list by hand (for reentrancy reasons among others). In these cases, while the users code may panic, we're calling it inside our own `extern "C"` (or `extern "system"`) function, which seems to (at least in practice) catch the panic and convert it to an abort.
However, on a few targets, most notably linux-gnu with recent glibc (but also fuchsia and redox), a tls dtor registration mechanism exists which we can actually use directly, [`__cxa_thread_atexit_impl`](https://github.com/rust-lang/rust/blob/master/library/std/src/sys/unix/thread_local_dtor.rs#L26-L36).
This is the case that seems most likely to be a cause for concern, as now we're passing a function to the system library and panicking out of it in a case where there are may not be Rust frames above it on the call stack (since it's running thread shutdown), and even if there were, it may not be prepared to handle such unwinding. If that's the case, it'd be bad.
Is it? Dunno. The fact that it's a `__cxa_*` function makes me think they probably have considered that the callback could throw but I have no evidence here and it doesn't seem to be written down anywhere, so it's just a guess. (I would not be surprised if someone comes into this thread to tell me how definitely-bad-news it is).
That said, as I said, all this is actually UB! If this isn't a "technically UB but fine in practice", but all bets are off if this is the kind of thing we are telling LLVM about.
[^ub]: This is UB so take that with a grain of salt -- I'm absolutely making assumptions about how the UB will behave "in practice" here, which is almost certainly a mistake.
Add `task::Waker::noop`
I have found myself reimplementing this function many times when I need a `Context` but don't have a runtime or `futures` to hand.
Prior art: [`futures::task::noop_waker`](https://docs.rs/futures/0.3/futures/task/fn.noop_waker.html) and [`futures::task::noop_waker_ref`](https://docs.rs/futures/0.3/futures/task/fn.noop_waker_ref.html)
Tracking issue: https://github.com/rust-lang/rust/issues/98286
Unresolved questions:
1. Should we also add `RawWaker::noop()`? (I don't think so, I can't think of a use case for it)
2. Should we also add `Context::noop()`? Depending on the future direction `Context` goes a "noop context" might not even make sense in future.
3. Should it be an associated constant instead? That would allow for `let cx = &mut Context::from_waker(&Waker::NOOP);` to work on one line which is pretty nice. I don't really know what the guideline is here.
r? rust-lang/libs-api `@rustbot` label +T-libs-api -T-libs
Improved std support for ps vita target
Fixed a couple of things in std support for ps vita via Vita SDK newlib oss implementation:
- Added missing hardware features to target spec
- Compile in thumb by default (newlib is also compiled in thumb)
- Fixed fs calls. Vita newlib has a not-very-posix dirent. Also vita does not expose inodes, it's stubbed as 0 in stat, and I'm stubbing it here for dirent (because vita newlibs's dirent doesn't even have that field)
- Enabled signal handlers for panic unwinding
- Dropped static link requirement from the platform support md. Also, rearranged sections to better stick with the template.
After the socket ancillary data implementation was introduced, the
build was broken on FreeBSD, add the same workaround as for the
existing implementations.
Remove ExtendElement, ExtendWith, extend_with
Related to #104624, broken up into two commits. The first removes wrapper trait ExtendWith and its only implementer struct ExtendElement. The second may have perf issues so may be reverted/removed if no alternate fix is found; it should be profiled.
r? `@scottmcm`
- Switch TypeId to 128 bits
- Hack around the fact that tracing-subscriber dislikes how TypeId is hashed
- Remove lowering of type_id128 from rustc_codegen_llvm
- Remove unnecessary `type_id128` intrinsic (just change return type of `type_id`)
- Only hash the lower 64 bits of the TypeId
- Reword comment
add `#[doc(alias="flatmap")]` to `Option::and_then`
I keep forgetting that rust calls this `and_then` and trying to search for `flatmap`. `and_then`'s docs even mention "Some languages call this operation flatmap", but it doesn't show up as a result in the search at `https://doc.rust-lang.org/std/?search=flatmap`
Option::map_or_else: Show an example of integrating with Result
Moving this from https://github.com/rust-lang/libs-team/issues/59 where an API addition was rejected. But I think it's valuable to add this example to the documentation at least.
QNX Neutrino: exponential backoff when fork/spawn needs a retry
Fixes#108594: When retrying, sleep with an exponential duration. When sleep duration is lower than minimum possible sleeping time, yield instead (this will not be often due to the exponential increase of duration).
Minimum possible sleeping time is determined using `libc::clock_getres` but only when spawn/fork failed the first time in a request. This is cached using a LazyLock.
CC `@gh-tr`
r? `@workingjubilee`
`@rustbot` label +O-neutrino
use c literals in compiler and library
Use c literals #108801 in compiler and library
currently blocked on:
* <strike>rustfmt: don't know how to format c literals</strike> nope, nightly one works.
* <strike>bootstrap</strike>
r? `@ghost`
`@rustbot` blocked
Require that const param tys implement `ConstParamTy`
1. Require that const param tys implement `ConstParamTy` instead of using `search_for_adt_const_param_violation`
2. Add `StructuralPartialEq` as a supertrait for `ConstParamTy`, since we need to make sure that we derive *both* `PartialEq` and `Eq`
3. Implement `ConstParamTy` for tuples up to 12 (or whatever the default for tuples is)
4. Add some custom diagnostics to `ConstParamTy` errors, to avoid regressions from (1.). It's still not as great as it could be -- will point out inline in comments.
r? `@BoxyUwU`
Fix bug in utf16_to_utf8 for zero length strings
This fixes the behavior of sending EOF by pressing Ctrl+Z => Enter in a windows console.
Previously, that would trip the unpaired surrogate error, whereas now we correctly detect EOF.
remove reference to Into in ? operator core/std docs, fix#111655
remove the text stating that `?` uses `Into::into` and add text stating it uses `From::from` instead. This closes#111655.
Uplift `clippy::cast_ref_to_mut` lint
This PR aims at uplifting the `clippy::cast_ref_to_mut` lint into rustc.
## `cast_ref_to_mut`
(deny-by-default)
The `cast_ref_to_mut` lint checks for casts of `&T` to `&mut T` without using interior mutability.
### Example
```rust,compile_fail
fn x(r: &i32) {
unsafe {
*(r as *const i32 as *mut i32) += 1;
}
}
```
### Explanation
Casting `&T` to `&mut T` without interior mutability is undefined behavior, as it's a violation of Rust reference aliasing requirements.
-----
Mostly followed the instructions for uplifting a clippy lint described here: https://github.com/rust-lang/rust/pull/99696#pullrequestreview-1134072751
`@rustbot` label: +I-lang-nominated
r? compiler
-----
For Clippy:
changelog: Moves: Uplifted `clippy::cast_ref_to_mut` into rustc
This fixes the behavior of sending EOF by pressing Ctrl+Z => Enter in a
windows console.
Previously, that would trip the unpaired surrogate error, whereas now we
correctly detect EOF.
Update cargo
17 commits in 64fb38c97ac4d3a327fc9032c862dd28c8833b17..f7b95e31642e09c2b6eabb18ed75007dda6677a0
2023-05-23 18:53:23 +0000 to 2023-05-30 19:25:02 +0000
- chore: detect the channel a PR wants to merge into (rust-lang/cargo#12181)
- refactor: de-depulicate `make_dep_prefix` implementation (rust-lang/cargo#12203)
- Re-enable code_generation test on Windows (rust-lang/cargo#12199)
- docs: add doc comments for git source and friends (rust-lang/cargo#12192)
- test: set retry sleep to 1ms for all tests (rust-lang/cargo#12194)
- fix(add): Reduce the chance we re-format the user's `[features]` table (rust-lang/cargo#12191)
- test(add): Remove expensive test (rust-lang/cargo#12188)
- Add a description of `Cargo.lock` conflicts in the Cargo FAQ (rust-lang/cargo#12185)
- refactor(tests): Reduce cargo-add setup load (rust-lang/cargo#12189)
- Warn when an edition 2021 crate is in a virtual workspace with default resolver (rust-lang/cargo#10910)
- refactor(tests): Reduce cargo-remove setup load (rust-lang/cargo#12184)
- chore: Lexicographically order `-Z` flags (rust-lang/cargo#12182)
- chore(ci): remove temporary fix for rustup 1.24.1 (rust-lang/cargo#12180)
- fix: AIX searches dynamic libraries in `LIBPATH`. (rust-lang/cargo#11968)
- deps: remove unused features from windows-sys (rust-lang/cargo#12176)
- Automatically inherit workspace lints when running cargo new/init (rust-lang/cargo#12174)
- Test that the new `debuginfo` options match between cargo and rustc (rust-lang/cargo#12022)
r? `@ghost`
Allow limited access to `OsStr` bytes
`OsStr` has historically kept its implementation details private out of
concern for locking us into a specific encoding on Windows.
This is an alternative to rust-lang#95290 which proposed specifying the encoding on Windows. Instead, this
only specifies that for cross-platform code, `OsStr`'s encoding is a superset of UTF-8 and defines
rules for safely interacting with it
At minimum, this can greatly simplify the `os_str_bytes` crate and every
arg parser that interacts with `OsStr` directly (which is most of those
that support invalid UTF-8).
Tracking issue: #111544
Uplift `clippy::invalid_utf8_in_unchecked` lint
This PR aims at uplifting the `clippy::invalid_utf8_in_unchecked` lint into two lints.
## `invalid_from_utf8_unchecked`
(deny-by-default)
The `invalid_from_utf8_unchecked` lint checks for calls to `std::str::from_utf8_unchecked` and `std::str::from_utf8_unchecked_mut` with an invalid UTF-8 literal.
### Example
```rust
unsafe {
std::str::from_utf8_unchecked(b"cl\x82ippy");
}
```
### Explanation
Creating such a `str` would result in undefined behavior as per documentation for `std::str::from_utf8_unchecked` and `std::str::from_utf8_unchecked_mut`.
## `invalid_from_utf8`
(warn-by-default)
The `invalid_from_utf8` lint checks for calls to `std::str::from_utf8` and `std::str::from_utf8_mut` with an invalid UTF-8 literal.
### Example
```rust
std::str::from_utf8(b"ru\x82st");
```
### Explanation
Trying to create such a `str` would always return an error as per documentation for `std::str::from_utf8` and `std::str::from_utf8_mut`.
-----
Mostly followed the instructions for uplifting a clippy lint described here: https://github.com/rust-lang/rust/pull/99696#pullrequestreview-1134072751
````@rustbot```` label: +I-lang-nominated
r? compiler
-----
For Clippy:
changelog: Moves: Uplifted `clippy::invalid_utf8_in_unchecked` into rustc
`[T; N]::zip` is "eager" but most zips are mapped.
This causes poor optimization in generated code.
This is a fundamental design issue and "zip" is
"prime real estate" in terms of function names,
so let's free it up again.
All the implementations of the trait already are `Copy`, and this seems to be enough to simplify the implementations enough to make the MIR inliner willing to inline basics like `Range::next`.
Fix docs for `alloc::realloc`
Fixes#108546.
Corrects the docs for `alloc::realloc` to bring the safety constraints into line with `Layout::from_size_align_unchecked`'s constraints.
Rework handling of recursive panics
This PR makes 2 changes to how recursive panics works (a panic while handling a panic).
1. The panic count is no longer used to determine whether to force an immediate abort. This allows code like the following to work without aborting the process immediately:
```rust
struct Double;
impl Drop for Double {
fn drop(&mut self) {
// 2 panics are active at once, but this is fine since it is caught.
std::panic::catch_unwind(|| panic!("twice"));
}
}
let _d = Double;
panic!("once");
```
Rustc already generates appropriate code so that any exceptions escaping out of a `Drop` called in the unwind path will immediately abort the process.
2. Any panics while the panic hook is executing will force an immediate abort. This is necessary to avoid potential deadlocks like #110771 where a panic happens while holding the backtrace lock. We don't even try to print the panic message in this case since the panic may have been caused by `Display` impls.
Fixes#110771
Rollup of 6 pull requests
Successful merges:
- #111936 (Include test suite metadata in the build metrics)
- #111952 (Remove DesugaringKind::Replace.)
- #111966 (Add #[inline] to array TryFrom impls)
- #111983 (Perform MIR type ops locally in new solver)
- #111997 (Fix re-export of doc hidden macro not showing up)
- #112014 (rustdoc: get unnormalized link destination for suggestions)
r? `@ghost`
`@rustbot` modify labels: rollup
Add #[inline] to array TryFrom impls
I was looking into https://github.com/rust-lang/rust/issues/111959 and I realized we don't have these. They seem like an uncontroversial addition.
IMO this PR does not fix that issue. I think the bad codegen is being caused by some underlying deeper problem but this change might cause the MIR inliner to paper over it in this specific case.
r? `@thomcc`
Update current implementation comments for `select_nth_unstable`
This more accurately reflects the actual implementation, as it hasn't been a simple quickselect since #106997. While it does say that the current implementation always runs in O(n), I don't think it should require an FCP as it doesn't guarantee linearity in general and only points out that the current implementation is in fact linear.
r? `@Amanieu`
Before this commit, both static and dynamic benches were converted to a
DynTestFn, with a boxed closure that ran the benchmarks exactly once.
While this worked, it conflicted with -Z panic-abort-tests as the flag
does not support dynamic tests. With this change, a StaticBenchFn is
converted to a StaticBenchAsTestFn, avoiding any dynamic test creation.
DynBenchFn is also converted to DynBenchAsTestFn for completeness.
Before this commit, tests were invoked in multiple places, especially
due to `-Z panic-abort-tests`, and adding a new test kind meant having
to chase down and update all these places.
This commit creates a new Runnable enum, and its children RunnableTest
and RunnableBench. The rest of the harness will now pass around the enum
rather than constructing and passing around boxed functions. The enum
has two children enums because invoking tests and invoking benchmarks
requires different parameters.
Add Median of Medians fallback to introselect
Fixes#102451.
This PR is a follow up to #106997. It adds a Fast Deterministic Selection implementation as a fallback to the introselect algorithm used by `select_nth_unstable`. This allows it to guarantee O(n) worst case running time, while maintaining good performance in all cases.
This would fix#102451, which was opened because the `select_nth_unstable` docs falsely claimed that it had O(n) worst case performance, even though it was actually quadratic in the worst case. #106997 improved the worst case complexity to O(n log n) by using heapsort as a fallback, and this PR further improves it to O(n) (this would also make #106933 unnecessary).
It also improves the actual runtime if the fallback gets called: Using a pathological input of size `1 << 19` (see the playground link in #102451), calculating the median is roughly 3x faster using fast deterministic selection as a fallback than it is using heapsort.
The downside to this is less code reuse between the sorting and selection algorithms, but I don't think it's that bad. The additional algorithms are ~250 LOC with no `unsafe` blocks (I tried using unsafe to avoid bounds checks but it didn't noticeably improve the performance).
I also let it fuzz for a while against the current `select_nth_unstable` implementation to ensure correctness, and it seems to still fulfill all the necessary postconditions.
cc `@scottmcm` who reviewed #106997
Support #[global_allocator] without the allocator shim
This makes it possible to use liballoc/libstd in combination with `--emit obj` if you use `#[global_allocator]`. This is what rust-for-linux uses right now and systemd may use in the future. Currently they have to depend on the exact implementation of the allocator shim to create one themself as `--emit obj` doesn't create an allocator shim.
Note that currently the allocator shim also defines the oom error handler, which is normally required too. Once `#![feature(default_alloc_error_handler)]` becomes the only option, this can be avoided. In addition when using only fallible allocator methods and either `--cfg no_global_oom_handling` for liballoc (like rust-for-linux) or `--gc-sections` no references to the oom error handler will exist.
To avoid this feature being insta-stable, you will have to define `__rust_no_alloc_shim_is_unstable` to avoid linker errors.
(Labeling this with both T-compiler and T-lang as it originally involved both an implementation detail and had an insta-stable user facing change. As noted above, the `__rust_no_alloc_shim_is_unstable` symbol requirement should prevent unintended dependence on this unstable feature.)
This is not a library, so there's no reason for them to be `pub`.
Without doing this, compiling the test crates causes private dep
lint errors:
error: type `PathBuf` from private dependency 'std' in public interface
--> library/std/tests/common/mod.rs:26:5
|
26 | pub fn join(&self, path: &str) -> PathBuf {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
= note: `-D exported-private-dependencies` implied by `-D warnings`
error: type `Path` from private dependency 'std' in public interface
--> library/std/tests/common/mod.rs:31:5
|
31 | pub fn path(&self) -> &Path {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^
error: could not compile `std` (test "create_dir_all_bare") due to 2 previous errors
This happens because Cargo passes `--extern 'priv:std=...` when
compiling the test crate.
I'm not sure if these warnings are desirable or not. They seem correct
in a very pedantic way (the dependency on `std` is not marked public,
since it's implicit), but also pointless (the test crate is not an API,
so who cares what it does).
[rustc_ty_utils] Treat `drop_in_place`'s *mut argument like &mut when adding LLVM attributes
This resurrects PR #103614, which has sat idle for a while.
This could probably use a new perf run, since we're on a new LLVM version now.
r? `@oli-obk`
cc `@RalfJung`
---
LLVM can make use of the `noalias` parameter attribute on the parameter to `drop_in_place` in areas like argument promotion. Because the Rust compiler fully controls the code for `drop_in_place`, it can soundly deduce parameter attributes on it.
In #103957, Miri was changed to retag `drop_in_place`'s argument as if it was `&mut`, matching this change.
Give better error when collecting into `&[T]`
The detection of slice reference of `{integral}` in `rustc_on_unimplemented` is hacky, but a proper solution requires changing `FmtPrinter` to add a parameter to print integers as `{integral}` and I didn't want to change it just for `rustc_on_unimplemented`. I can do that if requested, though.
I'm open to better wording; this is the best I could come up with.
Mark internal functions and traits unsafe to reflect preconditions
No semantics are changed in this PR; I only mark some functions and and a trait `unsafe` which already had implicit preconditions. Although it seems somewhat redundant for `numfmt::Part::Copy` to contain a `&[u8]` instead of a `&str`, given that all of its current consumers ultimately expect valid UTF-8. Is the type also intended to work for byte-slice formatting in the future?
Fix duplicate `arcinner_layout_for_value_layout` calls when using the uninit `Arc` constructors
What this fixes is the duplicate calls to `arcinner_layout_for_value_layout` seen here: https://godbolt.org/z/jr5Gxozhj
The issue was discovered alongside #111603 but is otherwise unrelated to the duplicate `alloca`s, which remain unsolved. Everything I tried to solve said main issue has failed.
As for the duplicate layout calculations, I also tried slapping `#[inline]` and `#[inline(always)]` on everything in sight but the only thing that worked in the end is to dedup the calls by hand.
Document `Pin` memory layout
The fact that `Pin` is `#[repr(transparent)]` technically isn't documented anywhere currently. I don't see any reason why `Pin`'s layout would ever change, so this PR codifies it.
`@rustbot` label +T-libs-api -T-libs +A-docs +A-layout +A-pin
Don't use inner macro in `marker_impls`
Just recurse instead of having to define an inner macro to avoid the problem with expansion binders being misnumbered between the `$meta` and `$T` variables.
cc `@Veykril` this should fixrust-lang/rust-analyzer#14862 since we've gotten rid of the inner macro.
don't skip inference for type in `offset_of!`
Fixes https://github.com/rust-lang/rust/issues/111678 by no longer skipping inference on the type in `offset_of!`. Simply erasing the regions the during writeback isn't enough and can cause ICEs. A test case for this is included.
This reverts https://github.com/rust-lang/rust/pull/111661, because it becomes redundant, since inference already erases the regions.
Use code with reliable branchless code-gen for slice::sort merge
The recent LLVM 16 update changes code-gen to be not branchless anymore, in the slice::sort implementation merge function. This improves performance by 30% for random patterns, restoring the performance to the state with LLVM 15.
Fixes#111559
Rollup of 10 pull requests
Successful merges:
- #111491 (Dont check `must_use` on nested `impl Future` from fn)
- #111606 (very minor cleanups)
- #111619 (Add timings for MIR passes to profiling report)
- #111652 (Better diagnostic for `use Self::..`)
- #111665 (Add more tests for the offset_of macro)
- #111708 (Give a more useful location for where a span_bug was delayed)
- #111715 (Fix doc comment for `ConstParamTy` derive)
- #111723 (style: do not overwrite obligations)
- #111743 (Improve cgu merging debug output)
- #111762 (fix: emit error when fragment is `MethodReceiverExpr` and items is empty)
r? `@ghost`
`@rustbot` modify labels: rollup
Add more tests for the offset_of macro
Implements what I [suggested in the tracking issue](https://github.com/rust-lang/rust/issues/106655#issuecomment-1535007205), plus some further improvements:
* ensuring that offset_of!(Self, ...) works iff inside an impl block
* ensuring that the output type is usize and doesn't coerce. this can be changed in the future, but if it is done, it should be a conscious decision
* improving the privacy checking test
* ensuring that generics don't let you escape the unsized check
r? `````@WaffleLapkin`````
`ascii::Char`-ify the escaping code in `core`
This means that `EscapeIterInner::as_str` no longer needs unsafe code, because the type system ensures the internal buffer is only ASCII, and thus valid UTF-8.
Come to think of it, this also gives it a (non-guaranteed) niche.
cc `@BurntSushi` as potentially interested
`ascii::Char` tracking issue: #110998
Add creation time support to `FileTimes` on apple and windows
Adds support for setting file creation times on platforms which support changing it directly (currently only Apple and Windows). Based on top of #110093 (which was split from this PR).
ACP: rust-lang/libs-team#199 (currently still in progress)
Tracking issue: #98245
`@rustbot` label +T-libs-api -T-libs
Shorten even more panic temporary lifetimes
Followup to #104134. As pointed out by `@bjorn3` in https://github.com/rust-lang/rust/pull/104134#pullrequestreview-1425585948, there are other cases in the panic macros which would also benefit from dropping their non-Send temporaries as soon as possible, avoiding pointlessly holding them across an await point.
For the tests added in this PR, here are the failures you get today on master without the macro changes in this PR:
<details>
<summary>tests/ui/macros/panic-temporaries-2018.rs</summary>
```console
error: future cannot be sent between threads safely
--> tests/ui/macros/panic-temporaries-2018.rs:52:18
|
LL | require_send(panic_display());
| ^^^^^^^^^^^^^^^ future returned by `panic_display` is not `Send`
|
= help: within `impl Future<Output = ()>`, the trait `Send` is not implemented for `*const u8`
note: future is not `Send` as this value is used across an await
--> tests/ui/macros/panic-temporaries-2018.rs:35:31
|
LL | f(panic!("{}", NOT_SEND)).await;
| -------- ^^^^^- `NOT_SEND` is later dropped here
| | |
| | await occurs here, with `NOT_SEND` maybe used later
| has type `NotSend` which is not `Send`
note: required by a bound in `require_send`
--> tests/ui/macros/panic-temporaries-2018.rs:48:25
|
LL | fn require_send(_: impl Send) {}
| ^^^^ required by this bound in `require_send`
error: future cannot be sent between threads safely
--> tests/ui/macros/panic-temporaries-2018.rs:52:18
|
LL | require_send(panic_display());
| ^^^^^^^^^^^^^^^ future returned by `panic_display` is not `Send`
|
= help: within `NotSend`, the trait `Sync` is not implemented for `*const u8`
note: future is not `Send` as this value is used across an await
--> tests/ui/macros/panic-temporaries-2018.rs:35:31
|
LL | f(panic!("{}", NOT_SEND)).await;
| ---------------------- ^^^^^- the value is later dropped here
| | |
| | await occurs here, with the value maybe used later
| has type `&NotSend` which is not `Send`
note: required by a bound in `require_send`
--> tests/ui/macros/panic-temporaries-2018.rs:48:25
|
LL | fn require_send(_: impl Send) {}
| ^^^^ required by this bound in `require_send`
error: future cannot be sent between threads safely
--> tests/ui/macros/panic-temporaries-2018.rs:53:18
|
LL | require_send(panic_str());
| ^^^^^^^^^^^ future returned by `panic_str` is not `Send`
|
= help: within `impl Future<Output = ()>`, the trait `Send` is not implemented for `*const u8`
note: future is not `Send` as this value is used across an await
--> tests/ui/macros/panic-temporaries-2018.rs:40:36
|
LL | f(panic!((NOT_SEND, "...").1)).await;
| -------- ^^^^^- `NOT_SEND` is later dropped here
| | |
| | await occurs here, with `NOT_SEND` maybe used later
| has type `NotSend` which is not `Send`
note: required by a bound in `require_send`
--> tests/ui/macros/panic-temporaries-2018.rs:48:25
|
LL | fn require_send(_: impl Send) {}
| ^^^^ required by this bound in `require_send`
error: future cannot be sent between threads safely
--> tests/ui/macros/panic-temporaries-2018.rs:54:18
|
LL | require_send(unreachable_display());
| ^^^^^^^^^^^^^^^^^^^^^ future returned by `unreachable_display` is not `Send`
|
= help: within `impl Future<Output = ()>`, the trait `Send` is not implemented for `*const u8`
note: future is not `Send` as this value is used across an await
--> tests/ui/macros/panic-temporaries-2018.rs:45:31
|
LL | f(unreachable!(NOT_SEND)).await;
| -------- ^^^^^- `NOT_SEND` is later dropped here
| | |
| | await occurs here, with `NOT_SEND` maybe used later
| has type `NotSend` which is not `Send`
note: required by a bound in `require_send`
--> tests/ui/macros/panic-temporaries-2018.rs:48:25
|
LL | fn require_send(_: impl Send) {}
| ^^^^ required by this bound in `require_send`
error: future cannot be sent between threads safely
--> tests/ui/macros/panic-temporaries-2018.rs:54:18
|
LL | require_send(unreachable_display());
| ^^^^^^^^^^^^^^^^^^^^^ future returned by `unreachable_display` is not `Send`
|
= help: within `NotSend`, the trait `Sync` is not implemented for `*const u8`
note: future is not `Send` as this value is used across an await
--> tests/ui/macros/panic-temporaries-2018.rs:45:31
|
LL | f(unreachable!(NOT_SEND)).await;
| ---------------------- ^^^^^- the value is later dropped here
| | |
| | await occurs here, with the value maybe used later
| has type `&NotSend` which is not `Send`
note: required by a bound in `require_send`
--> tests/ui/macros/panic-temporaries-2018.rs:48:25
|
LL | fn require_send(_: impl Send) {}
| ^^^^ required by this bound in `require_send`
error: aborting due to 5 previous errors
```
</details>
<details>
<summary>tests/ui/macros/panic-temporaries.rs</summary>
```console
error: future cannot be sent between threads safely
--> tests/ui/macros/panic-temporaries.rs:42:18
|
LL | require_send(panic_display());
| ^^^^^^^^^^^^^^^ future returned by `panic_display` is not `Send`
|
= help: within `impl Future<Output = ()>`, the trait `Send` is not implemented for `*const u8`
note: future is not `Send` as this value is used across an await
--> tests/ui/macros/panic-temporaries.rs:35:31
|
LL | f(panic!("{}", NOT_SEND)).await;
| -------- ^^^^^- `NOT_SEND` is later dropped here
| | |
| | await occurs here, with `NOT_SEND` maybe used later
| has type `NotSend` which is not `Send`
note: required by a bound in `require_send`
--> tests/ui/macros/panic-temporaries.rs:38:25
|
LL | fn require_send(_: impl Send) {}
| ^^^^ required by this bound in `require_send`
error: future cannot be sent between threads safely
--> tests/ui/macros/panic-temporaries.rs:42:18
|
LL | require_send(panic_display());
| ^^^^^^^^^^^^^^^ future returned by `panic_display` is not `Send`
|
= help: within `NotSend`, the trait `Sync` is not implemented for `*const u8`
note: future is not `Send` as this value is used across an await
--> tests/ui/macros/panic-temporaries.rs:35:31
|
LL | f(panic!("{}", NOT_SEND)).await;
| ---------------------- ^^^^^- the value is later dropped here
| | |
| | await occurs here, with the value maybe used later
| has type `&NotSend` which is not `Send`
note: required by a bound in `require_send`
--> tests/ui/macros/panic-temporaries.rs:38:25
|
LL | fn require_send(_: impl Send) {}
| ^^^^ required by this bound in `require_send`
error: aborting due to 2 previous errors
```
</details>
r? bjorn3
* ensuring that offset_of!(Self, ...) works iff inside an impl block
* ensuring that the output type is usize and doesn't coerce. this can be
changed in the future, but if it is done, it should be a conscious descision
* improving the privacy checking test
* ensuring that generics don't let you escape the unsized check
add examples of port 0 binding behavior
Was trying to find the method to specify the IP address but not the port, and there wasn't information easily accessible about it in the `TcpListener` or `SocketAddr`. Adding examples to `TcpListener` and `UdpSocket` for clarity.
Specialize ToString implementation for fmt::Arguments
Generates far fewer instructions by formatting into a String with `fmt::format` directly instead of going through the `fmt::Display` impl. This change is insta-stable.
Add a conversion from `&mut T` to `&mut UnsafeCell<T>`
Provides a safe way of downgrading an exclusive reference into an alias-able `&UnsafeCell<T>` reference.
ACP: https://github.com/rust-lang/libs-team/issues/198.
Change Vec examples to not assert exact capacity except where it is guaranteed
It was [brought up on discord](https://discord.com/channels/273534239310479360/818964227783262209/1107633959329878077) that the `Vec::into_boxed_slice` example contradicted the `Vec::with_capacity` docs in that the returned `Vec` might have _more_ capacity than requested.
So, to reduce confusion change all the `assert_eq!(vec.capacity(), _)` to `assert!(vec.capacity() >= _)`, except in 4 examples that have guaranteed capacities: `Vec::from_raw_parts`, `Vec::from_raw_parts_in`, `Vec::<()>::with_capacity`,`Vec::<(), _>::with_capacity_in`.
The recent LLVM 16 update changes code-gen to be not branchless anymore, in the
slice::sort implementation merge function. This improves performance by 30% for
random patterns, restoring the performance to the state with LLVM 15.
Don't claim `LocalKey::with` prevents a reference to be sent across threads
The documentation for `LocalKey` claims that `with` yields a reference that cannot be sent across threads, but this is false since you can easily do that with scoped threads. What it actually prevents is the reference from outliving the current thread.
(docs) Change "wanting" to "want"
Changing " If you’re wanting" to "If you want".
Wanting is not wrong, of course, but I think that "If you want" feels more natural to most readers.
Fix some misleading and copy-pasted `Pattern` examples
These examples were listed twice and also were confusable with doing a substring match instead of a any-of-set match.
Update doc for `PhantomData` to match code example
After https://github.com/rust-lang/rust/pull/106621, there is no longer a `T: 'a` annotation in the doc example, so update the text to match the code.
Stabilize const slice::split_at
This stabilizes the use of the following method in const context:
```rust
impl<T> [T] {
pub const fn split_at(&self, mid: usize) -> (&[T], &[T]);
}
```
cc tracking issue #101158
Implement `AsHandle`/`AsSocket` for `Arc`/`Rc`/`Box` on Windows
Implement the Windows counterpart to #97437 and #107317: Implement `AsHandle` and `AsSocket` for `Arc<T>`, `Rc<T>`, and `Box<T>`.
Add midpoint function for all integers and floating numbers
This pull-request adds the `midpoint` function to `{u,i}{8,16,32,64,128,size}`, `NonZeroU{8,16,32,64,size}` and `f{32,64}`.
This new function is analog to the [C++ midpoint](https://en.cppreference.com/w/cpp/numeric/midpoint) function, and basically compute `(a + b) / 2` with a rounding towards ~~`a`~~ negative infinity in the case of integers. Or simply said: `midpoint(a, b)` is `(a + b) >> 1` as if it were performed in a sufficiently-large signed integral type.
Note that unlike the C++ function this pull-request does not implement this function on pointers (`*const T` or `*mut T`). This could be implemented in a future pull-request if desire.
### Implementation
For `f32` and `f64` the implementation in based on the `libcxx` [one](18ab892ff7/libcxx/include/__numeric/midpoint.h (L65-L77)). I originally tried many different approach but all of them failed or lead me with a poor version of the `libcxx`. Note that `libstdc++` has a very similar one; Microsoft STL implementation is also basically the same as `libcxx`. It unfortunately doesn't seems like a better way exist.
For unsigned integers I created the macro `midpoint_impl!`, this macro has two branches:
- The first one take `$SelfT` and is used when there is no unsigned integer with at least the double of bits. The code simply use this formula `a + (b - a) / 2` with the arguments in the correct order and signs to have the good rounding.
- The second branch is used when a `$WideT` (at least double of bits as `$SelfT`) is provided, using a wider number means that no overflow can occur, this greatly improve the codegen (no branch and less instructions).
For signed integers the code basically forwards the signed numbers to the unsigned version of midpoint by mapping the signed numbers to their unsigned numbers (`ex: i8 [-128; 127] to [0; 255]`) and vice versa.
I originally created a version that worked directly on the signed numbers but the code was "ugly" and not understandable. Despite this mapping "overhead" the codegen is better than my most optimized version on signed integers.
~~Note that in the case of unsigned numbers I tried to be smart and used `#[cfg(target_pointer_width = "64")]` to determine if using the wide version was better or not by looking at the assembly on godbolt. This was applied to `u32`, `u64` and `usize` and doesn't change the behavior only the assembly code generated.~~
This means that `EscapeIterInner::as_str` no longer needs unsafe code, because the type system ensures the internal buffer is only ASCII, and thus valid UTF-8.
PhantomData: fix documentation wrt interaction with dropck
As far as I could find out, the `PhantomData`-dropck interaction *only* affects code using `may_dangle`. The documentation in the standard library has not been updated for 8 years and thus stems from a time when Rust still used "parametric dropck", before [RFC 1238](https://rust-lang.github.io/rfcs/1238-nonparametric-dropck.html). Back then what the docs said was correct, but with `may_dangle` dropck it stopped being entirely accurate and these days, with NLL, it is actively misleading.
Fixes https://github.com/rust-lang/rust/issues/102810
Fixes https://github.com/rust-lang/rust/issues/70841
Cc `@nikomatsakis` I hope what I am saying here is right.^^
Uplift `clippy::{drop,forget}_{ref,copy}` lints
This PR aims at uplifting the `clippy::drop_ref`, `clippy::drop_copy`, `clippy::forget_ref` and `clippy::forget_copy` lints.
Those lints are/were declared in the correctness category of clippy because they lint on useless and most probably is not what the developer wanted.
## `drop_ref` and `forget_ref`
The `drop_ref` and `forget_ref` lint checks for calls to `std::mem::drop` or `std::mem::forget` with a reference instead of an owned value.
### Example
```rust
let mut lock_guard = mutex.lock();
std::mem::drop(&lock_guard) // Should have been drop(lock_guard), mutex
// still locked
operation_that_requires_mutex_to_be_unlocked();
```
### Explanation
Calling `drop` or `forget` on a reference will only drop the reference itself, which is a no-op. It will not call the `drop` or `forget` method on the underlying referenced value, which is likely what was intended.
## `drop_copy` and `forget_copy`
The `drop_copy` and `forget_copy` lint checks for calls to `std::mem::forget` or `std::mem::drop` with a value that derives the Copy trait.
### Example
```rust
let x: i32 = 42; // i32 implements Copy
std::mem::forget(x) // A copy of x is passed to the function, leaving the
// original unaffected
```
### Explanation
Calling `std::mem::forget` [does nothing for types that implement Copy](https://doc.rust-lang.org/std/mem/fn.drop.html) since the value will be copied and moved into the function on invocation.
-----
Followed the instructions for uplift a clippy describe here: https://github.com/rust-lang/rust/pull/99696#pullrequestreview-1134072751
cc `@m-ou-se` (as T-libs-api leader because the uplifting was discussed in a recent meeting)