Commit Graph

14707 Commits

Author SHA1 Message Date
bors 8b2459c1f2 Auto merge of #123683 - pietroalbini:pa-cve-2024-24576-nightly, r=pietroalbini
Backport fix of CVE-2024-24576

See https://blog.rust-lang.org/2024/04/09/cve-2024-24576.html

r? `@ghost`
2024-04-09 19:56:18 +00:00
bors 033becf83c Auto merge of #123485 - madsmtm:use-libc-copyfile, r=joboet
macOS: Use `libc` definitions for copyfile

`COPYFILE_ALL` is not yet exposed in `libc`, but the rest of what we need is, so use those definitions instead of manually defining them.

The definitions were added in https://github.com/rust-lang/libc/pull/2667 and https://github.com/rust-lang/libc/pull/3346.
2024-04-09 14:15:09 +00:00
bjorn3 b4a395bcce Fix dead code warning 2024-04-09 13:44:53 +00:00
Guillaume Gomez 4f563a16f2
Rollup merge of #123665 - Jules-Bertholet:patch-1, r=lqd
Fix typo in `Future::poll()` docs

``@rustbot`` label A-docs
2024-04-09 13:39:24 +02:00
Guillaume Gomez 1c5db28ec3
Rollup merge of #123254 - stepancheg:thin-box-0-const-alloc, r=oli-obk
Do not allocate for ZST ThinBox (attempt 2 using const_allocate)

There's PR https://github.com/rust-lang/rust/pull/123184 which avoids allocation for ZST ThinBox.

That PR has an issue with unsoundness with padding in `MaybeUninit` (see comments in that PR). Also that PR relies on `Freeze` trait.

This PR is much simpler implementation which does not have this problem, but it uses `const_allocate` feature.

`@oli-obk` suggested that `const_allocate` should not be used for that feature. But I like how easy it to do this feature with `const_allocate`. Maybe it's OK to use `const_allocate` while `ThinBox` is unstable? Or, well, we can abandon this PR.

r? `@oli-obk`
2024-04-09 13:39:21 +02:00
Jules Bertholet c9be7b8db6
Fix typo in `Future::poll()` docs 2024-04-09 01:40:03 -04:00
Trevor Gross 0ef49fe35d Stabilize `cstr_count_bytes`
Newly stable API:

```rust
impl CStr {
    pub fn count_bytes(&self) -> usize;
}
```

Const stabilization has not yet been decided, so that will continue to be
gated under <https://github.com/rust-lang/rust/issues/113219>.

Fixes: <https://github.com/rust-lang/rust/issues/114441>
2024-04-08 22:38:59 -04:00
Chris Denton ceedae178e
Document Windows argument splitting 2024-04-09 01:19:33 +02:00
Chris Denton f66a096607
Disallow or quote all specials in bat args 2024-04-09 01:19:08 +02:00
Trevor Gross 313085f725 Change method calls to using the method directly
This is in accordance with Clippy's redundant_closure_for_method_calls.
2024-04-08 17:48:07 -04:00
Trevor Gross 6e68a2f475 Add `SAFETY` comments to the thread local implementation
Reduce `unsafe` block scope and add `SAFETY` comments.
2024-04-08 17:47:09 -04:00
Trevor Gross 2aec2fe3b8 Update thread local docs with idiomatic cell type use
The `thread_local!` examples use `RefCell` for `Copy` types. Update
examples to have one `Copy` and one non-`Copy` type using `Cell` and
`RefCell`, respectively.
2024-04-08 17:43:24 -04:00
Matthias Krüger 9570ac4d28
Rollup merge of #123564 - scottmcm:step-by-div-zero, r=joboet
Don't emit divide-by-zero panic paths in `StepBy::len`

I happened to notice today that there's actually two such calls emitted in the assembly: <https://rust.godbolt.org/z/1Wbbd3Ts6>

Since they're impossible, hopefully telling LLVM that will also help optimizations elsewhere.
2024-04-08 22:06:22 +02:00
bors 537aab7a2e Auto merge of #120131 - oli-obk:pattern_types_syntax, r=compiler-errors
Implement minimal, internal-only pattern types in the type system

rebase of https://github.com/rust-lang/rust/pull/107606

You can create pattern types with `std::pat::pattern_type!(ty is pat)`. The feature is incomplete and will panic on you if you use any pattern other than integral range patterns. The only way to create or deconstruct a pattern type is via `transmute`.

This PR's implementation differs from the MCP's text. Specifically

> This means you could implement different traits for different pattern types with the same base type. Thus, we just forbid implementing any traits for pattern types.

is violated in this PR. The reason is that we do need impls after all in order to make them usable as fields. constants of type `std::time::Nanoseconds` struct are used in patterns, so the type must be structural-eq, which it only can be if you derive several traits on it. It doesn't need to be structural-eq recursively, so we can just manually implement the relevant traits on the pattern type and use the pattern type as a private field.

Waiting on:

* [x] move all unrelated commits into their own PRs.
* [x] fix niche computation (see 2db07f94f44f078daffe5823680d07d4fded883f)
* [x] add lots more tests
* [x] T-types MCP https://github.com/rust-lang/types-team/issues/126 to finish
* [x] some commit cleanup
* [x] full self-review
* [x] remove 61bd325da19a918cc3e02bbbdce97281a389c648, it's not necessary anymore I think.
* [ ] ~~make sure we never accidentally leak pattern types to user code (add stability checks or feature gate checks and appopriate tests)~~ we don't even do this for the new float primitives
* [x] get approval that [the scope expansion to trait impls](https://rust-lang.zulipchat.com/#narrow/stream/326866-t-types.2Fnominated/topic/Pattern.20types.20types-team.23126/near/427670099) is ok

r? `@BoxyUwU`
2024-04-08 16:25:23 +00:00
bjorn3 bbd82ff44e Store all args in the unsupported Command implementation
This allows printing them in the Debug impl as well as getting them
again using the get_args() method. This allows programs that would
normally spawn another process to more easily show which program they
would have spawned if not for the fact that the target doesn't support
spawning child processes without requiring intrusive changes to keep the
args. For example rustc compiled to wasi will show the full linker
invocation that would have been done.
2024-04-08 16:21:07 +00:00
Matthias Krüger 5c3559df63
Rollup merge of #123595 - balaganesh102004:master, r=joboet
Documentation fix

Changed "It must not be an identical residual when interconversion is involved" to "The residual is not mandated to be identical when interconversion is involved." as the previous parenthetical appears to state that the residual is not permitted to be identical when interconversion is involved. However the intention of the original wording was to convey that the residual is not required to be identical when interconversion is involved, which makes more sense contextually.
2024-04-08 14:31:11 +02:00
Matthias Krüger 17c94b5f12
Rollup merge of #123089 - Philippe-Cholet:vecdeque_pop_assume_cap, r=Nilstrieb
Add invariant to VecDeque::pop_* that len < cap if pop successful

Similar to #114370 for VecDeque instead of Vec.

I initially come from https://github.com/rust-itertools/itertools/pull/899 where we noticed that `pop_front;push_back;` was slower than expected so `@scottmcm` suggested I file an issue which lead to https://internals.rust-lang.org/t/vecdeque-pop-front-push-back/20483 where **kornel** mentionned #114334 (fixed by #114370).

This is my first time with codegen tests, I based the test on what was done for Vec.
2024-04-08 14:31:11 +02:00
Matthias Krüger beaca9ce08
Rollup merge of #115984 - hermit-os:fuse, r=m-ou-se
extending filesystem support for Hermit

Extending `std` to create, change and read a directory for Hermit.

Hermit is a tier 3 platform and this PR changes only files, wich are related to the tier 3 platform.
2024-04-08 14:31:09 +02:00
Oli Scherer c340e67dec Add pattern types to parser 2024-04-08 11:57:17 +00:00
joboet 37c1758214
std: update abort message in `thread::set_current` 2024-04-08 12:17:19 +02:00
Philippe-Cholet 7a2678de7d Add invariant to VecDeque::pop_* that len < cap if pop successful
Similar to #114370 for VecDeque instead of Vec. It now uses `core::hint::assert_unchecked`.
2024-04-08 12:12:13 +02:00
bors a2c72ce594 Auto merge of #123506 - RalfJung:miri-test-libstd, r=Mark-Simulacrum
check-aux: test core, alloc, std in Miri

Let's see if this works, and how long it takes.
2024-04-08 00:08:44 +00:00
bors f65f84feb0 Auto merge of #123597 - Gbd199:patch-1, r=jhpratt
Fix typo in library/core/src/iter/traits/iterator.rs
2024-04-07 22:04:40 +00:00
Gabriel Dolberg a1d4066e53
Fix typo in library/core/src/iter/traits/iterator.rs 2024-04-07 18:55:28 +03:00
BALAGANESH 8f6ebf608d Made changes in documentation 2024-04-07 15:07:25 +00:00
bors e78913baef Auto merge of #123592 - matthiaskrgr:rollup-3k1pq8s, r=matthiaskrgr
Rollup of 2 pull requests

Successful merges:

 - #123584 (Emit an error when `rustc_doc_primitive` has an unknown value)
 - #123589 (sys_common::thread_local_key: make a note that this is not used on Windows)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-04-07 14:51:54 +00:00
bors 4e431fad67 Auto merge of #123561 - saethlin:str-unchecked-sub-index, r=scottmcm
Use unchecked_sub in str indexing

https://github.com/rust-lang/rust/pull/108763 applied this logic to indexing for slices, but of course `str` has its own separate impl.

Found this by skimming over the codegen for https://github.com/oxidecomputer/hubris/; their dist builds enable overflow checks so the lack of `unchecked_sub` was producing an impossible-to-hit overflow check and also inhibiting some inlining.

r? scottmcm
2024-04-07 12:49:15 +00:00
Ralf Jung b1d1ad9f8c sys_common::thread_local_key: make a note that this is not used on Windows 2024-04-07 12:23:47 +02:00
Ralf Jung a986c0a100 make a doctest less slow in Miri 2024-04-07 10:06:06 +02:00
Ralf Jung 1242093da2 also test parts of std
requires disabling some tests that do not work
2024-04-07 10:05:57 +02:00
Ralf Jung c0b564b767 disable benches in Miri 2024-04-07 09:58:10 +02:00
Matthias Krüger 0b5a8ac116
Rollup merge of #123522 - dtolnay:constatomicintoinner, r=Nilstrieb
Stabilize const Atomic*::into_inner

Partial stabilization for https://github.com/rust-lang/rust/issues/78729, for which the FCP has already completed.

The other `into_inner` functions in that tracking issue (`UnsafeCell`, `Cell`, `RefCell`) are blocked on https://github.com/rust-lang/rust/issues/73255 for now.

```console
error[E0493]: destructor of `UnsafeCell<T>` cannot be evaluated at compile-time
    --> library/core/src/cell.rs:2076:29
     |
2076 |     pub const fn into_inner(self) -> T {
     |                             ^^^^ the destructor for this type cannot be evaluated in constant functions
2077 |         self.value
2078 |     }
     |     - value is dropped here
```
2024-04-07 00:51:26 +02:00
Matthias Krüger 84dca1503e
Rollup merge of #123411 - saethlin:ub-checks, r=Urgau,RalfJung
Put checks that detect UB under their own flag below debug_assertions

Implementation of https://github.com/rust-lang/compiler-team/issues/725
2024-04-07 00:51:25 +02:00
Matthias Krüger 0ea427025b
Rollup merge of #119224 - Duckilicious:test_main_memory_leak, r=cuviper
Drop panic hook after running tests

Issue: https://github.com/rust-lang/rust/issues/119223
Previously we left the panic hook we allocated
on main termination. Doing so makes Valgrind
report it as a reachable unfreed block.
In order to fix that use `panic::take_hook()` before examining test results.

Example backtrace:
```
==146594== 16 bytes in 1 blocks are still reachable in loss record 1 of 1
==146594==    at 0x4A390C5: malloc (vg_replace_malloc.c:442)
==146594==    by 0x151336: alloc (alloc.rs:98)
==146594==    by 0x151336: alloc_impl (alloc.rs:181)
==146594==    by 0x151336: allocate (alloc.rs:241)
==146594==    by 0x151336: exchange_malloc (alloc.rs:330)
==146594==    by 0x151336: new<test::test_main::{closure_env#0}> (boxed.rs:217)
==146594==    by 0x151336: test::test_main (lib.rs:124)
==146594==    by 0x1522F9: test::test_main_static (lib.rs:160)
==146594==    by 0x11E102: reachable_block_with_cargo_test::main (lib.rs:1)
==146594==    by 0x11EABA: core::ops::function::FnOnce::call_once (function.rs:250)
==146594==    by 0x11E76D: std::sys_common::backtrace::__rust_begin_short_backtrace (backtrace.rs:154)
==146594==    by 0x11DFC0: std::rt::lang_start::{{closure}} (rt.rs:166)
==146594==    by 0x177D3A: call_once<(), (dyn core::ops::function::Fn<(), Output=i32> + core::marker::Sync + core::panic::unwind_safe::RefUnwindSafe)> (function.rs:284)
==146594==    by 0x177D3A: do_call<&(dyn core::ops::function::Fn<(), Output=i32> + core::marker::Sync + core::panic::unwind_safe::RefUnwindSafe), i32> (panicking.rs:504)
==146594==    by 0x177D3A: try<i32, &(dyn core::ops::function::Fn<(), Output=i32> + core::marker::Sync + core::panic::unwind_safe::RefUnwindSafe)> (panicking.rs:468)
==146594==    by 0x177D3A: catch_unwind<&(dyn core::ops::function::Fn<(), Output=i32> + core::marker::Sync + core::panic::unwind_safe::RefUnwindSafe), i32> (panic.rs:142)
==146594==    by 0x177D3A: {closure#2} (rt.rs:148)
==146594==    by 0x177D3A: do_call<std::rt::lang_start_internal::{closure_env#2}, isize> (panicking.rs:504)
==146594==    by 0x177D3A: try<isize, std::rt::lang_start_internal::{closure_env#2}> (panicking.rs:468)
==146594==    by 0x177D3A: catch_unwind<std::rt::lang_start_internal::{closure_env#2}, isize> (panic.rs:142)
==146594==    by 0x177D3A: std::rt::lang_start_internal (rt.rs:148)
==146594==    by 0x11DF99: std::rt::lang_start (rt.rs:165)
```
2024-04-07 00:51:25 +02:00
Scott McMurray 00bd24766f Don't emit divide-by-zero panic paths in `StepBy::len`
I happened to notice today that there's actually two such calls emitted in the assembly: <https://rust.godbolt.org/z/1Wbbd3Ts6>

Since they're impossible, hopefully telling LLVM that will also help optimizations elsewhere.
2024-04-06 11:37:57 -07:00
Ben Kimock 712aab72df Use unchecked_sub in str indexing 2024-04-06 14:09:03 -04:00
Tal Gelbard 92ebf60b3b Drop panic hook after running tests
Previously we left the panic hook we allocated
on main termination. Doing so makes Valgrind
report it as a reachable unfreed block.
In order to fix that use `panic::take_hook()` before
examining test results.

Example backtrace:
```
==146594== 16 bytes in 1 blocks are still reachable in loss record 1 of 1
==146594==    at 0x4A390C5: malloc (vg_replace_malloc.c:442)
==146594==    by 0x151336: alloc (alloc.rs:98)
==146594==    by 0x151336: alloc_impl (alloc.rs:181)
==146594==    by 0x151336: allocate (alloc.rs:241)
==146594==    by 0x151336: exchange_malloc (alloc.rs:330)
==146594==    by 0x151336: new<test::test_main::{closure_env#0}> (boxed.rs:217)
==146594==    by 0x151336: test::test_main (lib.rs:124)
==146594==    by 0x1522F9: test::test_main_static (lib.rs:160)
==146594==    by 0x11E102: reachable_block_with_cargo_test::main (lib.rs:1)
==146594==    by 0x11EABA: core::ops::function::FnOnce::call_once (function.rs:250)
==146594==    by 0x11E76D: std::sys_common::backtrace::__rust_begin_short_backtrace (backtrace.rs:154)
==146594==    by 0x11DFC0: std::rt::lang_start::{{closure}} (rt.rs:166)
==146594==    by 0x177D3A: call_once<(), (dyn core::ops::function::Fn<(), Output=i32> + core::marker::Sync + core::panic::unwind_safe::RefUnwindSafe)> (function.rs:284)
==146594==    by 0x177D3A: do_call<&(dyn core::ops::function::Fn<(), Output=i32> + core::marker::Sync + core::panic::unwind_safe::RefUnwindSafe), i32> (panicking.rs:504)
==146594==    by 0x177D3A: try<i32, &(dyn core::ops::function::Fn<(), Output=i32> + core::marker::Sync + core::panic::unwind_safe::RefUnwindSafe)> (panicking.rs:468)
==146594==    by 0x177D3A: catch_unwind<&(dyn core::ops::function::Fn<(), Output=i32> + core::marker::Sync + core::panic::unwind_safe::RefUnwindSafe), i32> (panic.rs:142)
==146594==    by 0x177D3A: {closure#2} (rt.rs:148)
==146594==    by 0x177D3A: do_call<std::rt::lang_start_internal::{closure_env#2}, isize> (panicking.rs:504)
==146594==    by 0x177D3A: try<isize, std::rt::lang_start_internal::{closure_env#2}> (panicking.rs:468)
==146594==    by 0x177D3A: catch_unwind<std::rt::lang_start_internal::{closure_env#2}, isize> (panic.rs:142)
==146594==    by 0x177D3A: std::rt::lang_start_internal (rt.rs:148)
==146594==    by 0x11DF99: std::rt::lang_start (rt.rs:165)
```

Signed-off-by: Tal Gelbard <talgelbard1@gmail.com>
2024-04-06 18:56:22 +03:00
Guillaume Gomez b4a761db78
Rollup merge of #123541 - RalfJung:remove-old-hacks, r=Mark-Simulacrum
remove miri-test-libstd hacks that are no longer needed

In https://github.com/rust-lang/rust/pull/123317 we developed a different approach to testing the standard library in Miri, and with https://github.com/rust-lang/miri-test-libstd/pull/56 the out-of-tree miri-test-libstd has been switched to that approach. That makes these hacks here no longer necessary.
2024-04-06 17:37:39 +02:00
Ben Kimock a7912cb421 Put checks that detect UB under their own flag below debug_assertions 2024-04-06 11:21:47 -04:00
Matthias Krüger cb7f1eec04
Rollup merge of #122291 - lilasta:stabilize_const_location_fields, r=dtolnay
Stabilize `const_caller_location` and `const_location_fields`

Closes #102911. Closes #76156.

tests: [library/core/tests/panic/location.rs](3521a2f2f3/library/core/tests/panic/location.rs)

API:
```rust
// core::panic::location
impl Location {
    pub const fn caller() -> &'static Location<'static>;
    pub const fn file(&self) -> &str;
    pub const fn line(&self) -> u32;
    pub const fn column(&self) -> u32;
}
```
2024-04-06 13:00:05 +02:00
Matthias Krüger 3bcf402322
Rollup merge of #114788 - tisonkun:get_mut_or_init, r=dtolnay
impl get_mut_or_init and get_mut_or_try_init for OnceCell and OnceLock

See also https://github.com/rust-lang/rust/issues/74465#issuecomment-1676522051

I'm trying to understand the process for such proposal. And I'll appreciate it if anyone can guide me the next step for consensus or adding tests.
2024-04-06 13:00:04 +02:00
Ralf Jung a2799ef869 remove miri-test-libstd hacks that are no longer needed 2024-04-06 09:03:19 +02:00
Matthias Krüger 58ac1b4244
Rollup merge of #123528 - dtolnay:asyncgeninternals, r=compiler-errors
Hide async_gen_internals from standard library documentation

These are from https://github.com/rust-lang/rust/pull/118420. It doesn't appear that there is any intention to ever make these APIs available to user code. These are just conveniences meant for the compiler's implementation of `async gen`. I don't think having them featured in documentation in <https://doc.rust-lang.org/1.77.1/core/task/enum.Poll.html> is appropriate.

![image](https://github.com/rust-lang/rust/assets/1940490/0a8ae90d-5c83-4ab1-b08a-50bad2433d69)
2024-04-06 08:56:36 +02:00
David Tolnay 262670a8f1
Hide async_gen_internals from standard library documentation 2024-04-05 18:54:38 -07:00
bors 30840c53f4 Auto merge of #123433 - GnomedDev:remove-threadname-alloc, r=joboet
Remove rt::init allocation for thread name

This removes one of the allocations in a `fn main() {}` program.
2024-04-06 00:17:23 +00:00
David Tolnay ff88a9a332
Stabilize const Atomic*::into_inner 2024-04-05 16:04:07 -07:00
Guillaume Gomez 1bffe75df6
Rollup merge of #123505 - ChrisDenton:revert-121666, r=workingjubilee
Revert "Use OS thread name by default"

This reverts #121666 (Use the OS thread name by default if `THREAD_INFO` has not been initialized) due to #123495 (Thread names are not always valid UTF-8).

It's not a direct revert because there have been other changes since that PR.
2024-04-05 22:33:28 +02:00
Guillaume Gomez 74a5bc6c9e
Rollup merge of #121419 - agg23:xrOS-pr, r=davidtwco
Add aarch64-apple-visionos and aarch64-apple-visionos-sim tier 3 targets

Introduces `aarch64-apple-visionos` and `aarch64-apple-visionos-sim` as tier 3 targets. This allows native development for the Apple Vision Pro's visionOS platform.

This work has been tracked in https://github.com/rust-lang/compiler-team/issues/642. There is a corresponding `libc` change https://github.com/rust-lang/libc/pull/3568 that is not required for merge.

Ideally we would be able to incorporate [this change](https://github.com/gimli-rs/object/pull/626) to the `object` crate, but the author has stated that a release will not be cut for quite a while. Therefore, the two locations that would reference the xrOS constant from `object` are hardcoded to their MachO values of 11 and 12, accompanied by TODOs to mark the code as needing change. I am open to suggestions on what to do here to get this checked in.

# 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 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.)

See [src/doc/rustc/src/platform-support/apple-visionos.md](e88379034a/src/doc/rustc/src/platform-support/apple-visionos.md)

> 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.

This naming scheme matches `$ARCH-$VENDOR-$OS-$ABI` which is matches the iOS Apple Silicon simulator (`aarch64-apple-ios-sim`) and other Apple targets.

> 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.
>  - Anything added to the Rust repository must be under the standard Rust license (`MIT OR Apache-2.0`).
>  - 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 besubject to any new license requirements.
>  - 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.
> - "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.

This contribution is fully available under the standard Rust license with no additional legal restrictions whatsoever. This PR does not introduce any new dependency less permissive than the Rust license policy.

The new targets do not depend on proprietary libraries.

> 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.

This new target mirrors the standard library for watchOS and iOS, with minor divergences.

> 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.

Documentation is provided in [src/doc/rustc/src/platform-support/apple-visionos.md](e88379034a/src/doc/rustc/src/platform-support/apple-visionos.md)

> 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.
> * 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.

> 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.
> * 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.

> 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.

I acknowledge these requirements and intend to ensure that they are met.

This target does not touch any existing tier 2 or tier 1 targets and should not break any other targets.
2024-04-05 22:33:25 +02:00
Stepan Koltsov f539134e20 Do not allocate for ZST ThinBox attempt 2 (using const_allocate)
There's PR https://github.com/rust-lang/rust/pull/123184
which avoids allocation for ZST ThinBox.

That PR has an issue with unsoundness with misuse of `MaybeUninit`
(see comments in that PR).

This PR is much simpler implementation which does not have this
problem, but it uses `const_allocate` feature.
2024-04-05 19:55:00 +01:00
bors 5958f5e08f Auto merge of #123317 - RalfJung:test-in-miri, r=m-ou-se,saethlin,onur-ozkan
Support running library tests in Miri

This adds a new bootstrap subcommand `./x.py miri` which can test libraries in Miri. This is in preparation for eventually doing that as part of bors CI, but this PR only adds the infrastructure, and doesn't enable it yet.

`@rust-lang/bootstrap` should this be `x.py test --miri library/core` or `x.py miri library/core`? The flag has the advantage that we don't have to copy all the arguments from `Subcommand::Test`. It has the disadvantage that most test steps just ignore `--miri` and still run tests the regular way. For clippy you went the route of making it a separate subcommand. ~~I went with a flag now as that seemed easier, but I can change this.~~ I made it a new subcommand. Note however that the regular cargo invocation would be `cargo miri test ...`, so `x.py` is still going to be different in that the `test` is omitted. That said, we could also make it `./x.py miri-test` to make that difference smaller -- that's in fact more consistent with the internal name of the command when bootstrap invokes cargo.

`@rust-lang/libs` ~~unfortunately this PR does some unholy things to the `lib.rs` files of our library crates.~~
`@m-ou-se` found a way that entirely avoids library-level hacks, except for some new small `lib.miri.rs` files that hopefully you will never have to touch. There's a new hack in cargo-miri but there it is in good company...
2024-04-05 13:17:09 +00:00
Chris Denton 7d008267dd
Revert #121666
This reverts #121666 due to #123495
2024-04-05 12:50:31 +00:00
Mads Marquart 3fe58393bc macOS: Use `libc` definitions for copyfile
`COPYFILE_ALL` is not yet exposed in `libc`, but the rest of what we need is, so use those definitions instead of manually defining them.
2024-04-05 04:25:39 +02:00
Jacob Pratt de2cb0d76c
Rollup merge of #123206 - stepancheg:pointee-metadata-freeze, r=Amanieu
Require Pointee::Metadata to be Freeze

So pointee metadata can be used in anonymous statics.

This is prerequisite for implementing ThinBox without allocation for ZST.

See https://github.com/rust-lang/rust/pull/123184#discussion_r1544627488

r? joboet
2024-04-04 21:16:55 -04:00
David Thomas 0989416d21 Remove rt::init allocation for thread name 2024-04-04 23:17:15 +01:00
Nadrieril 1a83bea107 Impl `DerefPure` for more std types 2024-04-05 00:02:42 +02:00
Matthias Krüger ad300b6738
Rollup merge of #123431 - slanterns:literal_byte_character_c_string_stabilize, r=dtolnay
Stabilize `proc_macro_byte_character` and `proc_macro_c_str_literals`

This PR stabilizes `proc_macro_byte_character` and `proc_macro_c_str_literals`:

```rust
// proc_macro::Literal

impl Literal {
    pub fn byte_character(byte: u8) -> Literal;
    pub fn c_string(string: &CStr) -> Literal
}
```

<br>

Tracking issue: https://github.com/rust-lang/rust/issues/115268, https://github.com/rust-lang/rust/issues/119750.
Implementation PR: https://github.com/rust-lang/rust/pull/112711, https://github.com/rust-lang/rust/pull/119651.

FCPs already completed in their respective tracking issues.

Closes https://github.com/rust-lang/rust/issues/115268. Closes https://github.com/rust-lang/rust/issues/119750.

r? libs-api
2024-04-04 14:51:18 +02:00
Matthias Krüger ee5009e745
Rollup merge of #123389 - ChrisDenton:dont-panic-on-startup, r=joboet
Avoid panicking unnecessarily on startup

On Windows, in `lang_start` we add an exception handler to catch stack overflows and we also reserve some stack space for the handler. Both of these are useful but they're not strictly necessary. The standard library has to work without them (e.g. if Rust is used from a foreign entry point) and the negative effect of not doing them is limited (i.e. you don't get the friendly stack overflow message).

As we really don't want to panic pre-main unless absolutely necessary, it now won't panic on failure. I've added some debug assertions so as to avoid programmer error.
2024-04-04 14:51:17 +02:00
Chris Denton 7b8f93ef4c
Add comments about using debug_assert 2024-04-04 10:48:11 +00:00
Arthur Carcano d9a8903886 force exhaustion in iter::ArrayChunks::into_remainder 2024-04-04 12:19:54 +02:00
Jacob Pratt 875d254750
Rollup merge of #122356 - devnexen:dfbsd_build_fix, r=jhpratt
std::rand: fix dragonflybsd after #121942.
2024-04-03 20:17:04 -04:00
Slanterns fbc56dfac1
Stabilize `Literal::c_string` 2024-04-04 05:04:27 +08:00
Slanterns 61ac7812c6
Stabilize `Literal::byte_character` 2024-04-04 05:00:49 +08:00
Matthias Krüger 80d592cc24
Rollup merge of #122964 - joboet:pointer_expose, r=Amanieu
Rename `expose_addr` to `expose_provenance`

`expose_addr` is a bad name, an address is just a number and cannot be exposed. The operation is actually about the provenance of the pointer.

This PR thus changes the name of the method to `expose_provenance` without changing its return type. There is sufficient precedence for returning a useful value from an operation that does something else without the name indicating such, e.g. [`Option::insert`](https://doc.rust-lang.org/nightly/std/option/enum.Option.html#method.insert) and [`MaybeUninit::write`](https://doc.rust-lang.org/nightly/std/mem/union.MaybeUninit.html#method.write).

Returning the address is merely convenient, not a fundamental part of the operation. This is implied by the fact that integers do not have provenance since
```rust
let addr = ptr.addr();
ptr.expose_provenance();
let new = ptr::with_exposed_provenance(addr);
```
must behave exactly like
```rust
let addr = ptr.expose_provenance();
let new = ptr::with_exposed_provenance(addr);
```
as the result of `ptr.expose_provenance()` and `ptr.addr()` is the same integer. Therefore, this PR removes the `#[must_use]` annotation on the function and updates the documentation to reflect the important part.

~~An alternative name would be `expose_provenance`. I'm not at all opposed to that, but it makes a stronger implication than we might want that the provenance of the pointer returned by `ptr::with_exposed_provenance`[^1] is the same as that what was exposed, which is not yet specified as such IIUC. IMHO `expose` does not make that connection.~~

A previous version of this PR suggested `expose` as name, libs-api [decided on](https://github.com/rust-lang/rust/pull/122964#issuecomment-2033194319) `expose_provenance` to keep the symmetry with `with_exposed_provenance`.

CC `@RalfJung`
r? libs-api

[^1]: I'm using the new name for `from_exposed_addr` suggested by #122935 here.
2024-04-03 22:11:00 +02:00
Ralf Jung a6803b9de4 add 'x.py miri', and make it work for 'library/{core,alloc,std}' 2024-04-03 20:27:20 +02:00
Maybe Waffle 7b5af57303 Add docs for `FromIterator<(AE, BE)> for (A, B)` 2024-04-03 17:48:54 +00:00
Maybe Waffle 03862a5538 Implement `FromIterator<(AE, BE)>` for `(impl Default+Extend<AE>, impl Default+Extend<BE>)` 2024-04-03 17:37:32 +00:00
joboet 989660c3e6
rename `expose_addr` to `expose_provenance` 2024-04-03 16:00:38 +02:00
joboet 061d8731fb
std: add comment about abort motivation 2024-04-03 14:33:43 +02:00
bors ceab6128fa Auto merge of #123390 - tgross35:f16-f128-libs-basic-impls-bootstrap, r=jhpratt
Put basic impls for f16 and f128 behind cfg(not(bootstrap))

We will lose `f16` and `f128` in the beta compiler after the revert for <https://github.com/rust-lang/rust/issues/123282> lands. Change what was added in <https://github.com/rust-lang/rust/pull/123085> to be behind `#[cfg(not(bootstrap))]` to account for this.
2024-04-03 12:32:34 +00:00
Jubilee 0c0d88864a
Rollup merge of #123388 - tshepang:consistency, r=jhpratt
use a consistent style for links
2024-04-02 23:44:29 -07:00
Jubilee abb0393595
Rollup merge of #122411 - alexcrichton:wasm32-wasip2-cabi-realloc, r=m-ou-se
Provide cabi_realloc on wasm32-wasip2 by default

This commit provides a component model intrinsic in the standard library
by default on the `wasm32-wasip2` target. This intrinsic is not
required by the component model itself but is quite common to use, for
example it's needed if a wasm module receives a string or a list.

The intention of this commit is to provide an overridable definition in
the standard library through a weak definition of this function. That
means that downstream crates can provide their own customized and more
specific versions if they'd like, but the standard library's version
should suffice for general-purpose use.
2024-04-02 23:44:28 -07:00
Jacob Pratt 9c1c0bfcb2
Rollup merge of #123203 - jkarneges:context-ext, r=Amanieu
Add `Context::ext`

This change enables `Context` to carry arbitrary extension data via a single `&mut dyn Any` field.

```rust
#![feature(context_ext)]

impl Context {
    fn ext(&mut self) -> &mut dyn Any;
}

impl ContextBuilder {
    fn ext(self, data: &'a mut dyn Any) -> Self;

    fn from(cx: &'a mut Context<'_>) -> Self;
    fn waker(self, waker: &'a Waker) -> Self;
}
```

Basic usage:

```rust
struct MyExtensionData {
    executor_name: String,
}

let mut ext = MyExtensionData {
    executor_name: "foo".to_string(),
};

let mut cx = ContextBuilder::from_waker(&waker).ext(&mut ext).build();

if let Some(ext) = cx.ext().downcast_mut::<MyExtensionData>() {
    println!("{}", ext.executor_name);
}
```

Currently, `Context` only carries a `Waker`, but there is interest in having it carry other kinds of data. Examples include [LocalWaker](https://github.com/rust-lang/rust/issues/118959), [a reactor interface](https://github.com/rust-lang/libs-team/issues/347), and [multiple arbitrary values by type](https://docs.rs/context-rs/latest/context_rs/). There is also a general practice in the ecosystem of sharing data between executors and futures via thread-locals or globals that would arguably be better shared via `Context`, if it were possible.

The `ext` field would provide a low friction (to stabilization) solution to enable experimentation. It would enable experimenting with what kinds of data we want to carry as well as with what data structures we may want to use to carry such data.

Dedicated fields for specific kinds of data could still be added directly on `Context` when we have sufficient experience or understanding about the problem they are solving, such as with `LocalWaker`. The `ext` field would be for data for which we don't have such experience or understanding, and that could be graduated to dedicated fields once proven.

Both the provider and consumer of the extension data must be aware of the concrete type behind the `Any`. This means it is not possible for the field to carry an abstract interface. However, the field can carry a concrete type which in turn carries an interface. There are different ways one can imagine an interface-carrying concrete type to work, hence the benefit of being able to experiment with such data structures.

## Passing interfaces

Interfaces can be placed in a concrete type, such as a struct, and then that type can be casted to `Any`. However, one gotcha is `Any` cannot contain non-static references. This means one cannot simply do:

```rust
struct Extensions<'a> {
    interface1: &'a mut dyn Trait1,
    interface2: &'a mut dyn Trait2,
}

let mut ext = Extensions {
    interface1: &mut impl1,
    interface2: &mut impl2,
};

let ext: &mut dyn Any = &mut ext;
```

To work around this without boxing, unsafe code can be used to create a safe projection using accessors. For example:

```rust
pub struct Extensions {
    interface1: *mut dyn Trait1,
    interface2: *mut dyn Trait2,
}

impl Extensions {
    pub fn new<'a>(
        interface1: &'a mut (dyn Trait1 + 'static),
        interface2: &'a mut (dyn Trait2 + 'static),
        scratch: &'a mut MaybeUninit<Self>,
    ) -> &'a mut Self {
        scratch.write(Self {
            interface1,
            interface2,
        })
    }

    pub fn interface1(&mut self) -> &mut dyn Trait1 {
        unsafe { self.interface1.as_mut().unwrap() }
    }

    pub fn interface2(&mut self) -> &mut dyn Trait2 {
        unsafe { self.interface2.as_mut().unwrap() }
    }
}

let mut scratch = MaybeUninit::uninit();
let ext: &mut Extensions = Extensions::new(&mut impl1, &mut impl2, &mut scratch);

// ext can now be casted to `&mut dyn Any` and back, and used safely
let ext: &mut dyn Any = ext;
```

## Context inheritance

Sometimes when futures poll other futures they want to provide their own `Waker` which requires creating their own `Context`. Unfortunately, polling sub-futures with a fresh `Context` means any properties on the original `Context` won't get propagated along to the sub-futures. To help with this, some additional methods are added to `ContextBuilder`.

Here's how to derive a new `Context` from another, overriding only the `Waker`:

```rust
let mut cx = ContextBuilder::from(parent_cx).waker(&new_waker).build();
```
2024-04-02 20:37:40 -04:00
Jacob Pratt e9ef8e1efa
Rollup merge of #122935 - RalfJung:with-exposed-provenance, r=Amanieu
rename ptr::from_exposed_addr -> ptr::with_exposed_provenance

As discussed on [Zulip](https://rust-lang.zulipchat.com/#narrow/stream/136281-t-opsem/topic/To.20expose.20or.20not.20to.20expose/near/427757066).

The old name, `from_exposed_addr`, makes little sense as it's not the address that is exposed, it's the provenance. (`ptr.expose_addr()` stays unchanged as we haven't found a better option yet. The intended interpretation is "expose the provenance and return the address".)

The new name nicely matches `ptr::without_provenance`.
2024-04-02 20:37:39 -04:00
Justin Karneges 036085dfec set tracking issue 2024-04-02 15:45:53 -07:00
bors 88c2f4f5f5 Auto merge of #123385 - matthiaskrgr:rollup-v69vjbn, r=matthiaskrgr
Rollup of 8 pull requests

Successful merges:

 - #123198 (Add fn const BuildHasherDefault::new)
 - #123226 (De-LLVM the unchecked shifts [MCP#693])
 - #123302 (Make sure to insert `Sized` bound first into clauses list)
 - #123348 (rustdoc: add a couple of regression tests)
 - #123362 (Check that nested statics in thread locals are duplicated per thread.)
 - #123368 (CFI: Support non-general coroutines)
 - #123375 (rustdoc: synthetic auto trait impls: accept unresolved region vars for now)
 - #123378 (Update sysinfo to 0.30.8)

Failed merges:

 - #123349 (Fix capture analysis for by-move closure bodies)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-04-02 21:23:53 +00:00
Trevor Gross 049a917535 Put basic impls for f16 and f128 behind cfg(not(bootstrap))
We will lose `f16` and `f128` in the beta compiler after the revert for
<https://github.com/rust-lang/rust/issues/123282> lands. Change what was
added in <https://github.com/rust-lang/rust/pull/123085> to be behind
`#[cfg(not(bootstrap))]` to account for this.
2024-04-02 16:19:55 -04:00
Chris Denton e457b77e2a
Avoid panicking unnecessarily on startup 2024-04-02 19:41:58 +00:00
Tshepang Mbambo a6b2d12c92 use a consistent style for links 2024-04-02 21:41:16 +02:00
Matthias Krüger 1b0e46f8a0
Rollup merge of #123226 - scottmcm:u32-shifts, r=WaffleLapkin
De-LLVM the unchecked shifts [MCP#693]

This is just one part of the MCP (https://github.com/rust-lang/compiler-team/issues/693), but it's the one that IMHO removes the most noise from the standard library code.

Seems net simpler this way, since MIR already supported heterogeneous shifts anyway, and thus it's not more work for backends than before.

r? WaffleLapkin
2024-04-02 21:22:01 +02:00
Matthias Krüger d63ddef803
Rollup merge of #123198 - krtab:build_hasher_default_const_new, r=Amanieu
Add fn const BuildHasherDefault::new

See [tracking issue](https://github.com/rust-lang/rust/issues/123197) for justification.
2024-04-02 21:22:00 +02:00
bors a77322c16f Auto merge of #118310 - scottmcm:three-way-compare, r=davidtwco
Add `Ord::cmp` for primitives as a `BinOp` in MIR

Update: most of this OP was written months ago.  See https://github.com/rust-lang/rust/pull/118310#issuecomment-2016940014 below for where we got to recently that made it ready for review.

---

There are dozens of reasonable ways to implement `Ord::cmp` for integers using comparison, bit-ops, and branches.  Those differences are irrelevant at the rust level, however, so we can make things better by adding `BinOp::Cmp` at the MIR level:

1. Exactly how to implement it is left up to the backends, so LLVM can use whatever pattern its optimizer best recognizes and cranelift can use whichever pattern codegens the fastest.
2. By not inlining those details for every use of `cmp`, we drastically reduce the amount of MIR generated for `derive`d `PartialOrd`, while also making it more amenable to MIR-level optimizations.

Having extremely careful `if` ordering to μoptimize resource usage on broadwell (#63767) is great, but it really feels to me like libcore is the wrong place to put that logic.  Similarly, using subtraction [tricks](https://graphics.stanford.edu/~seander/bithacks.html#CopyIntegerSign) (#105840) is arguably even nicer, but depends on the optimizer understanding it (https://github.com/llvm/llvm-project/issues/73417) to be practical.  Or maybe [bitor is better than add](https://discourse.llvm.org/t/representing-in-ir/67369/2?u=scottmcm)?  But maybe only on a future version that [has `or disjoint` support](https://discourse.llvm.org/t/rfc-add-or-disjoint-flag/75036?u=scottmcm)?  And just because one of those forms happens to be good for LLVM, there's no guarantee that it'd be the same form that GCC or Cranelift would rather see -- especially given their very different optimizers.  Not to mention that if LLVM gets a spaceship intrinsic -- [which it should](https://rust-lang.zulipchat.com/#narrow/stream/131828-t-compiler/topic/Suboptimal.20inlining.20in.20std.20function.20.60binary_search.60/near/404250586) -- we'll need at least a rustc intrinsic to be able to call it.

As for simplifying it in Rust, we now regularly inline `{integer}::partial_cmp`, but it's quite a large amount of IR.  The best way to see that is with 8811efa88b (diff-d134c32d028fbe2bf835fef2df9aca9d13332dd82284ff21ee7ebf717bfa4765R113) -- I added a new pre-codegen MIR test for a simple 3-tuple struct, and this PR change it from 36 locals and 26 basic blocks down to 24 locals and 8 basic blocks.  Even better, as soon as the construct-`Some`-then-match-it-in-same-BB noise is cleaned up, this'll expose the `Cmp == 0` branches clearly in MIR, so that an InstCombine (#105808) can simplify that to just a `BinOp::Eq` and thus fix some of our generated code perf issues.  (Tracking that through today's `if a < b { Less } else if a == b { Equal } else { Greater }` would be *much* harder.)

---

r? `@ghost`
But first I should check that perf is ok with this
~~...and my true nemesis, tidy.~~
2024-04-02 19:21:44 +00:00
Adam Gemmell 8923b589bd Document restricted_std
This PR aims to pin down exactly what restricted_std is meant to achieve
and what it isn't.

This commit fixes https://github.com/rust-lang/wg-cargo-std-aware/issues/87
by explaining why the error appears and what the choices the user has.
The error describes how std cannot function without knowing about some
form of OS/platform support. Any features of std that work without an
OS should be moved to core/alloc (see https://github.com/rust-lang/rust/issues/27242
https://github.com/rust-lang/rust/issues/103765).

Note that the message says "platform" and "environment" because, since
https://github.com/rust-lang/rust/pull/120232, libstd can be built for
some JSON targets. This is still unsupported (all JSON targets probably
should be unstable https://github.com/rust-lang/wg-cargo-std-aware/issues/90),
but a JSON target with the right configuration should hopefully have
some partial libstd support.

I propose closing https://github.com/rust-lang/wg-cargo-std-aware/issues/69
as "Won't fix" since any support of std without properly configured os,
vendor or env fields is very fragile considering future upgrades of Rust
or dependencies. In addition there's no likely path to it being fixed
long term (making std buildable for all targets being the only
solution). This is distinct from tier 3 platforms with limited std
support implemented (and as such aren't restricted_std) because these
platforms can conceptually work in the future and std support should
mainly improve over time.

The alternative to closing https://github.com/rust-lang/wg-cargo-std-aware/issues/69
is a new crate feature for std which escapes the restricted_std
mechanism in build.rs. It could be used with the -Zbuild-std-features
flag if we keep it permanently unstable, which I hope we can do anyway.
A minor side-effect in this scenario is that std wouldn't be marked as
unstable if documentation for it were generated with build-std.
2024-04-02 12:05:12 +01:00
joboet e7b5730d36
std: reduce code size of `set_current` 2024-04-02 11:41:31 +02:00
Steve Lau bb439900dd style: fmt 2024-04-02 14:29:38 +08:00
Steve Lau 6ad96825fc fix: build on haiku by adding missing import 2024-04-02 14:18:31 +08:00
bors 6bbd8c519a Auto merge of #122945 - andy-k:sorted-vec-example, r=jhpratt
improve example on inserting to a sorted vector to avoid shifting equal elements
2024-04-02 03:14:05 +00:00
Jubilee 48b2a517fc
Rollup merge of #123323 - devnexen:thread_set_name_solaris_fix, r=workingjubilee
std:🧵 set_name change for solaris/illumos.

truncate down to 32 (31 + 1) for solaris/illumos.
2024-04-01 17:22:10 -07:00
David Carlier ca36fe310e
std:🧵 set_name change for solaris/illumos.
truncate down to 32 (31 + 1) for solaris/illumos.
2024-04-01 22:16:13 +01:00
bors a7e3b1c8c5 Auto merge of #123315 - devnexen:thread_get_name_solaris, r=ChrisDenton
std:🧵 adding get_name implementation for solaris/illumos.

THREAD_NAME_MAX is 32 (31 max + 1 for the null terminator).
2024-04-01 16:38:55 +00:00
bors c518e5aeec Auto merge of #123265 - joboet:guardians_of_the_unix, r=ChrisDenton
Refactor stack overflow handling

Currently, every platform must implement a `Guard` that protects a thread from stack overflow. However, UNIX is the only platform that actually does so. Windows has a different mechanism for detecting stack overflow, while the other platforms don't detect it at all. Also, the UNIX stack overflow handling is split between `sys::pal::unix::stack_overflow`, which implements the signal handler, and `sys::pal::unix::thread`, which detects/installs guard pages.

This PR cleans this by getting rid of `Guard` and unifying UNIX stack overflow handling inside `stack_overflow` (commit 1). Therefore we can get rid of `sys_common::thread_info`, which stores `Guard` and the current `Thread` handle and move the `thread::current` TLS variable into `thread` (commit 2).

The second commit is not strictly speaking necessary. To keep the implementation clean, I've included it here, but if it causes too much noise, I can split it out without any trouble.
2024-04-01 14:35:38 +00:00
joboet d7b55e4c90
update comment 2024-04-01 15:28:27 +02:00
David Carlier 747d19326b
std:🧵 adding get_name implementation for solaris/illumos.
THREAD_NAME_MAX is 32 (31 max + 1 for the null terminator).
2024-04-01 10:01:21 +01:00
beetrees 0bbaa2505b
Fix error message for `env!` when env var is not valid Unicode 2024-04-01 05:44:45 +01:00
bors 66de611196 Auto merge of #123270 - JaniM:janim/string-alloc-doc, r=workingjubilee
doc: mention heap allocation earlier in String docs

Just a tiny addition.

Helps with #123263.
2024-03-31 22:39:04 +00:00
Jani Mustonen 418535b798 doc: mention heap allocation earlier in String docs
Just a tiny addition.

Helps with #123263.
2024-04-01 00:04:57 +03:00
bors 8058136502 Auto merge of #123299 - workingjubilee:rollup-2z8amaj, r=workingjubilee
Rollup of 5 pull requests

Successful merges:

 - #123180 (Rewrite `core-no-fp-fmt-parse` test in Rust)
 - #123267 (std:🧵 adding get_name haiku implementation.)
 - #123268 (warn against implementing Freeze)
 - #123271 (doc: describe panic conditions for SliceIndex implementations)
 - #123295 (add myself to compiler review rotation)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-03-31 20:35:15 +00:00
Jubilee 42ca32673a
Rollup merge of #123271 - JaniM:janim/sliceindex-doc, r=Nilstrieb
doc: describe panic conditions for SliceIndex implementations

Implementation note: The most probable place for users to find the documentation is at https://doc.rust-lang.org/std/slice/trait.SliceIndex.html

On that page, documentation added to specific methods will not be visible. As such, I opted to add the comments to the impl blocks directly.

Helps with #121568.
2024-03-31 13:18:17 -07:00
Jubilee 9ff4c70476
Rollup merge of #123268 - RalfJung:dont-freeze, r=Nilstrieb
warn against implementing Freeze

As [requested](https://github.com/rust-lang/rust/pull/123184#issuecomment-2028531388) by `@workingjubilee`
2024-03-31 13:18:17 -07:00
Ralf Jung 602401c4d4 warn against implementing Freeze 2024-03-31 22:15:48 +02:00
David Carlier e5c5ed00a5 std:🧵 adding get_name haiku implementation.
follow-up #123233
2024-03-31 17:47:44 +01:00
Jani Mustonen 4ca3151568 doc: describe panic conditions for SliceIndex implementations
Implementation note: The most probable place for users to find
the documentation is at https://doc.rust-lang.org/std/slice/trait.SliceIndex.html

On that page, documentation added to specific methods will not
be visible. As such, I opted to add the comments to the impl blocks
directly.

Helps with #121568.
2024-03-31 16:13:25 +03:00
Ralf Jung 42972f52de catch_panic: warn about panicking payload drop 2024-03-31 11:54:16 +02:00
joboet 7668418101
std: move `thread::current` TLS variable out of `thread_info` 2024-03-31 11:28:24 +02:00
joboet 5b9d7ab558
std: move UNIX stack overflow guard page handling into `stack_overflow.rs` 2024-03-31 11:24:33 +02:00
bors 5f358a848c Auto merge of #123233 - devnexen:thread_get_name_bsd, r=joboet
std:🧵 adding freebsd/netbsd to the linux's get_name implementa…

…tion.
2024-03-31 04:18:47 +00:00
Stepan Koltsov 8f5a28e0aa Require Pointee::Metadata to be Freeze
So pointee metadata can be used in anonymous statics.

This is prerequisite for implementing ThinBox without allocation for
ZST.

See https://github.com/rust-lang/rust/pull/123184#discussion_r1544627488
2024-03-31 03:35:17 +01:00
bors 1aedc9640c Auto merge of #123181 - stepancheg:pointee-metadata-debug, r=the8472,Amanieu
Require Debug for Pointee::Metadata

Useful for debugging.
2024-03-31 00:09:41 +00:00
bors 5da1a1b59a Auto merge of #123085 - tgross35:f16-f128-step4.0-libs-basic-impls, r=Amanieu
Add basic trait impls for `f16` and `f128`

Split off part of <https://github.com/rust-lang/rust/pull/122470> so the compiler doesn't ICE because it expects primitives to have some minimal traits.

Fixes <https://github.com/rust-lang/rust/issues/123074>
2024-03-30 21:58:49 +00:00
bors 8df7e723ea Auto merge of #99322 - GKFX:const-int-parse, r=Mark-Simulacrum
Make {integer}::from_str_radix constant

This commit makes FromStr on integers constant so that `const x: u32 = "23".parse();` works. More practical use-case is with environment variables at build time as discussed in https://github.com/rust-lang/rfcs/issues/1907.

Tracking issue #59133.

ACP: https://github.com/rust-lang/libs-team/issues/74
2024-03-30 19:56:58 +00:00
David Carlier c749483e26 std:🧵 adding freebsd/netbsd to the linux's get_name implementation. 2024-03-30 16:01:47 +00:00
Matthias Krüger 558880ab88
Rollup merge of #123201 - Wilfred:patch-2, r=Nilstrieb
Improve wording in std::any explanation

Prefer 'log' over 'log out' to avoid confusion, and use backticks consistently.
2024-03-30 14:30:50 +01:00
George Bateman 3855b8bb60
Make {integer}::from_str_radix constant 2024-03-30 12:43:58 +00:00
Scott McMurray 0601f0c66d De-LLVM the unchecked shifts [MCP#693]
This is just one part of the MCP, but it's the one that IMHO removes the most noise from the standard library code.

Seems net simpler this way, since MIR already supported heterogeneous shifts anyway, and thus it's not more work for backends than before.
2024-03-30 03:32:11 -07:00
bors 174d07b539 Auto merge of #121948 - Gankra:stab-align, r=dtolnay
stabilize ptr.is_aligned, move ptr.is_aligned_to to a new feature gate

This is an alternative to #121920
2024-03-30 04:36:09 +00:00
bors 877d36b192 Auto merge of #122976 - caibear:optimize_reserve_for_push, r=cuviper
Remove len argument from RawVec::reserve_for_push

Removes `RawVec::reserve_for_push`'s `len` argument since it's always the same as capacity.
Also makes `Vec::insert` use `RawVec::reserve_for_push`.
2024-03-30 00:29:24 +00:00
Aria Beingessner ea92faec49 stabilize ptr.is_aligned, move ptr.is_aligned_to to a new feature gate
This is an alternative to #121920
2024-03-29 19:59:46 -04:00
bors faae5f1ffe Auto merge of #122520 - scottmcm:stabilize_unchecked_math_basics, r=jhpratt
Stabilize `unchecked_{add,sub,mul}`

Tracking issue: #85122

I think we might as well just stabilize these basic three.  They're the ones that have `nuw`/`nsw` flags in LLVM.

Notably, this doesn't include the potentially-more-complex or -more-situational things like `unchecked_neg` or `unchecked_shr` that are under different feature flags.

To quote Ralf https://github.com/rust-lang/rust/issues/85122#issuecomment-1681669646,

> Are there any objections to stabilizing at least `unchecked_{add,sub,mul}`? For those there shouldn't be any surprises about what their safety requirements are.

*Semantially* these are [already available on stable, even in `const`, via](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=bdb1ff889b61950897f1e9f56d0c9a36) `checked_*`+`unreachable_unchecked`.  So IMHO we might as well just let people write them directly, rather than try to go through a `let Some(x) = x.checked_add(y) else { unsafe { hint::unreachable_unchecked() }};` dance.

I added additional text to each method to attempt to better describe the behaviour and encourage `wrapping_*` instead.

r? rust-lang/libs-api
2024-03-29 20:25:08 +00:00
Justin Karneges 13838a53fd rustfmt 2024-03-29 12:16:09 -07:00
bors af4a5a13a1 Auto merge of #121268 - Urgau:improve_ambi_wide_ptr_cmps, r=Nadrieril
Add detection of [Partial]Ord methods in the `ambiguous_wide_pointer_comparisons` lint

Partially addresses https://github.com/rust-lang/rust/issues/121264 by adding diagnostics items for PartialOrd and Ord methods, detecting such diagnostics items as "binary operation" and suggesting the correct replacement.

I also took the opportunity to change the suggestion to use new methods `.cast()` on `*mut T` an d `*const T`.
2024-03-29 18:23:57 +00:00
Justin Karneges c6ac3b02db Add `Context::ext` 2024-03-29 10:12:10 -07:00
Wilfred Hughes 7804edebfe
Improve wording in std::any explanation
Prefer 'log' over 'log out' to avoid confusion, and use backticks consistently.
2024-03-29 10:10:52 -07:00
Arthur Carcano 54ab425839 Add fn const BuildHasherDefault::new
Because `HashMap::with_hasher` constness is being stabilized this will
in turn allow creating empty HashMap<K,V,BuildHasherDefault<H>> in const
context for any H: Default + Hasher.
2024-03-29 17:10:17 +01:00
Urgau d4b514f982 Add detection of [Partial]Ord methods to the ambiguous wide ptr cmp lint 2024-03-29 16:36:17 +01:00
Urgau 4a9f3cac88 Add diagnostic items for Ord and PartialOrd methods 2024-03-29 16:25:41 +01:00
bors 1c19595575 Auto merge of #122616 - Jules-Bertholet:casemappingiter-layout, r=Nilstrieb
Optimize `core::char::CaseMappingIter`

Godbolt says this saves a few instructions…

`@rustbot` label T-libs A-layout C-optimization
2024-03-29 07:02:56 +00:00
Stepan Koltsov b110cb3dc6 Require Debug for Pointee::Metadata
Useful for debugging
2024-03-29 03:53:29 +00:00
bors 760e567af5 Auto merge of #122975 - DianQK:simplify_ub_check, r=saethlin
Eliminate `UbChecks` for non-standard libraries

 The purpose of this PR is to allow other passes to treat `UbChecks` as constants in MIR for optimization after #122629.

r? RalfJung
2024-03-29 02:25:43 +00:00
bors db2f9759f4 Auto merge of #122671 - Mark-Simulacrum:const-panic-msg, r=Nilstrieb
Codegen const panic messages as function calls

This skips emitting extra arguments at every callsite (of which there
can be many). For a librustc_driver build with overflow checks enabled,
this cuts 0.7MB from the resulting shared library (see [perf]).

A sample improvement from nightly:

```
        leaq    str.0(%rip), %rdi
        leaq    .Lalloc_d6aeb8e2aa19de39a7f0e861c998af13(%rip), %rdx
        movl    $25, %esi
        callq   *_ZN4core9panicking5panic17h17cabb89c5bcc999E@GOTPCREL(%rip)
```

to this PR:

```
        leaq    .Lalloc_d6aeb8e2aa19de39a7f0e861c998af13(%rip), %rdi
        callq   *_RNvNtNtCsduqIKoij8JB_4core9panicking11panic_const23panic_const_div_by_zero@GOTPCREL(%rip)
```

[perf]: https://perf.rust-lang.org/compare.html?start=a7e4de13c1785819f4d61da41f6704ed69d5f203&end=64fbb4f0b2d621ff46d559d1e9f5ad89a8d7789b&stat=instructions:u
2024-03-29 00:24:01 +00:00
Cai Bear aba592d09c Rename reserve_for_push to grow_one and fix comment. 2024-03-28 16:38:01 -07:00
Cai Bear 78dc89b0d5 Fix previous. 2024-03-28 16:21:54 -07:00
Cai Bear 18d390883e Remove len argument from RawVec::reserve_for_push because it's always equal to capacity. Also make Vec::insert use reserve_for_push. 2024-03-28 16:21:54 -07:00
Trevor Gross d7d5fc9734 Add basic trait impls for `f16` and `f128`
Split off part of <https://github.com/rust-lang/rust/pull/122470> so the
compiler doesn't ICE because it expects primitives to have some minimal
traits.

Fixes <https://github.com/rust-lang/rust/issues/123074>
2024-03-28 15:02:51 -04:00
Matthias Krüger 83b4d3d638
Rollup merge of #123164 - Marcondiro:unicode15-1, r=Manishearth
Bump Unicode printables to version 15.1, align to unicode_data

r? `@Manishearth`
Thanks!
2024-03-28 17:40:51 +01:00
Marcondiro e9870b5df3
Bump Unicode printables to version 15.1, align to unicode_data 2024-03-28 11:21:52 +01:00
Matthias Krüger 9c91e2cd84
Rollup merge of #123139 - scottmcm:simpler-nonzero-get, r=jhpratt
`num::NonZero::get` can be 1 transmute instead of 2

Just something I noticed in passing.  No need for a `match` in here to call `unreachable_unchecked`, as `transmute_unchecked` will add the appropriate `llvm.assume` <https://rust.godbolt.org/z/W5hjeETnc>.
2024-03-27 23:27:25 +01:00
Matthias Krüger ea7789c56e
Rollup merge of #123136 - Vagelis-Prokopiou:fix/docs, r=ChrisDenton
Some wording improvement

"Data" is usually considered as plural uncountable, therefore "some" seems to make more sense imo.
2024-03-27 23:27:24 +01:00
Matthias Krüger 45cec32ac3
Rollup merge of #123133 - xiaoxiangxianzi:master, r=fmease
chore: fix some comments
2024-03-27 23:27:24 +01:00
Matthias Krüger a9ed9fb943
Rollup merge of #121943 - joshlf:patch-11, r=scottmcm
Clarify atomic bit validity

The previous definition used the phrase "representation", which is ambiguous given the current state of memory model nomenclature in Rust. For integer types and for `AtomicPtr<T>`, the new wording clarifies that size and bit validity are guaranteed to match the corresponding native integer type/`*mut T`. For `AtomicBool`, the new wording clarifies that size, alignment, and bit validity are guaranteed to match `bool`.

Note that we use the phrase "size and alignment" rather than "layout" since the latter term also implies that the field types are the same. This isn't true - `AtomicXxx` doesn't store an `xxx`, but rather an `UnsafeCell<xxx>`. This distinction is important for some `unsafe` code, which needs to reason about the presence or absence of interior mutability in order to ensure that their code is sound (see e.g. https://github.com/google/zerocopy/issues/251).
2024-03-27 23:27:22 +01:00
Scott McMurray 336ff42367 `num::NonZero::get` can be 1 transmute instead of 3 2024-03-27 10:25:56 -07:00
Kornel 443e29cd97 Less generic code for Vec allocations 2024-03-27 15:27:47 +00:00
Vagelis Prokopiou cc4a1f42e6 Some wording improvement 2024-03-27 17:26:18 +02:00
xiaoxiangxianzi 3157114f0b chore: fix some comments
Signed-off-by: xiaoxiangxianzi <zhaoyizheng@outlook.com>
2024-03-27 22:32:53 +08:00
DianQK 47ed73a7b5
Eliminate `UbCheck` for non-standard libraries 2024-03-27 21:02:40 +08:00
bors 10a7aa14fe Auto merge of #123128 - GuillaumeGomez:rollup-3l3zu6s, r=GuillaumeGomez
Rollup of 6 pull requests

Successful merges:

 - #121843 (Implement `-L KIND=`@RUSTC_BUILTIN/...`)`
 - #122860 (coverage: Re-enable `UnreachablePropagation` for coverage builds)
 - #123021 (Make `TyCtxt::coroutine_layout` take coroutine's kind parameter)
 - #123024 (CFI: Enable KCFI testing of run-pass tests)
 - #123083 (lib: fix some unnecessary_cast clippy lint)
 - #123116 (rustdoc: Swap fields and variant documentations)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-03-27 09:32:38 +00:00
Guillaume Gomez 64a9360d3f
Rollup merge of #123083 - klensy:clippy-me, r=workingjubilee
lib: fix some unnecessary_cast clippy lint

Fixes few instances of `unnecessary_cast` clippy lint
2024-03-27 10:13:44 +01:00
tison 95e195f41e
impl get_mut_or_init and get_mut_or_try_init for OnceCell and OnceLock
See also https://github.com/rust-lang/rust/issues/74465#issuecomment-1676522051

Signed-off-by: tison <wander4096@gmail.com>
2024-03-27 16:16:08 +08:00
bors 0dcc1309d0 Auto merge of #116016 - jhpratt:kill-rustc-serialize, r=ehuss
Soft-destabilize `RustcEncodable` & `RustcDecodable`, remove from prelude in next edition

cc rust-lang/libs-team#272

Any use of `RustcEncodable` and `RustcDecodable` now triggers a deny-by-default lint. The derives have been removed from the 2024 prelude. I specifically chose **not** to document this in the module-level documentation, as the presence in existing preludes is not documented (which I presume is intentional).

This does not implement the proposed change for `rustfix`, which I will be looking into shortly.

With regard to the items in the preludes being stable, this should not be an issue because #15702 has been resolved.

r? libs-api
2024-03-27 07:30:36 +00:00
Matthias Krüger bce525323d
Rollup merge of #123118 - tgross35:rwlock-docs, r=workingjubilee
Update `RwLock` deadlock example to not use shadowing

Tweak variable names in the deadlock example to remove any potential confusion that the behavior is somehow shadowing-related.
2024-03-27 05:21:18 +01:00
Matthias Krüger 19a40ec5bf
Rollup merge of #123107 - avandesa:vec_pop_if, r=joboet
Implement `Vec::pop_if`

This PR adds `Vec::pop_if` to the public API, behind the `vec_pop_if` feature.

```rust
impl<T> Vec<T> {
    pub fn pop_if<F>(&mut self, f: F) -> Option<T>
        where F: FnOnce(&mut T) -> bool;
}
```

Tracking issue: #122741

## Open questions

- [ ] Should the first unit test be split up?
- [ ] I don't see any guidance on ordering of methods in impl blocks, should I move the method elsewhere?
2024-03-27 05:21:18 +01:00
Matthias Krüger 910e23bbbb
Rollup merge of #123084 - a1phyr:unixstream_read_buf, r=workingjubilee
`UnixStream`: override `read_buf`

Split from #122441

r? ``@workingjubilee``
2024-03-27 05:21:17 +01:00
Matthias Krüger d589021b4b
Rollup merge of #123038 - he32:netbsd-ilp32-fix, r=workingjubilee
std library thread.rs: fix NetBSD code for ILP32 CPUs.
2024-03-27 05:21:16 +01:00
Matthias Krüger 4bdf1711c6
Rollup merge of #122880 - a1phyr:preadv_more_platform, r=workingjubilee
Unix: Support more platforms with `preadv` and `pwritev`

- `aix`, `dragonfly` and `openbsd` with direct call
- `watchos` with weak linkage

cc #89517
2024-03-27 05:21:15 +01:00
Trevor Gross 0cd57725f9 Update `RwLock` deadlock example to not use shadowing
Tweak variable names in the deadlock example to remove any potential
confusion that the behavior is somehow shadowing-related.
2024-03-26 21:40:31 -04:00
Alex van de Sandt 07d3806eb1 Implement `Vec::pop_if` 2024-03-26 18:25:24 -04:00
Matthias Krüger ac5ffa51cd
Rollup merge of #123057 - sthibaul:systemtime, r=jhpratt
unix fs: Make hurd using explicit new rather than From

408c0ea216 ("unix time module now return result") dropped the From impl for SystemTime, breaking the hurd build (and probably the horizon build)

Fixes #123032
2024-03-26 21:23:50 +01:00
Matthias Krüger 0029a11d7d
Rollup merge of #122835 - compiler-errors:deref-pure, r=Nadrieril
Require `DerefMut` and `DerefPure` on `deref!()` patterns when appropriate

Waiting on the deref pattern syntax pr to merge

r? nadrieril
2024-03-26 21:23:48 +01:00
Matthias Krüger a4bf7224cb
Rollup merge of #123086 - ding-young:fix-ref-to-BufWriter, r=the8472
Fix doc link to BufWriter in std::fs::File documentation

It seems that doc link to `BufWriter` in `std::fs::File` doc leads to `BufReader`, not `BufWriter`.
See https://doc.rust-lang.org/std/fs/struct.File.html
2024-03-26 17:06:42 +01:00
Samuel Thibault 7b4e507961 unix fs: Make hurd and horizon using explicit new rather than From
408c0ea216 ("unix time module now return result") dropped the From
impl for SystemTime, breaking the hurd and horizon builds.

Fixes #123032
2024-03-26 15:58:00 +01:00
bors 536606bc5d Auto merge of #122939 - joboet:proc_macro_bridge_state, r=petrochenkov
Simplify proc macro bridge state

Currently, `proc_macro` uses a `ScopedCell` to store the client-side proc-macro bridge. Unfortunately, this requires the `Bridge`, which has non-negligible size, to be copied out and back again on every access. In some cases, the optimizer might be able to elide these copies, but in general, this is suboptimal.

This PR removes `ScopedCell` and employs a similar trick as in [`scoped_tls`](https://crates.io/crates/scoped-tls), meaning that the only thing stored in TLS is a pointer to the state, which now is a `RefCell`. Access to the pointer is then scoped so that it is always within the lifetime of the reference to the state. Unfortunately, `scoped_tls` requires the referenced type to be `'static`, which `Bridge` is not, therefore we cannot simply copy that macro but have to reimplement its TLS trick.

This removes the `#[forbid(unsafe_code)]` on the `client` module so that we do not have to export `Bridge`, which currently is private, to the whole crate. I can change that, if necessary.
2024-03-26 13:05:59 +00:00
Benoît du Garreau ff6d9f79ae Unix: Support more platforms with `preadv` and `pwritev` 2024-03-26 10:39:14 +01:00
Benoît du Garreau bff13e98ad `UnixStream`: override `read_buf` 2024-03-26 10:11:29 +01:00
ding-young a241ffc6b6 Fix link to BufWriter 2024-03-26 18:04:19 +09:00
Havard Eidnes 1ad3954668 std library unix/thread.rs: fix NetBSD code for ILP32 CPUs. 2024-03-26 08:39:42 +00:00
Ralf Jung 6e190fa993 panic_str only exists for the migration to 2021 panic macros 2024-03-26 08:11:34 +01:00
Michael Goulet fc1d7d275b Extract helper, fix comment on DerefPure 2024-03-25 19:39:45 -04:00
Michael Goulet b56279569b Require DerefPure for patterns 2024-03-25 19:39:45 -04:00
Jubilee ac0a9c58e8
Rollup merge of #123042 - dpaoliello:prelude, r=Nilstrieb
Import the 2021 prelude in the core crate

The `core` crate currently imports the v1 prelude
b3df0d7e5e/library/core/src/lib.rs (L285-L287)

This recently caused an issue when updating the `portable-simd` subtree since it was using a trait that was added to the 2021 prelude: https://github.com/rust-lang/rust/pull/122905#discussion_r1536228822

To make it easier to have a consistent build environment for subtrees and submodules that get included in `core`, we will now import the 2021 prelude into `core`.

Fixes #122912

r? `@Nilstrieb`
2024-03-25 14:35:37 -07:00
Jubilee cf9acea658
Rollup merge of #122896 - dpaoliello:stdarch, r=Amanieu
Update stdarch submodule

r? ```@Amanieu```
2024-03-25 14:35:35 -07:00
Jubilee c35e971ef7
Rollup merge of #122707 - reedwoodruff:string_docs_typo, r=workingjubilee
Fix a typo in the alloc::string::String docs
2024-03-25 14:35:34 -07:00
klensy 8560d01a96 lib: fix some unnecessary_cast clippy lint
warning: casting raw pointers to the same type and constness is unnecessary (`*mut V` -> `*mut V`)
   --> library\alloc\src\collections\btree\map\entry.rs:357:31
    |
357 |                 let val_ptr = root.borrow_mut().push(self.key, value) as *mut V;
    |                               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `root.borrow_mut().push
(self.key, value)`
    |
    = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_cast

warning: casting to the same type is unnecessary (`usize` -> `usize`)
   --> library\alloc\src\ffi\c_str.rs:411:56
    |
411 |             let slice = slice::from_raw_parts_mut(ptr, len as usize);
    |                                                        ^^^^^^^^^^^^ help: try: `len`
    |
    = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_cast

warning: casting raw pointers to the same type and constness is unnecessary (`*mut T` -> `*mut T`)
   --> library\alloc\src\slice.rs:516:25
    |
516 |                         (buf.as_mut_ptr() as *mut T).add(buf.len()),
    |                         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `buf.as_mut_ptr()`
    |
    = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_cast

warning: casting raw pointers to the same type and constness is unnecessary (`*mut T` -> `*mut T`)
   --> library\alloc\src\slice.rs:537:21
    |
537 |                     (buf.as_mut_ptr() as *mut T).add(buf.len()),
    |                     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `buf.as_mut_ptr()`
    |
    = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_cast

warning: casting raw pointers to the same type and constness is unnecessary (`*const ()` -> `*const ()`)
   --> library\alloc\src\task.rs:151:13
    |
151 |             waker as *const (),
    |             ^^^^^^^^^^^^^^^^^^ help: try: `waker`
    |
    = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_cast

warning: casting raw pointers to the same type and constness is unnecessary (`*const ()` -> `*const ()`)
   --> library\alloc\src\task.rs:323:13
    |
323 |             waker as *const (),
    |             ^^^^^^^^^^^^^^^^^^ help: try: `waker`
    |
    = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_cast

warning: casting to the same type is unnecessary (`usize` -> `usize`)
   --> library\std\src\sys_common\net.rs:110:21
    |
110 |             assert!(len as usize >= mem::size_of::<c::sockaddr_in>());
    |                     ^^^^^^^^^^^^ help: try: `len`
    |
    = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_cast

warning: casting to the same type is unnecessary (`usize` -> `usize`)
   --> library\std\src\sys_common\net.rs:116:21
    |
116 |             assert!(len as usize >= mem::size_of::<c::sockaddr_in6>());
    |                     ^^^^^^^^^^^^ help: try: `len`
    |
    = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_cast
2024-03-25 23:19:40 +03:00
Daniel Paoliello d261647c93 Import the 2021 prelude in the core crate 2024-03-25 13:12:06 -07:00
Ralf Jung 7731135af2 alloc::Layout: explicitly document size invariant on the type level 2024-03-25 20:18:46 +01:00
Matthias Krüger e3fbaa87c9
Rollup merge of #122990 - SkiFire13:transmute-may-copy, r=jhpratt
Clarify transmute example

The example claims using an iterator will copy the entire vector, but this is not true in practice thanks to internal specializations in the stdlib (see https://godbolt.org/z/cnxo3MYs5 for confirmation that this doesn't reallocate nor iterate over the vec's elements). Since neither the copy nor the optimization is guaranteed I opted for saying that they _may_ happen.
2024-03-25 11:00:13 +01:00
Scott McMurray c59e93c753 Address PR feedback 2024-03-24 17:42:35 -07:00
Reed 58e2ad3d58 Amended wording 2024-03-24 12:20:39 -07:00
Scott McMurray 8d5977d6af Slightly simplify the `iN::partial_cmp` MIR
This saves some debug and scope metadata in every single function that calls it.

Normally wouldn't be worth it, but with the derives there's *so* many of these.
2024-03-24 10:01:37 -07:00
Matthias Krüger cdf86bf443
Rollup merge of #122992 - devnexen:available_parallelism_sol_upd, r=Amanieu
std:🧵 refine available_parallelism for solaris/illumos.

Rather than the system-wide available cpus fallback solution, we fetch the cpus bound to the current process.
2024-03-24 17:08:19 +01:00
Matthias Krüger f67fb08605
Rollup merge of #122984 - RalfJung:panic-in-hook, r=Amanieu
panic-in-panic-hook: formatting a message that's just a string is risk-free

This slightly improves the output in the 'panic while processing panic' case if the panic message does not involve any formatting. Follow-up to https://github.com/rust-lang/rust/pull/122930.

r? ``@Amanieu``
2024-03-24 17:08:19 +01:00
Matthias Krüger a5852ef941
Rollup merge of #122983 - taiki-e:bsd, r=workingjubilee
Fix build failure on ARM/AArch64/PowerPC/RISC-V FreeBSD/NetBSD

Fixes https://github.com/rust-lang/rust/pull/121881#discussion_r1536764650

Checked targets: aarch64-unknown-freebsd, powerpc64-unknown-freebsd, armv7-unknown-freebsd, riscv64gc-unknown-freebsd, aarch64-unknown-netbsd.

r? ``@Amanieu``
cc ``@devnexen``
2024-03-24 17:08:18 +01:00
Matthias Krüger 6b1f4e44d2
Rollup merge of #122977 - cuviper:as_statically_known_str, r=RalfJung
Rename `Arguments::as_const_str` to `as_statically_known_str`

While `const` has a particular meaning about language guarantees, here
we need a fuzzier notion like whether constant propagation was
effective, and `statically_known` is the best term we have for now.

r? ``@RalfJung``
2024-03-24 17:08:18 +01:00
David Carlier 1871ea5710 fix build. 2024-03-24 16:02:02 +00:00
David Carlier 4b84df9ea3 std:🧵 refine available_parallelism for solaris/illumos.
Rather than the system-wide available cpus fallback solution, we fetch
the cpus bound to the current process.
2024-03-24 10:57:17 +00:00
Giacomo Stevanato fb65ca14b2 Clarify transmute example 2024-03-24 11:27:34 +01:00
Ralf Jung 0727b6ad0d panic-in-panic-hook: formatting a message that's just a string is risk-free 2024-03-24 10:29:44 +01:00
Taiki Endo 7aa76a7ac3 Fix build failure on ARM/AArch64/PowerPC/RISC-V FreeBSD/NetBSD 2024-03-24 17:26:48 +09:00
Scott McMurray 3da115a93b Add+Use `mir::BinOp::Cmp` 2024-03-23 23:23:41 -07:00
Jubilee 46f9b3e8b9
Rollup merge of #122797 - alexcrichton:fix-compile-wasm64, r=Mark-Simulacrum
Fix compile of wasm64-unknown-unknown target

This target is a Tier 3 target so it's not tested on CI, and it's broken since last used so this commit fixes a small unwind-related issue that cropped up in the meantime.
2024-03-23 22:59:41 -07:00
Jubilee 862d870070
Rollup merge of #122762 - RoboSchmied:RoboSchmied-typo, r=workingjubilee
fix typo of endianness

fix typo
endianess -> endianness
2024-03-23 22:59:41 -07:00
Jubilee 343c916332
Rollup merge of #120419 - Ayush1325:uefi-sys-os, r=nicholasbishop,workingjubilee
Expand sys/os for UEFI

- Implement current_exe() and getcwd()
2024-03-23 22:59:40 -07:00
Josh Stone b67ad8f626 Rename `Arguments::as_const_str` to `as_statically_known_str`
While `const` has a particular meaning about language guarantees, here
we need a fuzzier notion like whether constant propagation was
effective, and `statically_known` is the best term we have for now.
2024-03-23 21:49:29 -07:00
bors 548e14b439 Auto merge of #122966 - matthiaskrgr:rollup-20k8nsm, r=matthiaskrgr
Rollup of 9 pull requests

Successful merges:

 - #121281 (regression test for #103626)
 - #122168 (Fix validation on substituted callee bodies in MIR inliner)
 - #122217 (Handle str literals written with `'` lexed as lifetime)
 - #122379 (transmute: caution against int2ptr transmutation)
 - #122840 (`rustdoc --test`: Prevent reaching the maximum size of command-line by using files for arguments if there are too many)
 - #122907 (Uniquify `ReError` on input mode in canonicalizer)
 - #122942 (Add test in higher ranked subtype)
 - #122943 (add a couple more ice tests)
 - #122963 (core/panicking: fix outdated comment)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-03-24 02:30:17 +00:00
Andy Kurnia 643029693b clarify equivalency of binary_search and partition_point 2024-03-24 08:15:00 +08:00
Matthias Krüger 6f16b41a4b
Rollup merge of #122963 - RalfJung:core-panicking, r=m-ou-se
core/panicking: fix outdated comment

Looks like this function got renamed/changed at some point and the comment did not get updated.

r? `@m-ou-se`
2024-03-24 01:05:54 +01:00
Matthias Krüger 2dcc96883e
Rollup merge of #122379 - RalfJung:int2ptr-transmute, r=m-ou-se
transmute: caution against int2ptr transmutation

This came up in https://github.com/rust-lang/rust/pull/121282.
Cc ```@saethlin``` ```@scottmcm```

Eventually we'll add a proper description of provenance that we can reference, but that's a bunch of work and it's unclear who will have the time to do that when. Meanwhile, let's at least do what we can without mentioning provenance explicitly.
2024-03-24 01:05:52 +01:00
bors 9b8d12cf4c Auto merge of #122905 - dpaoliello:sync-portable-simd-2024-03-22, r=workingjubilee
Portable SIMD subtree update

Syncs nightly to the latest changes from rust-lang/portable-simd

r? `@calebzulawski`
2024-03-24 00:02:14 +00:00
Adam Gastineau 52960d499e Fixed builds with modified libc 2024-03-23 16:42:06 -07:00
Ralf Jung f2cff5ebb9 also rename the SIMD intrinsic 2024-03-23 23:03:37 +01:00
bors 2f090c30dd Auto merge of #122629 - RalfJung:assert-unsafe-precondition, r=saethlin
refactor check_{lang,library}_ub: use a single intrinsic

This enacts the plan I laid out [here](https://github.com/rust-lang/rust/pull/122282#issuecomment-1996917998): use a single intrinsic, called `ub_checks` (in aniticpation of https://github.com/rust-lang/compiler-team/issues/725), that just exposes the value of `debug_assertions` (consistently implemented in both codegen and the interpreter). Put the language vs library UB logic into the library.

This makes it easier to do something like https://github.com/rust-lang/rust/pull/122282 in the future: that just slightly alters the semantics of `ub_checks` (making it more approximating when crates built with different flags are mixed), but it no longer affects whether these checks can happen in Miri or compile-time.

The first commit just moves things around; I don't think these macros and functions belong into `intrinsics.rs` as they are not intrinsics.

r? `@saethlin`
2024-03-23 21:11:00 +00:00
Ralf Jung e74b01e925 core/panicking: fix outdated comment 2024-03-23 21:36:22 +01:00
Ralf Jung 6177530420 refactor check_{lang,library}_ub: use a single intrinsic, put policy into library 2024-03-23 18:45:05 +01:00
Ralf Jung 987ef4c922 move assert_unsafe_preconditions to its own file
These macros and functions are not intrinsics, after all.
2024-03-23 18:44:17 +01:00
bors 020bbe46bd Auto merge of #122947 - matthiaskrgr:rollup-10j7orh, r=matthiaskrgr
Rollup of 11 pull requests

Successful merges:

 - #120577 (Stabilize slice_split_at_unchecked)
 - #122698 (Cancel `cargo update` job if there's no updates)
 - #122780 (Rename `hir::Local` into `hir::LetStmt`)
 - #122915 (Delay a bug if no RPITITs were found)
 - #122916 (docs(sync): normalize dot in fn summaries)
 - #122921 (Enable more mir-opt tests in debug builds)
 - #122922 (-Zprint-type-sizes: print the types of awaitees and unnamed coroutine locals.)
 - #122927 (Change an ICE regression test to use the original reproducer)
 - #122930 (add panic location to 'panicked while processing panic')
 - #122931 (Fix some typos in the pin.rs)
 - #122933 (tag_for_variant follow-ups)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-03-23 15:58:17 +00:00
Matthias Krüger 9ff7a65752
Rollup merge of #122931 - herobs:patch-1, r=joboet
Fix some typos in the pin.rs
2024-03-23 15:00:21 +01:00
Matthias Krüger 691d5f533d
Rollup merge of #122930 - RalfJung:panic-in-panic-fmt, r=Amanieu
add panic location to 'panicked while processing panic'

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

r? `@Amanieu`
2024-03-23 15:00:20 +01:00
Matthias Krüger eee0cd11a4
Rollup merge of #122916 - MultisampledNight:docs-sync-typo, r=jhpratt
docs(sync): normalize dot in fn summaries

All other functions in e.g. [`Mutex`](https://doc.rust-lang.org/std/sync/struct.Mutex.html) have a dot at the end of their first doc line, except for the newly stabilized [`Mutex::clear_poison`](https://doc.rust-lang.org/std/sync/struct.Mutex.html#method.clear_poison) (and its friend [`RwLock::clear_poison`](https://doc.rust-lang.org/std/sync/struct.RwLock.html#method.clear_poison)).

This PR remedies that by adding a normalizing dot.
2024-03-23 15:00:19 +01:00
Matthias Krüger 71ce3c26e6
Rollup merge of #120577 - wutchzone:slice_split_at_unchecked, r=m-ou-se
Stabilize slice_split_at_unchecked

Greetings!

I took the opportunity, and I tried to stabilize the `slice_split_at_unchecked` feature. I followed the guidelines, and I hope everything was done correctly 🤞 .

Closes #76014
2024-03-23 15:00:17 +01:00
bors d6eb0f5a09 Auto merge of #122582 - scottmcm:swap-intrinsic-v2, r=oli-obk
Let codegen decide when to `mem::swap` with immediates

Making `libcore` decide this is silly; the backend has so much better information about when it's a good idea.

Thus this PR introduces a new `typed_swap` intrinsic with a fallback body, and replaces that fallback implementation when swapping immediates or scalar pairs.

r? oli-obk

Replaces #111744, and means we'll never need more libs PRs like #111803 or #107140
2024-03-23 13:57:55 +00:00
Andy Kurnia 5afe4a9e09 improve example on inserting to a sorted vector to avoid shifting equal elements 2024-03-23 21:38:32 +08:00
Ralf Jung 67b9d7d184 rename ptr::from_exposed_addr -> ptr::with_exposed_provenance 2024-03-23 13:18:33 +01:00
joboet ac770f7bd5
proc_macro: simplify bridge state 2024-03-23 12:15:11 +01:00
Herobs 9e7c00b0e9
Fix some typos in the pin.rs 2024-03-23 16:51:40 +08:00
Ralf Jung fc257fae3c add panic location to 'panicked while processing panic' 2024-03-23 09:44:04 +01:00
bors c308726599 Auto merge of #119552 - krtab:dead_code_priv_mod_pub_field, r=cjgillot,saethlin
Replace visibility test with reachability test in dead code detection

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

Also included is a fix for an error now flagged by the lint
2024-03-23 00:37:05 +00:00
Daniel Paoliello 9e0ec251d5 Merge commit 'cff979eec1ac0473fc4960ee6cde462c6aeda824' into sync-portable-simd-2024-03-22 2024-03-22 16:58:39 -07:00
MultisampledNight e853b50a72
docs(sync): normalize dot in fn summaries 2024-03-22 23:04:20 +01:00
Jacob Pratt fbf21c5763
Remove RustcEncodable/Decodable from 2024 prelude 2024-03-22 13:30:48 -07:00
Jacob Pratt 2624e9183d
Soft-destabilize `RustcEncodable`/`RustcDecodable` 2024-03-22 13:24:35 -07:00
Daniel Paoliello 9685161b04 Update stdarch submodule 2024-03-22 12:16:16 -07:00
Scott McMurray d0ce391b14 `swap_simple` no longer needs to be a separate function 2024-03-22 11:55:17 -07:00
John Kåre Alsaker c2e5ee40b6 Avoid a panic in `set_output_capture` in the default panic handler 2024-03-22 16:21:26 +01:00
Mark Rousskov 00f4daa276 Codegen const panic messages as function calls
This skips emitting extra arguments at every callsite (of which there
can be many). For a librustc_driver build with overflow checks enabled,
this cuts 0.7MB from the resulting binary.
2024-03-22 09:55:50 -04:00
Matthias Krüger ef4a64b5d2
Rollup merge of #122800 - zachs18:nonnull-slice-is_empty, r=Amanieu
Add `NonNull::<[T]>::is_empty`.

As per https://github.com/rust-lang/rust/issues/71146#issuecomment-2008373983

I figured this should be fine to be insta-stable (with an FCP), but I can edit if that is not desired.

r? ```@Amanieu```
2024-03-22 11:37:00 +01:00
bors cdb683f6e4 Auto merge of #122024 - clubby789:remove-spec-option-pe, r=jhpratt
Remove SpecOptionPartialEq

With the recent LLVM bump, the specialization for Option::partial_eq on types with niches is no longer necessary. I kept the manual implementation as it still gives us better codegen than the derive (will look at this seperately).

Also implemented PartialOrd/Ord by hand as it _somewhat_ improves codegen for #49892: https://godbolt.org/z/vx5Y6oW4Y
2024-03-22 04:06:25 +00:00
Matthias Krüger 1757cb5871
Rollup merge of #122829 - ShoyuVanilla:gen-block-impl-fused-iter, r=compiler-errors
Implement `FusedIterator` for `gen` block

cc #117078
2024-03-22 01:07:31 +01:00
Matthias Krüger fa99ebc7cf
Rollup merge of #122817 - ultrabear:ultrabear_btreedoc, r=Nilstrieb
Doc Guarantee: BTree(Set|Map):  `IntoIter` Iterate in Sorted by key Order

This Doc-only PR adds text to the IntoIterator implementation and IntoIter type for both BTreeMap and BTreeSet that states that the returned items will be in sorted-by-key order, this is a guarantee that is made by the iter() and iter_mut() methods of BTreeMap/Set and BTreeMap respectively, but not on into_iter methods or types.

I don't know how the IntoIter iteration would not be sorted by key, and I would like to rely on that behavior for my prefix_array crate.

The text appended to IntoIter documentation is based on each types respective iter() method documentation, as is the text used in the IntoIterator documentation; they are slightly inconsistent between Set/Map, but they are consistent within their own types documentation.
2024-03-22 01:07:30 +01:00
Matthias Krüger f0feebb270
Rollup merge of #121881 - devnexen:bsd_acceptfilter, r=Amanieu
std::net: adding acceptfilter feature for netbsd/freebsd.

similar to linux's ext deferaccept, to filter incoming connections before accept.
2024-03-22 01:07:30 +01:00
Zachary S 1b95760e41 Not insta-stable 2024-03-21 17:01:41 -05:00
bors 0ad927c0c0 Auto merge of #122785 - the8472:const-select-specialized-impl, r=Amanieu
select Vec::from_iter impls in a const block to optimize compile times

Ignoring whitespace diffs should make this easier to review.

This relies on the trick from #122301
Split out from #120682
2024-03-21 21:19:19 +00:00
Shoyu Vanilla ae4c5c891e Implement `FusedIterator` for `gen` block 2024-03-22 02:02:34 +09:00
Michael Goulet 2d633317f3 Implement macro-based deref!() syntax for deref patterns
Stop using `box PAT` syntax for deref patterns, as it's misleading and
also causes their semantics being tangled up.
2024-03-21 11:42:49 -04:00
lilasta d324d6de0e Stabilize `const_caller_location` and `const_location_fields` 2024-03-21 22:19:57 +09:00
Matthias Krüger 62e414d3af
Rollup merge of #122806 - compiler-errors:type-ascribe, r=fmease
Make `type_ascribe!` not a built-in

The only weird thing is the macro expansion note. I wonder if we should suppress these 🤔

r? ````@fmease```` since you told me about builtin# lol
2024-03-21 12:05:09 +01:00
ultrabear beb0c22c09
document into_iter in top level docs iterator ordering guarantees 2024-03-21 02:07:46 -07:00
ultrabear f8a093c8ea
document iteration ordering on into_iter method instead of IntoIterator implementation 2024-03-21 02:05:11 -07:00
ultrabear f6f89dc202
BTree(Set|Map): Guarantee that `IntoIter` will iterate in sorted by key order 2024-03-21 00:54:50 -07:00
Michael Goulet a015b90953 Make type_ascribe! not a built-in 2024-03-20 22:28:56 -04:00
Jacob Pratt 7a5ffccded
Rollup merge of #122765 - workingjubilee:test-for-vec-handling-usize-max, r=Nilstrieb
Add `usize::MAX` arg tests for Vec

Tests to prevent recurrence of the UB from the rust-lang/rust#122760 issue.

I skipped the `with_capacity`, `drain`, `reserve`, etc. APIs because they actually had a good assortment of tests earlier in the same file.

r? Nilstrieb
2024-03-20 20:29:46 -04:00
Jacob Pratt 43ad753adb
Rollup merge of #122729 - m-ou-se:relax, r=Amanieu
Relax SeqCst ordering in standard library.

Every single SeqCst in the standard library is unnecessary. In all cases, Relaxed or Release+Acquire was sufficient.

As I [wrote](https://marabos.nl/atomics/memory-ordering.html#common-misconceptions) in my book on atomics:

> [..] when reading code, SeqCst basically tells the reader: "this operation depends on the total order of every single SeqCst operation in the program," which is an incredibly far-reaching claim. The same code would likely be easier to review and verify if it used weaker memory ordering instead, if possible. For example, Release effectively tells the reader: "this relates to an acquire operation on the same variable," which involves far fewer considerations when forming an understanding of the code.
>
> It is advisable to see SeqCst as a warning sign. Seeing it in the wild often means that either something complicated is going on, or simply that the author did not take the time to analyze their memory ordering related assumptions, both of which are reasons for extra scrutiny.

r? ````@Amanieu```` ````@joboet````
2024-03-20 20:29:44 -04:00
Zachary S 4250216663 Add `NonNull::<[T]>::is_empty` as insta-stable. 2024-03-20 18:25:06 -05:00
Alex Crichton 2758435a8e Fix compile of wasm64-unknown-unknown target
This target is a Tier 3 target so it's not tested on CI, and it's broken
since last used so this commit fixes a small unwind-related issue that
cropped up in the meantime.
2024-03-20 14:55:02 -07:00
bors 1388d7a069 Auto merge of #122761 - jwong101:fix/vec-insert, r=workingjubilee,Nilstrieb
fix OOB pointer formed in Vec::index

Move the length check to before using `index` with `ptr::add` to prevent an out of bounds pointer from being formed.

Fixes #122760
2024-03-20 21:37:30 +00:00
The 8472 3ff1e448e7 select Vec::from_iter impls in a const block to optimize compile times 2024-03-20 19:26:38 +01:00
David Carlier 19cb05fd78 std::net: adding acceptfilter feature for netbsd/freebsd.
similar to linux's ext deferaccept, to filter incoming connections
before accept.
2024-03-20 18:15:31 +00:00
RoboSchmied 0d5a3f464f Update target.rs alloc.rs event.rs simd.rs
fix typos
2024-03-20 17:07:15 +01:00
Mara Bos 34621757ea SeqCst->Relaxed in condvar test.
Relaxed is enough here. Synchronization is done by the mutex.
2024-03-20 15:38:09 +01:00
Mara Bos acddc55748 SeqCst->Relaxed in thread local test.
Relaxed memory ordering is fine because spawn()/join() already provides
all the synchronization we need.
2024-03-20 15:38:09 +01:00
Mara Bos b45a725cbc SeqCst->Relaxed in std::net::test.
Relaxed is enough to have fetch_add(1) return each value only once
(until it wraps around).
2024-03-20 15:35:13 +01:00
Mara Bos 8b519f98e2 Use less restricted memory ordering in xous::thread_local_key.
SeqCst isn't necessary in any of these cases.
2024-03-20 15:35:11 +01:00
bors a128516cf9 Auto merge of #122754 - Mark-Simulacrum:bootstrap-bump, r=albertlarsan68
Bump to 1.78 bootstrap compiler

https://forge.rust-lang.org/release/process.html#master-bootstrap-update-t-2-day-tuesday
2024-03-20 13:43:41 +00:00
Mark Rousskov 02f1930595 step cfgs 2024-03-20 08:49:13 -04:00
bors c86f3ac24f Auto merge of #120717 - compiler-errors:cap-closure-kind, r=oli-obk
For async closures, cap closure kind, get rid of `by_mut_body`

Right now we have three `AsyncFn*` traits, and three corresponding futures that are returned by the `call_*` functions for them. This is fine, but it is a bit excessive, since the future returned by `AsyncFn` and `AsyncFnMut` are identical. Really, the only distinction we need to make with these bodies is "by ref" and "by move".

This PR removes `AsyncFn::CallFuture` and renames `AsyncFnMut::CallMutFuture` to `AsyncFnMut::CallRefFuture`. This simplifies MIR building for async closures, since we don't need to build an extra "by mut" body, but just a "by move" body which is materially different.

We need to do a bit of delicate handling of the ClosureKind for async closures, since we need to "cap" it to `AsyncFnMut` in some cases when we only care about what body we're looking for.

This also fixes a bug where `<{async closure} as Fn>::call` was returning a body that takes the async-closure receiver *by move*.

This also helps align the `AsyncFn` traits to the `LendingFn` traits' eventual designs.
2024-03-20 11:40:45 +00:00
Jubilee Young 92f668c20b Add usize::MAX arg tests for Vec 2024-03-20 01:21:19 -07:00
Matthias Krüger d7209bf858
Rollup merge of #122739 - Sky9x:insert-put, r=jhpratt
Add "put" as a confusable for insert on hash map/set

Already a confusable on btree map/set.

Java's `Map` calls the insert method `put`: https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/Map.html#put(K,V)
2024-03-20 05:51:24 +01:00
Matthias Krüger 2cf93ac9c8
Rollup merge of #122730 - ferrocene:hoverbear/qnx-ucred-cfgs, r=Amanieu
Expose `ucred::peer_cred` on QNX targets to enable dist builds

After following https://doc.rust-lang.org/rustc/platform-support/nto-qnx.html I attempted to run the following `x.py` command:

```bash
export build_env='
    CC_aarch64-unknown-nto-qnx710=qcc
    CFLAGS_aarch64-unknown-nto-qnx710=-Vgcc_ntoaarch64le_cxx
    CXX_aarch64-unknown-nto-qnx710=qcc
    AR_aarch64_unknown_nto_qnx710=ntoaarch64-ar
    CC_x86_64-pc-nto-qnx710=qcc
    CFLAGS_x86_64-pc-nto-qnx710=-Vgcc_ntox86_64_cxx
    CXX_x86_64-pc-nto-qnx710=qcc
    AR_x86_64_pc_nto_qnx710=ntox86_64-ar'
env $build_env ./x.py --stage 2 dist rust-std  --target aarch64-unknown-nto-qnx710,x86_64-pc-nto-qnx710,x86_64-unknown-linux-gnu
```

The result was the following error:

```
   Compiling object v0.32.2
   Compiling std_detect v0.1.5 (/home/ana/git/rust-lang/rust/library/stdarch/crates/std_detect)
   Compiling addr2line v0.21.0
error: function `peer_cred` is never used
  --> library/std/src/os/unix/net/ucred.rs:89:12
   |
89 |     pub fn peer_cred(socket: &UnixStream) -> io::Result<UCred> {
   |            ^^^^^^^^^
   |
   = note: `-D dead-code` implied by `-D warnings`
   = help: to override `-D warnings` add `#[allow(dead_code)]`

error: could not compile `std` (lib) due to 1 previous error
Build completed unsuccessfully in 0:06:25
```

I contacted `@flba-eb` and `@gh-tr` over email and we confirmed that `peer_cred` here should be flagged on `nto` targets. This should enable the clean `x.py --stage 2 dist rust-std` command on these platforms.
2024-03-20 05:51:23 +01:00
Matthias Krüger 4f3050b85a
Rollup merge of #121543 - onur-ozkan:clippy-args, r=oli-obk
various clippy fixes

We need to keep the order of the given clippy lint rules before passing them.
Since clap doesn't offer any useful interface for this purpose out of the box,
we have to handle it manually.

Additionally, this PR makes `-D` rules work as expected. Previously, lint rules were limited to `-W`. By enabling `-D`, clippy began to complain numerous lines in the tree, all of which have been resolved in this PR as well.

Fixes #121481
cc `@matthiaskrgr`
2024-03-20 05:51:22 +01:00
Joshua Wong 37718f949f fix OOB pointer formed in Vec::index
Move the length check to before using `index` with `ptr::add` to prevent
an out of bounds pointer from being formed.

Fixes #122760
2024-03-19 22:47:35 -05:00
Mark Rousskov 4fb89c5056 branch 1.78: replace-version-placeholder 2024-03-19 19:27:24 -04:00
onur-ozkan 81d7d7aabd resolve clippy errors
Signed-off-by: onur-ozkan <work@onurozkan.dev>
2024-03-20 00:12:00 +03:00
Michael Goulet 05116c5c30 Only split by-ref/by-move futures for async closures 2024-03-19 16:59:23 -04:00
Sky 49dd50f880
Add "put" as a confusable for insert on hash map/set 2024-03-19 14:28:01 -04:00
Matthias Krüger f7731243d9
Rollup merge of #122720 - heisen-li:offset_of, r=workingjubilee
[doc]:fix error code example

fixs #122716
2024-03-19 18:03:53 +01:00
clubby789 f8fd23a2ad Manually implement `PartialOrd`/`Ord` for `Option` 2024-03-19 16:32:07 +00:00
clubby789 5f254d8b66 Remove `SpecOptionPartialEq` 2024-03-19 16:32:01 +00:00
Ana Hobden d82d4196ac
Expose ucred::peer_cred on QNX targets to enable dist builds 2024-03-19 07:34:27 -07:00
Mara Bos 5a594f7bcd SeqCst->Relaxed for xous set_nonblocking.
The SeqCst wasn't synchronizing with anything. Relaxed is enough.
2024-03-19 15:27:11 +01:00
Mara Bos 69a4d77d67 SeqCst->{Release,Acquire} for xous DropLock.
SeqCst is unnecessary. Release+Acquire is the right ordering for a
mutex.
2024-03-19 15:27:11 +01:00
Mara Bos 60ad49005a SeqCst->Relaxed in pal::windows::pipe.
Relaxed is enough to ensure fetch_add(1) returns each integer exactly
once.
2024-03-19 15:27:11 +01:00
Mara Bos 46bb073423 SeqCst->{Release,Acquire} for wasm DropLock.
SeqCst is unnecessary. Release+Acquire is the right ordering for a
mutex.
2024-03-19 15:27:11 +01:00
Mara Bos e43aef0ef9 SeqCst->{Release,Acquire} in sys_common::thread_local_key.
SeqCst is unnecessary here.
2024-03-19 15:27:11 +01:00
Mara Bos 516684c22e Use less restricted memory ordering in thread_parking::pthread.
SeqCst is unnecessary here.
2024-03-19 15:27:11 +01:00
Mara Bos eb966983f2 SeqCst->{Release,Acquire} in xous mutex.
No need for SeqCst. Release+Acquire is the right memory ordering for a
mutex.
2024-03-19 15:27:11 +01:00
Mara Bos 9f25a04498 SeqCst->Relaxed for FIRST_PANIC.
Relaxed is enough to make sure this `swap` results in `true` only once.
2024-03-19 15:27:11 +01:00
Mara Bos 904fef0e24 SeqCst->{Release,Acquire} for alloc error hook.
SeqCst is unnecessary.
2024-03-19 15:27:11 +01:00
Mara Bos bf3debe9d7 SeqCst->Relaxed for proc_macro bridge counter.
Relaxed is enough here.
2024-03-19 15:27:11 +01:00
Mara Bos 5e4cc6f694 SeqCst->Relaxed in panic_unwind/emcc.
SeqCst is unnecessary here.
2024-03-19 15:27:11 +01:00
Mara Bos a2c74b8445 SeqCst->Relaxed in doc examples.
SeqCst is unnecessary here.
2024-03-19 15:27:11 +01:00
heisen-li a370ed7644 [doc]:fix error code example 2024-03-19 17:18:10 +08:00
Oli Scherer 3e5c468662 Make ptr_guaranteed_cmp a rustc_intrinsic and favor its body over backends implementing it 2024-03-19 09:17:40 +00:00
Oli Scherer e0d67aeb0b Make `vtable_align` a rustc_intrinsic 2024-03-19 09:13:48 +00:00
Oli Scherer 7f9830b16c Make `const_eval_select` a rustc_intrinsic 2024-03-19 09:12:58 +00:00
Ralf Jung f4adb1e6bd add notes on how to store 'ptr or int' 2024-03-19 07:19:22 +01:00
Adam Gastineau 4f6f433745 Support for visionOS 2024-03-18 20:45:45 -07:00
Jules Bertholet 2f1ab2ce09
Reimplement `CaseMappingIter` with `core::array::IntoIter`
Makes the iterator 2*usize larger, but I doubt that matters much.
In exchange, we save a lot on instruction count.

In the absence of delegation syntax,
we must forward all the specialized impls manually…
2024-03-18 23:07:28 -04:00
bors 21d94a3d2c Auto merge of #122055 - compiler-errors:stabilize-atb, r=oli-obk
Stabilize associated type bounds (RFC 2289)

This PR stabilizes associated type bounds, which were laid out in [RFC 2289]. This gives us a shorthand to express nested type bounds that would otherwise need to be expressed with nested `impl Trait` or broken into several `where` clauses.

### What are we stabilizing?

We're stabilizing the associated item bounds syntax, which allows us to put bounds in associated type position within other bounds, i.e. `T: Trait<Assoc: Bounds...>`. See [RFC 2289] for motivation.

In all position, the associated type bound syntax expands into a set of two (or more) bounds, and never anything else (see "How does this differ[...]" section for more info).

Associated type bounds are stabilized in four positions:
* **`where` clauses (and APIT)** - This is equivalent to breaking up the bound into two (or more) `where` clauses. For example, `where T: Trait<Assoc: Bound>` is equivalent to `where T: Trait, <T as Trait>::Assoc: Bound`.
* **Supertraits** - Similar to above, `trait CopyIterator: Iterator<Item: Copy> {}`. This is almost equivalent to breaking up the bound into two (or more) `where` clauses; however, the bound on the associated item is implied whenever the trait is used. See #112573/#112629.
* **Associated type item bounds** - This allows constraining the *nested* rigid projections that are associated with a trait's associated types. e.g. `trait Trait { type Assoc: Trait2<Assoc2: Copy>; }`.
* **opaque item bounds (RPIT, TAIT)** - This allows constraining associated types that are associated with the opaque without having to *name* the opaque. For example, `impl Iterator<Item: Copy>` defines an iterator whose item is `Copy` without having to actually name that item bound.

The latter three are not expressible in surface Rust (though for associated type item bounds, this will change in #120752, which I don't believe should block this PR), so this does represent a slight expansion of what can be expressed in trait bounds.

### How does this differ from the RFC?

Compared to the RFC, the current implementation *always* desugars associated type bounds to sets of `ty::Clause`s internally. Specifically, it does *not* introduce a position-dependent desugaring as laid out in [RFC 2289], and in particular:
* It does *not* desugar to anonymous associated items in associated type item bounds.
* It does *not* desugar to nested RPITs in RPIT bounds, nor nested TAITs in TAIT bounds.

This position-dependent desugaring laid out in the RFC existed simply to side-step limitations of the trait solver, which have mostly been fixed in #120584. The desugaring laid out in the RFC also added unnecessary complication to the design of the feature, and introduces its own limitations to, for example:
* Conditionally lowering to nested `impl Trait` in certain positions such as RPIT and TAIT means that we inherit the limitations of RPIT/TAIT, namely lack of support for higher-ranked opaque inference. See this code example: https://github.com/rust-lang/rust/pull/120752#issuecomment-1979412531.
* Introducing anonymous associated types makes traits no longer object safe, since anonymous associated types are not nameable, and all associated types must be named in `dyn` types.

This last point motivates why this PR is *not* stabilizing support for associated type bounds in `dyn` types, e.g, `dyn Assoc<Item: Bound>`. Why? Because `dyn` types need to have *concrete* types for all associated items, this would necessitate a distinct lowering for associated type bounds, which seems both complicated and unnecessary compared to just requiring the user to write `impl Trait` themselves. See #120719.

### Implementation history:

Limited to the significant behavioral changes and fixes and relevant PRs, ping me if I left something out--
* #57428
* #108063
* #110512
* #112629
* #120719
* #120584

Closes #52662

[RFC 2289]: https://rust-lang.github.io/rfcs/2289-associated-type-bounds.html
2024-03-19 00:04:09 +00:00
Matthias Krüger e5b9a42e37
Rollup merge of #122675 - tmfink:doc-clarify, r=scottmcm
core: document default attribute stabilization

As of now, the first release which stabilized the `#[default]` macro for the deriving the `Default` trait for enus is not documented.
I have had to search the [`RELEASES.md`](https://github.com/rust-lang/rust/blob/master/RELEASES.md) when making sure my code would be accepted by an older Rust compiler.

I just added a line in the doc comment since, as far as I know, there's no option to pass to the `#[stable()]` attribute.

I am open to improvements in the wording.
2024-03-18 22:24:39 +01:00
Matthias Krüger 223c23c63f
Rollup merge of #122642 - pallix:improve-wording-for-vec-swap_remove, r=Amanieu
Improve wording of `Vec::swap_remove`

This improve the wording for  `Vec::swap_remove`.
2024-03-18 22:24:38 +01:00
Reed 7b3ef13146 Fix a typo in the alloc::string::String docs 2024-03-18 11:39:00 -07:00
Ralf Jung bcf8015177 remove retag_box_to_raw, it is no longer needed 2024-03-18 10:32:25 +01:00
Ralf Jung c96fa5e143 add_retag: ensure box-to-raw-ptr casts are preserved for Miri 2024-03-18 10:32:25 +01:00
Scott McMurray 7d537106a1 Let codegen decide when to `mem::swap` with immediates
Making `libcore` decide this is silly; the backend has so much better information about when it's a good idea.

So introduce a new `typed_swap` intrinsic with a fallback body, but replace that implementation for immediates and scalar pairs.
2024-03-17 11:59:18 -07:00
Pierre Allix 23e1b570d7 Improve wording of `Vec::swap_remove` 2024-03-17 18:27:02 +01:00
Ayush Singh a2497a9679
Expand sys/os for UEFI
- Implement current_exe()
- Cache device_path_to_text protocol

Signed-off-by: Ayush Singh <ayushdevel1325@gmail.com>
2024-03-17 22:44:35 +05:30
Petr Portnov e7d397024f
chore(121952): echo comments on the `*_assign` methods 2024-03-17 17:06:12 +03:00
Petr Portnov 5ebed0ba4b
chore(121952): remove redundant comments
These were only relevant for the unsafe-containing implementations

Signed-off-by: Petr Portnov <me@progrm-jarvis.ru>
2024-03-17 17:00:48 +03:00
Petr Portnov b186f40b8b
feat: implement `{Div,Rem}Assign<NonZero<X>>` on `X`
Signed-off-by: Petr Portnov <me@progrm-jarvis.ru>
2024-03-17 17:00:44 +03:00
Matthias Krüger 3c07321541
Rollup merge of #119411 - yotamofek:array-ptr-get, r=Nilstrieb
Add as_(mut_)ptr and as_(mut_)slice to raw array pointers

Hey, first time contributing to the standard libraries so not completely sure about the process.

These functions are complementary to the ones being added in #74265 . I found them missing on array pointers.

See also:
- ACP: https://github.com/rust-lang/libs-team/issues/321
- Tracking issue: #119834
2024-03-17 08:23:25 +01:00
Travis Finkenauer d7b4b01911 core: document default attribute stabilization 2024-03-16 21:20:29 -07:00
Jules Bertholet 1c137b7582
Optimize `core::char::CaseMappingIter` layout
Godbolt says this saves a few instructions…
2024-03-16 23:42:06 -04:00
bors a615cea333 Auto merge of #121885 - reitermarkus:generic-nonzero-inner, r=oli-obk,wesleywiser
Move generic `NonZero` `rustc_layout_scalar_valid_range_start` attribute to inner type.

Tracking issue: https://github.com/rust-lang/rust/issues/120257

r? `@dtolnay`
2024-03-17 02:27:52 +00:00
León Orell Valerian Liehr de0c2a4723
Rollup merge of #122601 - joboet:ptr_replace, r=workingjubilee
Optimize `ptr::replace`

#83022 optimized `mem::replace` to reduce the number of `memcpy`s. `ptr::replace`, which is [documented to behave just like `mem::replace`](https://doc.rust-lang.org/nightly/std/ptr/fn.replace.html), was not optimized however, leading to [worse code](https://godbolt.org/z/T3hdEEdfe) and missed optimizations. This PR simply forwards `ptr::replace` to `mem::replace` to take advantage of the better implementation.
2024-03-16 23:28:49 +01:00
Yotam Ofek d0c0887498 Add as_(mut_)ptr and as_(mut_)slice to raw array pointers 2024-03-16 20:15:30 +00:00
Chris Denton a9f8f8b070
Rollup merge of #122583 - Zoxc:tls-non-mut, r=joboet
Use `UnsafeCell` for fast constant thread locals

This uses `UnsafeCell` instead of `static mut` for fast constant thread locals. This changes the type of the TLS shims to return `&UnsafeCell<T>` instead of `*mut T` which means they are always non-null so LLVM can optimize away the check for `Some` in `LocalKey::with` if `T` has no destructor.

LLVM is currently unable to do this optimization as we lose the fact that `__getit` always returns `Some` as it gets optimized to just returning the value of the TLS shim.
2024-03-16 18:27:34 +00:00
Chris Denton ceef59fa2b
Rollup merge of #122390 - ChrisDenton:bindgen, r=Mark-Simulacrum
Bump windows-bindgen to 0.55.0

windows-bindgen is the crate used to generate std's Windows API bindings.

Not many changes for us, it's mostly just simplifying the generate code (e.g. no more `-> ()`). The one substantial change is some structs now use `i8` byte arrays instead of `u8`. However, this only impacts one test.
2024-03-16 18:27:33 +00:00
joboet f2721338f6
core: optimize `ptr::replace` 2024-03-16 17:51:00 +01:00
John Kåre Alsaker b0b249399a Use `UnsafeCell` for fast constant thread locals 2024-03-16 12:34:52 +01:00
Matthias Krüger 1745f3d405
Rollup merge of #122562 - Wilfred:break_keyword_docs, r=workingjubilee
Mention labelled blocks in `break` docs

`break` doesn't require a loop, so note this in the docs. This is covered in the linked sections of the rust reference, but this page implied that `break` is only for loops.
2024-03-15 21:51:58 +01:00
Scott McMurray 50392ccc5a Workaround issue 122566 2024-03-15 13:09:04 -07:00
Wilfred Hughes e1e719e1a1 Mention labelled blocks in `break` docs
`break` doesn't require a loop, so note this in the docs.
This is covered in the linked sections of the rust reference,
but this page implied that `break` is only for loops.
2024-03-15 10:51:57 -07:00
Guillaume Gomez 4002638a44
Rollup merge of #122512 - baitcode:2024-03-14-buffer-documentation-fix, r=Nilstrieb
Cursor.rs documentation fix

Reason:

I've been learning Rust std library and got confused. Seek trait documentation clearly states that negative indexes will cause an error. And the code in the Cursor example uses negative index. I found myself trying to understand what am I missing until I've actually executed the code and got error. I decided to submit small fix to the documentation.
2024-03-15 17:24:08 +01:00
Scott McMurray 234e383c34 Stabilize `unchecked_{add,sub,mul}` 2024-03-14 18:39:37 -07:00
bors c2901f5435 Auto merge of #122511 - matthiaskrgr:rollup-swzilin, r=matthiaskrgr
Rollup of 10 pull requests

Successful merges:

 - #117118 ([AIX] Remove AixLinker's debuginfo() implementation)
 - #121650 (change std::process to drop supplementary groups based on CAP_SETGID)
 - #121764 (Make incremental sessions identity no longer depend on the crate names provided by source code)
 - #122212 (Copy byval argument to alloca if alignment is insufficient)
 - #122322 (coverage: Initial support for branch coverage instrumentation)
 - #122373 (Fix the conflict problem between the diagnostics fixes of lint `unnecessary_qualification`  and  `unused_imports`)
 - #122479 (Implement `Duration::as_millis_{f64,f32}`)
 - #122487 (Rename `StmtKind::Local` variant into `StmtKind::Let`)
 - #122498 (Update version of cc crate)
 - #122503 (Make `SubdiagMessageOp` well-formed)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-03-15 00:03:58 +00:00
Jubilee Young 442cc762c0 Use rust-lang/backtrace-rs@6fa4b85 2024-03-14 12:37:43 -07:00
Matthias Krüger 6366c64974
Rollup merge of #122498 - jfgoog:update-cc-crate-version, r=workingjubilee
Update version of cc crate

Reason:

In order to build the Windows version of the Rust toolchain for the Android platform, the following patch to the cc is crate is required to avoid incorrectly determining that we are building with the Android NDK: 57853c4bf8

This patch is present in version 1.0.80 and newer versions of the cc crate. The rustc source distribution currently has 3 different versions of cc in the vendor directory, only one of which has the necessary fix.

We (the Android Rust toolchain) are currently maintaining local patches to upgrade the cc crate dependency versions, which we would like to upstream.
2024-03-14 20:00:21 +01:00
Matthias Krüger 5d41186446
Rollup merge of #122479 - GrigorenkoPV:duration_millis_float, r=scottmcm
Implement `Duration::as_millis_{f64,f32}`

Implementation of #122451.

Linked const-unstability to #72440, so the post there should probably be updated to mentions the 2 new methods when/if this PR is merged.
2024-03-14 20:00:20 +01:00
Matthias Krüger eaa8dafe1a
Rollup merge of #121650 - GrigorenkoPV:cap_setgid, r=Amanieu
change std::process to drop supplementary groups based on CAP_SETGID

A trivial rebase of #95982

Should fix #39186 (from what I can tell)

Original description:

> Fixes #88716
>
> * Before this change, when a process was given a uid via `std::os::unix::process::CommandExt.uid`, there would be a `setgroups` call (when the process runs) to clear supplementary groups for the child **if the parent was root** (to remove potentially unwanted permissions).
> * After this change, supplementary groups are cleared if we have permission to do so, that is, if we have the CAP_SETGID capability.
>
> This new behavior was agreed upon in #88716 but there was a bit of uncertainty from `@Amanieu` here: [#88716 (comment)](https://github.com/rust-lang/rust/issues/88716#issuecomment-973366600)
>
> > I agree with this change, but is it really necessary to ignore an EPERM from setgroups? If you have permissions to change UID then you should also have permissions to change groups. I would feel more comfortable if we documented set_uid as requiring both UID and GID changing permissions.
>
> The way I've currently written it, we ignore an EPERM as that's what #88716 originally suggested. I'm not at all an expert in any of this so I'd appreciate feedback on whether that was the right way to go.
2024-03-14 20:00:17 +01:00
baitcode 07e0182fd3 Fix minor documentation issue. Code outside the test would fail. Seek documentation clearly states that negative indexes will cause error.
Just making the code in the example to return Result::Ok, instead of Result::Error.
2024-03-14 18:58:23 +00:00
James Farrell 21904319f8 Update version of cc crate
Reason:

In order to build the Windows version of the Rust toolchain for the Android platform, the following patch to the cc is crate is required to avoid incorrectly determining that we are building with the Android NDK: 57853c4bf8

This patch is present in version 1.0.80 and newer versions of the cc crate. The rustc source distribution currently has 3 different versions of cc in the vendor directory, only one of which has the necessary fix.

We (the Android Rust toolchain) are currently maintaining local patches to upgrade the cc crate dependency versions, which we would like to upstream.
2024-03-14 16:42:15 +00:00
Markus Reiter bc532a6307
Hide implementation details for `NonZero` auto traits. 2024-03-14 17:34:57 +01:00
Matthias Krüger 280a1da2a0
Rollup merge of #119029 - dylni:avoid-closing-invalid-handles, r=ChrisDenton
Avoid closing invalid handles

Documentation for [`HandleOrInvalid`] has this note:

> If holds a handle other than `INVALID_HANDLE_VALUE`, it will close the handle on drop.

Documentation for [`HandleOrNull`] has this note:

> If this holds a non-null handle, it will close the handle on drop.

Currently, both will call `CloseHandle` on their invalid handles as a result of using `OwnedHandle` internally, contradicting the above paragraphs. This PR adds destructors that match the documentation.

```@rustbot``` label A-io O-windows T-libs

[`HandleOrInvalid`]: https://doc.rust-lang.org/std/os/windows/io/struct.HandleOrInvalid.html
[`HandleOrNull`]: https://doc.rust-lang.org/std/os/windows/io/struct.HandleOrNull.html
2024-03-14 15:44:31 +01:00
Pavel Grigorenko d6a1b36cb4
Implement ptr_as_ref_unchecked (#122034) 2024-03-14 16:01:29 +03:00
bors c2fbe404d2 Auto merge of #122483 - matthiaskrgr:rollup-n07dsh5, r=matthiaskrgr
Rollup of 9 pull requests

Successful merges:

 - #104353 (Add CStr::bytes iterator)
 - #119676 (rustdoc-search: search types by higher-order functions)
 - #120699 (Document `TRACK_DIAGNOSTIC` calls.)
 - #121899 (Document how removing a type's field can be bad and what to do instead)
 - #122405 (Add methods to create StableMIR constant)
 - #122416 (Various style improvements to `rustc_lint::levels`)
 - #122421 (Improve `Step` docs)
 - #122440 (const-eval: organize and extend tests for required-consts)
 - #122461 (fix unsoundness in Step::forward_unchecked for signed integers)

Failed merges:

 - #122397 (Various cleanups around the const eval query providers)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-03-14 12:17:08 +00:00
Matthias Krüger 75dc99b996
Rollup merge of #122461 - the8472:fix-step-forward-unchecked, r=Amanieu
fix unsoundness in Step::forward_unchecked for signed integers

Fixes #122420

```rust
pub fn foo(a: i8, b: u8) -> i8 {
    unsafe { a.checked_add_unsigned(b).unwrap_unchecked() }
}
```

still compiles down to a single arithmetic instruction ([godbolt](https://rust.godbolt.org/z/qsd3xYWfE)).

But we may be losing some loop optimizations if llvm can no longer easily derive that it's a finite counted loop from the no-wrapping flags.
2024-03-14 11:10:00 +01:00
Matthias Krüger a0e50a4a96
Rollup merge of #122421 - CAD97:step-trait-docs, r=jhpratt
Improve `Step` docs

It [came up on urlo](https://users.rust-lang.org/t/implement-trait-step-in-1-76-0/108204?u=cad97) that the unstable reason string isn't helpful, so just remove it; there's nothing meaningful to add here.

Also makes a couple drive-by improvements to the method docs -- removes incorrect references, changes `forward_checked`'s invariant formulation to match `backward_checked`'s, and adds a helpful corollary that `step_unchecked(a, 0)` is always safe.
2024-03-14 11:09:59 +01:00
Matthias Krüger 1ae69ae615
Rollup merge of #104353 - clarfonthey:cstr-bytes-iter, r=cuviper
Add CStr::bytes iterator

See rust-lang/libs-team#135 for an ACP.

Since rust-lang/libs-team#134 was also accepted, this type is now `core::ffi::c_str::Bytes` instead of `core::ffi::CStrBytes`.
2024-03-14 11:09:56 +01:00
bors e69f14b14c Auto merge of #114038 - Stargateur:108277, r=ChrisDenton
unix time module now return result

First try to fix #108277 without break anything.

if anyone who read this know tips to be able to check compilation for different target I could use some help. So far I installed many target with rustup but `./x check --all-targets` doesn't seem to use them.

TODO:

- [x] better error
- [ ] test, how ?

`@rustbot` label -S-waiting-on-author +S-waiting-on-review
2024-03-14 10:05:32 +00:00
The 8472 be33586adc fix unsoundness in Step::forward_unchecked for signed integers 2024-03-14 00:57:02 +01:00
Pavel Grigorenko f2ec0d3d26
Implement `Duration::as_millis_{f64,f32}` 2024-03-14 01:37:12 +03:00
Alex Crichton 5af8187325 Provide `cabi_realloc` on `wasm32-wasip2` by default
This commit provides a component model intrinsic in the standard library
by default on the `wasm32-wasip2` target. This intrinsic is not
required by the component model itself but is quite common to use, for
example it's needed if a wasm module receives a string or a list.

The intention of this commit is to provide an overridable definition in
the standard library through a weak definition of this function. That
means that downstream crates can provide their own customized and more
specific versions if they'd like, but the standard library's version
should suffice for general-purpose use.
2024-03-13 08:15:08 -07:00
Alex Crichton 3311283f90 Get wasm32-wasip2 compiling with its custom pal implementation
The ordering of targets in `pal/mod.rs` did not end up using the wasip2
implementation, so after reordering that I've edited the implementation
to compile correctly.
2024-03-13 08:15:07 -07:00
Matthias Krüger dff680d359
Rollup merge of #122386 - joboet:move_pal_once, r=jhpratt
Move `Once` implementations to `sys`

Part of https://github.com/rust-lang/rust/issues/117276.
2024-03-13 06:41:24 +01:00
Matthias Krüger e42a702430
Rollup merge of #122255 - Nadrieril:min_exh_pats-libs, r=scottmcm
Use `min_exhaustive_patterns` in core & std

[`min_exhaustive_patterns`](https://github.com/rust-lang/rust/issues/119612) provides a subset of the functionality of [`exhaustive_patterns`](https://github.com/rust-lang/rust/issues/51085) which is likely to be stabilized much earlier than the full feature.

The subset covers all the compiler and std use cases. `compiler/` [already uses it](9dd6eda778); this PR switches `std` over.
2024-03-13 06:41:22 +01:00
Christopher Durham c527ec76ce Improve Step docs 2024-03-13 00:49:51 -04:00
ltdk a38a556ceb Reduce unsafe code, use more NonNull APIs per @cuviper review 2024-03-12 17:21:17 -04:00
Benoît du Garreau 8734809395 Specialize many implementations of `Read::read_buf_exact` 2024-03-12 18:28:55 +01:00
Ralf Jung d3299af26d transmute: caution against int2ptr transmutation 2024-03-12 17:26:45 +01:00
Chris Denton 6cb2f03c03
Convert [u8] to [i8] in test 2024-03-12 16:05:59 +00:00
Chris Denton 8e870c8ed1
Bump windows-bindgen to 0.55.0 2024-03-12 16:05:58 +00:00
Chris Denton b25203e30f
Bump windows-bindgen to 0.54.0 2024-03-12 16:05:58 +00:00
joboet 22a5267c83
std: move `Once` implementations to `sys` 2024-03-12 15:41:06 +01:00
Jonathan Jensen 34e59f49d5 Fix typo in lib.rs of proc_macro 2024-03-12 13:35:14 +01:00
Arthur Carcano f60c4ed197 Allow dead code in sys/pal
The dead_code lint was previously eroneously missing this dead code.
Since this lint bug has been fixed, the unused field need
to be removed or marked as `#[allow(dead_code)]`.

These structures API is common to all platforms so the code cannot be
removed and is hence marked allow(dead_code).
2024-03-12 12:06:16 +01:00
Arthur Carcano e78851813e Allow dead code in thread local dtor
The dead_code lint was previously eroneously missing this dead code.
Since this lint bug has been fixed, the unused field need
to be removed or marked as `#[allow(dead_code)]`.

Given the nature of this code, I don't feel confident removing the field
so it is only marked as allow(dead_code).
2024-03-12 10:59:41 +01:00
Arthur Carcano ccd99b384e Remove unused fields in some structures
The dead_code lint was previously eroneously missing those.
Since this lint bug has been fixed, the unused fields need
to be removed.
2024-03-12 10:59:40 +01:00
Nadrieril 9962a01e9f Use `min_exhaustive_patterns` in core & std 2024-03-12 08:20:46 +01:00
David Carlier 6a16638de6 std::rand: fix dragonflybsd after #121942. 2024-03-12 00:54:57 +00:00
bors dc2ffa4054 Auto merge of #122036 - alexcrichton:test-wasm-with-wasi, r=oli-obk
Test wasm32-wasip1 in CI, not wasm32-unknown-unknown

This commit changes CI to no longer test the `wasm32-unknown-unknown` target and instead test the `wasm32-wasip1` target. There was some discussion of this in a [Zulip thread], and the motivations for this PR are:

* Runtime failures on `wasm32-unknown-unknown` print nothing, meaning all you get is "something failed". In contrast `wasm32-wasip1` can print to stdout/stderr.

* The unknown-unknown target is missing lots of pieces of libstd, and while `wasm32-wasip1` is also missing some pieces (e.g. threads) it's missing fewer pieces. This means that many more tests can be run.

Overall my hope is to improve the debuggability of wasm failures on CI and ideally be a bit less of a maintenance burden.

This commit specifically removes the testing of `wasm32-unknown-unknown` and replaces it with testing of `wasm32-wasip1`. Along the way there were a number of other archiectural changes made as well, including:

* A new `target.*.runtool` option can now be specified in `config.toml` which is passed as `--runtool` to `compiletest`. This is used to reimplement execution of WebAssembly in a less-wasm-specific fashion.

* The default value for `runtool` is an ambiently located WebAssembly runtime found on the system, if any. I've implemented logic for Wasmtime.

* Existing testing support for `wasm32-unknown-unknown` and Emscripten has been removed. I'm not aware of Emscripten testing being run any time recently and otherwise `wasm32-wasip1` is in theory the focus now.

* I've added a new `//@ needs-threads` directive for `compiletest` and classified a bunch of wasm-ignored tests as needing threads. In theory these tests can run on `wasm32-wasi-preview1-threads`, for example.

* I've tried to audit all existing tests that are either `ignore-emscripten` or `ignore-wasm*`. Many now run on `wasm32-wasip1` due to being able to emit error messages, for example. Many are updated with comments as to why they can't run as well.

* The `compiletest` output matching for `wasm32-wasip1` automatically uses "match a subset" mode implemented in `compiletest`. This is because WebAssembly runtimes often add extra information on failure, such as the `unreachable` instruction in `panic!`, which isn't able to be matched against the golden output from native platforms.

* I've ported most existing `run-make` tests that use custom Node.js wrapper scripts to the new run-make-based-in-Rust infrastructure. To do this I added `wasmparser` as a dependency of `run-make-support` for the various wasm tests to use that parse wasm files. The one test that executed WebAssembly now uses `wasmtime`-the-CLI to execute the test instead. I have not ported over an exception-handling test as Wasmtime doesn't implement this yet.

* I've updated the `test` crate to print out timing information for WASI targets as it can do that (gets a previously ignored test now passing).

* The `test-various` image now builds a WASI sysroot for the WASI target and additionally downloads a fixed release of Wasmtime, currently the latest one at 18.0.2, and uses that for testing.

[Zulip thread]: https://rust-lang.zulipchat.com/#narrow/stream/131828-t-compiler/topic/Have.20wasm.20tests.20ever.20caused.20problems.20on.20CI.3F/near/424317944
2024-03-12 00:03:54 +00:00
Alex Crichton 8fcc009f7d libtest: Print timing information on WASI
This commit updates the libtest conditionals to use `std::time::Instant`
on WASI targets where it's implemented. Previously all wasm targets
wouldn't use this type.
2024-03-11 09:36:35 -07:00
Jubilee 1279830068
Rollup merge of #121438 - coolreader18:wasm32-panic-unwind, r=cuviper
std support for wasm32 panic=unwind

Tracking issue: #118168

This adds std support for `-Cpanic=unwind` on wasm, and with it slightly more fleshed out rustc support. Now, the stable default is still panic=abort without exception-handling, but if you `-Zbuild-std` with `RUSTFLAGS=-Cpanic=unwind`, you get wasm exception-handling try/catch blocks in the binary:

```rust
#[no_mangle]
pub fn foo_bar(x: bool) -> *mut u8 {
    let s = Box::<str>::from("hello");
    maybe_panic(x);
    Box::into_raw(s).cast()
}

#[inline(never)]
#[no_mangle]
fn maybe_panic(x: bool) {
    if x {
        panic!("AAAAA");
    }
}
```
```wat
;; snip...
(try $label$5
 (do
  (call $maybe_panic
   (local.get $0)
  )
  (br $label$1)
 )
 (catch_all
  (global.set $__stack_pointer
   (local.get $1)
  )
  (call $__rust_dealloc
   (local.get $2)
   (i32.const 5)
   (i32.const 1)
  )
  (rethrow $label$5)
 )
)
;; snip...
```
2024-03-11 09:29:34 -07:00
bors e919669d42 Auto merge of #122331 - jhpratt:rollup-cbl8xsy, r=jhpratt
Rollup of 9 pull requests

Successful merges:

 - #121148 (Add slice::try_range)
 - #121633 (Win10: Use `GetSystemTimePreciseAsFileTime` directly)
 - #121840 (Expose the Freeze trait again (unstably) and forbid implementing it manually)
 - #121907 (skip sanity check for non-host targets in `check` builds)
 - #122002 (std::threads: revisit stack address calculation on netbsd.)
 - #122108 (Add `target.*.runner` configuration for targets)
 - #122298 (RawVec::into_box: avoid unnecessary intermediate reference)
 - #122315 (Allow multiple `impl Into<{D,Subd}iagMessage>` parameters in a function.)
 - #122326 (Optimize `process_heap_alloc`)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-03-11 10:22:10 +00:00
Jacob Pratt 5a3d6c91b1
Rollup merge of #122326 - Zoxc:win-alloc-tweak, r=ChrisDenton
Optimize `process_heap_alloc`

This optimizes `process_heap_alloc` introduced in https://github.com/rust-lang/rust/pull/120205.

From:
```
.text:0000000180027ED0 ; std::sys::pal::windows::alloc::process_heap_alloc::h703a613b3e25ff93
.text:0000000180027ED0                 public _ZN3std3sys3pal7windows5alloc18process_heap_alloc17h703a613b3e25ff93E
.text:0000000180027ED0 _ZN3std3sys3pal7windows5alloc18process_heap_alloc17h703a613b3e25ff93E proc near
.text:0000000180027ED0                                         ; CODE XREF: std::sys::pal::common::alloc::realloc_fallback::hc4c96b4c24d03e77+23↑p
.text:0000000180027ED0                                         ; std::sys::pal::common::alloc::realloc_fallback::hc4c96b4c24d03e77+55↑p ...
.text:0000000180027ED0                 push    rsi
.text:0000000180027ED1                 push    rdi
.text:0000000180027ED2                 sub     rsp, 28h
.text:0000000180027ED6                 mov     rsi, rdx
.text:0000000180027ED9                 mov     edi, ecx
.text:0000000180027EDB                 mov     rcx, cs:_ZN3std3sys3pal7windows5alloc4HEAP17hb53ca4010cc29b62E ; std::sys::pal::windows::alloc::HEAP::hb53ca4010cc29b62
.text:0000000180027EE2                 test    rcx, rcx
.text:0000000180027EE5                 jnz     short loc_180027EFC
.text:0000000180027EE7                 call    cs:__imp_GetProcessHeap
.text:0000000180027EED                 test    rax, rax
.text:0000000180027EF0                 jz      short loc_180027F0E
.text:0000000180027EF2                 mov     rcx, rax
.text:0000000180027EF5                 mov     cs:_ZN3std3sys3pal7windows5alloc4HEAP17hb53ca4010cc29b62E, rax ; std::sys::pal::windows::alloc::HEAP::hb53ca4010cc29b62
.text:0000000180027EFC
.text:0000000180027EFC loc_180027EFC:                          ; CODE XREF: std::sys::pal::windows::alloc::process_heap_alloc::h703a613b3e25ff93+15↑j
.text:0000000180027EFC                 mov     edx, edi
.text:0000000180027EFE                 mov     r8, rsi
.text:0000000180027F01                 add     rsp, 28h
.text:0000000180027F05                 pop     rdi
.text:0000000180027F06                 pop     rsi
.text:0000000180027F07                 jmp     cs:__imp_HeapAlloc
.text:0000000180027F0E ; ---------------------------------------------------------------------------
.text:0000000180027F0E
.text:0000000180027F0E loc_180027F0E:                          ; CODE XREF: std::sys::pal::windows::alloc::process_heap_alloc::h703a613b3e25ff93+20↑j
.text:0000000180027F0E                 xor     eax, eax
.text:0000000180027F10                 add     rsp, 28h
.text:0000000180027F14                 pop     rdi
.text:0000000180027F15                 pop     rsi
.text:0000000180027F16                 retn
.text:0000000180027F16 _ZN3std3sys3pal7windows5alloc18process_heap_alloc17h703a613b3e25ff93E endp
```
to
```
.text:0000000180027EE0 ; std::sys::pal::windows::alloc::process_heap_alloc::h70f9d61a631e5c16
.text:0000000180027EE0                 public _ZN3std3sys3pal7windows5alloc18process_heap_alloc17h70f9d61a631e5c16E
.text:0000000180027EE0 _ZN3std3sys3pal7windows5alloc18process_heap_alloc17h70f9d61a631e5c16E proc near
.text:0000000180027EE0                                         ; CODE XREF: std::sys::pal::common::alloc::realloc_fallback::hc4c96b4c24d03e77+23↑p
.text:0000000180027EE0                                         ; std::sys::pal::common::alloc::realloc_fallback::hc4c96b4c24d03e77+54↑p ...
.text:0000000180027EE0                 mov     rcx, cs:_ZN3std3sys3pal7windows5alloc4HEAP17hb53ca4010cc29b62E ; std::sys::pal::windows::alloc::HEAP::hb53ca4010cc29b62
.text:0000000180027EE7                 test    rcx, rcx
.text:0000000180027EEA                 jz      short loc_180027EF3
.text:0000000180027EEC                 jmp     cs:__imp_HeapAlloc
.text:0000000180027EF3 ; ---------------------------------------------------------------------------
.text:0000000180027EF3
.text:0000000180027EF3 loc_180027EF3:                          ; CODE XREF: std::sys::pal::windows::alloc::process_heap_alloc::h70f9d61a631e5c16+A↑j
.text:0000000180027EF3                 mov     ecx, edx
.text:0000000180027EF5                 mov     rdx, r8
.text:0000000180027EF8                 jmp     std__sys__pal__windows__alloc__process_heap_init_and_alloc
.text:0000000180027EF8 _ZN3std3sys3pal7windows5alloc18process_heap_alloc17h70f9d61a631e5c16E endp
```

r? `@ChrisDenton`
2024-03-11 03:47:22 -04:00