Because the neutral element of `<fNN as iter::Sum>` was changed to
`neg_zero`, the documentation needed to be updated, as it was reporting
inadequate information about what should be expected from the return.
Co-authored-by: Jubilee <workingjubilee@gmail.com>
Rename `slice::take...` methods to `split_off...`
This rename was discussed and recommended in a recent t-libs meeting.
cc https://github.com/rust-lang/rust/issues/62280
There's an additional commit here which modifies internals of unstable `OneSidedRange` APIs in order to implement `split_off` methods in a panic-free way (remove `unreachable!()`) as recommended in https://github.com/rust-lang/rust/pull/88502/files#r760177240. I can split this out into a separate PR if needed.
implement inherent str constructors
implement #131114
this implements
- str::from_utf8
- str::from_utf8_mut
- str::from_utf8_unchecked
- str::from_utf8_unchecked_mut
i left `std::str::from_raw_parts` and `std::str::from_raw_parts_mut` out of this as those are unstable and were not mentioned by the tracking issue or the original pull request, but i can add those here as well.
i was also unsure of what to do with the `rustc_const_(un)stable` attributes: i removed the `#[rustc_const_stable]` attribute from `str::from_utf8`, `str::from_utf8_unchecked` and `str::from_utf8_unchecked_mut`, and left the`#[rust_const_unstable]` in `str::from_utf8_mut` (btw why is that one not const stable yet with #57349 merged?).
is there a way to redirect users to the stable `std::str::from_utf8` instead of only saying "hey this is unstable"?
for now i just removed the check for `str::from_utf8` in the test in `tests/ui/suggestions/suggest-std-when-using-type.rs`.
Mark `std::fmt::from_fn` as `#[must_use]`
While working on #135494 I managed to shoot my own foot a few times by forgetting to actually use the result of `fmt::from_fn`, so I think a `#[must_use]` could be appropriate!
Didn't have a good message to put in the attr so left it blank, still unstable so we can come back to it I guess?
cc #117729 (and a huge +1 for getting it stabilized, it's very useful IMHO)
#[contracts::requires(...)] + #[contracts::ensures(...)]
cc https://github.com/rust-lang/rust/issues/128044
Updated contract support: attribute syntax for preconditions and postconditions, implemented via a series of desugarings that culminates in:
1. a compile-time flag (`-Z contract-checks`) that, similar to `-Z ub-checks`, attempts to ensure that the decision of enabling/disabling contract checks is delayed until the end user program is compiled,
2. invocations of lang-items that handle invoking the precondition, building a checker for the post-condition, and invoking that post-condition checker at the return sites for the function, and
3. intrinsics for the actual evaluation of pre- and post-condition predicates that third-party verification tools can intercept and reinterpret for their own purposes (e.g. creating shims of behavior that abstract away the function body and replace it solely with the pre- and post-conditions).
Known issues:
* My original intent, as described in the MCP (https://github.com/rust-lang/compiler-team/issues/759) was to have a rustc-prefixed attribute namespace (like rustc_contracts::requires). But I could not get things working when I tried to do rewriting via a rustc-prefixed builtin attribute-macro. So for now it is called `contracts::requires`.
* Our attribute macro machinery does not provide direct support for attribute arguments that are parsed like rust expressions. I spent some time trying to add that (e.g. something that would parse the attribute arguments as an AST while treating the remainder of the items as a token-tree), but its too big a lift for me to undertake. So instead I hacked in something approximating that goal, by semi-trivially desugaring the token-tree attribute contents into internal AST constucts. This may be too fragile for the long-term.
* (In particular, it *definitely* breaks when you try to add a contract to a function like this: `fn foo1(x: i32) -> S<{ 23 }> { ... }`, because its token-tree based search for where to inject the internal AST constructs cannot immediately see that the `{ 23 }` is within a generics list. I think we can live for this for the short-term, i.e. land the work, and continue working on it while in parallel adding a new attribute variant that takes a token-tree attribute alongside an AST annotation, which would completely resolve the issue here.)
* the *intent* of `-Z contract-checks` is that it behaves like `-Z ub-checks`, in that we do not prematurely commit to including or excluding the contract evaluation in upstream crates (most notably, `core` and `std`). But the current test suite does not actually *check* that this is the case. Ideally the test suite would be extended with a multi-crate test that explores the matrix of enabling/disabling contracts on both the upstream lib and final ("leaf") bin crates.
Rollup of 5 pull requests
Successful merges:
- #134777 (Enable more tests on Windows)
- #135621 (Move some std tests to integration tests)
- #135844 ( Add new tool for dumping feature status based on tidy )
- #136167 (Implement unstable `new_range` feature)
- #136334 (Extract `core::ffi` primitives to a separate (internal) module)
Failed merges:
- #136201 (Removed dependency on the field-offset crate, alternate approach)
r? `@ghost`
`@rustbot` modify labels: rollup
Add `cast_signed` and `cast_unsigned` methods for `NonZero` types
Requested in https://github.com/rust-lang/rust/issues/125882 .
Note that this keeps the same names as the methods currently present on other
integer types. If we want to rename them, we can rename them all at the same
time.
Extract `core::ffi` primitives to a separate (internal) module
### Introduce library/core/src/ffi/primitives.rs
The regex preprocessing for PR #133944 would be more robust if the relevant types from core/src/ffi/mod.rs were first moved to library/core/src/ffi/primitives.rs, then there isn't a need to deal with traits / c_str / va_list / whatever might wind up in that module in the future
r? `@tgross35`
Implement unstable `new_range` feature
Switches `a..b`, `a..`, and `a..=b` to resolve to the new range types.
For rust-lang/rfcs#3550
Tracking issue #123741
also adds the re-export that was missed in the original implementation of `new_range_api`
Display of integers without raw pointers and without overflowing_literals
The benchmarks as is measure formatting speed of literals. The first commit `black_box`-es input to simulate runtime speed instead.
The second commit replaces `unsafe` pointer optimizations with plain array indices. The performance is equivalent on Apple M1. Needs peer review on Intel.
Happy to do the 128-bit version too if such change is welcome.
This has now been approved as a language feature and no longer needs
a `rustc_` prefix.
Also change the `contracts` feature to be marked as incomplete and
`contracts_internals` as internal.
1. Document the new intrinsics.
2. Make the intrinsics actually check the contract if enabled, and
remove `contract::check_requires` function.
3. Use panic with no unwind in case contract is using to check for
safety, we probably don't want to unwind. Following the same
reasoning as UB checks.
The extended syntax for function signature that includes contract clauses
should never be user exposed versus the interface we want to ship
externally eventually.
includes post-developed commit: do not suggest internal-only keywords as corrections to parse failures.
includes post-developed commit: removed tabs that creeped in into rustfmt tool source code.
includes post-developed commit, placating rustfmt self dogfooding.
includes post-developed commit: add backquotes to prevent markdown checking from trying to treat an attr as a markdown hyperlink/
includes post-developed commit: fix lowering to keep contracts from being erroneously inherited by nested bodies (like closures).
Rebase Conflicts:
- compiler/rustc_parse/src/parser/diagnostics.rs
- compiler/rustc_parse/src/parser/item.rs
- compiler/rustc_span/src/hygiene.rs
Remove contracts keywords from diagnostic messages
There was a macro parameter giving signed impls access to the
corresponding unsigned type, but not the other way around.
This will allow implementing methods converting in both directions.
rustc_allowed_through_unstable_modules: require deprecation message
This changes the `#[rustc_allowed_through_unstable_modules]` attribute so that a deprecation message (ideally directing people towards the stable path) is required.
Implement all mix/max functions in a (hopefully) more optimization amendable way
Previously the graph was like this:
```
min -> Ord::min -> min_by -> match on compare() (in these cases compare = Ord::cmp)
^
|
min_by_key
```
now it looks like this:
```
min -> Ord::min -> `<=` <- min_by_key
min_by -> `Ordering::is_le` of `compare()`
```
(`max*` and `minmax*` are the exact same, i.e. they also use `<=` and `is_le`)
I'm not sure how to test this, but it should probably be easier for the backend to optimize.
r? `@scottmcm`
cc https://github.com/rust-lang/rust/issues/115939#issuecomment-2622161134
Insert null checks for pointer dereferences when debug assertions are enabled
Similar to how the alignment is already checked, this adds a check
for null pointer dereferences in debug mode. It is implemented similarly
to the alignment check as a `MirPass`.
This inserts checks in the same places as the `CheckAlignment` pass and additionally
also inserts checks for `Borrows`, so code like
```rust
let ptr: *const u32 = std::ptr::null();
let val: &u32 = unsafe { &*ptr };
```
will have a check inserted on dereference. This is done because null references
are UB. The alignment check doesn't cover these places, because in `&(*ptr).field`,
the exact requirement is that the final reference must be aligned. This is something to
consider further enhancements of the alignment check.
For now this is implemented as a separate `MirPass`, to make it easy to disable
this check if necessary.
This is related to a 2025H1 project goal for better UB checks in debug
mode: https://github.com/rust-lang/rust-project-goals/pull/177.
r? `@saethlin`
Similar to how the alignment is already checked, this adds a check
for null pointer dereferences in debug mode. It is implemented similarly
to the alignment check as a MirPass.
This is related to a 2025H1 project goal for better UB checks in debug
mode: https://github.com/rust-lang/rust-project-goals/pull/177.
float::min/max: mention the non-determinism around signed 0
Turns out this can actually produce different results on different machines [in practice](https://github.com/rust-lang/rust/issues/83984#issuecomment-2623859230); that seems worth documenting. I assume LLVM will happily const-fold these operations so so there could be different results for the same input even on the same machine, depending on whether things get const-folded or not.
`@nikic` I remember there was an LLVM soundness fix regarding scalar evolution for loops that had to recognize certain operations as non-deterministic... it seems to me that pass would also have to avoid predicting the result of `llvm.{min,max}num`, for the same reason?
r? `@tgross35`
Cc `@rust-lang/libs-api`
If this lands we should also make Miri non-deterministic here.
Fixes https://github.com/rust-lang/rust/issues/83984
Stabilize `const_black_box`
This has been unstably const since #92226, but a tracking issue was never created. Per [discussion on Zulip][zulip], there should not be any blockers to making this const-stable. The function does not provide any functionality at compile time but does allow code reuse between const- and non-const functions, so stabilize it here.
[zulip]: https://rust-lang.zulipchat.com/#narrow/channel/146212-t-compiler.2Fconst-eval/topic/const_black_box
Remove minor future footgun in `impl Debug for MaybeUninit`
No longer breaks if `MaybeUninit` moves modules (technically it could break if `MaybeUninit` were renamed but realistically that will never happen)
Debug impl originally added in #133282
Add `AsyncFn*` to `core` prelude
In https://github.com/rust-lang/rust/pull/132611 these got added to the `std` prelude only, which looks like an oversight.
r? libs-api
cc `@compiler-errors`
Implement `int_from_ascii` (#134821)
Provides unstable `T::from_ascii()` and `T::from_ascii_radix()` for integer types `T`, as drafted in tracking issue #134821.
To deduplicate documentation without additional macros, implementations of `isize` and `usize` no longer delegate to equivalent integer types. After #132870 they are inlined anyway.
Cleanup docs for Allocator
This is an attempt to remove ungrammatical constructions and clean up the prose. I've sometimes had to try hard to understand what was being stated, so it is possible that I've misunderstood the original meaning. In particular, I did not see a difference between:
- the borrow-checker lifetime of the allocator type itself.
- as long as at least one of the allocator instance and all of its clones has not been dropped.
optimize slice::ptr_rotate for small rotates
r? `@scottmcm`
This swaps the positions and numberings of algorithms 1 and 2 in `slice::ptr_rotate`, and pulls the entire outer loop into algorithm 3 since it was redundant for the first two. Effectively, `ptr_rotate` now always does the `memcpy`+`memmove`+`memcpy` sequence if the shifts fit into the stack buffer.
With this change, an `IndexMap`-style `move_index` function is optimized correctly.
Assembly comparisons:
- `move_index`, before: https://godbolt.org/z/Kr616KnYM
- `move_index`, after: https://godbolt.org/z/1aoov6j8h
- the code from `#89714`, before: https://godbolt.org/z/Y4zaPxEG6
- the code from `#89714`, after: https://godbolt.org/z/1dPx83axc
related to #89714
some relevant discussion in https://internals.rust-lang.org/t/idea-shift-move-to-efficiently-move-elements-in-a-vec/22184
Behavior tests pass locally. I can't get any consistent microbenchmark results on my machine, but the assembly diffs look promising.
* Renames the methods:
* `get_many_mut` -> `get_disjoint_mut`
* `get_many_unchecked_mut` -> `get_disjoint_unchecked_mut`
* Does not rename the feature flag: `get_many_mut`
* Marks the feature as stable
* Renames some helper stuff:
* `GetManyMutError` -> `GetDisjointMutError`
* `GetManyMutIndex` -> `GetDisjointMutIndex`
* `get_many_mut_helpers` -> `get_disjoint_mut_helpers`
* `get_many_check_valid` -> `get_disjoint_check_valid`
This only touches slice methods.
HashMap's methods and feature gates are not renamed here
(nor are they stabilized).
Put the core unit tests in a separate coretests package
Having standard library tests in the same package as a standard library crate has bad side effects. It causes the test to have a dependency on a locally built standard library crate, while also indirectly depending on it through libtest. Currently this works out fine in the context of rust's build system as both copies are identical, but for example in cg_clif's tests I've found it basically impossible to compile both copies with the exact same compiler flags and thus the two copies would cause lang item conflicts.
This PR moves the tests of libcore to a separate package which doesn't depend on libcore, thus preventing the duplicate crates even when compiler flags don't exactly match between building the sysroot (for libtest) and building the test itself. The rest of the standard library crates do still have this issue however.
compiler_fence: fix example
The old example was wrong, an acquire fence is required in the signal handler. To make the point more clear, I changed the "data" variable to use non-atomic accesses.
Fixes https://github.com/rust-lang/rust/issues/133014
Rollup of 7 pull requests
Successful merges:
- #133631 (Support QNX 7.1 with `io-sock`+libstd and QNX 8.0 (`no_std` only))
- #134358 (compiler: Set `target_abi = "ilp32e"` on all riscv32e targets)
- #135812 (Fix GDB `OsString` provider on Windows )
- #135842 (TRPL: more backward-compatible Edition changes)
- #135946 (Remove extra whitespace from rustdoc breadcrumbs for copypasting)
- #135953 (ci.py: check the return code in `run-local`)
- #136019 (Add an `unchecked_div` alias to the `Div<NonZero<_>>` impls)
r? `@ghost`
`@rustbot` modify labels: rollup