Commit Graph

14433 Commits

Author SHA1 Message Date
Michael Goulet
b56279569b Require DerefPure for patterns 2024-03-25 19:39:45 -04:00
Jubilee
ac0a9c58e8
Rollup merge of #123042 - dpaoliello:prelude, r=Nilstrieb
Import the 2021 prelude in the core crate

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

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

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

Fixes #122912

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Successful merges:

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

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

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

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

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

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

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

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

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

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

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

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

Successful merges:

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

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

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

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

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

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

Greetings!

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

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

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

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

r? oli-obk

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

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

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

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

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

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

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

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

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

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

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

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

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

Ignoring whitespace diffs should make this easier to review.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Already a confusable on btree map/set.

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

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

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

The result was the following error:

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

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

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

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

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

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

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

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

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

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

### What are we stabilizing?

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

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

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

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

### How does this differ from the RFC?

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

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

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

### Implementation history:

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

Closes #52662

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Reason:

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

Successful merges:

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

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

Reason:

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

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

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

Implementation of #122451.

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

A trivial rebase of #95982

Should fix #39186 (from what I can tell)

Original description:

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

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

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

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

Documentation for [`HandleOrInvalid`] has this note:

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

Documentation for [`HandleOrNull`] has this note:

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

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

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

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

Successful merges:

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

Failed merges:

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

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

Fixes #122420

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

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

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

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

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

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

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

First try to fix #108277 without break anything.

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

TODO:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Tracking issue: #118168

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

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

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

Successful merges:

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

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

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

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

r? `@ChrisDenton`
2024-03-11 03:47:22 -04:00
Jacob Pratt
eb1ebbfc92
Rollup merge of #122298 - RalfJung:raw-vec-into-box, r=cuviper
RawVec::into_box: avoid unnecessary intermediate reference

Fixes the problem described [here](https://github.com/rust-lang/miri/issues/3341#issuecomment-1987207195).
2024-03-11 03:47:21 -04:00
Jacob Pratt
b3ac6fab3d
Rollup merge of #122002 - devnexen:thread_stack_netbsd_fix, r=workingjubilee,riastradh
std::threads: revisit stack address calculation on netbsd.

like older linux glibc versions, we need to get the guard size
 and increasing the stack's bottom address accordingly.
2024-03-11 03:47:20 -04:00
Jacob Pratt
05f22c3614
Rollup merge of #121840 - oli-obk:freeze, r=dtolnay
Expose the Freeze trait again (unstably) and forbid implementing it manually

non-emoji version of https://github.com/rust-lang/rust/pull/121501

cc #60715

This trait is useful for generic constants (associated consts of generic traits). See the test (`tests/ui/associated-consts/freeze.rs`) added in this PR for a usage example. The builtin `Freeze` trait is the only way to do it, users cannot work around this issue.

It's also a useful trait for building some very specific abstrations, as shown by the usage by the `zerocopy` crate: https://github.com/google/zerocopy/issues/941

cc ```@RalfJung```

T-lang signed off on reexposing this unstably: https://github.com/rust-lang/rust/pull/121501#issuecomment-1969827742
2024-03-11 03:47:19 -04:00
Jacob Pratt
1a989e0757
Rollup merge of #121633 - ChrisDenton:precise, r=Nilstrieb
Win10: Use `GetSystemTimePreciseAsFileTime` directly

On Windows 10 we can use `GetSystemTimePreciseAsFileTime` directly instead of lazy loading it (with a fallback).
2024-03-11 03:47:19 -04:00
Jacob Pratt
6c8c272ad4
Rollup merge of #121148 - clarfonthey:try-range, r=dtolnay
Add slice::try_range

This adds a fallible version of the unstable `slice::range` (tracking: #76393) which is highly requested in the tracking issue.

Hoping this can slide by without an ACP (since the feature is already being tracked), but let me know otherwise.
2024-03-11 03:47:18 -04:00
bors
6639672554 Auto merge of #117156 - jmillikin:os-unix-socket-ext, r=Amanieu,dtolnay
Convert `Unix{Datagram,Stream}::{set_}passcred()` to per-OS traits

These methods are the pre-stabilized API for obtaining peer credentials from an `AF_UNIX` socket, part of the `unix_socket_ancillary_data` feature.

Their current behavior is to get/set one of the `SO_PASSCRED` (Linux), `LOCAL_CREDS_PERSISTENT` (FreeBSD), or `LOCAL_CREDS` (NetBSD) socket options. On other targets the `{set_}passcred()` methods do not exist.

There are two problems with this approach:

1. Having public methods only exist for certain targets isn't permitted in a stable `std` API.

2. These options have generally similar purposes, but they are non-POSIX and their details can differ in subtle and surprising ways (such as whether they continue to be set after the next call to `recvmsg()`).

Splitting into OS-specific extension traits is the preferred solution to both problems.
2024-03-11 07:46:01 +00:00
John Kåre Alsaker
50760aa2b5 Optimize process_heap_alloc 2024-03-11 05:43:12 +01:00
bors
76ee6fc926 Auto merge of #122312 - matthiaskrgr:rollup-0p8y7gg, r=matthiaskrgr
Rollup of 9 pull requests

Successful merges:

 - #122275 (disable OOM test in Miri)
 - #122276 (io::Read trait: make it more clear when we are adressing implementations vs callers)
 - #122277 (BorrowedCursor docs clarification)
 - #122286 (use Instance::expect_resolve() instead of unwraping Instance::resolve())
 - #122290 (MIR printing: print the path of uneval'd const)
 - #122293 (diagnostics: Do not suggest using `#[unix_sigpipe]` without a value)
 - #122297 (bootstrap: document what the triples in 'Build' mean)
 - #122302 (docs: Correct ptr/ref verbiage in SliceIndex docs.)
 - #122304 (fix metadata for dyn-star in new solver)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-03-10 22:16:22 +00:00
Matthias Krüger
97f3b3383a
Rollup merge of #122302 - ratmice:issue122234, r=cuviper
docs: Correct ptr/ref verbiage in SliceIndex docs.

Fixes #122234
2024-03-10 22:16:45 +01:00
Matthias Krüger
ff09d32d83
Rollup merge of #122277 - RalfJung:BorrowedCursor, r=cuviper
BorrowedCursor docs clarification

If one reads the `BorrowedCursor` docs without having seen `BorrowedBuf` before, it is quite easy to assume that "unfilled" and "uninit" are synonyms.
2024-03-10 22:16:42 +01:00
Matthias Krüger
0c73b2db41
Rollup merge of #122276 - RalfJung:io-read, r=Nilstrieb
io::Read trait: make it more clear when we are adressing implementations vs callers

Inspired by [this](https://github.com/rust-lang/rust/issues/72186#issuecomment-1987076295) comment.

For some reason we only have that `buf` warning in `read` and `read_exact`, even though it affects a bunch of other functions of this trait as well. It doesn't seem worth copy-pasting the same text everywhere though so I did not change this.
2024-03-10 22:16:42 +01:00
Matthias Krüger
217d00494f
Rollup merge of #122275 - RalfJung:std-oom, r=workingjubilee
disable OOM test in Miri

Needed for https://github.com/rust-lang/miri-test-libstd
2024-03-10 22:16:42 +01:00
ltdk
15b71f491f Add CStr::bytes iterator 2024-03-10 17:04:04 -04:00
Jubilee Young
caae03c659 Update backtrace submodule to 0.3.70 2024-03-10 12:52:23 -07:00
matt rice
dd2cda731a docs: Correct ptr/ref verbiage in SliceIndex docs.
Fixes #122234
2024-03-10 11:50:05 -07:00
Ralf Jung
81ebaf27cb RawVec::into_box: avoid unnecessary intermediate reference 2024-03-10 18:07:34 +01:00
Markus Reiter
85dfb479df
Fix lint. 2024-03-10 13:18:07 +01:00
Markus Reiter
2d48a3a7bc
Move generic NonZero rustc_layout_scalar_valid_range_start attribute to inner type. 2024-03-10 13:18:07 +01:00
Matthias Krüger
9d03046a81
Rollup merge of #122271 - pitaj:diag_items-legacy_numeric_constants, r=Nilstrieb
Fix legacy numeric constant diag items

- missed syms for usize/isize
- missed diag items on unsigned integers

For rust-lang/rust-clippy#12312

r? ```@Nilstrieb```

Follow-up to #121272, #121361, #121667
This should be the last one 🤞 Sorry!
2024-03-10 10:58:20 +01:00
Matthias Krüger
4faf535a55
Rollup merge of #122244 - tvallotton:local_waker_leak_fix, r=Nilstrieb
fix: LocalWaker memory leak and some stability attributes

fixes #122180.
2024-03-10 10:58:18 +01:00
Matthias Krüger
f6d47dd1f1
Rollup merge of #121942 - devnexen:getrandom_for_dfbsd, r=joboet
std::rand: enable getrandom for dragonflybsd too.
2024-03-10 10:58:16 +01:00
Matthias Krüger
b81678e627
Rollup merge of #113525 - workingjubilee:handle-dynamic-minsigstksz, r=m-ou-se
Dynamically size sigaltstk in std

On modern Linux with Intel AMX and 1KiB matrices,
Arm SVE with potentially 2KiB vectors,
and RISCV Vectors with up to 16KiB vectors,
we must handle dynamic signal stack sizes.

We can do so unconditionally by using getauxval,
but assuming it may return 0 as an answer,
thus falling back to the old constant if needed.

Fixes https://github.com/rust-lang/rust/issues/107795
2024-03-10 10:58:14 +01:00
Matthias Krüger
1b44889ec2
Rollup merge of #112136 - clarfonthey:ffi-c_str, r=cuviper
Add std::ffi::c_str module

ACP: rust-lang/libs-team#134

`std::ffi` docs before change:
![Structs: VaList, VaListImpl, CStr, CString, FromBytesWithNulError, FromVecWithNulError, IntoStringError, NulError, OsStr, OsString](https://github.com/rust-lang/rust/assets/15850505/b2cf3534-30f9-4ef0-a655-bacdc3a19e17)

`std::ffi` docs after change:
![Re-exports: self::c_str::{FromBytesWithNulError, FromBytesUntilNulError, FromVecWithNulError, NulError, IntoStringError} ; Modules: c_str ; Structs: VaList, VaListImpl, CStr, CString, OsStr, OsString](https://github.com/rust-lang/rust/assets/15850505/23aa6964-da7a-4942-bbf7-42bde2146f9e)

(note: I'm omitting the `c_int`, etc. stuff from the screenshots since it's the same in both. this doesn't just delete those types)
2024-03-10 10:58:14 +01:00
Ralf Jung
c06f801ef6 BorrowedCursor docs clarification 2024-03-10 09:48:56 +01:00
Ralf Jung
93049bece0 io::Read trait: make it more clear when we are adressing implementations vs callers 2024-03-10 09:39:45 +01:00
Ralf Jung
1dd47e0a17 disable OOM test in Miri 2024-03-10 09:24:25 +01:00
Peter Jaszkowiak
83590ac069 fix legacy numeric constant diag items
- missed syms for usize/isize
- missed diag items on unsigned integers
2024-03-09 23:33:27 -07:00
bors
768408af12 Auto merge of #121662 - saethlin:precondition-unification, r=RalfJung
Distinguish between library and lang UB in assert_unsafe_precondition

As described in https://github.com/rust-lang/rust/pull/121583#issuecomment-1963168186, `assert_unsafe_precondition` now explicitly distinguishes between language UB (conditions we explicitly optimize on) and library UB (things we document you shouldn't do, and maybe some library internals assume you don't do).

`debug_assert_nounwind` was originally added to avoid the "only at runtime" aspect of `assert_unsafe_precondition`. Since then the difference between the macros has gotten muddied. This totally revamps the situation.

Now _all_ preconditions shall be checked with `assert_unsafe_precondition`. If you have a precondition that's only checkable at runtime, do a `const_eval_select` hack, as done in this PR.

r? RalfJung
2024-03-10 01:23:54 +00:00
Guillaume Boisseau
13ca978f91
Rollup merge of #121711 - ChrisDenton:junction, r=Mark-Simulacrum
Implement junction_point

Implements https://github.com/rust-lang/rust/issues/121709

We already had a private implementation that we use for tests so we could just make that public. Except it was very hacky as it was only ever intended for use in testing. I've made an improved version that at least handles path conversion correctly and has less need for things like the `Align8` hack. There's still room for further improvement though.
2024-03-09 21:40:09 +01:00
Guillaume Boisseau
9ccf798fff
Rollup merge of #121403 - kornelski:io-oom, r=dtolnay
impl From<TryReserveError> for io::Error

There's an obvious mapping between these two errors, and it makes I/O code less noisy.

I've chosen to use simple `ErrorKind::OutOfMemory` `io::Error`, without keeping `TryReserveError` for the `source()`, because:

* It matches current uses in libstd,
* `ErrorData::Custom` allocates, which is a risky proposition for handling OOM errors specifically.
* Currently `TryReserveError` has no public fields/methods, so it's usefulness is limited. How allocators should report errors, especially custom and verbose ones is still an open question.

Just in case I've added note in the doccomment that this may change.

The compiler forced me to declare stability of this impl. I think this implementation is simple enough that it doesn't need full-blown stabilization period, and I've marked it for the next release, but of course I can adjust the attribute if needed.
2024-03-09 21:40:07 +01:00
Guillaume Boisseau
cbd59d0f62
Rollup merge of #121280 - ajwock:maybeuninit_fill, r=Amanieu
Implement MaybeUninit::fill{,_with,_from}

ACP: rust-lang/libs-team#156
2024-03-09 21:40:07 +01:00
Guillaume Boisseau
e3c0158788
Rollup merge of #120504 - kornelski:try_with_capacity, r=Amanieu
Vec::try_with_capacity

Related to #91913

Implements try_with_capacity for `Vec`, `VecDeque`, and `String`. I can follow it up with more collections if desired.

`Vec::try_with_capacity()` is functionally equivalent to the current stable:

```rust
let mut v = Vec::new();
v.try_reserve_exact(n)?
```

However, `try_reserve` calls non-inlined `finish_grow`, which requires old and new `Layout`, and is designed to reallocate memory. There is benefit to using `try_with_capacity`, besides syntax convenience, because it generates much smaller code at the call site with a direct call to the allocator. There's codegen test included.

It's also a very desirable functionality for users of `no_global_oom_handling` (Rust-for-Linux), since it makes a very commonly used function available in that environment (`with_capacity` is used much more frequently than all `(try_)reserve(_exact)`).
2024-03-09 21:40:06 +01:00
Guillaume Boisseau
5b6d30a4a9
Rollup merge of #114655 - nbdd0121:io-safety, r=dtolnay
Make `impl<Fd: AsFd>` impl take `?Sized`

`@rustbot` labels: +T-libs-api +needs-fcp
2024-03-09 21:40:06 +01:00
Guillaume Boisseau
0a8ea93dd8
Rollup merge of #99153 - Dajamante:issue/95622, r=dtolnay
Add Read Impl for &Stdin

r? `@oli-obk`
fixes #95622
2024-03-09 21:40:05 +01:00
Ben Kimock
2a1f97f77f Explain why we don't use intrinsics::is_nonoverlapping 2024-03-09 13:36:36 -05:00
Tomás Vallotton
092a1ab001 fix: remove memory leak due to missing drop implementation for local waker. Also, fix some
of the stability attributes of LocalWaker's methods.
2024-03-09 14:38:58 -03:00
Ben Kimock
af49c4df0a NonZero::from_mut_unchecked is library UB 2024-03-09 12:27:11 -05:00
dylni
a82587c1d4 Avoid closing invalid handles 2024-03-09 11:42:56 -05:00
Ben Kimock
50d0bea153 Improve docs 2024-03-09 10:49:26 -05:00
Matthias Krüger
b14e8054af
Rollup merge of #122233 - RalfJung:custom-alloc-box, r=oli-obk
miri: do not apply aliasing restrictions to Box with custom allocator

This is the Miri side of https://github.com/rust-lang/rust/pull/122018. The "intrinsics with body" made this much more pleasant. :)

Fixes https://github.com/rust-lang/miri/issues/3341.
r? `@oli-obk`
2024-03-09 16:21:20 +01:00
Matthias Krüger
2bb4b9901f
Rollup merge of #122232 - RalfJung:misc, r=jhpratt
library/core: fix a comment, and a cfg(miri) warning

Just two things I noticed while working on another PR.
2024-03-09 16:21:20 +01:00
Matthias Krüger
a1f6191e0e
Rollup merge of #121358 - GnomedDev:lower-align-typeid, r=Mark-Simulacrum
Reduce alignment of TypeId to u64 alignment

Closes #115620
2024-03-09 16:21:14 +01:00
Ralf Jung
e632e3f9a5 miri: do not apply aliasing restrictions to Box with custom allocator 2024-03-09 13:08:55 +01:00
Ralf Jung
1082c36a4c fn is_align_to: move some comments closer to the cast they refer to 2024-03-09 11:54:27 +01:00
Ralf Jung
6aff1ca68c fix warning when building libcore for Miri 2024-03-09 11:11:10 +01:00
bors
48a15aa2c4 Auto merge of #122095 - lukas-code:windows-shutdown-test, r=ChrisDenton
fix `close_read_wakes_up` test

On windows, `shutdown` does not interrupt `read`, even though we document that it does (see https://github.com/rust-lang/rust/issues/121594).

The `close_read_wakes_up` test has a race condition and only passes on windows if the `shutdown` happens before the `read`. This PR ignores the test on windows adds a sleep to make it more likely that the `read` happens before the `shutdown` and the test actually tests what it is supposed to test on other platforms.

I'm submitting this before any docs changes, so that we can find out on what platforms `shutdown` actually works as documented.

r? `@ChrisDenton`
2024-03-09 06:23:18 +00:00
Ben Kimock
5a93a59fd5 Distinguish between library and lang UB in assert_unsafe_precondition 2024-03-08 18:53:58 -05:00
David Carlier
ffdd97f791 further changes from feedback 2024-03-08 22:39:20 +00:00
Michael Goulet
c63f3feb0f Stabilize associated type bounds 2024-03-08 20:56:25 +00:00
Matthias Krüger
948d32d94f
Rollup merge of #121201 - RalfJung:align_offset_contract, r=cuviper
align_offset, align_to: no longer allow implementations to spuriously fail to align

For a long time, we have allowed `align_offset` to fail to compute a properly aligned offset, and `align_to` to return a smaller-than-maximal "middle slice". This was done to cover the implementation of `align_offset` in const-eval and Miri. See https://github.com/rust-lang/rust/issues/62420 for more background. For about the same amount of time, this has caused confusion and surprise, where people didn't realize they have to write their code to be defensive against `align_offset` failures.

Another way to put this is: the specification is effectively non-deterministic, and non-determinism is hard to test for -- in particular if the implementation everyone uses to test always produces the same reliable result, and nobody expects it to be non-deterministic to begin with.

With https://github.com/rust-lang/rust/pull/117840, Miri has stopped making use of this liberty in the spec; it now always behaves like rustc. That only leaves const-eval as potential motivation for this behavior. I do not think this is sufficient motivation. Currently, none of the relevant functions are stably const: `align_offset` is unstably const, `align_to` is not const at all. I propose that if we ever want to make these const-stable, we just accept the fact that they can behave differently at compile-time vs at run-time. This is not the end of the world, and it seems to be much less surprising to programmers than unexpected non-determinism. (Related: https://github.com/rust-lang/rfcs/pull/3352.)

`@thomcc` has repeatedly made it clear that they strongly dislike the non-determinism in align_offset, so I expect they will support this. `@oli-obk,` what do you think? Also, whom else should we involve? The primary team responsible is clearly libs-api, so I will nominate this for them. However, allowing const-evaluated code to behave different from run-time code is t-lang territory. The thing is, this is not stabilizing anything t-lang-worthy immediately, but it still does make a decision we will be bound to: if we accept this change, then
- either `align_offset`/`align_to` can never be called in const fn,
- or we allow compile-time behavior to differ from run-time behavior.

So I will nominate for t-lang as well, with the question being: are you okay with accepting either of these outcomes (without committing to which one, just accepting that it has to be one of them)? This closes the door to "have `align_offset` and `align_to` at compile-time and also always have compile-time behavior match run-time behavior".

Closes https://github.com/rust-lang/rust/issues/62420
2024-03-08 21:01:59 +01:00
Ralf Jung
507583a40c align_offset, align_to: no longer allow implementations to spuriously fail to align 2024-03-08 18:28:38 +01:00
Matthias Krüger
d16c55d6f6
Rollup merge of #122099 - Urgau:btreemap-inline-new, r=Amanieu
Add  `#[inline]` to `BTreeMap::new` constructor

This PR add the `#[inline]` attribute to `BTreeMap::new` constructor as to make it eligible for inlining.

<details>

For some context: I was profiling `rustc --check-cfg` with callgrind and due to the way we currently setup all the targets and we end-up calling `BTreeMap::new` multiple times for (nearly) all the targets. Adding the `#[inline]` attribute reduced the number of instructions needed.

</details>
2024-03-08 08:19:19 +01:00
Matthias Krüger
f586a79384
Rollup merge of #121938 - blyxxyz:quadratic-vectored-write, r=Amanieu
Fix quadratic behavior of repeated vectored writes

Some implementations of `Write::write_vectored` in the standard library (`BufWriter`, `LineWriter`, `Stdout`, `Stderr`) check all buffers to calculate the total length. This is O(n) over the number of buffers.

It's common that only a limited number of buffers is written at a time (e.g. 1024 for `writev(2)`). `write_vectored_all` will then call `write_vectored` repeatedly, leading to a runtime of O(n²) over the number of buffers.

This fix is to only calculate as much as needed if it's needed.

Here's a test program:
```rust
#![feature(write_all_vectored)]

use std::fs::File;
use std::io::{BufWriter, IoSlice, Write};
use std::time::Instant;

fn main() {
    let buf = vec![b'\0'; 100_000_000];
    let mut slices: Vec<IoSlice<'_>> = buf.chunks(100).map(IoSlice::new).collect();
    let mut writer = BufWriter::new(File::create("/dev/null").unwrap());

    let start = Instant::now();
    write_smart(&slices, &mut writer);
    println!("write_smart(): {:?}", start.elapsed());

    let start = Instant::now();
    writer.write_all_vectored(&mut slices).unwrap();
    println!("write_all_vectored(): {:?}", start.elapsed());
}

fn write_smart(mut slices: &[IoSlice<'_>], writer: &mut impl Write) {
    while !slices.is_empty() {
        // Only try to write as many slices as can be written
        let res = writer
            .write_vectored(slices.get(..1024).unwrap_or(slices))
            .unwrap();
        slices = &slices[(res / 100)..];
    }
}
```
Before this change:
```
write_smart(): 6.666952ms
write_all_vectored(): 498.437092ms
```
After this change:
```
write_smart(): 6.377158ms
write_all_vectored(): 6.923412ms
```

`LineWriter` (and by extension `Stdout`) isn't fully repaired by this because it looks for newlines. I could open an issue for that after this is merged, I think it's fixable but not trivially.
2024-03-08 08:19:19 +01:00
Matthias Krüger
b1aca86011
Rollup merge of #120608 - kornelski:slice-ptr-doc, r=cuviper
Docs for std::ptr::slice_from_raw_parts
2024-03-08 08:19:18 +01:00
Matthias Krüger
876847bed8
Rollup merge of #118623 - haydonryan:master, r=workingjubilee
Improve std::fs::read_to_string example

Resolves  [#118621](https://github.com/rust-lang/rust/issues/118621)

For the original code to succeed it requires address.txt to contain a socketaddress, however it is much easier to follow if this is just any strong - eg address could be a street address or just text.

Also changed the variable name from "foo" to something more meaningful as cargo clippy warns you against using foo as a placeholder.

```
$ cat main.rs
use std::fs;
use std::error::Error;

fn main() -> Result<(), Box<dyn Error>> {
    let addr: String = fs::read_to_string("address.txt")?.parse()?;
    println!("{}", addr);
    Ok(())
}

$ cat address.txt
123 rusty lane
san francisco 94999

$ cargo run
    Finished dev [unoptimized + debuginfo] target(s) in 0.00s
     Running `/home/haydon/workspace/rust-test-pr/tester/target/debug/tester`
123 rusty lane
san francisco 94999

```
2024-03-08 08:19:16 +01:00
bors
9fb91aa2e7 Auto merge of #122059 - nyurik:with-as-const-str, r=cuviper
Optimize write with as_const_str for shorter code

Following up on #121001

Apparently this code generates significant code block for each call to `write()` with non-simple formatting string - approx 100 lines of assembly code, possibly due to `dyn` (?).  See generated assembly code [here](https://github.com/nyurik/rust-optimize-format-str/compare/before-changes..with-my-change#diff-6b404e954c692d8cdc8c452d819a216aa5dcf40522b5944639e9ad947279a477):

<details><summary>Details</summary>
<p>

This is the inlining of `write!(buffer, "Iteration {value} was written")`

```asm
core::fmt::Write::write_fmt:
		// /home/nyurik/dev/rust/rust/library/core/src/fmt/mod.rs : 194
		fn write_fmt(&mut self, args: Arguments<'_>) -> Result {
	push r15
	push r14
	push r13
	push r12
	push rbx
	mov rdx, rsi
		// /home/nyurik/dev/rust/rust/library/core/src/fmt/mod.rs : 427
		match (self.pieces, self.args) {
	mov rcx, qword ptr [rsi + 8]
	mov rax, qword ptr [rsi + 24]
		// /home/nyurik/dev/rust/rust/library/core/src/fmt/mod.rs : 428
		([], []) => Some(""),
	cmp rcx, 1
	je .LBB0_8
	test rcx, rcx
	jne .LBB0_9
	test rax, rax
	jne .LBB0_9
		// /home/nyurik/dev/rust/rust/library/alloc/src/vec/mod.rs : 911
		self.buf.reserve(self.len, additional);
	lea r12, [rdi + 16]
	lea rsi, [rip + .L__unnamed_2]
	xor ebx, ebx
.LBB0_6:
	mov r14, qword ptr [r12]
	jmp .LBB0_7
.LBB0_8:
		// /home/nyurik/dev/rust/rust/library/core/src/fmt/mod.rs : 429
		([s], []) => Some(s),
	test rax, rax
	je .LBB0_4
.LBB0_9:
		// /home/nyurik/dev/rust/rust/library/core/src/fmt/mod.rs : 1108
		if let Some(s) = args.as_str() { output.write_str(s) } else { write_internal(output, args) }
	lea rsi, [rip + .L__unnamed_1]
	pop rbx
	pop r12
	pop r13
	pop r14
	pop r15
	jmp qword ptr [rip + core::fmt::write_internal@GOTPCREL]
.LBB0_4:
	mov rax, qword ptr [rdx]
		// /home/nyurik/dev/rust/rust/library/core/src/fmt/mod.rs : 429
		([s], []) => Some(s),
	mov rsi, qword ptr [rax]
	mov rbx, qword ptr [rax + 8]
		// /home/nyurik/dev/rust/rust/library/alloc/src/raw_vec.rs : 248
		if T::IS_ZST { usize::MAX } else { self.cap.0 }
	mov rax, qword ptr [rdi]
		// /home/nyurik/dev/rust/rust/library/alloc/src/vec/mod.rs : 911
		self.buf.reserve(self.len, additional);
	mov r14, qword ptr [rdi + 16]
		// /home/nyurik/dev/rust/rust/library/core/src/num/mod.rs : 1281
		uint_impl! {
	sub rax, r14
		// /home/nyurik/dev/rust/rust/library/alloc/src/raw_vec.rs : 392
		additional > self.capacity().wrapping_sub(len)
	cmp rax, rbx
		// /home/nyurik/dev/rust/rust/library/alloc/src/raw_vec.rs : 309
		if self.needs_to_grow(len, additional) {
	jb .LBB0_5
.LBB0_7:
	mov rax, qword ptr [rdi + 8]
		// /home/nyurik/dev/rust/rust/library/core/src/ptr/mut_ptr.rs : 1046
		unsafe { intrinsics::offset(self, count) }
	add rax, r14
	mov r15, rdi
		// /home/nyurik/dev/rust/rust/library/core/src/intrinsics.rs : 2922
		copy_nonoverlapping(src, dst, count)
	mov rdi, rax
	mov rdx, rbx
	call qword ptr [rip + memcpy@GOTPCREL]
		// /home/nyurik/dev/rust/rust/library/alloc/src/vec/mod.rs : 2040
		self.len += count;
	add r14, rbx
	mov qword ptr [r15 + 16], r14
		// /home/nyurik/dev/rust/rust/library/core/src/fmt/mod.rs : 216
		}
	xor eax, eax
	pop rbx
	pop r12
	pop r13
	pop r14
	pop r15
	ret
.LBB0_5:
		// /home/nyurik/dev/rust/rust/library/alloc/src/vec/mod.rs : 911
		self.buf.reserve(self.len, additional);
	lea r12, [rdi + 16]
	mov r15, rdi
	mov r13, rsi
		// /home/nyurik/dev/rust/rust/library/alloc/src/raw_vec.rs : 310
		do_reserve_and_handle(self, len, additional);
	mov rsi, r14
	mov rdx, rbx
	call alloc::raw_vec::RawVec<T,A>::reserve::do_reserve_and_handle
	mov rsi, r13
	mov rdi, r15
	jmp .LBB0_6
```

</p>
</details>

```rust
#[inline]
pub fn write(output: &mut dyn Write, args: Arguments<'_>) -> Result {
    if let Some(s) = args.as_str() { output.write_str(s) } else { write_internal(output, args) }
}
```

So, this brings back the older experiment - where I used `if core::intrinsics::is_val_statically_known(s.is_some()) { s } else { None }` helper function, and called it in multiple places that used `write`.  This is not as optimal because now every user of `write` must do this logic, but at least it results in significantly smaller assembly code for the formatting case, and results in identical code as now for the "simple" (no formatting) case. See [assembly comparison](https://github.com/nyurik/rust-optimize-format-str/compare/with-my-change..with-as-const-str#diff-6b404e954c692d8cdc8c452d819a216aa5dcf40522b5944639e9ad947279a477) of what is now with what this change brings (focus only on `fmt/intel-lib.txt` and `str/intel-lib.txt` files).

```rust
               if let Some(s) = args.as_const_str() {
                    self.write_str(s)
                } else {
                    write(self, args)
                }
```
2024-03-08 04:15:17 +00:00
Guillaume Gomez
92d7e02bb2
Rollup merge of #122147 - kadiwa4:private_impl_mods, r=workingjubilee
Make `std::os::unix::ucred` module private

Tracking issue: #42839

Currently, this unstable module exists: [`std::os::unix::ucred`](https://doc.rust-lang.org/stable/std/os/unix/ucred/index.html).
All it does is provide `UCred` (which is also available from `std::os::unix::net`), `impl_*` (which is probably a mishap and should be private) and `peer_cred` (which is undocumented but has a documented counterpart at `std::os::unix::net::UnixStream::peer_cred`).

This PR makes the entire `ucred` module private and moves it into `net`, because that's where it is used.

I hope it's fine to simply remove it without a deprecation phase. Otherwise, I can add back a deprecated reexport module `std::os::unix::ucred`.

`@rustbot` label: -T-libs +T-libs-api
2024-03-07 18:32:51 +01:00
Guillaume Gomez
b0d7f2bb0e
Rollup merge of #119888 - weiznich:stablize_diagnostic_namespace, r=compiler-errors
Stabilize the `#[diagnostic]` namespace and `#[diagnostic::on_unimplemented]` attribute

This PR stabilizes the `#[diagnostic]` attribute namespace and a minimal option of the `#[diagnostic::on_unimplemented]` attribute.

The `#[diagnostic]` attribute namespace is meant to provide a home for attributes that allow users to influence error messages emitted by the compiler. The compiler is not guaranteed to use any of this hints, however it should accept any (non-)existing attribute in this namespace and potentially emit lint-warnings for unused attributes and options. This is meant to allow discarding certain attributes/options in the future to allow fundamental changes to the compiler without the need to keep then non-meaningful options working.

The `#[diagnostic::on_unimplemented]` attribute is allowed to appear on a trait definition. This allows crate authors to hint the compiler to emit a specific error message if a certain trait is not implemented. For the `#[diagnostic::on_unimplemented]` attribute the following options are implemented:

* `message` which provides the text for the top level error message
* `label` which provides the text for the label shown inline in the broken code in the error message
* `note` which provides additional notes.

The `note` option can appear several times, which results in several note messages being emitted. If any of the other options appears several times the first occurrence of the relevant option specifies the actually used value. Any other occurrence generates an lint warning. For any other non-existing option a lint-warning is generated.

All three options accept a text as argument. This text is allowed to contain format parameters referring to generic argument or `Self` by name via the `{Self}` or `{NameOfGenericArgument}` syntax. For any non-existing argument a lint warning is generated.

This allows to have a trait definition like:

```rust
#[diagnostic::on_unimplemented(
    message = "My Message for `ImportantTrait<{A}>` is not implemented for `{Self}`",
    label = "My Label",
    note = "Note 1",
    note = "Note 2"
)]
trait ImportantTrait<A> {}

```

which then generates for the following code

```rust
fn use_my_trait(_: impl ImportantTrait<i32>) {}

fn main() {
    use_my_trait(String::new());
}
```

this error message:

```
error[E0277]: My Message for `ImportantTrait<i32>` is not implemented for `String`
  --> src/main.rs:14:18
   |
14 |     use_my_trait(String::new());
   |     ------------ ^^^^^^^^^^^^^ My Label
   |     |
   |     required by a bound introduced by this call
   |
   = help: the trait `ImportantTrait<i32>` is not implemented for `String`
   = note: Note 1
   = note: Note 2
```

[Playground with the unstable feature](https://play.rust-lang.org/?version=nightly&mode=debug&edition=2021&gist=05133acce8e1d163d481e97631f17536)

Fixes #111996
2024-03-07 18:32:46 +01:00
Kalle Wachsmuth
5ce3db2248
make std::os::unix::ucred module private 2024-03-07 16:23:35 +01:00
Ralf Jung
1a2bc1102d Rust is a proper name: rust → Rust 2024-03-07 07:49:22 +01:00
bors
aa029ce4d8 Auto merge of #122113 - matthiaskrgr:rollup-5d1jnwi, r=matthiaskrgr
Rollup of 9 pull requests

Successful merges:

 - #121958 (Fix redundant import errors for preload extern crate)
 - #121976 (Add an option to have an external download/bootstrap cache)
 - #122022 (loongarch: add frecipe and relax target feature)
 - #122026 (Do not try to format removed files)
 - #122027 (Uplift some feeding out of `associated_type_for_impl_trait_in_impl` and into queries)
 - #122063 (Make the lowering of `thir::ExprKind::If` easier to follow)
 - #122074 (Add missing PartialOrd trait implementation doc for array)
 - #122082 (remove outdated fixme comment)
 - #122091 (Note why we're using a new thread in `test_get_os_named_thread`)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-03-07 02:30:40 +00:00
Matthias Krüger
7220e52f94
Rollup merge of #122088 - ChrisDenton:fixme, r=workingjubilee
Remove unnecessary fixme on new thread stack size

As the FIXME itself notes, there's nothing to fix here.

And as the documentation for [`CreateThread`] says of `dwStackSize`, the value is rounded up to the nearest page. A 4kb stack is very small but perfectly usable if you're careful. Of course it will be very limited but there's no reason to add artificial limits. We don't know what the user is doing.

[`CreateThread`]: https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-createthread
2024-03-07 00:57:41 +01:00
Matthias Krüger
f1354ed772
Rollup merge of #122072 - KonradHoeffner:patch-1, r=cuviper
Refer to "slice" instead of "vector" in Ord and PartialOrd trait impl of slices

The trait implementation comments of Ord and PartialOrd for slice incorrectly mention "vectors" instead of "slices".
This PR fixes those two comments as requested in #122071.
2024-03-07 00:57:41 +01:00
Matthias Krüger
3827584370
Rollup merge of #122091 - ChrisDenton:comment, r=RalfJung
Note why we're using a new thread in `test_get_os_named_thread`

``@RalfJung`` expressed some "surprise and confusion" about why we're spawning a new thread in this test. Hopefully this comment will help future readers.
2024-03-06 22:41:57 +01:00
Matthias Krüger
6279ef2b4e
Rollup merge of #122074 - KonradHoeffner:patch-2, r=jhpratt
Add missing PartialOrd trait implementation doc for array

Analogously to vectors and slices, this PR documents the lexicographic sorting of PartialOrd as rustdoc comment on the trait implementation of PartialOrd for arrays.
Associated issue: #122073.
2024-03-06 22:41:56 +01:00
Matthias Krüger
1b157a0987
Rollup merge of #113518 - jyn514:streaming-failures, r=cuviper
bootstrap/libtest: print test name eagerly on failure even with `verbose-tests=false` / `--quiet`

Previously, libtest would wait until all tests finished running to print the progress, which made it
annoying to run many tests at once (since you don't know which have failed). Change it to print the
names as soon as they fail.

This makes it much easier to know which test failed without having to wait for compiletest to completely finish running. Before:
```
Testing stage0 compiletest suite=ui mode=ui (x86_64-unknown-linux-gnu)

running 15274 tests
iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii    88/15274
iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii   176/15274
iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii   264/15274
iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii   352/15274
iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii   440/15274
iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii   528/15274
iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiFFiiiiiii
...
```

After:
```
Testing stage0 compiletest suite=ui mode=ui (x86_64-unknown-linux-gnu)

running 15274 tests
iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii    88/15274
iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii   176/15274
iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii   264/15274
iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii   352/15274
iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii   440/15274
iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii   528/15274
iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii
[ui] tests/ui/associated-type-bounds/implied-in-supertrait.rs ... F

[ui] tests/ui/associated-type-bounds/return-type-notation/basic.rs#next_with ... F
iiiiiiiiiiiii
...
```

This serves a similar use case to the existing RUSTC_TEST_FAIL_FAST, but is on by default and as a result much more discoverable. We should consider unifying RUSTC_TEST_FAIL_FAST with the `--no-fail-fast` flag in the future for consistency and discoverability.
2024-03-06 22:02:45 +01:00
Chris Denton
8718317725
Document and test minimal stack size on Windows 2024-03-06 19:54:09 +00:00