Change pedantically incorrect OnceCell/OnceLock wording
While the semantic intent of a OnceCell/OnceLock is that it can only be written to once (upon init), the fact of the matter is that both these types offer a `take(&mut self) -> Option<T>` mechanism that, when successful, resets the cell to its initial state, thereby [technically allowing it to be written to again](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=415c023a6ae1ef35f371a2d3bb1aa735)
Despite the fact that this can only happen with a mutable reference (generally only used during the construction of the OnceCell/OnceLock), it would be incorrect to say that the type itself as a whole *categorically* prevents being initialized or written to more than once (since it is possible to imagine an identical type only without the `take()` method that actually fulfills that contract).
To clarify, change "that cannot be.." to "that nominally cannot.." and add a note to OnceCell about what can be done with an `&mut Self` reference.
```@rustbot``` label +A-rustdocs
Make TLS accessors closures that return pointers
The current TLS macros generate a function that returns an `Option<&'static T>`. This is both risky as we lie about lifetimes, and necessitates that those functions are `unsafe`. By returning a `*const T` instead, the accessor function do not have safety requirements any longer and can be made closures without hassle. This PR does exactly that!
For native TLS, the closure approach makes it trivial to select the right accessor function at compile-time, which could result in a slight speed-up (I have the hope that the accessors are now simple enough for the MIR-inliner to kick in).
on netbsd, procfs is not as central as on linux/solaris thus
can be perfectly not mounted.
Thus using fcntl with F_GETPATH, the kernel deals with MAXPATHLEN
internally too.
While slightly verbose, it helps explain "why bother with OnceLock?"
This is a point of confusion that has been raised multiple times
shortly before and after the stabilization of LazyLock.
This example is spiritually an example of LazyLock, as it computes a
variable at runtime but accepts no inputs into that process.
It is also slightly simpler and thus easier to understand.
Change it to an even-more concise version and move it to LazyLock.
The example now editorializes slightly more. This may be unnecessary,
but it can be educational for the reader.
The `mir!` macro has multiple parts:
- An optional return type annotation.
- A sequence of zero or more local declarations.
- A mandatory starting anonymous basic block, which is brace-delimited.
- A sequence of zero of more additional named basic blocks.
Some `mir!` invocations use braces with a "block" style, like so:
```
mir! {
let _unit: ();
{
let non_copy = S(42);
let ptr = std::ptr::addr_of_mut!(non_copy);
// Inside `callee`, the first argument and `*ptr` are basically
// aliasing places!
Call(_unit = callee(Move(*ptr), ptr), ReturnTo(after_call), UnwindContinue())
}
after_call = {
Return()
}
}
```
Some invocations use parens with a "block" style, like so:
```
mir!(
let x: [i32; 2];
let one: i32;
{
x = [42, 43];
one = 1;
x = [one, 2];
RET = Move(x);
Return()
}
)
```
And some invocations uses parens with a "tighter" style, like so:
```
mir!({
SetDiscriminant(*b, 0);
Return()
})
```
This last style is generally used for cases where just the mandatory
starting basic block is present. Its braces are placed next to the
parens.
This commit changes all `mir!` invocations to use braces with a "block"
style. Why?
- Consistency is good.
- The contents of the invocation is a block of code, so it's odd to use
parens. They are more normally used for function-like macros.
- Most importantly, the next commit will enable rustfmt for
`tests/mir-opt/`. rustfmt is more aggressive about formatting macros
that use parens than macros that use braces. Without this commit's
changes, rustfmt would break a couple of `mir!` macro invocations that
use braces within `tests/mir-opt` by inserting an extraneous comma.
E.g.:
```
mir!(type RET = (i32, bool);, { // extraneous comma after ';'
RET.0 = 1;
RET.1 = true;
Return()
})
```
Switching those `mir!` invocations to use braces avoids that problem,
resulting in this, which is nicer to read as well as being valid
syntax:
```
mir! {
type RET = (i32, bool);
{
RET.0 = 1;
RET.1 = true;
Return()
}
}
```
Implement feature `integer_sign_cast`
Tracking issue: https://github.com/rust-lang/rust/issues/125882
Since this is my first time making a library addition I wasn't sure where to place the new code relative to existing code. I decided to place it near the top where there are already some other basic bitwise manipulation functions. If there is an official guideline for the ordering of functions, please let me know.
Change f32::midpoint to upcast to f64
This has been verified by kani as a correct optimization
see: https://github.com/rust-lang/rust/issues/110840#issuecomment-1942587398
The new implementation is branchless and only differs in which NaN values are produced (if any are produced at all), which is fine to change. Aside from NaN handling, this implementation produces bitwise identical results to the original implementation.
Question: do we need a codegen test for this? I didn't add one, since the original PR #92048 didn't have any codegen tests.
std::pal::unix::thread fetching min stack size on netbsd.
PTHREAD_STACK_MIN is not defined however sysconf/_SC_THREAD_STACK_MIN returns it as it can vary from arch to another.
This has been verified by kani as a correct optimization
see: https://github.com/rust-lang/rust/issues/110840#issuecomment-1942587398
The new implementation is branchless, and only differs in which NaN
values are produced (if any are produced at all). Which is fine to change.
Aside from NaN handling, this implementation produces bitwise identical
results to the original implementation.
The new implementation is gated on targets that have a fast 64-bit
floating point implementation in hardware, and on WASM.
Unroll first iteration of checked_ilog loop
This follows the optimization of #115913. As shown in https://github.com/rust-lang/rust/pull/115913#issuecomment-2066788006, the performance was improved in all important cases, but some regressions were introduced for the benchmarks `u32_log_random_small`, `u8_log_random` and `u8_log_random_small`.
Basically, #115913 changed the implementation from one division per iteration to one multiplication per iteration plus one division. When there are zero iterations, this is a regression from zero divisions to one division.
This PR avoids this by avoiding the division if we need zero iterations by returning `Some(0)` early. It also reduces the number of multiplications by one in all other cases.
Apply `x clippy --fix` and `x fmt` on Rustc
<!--
If this PR is related to an unstable feature or an otherwise tracked effort,
please link to the relevant tracking issue here. If you don't know of a related
tracking issue or there are none, feel free to ignore this.
This PR will get automatically assigned to a reviewer. In case you would like
a specific user to review your work, you can assign it to them by using
r? <reviewer name>
-->
Just run `x clippy --fix` and `x fmt`, and remove some changes like `impl Default`.
Implement `needs_async_drop` in rustc and optimize async drop glue
This PR expands on #121801 and implements `Ty::needs_async_drop` which works almost exactly the same as `Ty::needs_drop`, which is needed for #123948.
Also made compiler's async drop code to look more like compiler's regular drop code, which enabled me to write an optimization where types which do not use `AsyncDrop` can simply forward async drop glue to `drop_in_place`. This made size of the async block from the [async_drop test](67980dd6fb/tests/ui/async-await/async-drop.rs) to decrease by 12%.
Make `std::env::{set_var, remove_var}` unsafe in edition 2024
Allow calling these functions without `unsafe` blocks in editions up until 2021, but don't trigger the `unused_unsafe` lint for `unsafe` blocks containing these functions.
Fixes#27970.
Fixes#90308.
CC #124866.
drop_in_place: weaken the claim of equivalence with drop(ptr.read())
The two are *not* semantically equivalent in all cases, so let's not be so definite about this.
Fixes https://github.com/rust-lang/rust/issues/112015
Add lang items for `AsyncFn*`, `Future`, `AsyncFnKindHelper`'s associated types
Adds lang items for `AsyncFnOnce::Output`, `AsyncFnOnce::CallOnceFuture`, `AsyncFnMut::CallRefFuture`, and uses them in the new solver. I'm mostly interested in doing this to help accelerate uplifting the new trait solver into a separate crate.
The old solver is kind of spaghetti, so I haven't moved that to use these lang items (i.e. it still uses `item_name`-based comparisons).
update: Also adds lang items for `Future::Output` and `AsyncFnKindHelper::Upvars`.
cc ``@lcnr``
Allow calling these functions without `unsafe` blocks in editions up
until 2021, but don't trigger the `unused_unsafe` lint for `unsafe`
blocks containing these functions.
Fixes#27970.
Fixes#90308.
CC #124866.
This is create symmetry between the already existing TAU constant (2pi)
and the newly-introduced FRAC_1_SQRT_2PI, keeping the more common
name while increasing visibility.
Make more of the test suite run on Mac Catalyst
Combined with https://github.com/rust-lang/rust/pull/125225, the only failing parts of the test suite are in `tests/rustdoc-js`, `tests/rustdoc-js-std` and `tests/debuginfo`. Tested with:
```console
./x test --target=aarch64-apple-ios-macabi library/std
./x test --target=aarch64-apple-ios-macabi --skip=tests/rustdoc-js --skip=tests/rustdoc-js-std --skip=tests/debuginfo tests
```
Will probably put up a PR later to enable _running_ on (not just compiling for) Mac Catalyst in CI, though not sure where exactly I should do so? `src/ci/github-actions/jobs.yml`?
Note that I've deliberately _not_ enabled stack overflow handlers on iOS/tvOS/watchOS/visionOS (see https://github.com/rust-lang/rust/issues/25872), but rather just skipped those tests, as it uses quite a few APIs that I'd be weary about getting rejected by the App Store (note that Swift doesn't do it on those platforms either).
r? ``@workingjubilee``
CC ``@thomcc``
``@rustbot`` label O-ios O-apple
rustfmt fixes
The `rmake.rs` entries in `rustfmt.toml` are causing major problems for `x fmt`. This PR removes them and does some minor related cleanups.
r? ``@GuillaumeGomez``
This adds the `only-apple`/`ignore-apple` compiletest directive, and
uses that basically everywhere instead of `only-macos`/`ignore-macos`.
Some of the updates in `run-make` are a bit redundant, as they use
`ignore-cross-compile` and won't run on iOS - but using Apple in these
is still more correct, so I've made that change anyhow.
It's reasonable to want to, but in the current implementation this
causes multiple problems.
- All the `rmake.rs` files are formatted every time even when they
haven't changed. This is because they get whitelisted unconditionally
in the `OverrideBuilder`, before the changed files get added.
- The way `OverrideBuilder` works, if any files gets whitelisted then no
unmentioned files will get traversed. This is surprising, and means
that the `rmake.rs` entries broke the use of explicit paths to `x
fmt`, and also broke `GITHUB_ACTIONS=true git check --fmt`.
The commit removes the `rmake.rs` entries, fixes the formatting of a
couple of files that were misformatted (not previously caught due to the
`GITHUB_ACTIONS` breakage), and bans `!`-prefixed entries in
`rustfmt.toml` because they cause all these problems.
update tracking issue for lazy_cell_consume
<!--
If this PR is related to an unstable feature or an otherwise tracked effort,
please link to the relevant tracking issue here. If you don't know of a related
tracking issue or there are none, feel free to ignore this.
This PR will get automatically assigned to a reviewer. In case you would like
a specific user to review your work, you can assign it to them by using
r? <reviewer name>
-->
Bump backtrace to 0.3.72
This removes a bunch of dead code, contains critical aarch64-windows fixes, some less-critical windows-in-general improvements, adds visionOS support (and probably improves support for a bunch of Apple platforms...), and harmonizes backtrace's dependencies with rustc/std's.
See https://github.com/rust-lang/backtrace-rs/compare/0.3.71...0.3.72
r? `@ghost`
Always use the general case char count with `optimize_for_size`
The faster algo is really expensive, over a kilobyte if the full algo is present in a binary.
With this PR the general case algo is picked always instead of only for small strings.
In a test of mine this change makes the total binary go from 3116 bytes to 2032 bytes in opt-level 3 and from 1652 bytes to 1428 bytes in opt-level z. I've seen it much worse in real application, so the savings (especially on 'z') will be higher in many cases.
This is the second pr of this kind after #125606
Less syscalls for the `copy_file_range` probe
If it's obvious from the actual syscall results themselves that the syscall is supported or unsupported, don't do an extra syscall with an invalid file descriptor.
CC #122052
Panic if `PathBuf::set_extension` would add a path separator
This is likely never intended and potentially a security vulnerability if it happens.
I'd guess that it's mostly literal strings that are passed to this function in practice, so I'm guessing this doesn't break anyone.
CC #125060
Fix `VecDeque::shrink_to` UB when `handle_alloc_error` unwinds.
Fixes#123369
For `VecDeque` it's relatively simple to restore the buffer into a consistent state so this PR does just that.
Note that with its current implementation, `shrink_to` may change the internal arrangement of elements in the buffer, so e.g. `[D, <uninit>, A, B, C]` will become `[<uninit>, A, B, C, D]` and `[<uninit>, <uninit>, A, B, C]` may become `[B, C, <uninit>, <uninit>, A]` if `shrink_to` unwinds. This shouldn't be an issue though as we don't make any guarantees about the stability of the internal buffer arrangement (and this case is impossible to hit on stable anyways).
This PR also includes a test with code adapted from #123369 which fails without the new `shrink_to` code. Does this suffice or do we maybe need more exhaustive tests like in #108475?
cc `@Amanieu`
`@rustbot` label +T-libs
Stabilize `LazyCell` and `LazyLock`
Closes#109736
This stabilizes the [`LazyLock`](https://doc.rust-lang.org/stable/std/sync/struct.LazyLock.html) and [`LazyCell`](https://doc.rust-lang.org/stable/std/cell/struct.LazyCell.html) types:
```rust
static HASHMAP: LazyLock<HashMap<i32, String>> = LazyLock::new(|| {
println!("initializing");
let mut m = HashMap::new();
m.insert(13, "Spica".to_string());
m.insert(74, "Hoyten".to_string());
m
});
let lazy: LazyCell<i32> = LazyCell::new(|| {
println!("initializing");
92
});
```
r? libs-api
Add assert_unsafe_precondition to unchecked_{add,sub,neg,mul,shl,shr} methods
(Old PR is haunted, opening a new one. See #117494 for previous discussion.)
This ensures that these preconditions are actually checked in debug mode, and hopefully should let people know if they messed up. I've also replaced the calls (I could find) in the code that use these intrinsics directly with those that use these methods, so that the asserts actually apply.
More discussions on people misusing these methods in the tracking issue: https://github.com/rust-lang/rust/issues/85122.
Add manual Sync impl for ReentrantLockGuard
Fixes: #125526
Tracking Issue: #121440
this impl is even shown in the summary in the tracking issue, but apparently was forgotten in the actual implementation
Bump bootstrap compiler to the latest beta compiler
This PR updates the bootstrap compiler, aka stage0 to the latest beta version, since it contains rust-lang/cargo#13925.
It removes those unconditional Cargo warnings:
```
warning: [...]/rust/library/core/Cargo.toml: unused manifest key: lints.rust.unexpected_cfgs.check-cfg
warning: [...]/rust/library/std/Cargo.toml: unused manifest key: lints.rust.unexpected_cfgs.check-cfg
warning: [...]/rust/library/alloc/Cargo.toml: unused manifest key: lints.rust.unexpected_cfgs.check-cfg
```
for all contributors/users of this repository (including CI).
I don't know if that's something we do, or if it's even advisable, feel free to close.
r? `@Mark-Simulacrum`
Rollup of 5 pull requests
Successful merges:
- #125455 (Make `clamp` inline)
- #125477 (Run rustfmt on files that need it.)
- #125481 (Fix the dead link in the bootstrap README)
- #125482 (Notify kobzol after changes to `opt-dist`)
- #125489 (Revert problematic opaque type change)
r? `@ghost`
`@rustbot` modify labels: rollup
While the semantic intent of a OnceCell/OnceLock is that it can only be written
to once (upon init), the fact of the matter is that both these types offer a
`take(&mut self) -> Option<T>` mechanism that, when successful, resets the cell
to its initial state, thereby technically allowing it to be written to again.
Despite the fact that this can only happen with a mutable reference (generally
only used during the construction of the OnceCell/OnceLock), it would be
incorrect to say that the type itself as a whole categorically prevents being
initialized or written to more than once (since it is possible to imagine an
identical type only without the `take()` method that actually fulfills that
contract).
To clarify, change "that cannot be.." to "that nominally cannot.." and add a
note to OnceCell about what can be done with an `&mut Self` reference.
Run rustfmt on files that need it.
Somehow these files aren't properly formatted. By default `x fmt` and `x tidy` only check files that have changed against master, so if an ill-formatted file somehow slips in it can stay that way as long as it doesn't get modified(?)
I found these when I ran `x fmt` explicitly on every `.rs` file in the repo, while working on
https://github.com/rust-lang/compiler-team/issues/750.
Make `clamp` inline
Context: rust-lang/rust-clippy#12826
This results in slightly more optimized assembly. (And most important, it's now less than lines than just manually clamping a value)
Simplify key-based thread locals
This PR simplifies key-based thread-locals by:
* unifying the macro expansion of `const` and non-`const` initializers
* reducing the amount of code in the expansion
* simply reallocating on recursive initialization instead of going through `LazyKeyInner`
* replacing `catch_unwind` with the shared `abort_on_dtor_unwind`
It does not change the initialization behaviour described in #110897.
Add a fast-path to `Debug` ASCII `&str`
Instead of going through the `EscapeDebug` machinery, we can just skip over ASCII chars that don’t need any escaping.
---
This is an alternative / a companion to https://github.com/rust-lang/rust/pull/121138.
The other PR is adding the fast path deep within `EscapeDebug`, whereas this skips as early as possible.
Validate the special layout restriction on `DynMetadata`
If you look at <https://stdrs.dev/nightly/x86_64-unknown-linux-gnu/std/ptr/struct.DynMetadata.html>, you'd think that `DynMetadata` is a struct with fields.
But it's actually not, because the lang item is special-cased in rustc_middle layout:
7601adcc76/compiler/rustc_middle/src/ty/layout.rs (L861-L864)
That explains the very confusing codegen ICEs I was getting in https://github.com/rust-lang/rust/pull/124251#issuecomment-2128543265
> Tried to extract_field 0 from primitive OperandRef(Immediate((ptr: %5 = load ptr, ptr %4, align 8, !nonnull !3, !align !5, !noundef !3)) @ TyAndLayout { ty: DynMetadata<dyn Callsite>, layout: Layout { size: Size(8 bytes), align: AbiAndPrefAlign { abi: Align(8 bytes), pref: Align(8 bytes) }, abi: Scalar(Initialized { value: Pointer(AddressSpace(0)), valid_range: 1..=18446744073709551615 }), fields: Primitive, largest_niche: Some(Niche { offset: Size(0 bytes), value: Pointer(AddressSpace(0)), valid_range: 1..=18446744073709551615 }), variants: Single { index: 0 }, max_repr_align: None, unadjusted_abi_align: Align(8 bytes) } })
because there was a `Field` projection despite the layout clearly saying it's [`Primitive`](https://doc.rust-lang.org/nightly/nightly-rustc/rustc_target/abi/enum.FieldsShape.html#variant.Primitive).
Thus this PR updates the MIR validator to check for such a projection, and changes `libcore` to not ever emit any projections into `DynMetadata`, just to transmute the whole thing when it wants a pointer.
Somehow these files aren't properly formatted. By default `x fmt` and `x
tidy` only check files that have changed against master, so if an
ill-formatted file somehow slips in it can stay that way as long as it
doesn't get modified(?)
I found these when I ran `x fmt` explicitly on every `.rs` file in the
repo, while working on
https://github.com/rust-lang/compiler-team/issues/750.
Rollup of 6 pull requests
Successful merges:
- #125263 (rust-lld: fallback to rustc's sysroot if there's no path to the linker in the target sysroot)
- #125345 (rustc_codegen_llvm: add support for writing summary bitcode)
- #125362 (Actually use TAIT instead of emulating it)
- #125412 (Don't suggest adding the unexpected cfgs to the build-script it-self)
- #125445 (Migrate `run-make/rustdoc-with-short-out-dir-option` to `rmake.rs`)
- #125452 (Cleanup check-cfg handling in core and std)
r? `@ghost`
`@rustbot` modify labels: rollup
Cleanup check-cfg handling in core and std
Follow-up to https://github.com/rust-lang/rust/pull/125296 where we:
- expect any feature cfg in std, due to `#[path]` imports
- move some check-cfg args inside the `build.rs` as per Cargo recommendation
- and replace the fake Cargo feature `"restricted-std"` by the custom cfg `restricted_std`
Fixes https://github.com/rust-lang/rust/pull/125296#issuecomment-2127009301
r? `@bjorn3` (maybe, feel free to re-roll)
Actually use TAIT instead of emulating it
`core`'s `impl_fn_for_zst` macro is just a hacky way of emulating TAIT. TAIT has become stable enough to be used [in other places](e8fbd99128/library/std/src/backtrace.rs (L431)) inside the standard library, so let's use it in `core` as well.
Rollup of 7 pull requests
Successful merges:
- #122382 (Detect unused structs which implement private traits)
- #124389 (Add a warning to proc_macro::Delimiter::None that rustc currently does not respect it.)
- #125224 (Migrate `run-make/issue-53964` to `rmake`)
- #125227 (Migrate `run-make/issue-30063` to `rmake`)
- #125336 (Add dedicated definition for intrinsics)
- #125401 (Migrate `run-make/rustdoc-scrape-examples-macros` to `rmake.rs`)
- #125454 (Improve the doc of query associated_item)
r? `@ghost`
`@rustbot` modify labels: rollup
Add a warning to proc_macro::Delimiter::None that rustc currently does not respect it.
It does not provide the behaviour it is indicated to provide when used in a proc_macro context.
This seems to be a bug, (https://github.com/rust-lang/rust/issues/67062), but it is a long standing one, and hard to discover.
This pull request adds a warning to inform users of this issue, with a link to the relevant issue, and a version number of the last known affected rustc version.
Expand `for_loops_over_fallibles` lint to lint on fallibles behind references.
Extends the scope of the (warn-by-default) lint `for_loops_over_fallibles` from just `for _ in x` where `x: Option<_>/Result<_, _>` to also cover `x: &(mut) Option<_>/Result<_>`
```rs
fn main() {
// Current lints
for _ in Some(42) {}
for _ in Ok::<_, i32>(42) {}
// New lints
for _ in &Some(42) {}
for _ in &mut Some(42) {}
for _ in &Ok::<_, i32>(42) {}
for _ in &mut Ok::<_, i32>(42) {}
// Should not lint
for _ in Some(42).into_iter() {}
for _ in Some(42).iter() {}
for _ in Some(42).iter_mut() {}
for _ in Ok::<_, i32>(42).into_iter() {}
for _ in Ok::<_, i32>(42).iter() {}
for _ in Ok::<_, i32>(42).iter_mut() {}
}
```
<details><summary><code>cargo build</code> diff</summary>
```diff
diff --git a/old.out b/new.out
index 84215aa..ca195a7 100644
--- a/old.out
+++ b/new.out
`@@` -1,33 +1,93 `@@`
warning: for loop over an `Option`. This is more readably written as an `if let` statement
--> src/main.rs:3:14
|
3 | for _ in Some(42) {}
| ^^^^^^^^
|
= note: `#[warn(for_loops_over_fallibles)]` on by default
help: to check pattern in a loop use `while let`
|
3 | while let Some(_) = Some(42) {}
| ~~~~~~~~~~~~~~~ ~~~
help: consider using `if let` to clear intent
|
3 | if let Some(_) = Some(42) {}
| ~~~~~~~~~~~~ ~~~
warning: for loop over a `Result`. This is more readably written as an `if let` statement
--> src/main.rs:4:14
|
4 | for _ in Ok::<_, i32>(42) {}
| ^^^^^^^^^^^^^^^^
|
help: to check pattern in a loop use `while let`
|
4 | while let Ok(_) = Ok::<_, i32>(42) {}
| ~~~~~~~~~~~~~ ~~~
help: consider using `if let` to clear intent
|
4 | if let Ok(_) = Ok::<_, i32>(42) {}
| ~~~~~~~~~~ ~~~
-warning: `for-loops-over-fallibles` (bin "for-loops-over-fallibles") generated 2 warnings
- Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.04s
+warning: for loop over a `&Option`. This is more readably written as an `if let` statement
+ --> src/main.rs:7:14
+ |
+7 | for _ in &Some(42) {}
+ | ^^^^^^^^^
+ |
+help: to check pattern in a loop use `while let`
+ |
+7 | while let Some(_) = &Some(42) {}
+ | ~~~~~~~~~~~~~~~ ~~~
+help: consider using `if let` to clear intent
+ |
+7 | if let Some(_) = &Some(42) {}
+ | ~~~~~~~~~~~~ ~~~
+
+warning: for loop over a `&mut Option`. This is more readably written as an `if let` statement
+ --> src/main.rs:8:14
+ |
+8 | for _ in &mut Some(42) {}
+ | ^^^^^^^^^^^^^
+ |
+help: to check pattern in a loop use `while let`
+ |
+8 | while let Some(_) = &mut Some(42) {}
+ | ~~~~~~~~~~~~~~~ ~~~
+help: consider using `if let` to clear intent
+ |
+8 | if let Some(_) = &mut Some(42) {}
+ | ~~~~~~~~~~~~ ~~~
+
+warning: for loop over a `&Result`. This is more readably written as an `if let` statement
+ --> src/main.rs:9:14
+ |
+9 | for _ in &Ok::<_, i32>(42) {}
+ | ^^^^^^^^^^^^^^^^^
+ |
+help: to check pattern in a loop use `while let`
+ |
+9 | while let Ok(_) = &Ok::<_, i32>(42) {}
+ | ~~~~~~~~~~~~~ ~~~
+help: consider using `if let` to clear intent
+ |
+9 | if let Ok(_) = &Ok::<_, i32>(42) {}
+ | ~~~~~~~~~~ ~~~
+
+warning: for loop over a `&mut Result`. This is more readably written as an `if let` statement
+ --> src/main.rs:10:14
+ |
+10 | for _ in &mut Ok::<_, i32>(42) {}
+ | ^^^^^^^^^^^^^^^^^^^^^
+ |
+help: to check pattern in a loop use `while let`
+ |
+10 | while let Ok(_) = &mut Ok::<_, i32>(42) {}
+ | ~~~~~~~~~~~~~ ~~~
+help: consider using `if let` to clear intent
+ |
+10 | if let Ok(_) = &mut Ok::<_, i32>(42) {}
+ | ~~~~~~~~~~ ~~~
+
+warning: `for-loops-over-fallibles` (bin "for-loops-over-fallibles") generated 6 warnings
+ Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.02s
```
</details>
-----
Question:
* ~~Currently, the article `an` is used for `&Option`, and `&mut Option` in the lint diagnostic, since that's what `Option` uses. Is this okay or should it be changed? (likewise, `a` is used for `&Result` and `&mut Result`)~~ The article `a` is used for `&Option`, `&mut Option`, `&Result`, `&mut Result` and (as before) `Result`. Only `Option` uses `an` (as before).
`@rustbot` label +A-lint
Rollup of 7 pull requests
Successful merges:
- #125043 (reference type safety invariant docs: clarification)
- #125306 (Force the inner coroutine of an async closure to `move` if the outer closure is `move` and `FnOnce`)
- #125355 (Use Backtrace::force_capture instead of Backtrace::capture in rustc_log)
- #125382 (rustdoc: rename `issue-\d+.rs` tests to have meaningful names (part 7))
- #125391 (Minor serialize/span tweaks)
- #125395 (Remove unnecessary `.md` from the documentation sidebar)
- #125399 (Stop using `to_hir_binop` in codegen)
r? `@ghost`
`@rustbot` modify labels: rollup
reference type safety invariant docs: clarification
The old text could have been read as saying that you can call a function if these requirements are upheld, which is definitely not true as they are an underapproximation of the actual safety invariant.
I removed the part about functions relaxing the requirements via their documentation... this seems incoherent with saying that it may actually be unsound to ever temporarily violate the requirement. Furthermore, a function *cannot* just relax this for its return value, that would in general be unsound. And the part about "unsafe code in a safe function may assume these invariants are ensured of arguments passed by the caller" also interacts with relaxing things: clearly, if the invariant has been relaxed, unsafe code cannot rely on it any more. There may be a place to give general guidance on what kinds of function contracts can exist, but the reference type is definitely not the right place to write that down.
I also took a clarification from https://github.com/rust-lang/rust/pull/121965 that is orthogonal to the rest of that PR.
Cc ```@joshlf``` ```@scottmcm```
miri: rename intrinsic_fallback_checks_ub to intrinsic_fallback_is_spec
Checking UB is not the only concern, we also have to make sure we are not losing out on non-determinism.
r? ``@oli-obk`` (not urgent, take your time)
offset: allow zero-byte offset on arbitrary pointers
As per prior `@rust-lang/opsem` [discussion](https://github.com/rust-lang/opsem-team/issues/10) and [FCP](https://github.com/rust-lang/unsafe-code-guidelines/issues/472#issuecomment-1793409130):
- Zero-sized reads and writes are allowed on all sufficiently aligned pointers, including the null pointer
- Inbounds-offset-by-zero is allowed on all pointers, including the null pointer
- `offset_from` on two pointers derived from the same allocation is always allowed when they have the same address
This removes surprising UB (in particular, even C++ allows "nullptr + 0", which we currently disallow), and it brings us one step closer to an important theoretical property for our semantics ("provenance monotonicity": if operations are valid on bytes without provenance, then adding provenance can't make them invalid).
The minimum LLVM we require (v17) includes https://reviews.llvm.org/D154051, so we can finally implement this.
The `offset_from` change is needed to maintain the equivalence with `offset`: if `let ptr2 = ptr1.offset(N)` is well-defined, then `ptr2.offset_from(ptr1)` should be well-defined and return N. Now consider the case where N is 0 and `ptr1` dangles: we want to still allow offset_from here.
I think we should change offset_from further, but that's a separate discussion.
Fixes https://github.com/rust-lang/rust/issues/65108
[Tracking issue](https://github.com/rust-lang/rust/issues/117945) | [T-lang summary](https://github.com/rust-lang/rust/pull/117329#issuecomment-1951981106)
Cc `@nikic`
Use functions from `crt_externs.h` on iOS/tvOS/watchOS/visionOS
Use `_NSGetEnviron`, `_NSGetArgc` and `_NSGetArgv` on iOS/tvOS/watchOS/visionOS, see each commit and the code comments for details. This allows us to unify more code with the macOS implementation, as well as avoiding linking to the `Foundation` framework (which is good for startup performance).
The biggest problem with doing this would be if it lead to App Store rejections. After doing a bunch of research on this, while [it did happen once in 2009](https://blog.unity.com/engine-platform/unity-app-store-submissions-problem-solved), I find it fairly unlikely to happen nowadays, especially considering that Apple has later _added_ `crt_externs.h` to the iOS/tvOS/watchOS/visionOS SDKs, strongly signifying the functions therein is indeed supported on those platforms (even though they lack an availability attribute).
That we've been overly cautious here has also been noted by `@thomcc` in https://github.com/rust-lang/rust/pull/117910#issuecomment-1903372350.
r? `@workingjubilee`
`@rustbot` label O-apple
Add opt-for-size core lib feature flag
Adds a feature flag to the core library that enables the possibility to have smaller implementations for certain algorithms.
So far, the core lib has traded performance for binary size. This is likely what most people want since they have big simd-capable machines. However, people on small machines, like embedded devices, don't enjoy the potential speedup of the bigger algorithms, but do have to pay for them. These microcontrollers often only have 16-1024kB of flash memory.
This PR is the result of some talks with project members like `@Amanieu` at RustNL.
There are some open questions of how this is eventually stabilized, but it's a similar question as with the existing `panic_immediate_abort` feature.
Speaking as someone from the embedded side, we'd rather have this unstable for a while as opposed to not having it at all. In the meantime we can try to use it and also add additional PRs to the core lib that uses the feature flag in areas where we find benefit.
Open questions from my side:
- Is this a good feature name?
- `panic_immediate_abort` is fairly verbose, so I went with something equally verbose
- It's easy to refactor later
- I've added the feature to `std` and `alloc` as well as they might benefit too. Do we agree?
- I expect these to get less usage out of the flag since most size-constraint projects don't use these libraries often.
Add `IntoIterator` for `Box<[T]>` + edition 2024-specific lints
* Adds a similar method probe opt-out mechanism to the `[T;N]: IntoIterator` implementation for edition 2021.
* Adjusts the relevant lints (shadowed `.into_iter()` calls, new source of method ambiguity).
* Adds some tests.
* Took the liberty to rework the logic in the `ARRAY_INTO_ITER` lint, since it was kind of confusing.
Based mostly off of #116607.
ACP: rust-lang/libs-team#263
References #59878
Tracking for Rust 2024: https://github.com/rust-lang/rust/issues/123759
Crater run was done here: https://github.com/rust-lang/rust/pull/116607#issuecomment-1770293013
Consensus afaict was that there is too much breakage, so let's do this in an edition-dependent way much like `[T; N]: IntoIterator`.
The behavior makes sense because `Path::new("one_component").parent() ==
Some(Path::new(""))`, so if one naively wants to create the parent
directory for a file to be written, it simply works.
Closes#105108 by documenting the current behavior.
switch to the default implementation of `write_vectored`
HermitOS doesn't support write_vectored and switch to the default implementation of `write_vectored`.
Fix `read_exact` and `read_buf_exact` for `&[u8]` and `io:Cursor`
- Drain after `read_exact` and `read_buf_exact`
- Append to cursor in `read_buf_exact`
Remove libc from MSVC targets
``@ChrisDenton`` started working on a project to remove libc from Windows MSVC targets. I'm completing that work here.
The primary change is to cfg out the dependency in `library/`. And then there's a lot of test patching. Happy to separate this more if people want.
Instead of having a single loop that works on utf-8 `char`s,
this splits the implementation into a loop that quickly skips over
printable ASCII, falling back to per-char iteration for other chunks.
Instead of writing each `char` of an escape sequence one by one,
this delegates to `Display`, which uses `write_str` internally
in order to write the whole escape sequence at once.
Add `fn into_raw_with_allocator` to Rc/Arc/Weak.
Split out from #119761
Add `fn into_raw_with_allocator` for `Rc`/`rc::Weak`[^1]/`Arc`/`sync::Weak`.
* Pairs with `from_raw_in` (which already exists on all 4 types).
* Name matches `Box::into_raw_with_allocator`.
* Associated fns on `Rc`/`Arc`, methods on `Weak`s.
<details> <summary>Future PR/ACP</summary>
As a follow-on to this PR, I plan to make a PR/ACP later to move `into_raw(_parts)` from `Container<_, A: Allocator>` to only `Container<_, Global>` (where `Container` = `Vec`/`Box`/`Rc`/`rc::Weak`/`Arc`/`sync::Weak`) so that users of non-`Global` allocators have to explicitly handle the allocator when using `into_raw`-like APIs.
The current behaviors of stdlib containers are inconsistent with respect to what happens to the allocator when `into_raw` is called (which does not return the allocator)
| Type | `into_raw` currently callable with | behavior of `into_raw`|
| --- | --- | --- |
| `Box` | any allocator | allocator is [dropped](https://doc.rust-lang.org/nightly/src/alloc/boxed.rs.html#1060) |
| `Vec` | any allocator | allocator is [forgotten](https://doc.rust-lang.org/nightly/src/alloc/vec/mod.rs.html#884) |
| `Arc`/`Rc`/`Weak` | any allocator | allocator is [forgotten](https://doc.rust-lang.org/src/alloc/sync.rs.html#1487)(Arc) [(sync::Weak)](https://doc.rust-lang.org/src/alloc/sync.rs.html#2726) [(Rc)](https://doc.rust-lang.org/src/alloc/rc.rs.html#1352) [(rc::Weak)](https://doc.rust-lang.org/src/alloc/rc.rs.html#2993) |
In my opinion, neither implicitly dropping nor implicitly forgetting the allocator is ideal; dropping it could immediately invalidate the returned pointer, and forgetting it could unintentionally leak memory. My (to-be) proposed solution is to just forbid calling `into_raw(_parts)` on containers with non-`Global` allocators, and require calling `into_raw_with_allocator`(/`Vec::into_raw_parts_with_alloc`)
</details>
[^1]: Technically, `rc::Weak::into_raw_with_allocator` is not newly added, as it was modified and renamed from `rc::Weak::into_raw_and_alloc`.
chore: Remove repeated words (extension of #124924)
When I saw #124924 I thought "Hey, I'm sure that there are far more than just two typos of this nature in the codebase". So here's some more typo-fixing.
Some found with regex, some found with a spellchecker. Every single one manually reviewed by me (along with hundreds of false negatives by the tools)
revise the interpretation of ReadDir for HermitOS
HermitOS supports getdents64. As under Linux, the dirent64 entry `d_off` is not longer used, because its definition is not clear. Instead of `d_off` the entry `d_reclen` is used to determine the end of the dirent64 entry.
In addition, take up `@workingjubilee` suggestion from the discussions in rust-lang/rust#115984 to increase the readability.
Hermit is a tier 3 platform and this PR changes only files, wich are related to the tier 3 platform.
Update documentation related to the recent cmd.exe fix
Fix some grammar nits, change `bat` (extension) -> `batch` (file), and make line wrapping more consistent.
Fix#124275: Implemented Default for `Arc<str>`
With added implementations.
```
GOOD Arc<CStr>
BROKEN Arc<OsStr> // removed
GOOD Rc<str>
GOOD Rc<CStr>
BROKEN Rc<OsStr> // removed
GOOD Rc<[T]>
GOOD Arc<[T]>
```
For discussion of https://github.com/rust-lang/rust/pull/124367#issuecomment-2091940137.
Key pain points currently:
> I've had a guess at the best locations/feature attrs for them but they might not be correct.
> However I'm unclear how to get the OsStr impl to compile, which file should they go in to avoid the error below? Is it possible, perhaps with some special std rust lib magic?
alloc: implement FromIterator for Box<str>
`Box<[T]>` implements `FromIterator<T>` using `Vec<T>` + `into_boxed_slice()`.
Add analogous `FromIterator` implementations for `Box<str>`
matching the current implementations for `String`.
Remove the `Global` allocator requirement for `FromIterator<Box<str>>` too.
ACP: https://github.com/rust-lang/libs-team/issues/196
LLVM currently adds a redundant check for the returned option, in addition
to the `self.ptr != self.end` check when using the default
`Iterator::fold` method that calls `vec::IntoIter::next` in a loop.
If we're comfortable using `_NSGetEnviron` from `crt_externs.h`, there shouldn't be an issue with using these either, and then we can merge with the macOS implementation.
This also fixes two test cases on Mac Catalyst:
- `tests/ui/command/command-argv0.rs`, maybe because `[[NSProcessInfo processInfo] arguments]` somehow converts the name of the first argument?
- `tests/ui/env-funky-keys.rs` since we no longer link to Foundation.
feat: update stdarch submodule for intrinsics on ARM
Submodule update for stdarch library
10 commits in c0257c1660e78c80ad1b9136fcc5555b14da5b4c..df3618d9f35165f4bc548114e511c49c29e1fd9b
2024-04-22 01:24:03 +0200 to 2024-05-14 15:52:07 +0200
- feat: stabilization for stdarch_aarch64_crc32
- Add vec_insert and vec_extract
- Remove libc dependency on Windows by using Win32 to get env vars
- Add vec_orc
- Simplify vec_andc implementation
- Silence unexpected-cfgs
- Add vec_mul
- Remove `#![feature(inline_const)]`
- Add `#[cfg_attr(miri, ignore)]` to tests of intrinsics that cannot be supported by Miri
- Implement ARM `__ssat` and `__usat` functions
r? Amanieu
Re-add `From<f16> for f64`
This impl was originally added in #122470 before being removed in #123830 due to #123831. However, the issue only affects `f32` (which currently only has one `From<{float}>` impl, `From<f32>`) as `f64` already has two `From<{float}>` impls (`From<f32>` and `From<f64>`) and is also the float literal fallback type anyway. Therefore it is safe to re-add `From<f16> for f64`.
This PR also updates the FIXME link to point to the open issue #123831 rather than the closed issue #123824.
Tracking issue: #116909
`@rustbot` label +F-f16_and_f128 +T-libs-api
- `slice::sort` -> driftsort
https://github.com/Voultapher/sort-research-rs/blob/main/writeup/driftsort_introduction/text.md
- `slice::sort_unstable` -> ipnsort
https://github.com/Voultapher/sort-research-rs/blob/main/writeup/ipnsort_introduction/text.md
Replaces the sort implementations with tailor made ones that strike a
balance of run-time, compile-time and binary-size, yielding run-time and
compile-time improvements. Regressing binary-size for `slice::sort`
while improving it for `slice::sort_unstable`. All while upholding the
existing soft and hard safety guarantees, and even extending the soft
guarantees, detecting strict weak ordering violations with a high chance
and reporting it to users via a panic.
In addition the implementation of `select_nth_unstable` is also adapted
as it uses `slice::sort_unstable` internals.
Refactor examples and enhance documentation in result.rs
- Replaced `map` with `map_err` in the error handling example for correctness
- Reordered example code to improve readability and logical flow
- Added assertions to examples to demonstrate expected outcomes
Invert comparison in `uN::checked_sub`
After #124114, LLVM no longer combines the comparison and subtraction in `uN::checked_sub` when either operand is a constant (demo: https://rust.godbolt.org/z/MaeoYbsP1). The difference is more pronounced when the expression is slightly more complex (https://rust.godbolt.org/z/4rPavsYdc).
This is due to the use of `>=` here:
ee97564e3a/library/core/src/num/uint_macros.rs (L581-L593)
For constant `C`, LLVM eagerly converts `a >= C` into `a > C - 1`, but the backend can only combine `a < C` with `a - C`, not `C - 1 < a` and `a - C`: e586556e37/llvm/lib/CodeGen/CodeGenPrepare.cpp (L1697-L1742)
This PR[^1] simply inverts the `>=` into `<` to restore the LLVM magic, and somewhat align this with the implementation of `uN::overflowing_sub` from #103299.
When the result is stored as an `Option` (rather than being branched/cmoved on), the discriminant is `self >= rhs`. This PR doesn't affect the codegen (and relevant tests) of that since LLVM will negate `self < rhs` to `self >= rhs` when necessary.
[^1]: Note to `self`: My very first contribution to publicly-used code. Hopefully like what I should learn to always be, tiny and humble.
Many, many projects use `size_of` to get the size of a type. However,
it's also often equally easy to hardcode a size (e.g. `8` instead of
`size_of::<u64>()`). Minimizing friction in the use of `size_of` helps
ensure that people use it and make code more self-documenting.
The name `size_of` is unambiguous: the name alone, without any prefix or
path, is self-explanatory and unmistakeable for any other functionality.
Adding it to the prelude cannot produce any name conflicts, as any local
definition will silently shadow the one from the prelude. Thus, we don't
need to wait for a new edition prelude to add it.
Add `size_of_val`, `align_of`, and `align_of_val` as well, with similar
justification: widely useful, self-explanatory, unmistakeable for
anything else, won't produce conflicts.
This is likely never intended and potentially a security vulnerability
if it happens.
I'd guess that it's mostly literal strings that are passed to this
function in practice, so I'm guessing this doesn't break anyone.
CC #125060
Update reference safety requirements
Per https://github.com/rust-lang/rust/pull/116677#issuecomment-1945495786, the language as written promises too much. This PR relaxes the language to be consistent with current semantics. If and when #117945 is implemented, we can revert to the old language.
While we're here, we also require that references be non-null.
cc ``@RalfJung``
std::alloc: use posix_memalign instead of memalign on solarish
`memalign` on Solarish requires the alignment to be at least the size of a pointer, which we did not honor. `posix_memalign` also requires that, but that code path already takes care of this requirement.
close GH-124787