Commit Graph

6916 Commits

Author SHA1 Message Date
bors
9cdfe285ca Auto merge of #125423 - fmease:rollup-ne4l9y4, r=fmease
Rollup of 7 pull requests

Successful merges:

 - #125043 (reference type safety invariant docs: clarification)
 - #125306 (Force the inner coroutine of an async closure to `move` if the outer closure is `move` and `FnOnce`)
 - #125355 (Use Backtrace::force_capture instead of Backtrace::capture in rustc_log)
 - #125382 (rustdoc: rename `issue-\d+.rs` tests to have meaningful names (part 7))
 - #125391 (Minor serialize/span tweaks)
 - #125395 (Remove unnecessary `.md` from the documentation sidebar)
 - #125399 (Stop using `to_hir_binop` in codegen)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-05-22 21:51:26 +00:00
León Orell Valerian Liehr
ab9e0a72ef
Rollup merge of #125043 - RalfJung:ref-type-safety-invariant, r=scottmcm
reference type safety invariant docs: clarification

The old text could have been read as saying that you can call a function if these requirements are upheld, which is definitely not true as they are an underapproximation of the actual safety invariant.

I removed the part about functions relaxing the requirements via their documentation... this seems incoherent with saying that it may actually be unsound to ever temporarily violate the requirement. Furthermore, a function *cannot* just relax this for its return value, that would in general be unsound. And the part about "unsafe code in a safe function may assume these invariants are ensured of arguments passed by the caller" also interacts with relaxing things: clearly, if the invariant has been relaxed, unsafe code cannot rely on it any more. There may be a place to give general guidance on what kinds of function contracts can exist, but the reference type is definitely not the right place to write that down.

I also took a clarification from https://github.com/rust-lang/rust/pull/121965 that is orthogonal to the rest of that PR.

Cc ```@joshlf``` ```@scottmcm```
2024-05-22 23:41:11 +02:00
León Orell Valerian Liehr
8219fd2bc1
Rollup merge of #125296 - tesuji:checkcfg-buildstd, r=Nilstrieb,michaelwoerister
Fix `unexpected_cfgs` lint on std

closes #125291

r? rust-lang/compiler
2024-05-22 19:04:45 +02:00
León Orell Valerian Liehr
76d4bfb1c6
Rollup merge of #124896 - RalfJung:miri-intrinsic-fallback, r=oli-obk
miri: rename intrinsic_fallback_checks_ub to intrinsic_fallback_is_spec

Checking UB is not the only concern, we also have to make sure we are not losing out on non-determinism.

r? ``@oli-obk`` (not urgent, take your time)
2024-05-22 19:04:43 +02:00
bors
5d328a1f62 Auto merge of #117329 - RalfJung:offset-by-zero, r=oli-obk,scottmcm
offset: allow zero-byte offset on arbitrary pointers

As per prior `@rust-lang/opsem` [discussion](https://github.com/rust-lang/opsem-team/issues/10) and [FCP](https://github.com/rust-lang/unsafe-code-guidelines/issues/472#issuecomment-1793409130):

- Zero-sized reads and writes are allowed on all sufficiently aligned pointers, including the null pointer
- Inbounds-offset-by-zero is allowed on all pointers, including the null pointer
- `offset_from` on two pointers derived from the same allocation is always allowed when they have the same address

This removes surprising UB (in particular, even C++ allows "nullptr + 0", which we currently disallow), and it brings us one step closer to an important theoretical property for our semantics ("provenance monotonicity": if operations are valid on bytes without provenance, then adding provenance can't make them invalid).

The minimum LLVM we require (v17) includes https://reviews.llvm.org/D154051, so we can finally implement this.

The `offset_from` change is needed to maintain the equivalence with `offset`: if `let ptr2 = ptr1.offset(N)` is well-defined, then `ptr2.offset_from(ptr1)` should be well-defined and return N. Now consider the case where N is 0 and `ptr1` dangles: we want to still allow offset_from here.

I think we should change offset_from further, but that's a separate discussion.

Fixes https://github.com/rust-lang/rust/issues/65108
[Tracking issue](https://github.com/rust-lang/rust/issues/117945) | [T-lang summary](https://github.com/rust-lang/rust/pull/117329#issuecomment-1951981106)

Cc `@nikic`
2024-05-22 13:04:14 +00:00
Jubilee Young
3a21fb5cec Wrap Context.ext in AssertUnwindSafe 2024-05-21 19:05:37 -07:00
Ralf Jung
9526ce60fd improve comment wording 2024-05-21 21:13:20 +02:00
Lzu Tao
df3a32066f tidy alphabetica 2024-05-21 18:17:55 +00:00
Lzu Tao
c7d2f4592f addresss reviews 2024-05-21 18:17:55 +00:00
Lzu Tao
63fe640f5d Update check-cfg lists for core 2024-05-21 18:17:55 +00:00
joboet
fde4a22da2
core: actually use TAIT instead of emulating it 2024-05-21 15:59:48 +02:00
bors
6715446db6 Auto merge of #125358 - matthiaskrgr:rollup-mx841tg, r=matthiaskrgr
Rollup of 7 pull requests

Successful merges:

 - #124570 (Miscellaneous cleanups)
 - #124772 (Refactor documentation for Apple targets)
 - #125011 (Add opt-for-size core lib feature flag)
 - #125218 (Migrate `run-make/no-intermediate-extras` to new `rmake.rs`)
 - #125225 (Use functions from `crt_externs.h` on iOS/tvOS/watchOS/visionOS)
 - #125266 (compiler: add simd_ctpop intrinsic)
 - #125348 (Small fixes to `std::path::absolute` docs)

Failed merges:

 - #125296 (Fix `unexpected_cfgs` lint on std)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-05-21 12:50:09 +00:00
Matthias Krüger
fd975f75fa
Rollup merge of #125266 - workingjubilee:stream-plastic-love, r=RalfJung,nikic
compiler: add simd_ctpop intrinsic

Fairly straightforward addition.

cc `@rust-lang/opsem` new (extremely boring) intrinsic
2024-05-21 12:47:06 +02:00
Matthias Krüger
4abf179b14
Rollup merge of #125011 - diondokter:opt-for-size, r=Amanieu,kobzol
Add opt-for-size core lib feature flag

Adds a feature flag to the core library that enables the possibility to have smaller implementations for certain algorithms.

So far, the core lib has traded performance for binary size. This is likely what most people want since they have big simd-capable machines. However, people on small machines, like embedded devices, don't enjoy the potential speedup of the bigger algorithms, but do have to pay for them. These microcontrollers often only have 16-1024kB of flash memory.

This PR is the result of some talks with project members like `@Amanieu` at RustNL.
There are some open questions of how this is eventually stabilized, but it's a similar question as with the existing `panic_immediate_abort` feature.

Speaking as someone from the embedded side, we'd rather have this unstable for a while as opposed to not having it at all. In the meantime we can try to use it and also add additional PRs to the core lib that uses the feature flag in areas where we find benefit.

Open questions from my side:
- Is this a good feature name?
  - `panic_immediate_abort` is fairly verbose, so I went with something equally verbose
  - It's easy to refactor later
- I've added the feature to `std` and `alloc` as well as they might benefit too. Do we agree?
  - I expect these to get less usage out of the flag since most size-constraint projects don't use these libraries often.
2024-05-21 12:47:04 +02:00
Michael Goulet
a502e7ac1d Implement BOXED_SLICE_INTO_ITER 2024-05-20 19:21:30 -04:00
Michael Goulet
1a81092531 Add the impls for Box<[T]>: IntoIterator
Co-authored-by: ltdk <usr@ltdk.xyz>
2024-05-20 19:21:30 -04:00
Taiki Endo
c31ec4fb04 Fix c_char on AIX
Refs: https://github.com/rust-lang/rust/issues/122985
2024-05-20 22:46:13 +09:00
Arpad Borsos
aaba972e06
Switch to primarily using &str
Surprisingly, benchmarks have shown that using `&str`
instead of `&[u8]` with some `unsafe` code is actually faster.
2024-05-20 11:31:02 +02:00
Arpad Borsos
42d870ec88
Introduce printable-ASCII fast-path for impl Debug for str
Instead of having a single loop that works on utf-8 `char`s,
this splits the implementation into a loop that quickly skips over
printable ASCII, falling back to per-char iteration for other chunks.
2024-05-20 11:10:38 +02:00
Arpad Borsos
3fda931afe
Add a fast-path to Debug ASCII &str
Instead of going through the `EscapeDebug` machinery, we can just skip over ASCII chars that don’t need any escaping.
2024-05-20 10:04:45 +02:00
Arpad Borsos
0334c45bb5
Write char::DebugEscape sequences using write_str
Instead of writing each `char` of an escape sequence one by one,
this delegates to `Display`, which uses `write_str` internally
in order to write the whole escape sequence at once.
2024-05-20 10:04:44 +02:00
bors
959a67a7f2 Auto merge of #123786 - a1phyr:cursor_unsafe, r=joboet
Remove bound checks from `BorrowedBuf` and `BorrowedCursor` methods
2024-05-19 17:16:12 +00:00
Jubilee Young
1914c722b5 compiler: add simd_ctpop intrinsic 2024-05-18 18:11:20 -07:00
beetrees
827711d087
Add #[inline] to float Debug fallback used by cfg(no_fp_fmt_parse) 2024-05-18 16:25:55 +01:00
Noa
53b317710d
Inline Duration construction into Duration::from_{millis,micros,nanos} 2024-05-17 18:37:59 -05:00
Noa
35522a9e09
Don't call Duration::new unnecessarily in Duration::from_secs 2024-05-17 14:26:50 -05:00
bors
ddba1dc97e Auto merge of #125188 - tgross35:f16-f128-powi, r=Nilstrieb
Add `powi` fo `f16` and `f128`

This will unblock adding support to compiler_builtins (<https://github.com/rust-lang/compiler-builtins/pull/614>), which will then unblock adding tests for these new functions.
2024-05-17 11:24:07 +00:00
Matthias Krüger
a6862f8612
Rollup merge of #125186 - Colepng:master, r=lqd
Remove duplicate word from addr docs

This PR simply removes a duplicate word from the addr docs for *mut T.
2024-05-17 07:20:58 +02:00
Matthias Krüger
7a8d222d6b
Rollup merge of #125171 - scottmcm:rename-flatten, r=jhpratt
Rename `flatten(_mut)` → `as_flattened(_mut)`

As requested by libs-api in https://github.com/rust-lang/rust/issues/95629#issuecomment-2113081194

(This is just the rename, not the stabilization, so can land without waiting on the FCP in that other issue.)
2024-05-17 07:20:57 +02:00
Trevor Gross
7685734384 Add powi to f16 and f128
This will unblock adding support to compiler_builtins
(<https://github.com/rust-lang/compiler-builtins/pull/614>), which will
then unblock adding tests for these new functions.
2024-05-16 15:41:06 -05:00
Trevor Gross
a7ca099e03 Add doctests for f16 and f128 library functions where possible 2024-05-16 15:16:42 -05:00
Cole Kauder-McMurrich
d8b9717038
Remove duplicate word from addr docs 2024-05-16 16:16:38 -04:00
bors
2d89cee625 Auto merge of #124728 - beetrees:from-f16-for-f64, r=BurntSushi
Re-add `From<f16> for f64`

This impl was originally added in #122470 before being removed in #123830 due to #123831. However, the issue only affects `f32` (which currently only has one `From<{float}>` impl, `From<f32>`) as `f64` already has two `From<{float}>` impls (`From<f32>` and `From<f64>`) and is also the float literal fallback type anyway. Therefore it is safe to re-add `From<f16> for f64`.

This PR also updates the FIXME link to point to the open issue #123831 rather than the closed issue #123824.

Tracking issue: #116909

`@rustbot` label +F-f16_and_f128 +T-libs-api
2024-05-16 16:48:58 +00:00
Lukas Bergdoll
88fb5edb65 Fix linkchecker doc errors
Also includes small doc fixes.
2024-05-16 17:08:56 +02:00
Lukas Bergdoll
8300f67c6e Turn bare links into automatic links 2024-05-16 17:08:56 +02:00
Lukas Bergdoll
1a6b0e410e Fix tidy errors 2024-05-16 17:08:55 +02:00
Lukas Bergdoll
e49be415cd Replace sort implementations
- `slice::sort` -> driftsort
  https://github.com/Voultapher/sort-research-rs/blob/main/writeup/driftsort_introduction/text.md

- `slice::sort_unstable` -> ipnsort
  https://github.com/Voultapher/sort-research-rs/blob/main/writeup/ipnsort_introduction/text.md

Replaces the sort implementations with tailor made ones that strike a
balance of run-time, compile-time and binary-size, yielding run-time and
compile-time improvements. Regressing binary-size for `slice::sort`
while improving it for `slice::sort_unstable`. All while upholding the
existing soft and hard safety guarantees, and even extending the soft
guarantees, detecting strict weak ordering violations with a high chance
and reporting it to users via a panic.

In addition the implementation of `select_nth_unstable` is also adapted
as it uses `slice::sort_unstable` internals.
2024-05-16 17:08:55 +02:00
bors
4a78c00e22 Auto merge of #124959 - prorealize:update-result-documentation, r=joboet
Refactor examples and enhance documentation in result.rs

- Replaced `map` with `map_err` in the error handling example for correctness
- Reordered example code to improve readability and logical flow
- Added assertions to examples to demonstrate expected outcomes
2024-05-16 12:21:12 +00:00
Scott McMurray
facc0bb78e Rename flatten(_mut)as_flattened(_mut) 2024-05-15 23:39:33 -07:00
Zachary S
376a8c0ae5 Allow for_loops_over_fallibles in test that tests &mut Result as IntoIterator. 2024-05-15 13:51:16 -05:00
León Orell Valerian Liehr
4f7d9d4ad8
Rollup merge of #125038 - ivan-shrimp:checked_sub, r=joboet
Invert comparison in `uN::checked_sub`

After #124114, LLVM no longer combines the comparison and subtraction in `uN::checked_sub` when either operand is a constant (demo: https://rust.godbolt.org/z/MaeoYbsP1). The difference is more pronounced when the expression is slightly more complex (https://rust.godbolt.org/z/4rPavsYdc).

This is due to the use of `>=` here:

ee97564e3a/library/core/src/num/uint_macros.rs (L581-L593)

For constant `C`, LLVM eagerly converts `a >= C` into `a > C - 1`, but the backend can only combine `a < C` with `a - C`, not `C - 1 < a` and `a - C`: e586556e37/llvm/lib/CodeGen/CodeGenPrepare.cpp (L1697-L1742)

This PR[^1] simply inverts the `>=` into `<` to restore the LLVM magic, and somewhat align this with the implementation of `uN::overflowing_sub` from #103299.

When the result is stored as an `Option` (rather than being branched/cmoved on), the discriminant is `self >= rhs`. This PR doesn't affect the codegen (and relevant tests) of that since LLVM will negate `self < rhs` to `self >= rhs` when necessary.

[^1]: Note to `self`: My very first contribution to publicly-used code. Hopefully like what I should learn to always be, tiny and humble.
2024-05-15 14:21:38 +02:00
León Orell Valerian Liehr
3873a74f8a
Rollup merge of #124307 - reitermarkus:escape-debug-size-hint-inline, r=joboet
Optimize character escaping.

Allow optimization of panicking branch in `EscapeDebug`, see https://github.com/rust-lang/rust/pull/121805.

r? `@joboet`
2024-05-15 14:21:37 +02:00
Renato A
e1611aa690
Update library/core/src/result.rs
Co-authored-by: joboet <jonasboettiger@icloud.com>
2024-05-15 08:07:16 -03:00
Artyom Pavlov
8da41b107d
Divide float nanoseconds instead of seconds 2024-05-15 00:38:34 +03:00
Jacob Pratt
74a78af0e2
Rollup merge of #116675 - joshlf:patch-10, r=scottmcm
[ptr] Document maximum allocation size

Partially addresses https://github.com/rust-lang/unsafe-code-guidelines/issues/465
2024-05-13 21:14:15 -04:00
Joshua Liebow-Feeser
293b5cb1ca [ptr] Document maximum allocation size 2024-05-13 11:14:45 -07:00
Lokathor
b468f21051 Don't use T with both Result and Option, improve explanation. 2024-05-13 10:36:42 -06:00
Josh Triplett
a5a60d75a8 Add size_of, size_of_val, align_of, and align_of_val to the prelude
Many, many projects use `size_of` to get the size of a type. However,
it's also often equally easy to hardcode a size (e.g. `8` instead of
`size_of::<u64>()`). Minimizing friction in the use of `size_of` helps
ensure that people use it and make code more self-documenting.

The name `size_of` is unambiguous: the name alone, without any prefix or
path, is self-explanatory and unmistakeable for any other functionality.
Adding it to the prelude cannot produce any name conflicts, as any local
definition will silently shadow the one from the prelude. Thus, we don't
need to wait for a new edition prelude to add it.

Add `size_of_val`, `align_of`, and `align_of_val` as well, with similar
justification: widely useful, self-explanatory, unmistakeable for
anything else, won't produce conflicts.
2024-05-13 15:11:28 +02:00
Ralf Jung
5c33a5690d offset, offset_from: allow zero-byte offset on arbitrary pointers 2024-05-13 07:59:16 +02:00
Ralf Jung
7c76eec30f reference type safety invariant docs: clarification 2024-05-12 10:03:53 +02:00
ivan-shrimp
7fde7308bf reverse condition in uN::checked_sub 2024-05-12 11:29:24 +08:00
Joshua Liebow-Feeser
15df3d78e4
References must also be non-null 2024-05-11 12:08:19 -07:00
Joshua Liebow-Feeser
1cefaa7432
Relax slice safety requirements
Per https://github.com/rust-lang/rust/pull/116677#issuecomment-1945495786, the language as written promises too much. This PR relaxes the language to be consistent with current semantics. If and when #117945 is implemented, we can revert to the old language.
2024-05-11 11:50:20 -07:00
Dion Dokter
1d1981b7b0 Add opt-for-size core lib feature flag 2024-05-11 14:07:19 +02:00
Matthias Krüger
6c3fce90cc
Rollup merge of #124954 - kpreid:fmterr, r=Nilstrieb
Document proper usage of `fmt::Error` and `fmt()`'s `Result`.

I've seen several newcomers wonder why `fmt::Error` doesn't have any error detail information, or propose to return it in response to an error condition found inside a `impl fmt::Display for MyType`.

That is incorrect, per [a lone paragraph of the `fmt` module's documentation](https://doc.rust-lang.org/1.78.0/std/fmt/index.html#formatting-traits). However, users looking to implement a formatting trait won't necessarily look there. Therefore, let's add the critical information (that formatting per se is infallible) to all the involved items: every `fmt()` method, and `fmt::Error`.

This PR is not intended to make any novel claims about `fmt`; only to repeat an existing one in places where it will be more visible.
2024-05-11 13:16:40 +02:00
Matthias Krüger
03ff775966
Rollup merge of #124928 - okaneco:trim_ascii, r=workingjubilee
Stabilize `byte_slice_trim_ascii` for `&[u8]`/`&str`

Remove feature from documentation examples
Update intra-doc link for `u8::is_ascii_whitespace` on `&[u8]` functions

Closes #94035

FCP has successfully completed https://github.com/rust-lang/rust/issues/94035#issuecomment-2102690397
2024-05-11 13:16:40 +02:00
okaneco
9fb49faf40 Stabilize byte_slice_trim_ascii for &[u8]/&str
Remove feature from documentation examples
Add rustc_const_stable attribute to stabilized functions
Update intra-doc link for `u8::is_ascii_whitespace` on `&[u8]` functions
2024-05-10 23:42:40 -04:00
Infinixius
781d737478
Fix typo in ManuallyDrop's documentation 2024-05-10 23:13:32 +00:00
bors
cf774742b6 Auto merge of #124863 - DaniPopes:from-str-radix-panic, r=Amanieu
from_str_radix: outline only the panic function

In the `{integer}::from_str_radix` function, the radix check is labeled as `cold` and `inline(never)`, along with its corresponding panic. It probably was intended to apply these attributes only to the panic function.
2024-05-10 11:48:15 +00:00
Renato Alves
4a953dc5ff Fix assert 2024-05-10 08:10:30 -03:00
Matthias Krüger
f3f9f0c5e6
Rollup merge of #124551 - Swatinem:debug-str-bench, r=cuviper
Add benchmarks for `impl Debug for str`

In order to inform future perf improvements and prevent regressions, lets add some benchmarks that stress `impl Debug for str`.

---

As I am currently working on improving the perf in https://github.com/rust-lang/rust/pull/121150, its nice to have these benchmarks.

Writing them, I also saw that escapes are written out one char at a time, even though other parts of the code are already optimizing that via `as_str`, which I intend to do as well as a followup improvement.

r? ``@cuviper``
☝🏻 as you were also assigned to https://github.com/rust-lang/rust/pull/121150, CC ``@the8472`` if you want to steal the review :-)
2024-05-10 07:30:19 +02:00
Renato Alves
336dd16d05 Refactor examples and enhance documentation in result.rs 2024-05-10 01:03:00 -03:00
Kevin Reid
c21c5baad9 Document proper usage of fmt::Error and fmt()'s Result.
Documentation of these properties previously existed in a lone paragraph
in the `fmt` module's documentation:
<https://doc.rust-lang.org/1.78.0/std/fmt/index.html#formatting-traits>
However, users looking to implement a formatting trait won't necessarily
look there. Therefore, let's add the critical information (that
formatting per se is infallible) to all the involved items.
2024-05-09 17:58:38 -07:00
Markus Reiter
4edf12d33e
Improve escape methods. 2024-05-09 17:04:30 +02:00
bors
ee9a9f84c5 Auto merge of #124793 - scottmcm:simplify-as-chunks, r=Nilstrieb
Implement `as_chunks` with `split_at_unchecked`

We were discussing various ways to do [this on Discord](https://discord.com/channels/273534239310479360/273541522815713281/1236946363120619521), and in the process I noticed that <https://rust.godbolt.org/z/1P16P37Go> is emitting a panic path inside `as_chunks`.  It optimizes out in release, but we could just not do that in the first place.

We're already doing unsafe code that depends on this value being calculated correctly, so might as well call `split_at_unchecked` instead of `split_at`.
2024-05-09 01:55:46 +00:00
bors
87293c9585 Auto merge of #124910 - matthiaskrgr:rollup-lo1uvdn, r=matthiaskrgr
Rollup of 8 pull requests

Successful merges:

 - #123344 (Remove braces when fixing a nested use tree into a single item)
 - #124587 (Generic `NonZero` post-stabilization changes.)
 - #124775 (crashes: add lastest batch of crash tests)
 - #124869 (Make sure we don't deny macro vars w keyword names)
 - #124876 (Simplify `use crate::rustc_foo::bar` occurrences.)
 - #124892 (Update cc crate to v1.0.97)
 - #124903 (Ignore empty RUSTC_WRAPPER in bootstrap)
 - #124909 (Reapply the part of #124548 that bors forgot)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-05-08 21:47:34 +00:00
Markus Reiter
16981ba406
Avoid panicking branch in EscapeIterInner. 2024-05-08 21:52:32 +02:00
Markus Reiter
e3fc97be2b
Inline EscapeDebug::size_hint. 2024-05-08 21:52:31 +02:00
bors
ec1b69852f Auto merge of #124795 - scottmcm:simplify-slice-from-raw-parts, r=joboet
Avoid a cast in `ptr::slice_from_raw_parts(_mut)`

Casting to `*const ()` or `*mut ()` is no longer needed after https://github.com/rust-lang/rust/pull/123840 so let's make the MIR smaller (and more inline-able, as seen in the tests).

If [ACP#362](https://github.com/rust-lang/libs-team/issues/362) goes through we can keep calling `ptr::from_raw_parts(_mut)` in these also without the cast, but that hasn't had any libs-api attention yet, so I'm not waiting on it.
2024-05-08 19:37:57 +00:00
Markus Reiter
bd8e565e16
Use generic NonZero. 2024-05-08 21:37:55 +02:00
Markus Reiter
767711b905
Use generic NonZero in examples. 2024-05-08 21:37:53 +02:00
Ralf Jung
75f57670b0 miri: rename intrinsic_fallback_checks_ub to intrinsic_fallback_is_spec 2024-05-08 17:46:06 +02:00
Jubilee
ceb5ec3ad9
Rollup merge of #124838 - RalfJung:next_power_of_two, r=scottmcm
next_power_of_two: add a doctest to show what happens on 0
2024-05-08 00:37:11 -07:00
Lokathor
10f8d1ffef use teletype on the attribute name 2024-05-07 18:35:00 -06:00
Lokathor
f94fa6bee3 Some Result combinations work like an Option. 2024-05-07 18:08:36 -06:00
DaniPopes
eac37b6caf
from_str_radix: outline only the panic function 2024-05-08 00:20:06 +02:00
bors
cc8d9b6927 Auto merge of #124836 - tgross35:const-slice-last-chunk, r=BurntSushi
Correct the const stabilization of `last_chunk` for slices

`<[T]>::last_chunk` should have become const stable as part of <https://github.com/rust-lang/rust/pull/117561>. Update the const stability gate to reflect this.
2024-05-07 12:40:20 +00:00
Ralf Jung
776f182241 next_power_of_two: add a doctest to show what happens on 0 2024-05-07 10:48:04 +02:00
Trevor Gross
3488679768 Correct the const stabilization of last_chunk for slices
`<[T]>::last_chunk` should have become const stable as part of
<https://github.com/rust-lang/rust/pull/117561>. Update the const
stability gate to reflect this.
2024-05-07 03:03:44 -05:00
Trevor Spiteri
fac0a74450 f16::is_sign_{positive,negative} were feature-gated on f128 2024-05-06 23:36:47 +02:00
bors
fc47cf38e5 Auto merge of #123850 - tspiteri:f16_f128_consts, r=Amanieu
Add constants for f16 and f128

- Commit 1 adds associated constants for `f16`, excluding NaN and infinities as these are implemented using arithmetic for `f32` and `f64`.
- Commit 2 adds associated constants for `f128`, excluding NaN and infinities.
- Commit 3 adds constants in `std::f16::consts`.
- Commit 4 adds constants in `std::f128::consts`.
2024-05-06 14:45:28 +00:00
Scott McMurray
61517dbbe6 Avoid a cast in ptr::slice_from_raw_parts(_mut)
Casting to `*const ()` or `*mut ()` just bloats the MIR, so let's not.

If ACP#362 goes through we can keep calling `ptr::from_raw_parts(_mut)` in these also without the cast, but that hasn't had any libs-api attention yet, so I'm not waiting on it.
2024-05-06 01:53:54 -07:00
Scott McMurray
49af347653 Implement as_chunks with split_at_unchecked 2024-05-06 01:04:27 -07:00
Guillaume Gomez
4eedf7385b
Rollup merge of #124750 - ultrabear:ultrabear_softfloatdoc, r=workingjubilee
Document That `f16` And `f128` Hardware Support is Limited (v2)

This PR is identical to #123892, which was approved and merged but then removed from master by a force-push due to a [CI bug](https://rust-lang.zulipchat.com/#narrow/stream/242791-t-infra/topic/ci.20broken.3F).

r? ghost

Original PR description:

---

This adds a small paragraph to the recently added f16 and f128 types explaining that hardware support may be limited, and that performance may suffer as a result of that.

I mainly wrote this because I felt it may be useful to express in some form; as a launchpoint for readers of the documentation if they have issues with performance.

I tried to word the documentation in a way that doesn't create false assumptions (that f16/f128 is too slow to use, for instance), removing the software implementation part could mislead people to thinking that f16/f128 is only available on some platforms, not all, so I believe it is important to keep in.\
"not all *major* platforms" is specifically said so as to not be redundant, because not all platforms implement many things, but the average rustacean is probably going to be using x86_64 or aarch64 derived ISA's, which is who this documentation is targeted towards.

I'm not sure of the best way to word the documentation, or if it should even be added, but I feel like it may be useful to have (potentially in a reworded way, I'm not very confident in the current wording and cannot decide if that is because it is too vague to be useful or too specific to be generally correct).
2024-05-05 16:42:48 +02:00
beetrees
5cc4ee3d88
Re-add From<f16> for f64 2024-05-04 22:56:35 +01:00
Alex H
5aa2f9a208
Make f128 docs mention lack of any normal platform support
Co-authored-by: Jubilee <46493976+workingjubilee@users.noreply.github.com>

Update library/core/src/primitive_docs.rs

Remove orphaned doc link and clean up grammar a bit

Update library/core/src/primitive_docs.rs
2024-05-04 14:51:55 -07:00
Alex H
3ef25288a4
Make f16 and f128 docs clearer on platform support
Co-authored-by: Jubilee <46493976+workingjubilee@users.noreply.github.com>

Update library/core/src/primitive_docs.rs

Rewrite f16 and f128 hw support comments to match PR feedback

I wrote RISC-V allcaps in all cases, and wrote amd64 lowercase in all
cases, im not sure if either is the more correct way for either
platform, thats just how I normally write them, if theres a precedent
elsewhere it should probably be changed to match though.

Update library/core/src/primitive_docs.rs

Co-authored-by: Jubilee <46493976+workingjubilee@users.noreply.github.com>

Update library/core/src/primitive_docs.rs

Co-authored-by: Jubilee <46493976+workingjubilee@users.noreply.github.com>

Update library/core/src/primitive_docs.rs
2024-05-04 14:51:35 -07:00
Alex H
e30ad6ff2c
Tgross feedback tweaks
Co-authored-by: Trevor Gross <t.gross35@gmail.com>

Update library/core/src/primitive_docs.rs

Co-authored-by: Trevor Gross <t.gross35@gmail.com>

Update library/core/src/primitive_docs.rs
2024-05-04 14:51:13 -07:00
Matthias Krüger
a5cc1f663f
Rollup merge of #124699 - scottmcm:split_at_unchecked_should_use_unchecked, r=Nilstrieb
Use `unchecked_sub` in `split_at`

LLVM currently isn't figuring it out on its own, even in the checked version where it hypothetically could.

Before: <https://rust.godbolt.org/z/PEY38YrKs>
```llvm
bb1:                                              ; preds = %start
  %4 = getelementptr inbounds float, ptr %x.0, i64 %n
  %5 = sub i64 %x.1, %n
```

After:
```llvm
bb1:                                              ; preds = %start
  %4 = getelementptr inbounds float, ptr %x.0, i64 %n
  %5 = sub nuw i64 %x.1, %n
```

This is not using the wrapper because there's already a ubcheck covering it, so I don't want this to get a second one once #121571 lands.

---

This is basically the same as #108763, since `split_at` is essentially doing two `get_unchecked`s.
2024-05-04 18:36:38 +02:00
Matthias Krüger
5f4f4fbb98
Rollup merge of #124701 - scottmcm:unchecked_sub_docs, r=Nilstrieb
Docs: suggest `uN::checked_sub` instead of check-then-unchecked

As of #124114 it's exactly the same in codegen, so might as well not use `unsafe`.

Note that this is only for *unsigned*, since the overflow conditions for `iN::checked_sub` are more complicated.
2024-05-04 12:37:24 +02:00
Matthias Krüger
770567101c
Rollup merge of #124700 - scottmcm:unneeded_cast, r=Nilstrieb
Remove an unnecessary cast

Very minor thing, obviously, but I randomly saw this unnecessary cast showing up in the UbChecks, so might as well get rid of it.
2024-05-04 12:37:24 +02:00
Matthias Krüger
ceb7b5e70e
Rollup merge of #124293 - oli-obk:miri_intrinsic_fallback_body, r=RalfJung
Let miri and const eval execute intrinsics' fallback bodies

fixes https://github.com/rust-lang/miri/issues/3397

r? ``@RalfJung``
2024-05-04 12:37:22 +02:00
Scott McMurray
e1c833eb07 Docs: suggest uN::checked_sub instead of check-then-unchecked
As of 124114 it's exactly the same in codegen, so might as well not use `unsafe`.

Note that this is only for *unsigned*, since the overflow conditions for `iN::checked_sub` are more complicated.
2024-05-04 01:44:49 -07:00
Scott McMurray
b95d1b716f Remove an unnecessary cast
Very minor thing, obviously, but I randomly saw this unnecessary cast showing up in the UbChecks, so might as well get rid of it.
2024-05-04 01:25:39 -07:00
Scott McMurray
f1de4c16ee Use unchecked_sub in split_at 2024-05-04 00:54:21 -07:00
Ralf Jung
4e97c6c5c7 mark const_(de)allocate intrinsics as suitable for Miri 2024-05-04 08:40:42 +02:00
Michael Goulet
93ca906cb5
Rollup merge of #124678 - UserIsntAvailable:feat/stabilize-split-at-checked, r=jhpratt
Stabilize `split_at_checked`

Closes #119128

For the const version of `slice::split_at_mut_checked`, I'm reusing the `const_slice_split_at_mut` feature flag (#101804). I don't if it okay to reuse tracking issues or if it preferred to create new ones...
2024-05-03 23:34:24 -04:00
UserIsntAvailable
4c286c7f9a feat: stabilize split_at_checked 2024-05-03 15:02:02 -04:00
Matthias Krüger
1ff247c404
Rollup merge of #124593 - GKFX:cstr-literals-in-api-docs, r=workingjubilee
Describe and use CStr literals in CStr and CString docs

Mention CStr literals in the description of both types, and use them in some of the code samples for CStr. This is intended to make C string literals more discoverable.

Additionally, I don't think the orange "This example is not tested" warnings are very encouraging, so I have made the examples on `CStr` build.
2024-05-03 20:33:46 +02:00
Matthias Krüger
4b913a2330
Rollup merge of #123815 - trueb2:patch-1, r=workingjubilee
Fix cannot usage in time.rs

Fix a small grammar error in usage of cannot in time.rs errors
2024-05-03 20:33:44 +02:00
Matthias Krüger
a296693376
Rollup merge of #122492 - GrigorenkoPV:ptr_as_ref_unchecked, r=workingjubilee
Implement ptr_as_ref_unchecked

Implementation of #122034.

Prefixed the feature name with `ptr_` for clarity.

Linked const-unstability to #91822, so the post there should probably be updated to mentions the 3 new methods when/if this PR is merged.
2024-05-03 20:33:44 +02:00
Артём Павлов [Artyom Pavlov]
6d223bb6a1 Use CURRENT_RUSTC_VERSION 2024-05-03 17:42:34 +03:00
Артём Павлов [Artyom Pavlov]
1f1653c328 Stabilize div_duration 2024-05-03 17:31:55 +03:00
Oli Scherer
821d23b329 Ensure miri only uses fallback bodies that have manually been vetted to preserve all UB that the native intrinsic would have 2024-05-03 09:16:57 +00:00
Matthias Krüger
e2a53441b9
Rollup merge of #124626 - RalfJung:const_eval_select, r=joboet
const_eval_select: add tracking issue
2024-05-03 06:04:23 +02:00
Matthias Krüger
e17a222a0a
Rollup merge of #123480 - Nadrieril:impl-all-derefpures, r=compiler-errors
deref patterns: impl `DerefPure` for more std types

Context: [deref patterns](https://github.com/rust-lang/rust/issues/87121). The requirements of `DerefPure` aren't precise yet, but these types unambiguously satisfy them.

Interestingly, a hypothetical `impl DerefMut for Cow` that does a `Clone` would *not* be eligible for `DerefPure` if we allow mixing deref patterns with normal patterns. If the following is exhaustive then the `DerefMut` would cause UB:
```rust
match &mut Cow::Borrowed(&()) {
    Cow::Owned(_) => ..., // Doesn't match
    deref!(_x) if false => ..., // Causes the variant to switch to `Owned`
    Cow::Borrowed(_) => ..., // Doesn't match
    // We reach unreachable
}
```
2024-05-03 06:04:19 +02:00
George Bateman
0e0042f16e
Update based on review 2024-05-02 21:29:13 +01:00
Ralf Jung
dbe2f51d62 const_eval_select: add tracking issue 2024-05-02 18:39:27 +02:00
Trevor Spiteri
30d787ae9b add constants in std::f128::consts 2024-05-02 15:13:30 +02:00
Trevor Spiteri
5ea4873fbe add constants in std::f16::consts 2024-05-02 15:13:30 +02:00
Trevor Spiteri
96f6b0be57 add f128 associated constants
NaN and infinity are not included as they require arithmetic.
2024-05-02 15:13:30 +02:00
Trevor Spiteri
f679a9e79c add f16 associated constants
NaN and infinity are not included as they require arithmetic.
2024-05-02 15:13:30 +02:00
bors
80451a485b Auto merge of #124419 - WaffleLapkin:never-type-fallback-docs, r=workingjubilee
Document never type fallback in `!`'s docs

Pulled the documentation I've written for #123939.

I want a single place where never type fallback is explained, which can be referred in all the lints and migration materials.
2024-05-02 11:54:53 +00:00
Waffle Maybe
e18b6e819e
fixup links in never type docs
Co-authored-by: Jubilee <46493976+workingjubilee@users.noreply.github.com>
2024-05-02 06:04:16 +02:00
Mark Rousskov
44988e2577 Workaround rustfmt bug replacing type ascription 2024-05-01 23:23:00 -04:00
Waffle Lapkin
e2eb053bba Slightly reformat !'s docs after applying github suggestions 2024-05-02 04:19:43 +02:00
Mark Rousskov
a64f941611 Step bootstrap cfgs 2024-05-01 22:19:11 -04:00
Waffle Maybe
3a40e838bf
Apply suggestions from code review
Co-authored-by: Kevin Reid <kpreid@switchb.org>
Co-authored-by: Herman Skogseth <herman.skogseth@me.com>
Co-authored-by: Jubilee <46493976+workingjubilee@users.noreply.github.com>
2024-05-02 04:13:57 +02:00
Mark Rousskov
bd7d328807 Replace version placeholders for 1.79 2024-05-01 21:01:51 -04:00
George Bateman
e610a52a62
Describe and use CStr literals in CStr and CString docs 2024-05-01 19:59:00 +01:00
Matthias Krüger
38cbad9d26
Rollup merge of #124542 - CBSpeir:diagnostic-item-enumerate-method, r=scottmcm
Add diagnostic item for `std::iter::Iterator::enumerate`

Adds a diagnostic item for the `std::iter:Iterator::enumerate` trait method. This change, along with PR https://github.com/rust-lang/rust/pull/124308, will be used by the clippy `unused_enumerate_index` lint to move away from paths to using diagnostic items.

see: https://github.com/rust-lang/rust-clippy/issues/5393
2024-05-01 20:05:26 +02:00
Arpad Borsos
5fe296c6c5
Add benchmarks for impl Debug for str
In order to inform future perf improvements and prevent regressions,
lets add some benchmarks that stress `impl Debug for str`.
2024-05-01 09:54:29 +02:00
bors
2e88e9e7d0 Auto merge of #124491 - madsmtm:target_vendor-apple, r=workingjubilee
Use `target_vendor = "apple"` instead of `target_os = "..."`

Use `target_vendor = "apple"` instead of `all(target_os = "macos", target_os = "ios", target_os = "tvos", target_os = "watchos", target_os = "visionos")`.

The apple targets are quite close to being identical, with iOS, tvOS, watchOS and visionOS being even closer, so using `target_vendor` when possible makes it clearer when something is actually OS-specific, or just Apple-specific.
Note that `target_vendor` will [be deprecated in the future](https://github.com/rust-lang/rust/issues/100343), but not before an alternative (like `target_family = "apple"`) is available.

While doing this, I found various inconsistencies and small mistakes in the standard library, see the commits for details. Will follow-up with an extra PR for a similar issue that need a bit more discussion. EDIT: https://github.com/rust-lang/rust/pull/124494

Since you've talked about using `target_vendor = "apple"` in the past:
r? workingjubilee

CC `@simlay,` `@thomcc`
`@rustbot` label O-macos O-ios O-tvos O-watchos O-visionos
2024-05-01 02:11:29 +00:00
Christopher B. Speir
c8079e9390 Add diagnostic item for std::iter::Iterator::enumerate 2024-04-29 17:36:31 -05:00
许杰友 Jieyou Xu (Joe)
0580588ec6
Rollup merge of #124484 - GKFX:offset_of_must_use, r=jieyouxu
Fix #124478 - offset_of! returns a temporary

This was due to the must_use() call. Adding HIR's `OffsetOf` to the must_use checking within the compiler avoids this issue while maintaining the lint output.

Fixes #124478. `@tgross35`
2024-04-29 18:03:24 +01:00
bors
5b1d58c9e2 Auto merge of #124502 - NCGThompson:statically-known-docs, r=jhpratt
Update `is_val_statically_known` Docs

* Add `Type Requirements` section, listing the allowed inputs, as requested by #121115
* Add `Pointers` subsection, explaining is_val_statically_known handles pointers.
* Add `Stability concerns` section, referring to other documentation relating to consistency in `const` functions.

Fixes #121115

Sorry this took so long.
2024-04-29 03:00:12 +00:00
Nicholas Thompson
5969ad4cae Update is_val_statically_known docs
* Add `Type Requirements` section, listing the allowed inputs, as requested by #121115
* Add `Pointers` subsection, explaining is_val_statically_known handles pointers.
* Add `Stability concerns` section, referring to other documentation relating to consistency in `const` functions.
2024-04-28 21:00:53 -04:00
Trevor Gross
e0f8202ed5 Stabilize non_null_convenience
Fully stabilize the following API, including const where applicable:

    impl <T> NonNull<T> {
        pub const unsafe fn offset(self, count: isize) -> Self;
        pub const unsafe fn add(self, count: usize) -> Self;
        pub const unsafe fn sub(self, count: usize) -> Self;
        pub const unsafe fn offset_from(self, origin: NonNull<T>) -> isize;
        pub const unsafe fn read(self) -> T;
        pub unsafe fn read_volatile(self) -> T;
        pub const unsafe fn read_unaligned(self) -> T;
        pub unsafe fn write_volatile(self, val: T);
        pub unsafe fn replace(self, src: T) -> T;
    }

    impl<T: ?Sized> NonNull<T> {
        pub const unsafe fn byte_offset(self, count: isize) -> Self;
        pub const unsafe fn byte_add(self, count: usize) -> Self;
        pub const unsafe fn byte_sub(self, count: usize) -> Self;
        pub const unsafe fn byte_offset_from<U: ?Sized>(self, origin: NonNull<U>) -> isize;
        pub unsafe fn drop_in_place(self);
    }

Stabilize the following without const:

    impl <T> NonNull<T> {
        // const under `const_intrinsic_copy`
        pub const unsafe fn copy_to(self, dest: NonNull<T>, count: usize);
        pub const unsafe fn copy_to_nonoverlapping(self, dest: NonNull<T>, count: usize);
        pub const unsafe fn copy_from(self, src: NonNull<T>, count: usize);
        pub const unsafe fn copy_from_nonoverlapping(self, src: NonNull<T>, count: usize);

        // const under `const_ptr_write`
        pub const unsafe fn write(self, val: T);
        pub const unsafe fn write_bytes(self, val: u8, count: usize);
        pub const unsafe fn write_unaligned(self, val: T);

        // const under `const_swap`
        pub const unsafe fn swap(self, with: NonNull<T>);

        // const under `const_align_offset`
        pub const fn align_offset(self, align: usize) -> usize;

        // const under `const_pointer_is_aligned`
        pub const fn is_aligned(self) -> bool;
    }

Left the following unstable:

    impl <T> NonNull<T> {
        // moved gate to `ptr_sub_ptr`
        pub const unsafe fn sub_ptr(self, subtracted: NonNull<T>) -> usize;
    }

    impl <T: ?Sized> NonNull<T> {
        // moved gate to `pointer_is_aligned_to`
        pub const fn is_aligned_to(self, align: usize) -> bool;
    }

Fixes: https://github.com/rust-lang/rust/issues/117691
2024-04-28 16:19:53 -05:00
Mads Marquart
214d588a5b Fix va_list on watchOS and visionOS 2024-04-28 21:30:40 +02:00
George Bateman
ca79086c87
Fix #124478 - offset_of! returns a temporary
This was due to the must_use() call. Adding HIR's OffsetOf to the must_use
checking within the compiler avoids this issue.
2024-04-28 18:36:08 +01:00
bors
cb49406457 Auto merge of #124210 - the8472:consign-ebadf-to-the-fire, r=Mark-Simulacrum
Abort a process when FD ownership is violated

When an owned FD has already been closed before it's dropped that means something else touched an FD in ways it is not allowed to. At that point things can already be arbitrarily bad, e.g. clobbered mmaps. Recovery is not possible.
All we can do is hasten the fire.

Unlike the previous attempt in #124130 this shouldn't suffer from the possibility that FUSE filesystems can return arbitrary errors.
2024-04-28 06:20:28 +00:00
Waffle Maybe
b73bfd26e4
Apply suggestions from code review
Co-authored-by: Jubilee <46493976+workingjubilee@users.noreply.github.com>
2024-04-27 00:47:23 +02:00
Matthias Geier
30b676cc00 Add missing .into_iter() 2024-04-26 21:18:00 +02:00
Matthias Geier
4df1303cff Extend the example code and assert the result 2024-04-26 20:53:23 +02:00
Waffle Lapkin
23b67de151 Document never type fallback in !'s docs 2024-04-26 20:49:34 +02:00
Matthias Geier
22319bf6ba Add "safety" comment 2024-04-26 20:44:59 +02:00
bors
4d570eea02 Auto merge of #123909 - dtolnay:utf8chunks, r=joboet
Stabilize `Utf8Chunks`

Pending FCP in https://github.com/rust-lang/rust/issues/99543.

This PR includes the proposed modification in https://github.com/rust-lang/libs-team/issues/190 as agreed in https://github.com/rust-lang/rust/issues/99543#issuecomment-2050406568.
2024-04-26 17:41:24 +00:00
bors
5ff8fbb2d8 Auto merge of #124393 - scottmcm:do-the-macros-still-matter, r=joboet
Convert some iter macros to normal functions

With all the MIR optimization changes that have happened since these were written, let's see if they still actually matter.

\*perf comes back\*

Well, it looks like it's not longer relevant for instruction, cycle, nor wall-time perf.  Looks like a bunch of things are maybe 10kb bigger in debug, but some are also 50k *smaller* in debug.

So I think they should switch to being normal functions as the "greatly improves performance" justification for them being macros seems to no longer be true -- probably thanks to us always building `core` with `-Z inline-mir` so the difference is negligible.
2024-04-26 11:16:05 +00:00
Scott McMurray
cd47a0ed08 Convert some iter macros to normal functions
With all the MIR optimization changes that have happened since these were written, let's see if they still actually matter.
2024-04-25 22:16:02 -07:00
lcnr
ce70584753 remove trivial bounds 2024-04-25 17:31:00 +00:00
David Tolnay
61cf00464e
Stabilize Utf8Chunks 2024-04-24 15:27:47 -07:00
Matthias Krüger
177139032a
Rollup merge of #124322 - whosehang:master, r=Nilstrieb
chore: fix some typos in comments
2024-04-25 00:19:54 +02:00
bors
ef8b9dcf23 Auto merge of #124330 - fmease:rollup-a98y7jf, r=fmease
Rollup of 6 pull requests

Successful merges:

 - #123316 (Test `#[unix_sigpipe = "inherit"]` with both `SIG_DFL` and `SIG_IGN`)
 - #123794 (More DefineOpaqueTypes::Yes)
 - #123881 (Bump Fuchsia versions)
 - #124281 (fix weak memory bug in TLS on Windows)
 - #124282 (windows fill_utf16_buf: explain the expected return value)
 - #124308 (Add diagnostic item for `std::iter::Enumerate`)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-04-24 19:26:50 +00:00
Jacob Trueb
3ad0618076 Fix cannot usage in time.rs 2024-04-24 17:37:44 +00:00
Gary Guo
f8a1cad07c Add cfg_attr(bootstrap) to doc tests 2024-04-24 13:12:33 +01:00
Gary Guo
94c1920497 Stabilise inline_const 2024-04-24 13:12:25 +01:00
León Orell Valerian Liehr
eaeaeb92a5
Rollup merge of #124308 - CBSpeir:diagnostic-item-enumerate, r=compiler-errors
Add diagnostic item for `std::iter::Enumerate`

This adds a diagnostic item for `std::iter::Enumerate`.  The change will be used by the clippy `unused_enumerate_index` lint to move away from type paths to using diagnostic items.

see: https://github.com/rust-lang/rust-clippy/issues/5393
2024-04-24 14:00:58 +02:00
Oli Scherer
aef0f4024a Error on using yield without also using #[coroutine] on the closure
And suggest adding the `#[coroutine]` to the closure
2024-04-24 08:05:29 +00:00
whosehang
65d7c1d2d6 chore: fix some typos in comments
Signed-off-by: whosehang <whosehang@outlook.com>
2024-04-24 13:58:51 +08:00
Christopher B. Speir
bcc4469c2b Add diagnostic item for std::iter::Enumerate 2024-04-23 16:50:10 -05:00
bors
40dcd796d0 Auto merge of #124302 - matthiaskrgr:rollup-2aya8n8, r=matthiaskrgr
Rollup of 3 pull requests

Successful merges:

 - #124003 (Dellvmize some intrinsics (use `u32` instead of `Self` in some integer intrinsics))
 - #124169 (Don't fatal when calling `expect_one_of` when recovering arg in `parse_seq`)
 - #124286 (Subtree sync for rustc_codegen_cranelift)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-04-23 18:23:46 +00:00
Matthias Krüger
918304b190
Rollup merge of #124003 - WaffleLapkin:dellvmization, r=scottmcm,RalfJung,antoyo
Dellvmize some intrinsics (use `u32` instead of `Self` in some integer intrinsics)

This implements https://github.com/rust-lang/compiler-team/issues/693 minus what was implemented in #123226.

Note: I decided to _not_ change `shl`/... builder methods, as it just doesn't seem worth it.

r? ``@scottmcm``
2024-04-23 20:17:51 +02:00
León Orell Valerian Liehr
2d7d480054
Rollup merge of #123048 - RalfJung:layout, r=dtolnay
alloc::Layout: explicitly document size invariant on the type level

https://github.com/rust-lang/rust/pull/95295 added this to the constructor, but it seems worth documenting the type invariant at the type level.
2024-04-23 17:25:16 +02:00
Trevor Spiteri
3b2436c136 unroll first iter of checked_ilog loop to save one multiplication 2024-04-23 15:49:00 +02:00
Matthias Krüger
72e8fb4268
Rollup merge of #123050 - RalfJung:panic_str, r=m-ou-se
panic_str only exists for the migration to 2021 panic macros

The only caller is `expect_failed`, which is already a cold inline(never) function, so inlining into that function should be fine. (And indeed `panic_str` was `#[inline]` anyway.)

The existence of panic_str risks someone calling it when they should call `panic` instead, and I can't see a reason why this footgun should exist.

I also extended the comment in `panic` to explain why it needs a `'static` string -- I know I've wondered about this in the past and it took me quite a while to understand.
2024-04-23 12:10:25 +02:00
bors
aca749eefc Auto merge of #121801 - zetanumbers:async_drop_glue, r=oli-obk
Add simple async drop glue generation

This is a prototype of the async drop glue generation for some simple types. Async drop glue is intended to behave very similar to the regular drop glue except for being asynchronous. Currently it does not execute synchronous drops but only calls user implementations of `AsyncDrop::async_drop` associative function and awaits the returned future. It is not complete as it only recurses into arrays, slices, tuples, and structs and does not have same sensible restrictions as the old `Drop` trait implementation like having the same bounds as the type definition, while code assumes their existence (requires a future work).

This current design uses a workaround as it does not create any custom async destructor state machine types for ADTs, but instead uses types defined in the std library called future combinators (deferred_async_drop, chain, ready_unit).

Also I recommend reading my [explainer](https://zetanumbers.github.io/book/async-drop-design.html).

This is a part of the [MCP: Low level components for async drop](https://github.com/rust-lang/compiler-team/issues/727) work.

Feature completeness:

 - [x] `AsyncDrop` trait
 - [ ] `async_drop_in_place_raw`/async drop glue generation support for
   - [x] Trivially destructible types (integers, bools, floats, string slices, pointers, references, etc.)
   - [x] Arrays and slices (array pointer is unsized into slice pointer)
   - [x] ADTs (enums, structs, unions)
   - [x] tuple-like types (tuples, closures)
   - [ ] Dynamic types (`dyn Trait`, see explainer's [proposed design](https://github.com/zetanumbers/posts/blob/main/async-drop-design.md#async-drop-glue-for-dyn-trait))
   - [ ] coroutines (https://github.com/rust-lang/rust/pull/123948)
 - [x] Async drop glue includes sync drop glue code
 - [x] Cleanup branch generation for `async_drop_in_place_raw`
 - [ ] Union rejects non-trivially async destructible fields
 - [ ] `AsyncDrop` implementation requires same bounds as type definition
 - [ ] Skip trivially destructible fields (optimization)
 - [ ] New [`TyKind::AdtAsyncDestructor`](https://github.com/zetanumbers/posts/blob/main/async-drop-design.md#adt-async-destructor-types) and get rid of combinators
 - [ ] [Synchronously undroppable types](https://github.com/zetanumbers/posts/blob/main/async-drop-design.md#exclusively-async-drop)
 - [ ] Automatic async drop at the end of the scope in async context
2024-04-23 02:10:23 +00:00
Guillaume Gomez
6a326d889a
Rollup merge of #124230 - reitermarkus:generic-nonzero-stable, r=dtolnay
Stabilize generic `NonZero`.

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

r? `@dtolnay`
2024-04-22 20:26:00 +02:00
Guillaume Gomez
206e0df78d
Rollup merge of #115913 - FedericoStra:checked_ilog, r=the8472
checked_ilog: improve performance

Addresses #115874.

(This PR replicates the original #115875, which I accidentally closed by deleting my forked repository...)
2024-04-22 20:25:58 +02:00
The 8472
25babe9a79 export assert_unsafe_precondition macro for std-internal use 2024-04-22 19:02:37 +02:00
Markus Reiter
33e68aadc9
Stabilize generic NonZero. 2024-04-22 18:48:47 +02:00
Gurinder Singh
f31e4aef0b Add comma at one place in abs() documentation 2024-04-22 08:16:47 +05:30
Scott McMurray
1398fe7a5e Address more PR feedback 2024-04-21 11:08:38 -07:00
Scott McMurray
de64ff76f8 Use it in the library, and InstSimplify it away in the easy places 2024-04-21 11:08:37 -07:00
Scott McMurray
4f4442655e Add an intrinsic that lowers to AggregateKind::RawPtr 2024-04-21 11:08:37 -07:00
Guillaume Gomez
24b8c54f6d
Rollup merge of #124184 - gurry:124152-suggest-unsigned-abs-in-abs-doc, r=jhpratt
Suggest using `unsigned_abs` in `abs` documentation

Fixes #124152
2024-04-21 13:30:26 +02:00
bors
453ceafce3 Auto merge of #124208 - jieyouxu:rollup-gbgpu4u, r=jieyouxu
Rollup of 10 pull requests

Successful merges:

 - #123379 (Print note with closure signature on type mismatch)
 - #123967 (static_mut_refs: use raw pointers to remove the remaining FIXME)
 - #123976 (Use fake libc in core test)
 - #123986 (lint-docs: Add redirects for renamed lints.)
 - #124053 (coverage: Branch coverage tests for lazy boolean operators)
 - #124071 (Add llvm-bitcode-linker to build manifest)
 - #124103 (Improve std::fs::Metadata Debug representation)
 - #124132 (llvm RustWrapper: explain OpBundlesIndirect argument type)
 - #124191 (Give a name to each distinct manipulation of pretty-printer FixupContext)
 - #124196 (mir-opt tests: rename unit-test -> test-mir-pass)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-04-20 22:35:56 +00:00
许杰友 Jieyou Xu (Joe)
a73aabfa92
Rollup merge of #123976 - ChrisDenton:no-libc-in-std-doc-tests, r=Mark-Simulacrum
Use fake libc in core test

The war on libc continues.

Some platforms may not need to link to the libc crate (and it's possible some may not even have a libc), therefore we shouldn't require it for tests. This creates dummy `malloc` and `free` implementations for use in the pointer docs, but, keeps the public documentation looking the same as before.
2024-04-20 21:45:35 +01:00
bors
dbce3b43b6 Auto merge of #122013 - Swatinem:unicode-gen-fastpath, r=scottmcm
Add a lower bound check to `unicode-table-generator` output

This adds a dedicated check for the lower bound
(if it is outside of ASCII range) to the output of the `unicode-table-generator` tool.

This generalized the ASCII-only fast-path, but only for the `Grapheme_Extend` property for now, as that is the only one with a lower bound outside of ASCII.
2024-04-20 20:33:25 +00:00
Arpad Borsos
488598c183
Add a lower bound check to unicode-table-generator output
This adds a dedicated check for the lower bound
(if it is outside of ASCII range) to the output of the `unicode-table-generator` tool.

This generalized the ASCII-only fast-path, but only for the `Grapheme_Extend` property for now,
as that is the only one with a lower bound outside of ASCII.
2024-04-20 10:16:45 +02:00
Gurinder Singh
02ac46c0c2 Suggest using unsigned_abs in abs documentation 2024-04-20 10:18:47 +05:30
bors
9c7b1f4848 Auto merge of #124114 - scottmcm:better-checked, r=workingjubilee
Make `checked` ops emit *unchecked* LLVM operations where feasible

For things with easily pre-checked overflow conditions -- shifts and unsigned subtraction -- write the checked methods in such a way that we stop emitting wrapping versions of them.

For example, today <https://rust.godbolt.org/z/qM9YK8Txb> neither
```rust
a.checked_sub(b).unwrap()
```
nor
```rust
a.checked_sub(b).unwrap_unchecked()
```
actually optimizes to `sub nuw`.  After this PR they do.

cc #103299
2024-04-20 04:11:16 +00:00
Jubilee
3831cbb28f
Rollup merge of #123406 - krtab:fix_remainder_iterchunk, r=scottmcm
Force exhaustion in iter::ArrayChunks::into_remainder

Closes: #123333
2024-04-18 21:38:54 -07:00
Scott McMurray
986d9f104b Make checked ops emit *unchecked* LLVM operations where feasible
For things with easily pre-checked overflow conditions -- shifts and unsigned subtraction -- write then checked methods in such a way that we stop emitting wrapping versions of them.

For example, today <https://rust.godbolt.org/z/qM9YK8Txb> neither
```rust
a.checked_sub(b).unwrap()
```
nor
```rust
a.checked_sub(b).unwrap_unchecked()
```
actually optimizes to `sub nuw`.  After this PR they do.
2024-04-18 18:11:21 -07:00
bors
c5de414865 Auto merge of #123144 - dpaoliello:arm64eclib, r=GuillaumeGomez,ChrisDenton,wesleywiser
Add support for Arm64EC to the Standard Library

Adds the final pieces so that the standard library can be built for arm64ec-pc-windows-msvc (initially added in #119199)

* Bumps `windows-sys` to 0.56.0, which adds support for Arm64EC.
* Correctly set the `isEC` parameter for LLVM's `writeArchive` function.
* Add `#![feature(asm_experimental_arch)]` to library crates where Arm64EC inline assembly is used, as it is currently unstable.
2024-04-18 12:22:52 +00:00
ardi
9cc9ba5cae fix: make str::from_raw_parts_mut mut 2024-04-18 01:46:49 +02:00
Matthias Krüger
21deaed4a1
Rollup merge of #122201 - coolreader18:doc-clone_from, r=dtolnay
Document overrides of `clone_from()` in core/std

As mentioned in https://github.com/rust-lang/rust/pull/96979#discussion_r1379502413

Specifically, when an override doesn't just forward to an inner type, document the behavior and that it's preferred over simply assigning a clone of source. Also, change instances where the second parameter is "other" to "source".

I reused some of the wording over and over for similar impls, but I'm not sure that the wording is actually *good*. Would appreciate feedback about that.

Also, now some of these seem to provide pretty specific guarantees about behavior (e.g. will reuse the exact same allocation iff the len is the same), but I was basing it off of the docs for [`Box::clone_from`](https://doc.rust-lang.org/1.75.0/std/boxed/struct.Box.html#method.clone_from-1) - I'm not sure if providing those strong guarantees is actually good or not.
2024-04-17 18:01:37 +02:00
Noa
87db7c32a7
Address comments 2024-04-17 00:18:04 -05:00
Guillaume Gomez
183c706305
Rollup merge of #123859 - krtab:uneeded_clone, r=cuviper
Remove uneeded clones now that TrustedStep implies Copy

This is a follow up to 11fa1764ee (from #112083)
2024-04-16 21:41:25 +02:00
zetanumbers
24a24ec6ba Add simple async drop glue generation
Explainer: https://zetanumbers.github.io/book/async-drop-design.html

https://github.com/rust-lang/rust/pull/121801
2024-04-16 20:45:07 +03:00
Arthur Carcano
864eb7fa14 Remove uneeded clones now that TrustedStep implies Copy
This is a follow up to 11fa1764ee
2024-04-16 16:11:06 +02:00
Maybe Waffle
ceead1bda6 Change intrinsic types to use u32 instead of T to match stable reexports 2024-04-16 11:53:04 +00:00
Daniel Paoliello
32f5ca4be7 Add support for Arm64EC to the Standard Library 2024-04-15 16:05:16 -07:00
Chris Denton
89117f85e3
Use fake libc in core test 2024-04-15 17:50:49 +00:00
Benoît du Garreau
6ce268e10a Remove bound checks from BorrowedBuf and BorrowedCursor methods 2024-04-15 10:29:43 +02:00
Guillaume Gomez
32be7b7129
Rollup merge of #123915 - shenawy29:patch-1, r=Nilstrieb
improve documentation slightly regarding some pointer methods
2024-04-14 23:24:34 +02:00
bors
a8a88fe524 Auto merge of #122268 - ChrisDenton:no-libc, r=Mark-Simulacrum
Link MSVC default lib in core

## The Problem

On Windows MSVC, Rust invokes the linker directly. This means only the objects and libraries Rust explicitly passes to the linker are used. In short, this is equivalent to passing `-nodefaultlibs`, `-nostartfiles`, etc for gnu compilers.

To compensate for this [the libc crate links to the necessary libraries](a0f5b4b213/src/windows/mod.rs (L258-L261)). The libc crate is then linked from std, thus when you use std you get the defaults back.or integrate with C/C++.

However, this has a few problems:

- For `no_std`, users are left to manually pass the default lib to the linker
- Whereas `std` has the opposite problem, using [`/nodefaultlib`](https://learn.microsoft.com/en-us/cpp/build/reference/nodefaultlib-ignore-libraries?view=msvc-170) doesn't work as expected because Rust treats them as normal libs. This is a particular problem when you want to use e.g. the debug CRT libraries in their place or integrate with C/C++..

## The solution

This PR fixes this in two ways:

- moves linking the default lib into `core`
- passes the lib to the linker using [`/defaultlib`](https://learn.microsoft.com/en-us/cpp/build/reference/defaultlib-specify-default-library?view=msvc-170). This allows users to override it in the normal way (i.e. with [`/nodefaultlib`](https://learn.microsoft.com/en-us/cpp/build/reference/nodefaultlib-ignore-libraries?view=msvc-170)).

This is more or less equivalent to what the MSVC C compiler does. You can see what this looks like in my second commit, which I'll reproduce here for convenience:

```rust
// In library/core
#[cfg(all(windows, target_env = "msvc"))]
#[link(
    name = "/defaultlib:msvcrt",
    modifiers = "+verbatim",
    cfg(not(target_feature = "crt-static"))
)]
#[link(name = "/defaultlib:libcmt", modifiers = "+verbatim", cfg(target_feature = "crt-static"))]
extern "C" {}
```

## Alternatives

- Add the above to `unwind` and `std` but not `core`
- The status quo
- Some other kind of compiler magic maybe

This bares some discussion so I've t-libs nominated it.
2024-04-14 13:28:21 +00:00
Mohamed El-Shenawy
5b8864ab80
improve documentation slightly regarding some pointer methods 2024-04-14 09:56:33 +02:00
Chris Denton
87e1dd0dfd
Move msvc libs to core 2024-04-14 07:11:53 +00:00
Matthias Krüger
2bec57d4a9
Rollup merge of #123875 - Ghamza-Jd:master, r=joboet
Doc: replace x with y for hexa-decimal fmt

I found it a bit unintuitive to know which is variable and which is the format string in `format!("{x:x}")`, so I switched it to `y`.
2024-04-14 09:01:58 +02:00
bors
f3c6608861 Auto merge of #107462 - WaffleLapkin:from_iterator_for_tuple, r=dtolnay
Implement `FromIterator` for `(impl Default + Extend, impl Default + Extend)`

Similarly to how https://github.com/rust-lang/rust/pull/85835 implemented `Extend` for `(impl Extend, impl Extend)`:
```rust
impl<A, B, AE, BE> FromIterator<(AE, BE)> for (A, B)
where
    A: Default + Extend<AE>,
    B: Default + Extend<BE>,
{ ... }
```
2024-04-14 03:15:53 +00:00
bors
7ab5eb8fe7 Auto merge of #123819 - joboet:fmt_usize_marker, r=Mark-Simulacrum
Get rid of `USIZE_MARKER` in formatting infrastructure

An alternative to #123780.

The `USIZE_MARKER` function used to differentiate between placeholder and count arguments is never called anyway, so we can just replace the function-pointer-comparison hack with an `enum` and an `unreachable_unchecked`, hopefully without causing a regression.

CC `@RalfJung`
2024-04-14 00:03:53 +00:00
ultrabear
3fd8c6432d
doc note that f16 and f128 hardware support is limited 2024-04-13 04:15:10 -07:00
Jacob Pratt
0518ecc700
Rollup merge of #123868 - eduardosm:stabilize-slice_ptr_len, r=jhpratt
Stabilize (const_)slice_ptr_len and (const_)slice_ptr_is_empty_nonnull

Stabilized API:

```rust
impl<T> *mut [T] {
    pub const fn len(self) -> usize;
    pub const fn is_empty(self) -> bool;
}

impl<T> *const [T] {
    pub const fn len(self) -> usize;
    pub const fn is_empty(self) -> bool;
}

impl<T> NonNull<[T]> {
    pub const fn is_empty(self) -> bool;
}
```

FCP completed in tracking issue: https://github.com/rust-lang/rust/issues/71146
2024-04-13 00:18:46 -04:00
Hamza Jadid
fa21dd4a97
chore: replace x with y for hexa-decimal fmt 2024-04-13 02:16:20 +03:00
Eduardo Sánchez Muñoz
fb9e1f73b3 Stabilize (const_)slice_ptr_len and (const_)slice_ptr_is_empty_nonnull 2024-04-12 21:23:20 +02:00
Matthias Krüger
be3ea1dfb0
Rollup merge of #123833 - dpaoliello:stdarch, r=Amanieu
Update stdarch submodule

`asm_experimental_arch` is required in `core` as we're now using unstable inline assembly when building Arm64EC.

Brings in the fix for <https://github.com/rust-lang/stdarch/issues/1555> (cc `@tslnc04).`

r? `@Amanieu`
2024-04-12 17:41:34 +02:00
bors
bd71213cf0 Auto merge of #123846 - matthiaskrgr:rollup-85y28av, r=matthiaskrgr
Rollup of 3 pull requests

Successful merges:

 - #123796 (Remove unused cargo-platform dependency from tidy)
 - #123830 (Remove `From` impls for unstable types that break inference)
 - #123842 (fix typo in pin.rs)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-04-12 13:13:50 +00:00
Matthias Krüger
e256d5f2ee
Rollup merge of #123842 - ShockYoungCHN:master, r=scottmcm
fix typo in pin.rs

correct "implemts" to "implements".
2024-04-12 13:35:31 +02:00
Matthias Krüger
bcf24d6467
Rollup merge of #123830 - tgross35:f16-f128-from-inference-fix, r=Nilstrieb
Remove `From` impls for unstable types that break inference

Adding additional `From` implementations that fit `f32::from(<unaffixed float>)` broke inference. Remove these for now.

I added a test to make sure this doesn't quietly change in the future, even though the behavior is not technically guaranteed https://github.com/rust-lang/rust/issues/123824#issuecomment-2050628184

Fixes: <https://github.com/rust-lang/rust/issues/123824>
2024-04-12 13:35:30 +02:00
bors
7bdae134cb Auto merge of #123783 - tgross35:f16-f128-debug-impl, r=Amanieu
Add a `Debug` impl and some basic functions to `f16` and `f128`

`compiler_builtins` uses some convenience functions like `is_nan` and `is_sign_positive`. Add these, as well as a temporary implementation for `Debug` that prints the bit representation.
2024-04-12 11:11:50 +00:00
joboet
0f52cd0e71
core: get rid of USIZE_MARKER 2024-04-12 12:00:14 +02:00
Yuanzhuo Yang
41ac5d93d6
fix pin.rs typo
correct "implemts" to "implements"
2024-04-12 01:28:58 -05:00
Daniel Paoliello
8a6ec2eadd Update stdarch submodule 2024-04-11 16:26:02 -07:00
Trevor Gross
9bcc98818c Remove From impls for unstable types that break inference
Adding additional `From` implementations that fit `f32::from(<unaffixed
float>)` broke inference. Remove these for now.

Fixes: <https://github.com/rust-lang/rust/issues/123824>
2024-04-11 18:04:31 -04:00
bors
a07f3eb43a Auto merge of #123823 - matthiaskrgr:rollup-8zdtggx, r=matthiaskrgr
Rollup of 8 pull requests

Successful merges:

 - #122882 (Avoid a panic in `set_output_capture` in the default panic handler)
 - #123523 (Account for trait/impl difference when suggesting changing argument from ref to mut ref)
 - #123744 (Silence `unused_imports` for redundant imports)
 - #123784 (Replace `document.write` with `document.head.insertAdjacent`)
 - #123798 (Avoid invalid socket address in length calculation)
 - #123804 (Stop using `HirId` for fn-like parents since closures are not `OwnerNode`s)
 - #123806 (Panic on overflow in `BorrowedCursor::advance`)
 - #123820 (Add my former address to .mailmap)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-04-11 21:56:11 +00:00
Matthias Krüger
d8ae975c02
Rollup merge of #123806 - joboet:advanced_overflow, r=Amanieu
Panic on overflow in `BorrowedCursor::advance`

Passing `usize::MAX` to `advance` clearly isn't correct, but the current assertion fails to detect this when overflow checks are disabled. This isn't unsound, but should probably be fixed regardless.
2024-04-11 22:38:56 +02:00
Trevor Gross
5159ecd922 Add a Debug impl and some basic functions to f16 and f128
`compiler_builtins` uses some convenience functions like `is_nan` and
`is_sign_positive`. Add these, as well as a temporary implementation for
`Debug` that prints the bit representation.
2024-04-11 15:31:10 -04:00
joboet
91fe6f9343
core: panic on overflow in BorrowedCursor 2024-04-11 18:33:46 +02:00
Tobias Nießen
e1972c0061
Avoid invalid socket address in length calculation 2024-04-11 17:27:23 +02:00
Tomoki Nakagawa
68914f2095 Correct broken link in core::pin doc 2024-04-11 15:02:49 +09:00
León Orell Valerian Liehr
d7d5be0c40
Rollup merge of #123661 - tgross35:stabilize-cstr_count_bytes, r=dtolnay
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>.

FCP finished at https://github.com/rust-lang/rust/issues/114441#issuecomment-2016942573.

Fixes: <https://github.com/rust-lang/rust/issues/114441>
2024-04-11 01:56:25 +02:00
Trevor Gross
311ad55c32 Add primitive documentation for f16 and f128 2024-04-10 13:50:27 -04:00
Trevor Gross
143ecc3202 Add basic f16 and f128 modules
Create empty modules so `rustdoc` has someplace to link to for these
types.
2024-04-10 13:50:27 -04:00
Trevor Gross
454de78ea3 Add basic library support for f16 and f128
Implement basic operation traits that get lowered to intrinsics. This
includes codegen tests for implemented operations.
2024-04-10 13:50:27 -04:00
Trevor Gross
88bcc79f31 Revert "Put basic impls for f16 and f128 behind cfg(not(bootstrap))"
This reverts commit 049a917535.

The resolution to <https://github.com/rust-lang/rust/issues/123282> is
that the `f16`/`f128` regression in the beta compiler was fixable
without a revert, so the commit adding `#[cfg(not(bootstrap))]` is no
longer useful (added in
<https://github.com/rust-lang/rust/pull/123390>).

Revert this commit because not having these basic impls bootstrap-gated
simplifies everything else that uses them.
2024-04-10 13:50:27 -04: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
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
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
Oli Scherer
c340e67dec Add pattern types to parser 2024-04-08 11:57:17 +00: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
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
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
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
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
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
David Tolnay
262670a8f1
Hide async_gen_internals from standard library documentation 2024-04-05 18:54:38 -07:00
David Tolnay
ff88a9a332
Stabilize const Atomic*::into_inner 2024-04-05 16:04:07 -07: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
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
Nadrieril
1a83bea107 Impl DerefPure for more std types 2024-04-05 00:02:42 +02:00
Arthur Carcano
d9a8903886 force exhaustion in iter::ArrayChunks::into_remainder 2024-04-04 12:19:54 +02: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
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
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