Commit Graph

13290 Commits

Author SHA1 Message Date
bors 8b94152af6 Auto merge of #117958 - risc0:erik/target-triple, r=davidtwco,Mark-Simulacrum
riscv32im-risc0-zkvm-elf: add target

This pull request adds RISC Zero's Zero Knowledge Virtual Machine (zkVM) as a target for rust. The zkVM used to produce proofs of execution of RISC-V ELF binaries. In order to do this, the target will execute the ELF to generate a receipt containing the output of the computation along with a cryptographic seal. This receipt can be verified to ensure the integrity of the computation and its result. This target is implemented as software only; it has no hardware implementation.

## Tier 3 target policy:

Here is a copy of the tier 3 target policy:

> Tier 3 target policy:
>
> At this tier, the Rust project provides no official support for a target, so we
> place minimal requirements on the introduction of targets.
>
> A proposed new tier 3 target must be reviewed and approved by a member of the
> compiler team based on these requirements. The reviewer may choose to gauge
> broader compiler team consensus via a [[Major Change Proposal (MCP)](https://forge.rust-lang.org/compiler/mcp.html)](https://forge.rust-lang.org/compiler/mcp.html).
>
> A proposed target or target-specific patch that substantially changes code
> shared with other targets (not just target-specific code) must be reviewed and
> approved by the appropriate team for that shared code before acceptance.
>
> - A tier 3 target must have a designated developer or developers (the "target
> maintainers") on record to be CCed when issues arise regarding the target.
> (The mechanism to track and CC such developers may evolve over time.)

The maintainers are named in the target description file

> - Targets must use naming consistent with any existing targets; for instance, a
> target for the same CPU or OS as an existing Rust target should use the same
> name for that CPU or OS. Targets should normally use the same names and
> naming conventions as used elsewhere in the broader ecosystem beyond Rust
> (such as in other toolchains), unless they have a very good reason to
> diverge. Changing the name of a target can be highly disruptive, especially
> once the target reaches a higher tier, so getting the name right is important
> even for a tier 3 target.
> - Target names should not introduce undue confusion or ambiguity unless
> absolutely necessary to maintain ecosystem compatibility. For example, if
> the name of the target makes people extremely likely to form incorrect
> beliefs about what it targets, the name should be changed or augmented to
> disambiguate it.
> - If possible, use only letters, numbers, dashes and underscores for the name.
> Periods (`.`) are known to cause issues in Cargo.
>

We understand.

> - Tier 3 targets may have unusual requirements to build or use, but must not
> create legal issues or impose onerous legal terms for the Rust project or for
> Rust developers or users.
>     - The target must not introduce license incompatibilities.

We understand and will not introduce incompatibilities. All of our code that we publish is licensed under Apache-2.0.

> - Anything added to the Rust repository must be under the standard Rust license (`MIT OR Apache-2.0`).

We understand. We are open to either license for the Rust repository.

> - The target must not cause the Rust tools or libraries built for any other
> host (even when supporting cross-compilation to the target) to depend
> on any new dependency less permissive than the Rust licensing policy. This
> applies whether the dependency is a Rust crate that would require adding
> new license exceptions (as specified by the `tidy` tool in the
> rust-lang/rust repository), or whether the dependency is a native library
> or binary. In other words, the introduction of the target must not cause a
> user installing or running a version of Rust or the Rust tools to be
> subject to any new license requirements.

We understand. The runtime libraries and the execution environment and software associated with this environment uses `Apache-2.0` so this should not be an issue.

> - Compiling, linking, and emitting functional binaries, libraries, or other
> code for the target (whether hosted on the target itself or cross-compiling
> from another target) must not depend on proprietary (non-FOSS) libraries.
> Host tools built for the target itself may depend on the ordinary runtime
> libraries supplied by the platform and commonly used by other applications
> built for the target, but those libraries must not be required for code
> generation for the target; cross-compilation to the target must not require
> such libraries at all. For instance, `rustc` built for the target may
> depend on a common proprietary C runtime library or console output library,
> but must not depend on a proprietary code generation library or code
> optimization library. Rust's license permits such combinations, but the
> Rust project has no interest in maintaining such combinations within the
> scope of Rust itself, even at tier 3.

We understand. We only depend on FOSS libraries. Dependencies such as runtime libraries for this target are licensed as `Apache-2.0`.

> - "onerous" here is an intentionally subjective term. At a minimum, "onerous"
> legal/licensing terms include but are *not* limited to: non-disclosure
> requirements, non-compete requirements, contributor license agreements
> (CLAs) or equivalent, "non-commercial"/"research-only"/etc terms,
> requirements conditional on the employer or employment of any particular
> Rust developers, revocable terms, any requirements that create liability
> for the Rust project or its developers or users, or any requirements that
> adversely affect the livelihood or prospects of the Rust project or its
> developers or users.

There are no such terms present

> - Neither this policy nor any decisions made regarding targets shall create any
> binding agreement or estoppel by any party. If any member of an approving
> Rust team serves as one of the maintainers of a target, or has any legal or
> employment requirement (explicit or implicit) that might affect their
> decisions regarding a target, they must recuse themselves from any approval
> decisions regarding the target's tier status, though they may otherwise
> participate in discussions.

I am not the reviewer of this pull request

> - This requirement does not prevent part or all of this policy from being
> cited in an explicit contract or work agreement (e.g. to implement or
> maintain support for a target). This requirement exists to ensure that a
> developer or team responsible for reviewing and approving a target does not
> face any legal threats or obligations that would prevent them from freely
> exercising their judgment in such approval, even if such judgment involves
> subjective matters or goes beyond the letter of these requirements.

We understand.

> - Tier 3 targets should attempt to implement as much of the standard libraries
> as possible and appropriate (`core` for most targets, `alloc` for targets
> that can support dynamic memory allocation, `std` for targets with an
> operating system or equivalent layer of system-provided functionality), but
> may leave some code unimplemented (either unavailable or stubbed out as
> appropriate), whether because the target makes it impossible to implement or
> challenging to implement. The authors of pull requests are not obligated to
> avoid calling any portions of the standard library on the basis of a tier 3
> target not implementing those portions.

The target implements core and alloc. And std support is currently experimental as some functionalities in std are either a) not applicable to our target or b) more work in research and experimentation needs to be done. For more information about the characteristics of this target, please refer to the target description file.

> - The target must provide documentation for the Rust community explaining how
> to build for the target, using cross-compilation if possible. If the target
> supports running binaries, or running tests (even if they do not pass), the
> documentation must explain how to run such binaries or tests for the target,
> using emulation if possible or dedicated hardware if necessary.

See file target description file

> - Tier 3 targets must not impose burden on the authors of pull requests, or
> other developers in the community, to maintain the target. In particular,
> do not post comments (automated or manual) on a PR that derail or suggest a
> block on the PR based on a tier 3 target. Do not send automated messages or
> notifications (via any medium, including via ``@`)` to a PR author or others
> involved with a PR regarding a tier 3 target, unless they have opted into
> such messages.

We understand.

> - Backlinks such as those generated by the issue/PR tracker when linking to
> an issue or PR are not considered a violation of this policy, within
> reason. However, such messages (even on a separate repository) must not
> generate notifications to anyone involved with a PR who has not requested
> such notifications.

We understand.

> - Patches adding or updating tier 3 targets must not break any existing tier 2
> or tier 1 target, and must not knowingly break another tier 3 target without
> approval of either the compiler team or the maintainers of the other tier 3
> target.
>     - In particular, this may come up when working on closely related targets,
>     such as variations of the same architecture with different features. Avoid
>     introducing unconditional uses of features that another variation of the
>     target may not have; use conditional compilation or runtime detection, as
>     appropriate, to let each target run code supported by that target.

We understand.

> If a tier 3 target stops meeting these requirements, or the target maintainers
> no longer have interest or time, or the target shows no signs of activity and
> has not built for some time, or removing the target would improve the quality
> of the Rust codebase, we may post a PR to remove it; any such PR will be CCed
> to the target maintainers (and potentially other people who have previously
> worked on the target), to check potential interest in improving the situation.

We understand.
2024-01-23 09:30:36 +00:00
bors e35a56d96f Auto merge of #119892 - joboet:libs_use_assert_unchecked, r=Nilstrieb,cuviper
Use `assert_unchecked` instead of `assume` intrinsic in the standard library

Now that a public wrapper for the `assume` intrinsic exists, we can use it in the standard library.

CC #119131
2024-01-23 06:45:58 +00:00
Matthias Krüger a787232abb
Rollup merge of #120233 - oli-obk:revert_trait_obj_upcast_stabilization, r=lcnr
Revert stabilization of trait_upcasting feature

Reverts #118133

This reverts commit 6d2b84b3ed, reversing changes made to 73bc12199e.

The feature has a soundness bug:

* #120222

It is unclear to me whether we'll actually want to destabilize, but I thought it was still prudent to open the PR for easy destabilization once we get there.
2024-01-22 22:12:10 +01:00
Matthias Krüger a4307184be
Rollup merge of #120220 - nnethercote:TokenStream-Display-docs, r=petrochenkov
Document `Token{Stream,Tree}::Display` more thoroughly.

To expressly warn against the kind of proc macro implementation that was broken in #119875.

r? ``@petrochenkov``
2024-01-22 22:12:10 +01:00
Matthias Krüger 221115cbd6
Rollup merge of #120143 - compiler-errors:consolidate-instance-resolve-for-coroutines, r=oli-obk
Consolidate logic around resolving built-in coroutine trait impls

Deduplicates a lot of code. Requires defining a new lang item for `Coroutine::resume` for consistency, but it seems not harmful at worst, and potentially later useful at best.

r? oli-obk
2024-01-22 22:12:08 +01:00
Matthias Krüger 42e1db52ac
Rollup merge of #120109 - joboet:move_pal_cmath, r=ChrisDenton
Move cmath into `sys`

Part of #117276.

r? ``@ChrisDenton``
2024-01-22 22:12:08 +01:00
Matthias Krüger 67d093682c
Rollup merge of #119664 - ChrisDenton:mingw-pty, r=thomcc
Fix tty detection for msys2's `/dev/ptmx`

Our "true negative" detection assumes that if at least one std handle is a Windows console then no other handle will be a msys2 tty pipe. This turns out to be a faulty assumption in the case of redirection to  `/dev/ptmx` in an msys2 shell. Maybe this is an msys2 bug but in any case we should try to make it work.

An alternative to this would be to replace the "true negative" detection with an attempt to detect if we're in an msys environment (e.g. by sniffing environment variables) but that seems like it'd be flaky too.

Fixes #119658
2024-01-22 22:12:06 +01:00
bors d5fd099729 Auto merge of #120242 - matthiaskrgr:rollup-a93yj3i, r=matthiaskrgr
Rollup of 10 pull requests

Successful merges:

 - #117910 (Refactor uses of `objc_msgSend` to no longer have clashing definitions)
 - #118639 (Undeprecate lint `unstable_features` and make use of it in the compiler)
 - #119801 (Fix deallocation with wrong allocator in (A)Rc::from_box_in)
 - #120058 (bootstrap: improvements for compiler builds)
 - #120059 (Make generic const type mismatches not hide trait impls from the trait solver)
 - #120097 (Report unreachable subpatterns consistently)
 - #120137 (Validate AggregateKind types in MIR)
 - #120164 (`maybe_lint_impl_trait`: separate `is_downgradable` from `is_object_safe`)
 - #120181 (Allow any `const` expression blocks in `thread_local!`)
 - #120218 (rustfmt: Check that a token can begin a nonterminal kind before parsing it as a macro arg)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-01-22 18:22:32 +00:00
Erik Kaneda 75d7d7091a
zkvm: add partial std support
Co-authored-by: Frank Laub <flaub@risc0.com>
Co-authored-by: nils <nils@risc0.com>
Co-authored-by: Victor Graf <victor@risczero.com>
Co-authored-by: weikengchen <w.k@berkeley.edu>
2024-01-22 10:15:11 -08:00
Erik Kaneda 966b94e0a2
rustc: implement support for `riscv32im_risc0_zkvm_elf`
This also adds changes in the rust test suite in order to get a few of them to
pass.

Co-authored-by: Frank Laub <flaub@risc0.com>
Co-authored-by: Urgau <3616612+Urgau@users.noreply.github.com>
2024-01-22 10:07:36 -08:00
Matthias Krüger d3761de43f
Rollup merge of #120181 - dtolnay:tlconst, r=thomcc
Allow any `const` expression blocks in `thread_local!`

This PR contains a rebase of the macro change from #116392, together with adding a test under library/std/tests.

Testing this feature by making the documentation's example code needlessly more complicated was not appropriate as pointed out in https://github.com/rust-lang/rust/pull/116392#pullrequestreview-1753097757.

Without the macro change, this new test would fail to build as follows:

```console
error: no rules expected the token `let`
   --> library/std/tests/thread.rs:26:13
    |
26  |             let value = 1;
    |             ^^^ no rules expected this token in macro call
    |
note: while trying to match meta-variable `$init:expr`
   --> library/std/src/thread/local.rs:189:69
    |
189 |     ($(#[$attr:meta])* $vis:vis static $name:ident: $t:ty = const { $init:expr }; $($rest:tt)*) => (
    |                                                                     ^^^^^^^^^^
```

Closes #116392.
2024-01-22 16:55:00 +01:00
Matthias Krüger 97bcf0da7c
Rollup merge of #119801 - zachs18:zachs18-patch-1, r=steffahn,Nilstrieb
Fix deallocation with wrong allocator in (A)Rc::from_box_in

Deallocate the `Box` with the original allocator (via `&A`), not `Global`.

Fixes #119749

<details> <summary>Example code with error and Miri output</summary>

(Note that this UB is not observable on stable, because the only usable allocator on stable is `Global` anyway.)

Code ([playground link](https://play.rust-lang.org/?version=nightly&mode=debug&edition=2021&gist=96193c2c6a1912d7f669fbbe39174b09)):

```rs
#![feature(allocator_api)]
use std::alloc::System;

// uncomment one of these
use std::rc::Rc;
//use std::sync::Arc as Rc;

fn main() {
    let x: Box<[u32], System> = Box::new_in([1,2,3], System);
    let _: Rc<[u32], System> = Rc::from(x);
}
```

Miri output:

```rs
error: Undefined Behavior: deallocating alloc904, which is C heap memory, using Rust heap deallocation operation
   --> /playground/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/alloc.rs:117:14
    |
117 |     unsafe { __rust_dealloc(ptr, layout.size(), layout.align()) }
    |              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ deallocating alloc904, which is C heap memory, using Rust heap deallocation operation
    |
    = help: this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior
    = help: see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information
    = note: BACKTRACE:
    = note: inside `std::alloc::dealloc` at /playground/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/alloc.rs:117:14: 117:64
    = note: inside `<std::alloc::Global as std::alloc::Allocator>::deallocate` at /playground/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/alloc.rs:254:22: 254:51
    = note: inside `<std::boxed::Box<std::mem::ManuallyDrop<[u32]>> as std::ops::Drop>::drop` at /playground/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/boxed.rs:1244:17: 1244:66
    = note: inside `std::ptr::drop_in_place::<std::boxed::Box<std::mem::ManuallyDrop<[u32]>>> - shim(Some(std::boxed::Box<std::mem::ManuallyDrop<[u32]>>))` at /playground/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/ptr/mod.rs:507:1: 507:56
    = note: inside `std::mem::drop::<std::boxed::Box<std::mem::ManuallyDrop<[u32]>>>` at /playground/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/mem/mod.rs:992:24: 992:25
    = note: inside `std::rc::Rc::<[u32], std::alloc::System>::from_box_in` at /playground/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/rc.rs:1928:13: 1928:22
    = note: inside `<std::rc::Rc<[u32], std::alloc::System> as std::convert::From<std::boxed::Box<[u32], std::alloc::System>>>::from` at /playground/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/rc.rs:2504:9: 2504:27
note: inside `main`
   --> src/main.rs:10:32
    |
10  |     let _: Rc<[u32], System> = Rc::from(x);
    |                                ^^^^^^^^^^^

note: some details are omitted, run with `MIRIFLAGS=-Zmiri-backtrace=full` for a verbose backtrace

error: aborting due to 1 previous error
```

</details>
2024-01-22 16:54:57 +01:00
Matthias Krüger e355b276bd
Rollup merge of #117910 - madsmtm:msg-send-no-clashing, r=thomcc
Refactor uses of `objc_msgSend` to no longer have clashing definitions

This is very similar to what Apple's own headers encourage you to do (cast the function pointer before use instead of making new declarations).

Additionally, I'm documenting a few of the memory management rules we're following, ensuring that the `args` function doesn't leak memory (if you wrap it in an autorelease pool).

Motivation is to avoid issues with clashing definitions, like described in https://github.com/rust-lang/rust/issues/12707#issuecomment-1570735643 and https://github.com/rust-lang/rust/issues/46188#issuecomment-1288058453, CC ``@bjorn3.``
2024-01-22 16:54:56 +01:00
Matthias Krüger 8c3c8bba03
Rollup merge of #119943 - devnexen:listener_update3, r=thomcc
std::net: bind update for using backlog as `-1` too.

Albeit not documented, macOs also support negative value for the backlog argument.

ref: 2ff845c2e0/bsd/kern/uipc_socket.c (L1061)
2024-01-22 16:13:27 +01:00
Matthias Krüger e9c2e1bfbe
Rollup merge of #119408 - betrusted-io:xous-fixes-add-network, r=Mark-Simulacrum
xous: misc fixes + add network support

This patchset makes several fixes to Xous support. Additionally, this patch adds networking support.

Many of these fixes are the result of the recent patch to get `unwinding` support merged. As a result of this patch, we can now run rust tests. As a result of these tests, we now have 729 tests passing:

```
failures:
    env::tests::test
    env::tests::test_self_exe_path
    env::tests::vars_debug
    env::tests::vars_os_debug
    os::raw::tests::same
    path::tests::test_push
    path::tests::test_set_file_name
    time::tests::since_epoch
test result: FAILED. 729 passed; 8 failed; 1 ignored; 0 measured; 0 filtered out; finished in 214.54s
```

In the course of fixing several tests and getting the test sequence to reliably run, several issues were found. This patchset fixes those issues.
2024-01-22 16:13:26 +01:00
Matthias Krüger 99b4f80f73
Rollup merge of #118578 - mina86:c, r=dtolnay
core: introduce split_at{,_mut}_checked

Introduce split_at_checked and split_at_mut_checked methods to slices
types (including str) which are non-panicking versions of split_at and
split_at_mut  respectively.  This is analogous to get method being
non-panicking version of indexing.

- https://github.com/rust-lang/libs-team/issues/308
- https://github.com/rust-lang/rust/issues/119128
2024-01-22 16:13:24 +01:00
joboet f88e64343e
std: move cmath into `sys` 2024-01-22 15:30:54 +01:00
Oli Scherer 9a20cf1697 Revert "Auto merge of #118133 - Urgau:stabilize_trait_upcasting, r=WaffleLapkin"
This reverts commit 6d2b84b3ed, reversing
changes made to 73bc12199e.
2024-01-22 14:24:31 +00:00
Chris Denton e74c667a53
Fix msys2 tty detection for /dev/ptmx
Our "true negative" detection assumes that if at least one std handle is a Windows console then no other handle will be a msys2 tty pipe. This turns out to be a faulty assumption in the case of  `/dev/ptmx`.
2024-01-22 13:44:21 +00:00
bors 366d112fa6 Auto merge of #120226 - matthiaskrgr:rollup-9xwx0si, r=matthiaskrgr
Rollup of 9 pull requests

Successful merges:

 - #118714 ( Explanation that fields are being used when deriving `(Partial)Ord` on enums)
 - #119710 (Improve `let_underscore_lock`)
 - #119726 (Tweak Library Integer Division Docs)
 - #119746 (rustdoc: hide modals when resizing the sidebar)
 - #119986 (Fix error counting)
 - #120194 (Shorten `#[must_use]` Diagnostic Message for `Option::is_none`)
 - #120200 (Correct the anchor of an URL in an error message)
 - #120203 (Replace `#!/bin/bash` with `#!/usr/bin/env bash` in rust-installer tests)
 - #120212 (Give nnethercote more reviews)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-01-22 11:08:57 +00:00
bors 6fff796eac Auto merge of #120196 - matthiaskrgr:rollup-id2zocf, r=matthiaskrgr
Rollup of 8 pull requests

Successful merges:

 - #120005 (Update Readme)
 - #120045 (Un-hide `iter::repeat_n`)
 - #120128 (Make stable_mir::with_tables sound)
 - #120145 (fix: Drop guard was deallocating with the incorrect size)
 - #120158 (`rustc_mir_dataflow`: Restore removed exports)
 - #120167 (Capture the rationale for `-Zallow-features=` in bootstrap.py)
 - #120174 (Warn users about limited review for tier 2 and 3 code)
 - #120180 (Document some alternatives to `Vec::split_off`)

Failed merges:

 - #120171 (Fix assume and assert in jump threading)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-01-22 08:56:22 +00:00
Matthias Krüger 1df60b2257
Rollup merge of #120194 - HTGAzureX1212:HTGAzureX1212shorten-option-must-use, r=Nilstrieb
Shorten `#[must_use]` Diagnostic Message for `Option::is_none`

This shortens the `#[must_use]` diagnostics displayed, in light of the [review comment](https://github.com/rust-lang/rust/pull/62431/files#r300819839) on when this was originally added.
2024-01-22 07:56:43 +01:00
Matthias Krüger 7d7c2257d3
Rollup merge of #119726 - NCGThompson:div-overflow-doc, r=Nilstrieb
Tweak Library Integer Division Docs

Improved the documentation and diagnostics related to panicking in the division-like methods in std:

* For signed methods that can overflow, clarified "results in overflow" to "self is -1 and rhs is Self::MIN." This is more concise than saying "results in overflow" and then explaining how it could overflow.
* For floor/ceil_div, corrected the documentation and made it more like the documentation in other methods.
* For signed methods that can overflow, explicitly mention that they are not affected by compiler flags.
* Removed all unused rustc_inherit_overflow_checks attributes. The non-division-like operations will never overflow.
* Added track_caller attributes to all methods that can panic. The panic messages will always be correct. For example, division methods all have / before %.
* Edited the saturating_div documentation to be consistent with similar methods.
2024-01-22 07:56:42 +01:00
Matthias Krüger 6f7222c1e6
Rollup merge of #118714 - The-Ludwig:explain_ord_derive_enum_field, r=Nilstrieb
Explanation that fields are being used when deriving `(Partial)Ord` on enums

When deriving `std::cmp::Ord` or `std::cmp::PartialOrd` on enums, their fields are compared if the variants are equal.
This means that the last assertion in the following snipped panics.
```rust
use std::cmp::{PartialEq, Eq, PartialOrd, Ord};

#[derive(PartialEq, Eq, PartialOrd, Ord)]
enum Sizes {
    Small(usize),
    Big(usize),
}

fn main() {
    let a = Sizes::Big(3);
    let b = Sizes::Big(5);
    let c = Sizes::Small(10);
    assert!( c < a);
    assert_eq!(a, c);
}
```

This is more often expected behavior than not, and can be easily circumvented, as discussed in [this thread](https://users.rust-lang.org/t/how-to-sort-enum-variants/52291/4).
But it is addressed nowhere in the documentation, yet.
So I stumbled across this, as I personally did not expect fields being used in `PartialOrd`.
I added the explanation to the documentation.
2024-01-22 07:56:41 +01:00
Nicholas Nethercote c4fc9ff0d3 Document `Token{Stream,Tree}::Display` more thoroughly.
To expressly warn against the kind of proc macro implementation that was
broken in #119875.
2024-01-22 13:31:52 +11:00
Michal Nazarewicz 50cbbef86a review 2024-01-21 20:12:00 +01:00
bors d9d89fd53d Auto merge of #119807 - Emilgardis:track_caller_from_impl_into, r=Nilstrieb
Add `#[track_caller]` to the "From implies Into" impl

This pr implements what was mentioned in https://github.com/rust-lang/rust/issues/77474#issuecomment-1074480790

This follows from my URLO https://users.rust-lang.org/t/104497

```rust
#![allow(warnings)]
fn main() {
    // Gives a good location
    let _: Result<(), Loc> = dbg!(Err::<(), _>(()).map_err(|e| e.into()));

    // still doesn't work, gives location of `FnOnce::call_once()`
    let _: Result<(), Loc> = dbg!(Err::<(), _>(()).map_err(Into::into));
}

#[derive(Debug)]
pub struct Loc {
    pub l: &'static std::panic::Location<'static>,
}

impl From<()> for Loc {
    #[track_caller]
    fn from(_: ()) -> Self {
        Loc {
            l: std::panic::Location::caller(),
        }
    }
}
```
2024-01-21 14:17:25 +00:00
Matthias Krüger 3eb7fe32a1
Rollup merge of #120180 - Zalathar:vec-split-off-alternatives, r=dtolnay
Document some alternatives to `Vec::split_off`

One of the discussion points that came up in #119917 is that some people use `Vec::split_off` in cases where they probably shouldn't, because the alternatives (like `mem::take`) are hard to discover.

This PR adds some suggestions to the documentation of `split_off` that should point people towards alternatives that might be more appropriate for their use-case.

I've deliberately tried to keep these changes as simple and uncontroversial as possible, so that they don't depend on how the team decides to handle the concerns raised in #119917. That's why I haven't touched the existing documentation for `split_off`, and haven't added links to `split_off` to the documentation of other methods.
2024-01-21 12:28:55 +01:00
Matthias Krüger 4a941d384d
Rollup merge of #120145 - the8472:fix-inplace-dest-drop, r=cuviper
fix: Drop guard was deallocating with the incorrect size

InPlaceDstBufDrop holds onto the allocation before the shrinking happens which means it must deallocate the destination elements but the source allocation.

Thanks `@cuviper` for spotting this.
2024-01-21 12:28:53 +01:00
Matthias Krüger 092d62734a
Rollup merge of #120045 - scottmcm:unhide-repeat-n, r=Mark-Simulacrum
Un-hide `iter::repeat_n`

ACP accepted in https://github.com/rust-lang/libs-team/issues/120#issuecomment-1894144403
2024-01-21 12:28:52 +01:00
bors fa404339c9 Auto merge of #85528 - the8472:iter-markers, r=dtolnay
Implement iterator specialization traits on more adapters

This adds

* `TrustedLen` to `Skip` and `StepBy`
* `TrustedRandomAccess` to `Skip`
* `InPlaceIterable` and `SourceIter` to  `Copied` and `Cloned`

The first two might improve performance in the compiler itself since `skip` is used in several places. Constellations that would exercise the last point are probably rare since it would require an owning iterator that has references as Items somewhere in its iterator pipeline.

Improvements for `Skip`:

```
# old
test iter::bench_skip_trusted_random_access                     ... bench:       8,335 ns/iter (+/- 90)

# new
test iter::bench_skip_trusted_random_access                     ... bench:       2,753 ns/iter (+/- 27)
```
2024-01-21 11:17:46 +00:00
HTGAzureX1212 1821bfaa09
chore: suggest wrapping in an `assert!()` instead
This shortens the `#[must_use]` diagnostics displayed, in light of the [review comment](https://github.com/rust-lang/rust/pull/62431/files#r300819839) on when this was originally added.
2024-01-21 18:39:09 +08:00
Nadrieril a1b41a9048
Rollup merge of #119996 - joboet:move_pal_os_str, r=ChrisDenton
Move OS String implementation into `sys`

Part of #117276. The new structure is really useful here, since we can easily eliminate a number of ugly `#[path]`-based imports.

In the future, it might be good to move the WTF-8 implementation directly to the OS string implementation, I cannot see it being used anywhere else. That is a story for another PR, however.
2024-01-21 06:38:37 +01:00
Nadrieril 3cd378cc15
Rollup merge of #119081 - jstasiak:is-ipv4-mapped, r=dtolnay
Add Ipv6Addr::is_ipv4_mapped

This change consists of cherry-picking the content from the original PR[1], which got closed due to inactivity, and applying the following changes:

* Resolving merge conflicts (obviously)
* Linked to to_ipv4_mapped instead of to_ipv4 in the documentation (seems more appropriate)
* Added the must_use and rustc_const_unstable attributes the original didn't have

I think it's a reasonably useful method to have.

[1] https://github.com/rust-lang/rust/pull/86490
2024-01-21 06:38:35 +01:00
Nadrieril e8d1c2ef9c
Rollup merge of #118811 - EbbDrop:is-sorted-by-bool, r=Mark-Simulacrum
Use `bool` instead of `PartiolOrd` as return value of the comparison closure in `{slice,Iteraotr}::is_sorted_by`

Changes the function signature of the closure given to `{slice,Iteraotr}::is_sorted_by` to return a `bool` instead of a `PartiolOrd` as suggested by the libs-api team here: https://github.com/rust-lang/rust/issues/53485#issuecomment-1766411980.

This means these functions now return true if the closure returns true for all the pairs of values.
2024-01-21 06:38:35 +01:00
Nadrieril b661cd6c57
Rollup merge of #116090 - rmehri01:strict_integer_ops, r=m-ou-se
Implement strict integer operations that panic on overflow

This PR implements the first part of the ACP for adding panic on overflow style arithmetic operations (https://github.com/rust-lang/libs-team/issues/270), mentioned in #116064.

It adds the following operations on both signed and unsigned integers:

- `strict_add`
- `strict_sub`
- `strict_mul`
- `strict_div`
- `strict_div_euclid`
- `strict_rem`
- `strict_rem_euclid`
- `strict_neg`
- `strict_shl`
- `strict_shr`
- `strict_pow`

Additionally, signed integers have:

- `strict_add_unsigned`
- `strict_sub_unsigned`
- `strict_abs`

And unsigned integers have:

- `strict_add_signed`

The `div` and `rem` operations are the same as normal division and remainder but are added for completeness similar to the corresponding `wrapping_*` operations.

I'm not sure if I missed any operations, I basically found them from the `wrapping_*` and `checked_*` operations on both integer types.
2024-01-21 06:38:34 +01:00
David Tolnay c43344e839
Add test of thread_local containing multiline const block
Before making thread_local accept statements inside the const block,
this test would fail to compile as follows:

    error: no rules expected the token `let`
       --> library/std/tests/thread.rs:26:13
        |
    26  |             let value = 1;
        |             ^^^ no rules expected this token in macro call
        |
    note: while trying to match meta-variable `$init:expr`
       --> library/std/src/thread/local.rs:189:69
        |
    189 |     ($(#[$attr:meta])* $vis:vis static $name:ident: $t:ty = const { $init:expr }; $($rest:tt)*) => (
        |                                                                     ^^^^^^^^^^
2024-01-20 19:00:27 -08:00
David Tolnay f52b88e91f
Revert example change from PR 116392 2024-01-20 18:39:48 -08:00
Nikolai Vazquez fc75a4e146
Allow any expression blocks in `thread_local!` 2024-01-20 18:39:16 -08:00
Zalathar 6f1944d394 Document some alternatives to `Vec::split_off` 2024-01-21 11:56:55 +11:00
bors 4cb17b4e78 Auto merge of #111803 - scottmcm:simple-swap-alternative, r=Mark-Simulacrum
Tweak the threshold for chunked swapping

Thanks to `@AngelicosPhosphoros` for the tests here, which I copied from #98892.

This is an experiment as a simple alternative to that PR that just tweaks the existing threshold, since that PR showed that 3×Align (like `String`) currently doesn't work as well as it could.
2024-01-20 21:54:44 +00:00
EbbDrop 606eeb84ad Use bool instead of PartiolOrd in is_sorted_by 2024-01-20 21:38:34 +01:00
bors 038d115cd8 Auto merge of #120170 - GuillaumeGomez:rollup-edqdf30, r=GuillaumeGomez
Rollup of 6 pull requests

Successful merges:

 - #119997 (Fix impl stripped in rustdoc HTML whereas it should not be in case the impl is implemented on a type alias)
 - #120000 (Ensure `callee_id`s are body owners)
 - #120063 (Remove special handling of `box` expressions from parser)
 - #120116 (Remove alignment-changing in-place collect)
 - #120138 (Increase vscode settings.json `git.detectSubmodulesLimit`)
 - #120169 (Spelling fix)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-01-20 19:55:26 +00:00
Guillaume Gomez 774cd3afd5
Rollup merge of #120169 - sunrosa:patch-1, r=ChrisDenton
Spelling fix

"It's" expands to "it is". "It is use..." doesn't make sense.

"Its" is the possessive form, and the intended form here.
2024-01-20 20:06:36 +01:00
Guillaume Gomez b917753d79
Rollup merge of #120116 - the8472:only-same-alignments, r=cuviper
Remove alignment-changing in-place collect

This removes the alignment-changing in-place collect optimization introduced in #110353
Currently stable users can't benefit from the optimization because GlobaAlloc doesn't support alignment-changing realloc and neither do most posix allocators. So in practice it has a negative impact on performance.

Explanation from https://github.com/rust-lang/rust/issues/120091#issuecomment-1899071681:

> > You mention that in case of alignment mismatch -- when the new alignment is less than the old -- the implementation calls `mremap`.
>
> I was trying to note that this isn't really the case in practice, due to the semantics of Rust's allocator APIs. The only use of the allocator within the `in_place_collect` implementation itself is [a call to `Allocator::shrink()`](db7125f008/library/alloc/src/vec/in_place_collect.rs (L299-L303)), which per its documentation [allows decreasing the required alignment](https://doc.rust-lang.org/1.75.0/core/alloc/trait.Allocator.html). However, in stable Rust, the only available `Allocator` is [`Global`](https://doc.rust-lang.org/1.75.0/alloc/alloc/struct.Global.html), which delegates to the registered `GlobalAlloc`. Since `GlobalAlloc::realloc()` [cannot change the required alignment](https://doc.rust-lang.org/1.75.0/core/alloc/trait.GlobalAlloc.html#method.realloc), the implementation of [`<Global as Allocator>::shrink()`](db7125f008/library/alloc/src/alloc.rs (L280-L321)) must fall back to creating a brand-new allocation, `memcpy`ing the data into it, and freeing the old allocation, whenever the alignment doesn't remain exactly the same.
>
> Therefore, the underlying allocator, provided by libc or some other source, has no opportunity to internally `mremap()` the data when the alignment is changed, since it has no way of knowing that the allocation is the same.
2024-01-20 20:06:35 +01:00
sunrosa 0e96840e7e
Spelling fix
"It's" expands to "it is". "Its" is the possessive form.
2024-01-20 18:27:55 +00:00
bors 1828461982 Auto merge of #117756 - a1phyr:hashmap_fold, r=the8472
`HashMap`/`HashSet`: forward `fold` implementations of iterators

Use [rust-lang/hasbrown#480](https://github.com/rust-lang/hashbrown/pull/480) in `std`

Note: this needs a version bump of hashbrown before merging
2024-01-20 17:53:26 +00:00
Michal Nazarewicz 755cfbf236 core: introduce split_at{,_mut}_checked
Introduce split_at_checked and split_at_mut_checked methods to slices
types (including str) which are non-panicking versions of split_at and
split_at_mut  respectively.  This is analogous to get method being
non-panicking version of indexing.
2024-01-20 15:18:31 +01:00
Matthias Krüger 862d3fe769
Rollup merge of #120150 - Jules-Bertholet:stabilize-round-ties-even, r=cuviper
Stabilize `round_ties_even`

Closes  #96710

`@rustbot` label -T-libs T-libs-api
2024-01-20 09:37:29 +01:00
Matthias Krüger 6f67208d72
Rollup merge of #118799 - GKFX:stabilize-simple-offsetof, r=wesleywiser
Stabilize single-field offset_of

This PR stabilizes offset_of for a single field. There has been some further discussion at https://github.com/rust-lang/rust/issues/106655 about whether this is advisable; I'm opening the PR anyway so that the code is available.
2024-01-20 09:37:26 +01:00