ptr docs: make it clear that we are talking only about memory accesses
This should make it harder to take this sentence out of context and misunderstand it.
stabilize const_swap
libs-api FCP passed in https://github.com/rust-lang/rust/issues/83163.
However, I only just realized that this actually involves an intrinsic. The intrinsic could be implemented entirely with existing stable const functionality, but we choose to make it a primitive to be able to detect more UB. So nominating for `@rust-lang/lang` to make sure they are aware; I leave it up to them whether they want to FCP this.
While at it I also renamed the intrinsic to make the "nonoverlapping" constraint more clear.
Fixes#83163
The comment says that the expression involves no function call, but
that was only true for the example above, the example here _does_
contain a function call.
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.
Add a compiler intrinsic to back `bigint_helper_methods`
cc https://github.com/rust-lang/rust/issues/85532
This adds a new `carrying_mul_add` intrinsic, to implement `wide_mul` and `carrying_mul`.
It has fallback MIR for all types -- including `u128`, which isn't currently supported on nightly -- so that it'll continue to work on all backends, including CTFE.
Then it's overridden in `cg_llvm` to use wider intermediate types, including `i256` for `u128::carrying_mul`.
ptr::copy: fix docs for the overlapping case
Fixes https://github.com/rust-lang/unsafe-code-guidelines/issues/549
As discussed in that issue, it doesn't make any sense for `copy` to read a byte via `src` after it was already written via `dst`. The entire point of this method is that is copies correctly even if they overlap, and that requires always reading any given location before writing it.
Cc `@rust-lang/opsem`
docs: inline `std::ffi::c_str` types to `std::ffi`
Rustdoc has no way to show that an item is stable, but only at a different path. `std::ffi::c_str::NulError` is not stable, but `std::ffi::NulError` is.
To avoid marking these types as unstable when someone just wants to follow a link from `CString`, inline them into their stable paths.
Fixes#134702
r? `@tgross35`
Update Code Example for `Iterator::rposition`
Added an additional assertion to the example to show the behavior of `iter.next_back` after using `iter.rposition`.
core: fix const ptr::swap_nonoverlapping when there are pointers at odd offsets
Ensure that the pointer gets swapped correctly even if it is not stored at an aligned offset. This rules out implementations that copy things in a `usize` loop -- so our implementation needs to be adjusted to avoid such a loop when running in const context.
Part of https://github.com/rust-lang/rust/issues/133668
Fix safety docs for `dyn Any + Send {+ Sync}`
Fixes the `# Safety` docs for `dyn Any + Send`'s `downcast_{mut/ref}_unchecked` to show the direct instructions , where previously the would tell the user to find the docs on `dyn Any` themselves.
This also adds them for `downcast_{mut/ref}_unchecked` on `dyn Any + Send + Sync`
Use `#[derive(Default)]` instead of manual `impl` when possible
While working on #134175 I noticed a few manual `Default` `impl`s that could be `derive`d instead. These likely predate the existence of the `#[default]` attribute for `enum`s.
Revert stabilization of the `#[coverage(..)]` attribute
Due to a process mixup, the PR to stabilize the `#[coverage(..)]` attribute (#130766) was merged while there are still outstanding concerns. The default action in that situation is to revert, and the feature is not sufficiently urgent or uncontroversial to justify special treatment, so this PR reverts that stabilization.
---
- A key point that came up in offline discussions is that unlike most user-facing features, this one never had a proper RFC, so parts of the normal stabilization process that implicitly rely on an RFC break down in this case.
- As the implementor and de-facto owner of the feature in its current form, I would like to think that I made good choices in designing and implementing it, but I don't feel comfortable proceeding to stabilization without further scrutiny.
- There hasn't been a clear opportunity for T-compiler to weigh in or express concerns prior to stabilization.
- The stabilization PR cites a T-lang FCP that occurred in the tracking issue, but due to the messy design and implementation history (and lack of a clear RFC), it's unclear what that FCP approval actually represents in this case.
- At the very least, we should not proceed without a clear statement from T-lang or the relevant members about the team's stance on this feature, especially in light of the other concerns listed here.
- The existing user-facing documentation doesn't clearly reflect which parts of the feature are stable commitments, and which parts are subject to change. And there doesn't appear to be a clear consensus anywhere about where that line is actually drawn, or whether the chosen boundary is acceptable to the relevant teams and individuals.
- For example, the [stabilization report comment](https://github.com/rust-lang/rust/issues/84605#issuecomment-2166514660) mentions that some aspects are subject to change, but that text isn't consistent with my earlier comments, and there doesn't appear to have been any explicit discussion or approval process.
- [The current reference text](https://github.com/rust-lang/reference/blob/4dfaa4f/src/attributes/coverage-instrumentation.md) doesn't mention this distinction at all, and instead simply describes the current implementation behaviour.
- When the implementation was changed to its current form, the associated user-facing error messages were not updated, so they still refer to the attribute only being allowed on functions and closures.
- On its own, this might have been reasonable to fix-forward in the absence of other concerns, but the fact that it never came up earlier highlights the breakdown in process that has occurred here.
---
Apologies to everyone who was excited for this stabilization to land, but unfortunately it simply isn't ready yet.
Rollup of 6 pull requests
Successful merges:
- #130289 (docs: Permissions.readonly() also ignores root user special permissions)
- #134583 (docs: `transmute<&mut T, &mut MaybeUninit<T>>` is unsound when exposed to safe code)
- #134611 (Align `{i686,x86_64}-win7-windows-msvc` to their parent targets)
- #134629 (compiletest: Allow using a specific debugger when running debuginfo tests)
- #134642 (Implement `PointerLike` for `isize`, `NonNull`, `Cell`, `UnsafeCell`, and `SyncUnsafeCell`.)
- #134660 (Fix spacing of markdown code block fences in compiler rustdoc)
r? `@ghost`
`@rustbot` modify labels: rollup
Implement `PointerLike` for `isize`, `NonNull`, `Cell`, `UnsafeCell`, and `SyncUnsafeCell`.
* Implementing `PointerLike` for `UnsafeCell` enables the possibility of interior mutable `dyn*` values. Since this means potentially exercising new codegen behavior, I added a test for it in `tests/ui/dyn-star/cell.rs`. Please let me know if there are further sorts of tests that should be written, or other care that should be taken with this change.
It is unfortunately not possible without compiler changes to implement `PointerLike` for `Atomic*` types, since they are not `repr(transparent)` (and, in theory if not in practice, `AtomicUsize`'s alignment may be greater than that of an ordinary pointer or `usize`).
* Implementing `PointerLike` for `NonNull` is useful for pointer types which wrap `NonNull`.
* Implementing `PointerLike` for `isize` is just for completeness; I have no use cases in mind, but I cannot think of any reason not to do this.
* Tracking issue: #102425
`@rustbot` label +F-dyn_star
(there is no label or tracking issue for F-pointer_like_trait)
docs: `transmute<&mut T, &mut MaybeUninit<T>>` is unsound when exposed to safe code
Closes#66699
On my system (Edit: And also in the [playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=90529e2a9900599cb759e4bfaa5b5efe)) the example program terminates with an unpredictable exit code:
```console
$ cargo +nightly build && target/debug/bin ; echo $?
255
$ cargo +nightly build && target/debug/bin ; echo $?
253
```
And miri considers the code to have undefined behavior:
```console
$ cargo +nightly miri run
error: Undefined Behavior: using uninitialized data, but this operation requires initialized memory
--> src/main.rs:12:24
|
12 | std::process::exit(*code); // UB! Accessing uninitialized memory
| ^^^^^ using uninitialized data, but this operation requires initialized memory
|
error: aborting due to 1 previous error
```
Implementing `PointerLike` for `UnsafeCell` enables the possibility of
interior mutable `dyn*` values. Since this means potentially exercising
new codegen behavior, I added a test for it in `tests/ui/dyn-star/cell.rs`.
Also updated UI tests to account for the `isize` implementation changing
error messages.
Delete `Rvalue::Len` 🎉
Everything's moved to `PtrMetadata`, so we can get rid of the `Len` variant now.
~~Depends on #134326, so draft until that lands~~ Ready!
r? mir
I've removed the cryptic message about not being able to call `&mut self` methods while retaining a shared borrow of the iterator, such as `as_slice` produces. This is just normal borrowing rules and does not seem especially relevant here. I can whip up a replacement if someone thinks it has value.
Asserts the maximum value that can be returned from `Vec::len`
Currently, casting `Vec<i32>` to `Vec<u32>` takes O(1) time:
```rust
// See <https://godbolt.org/z/hxq3hnYKG> for assembly output.
pub fn cast(vec: Vec<i32>) -> Vec<u32> {
vec.into_iter().map(|e| e as _).collect()
}
```
But the generated assembly is not the same as the identity function, which prevents us from casting `Vec<Vec<i32>>` to `Vec<Vec<u32>>` within O(1) time:
```rust
// See <https://godbolt.org/z/7n48bxd9f> for assembly output.
pub fn cast(vec: Vec<Vec<i32>>) -> Vec<Vec<u32>> {
vec.into_iter()
.map(|e| e.into_iter().map(|e| e as _).collect())
.collect()
}
```
This change tries to fix the problem. You can see the comparison here: <https://godbolt.org/z/jdManrKvx>.
In the playground the example program terminates with an unpredictable exit
code. The undefined behavior is also detected by miri:
error: Undefined Behavior: using uninitialized data
Document `PointerLike` implementation restrictions.
Since <https://github.com/rust-lang/rust/pull/133226>, it is no longer automatically implemented, but must be manually implemented, with special restrictions. The documentation now (roughly) explains those special restrictions.
cc `@compiler-errors` (author of the previous PR)
Rollup of 6 pull requests
Successful merges:
- #134364 (Use E0665 for missing `#[default]` on enum and update doc)
- #134601 (Support pretty-printing `dyn*` trait objects)
- #134603 (Explain why a type is not eligible for `impl PointerLike`.)
- #134618 (coroutine_clone: add comments)
- #134630 (Use `&raw` for `ptr` primitive docs)
- #134637 (Flatten effects directory now that it doesn't really test anything specific)
r? `@ghost`
`@rustbot` modify labels: rollup
Optimize `is_ascii` for `str` and `[u8]` further
Replace the existing optimized function with one that enables auto-vectorization.
This is especially beneficial on x86-64 as `pmovmskb` can be emitted with careful structuring of the code. The instruction can detect non-ASCII characters one vector register width at a time instead of the current `usize` at a time check.
The resulting implementation is completely safe.
`case00_libcore` is the current implementation, `case04_while_loop` is this PR.
```
benchmarks:
ascii::is_ascii_slice::long::case00_libcore 22.25/iter +/- 1.09
ascii::is_ascii_slice::long::case04_while_loop 6.78/iter +/- 0.92
ascii::is_ascii_slice::medium::case00_libcore 2.81/iter +/- 0.39
ascii::is_ascii_slice::medium::case04_while_loop 1.56/iter +/- 0.78
ascii::is_ascii_slice::short::case00_libcore 5.55/iter +/- 0.85
ascii::is_ascii_slice::short::case04_while_loop 3.75/iter +/- 0.22
ascii::is_ascii_slice::unaligned_both_long::case00_libcore 26.59/iter +/- 0.66
ascii::is_ascii_slice::unaligned_both_long::case04_while_loop 5.78/iter +/- 0.16
ascii::is_ascii_slice::unaligned_both_medium::case00_libcore 2.97/iter +/- 0.32
ascii::is_ascii_slice::unaligned_both_medium::case04_while_loop 2.41/iter +/- 0.10
ascii::is_ascii_slice::unaligned_head_long::case00_libcore 23.71/iter +/- 0.79
ascii::is_ascii_slice::unaligned_head_long::case04_while_loop 7.83/iter +/- 1.31
ascii::is_ascii_slice::unaligned_head_medium::case00_libcore 3.69/iter +/- 0.54
ascii::is_ascii_slice::unaligned_head_medium::case04_while_loop 7.05/iter +/- 0.32
ascii::is_ascii_slice::unaligned_tail_long::case00_libcore 24.44/iter +/- 1.41
ascii::is_ascii_slice::unaligned_tail_long::case04_while_loop 5.12/iter +/- 0.18
ascii::is_ascii_slice::unaligned_tail_medium::case00_libcore 3.24/iter +/- 0.40
ascii::is_ascii_slice::unaligned_tail_medium::case04_while_loop 2.86/iter +/- 0.14
```
`unaligned_head_medium` is the main regression in the benchmarks. It is a 32 byte string being sliced `bytes[1..]`.
The first commit can be used to run the benchmarks against the current core implementation.
Previous implementation was done in #74066
---
Two potential drawbacks of this implementation are that it increases instruction count and may regress other platforms/architectures. The benches here may also be too artificial to glean much insight from.
https://rust.godbolt.org/z/G9znGfY36
Correctly document CTFE behavior of is_null and methods that call is_null.
The "panic in const if CTFE doesn't know the answer" behavior was discussed to be the desired behavior in #74939, and is currently how the function actually behaves.
I intentionally wrote this documentation to allow for the possibility that a panic might not occur even if the pointer is out of bounds, because of #133700 and other potential changes in the future.
This is beta-nominated since `const fn is_null` stabilization is in beta already but the docs there are wrong, and it seems better to have the docs be correct at the time of stabilization.
The "panic in const if CTFE doesn't know the answer" behavior was discussed to be the desired behavior in #74939, and is currently how the function actually behaves.
I intentionally wrote this documentation to allow for the possibility that a panic might not occur even if the pointer is out of bounds, because of #133700 and other potential changes in the future.
Less unwrap() in documentation
I think the common use of `.unwrap()` in examples makes it overrepresented, looking like a more typical way of error handling than it really is in real programs.
Therefore, this PR changes a bunch of examples to use different error handling methods, primarily the `?` operator. Additionally, `unwrap()` docs warn that it might abort the program.
Improve prose around into_slice example of IterMut
Having a part without modification and one with seems redundant, since `into_slice` is only called for the part without. I have brought the modification into the remaining part, although it perhaps does not add much (or only distracts?).
unimplement `PointerLike` for trait objects
Values of type `dyn* PointerLike` or `dyn PointerLike` are not pointer-like so these types should not implement `PointerLike`.
After https://github.com/rust-lang/rust/pull/133226, `PointerLike` allows user implementations, so we can't just mark it with `#[rustc_deny_explicit_impl(implement_via_object = false)]`. Instead, this PR splits the `#[rustc_deny_explicit_impl(implement_via_object = ...)]` attribute into two separate attributes `#[rustc_deny_explicit_impl]` and `#[rustc_do_not_implement_via_object]` so that we opt out of the automatic `impl PointerLike for dyn PointerLike` and still allow user implementations.
For traits that are marked with `#[do_not_implement_via_object]` but not `#[rustc_deny_explicit_impl]` I've also made it possible to add a manual `impl Trait for dyn Trait`. There is no immediate need for this, but it was one line to implement and seems nice to have.
fixes https://github.com/rust-lang/rust/issues/134545
fixes https://github.com/rust-lang/rust/issues/134543
r? `@compiler-errors`
This commit splits the `#[rustc_deny_explicit_impl(implement_via_object = ...)]` attribute
into two attributes `#[rustc_deny_explicit_impl]` and `#[rustc_do_not_implement_via_object]`.
This allows us to have special traits that can have user-defined impls but do not have the
automatic trait impl for trait objects (`impl Trait for dyn Trait`).
Rename `elem_offset` to `element_offset`
Tracking issue: #126769
Renames `slice::elem_offset` to `slice::element_offset` and improves the documentation of it and its related methods.
The current documentation can be misinterpreted (as explained [here](https://github.com/rust-lang/rust/issues/126769#issuecomment-2453363897)).
Stabilize `#[diagnostic::do_not_recommend]`
This PR seeks to stabilize the `#[diagnostic::do_not_recommend]`attribute.
This attribute was first proposed as `#[do_not_recommend`] attribute in RFC 2397 (https://github.com/rust-lang/rfcs/pull/2397). It gives the crate authors the ability to not suggest to the compiler to not show certain traits in its error messages.
With the presence of the `#[diagnostic]` tool attribute namespace it was decided to move the attribute there, as that lowers the amount of guarantees the compiler needs to give about the exact way this influences error messages. It turns the attribute into a hint which can be ignored. In addition to the original proposed functionality this attribute now also hides the marked trait in help messages ("This trait is implemented by: ").
The attribute does not accept any argument and can only be placed on trait implementations. If it is placed somewhere else a lint warning is emitted and the attribute is otherwise ignored. If an argument is detected a lint warning is emitted and the argument is ignored. This follows the rules outlined by the diagnostic namespace.
This attribute allows crates like diesel to improve their error messages drastically. The most common example here is the following error message:
```
error[E0277]: the trait bound `&str: Expression` is not satisfied
--> /home/weiznich/Documents/rust/rust/tests/ui/diagnostic_namespace/do_not_recommend.rs:53:15
|
LL | SelectInt.check("bar");
| ^^^^^ the trait `Expression` is not implemented for `&str`, which is required by `&str: AsExpression<Integer>`
|
= help: the following other types implement trait `Expression`:
Bound<T>
SelectInt
note: required for `&str` to implement `AsExpression<Integer>`
--> /home/weiznich/Documents/rust/rust/tests/ui/diagnostic_namespace/do_not_recommend.rs:26:13
|
LL | impl<T, ST> AsExpression<ST> for T
| ^^^^^^^^^^^^^^^^ ^
LL | where
LL | T: Expression<SqlType = ST>,
| ------------------------ unsatisfied trait bound introduced here
```
By applying the new attribute to the wild card trait implementation of
`AsExpression` for `T: Expression` the error message becomes:
```
error[E0277]: the trait bound `&str: AsExpression<Integer>` is not satisfied
--> $DIR/as_expression.rs:55:15
|
LL | SelectInt.check("bar");
| ^^^^^ the trait `AsExpression<Integer>` is not implemented for `&str`
|
= help: the trait `AsExpression<Text>` is implemented for `&str`
= help: for that trait implementation, expected `Text`, found `Integer`
```
which makes it much easier for users to understand that they are facing a type mismatch.
Other explored example usages include:
* This standard library error message: https://github.com/rust-lang/rust/pull/128008
* That bevy derived example:
e1f3068995/tests/ui/diagnostic_namespace/do_not_recommend/supress_suggestions_in_help.rs (No
more tuple pyramids)
Fixes#51992
r? ``@compiler-errors``
This PR also adds a few more tests, makes sure that all the tests are run for the old and new trait solver and adds a check that the attribute does not contain arguments.
Use field init shorthand where possible
Field init shorthand allows writing initializers like `tcx: tcx` as
`tcx`. The compiler already uses it extensively. Fix the last few places
where it isn't yet used.
EDIT: this PR also updates `rustfmt.toml` to set
`use_field_init_shorthand = true`.
This commit seeks to stabilize the `#[diagnostic::do_not_recommend]`
attribute.
This attribute was first proposed as `#[do_not_recommend`] attribute in
RFC 2397 (https://github.com/rust-lang/rfcs/pull/2397). It gives the
crate authors the ability to not suggest to the compiler to not show
certain traits in it's error messages. With the presence of the
`#[diagnostic]` tool attribute namespace it was decided to move the
attribute there, as that lowers the amount of guarantees the compiler
needs to give about the exact way this influences error messages. It
turns the attribute into a hint which can be ignored. In addition to the
original proposed functionality this attribute now also hides the marked
trait in help messages ("This trait is implemented by: ").
The attribute does not accept any argument and can only be placed on
trait implementations. If it is placed somewhere else a lint warning is
emitted and the attribute is otherwise ignored. If an argument is
detected a lint warning is emitted and the argument is ignored. This
follows the rules outlined by the diagnostic namespace.
This attribute allows crates like diesel to improve their error messages
drastically. The most common example here is the following error
message:
```
error[E0277]: the trait bound `&str: Expression` is not satisfied
--> /home/weiznich/Documents/rust/rust/tests/ui/diagnostic_namespace/do_not_recommend.rs:53:15
|
LL | SelectInt.check("bar");
| ^^^^^ the trait `Expression` is not implemented for `&str`, which is required by `&str: AsExpression<Integer>`
|
= help: the following other types implement trait `Expression`:
Bound<T>
SelectInt
note: required for `&str` to implement `AsExpression<Integer>`
--> /home/weiznich/Documents/rust/rust/tests/ui/diagnostic_namespace/do_not_recommend.rs:26:13
|
LL | impl<T, ST> AsExpression<ST> for T
| ^^^^^^^^^^^^^^^^ ^
LL | where
LL | T: Expression<SqlType = ST>,
| ------------------------ unsatisfied trait bound introduced here
```
By applying the new attribute to the wild card trait implementation of
`AsExpression` for `T: Expression` the error message becomes:
```
error[E0277]: the trait bound `&str: AsExpression<Integer>` is not satisfied
--> $DIR/as_expression.rs:55:15
|
LL | SelectInt.check("bar");
| ^^^^^ the trait `AsExpression<Integer>` is not implemented for `&str`
|
= help: the trait `AsExpression<Text>` is implemented for `&str`
= help: for that trait implementation, expected `Text`, found `Integer`
```
which makes it much easier for users to understand that they are facing
a type mismatch.
Other explored example usages included
* This standard library error message: https://github.com/rust-lang/rust/pull/128008
* That bevy derived example:
e1f3068995/tests/ui/diagnostic_namespace/do_not_recommend/supress_suggestions_in_help.rs (No
more tuple pyramids)
Fixes#51992
Field init shorthand allows writing initializers like `tcx: tcx` as
`tcx`. The compiler already uses it extensively. Fix the last few places
where it isn't yet used.
rustdoc-search: handle `impl Into<X>` better
This PR fixes two bugs I ran into while searching the compiler docs:
- It omitted an `impl Trait` entry in the type signature field, producing `TyCtxt, , Symbol -> bool`
- It didn't let me search for `TyCtxt, DefId, Symbol -> bool` even though that's a perfectly good description of the function I was looking for (the function actually used `impl Into<DefId>`
r? ``@GuillaumeGomez`` cc ``@lolbinarycat``
Add clarity to the examples of some `Vec` & `VecDeque` methods
In some `Vec` and `VecDeque` examples where elements are `i32`, examples can seem a bit confusing at first glance if a parameter of the method is an `usize`.
In this case, I think it's better to use `char` rather than `i32`.
> [!NOTE]
> It's already done in the implementation of `VecDeque::insert`
#### Difference
- `i32`
```rs
let mut v = vec![1, 2, 3];
assert_eq!(v.remove(1), 2);
assert_eq!(v, [1, 3]);
```
- `char`
```rs
let mut v = vec!['a', 'b', 'c'];
assert_eq!(v.remove(1), 'b');
assert_eq!(v, ['a', 'c']);
```
Even tho it's pretty minor, it's a nice to have.
Doc: Extend for tuples to be stabilized in 1.85.0
I assumed the RUSTC_CURRENT_VERSION would be replaced automatically, but it doesn't look like it on the nightly docs page. Sorry!
Rollup of 6 pull requests
Successful merges:
- #132150 (Fix powerpc64 big-endian FreeBSD ABI)
- #133942 (Clarify how to use `black_box()`)
- #134081 (Try to evaluate constants in legacy mangling)
- #134192 (Remove `Lexer`'s dependency on `Parser`.)
- #134208 (coverage: Tidy up creation of covmap and covfun records)
- #134211 (On Neutrino QNX, reduce the need to set archiver via environment variables)
r? `@ghost`
`@rustbot` modify labels: rollup
Clarify how to use `black_box()`
Closes#133923.
r? libs
^ (I think that's the right group, this is my first time!)
This PR adds further clarification on the [`black_box()`](https://doc.rust-lang.org/stable/std/hint/fn.black_box.html) documentation. Specifically, it teaches _how_ to use it, instead of just _when_ to use it.
I tried my best to make it clear and accurate, but a lot of my information is sourced from https://github.com/rust-lang/rust-clippy/issues/12707 and [manually inspecting assembly](https://godbolt.org/). Please tell me if I got anything wrong!
Update includes in `/library/core/src/error.rs`.
This PR removes the `crate::fmt::Result` include in `/library/core/src/error.rs`.
The main issue with this `use` statement is that it shadows the `Result` type from the prelude (i.e. `crate::result::Result`). This indirectly makes all docs references to `Result` in this module point to the wrong type (but only in `core::error` - not `std::error`, wherein this include isn't present to begin with).
Fixes: #134169
Fix typos in docs on provenance
This is related to [strict provenance](https://github.com/rust-lang/rust/issues/95228).
Added a couple cross-refs, also replaced
> Create a pointer without provenance from just an address (see [`ptr::dangling`]).
with
> Create a pointer without provenance from just an address (see [`without_provenance`]).
as this method actually takes an address.
Add AST support for unsafe binders
I'm splitting up #130514 into pieces. It's impossible for me to keep up with a huge PR like that. I'll land type system support for this next, probably w/o MIR lowering, which will come later.
r? `@oli-obk`
cc `@BoxyUwU` and `@lcnr` who also may want to look at this, though this PR doesn't do too much yet
Switch inline(always) in core/src/fmt/rt.rs to plain inline
I have a vague memory of these being instantiated a lot. Let's ask perf.
Looks like this is an improvement!
Stabilize the Rust 2024 prelude
This stabilizes the `core::prelude::rust_2024` and `std::prelude::rust_2024` modules. I missed these in the #133349 stabilization.
De-duplicate and improve definition of core::ffi::c_char
Instead of having a list of unsigned char targets for each OS, follow the logic Clang uses and instead set the value based on architecture with a special case for Darwin and Windows operating systems. This makes it easier to support new operating systems targeting Arm/AArch64 without having to modify this config statement for each new OS. The new list does not quite match Clang since I noticed a few bugs in the Clang implementation (https://github.com/llvm/llvm-project/issues/115957).
Fixes https://github.com/rust-lang/rust/issues/129945
Closes https://github.com/rust-lang/rust/pull/131319
Instead of having a list of unsigned char targets for each OS, follow the
logic Clang uses and instead set the value based on architecture with
a special case for Darwin and Windows operating systems. This makes it
easier to support new operating systems targeting Arm/AArch64 without
having to modify this config statement for each new OS. The new list does
not quite match Clang since I noticed a few bugs in the Clang
implementation (https://github.com/llvm/llvm-project/issues/115957).
Fixes: https://github.com/rust-lang/rust/issues/129945
Implementation of `fmt::FormattingOptions`
Tracking issue: #118117
Public API:
```rust
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct FormattingOptions { … }
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum Sign {
Plus,
Minus
}
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum DebugAsHex {
Lower,
Upper
}
impl FormattingOptions {
pub fn new() -> Self;
pub fn sign(&mut self, sign: Option<Sign>) -> &mut Self;
pub fn sign_aware_zero_pad(&mut self, sign_aware_zero_pad: bool) -> &mut Self;
pub fn alternate(&mut self, alternate: bool) -> &mut Self;
pub fn fill(&mut self, fill: char) -> &mut Self;
pub fn align(&mut self, alignment: Option<Alignment>) -> &mut Self;
pub fn width(&mut self, width: Option<usize>) -> &mut Self;
pub fn precision(&mut self, precision: Option<usize>) -> &mut Self;
pub fn debug_as_hex(&mut self, debug_as_hex: Option<DebugAsHex>) -> &mut Self;
pub fn get_sign(&self) -> Option<Sign>;
pub fn get_sign_aware_zero_pad(&self) -> bool;
pub fn get_alternate(&self) -> bool;
pub fn get_fill(&self) -> char;
pub fn get_align(&self) -> Option<Alignment>;
pub fn get_width(&self) -> Option<usize>;
pub fn get_precision(&self) -> Option<usize>;
pub fn get_debug_as_hex(&self) -> Option<DebugAsHex>;
pub fn create_formatter<'a>(self, write: &'a mut (dyn Write + 'a)) -> Formatter<'a>;
}
impl<'a> Formatter<'a> {
pub fn new(write: &'a mut (dyn Write + 'a), options: FormattingOptions) -> Self;
pub fn with_options<'b>(&'b mut self, options: FormattingOptions) -> Formatter<'b>;
pub fn sign(&self) -> Option<Sign>;
pub fn options(&self) -> FormattingOptions;
}
```
Relevant changes from the public API in the tracking issue (I'm leaving out some stuff I consider obvious mistakes, like missing `#[derive(..)]`s and `pub` specifiers):
- `enum DebugAsHex`/`FormattingOptions::debug_as_hex`/`FormattingOptions::get_debug_as_hex`: To support `{:x?}` as well as `{:X?}`. I had completely missed these options in the ACP. I'm open for any and all bikeshedding, not married to the name.
- `fill`/`get_fill` now takes/returns `char` instead of `Option<char>`. This simply mirrors what `Formatter::fill` returns (with default being `' '`).
- Changed `zero_pad`/`get_zero_pad` to `sign_aware_zero_pad`/`get_sign_aware_zero_pad`. This also mirrors `Formatter::sign_aware_zero_pad`. While I'm not a fan of this quite verbose name, I do believe that having the interface of `Formatter` and `FormattingOptions` be compatible is more important.
- For the same reason, renamed `alignment`/`get_alignment` to `aling`/`get_align`.
- Deviating from my initial idea, `Formatter::with_options` returns a `Formatter` which has the lifetime of the `self` reference as its generic lifetime parameter (in the original API spec, the generic lifetime of the returned `Formatter` was the generic lifetime used by `self` instead). Otherwise, one could construct two `Formatter`s that both mutably borrow the same underlying buffer, which would be unsound. This solution still has performance benefits over simply using `Formatter::new`, so I believe it is worthwhile to keep this method.
Stabilize noop_waker
Tracking Issue: #98286
This is a handy feature that's been used widely in tests and example async code and it'd be nice to make it available to users.
cc `@rust-lang/wg-async`
Replace black with ruff in `tidy`
`ruff` can both lint and format Python code (in fact, it should be a mostly drop-in replacement for `black` in terms of formatting), so it's not needed to use `black` anymore. This PR removes `black` and replaces it with `ruff`, to get rid of one Python dependency, and also to make Python formatting faster (although that's a small thing).
If we decide to merge this, we'll need to "reformat the world" - `ruff` is not perfectly compatible with `black`, and it also looks like `black` was actually ignoring some files before. I tried it locally (`./x test tidy --extra-checks=py:fmt --bless`) and it also reformatted some code in subtrees (e.g. `clippy` or `rustc_codegen_gcc`) - I'm not sure how to handle that.
Formatter::with_options takes self as a mutable reference (`&'a mut
Formatter<'b>`). `'a` and `'b` need to be different lifetimes. Just taking `&'a
mut Formatter<'a>` and trusting in Rust being able to implicitely convert from
`&'a mut Formatter<'b>` if necessary (after all, `'a` must be smaller than `'b`
anyway) fails because `'b` is behind a *mutable* reference. For background on
on this behavior, see https://doc.rust-lang.org/nomicon/subtyping.html#variance.
The idea behind this is to make implementing `fmt::FormattingOptions` (as well
as any future changes to `std::Formatter`) easier.
In theory, this might have a negative performance impact because of the
additional function calls. However, I strongly believe that those will be
inlined anyway, thereby producing assembly code that has comparable performance.
clarify simd_relaxed_fma non-determinism
This is the safer spec in the sense that it is more likely to be satisfied by the backend -- and if people are okay with a non-deterministic result, I assume they don't care whether it's the same choice across all lanes or not?
Cc ``@calebzulawski`` ``@workingjubilee``
Rename `core_pattern_type` and `core_pattern_types` lib feature gates to `pattern_type_macro`
That's what the gates are actually gating, and the single char difference in naming was not helpful either
fixes#128987
Add lint against function pointer comparisons
This is kind of a follow-up to https://github.com/rust-lang/rust/pull/117758 where we added a lint against wide pointer comparisons for being ambiguous and unreliable; well function pointer comparisons are also unreliable. We should IMO follow a similar logic and warn people about it.
-----
## `unpredictable_function_pointer_comparisons`
*warn-by-default*
The `unpredictable_function_pointer_comparisons` lint checks comparison of function pointer as the operands.
### Example
```rust
fn foo() {}
let a = foo as fn();
let _ = a == foo;
```
### Explanation
Function pointers comparisons do not produce meaningful result since they are never guaranteed to be unique and could vary between different code generation units. Furthermore different function could have the same address after being merged together.
----
This PR also uplift the very similar `clippy::fn_address_comparisons` lint, which only linted on if one of the operand was an `ty::FnDef` while this PR lints proposes to lint on all `ty::FnPtr` and `ty::FnDef`.
```@rustbot``` labels +I-lang-nominated
~~Edit: Blocked on https://github.com/rust-lang/libs-team/issues/323 being accepted and it's follow-up pr~~
Update `NonZero` and `NonNull` to not field-project (per MCP#807)
https://github.com/rust-lang/compiler-team/issues/807#issuecomment-2506098540 was accepted, so this is the first PR towards moving the library to not using field projections into `[rustc_layout_scalar_valid_range_*]` types.
`NonZero` was already using `transmute` nearly everywhere, so there are very few changes to it.
`NonNull` needed more changes, but they're mostly simple, changing `.pointer` to `.as_ptr()`.
r? libs
cc #133324, which will tidy up some of the MIR from this a bit more, but isn't a blocker.
LLVM does not include an implementation of the va_arg instruction for
Xtensa. From what I understand, this is a conscious decision and
instead language frontends are encouraged to implement it themselves.
The rationale seems to be that loading values correctly requires
language and ABI-specific knowledge that LLVM lacks.
This is true of most architectures, and rustc already provides
implementation for a number of them. This commit extends the support to
include Xtensa.
See https://lists.llvm.org/pipermail/llvm-dev/2017-August/116337.html
for some discussion on the topic.
Unfortunately there does not seem to be a reference document for the
semantics of the va_list and va_arg on Xtensa. The most reliable source
is the GCC implementation, which this commit tries to follow. Clang also
provides its own compatible implementation.
This was tested for all the types that rustc allows in variadics.
Co-authored-by: Brian Tarricone <brian@tarricone.org>
Co-authored-by: Jonathan Bastien-Filiatrault <joe@x2a.org>
Co-authored-by: Paul Lietar <paul@lietar.net>
Approved in [ACP 491](https://github.com/rust-lang/libs-team/issues/491).
Remove the `unsafe` on `core::intrinsics::breakpoint()`, since it's a
safe intrinsic to call and has no prerequisites.
(Thanks to @zachs18 for figuring out the `bootstrap`/`not(bootstrap)`
logic.)
Stabilize `const_maybe_uninit_write`
Mark the following API const stable:
```rust
impl<T> MaybeUninit<T> {
pub const fn write(&mut self, val: T) -> &mut T;
}
```
This depends on `const_mut_refs` and [`const_maybe_uninit_assume_init`](https://github.com/rust-lang/rust/issues/86722), both of which have recently been stabilized.
Closes: <https://github.com/rust-lang/rust/issues/63567>
Mark the following API const stable:
impl<T> MaybeUninit<T> {
pub const fn write(&mut self, val: T) -> &mut T;
}
This depends on `const_mut_refs` and `const_maybe_uninit_assume_init`,
both of which have recently been stabilized.
Tracking issue: <https://github.com/rust-lang/rust/issues/63567>
Stabilize unsigned and float variants of `num_midpoint` feature
This PR proposes that we stabilize the unsigned variants of the [`num_midpoint`](https://github.com/rust-lang/rust/issues/110840#issue-1684506201) feature as well as the floats variants, since they are not subject to any unresolved questions, which is equivalent to doing `(a + b) / 2` (and `(a + b) >> 1`) in a sufficiently large number.
The stabilized API surface would be:
```rust
/// Calculates the middle point of `self` and `rhs`.
///
/// `midpoint(a, b)` is `(a + b) / 2` as if it were performed in a sufficiently-large unsigned integral type.
/// This implies that the result is always rounded towards negative infinity and that no overflow will ever occur.
impl u{8,16,32,64,128,size} {
pub const fn midpoint(self, rhs: Self) -> Self;
}
impl NonZeroU{8,16,32,64,size} {
pub const fn midpoint(self, rhs: Self) -> Self;
}
impl f{32,64} {
pub const fn midpoint(self, rhs: Self) -> Self;
}
```
The signed variants `u{8,16,32,64,128,size}` would remain gated, until a decision is made about the rounding mode, in other words that the [unresolved questions](https://github.com/rust-lang/rust/issues/110840#issue-1684506201) are resolved.
cc `@rust-lang/libs-api`
cc `@scottmcm`
r? libs-api
Mark `slice::copy_from_slice` unstably const
Tracking issue #131415
I used `const_eval_select` for runtime and const panic functions because const formatting isn't available yet.
Add diagnostic item for `std::ops::ControlFlow`
This will be used in Clippy to detect useless conversions done through `ControlFlow::map_break()` and `ControlFlow::map_continue()`.
Something about the MIR lowering for `||` ended up breaking this, but it's fixed by changing the code to use `|` instead.
I also added an assembly test to ensure it *keeps* being `adc`.
changes old intrinsic declaration to new declaration
This pr is for issue #132735
It changes old `extern "intrinsic"` code block with new declaration.
There are other blocks that use old declaration but as the changes needed in single block is quite large I do them in parts
Bump boostrap compiler to new beta
Currently failing due to something about the const stability checks and `panic!`. I'm not sure why though since I wasn't able to see any PRs merged in the past few days that would result in a `cfg(bootstrap)` that shouldn't be removed. cc `@RalfJung` #131349
Use consistent wording in docs, use is zero instead of is 0
In documentation, wording of _"`rhs` is zero"_ and _"`rhs` is 0"_ is intermixed. This is especially visible [here](https://doc.rust-lang.org/std/primitive.usize.html#method.div_ceil).
This changes all occurrences to _"`rhs` is zero"_ for better readability.
That is, differentiate between out-of-bounds and overlapping indices, and remove the generic parameter `N`.
I also exported `GetManyMutError` from `alloc` (and `std`), which was apparently forgotten.
Changing the error to carry additional details means LLVM no longer generates separate short-circuiting branches for the checks, instead it generates one branch at the end. I therefore changed the code to use early returns to make LLVM generate jumps. Benchmark results between the approaches are somewhat mixed, but I chose this approach because it is significantly faster with ranges and also faster with `unwrap()`.