derive(SmartPointer): assume pointee from the single generic and better error messages
Fix#129465
Actually RFC says that `#[pointee]` can be inferred when there is no ambiguity, or there is only one generic type parameter so to say.
cc ```@Darksonn```
r? ```@compiler-errors```
Emit specific message for time<=0.3.35
```
error[E0282]: type annotations needed for `Box<_>`
--> /home/gh-estebank/.cargo/registry/src/index.crates.io-6f17d22bba15001f/time-0.3.34/src/format_description/parse/mod.rs:83:9
|
83 | let items = format_items
| ^^^^^
...
86 | Ok(items.into())
| ---- type must be known at this point
|
= note: this is an inference error on `time` caused by a change in Rust 1.80.0; update `time` to version `>=0.3.36`
```
Partially mitigate the fallout from https://github.com/rust-lang/rust/issues/127343. Although the biggest benefit of this would have been if we had had this in 1.80 before it became stable, the long-tail of that change will be felt for a *long* time, so better late than never.
We can also emit an even more targeted error instead of this inference failure.
rustc_target: Add various aarch64 features
Add various aarch64 features already supported by LLVM and Linux.
Additionally include some comment fixes to ensure consistency of feature names with the Arm ARM.
Compiler support for features added to stdarch by https://github.com/rust-lang/stdarch/pull/1614.
Tracking issue for unstable aarch64 features is https://github.com/rust-lang/rust/issues/127764.
List of added features:
- FEAT_CSSC
- FEAT_ECV
- FEAT_FAMINMAX
- FEAT_FLAGM2
- FEAT_FP8
- FEAT_FP8DOT2
- FEAT_FP8DOT4
- FEAT_FP8FMA
- FEAT_HBC
- FEAT_LSE128
- FEAT_LSE2
- FEAT_LUT
- FEAT_MOPS
- FEAT_LRCPC3
- FEAT_SVE_B16B16
- FEAT_SVE2p1
- FEAT_WFxT
- FEAT_SME
- FEAT_SME_F16F16
- FEAT_SME_F64F64
- FEAT_SME_F8F16
- FEAT_SME_F8F32
- FEAT_SME_FA64
- FEAT_SME_I16I64
- FEAT_SME_LUTv2
- FEAT_SME2
- FEAT_SME2p1
- FEAT_SSVE_FP8DOT2
- FEAT_SSVE_FP8DOT4
- FEAT_SSVE_FP8FMA
FEAT_FPMR is added in the first commit and then removed in a separate one to highlight it being removed from upstream LLVM 19. The intention is for it to be detectable at runtime through stdarch but not have a corresponding Rust compile-time feature.
Implement a first version of RFC 3525: struct target features
This PR is an attempt at implementing https://github.com/rust-lang/rfcs/pull/3525, behind a feature gate `struct_target_features`.
There's obviously a few tasks that ought to be done before this is merged; in no particular order:
- add proper error messages
- add tests
- create a tracking issue for the RFC
- properly serialize/deserialize the new target_features field in `rmeta` (assuming I even understood that correctly :-))
That said, as I am definitely not a `rustc` expert, I'd like to get some early feedback on the overall approach before fixing those things (and perhaps some pointers for `rmeta`...), hence this early PR :-)
Here's an example piece of code that I have been using for testing - with the new code, the calls to intrinsics get correctly inlined:
```rust
#![feature(struct_target_features)]
use std::arch::x86_64::*;
/*
// fails to compile
#[target_feature(enable = "avx")]
struct Invalid(u32);
*/
#[target_feature(enable = "avx")]
struct Avx {}
#[target_feature(enable = "sse")]
struct Sse();
/*
// fails to compile
extern "C" fn bad_fun(_: Avx) {}
*/
/*
// fails to compile
#[inline(always)]
fn inline_fun(_: Avx) {}
*/
trait Simd {
fn do_something(&self);
}
impl Simd for Avx {
fn do_something(&self) {
unsafe {
println!("{:?}", _mm256_setzero_ps());
}
}
}
impl Simd for Sse {
fn do_something(&self) {
unsafe {
println!("{:?}", _mm_setzero_ps());
}
}
}
struct WithAvx {
#[allow(dead_code)]
avx: Avx,
}
impl Simd for WithAvx {
fn do_something(&self) {
unsafe {
println!("{:?}", _mm256_setzero_ps());
}
}
}
#[inline(never)]
fn dosomething<S: Simd>(simd: &S) {
simd.do_something();
}
fn main() {
/*
// fails to compile
Avx {};
*/
if is_x86_feature_detected!("avx") {
let avx = unsafe { Avx {} };
dosomething(&avx);
dosomething(&WithAvx { avx });
}
if is_x86_feature_detected!("sse") {
dosomething(&unsafe { Sse {} })
}
}
```
Tracking:
- https://github.com/rust-lang/rust/issues/129107
```
error[E0282]: type annotations needed for `Box<_>`
--> ~/.cargo/registry/src/index.crates.io-6f17d22bba15001f/time-0.3.34/src/format_description/parse/mod.rs:83:9
|
83 | let items = format_items
| ^^^^^
...
86 | Ok(items.into())
| ---- type must be known at this point
|
= note: this is an inference error on crate `time` caused by a change in Rust 1.80.0; update `time` to version `>=0.3.35`
```
Partially address #127343.
Rename `BikeshedIntrinsicFrom` to `TransmuteFrom`
As our implementation of MCP411 nears completion and we begin to solicit testing, it's no longer reasonable to expect testers to type or remember `BikeshedIntrinsicFrom`. The name degrades the ease-of-reading of documentation, and the overall experience of using compiler safe transmute.
Tentatively, we'll instead adopt `TransmuteFrom`.
This name seems to be the one most likely to be stabilized, after discussion on Zulip [1]. We may want to revisit the ordering of `Src` and `Dst` before stabilization, at which point we'd likely consider `TransmuteInto` or `Transmute`.
[1] https://rust-lang.zulipchat.com/#narrow/stream/216762-project-safe-transmute/topic/What.20should.20.60BikeshedIntrinsicFrom.60.20be.20named.3F
Tracking Issue: https://github.com/rust-lang/rust/issues/99571
r? `@compiler-errors`
interpret: do not make const-eval query result depend on tcx.sess
The check against calling functions with missing target features uses `tcx.sess` to determine which target features are available. However, this can differ between different crates in a crate graph, so the same const-eval query can come to different conclusions about whether a constant evaluates successfully or not -- which is bad, we should consistently get the same result everywhere.
add repr to the allowlist for naked functions
Fixes#129412 (combining unstable features #90957 (`#![feature(naked_functions)]`) and #82232 (`#![feature(fn_align)]`)
Get rid of `predicates_defined_on`
This is the uncontroversial part of #129532. This simply inlines the `predicates_defined_on` into into `predicates_of`. Nothing should change here logically.
Stop storing a special inner body for the coroutine by-move body for async closures
...and instead, just synthesize an item which is treated mostly normally by the MIR pipeline.
This PR does a few things:
* We synthesize a new `DefId` for the by-move body of a closure, which has its `mir_built` fed with the output of the `ByMoveBody` MIR transformation, and some other relevant queries.
* This has the `DefKind::ByMoveBody`, which we use to distinguish it from "real" bodies (that come from HIR) which need to be borrowck'd. Introduce `TyCtxt::is_synthetic_mir` to skip over `mir_borrowck` which is called by `mir_promoted`; borrowck isn't really possible to make work ATM since it heavily relies being called on a body generated from HIR, and is redundant by the construction of the by-move-body.
* Remove the special `PassManager` hacks for handling the inner `by_move_body` stored within the coroutine's mir body. Instead, this body is fed like a regular MIR body, so it's goes through all of the `tcx.*_mir` stages normally (build -> promoted -> ...etc... -> optimized) ✨.
* Remove the `InstanceKind::ByMoveBody` shim, since now we have a "regular" def id, we can just use `InstanceKind::Item`. This also allows us to remove the corresponding hacks from codegen, such as in `fn_sig_for_fn_abi` ✨.
Notable remarks:
* ~~I know it's kind of weird to be using `DefKind::Closure` here, since it's not a distinct closure but just a new MIR body. I don't believe it really matters, but I could also use a different `DefKind`... maybe one that we could use for synthetic MIR bodies in general?~~ edit: We're doing this now.
The main `arbitrary_self_types` feature gate will shortly be reused for
a new version of arbitrary self types which we are amending per [this
RFC](https://github.com/rust-lang/rfcs/blob/master/text/3519-arbitrary-self-types-v2.md).
The main amendments are:
* _do_ support `self` types which can't safely implement `Deref`
* do _not_ support generic `self` types
* do _not_ support raw pointers as `self` types.
This PR relates to the last of those bullet points: this strips pointer
support from the current `arbitrary_self_types` feature.
We expect this to cause some amount of breakage for crates using this
unstable feature to allow raw pointer self types. If that's the case, we
want to know about it, and we want crate authors to know of the upcoming
changes.
For now, this can be resolved by adding the new
`arbitrary_self_types_pointers` feature to such crates. If we determine
that use of raw pointers as self types is common, then we may maintain
that as an unstable feature even if we come to stabilize the rest of the
`arbitrary_self_types` support in future. If we don't hear that this PR
is causing breakage, then perhaps we don't need it at all, even behind
an unstable feature gate.
[Tracking issue](https://github.com/rust-lang/rust/issues/44874)
This is [step 4 of the plan outlined here](https://github.com/rust-lang/rust/issues/44874#issuecomment-2122179688)
make it possible to enable const_precise_live_drops per-function
This makes const_precise_live_drops work with rustc_allow_const_fn_unstable so that we can stabilize individual functions that rely on const_precise_live_drops.
The goal is that we can use that to stabilize some of https://github.com/rust-lang/rust/issues/67441 without having to stabilize const_precise_live_drops.
As our implementation of MCP411 nears completion and we begin to
solicit testing, it's no longer reasonable to expect testers to
type or remember `BikeshedIntrinsicFrom`. The name degrades the
ease-of-reading of documentation, and the overall experience of
using compiler safe transmute.
Tentatively, we'll instead adopt `TransmuteFrom`.
This name seems to be the one most likely to be stabilized, after
discussion on Zulip [1]. We may want to revisit the ordering of
`Src` and `Dst` before stabilization, at which point we'd likely
consider `TransmuteInto` or `Transmute`.
[1] https://rust-lang.zulipchat.com/#narrow/stream/216762-project-safe-transmute/topic/What.20should.20.60BikeshedIntrinsicFrom.60.20be.20named.3F
Add various aarch64 features already supported by LLVM and Linux.
The features are marked as unstable using a newly added symbol, i.e.
aarch64_unstable_target_feature.
Additionally include some comment fixes to ensure consistency of
feature names with the Arm ARM and support for architecture version
target features up to v9.5a.
This commit adds compiler support for the following features:
- FEAT_CSSC
- FEAT_ECV
- FEAT_FAMINMAX
- FEAT_FLAGM2
- FEAT_FP8
- FEAT_FP8DOT2
- FEAT_FP8DOT4
- FEAT_FP8FMA
- FEAT_FPMR
- FEAT_HBC
- FEAT_LSE128
- FEAT_LSE2
- FEAT_LUT
- FEAT_MOPS
- FEAT_LRCPC3
- FEAT_SVE_B16B16
- FEAT_SVE2p1
- FEAT_WFxT
Add `f16` and `f128` inline ASM support for `aarch64`
Adds `f16` and `f128` inline ASM support for `aarch64`. SIMD vector types are taken from [the ARM intrinsics list](https://developer.arm.com/architectures/instruction-sets/intrinsics/#f:`@navigationhierarchiesreturnbasetype=[float]&f:@navigationhierarchieselementbitsize=[16]&f:@navigationhierarchiesarchitectures=[A64]).` Based on the work of `@lengrongfu` in #127043.
Relevant issue: #125398
Tracking issue: #116909
`@rustbot` label +F-f16_and_f128
try-job: aarch64-gnu
try-job: aarch64-apple
Add Trusty OS as tier 3 target
This PR adds support for the [Trusty secure operating system](https://source.android.com/docs/security/features/trusty) as a Tier 3 supported target. This upstreams [the patch that we have been using](https://cs.android.com/android/platform/superproject/+/master:external/rust/crates/libc/patches/trusty.patch;l=1;drc=122e586e93a534160230dc10ae3474cf31dd8f7f) internally. This also revives https://github.com/rust-lang/rust/pull/103895 which was closed due to inactivity, and is being resumed now that time allows.
And MCP has already been done for adding this platform: rust-lang/compiler-team/issues/568
# Target Tier Policy Acknowledgements
> A tier 3 target must have a designated developer or developers (the "target maintainers") on record to be CCed when issues arise regarding the target. (The mechanism to track and CC such developers may evolve over time.)
- Nicole LeGare (``@randomPoison)``
- Stephen Crane (``@rinon)``
- As a fallback trusty-dev-team@google.com can be contacted
> Targets must use naming consistent with any existing targets; for instance, a target for the same CPU or OS as an existing Rust target should use the same name for that CPU or OS. Targets should normally use the same names and naming conventions as used elsewhere in the broader ecosystem beyond Rust (such as in other toolchains), unless they have a very good reason to diverge. Changing the name of a target can be highly disruptive, especially once the target reaches a higher tier, so getting the name right is important even for a tier 3 target.
The two new Trusty targets, `aarch64-unknown-trusty` and `armv7-unknown-trusty` both follow the existing naming convention for similar targets.
> Target names should not introduce undue confusion or ambiguity unless absolutely necessary to maintain ecosystem compatibility. For example, if the name of the target makes people extremely likely to form incorrect beliefs about what it targets, the name should be changed or augmented to disambiguate it.
👍
> Tier 3 targets may have unusual requirements to build or use, but must not create legal issues or impose onerous legal terms for the Rust project or for Rust developers or users.
There are no known legal issues or license incompatibilities.
> Neither this policy nor any decisions made regarding targets shall create any binding agreement or estoppel by any party. If any member of an approving Rust team serves as one of the maintainers of a target, or has any legal or employment requirement (explicit or implicit) that might affect their decisions regarding a target, they must recuse themselves from any approval decisions regarding the target's tier status, though they may otherwise participate in discussions.
👍
> Tier 3 targets should attempt to implement as much of the standard libraries as possible and appropriate (core for most targets, alloc for targets that can support dynamic memory allocation, std for targets with an operating system or equivalent layer of system-provided functionality), but may leave some code unimplemented (either unavailable or stubbed out as appropriate), whether because the target makes it impossible to implement or challenging to implement. The authors of pull requests are not obligated to avoid calling any portions of the standard library on the basis of a tier 3 target not implementing those portions.
This PR only adds the targets for the platform. `std` support will be added once platform support is added to the libc crate, which depends on the language targets being added to rustc.
> The target must provide documentation for the Rust community explaining how to build for the target, using cross-compilation if possible. If the target supports running binaries, or running tests (even if they do not pass), the documentation must explain how to run such binaries or tests for the target, using emulation if possible or dedicated hardware if necessary.
👍
> Tier 3 targets must not impose burden on the authors of pull requests, or other developers in the community, to maintain the target. In particular, do not post comments (automated or manual) on a PR that derail or suggest a block on the PR based on a tier 3 target. Do not send automated messages or notifications (via any medium, including via ``@)`` to a PR author or others involved with a PR regarding a tier 3 target, unless they have opted into such messages.
👍
> Patches adding or updating tier 3 targets must not break any existing tier 2 or tier 1 target, and must not knowingly break another tier 3 target without approval of either the compiler team or the maintainers of the other tier 3 target.
👍
> Tier 3 targets must be able to produce assembly using at least one of rustc's supported backends from any host target. (Having support in a fork of the backend is not sufficient, it must be upstream.)
👍
More work on `zstd` compression
r? ``@Kobzol`` as we've discussed this.
This is a draft to show the current approach of supporting zstd in compiletest, and making the tests using it unconditional.
Knowing whether llvm/lld was built with `LLVM_ENABLE_ZSTD` is quite hard, so there are two strategies. There are details in the code, and we can discuss this approach. Until we know the config used to build CI artifacts, it seems our options are somewhat limited in any case.
zlib compression seems always enabled, so we only check this in its dedicated test, allowing the test to ignore errors due to zstd not being supported.
The zstd test is made unconditional in what it tests, by relying on `needs-llvm-zstd` to be ignored when `llvm.libzstd` isn't enabled in `config.toml`.
try-job: x86_64-gnu
try-job: x86_64-msvc
try-job: x86_64-gnu-distcheck
simd_shuffle intrinsic: allow argument to be passed as vector
See https://github.com/rust-lang/rust/issues/128738 for context.
I'd like to get rid of [this hack](6c0b89dfac/compiler/rustc_codegen_ssa/src/mir/block.rs (L922-L935)). https://github.com/rust-lang/rust/pull/128537 almost lets us do that since constant SIMD vectors will then be passed as immediate arguments. However, simd_shuffle for some reason actually takes an *array* as argument, not a vector, so the hack is still required to ensure that the array becomes an immediate (which then later stages of codegen convert into a vector, as that's what LLVM needs).
This PR prepares simd_shuffle to also support a vector as the `idx` argument. Once this lands, stdarch can hopefully be updated to pass `idx` as a vector, and then support for arrays can be removed, which finally lets us get rid of that hack.
Remove Duplicate E0381 Label
Aims to resolve https://github.com/rust-lang/rust/issues/129274, and adds a test for the case.
Essentially, we are duplicating this span for some reason. For now, I'm just using a set to collect the spans rather than the vec. I imagine there's probably no real reason to inspect duplicates in this area, but if I'm wrong I can adjust to collect "seen spans" in just the point where this label is applied.
I'm not sure why it's producing duplicate spans. Looks like this has been this way for a while? I think it gives the duplicate label on 1.75.0 for example.
Do not ICE on non-ADT rcvr type when looking for crate version collision
When looking for multiple versions of the same crate, do not blindly construct the receiver type.
Follow up to #128786.
Fixes#129205Fixes#129216
Document & implement the transmutation modeled by `BikeshedIntrinsicFrom`
Documents that `BikeshedIntrinsicFrom` models transmute-via-union, which is slightly more expressive than the transmute-via-cast implemented by `transmute_copy`. Additionally, we provide an implementation of transmute-via-union as a method on the `BikeshedIntrinsicFrom` trait with additional documentation on the boundary between trait invariants and caller obligations.
Whether or not transmute-via-union is the right kind of transmute to model remains up for discussion [1]. Regardless, it seems wise to document the present behavior.
[1] https://rust-lang.zulipchat.com/#narrow/stream/216762-project-safe-transmute/topic/What.20'kind'.20of.20transmute.20to.20model.3F/near/426331967
Tracking Issue: https://github.com/rust-lang/rust/issues/99571
r? `@compiler-errors`
cc `@scottmcm,` `@Lokathor`
Tie `impl_trait_overcaptures` lint to Rust 2024
The `impl_trait_overcaptures` lint is part of the migration to Rust 2024 and the Lifetime Capture Rules 2024. Now that we've stabilized precise capturing (RFC 3617), let's tie this lint to the `rust_2024_compatibility` lint group.
Tracking:
- https://github.com/rust-lang/rust/issues/117587
r? `@compiler-errors`
Without suitable `needs-llvm-components` directives, these tests that
rely on target-specific codegen can fail if used with a LLVM that is
built without the required components.
The `impl_trait_overcaptures` lint is part of the migration to Rust
2024 and the Lifetime Capture Rules 2024. Now that we've stabilized
precise capturing (RFC 3617), let's tie this lint to the
`rust_2024_compatibility` lint group.
add back test for stable-const-can-only-call-stable-const
This got accidentally removed in https://github.com/rust-lang/rust/pull/128596 (file `tests/ui/internal/internal-unstable-const.rs`). The test has little to do with "allow internal unstable" though, so add it in a file that already tests various const stability things.
Also tweak the help that suggests to add `rustc_allow_const_fn_unstable` to make it clear that this needs team approval, since it is a fairly big gun.
rustdoc: clean up tuple <-> primitive conversion docs
This adds a minor missing feature to `fake_variadic`, so that it can render `impl From<(T,)> for [T; 1]` correctly.
Remove redundant flags from `lower_ty_common` that can be inferred from the HIR
...and then get rid of `lower_ty_common`.
r? ``@fmease`` or re-roll if you're busy!
Use subtyping for `UnsafeFnPointer` coercion, too
I overlooked this in #129059, which changed MIR typechecking to use subtyping for other fn pointer coercions.
Fixes#129285
Print the generic parameter along with the variance in dumps.
This allows to make sure we are testing what we think we are testing.
While the tests are correct, I discovered that opaque duplicated args are in the reverse declaration order.
Add a special case for `CStr`/`CString` in the `improper_ctypes` lint
Revives #120176. Just needed to bless a test and fix an argument, but seemed reasonable to me otherwise.
Instead of saying to "consider adding a `#[repr(C)]` or `#[repr(transparent)]` attribute to this struct", we now tell users to "Use `*const ffi::c_char` instead, and pass the value from `CStr::as_ptr()`" when the type involved is a `CStr` or a `CString`.
The suggestion is not made for `&mut CString` or `*mut CString`.
r? ``````@cjgillot`````` (since you were the reviewer of the original PR #120176, but feel free to reroll)
Detect `*` operator on `!Sized` expression
The suggestion is new:
```
error[E0277]: the size for values of type `str` cannot be known at compilation time
--> $DIR/unsized-str-in-return-expr-arg-and-local.rs:15:9
|
LL | let x = *"";
| ^ doesn't have a size known at compile-time
|
= help: the trait `Sized` is not implemented for `str`
= note: all local variables must have a statically known size
= help: unsized locals are gated as an unstable feature
help: references to `!Sized` types like `&str` are `Sized`; consider not dereferencing the expression
|
LL - let x = *"";
LL + let x = "";
|
```
Fix#128199.
remove invalid `TyCompat` relation for effects
if the current impl uses `Maybe` (`impl const`), the parent impl must use `Maybe` (`impl const`) as well.
I'd like to rename `TyCompat` to `Sub` which is probably clearer. But it would conflict with my other PR.
r? ``@rust-lang/project-const-traits``
Retroactively feature gate `ConstArgKind::Path`
This puts the lowering introduced by #125915 under a feature gate until we fix the regressions introduced by it. Alternative to whole sale reverting the PR since it didn't seem like a very clean revert and I think this is generally a step in the right direction and don't want to get stuck landing and reverting the PR over and over :)
cc #129137 ``@camelid,`` tests taken from there. beta is branching soon so I think it makes sense to not try and rush that fix through since it wont have much time to bake and if it has issues we can't simply revert it on beta.
Fixes#128016
make writes_through_immutable_pointer a hard error
This turns the lint added in https://github.com/rust-lang/rust/pull/118324 into a hard error. This has been reported in cargo's future-compat reports since Rust 1.76 (released in February). Given that const_mut_refs is still unstable, it should be impossible to even hit this error on stable: we did accidentally stabilize some functions that can cause this error, but that got reverted in https://github.com/rust-lang/rust/pull/117905. Still, let's do a crater run just to be sure.
Given that this should only affect unstable code, I don't think it needs an FCP, but let's Cc ``@rust-lang/lang`` anyway -- any objection to making this unambiguous UB into a hard error during const-eval? This can be viewed as part of https://github.com/rust-lang/rust/pull/129195 which is already nominated for discussion.
By keeping track of attributes that have been previously processed.
This fixes the `macro-rules-derive-cfg.stdout` test, and is necessary
for #124141 which removes nonterminals.
Also shrink the `SmallVec` inline size used in `IntervalSet`. 2 gives
slightly better perf than 4 now that there's an `IntervalSet` in
`Parser`, which is cloned reasonably often.
Documents that `BikeshedIntrinsicFrom` models transmute-via-union,
which is slightly more expressive than the transmute-via-cast
implemented by `transmute_copy`. Additionally, we provide an
implementation of transmute-via-union as a method on the
`BikeshedIntrinsicFrom` trait with additional documentation on
the boundary between trait invariants and caller obligations.
Whether or not transmute-via-union is the right kind of transmute
to model remains up for discussion [1]. Regardless, it seems wise
to document the present behavior.
[1] https://rust-lang.zulipchat.com/#narrow/stream/216762-project-safe-transmute/topic/What.20'kind'.20of.20transmute.20to.20model.3F/near/426331967
Rollup of 9 pull requests
Successful merges:
- #128511 (Document WebAssembly target feature expectations)
- #129243 (do not build `cargo-miri` by default on stable channel)
- #129263 (Add a missing compatibility note in the 1.80.0 release notes)
- #129276 (Stabilize feature `char_indices_offset`)
- #129350 (adapt integer comparison tests for LLVM 20 IR changes)
- #129408 (Fix handling of macro arguments within the `dropping_copy_types` lint)
- #129426 (rustdoc-search: use tighter json for names and parents)
- #129437 (Fix typo in a help diagnostic)
- #129457 (kobzol vacation)
r? `@ghost`
`@rustbot` modify labels: rollup
Fix handling of macro arguments within the `dropping_copy_types` lint
This PR fixes the handling of spans with different context (aka macro arguments) than the primary expression within the different `{drop,forget}ing_copy_types` and `{drop,forget}ing_references` lints.
<details>
<summary>Before</summary>
```
warning: calls to `std::mem::drop` with a value that implements `Copy` does nothing
--> drop_writeln.rs:5:5
|
5 | drop(writeln!(&mut msg, "test"));
| ^^^^^--------------------------^
| |
| argument has type `Result<(), std::fmt::Error>`
|
= note: `#[warn(dropping_copy_types)]` on by default
help: use `let _ = ...` to ignore the expression or result
--> /home/[..]/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/macros/mod.rs:688:9
|
68| let _ =
| ~~~~~~~
```
</details>
<details>
<summary>With this PR</summary>
```
warning: calls to `std::mem::drop` with a value that implements `Copy` does nothing
--> drop_writeln.rs:5:5
|
5 | drop(writeln!(&mut msg, "test"));
| ^^^^^--------------------------^
| |
| argument has type `Result<(), std::fmt::Error>`
|
= note: `#[warn(dropping_copy_types)]` on by default
help: use `let _ = ...` to ignore the expression or result
|
5 - drop(writeln!(&mut msg, "test"));
5 + let _ = writeln!(&mut msg, "test");
|
```
</details>
``````@rustbot`````` label +L-dropping_copy_types
- Trim some unnecessary fat from the type declaration.
- Add another attribute, to make it a stronger test of `cfg_attr`
processing. Note that the current output is incorrect, because it
duplicates the added attribute. The next commit will fix this.
This example triggers an assertion failure:
```
fn f() -> u32 {
#[cfg_eval] #[cfg(not(FALSE))] 0
}
```
The sequence of events:
- `configure_annotatable` calls `parse_expr_force_collect`, which calls
`collect_tokens`.
- Within that, we end up in `parse_expr_dot_or_call`, which again calls
`collect_tokens`.
- The return value of the `f` call is the expression `0`.
- This inner call collects tokens for `0` (parser range 10..11) and
creates a replacement covering `#[cfg(not(FALSE))] 0` (parser range
0..11).
- We return to the outer `collect_tokens` call. The return value of the
`f` call is *again* the expression `0`, again with the range 10..11,
but the replacement from earlier covers the range 0..11. The code
mistakenly assumes that any attributes from an inner `collect_tokens`
call fit entirely within the body of the result of an outer
`collect_tokens` call. So it adjusts the replacement parser range
0..11 to a node range by subtracting 10, resulting in -10..1. This is
an invalid range and triggers an assertion failure.
It's tricky to follow, but basically things get complicated when an AST
node is returned from an inner `collect_tokens` call and then returned
again from an outer `collect_token` node without being wrapped in any
kind of additional layer.
This commit changes `collect_tokens` to return early in some extra cases,
avoiding the construction of lazy tokens. In the example above, the
outer `collect_tokens` returns earlier because the `0` token already has
tokens and `self.capture_state.capturing` is `Capturing::No`. This early
return avoids the creation of the invalid range and the assertion
failure.
Fixes#129166. Note: these invalid ranges have been happening for a long
time. #128725 looks like it's at fault only because it introduced the
assertion that catches the invalid ranges.
Fix extern crates not being hidden with `doc(hidden)`
Fixes#126796.
Only the current crate should never be stripped, any other crate should be strippable.
r? ``@notriddle``
Migrate `x86_64-fortanix-unknown-sgx-lvi` `run-make` test to rmake
Part of #121876 and the associated [Google Summer of Code project](https://blog.rust-lang.org/2024/05/01/gsoc-2024-selected-projects.html).
The final Makefile! Every Makefile test is now claimed.
This is difficult to test due to the uncommon architecture it is specific to. I don't think it is in the CI (I didn't find it in `jobs.yml`, but if there is a way to test it, please do.
Locally, on Linux, it compiles and panics at the `llvm_filecheck` part (if I replace the `x86_64-fortanix-unknown-sgx` with `x86_64-unknown-linux-gnu`, of course), which is expected.
For this reason, the Makefile and associated script have been kept, but with a leading underscore.
Allow rust staticlib to work with MSVC's /WHOLEARCHIVE
This fixes#129020 by renaming the `__NULL_IMPORT_DESCRIPTOR` to prevent conflicts.
try-job: dist-i686-msvc
Rollup of 8 pull requests
Successful merges:
- #128432 (WASI: forbid `unsafe_op_in_unsafe_fn` for `std::{os, sys}`)
- #129373 (Add missing module flags for CFI and KCFI sanitizers)
- #129374 (Use `assert_unsafe_precondition!` in `AsciiChar::digit_unchecked`)
- #129376 (Change `assert_unsafe_precondition` docs to refer to `check_language_ub`)
- #129382 (Add `const_cell_into_inner` to `OnceCell`)
- #129387 (Advise against removing the remaining Python scripts from `tests/run-make`)
- #129388 (Do not rely on names to find lifetimes.)
- #129395 (Pretty-print own args of existential projections (dyn-Trait w/ GAT constraints))
r? `@ghost`
`@rustbot` modify labels: rollup
Pretty-print own args of existential projections (dyn-Trait w/ GAT constraints)
Previously we would just drop them. This bug isn't that significant as it can only be triggered by user code that constrains GATs inside trait object types which is currently gated under the interim feature `generic_associated_types_extended` (whose future is questionable) or on stable if the GATs are 'disabled' in dyn-Trait via `where Self: Sized` (in which case the assoc type bindings get ignored anyway (and trigger the warn-by-default lint `unused_associated_type_bounds`)), so yeah.
Affects diagnostic output and output of `std::any::type_name{_of_val}`.
Do not rely on names to find lifetimes.
For some reason, we were trying to find the lifetime parameter from its name, instead of using the def_id we have.
This PR uses it instead. This changes some ui tests, I think to be more sensible.
Advise against removing the remaining Python scripts from `tests/run-make`
After some recent PRs (e.g. #129185), there are only two Python scripts left in `tests/run-make`.
Having come so far, it's tempting to try to get rid of the remaining ones. But after trying that myself, I've come to the conclusion that it's not worth the extra hassle, especially if it means pulling in an XML-parsing crate just for one test.
This PR therefore leaves behind a few signpost comments to explain why getting rid of these particular scripts has low value.
Add missing module flags for CFI and KCFI sanitizers
Set the cfi-normalize-integers and kcfi-offset module flags when Control-Flow Integrity sanitizers are used, so functions generated by the LLVM backend use the same CFI/KCFI options as rustc.
cfi-normalize-integers tells LLVM to also use integer normalization for generated functions when -Zsanitizer-cfi-normalize-integers is used.
kcfi-offset specifies the number of prefix nops between the KCFI type hash and the function entry when -Z patchable-function-entry is used. Note that LLVM assumes all indirectly callable functions use the same number of prefix NOPs with -Zsanitizer=kcfi.
Trying to get rid of this Python script looks tempting, because it's currently
the only Python script in the whole `run-make` suite that we actually run.
But getting rid of it would require pulling in a Rust crate to parse XML
instead, and that's probably not worth the extra hassle for a relatively-minor
test.
Set the cfi-normalize-integers and kcfi-offset module flags when
Control-Flow Integrity sanitizers are used, so functions generated by
the LLVM backend use the same CFI/KCFI options as rustc.
cfi-normalize-integers tells LLVM to also use integer normalization
for generated functions when -Zsanitizer-cfi-normalize-integers is
used.
kcfi-offset specifies the number of prefix nops between the KCFI
type hash and the function entry when -Z patchable-function-entry is
used. Note that LLVM assumes all indirectly callable functions use the
same number of prefix NOPs with -Zsanitizer=kcfi.
bump conflicting_repr_hints lint to be shown in dependencies
This has been a future compatibility lint for years, let's bump it up to be shown in dependencies (so that hopefully we can then make it a hard error fairly soon).
Cc https://github.com/rust-lang/rust/issues/68585
Point at explicit `'static` obligations on a trait
Given `trait Any: 'static` and a `struct` with a `Box<dyn Any + 'a>` field, point at the `'static` bound in `Any` to explain why `'a: 'static`.
```
error[E0478]: lifetime bound not satisfied
--> f202.rs:2:12
|
2 | value: Box<dyn std::any::Any + 'a>,
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
note: lifetime parameter instantiated with the lifetime `'a` as defined here
--> f202.rs:1:14
|
1 | struct Hello<'a> {
| ^^
note: but lifetime parameter must outlive the static lifetime
--> /home/gh-estebank/rust/library/core/src/any.rs:113:16
|
113 | pub trait Any: 'static {
| ^^^^^^^
```
Partially address #33652.
Improve diagnostic-related lints: `untranslatable_diagnostic` & `diagnostic_outside_of_impl`
Summary:
- Made `untranslatable_diagnostic` point to problematic arguments instead of the function call
(I found this misleading while working on some `A-translation` PRs: my first impression was that
the methods themselves were not translation-aware and needed to be changed,
while in reality the problem was with the hardcoded strings passed as arguments).
- Made the shared pass of `untranslatable_diagnostic` & `diagnostic_outside_of_impl` more efficient.
`@rustbot` label D-imprecise-spans A-translation
use old ctx if has same expand environment during decode span
Fixes#112680
The root reason why #112680 failed with incremental compilation on the second attempt is the difference in `opaque` between the span of the field [`ident`](https://github.com/rust-lang/rust/blob/master/compiler/rustc_hir_typeck/src/expr.rs#L2348) and the span in the incremental cache at `tcx.def_ident_span(field.did)`.
- Let's call the span of `ident` as `span_a`, which is generated by [`apply_mark_internal`](https://github.com/rust-lang/rust/blob/master/compiler/rustc_span/src/hygiene.rs#L553-L554). Its content is similar to:
```rs
span_a_ctx -> SyntaxContextData {
opaque: span_a_ctx,
opaque_and_semitransparent: span_a_ctx,
// ....
}
```
- And call the span of `tcx.def_ident_span` as `span_b`, which is generated by [`decode_syntax_context`](https://github.com/rust-lang/rust/blob/master/compiler/rustc_span/src/hygiene.rs#L1390). Its content is:
```rs
span_b_ctx -> SyntaxContextData {
opaque: span_b_ctx,
// note `span_b_ctx` is not same as `span_a_ctx`
opaque_and_semitransparent: span_b_ctx,
// ....
}
```
Although they have the same `parent` (both refer to the root) and `outer_expn`, I cannot find the specific connection between them. Therefore, I chose a solution that may not be the best: give up the incremental compile cache to ensure we can use `span_a` in this case.
r? `@petrochenkov` Do you have any advice on this? Or perhaps this solution is acceptable?
Given `trait Any: 'static` and a `struct` with a `Box<dyn Any + 'a>` field, point at the `'static` bound in `Any` to explain why `'a: 'static`.
```
error[E0478]: lifetime bound not satisfied
--> f202.rs:2:12
|
2 | value: Box<dyn std::any::Any + 'a>,
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
note: lifetime parameter instantiated with the lifetime `'a` as defined here
--> f202.rs:1:14
|
1 | struct Hello<'a> {
| ^^
note: but lifetime parameter must outlive the static lifetime
--> /home/gh-estebank/rust/library/core/src/any.rs:113:16
|
113 | pub trait Any: 'static {
| ^^^^^^^
```
Partially address #33652.
CFI: Erase regions when projecting ADT to its transparent non-1zst field
The output from `FieldDef::ty` (or `TyCtxt::type_of`) may have free regions (well, `'static`) -- erase it.
Fixes#129169Fixes#123685
Special case DUMMY_SP to emit line 0/column 0 locations on DWARF platforms.
Line 0 has a special meaning in DWARF. From the version 5 spec:
The compiler may emit the value 0 in cases
where an instruction cannot be attributed to any
source line.
DUMMY_SP spans cannot be attributed to any line. However, because rustc internally stores line numbers starting at zero, lookup_debug_loc() adjusts every line number by one. Special casing DUMMY_SP to actually emit line 0 ensures rustc communicates to the debugger that there's no meaningful source code for this instruction, rather than telling the debugger to jump to line 1 randomly.
This commit adds the headers for the top level documentation to
rustdoc's existing table of contents, along with associated items.
It only show two levels of headers. Going further would require the
sidebar to be wider, and that seems unnecessary (the crates that
have manually-built TOCs usually don't need deeply nested headers).
Don't consider locals to shadow inner items' generics
We don't want to consider the bindings from a `RibKind::Module` itself, because for an inner item that module will contain the local bindings from the function body or wherever else the inner item is being defined.
Fixes#129265
r? petrochenkov
skip updating when external binding is existed
Fixes#128813
For following code:
```rs
extern crate core;
fn f() {
use ::core;
}
macro_rules! m {
() => {
extern crate std as core;
};
}
m!();
fn main() {}
```
- In the first loop, we define `extern crate core` and `use ::core` will be referred to `core` (yes, it does not consider if there are some macros that are not expanded. Ideally, this should be delayed if there are some unexpanded macros in the root, but I didn't change it like that because it seems like a huge change).
- Then `m` is expanded, which makes `extern_prelude('core')` return `std` rather than `core`, causing the inconsistency.
r? `@petrochenkov`
Don't generate functions with the `rustc_intrinsic_must_be_overridden` attribute
Functions with the attribute `rustc_intrinsic_must_be_overridden` never be called.
r? compiler
Stabilize opaque type precise capturing (RFC 3617)
This PR partially stabilizes opaque type *precise capturing*, which was specified in [RFC 3617](https://github.com/rust-lang/rfcs/pull/3617), and whose syntax was amended by FCP in [#125836](https://github.com/rust-lang/rust/issues/125836).
This feature, as stabilized here, gives us a way to explicitly specify the generic lifetime parameters that an RPIT-like opaque type captures. This solves the problem of overcapturing, for lifetime parameters in these opaque types, and will allow the Lifetime Capture Rules 2024 ([RFC 3498](https://github.com/rust-lang/rfcs/pull/3498)) to be fully stabilized for RPIT in Rust 2024.
### What are we stabilizing?
This PR stabilizes the use of a `use<'a, T>` bound in return-position impl Trait opaque types. Such a bound fully specifies the set of generic parameters captured by the RPIT opaque type, entirely overriding the implicit default behavior. E.g.:
```rust
fn does_not_capture<'a, 'b>() -> impl Sized + use<'a> {}
// ~~~~~~~~~~~~~~~~~~~~
// This RPIT opaque type does not capture `'b`.
```
The way we would suggest thinking of `impl Trait` types *without* an explicit `use<..>` bound is that the `use<..>` bound has been *elided*, and that the bound is filled in automatically by the compiler according to the edition-specific capture rules.
All non-`'static` lifetime parameters, named (i.e. non-APIT) type parameters, and const parameters in scope are valid to name, including an elided lifetime if such a lifetime would also be valid in an outlives bound, e.g.:
```rust
fn elided(x: &u8) -> impl Sized + use<'_> { x }
```
Lifetimes must be listed before type and const parameters, but otherwise the ordering is not relevant to the `use<..>` bound. Captured parameters may not be duplicated. For now, only one `use<..>` bound may appear in a bounds list. It may appear anywhere within the bounds list.
### How does this differ from the RFC?
This stabilization differs from the RFC in one respect: the RFC originally specified `use<'a, T>` as syntactically part of the RPIT type itself, e.g.:
```rust
fn capture<'a>() -> impl use<'a> Sized {}
```
However, settling on the final syntax was left as an open question. T-lang later decided via FCP in [#125836](https://github.com/rust-lang/rust/issues/125836) to treat `use<..>` as a syntactic bound instead, e.g.:
```rust
fn capture<'a>() -> impl Sized + use<'a> {}
```
### What aren't we stabilizing?
The key goal of this PR is to stabilize the parts of *precise capturing* that are needed to enable the migration to Rust 2024.
There are some capabilities of *precise capturing* that the RFC specifies but that we're not stabilizing here, as these require further work on the type system. We hope to lift these limitations later.
The limitations that are part of this PR were specified in the [RFC's stabilization strategy](https://rust-lang.github.io/rfcs/3617-precise-capturing.html#stabilization-strategy).
#### Not capturing type or const parameters
The RFC addresses the overcapturing of type and const parameters; that is, it allows for them to not be captured in opaque types. We're not stabilizing that in this PR. Since all in scope generic type and const parameters are implicitly captured in all editions, this is not needed for the migration to Rust 2024.
For now, when using `use<..>`, all in scope type and const parameters must be nameable (i.e., APIT cannot be used) and included as arguments. For example, this is an error because `T` is in scope and not included as an argument:
```rust
fn test<T>() -> impl Sized + use<> {}
//~^ ERROR `impl Trait` must mention all type parameters in scope in `use<...>`
```
This is due to certain current limitations in the type system related to how generic parameters are represented as captured (i.e. bivariance) and how inference operates.
We hope to relax this in the future, and this stabilization is forward compatible with doing so.
#### Precise capturing for return-position impl Trait **in trait** (RPITIT)
The RFC specifies precise capturing for RPITIT. We're not stabilizing that in this PR. Since RPITIT already adheres to the Lifetime Capture Rules 2024, this isn't needed for the migration to Rust 2024.
The effect of this is that the anonymous associated types created by RPITITs must continue to capture all of the lifetime parameters in scope, e.g.:
```rust
trait Foo<'a> {
fn test() -> impl Sized + use<Self>;
//~^ ERROR `use<...>` precise capturing syntax is currently not allowed in return-position `impl Trait` in traits
}
```
To allow this involves a meaningful amount of type system work related to adding variance to GATs or reworking how generics are represented in RPITITs. We plan to do this work separately from the stabilization. See:
- https://github.com/rust-lang/rust/pull/124029
Supporting precise capturing for RPITIT will also require us to implement a new algorithm for detecting refining capture behavior. This may involve looking through type parameters to detect cases where the impl Trait type in an implementation captures fewer lifetimes than the corresponding RPITIT in the trait definition, e.g.:
```rust
trait Foo {
fn rpit() -> impl Sized + use<Self>;
}
impl<'a> Foo for &'a () {
// This is "refining" due to not capturing `'a` which
// is implied by the trait's `use<Self>`.
fn rpit() -> impl Sized + use<>;
// This is not "refining".
fn rpit() -> impl Sized + use<'a>;
}
```
This stabilization is forward compatible with adding support for this later.
### The technical details
This bound is purely syntactical and does not lower to a [`Clause`](https://doc.rust-lang.org/1.79.0/nightly-rustc/rustc_middle/ty/type.ClauseKind.html) in the type system. For the purposes of the type system (and for the types team's curiosity regarding this stabilization), we have no current need to represent this as a `ClauseKind`.
Since opaques already capture a variable set of lifetimes depending on edition and their syntactical position (e.g. RPIT vs RPITIT), a `use<..>` bound is just a way to explicitly rather than implicitly specify that set of lifetimes, and this only affects opaque type lowering from AST to HIR.
### FCP plan
While there's much discussion of the type system here, the feature in this PR is implemented internally as a transformation that happens before lowering to the type system layer. We already support impl Trait types partially capturing the in scope lifetimes; we just currently only expose that implicitly.
So, in my (errs's) view as a types team member, there's nothing for types to weigh in on here with respect to the implementation being stabilized, and I'd suggest a lang-only proposed FCP (though we'll of course CC the team below).
### Authorship and acknowledgments
This stabilization report was coauthored by compiler-errors and TC.
TC would like to acknowledge the outstanding and speedy work that compiler-errors has done to make this feature happen.
compiler-errors thanks TC for authoring the RFC, for all of his involvement in this feature's development, and pushing the Rust 2024 edition forward.
### Open items
We're doing some things in parallel here. In signaling the intention to stabilize, we want to uncover any latent issues so we can be sure they get addressed. We want to give the maximum time for discussion here to happen by starting it while other remaining miscellaneous work proceeds. That work includes:
- [x] Look into `syn` support.
- https://github.com/dtolnay/syn/issues/1677
- https://github.com/dtolnay/syn/pull/1707
- [x] Look into `rustfmt` support.
- https://github.com/rust-lang/rust/pull/126754
- [x] Look into `rust-analyzer` support.
- https://github.com/rust-lang/rust-analyzer/issues/17598
- https://github.com/rust-lang/rust-analyzer/pull/17676
- [x] Look into `rustdoc` support.
- https://github.com/rust-lang/rust/issues/127228
- https://github.com/rust-lang/rust/pull/127632
- https://github.com/rust-lang/rust/pull/127658
- [x] Suggest this feature to RfL (a known nightly user).
- [x] Add a chapter to the edition guide.
- https://github.com/rust-lang/edition-guide/pull/316
- [x] Update the Reference.
- https://github.com/rust-lang/reference/pull/1577
### (Selected) implementation history
* https://github.com/rust-lang/rfcs/pull/3498
* https://github.com/rust-lang/rfcs/pull/3617
* https://github.com/rust-lang/rust/pull/123468
* https://github.com/rust-lang/rust/issues/125836
* https://github.com/rust-lang/rust/pull/126049
* https://github.com/rust-lang/rust/pull/126753Closes#123432.
cc `@rust-lang/lang` `@rust-lang/types`
`@rustbot` labels +T-lang +I-lang-nominated +A-impl-trait +F-precise_capturing
Tracking:
- https://github.com/rust-lang/rust/issues/123432
----
For the compiler reviewer, I'll leave some inline comments about diagnostics fallout :^)
r? compiler
This approach is, roughly, based on how Discourse does it.
It came up while discussing some other possible sidebar changes,
as a design that made rapid scanning easier while avoiding the
inherent trade-offs in summarizing.
Added "copy" to Debug fmt for copy operands
In MIR's debug mode (--emit mir) the printing for Operands is slightly inconsistent.
The RValues - values on the right side of an Assign - are usually printed with their Operand when they are Places.
Example:
_2 = move _3
But for arguments, the operand is omitted.
_2 = _1
I propose a change be made, to display the place with the operand.
_2 = copy _1
Move and copy have different semantics, meaning this difference is important and helpful to the user. It also adds consistency to the pretty printing.
-- EDIT --
Consider this example Rust program and its MIR output with the **updated pretty printer.**
This was generated with the arguments --emit mir --crate-type lib -Zmir-opt-level=0 (Otherwise, it's optimised away since it's a junk program).
```rust
fn main(foo: i32) {
let v = 10;
if v == 20 {
foo;
}
else {
v;
}
}
```
```MIR
// WARNING: This output format is intended for human consumers only
// and is subject to change without notice. Knock yourself out.
fn main(_1: i32) -> () {
debug foo => _1;
let mut _0: ();
let _2: i32;
let mut _3: bool;
let mut _4: i32;
let _5: i32;
let _6: i32;
scope 1 {
debug v => _2;
}
bb0: {
StorageLive(_2);
_2 = const 10_i32;
StorageLive(_3);
StorageLive(_4);
_4 = copy _2;
_3 = Eq(move _4, const 20_i32);
switchInt(move _3) -> [0: bb2, otherwise: bb1];
}
bb1: {
StorageDead(_4);
StorageLive(_5);
_5 = copy _1;
StorageDead(_5);
_0 = const ();
goto -> bb3;
}
bb2: {
StorageDead(_4);
StorageLive(_6);
_6 = copy _2;
StorageDead(_6);
_0 = const ();
goto -> bb3;
}
bb3: {
StorageDead(_3);
StorageDead(_2);
return;
}
}
```
In this example program, we can see that when we move a place, it is preceded by "move". e.g. ``` _3 = Eq(move _4, const 20_i32);```. However, when we copy a place such as ```_5 = _1;```, it is not preceded by the operand in the original printout. I propose to change the print to include the copy ```_5 = copy _1``` as in this example.
Regarding the arguments part. When I originally submitted this PR, I was under the impression this only affected the print for arguments to a function, but actually, it affects anything that uses a copy. This is preferable anyway with regard to consistency. The PR is about making ```copy``` explicit.
safe transmute: check lifetimes
Modifies `BikeshedIntrinsicFrom` to forbid lifetime extensions on references. This static check can be opted out of with the `Assume::lifetimes` flag.
Fixes#129097
Tracking Issue: https://github.com/rust-lang/rust/issues/99571
r? `@compiler-errors`
Delete debuginfo test suite infra for gdb without Rust support and lldb with Rust support
Implements https://github.com/rust-lang/rust/issues/128953
I also deleted all the `min-lldb-version: 310` comments, because the oldest compatible distro I can find is Ubuntu 16.04 which ships lldb 3.8, though of course the package that the Ubuntu maintainers put together for that is broken.
Rocky Linux 8 amusingly ships lldb 17, even though it has a similar glibc and kernel version.
This PR is multiple highly mechanical changes. Some of the commits were created by just running `sed`. You may find it easier to review each commit separately.
Switch to using the v2 resolver in most workspaces
Pinning the resolver to v1 was done in 5abff3753a ("Explicit set workspace.resolver ...") in order to suppress warnings. Since there is no specific reason not to use the new resolver and since it fixes issues, change to `resolver = "2"` everywhere except library.
Fix order of normalization and recursion in const folding.
Fixes#126831.
Without this patch, type normalization is not always idempotent, which leads to all sorts of bugs in places that assume that normalizing a normalized type does nothing.
Tracking issue: https://github.com/rust-lang/rust/issues/95174
r? BoxyUwU
Suggest adding Result return type for associated method in E0277.
Recommit #126515 because I messed up during rebase,
Suggest adding Result return type for associated method in E0277.
For following:
```rust
struct A;
impl A {
fn test4(&self) {
let mut _file = File::create("foo.txt")?;
//~^ ERROR the `?` operator can only be used in a method
}
```
Suggest:
```rust
impl A {
fn test4(&self) -> Result<(), Box<dyn std::error::Error>> {
let mut _file = File::create("foo.txt")?;
//~^ ERROR the `?` operator can only be used in a method
Ok(())
}
}
```
For #125997
r? `@cjgillot`
Stabilize `raw_ref_op` (RFC 2582)
This stabilizes the syntax `&raw const $expr` and `&raw mut $expr`. It has existed unstably for ~4 years now, and has been exposed on stable via the `addr_of` and `addr_of_mut` macros since Rust 1.51 (released more than 3 years ago). I think it has become clear that these operations are here to stay. So it is about time we give them proper primitive syntax. This has two advantages over the macro:
- Being macros, `addr_of`/`addr_of_mut` could in theory do arbitrary magic with the expression on which they work. The only "magic" they actually do is using the argument as a place expression rather than as a value expression. Place expressions are already a subtle topic and poorly understood by many programmers; having this hidden behind a macro using unstable language features makes this even worse. Conversely, people do have an idea of what happens below `&`/`&mut`, so we can make the subtle topic a lot more approachable by connecting to existing intuition.
- The name `addr_of` is quite unfortunate from today's perspective, given that we have accepted provenance as a reality, which means that a pointer is *not* just an address. Strict provenance has a method, `addr`, which extracts the address of a pointer; using the term `addr` in two different ways is quite unfortunate. That's why this PR soft-deprecates `addr_of` -- we will wait a long time before actually showing any warning here, but we should start telling people that the "addr" part of this name is somewhat misleading, and `&raw` avoids that potential confusion.
In summary, this syntax improves developers' ability to conceptualize the operational semantics of Rust, while making a fundamental operation frequently used in unsafe code feel properly built in.
Possible questions to consider, based on the RFC and [this](https://github.com/rust-lang/rust/issues/64490#issuecomment-1163802912) great summary by `@CAD97:`
- Some questions are entirely about the semantics. The semantics are the same as with the macros so I don't think this should have any impact on this syntax PR. Still, for completeness' sake:
- Should `&raw const *mut_ref` give a read-only pointer?
- Tracked at: https://github.com/rust-lang/unsafe-code-guidelines/issues/257
- I think ideally the answer is "no". Stacked Borrows says that pointer is read-only, but Tree Borrows says it is mutable.
- What exactly does `&raw const (*ptr).field` require? Answered in [the reference](https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html): the arithmetic to compute the field offset follows the rules of `ptr::offset`, making it UB if it goes out-of-bounds. Making this a safe operation (using `wrapping_offset` rules) is considered too much of a loss for alias analysis.
- Choose a different syntax? I don't want to re-litigate the RFC. The only credible alternative that has been proposed is `&raw $place` instead of `&raw const $place`, which (IIUC) could be achieved by making `raw` a contextual keyword in a new edition. The type is named `*const T`, so the explicit `const` is consistent in that regard. `&raw expr` lacks the explicit indication of immutability. However, `&raw const expr` is quite a but longer than `addr_of!(expr)`.
- Shouldn't we have a completely new, better raw pointer type instead? Yes we all want to see that happen -- but I don't think we should block stabilization on that, given that such a nicer type is not on the horizon currently and given the issues with `addr_of!` mentioned above. (If we keep the `&raw $place` syntax free for this, we could use it in the future for that new type.)
- What about the lint the RFC talked about? It hasn't been implemented yet. Given that the problematic code is UB with or without this stabilization, I don't think the lack of the lint should block stabilization.
- I created an issue to track adding it: https://github.com/rust-lang/rust/issues/127724
- Other points from the "future possibilites of the RFC
- "Syntactic sugar" extension: this has not been implemented. I'd argue this is too confusing, we should stick to what the RFC suggested and if we want to do anything about such expressions, add the lint.
- Encouraging / requiring `&raw` in situations where references are often/definitely incorrect: this has been / is being implemented. On packed fields this already is a hard error, and for `static mut` a lint suggesting raw pointers is being rolled out.
- Lowering of casts: this has been implemented. (It's also an invisible implementation detail.)
- `offsetof` woes: we now have native `offset_of` so this is not relevant any more.
To be done before landing:
- [x] Suppress `unused_parens` lint around `&raw {const|mut}` expressions
- See bottom of https://github.com/rust-lang/rust/pull/127679#issuecomment-2264073752 for rationale
- Implementation: https://github.com/rust-lang/rust/pull/128782
- [ ] Update the Reference.
- https://github.com/rust-lang/reference/pull/1567
Fixes https://github.com/rust-lang/rust/issues/64490
cc `@rust-lang/lang` `@rust-lang/opsem`
try-job: x86_64-msvc
try-job: test-various
try-job: dist-various-1
try-job: armhf-gnu
try-job: aarch64-apple
`pulldown-cmark` has slightly different behavior between 0.11.0 and
0.11.2, causing one of the `unportable-markdown` tests to no longer emit
an error. Per [1], remove the error annotation and bless the output.
[1]: https://github.com/rust-lang/rust/pull/128722#issuecomment-2295522292
Move ZST ABI handling to `rustc_target`
Currently, target specific handling of ZST function call ABI (specifically passing them indirectly instead of ignoring them) is handled in `rustc_ty_utils`, whereas all other target specific function call ABI handling is located in `rustc_target`. This PR moves the ZST handling to `rustc_target` so that all the target-specific function call ABI handling is in one place. In the process of doing so, this PR fixes#125850 by ensuring that ZST arguments are always correctly ignored in the x86-64 `"sysv64"` ABI; any code which would be affected by this fix would have ICEd before this PR. Tests are also added using `#[rustc_abi(debug)]` to ensure this behaviour does not regress.
Fixes#125850
Modifies `BikeshedIntrinsicFrom` to forbid lifetime extensions on
references. This static check can be opted out of with the
`Assume::lifetimes` flag.
Fixes#129097
Disable `dump-ice-to-disk` for i686-mingw (again)
To avoid blocking full CI or `i686-mingw` try jobs (failed in https://github.com/rust-lang/rust/pull/127679#issuecomment-2295184771).
At least we now have some context for why the assertion failed.
Anyone with r+ can approve this.
Port `run-make/libtest-json/validate_json.py` to Rust
This is a trivial Python script that simply tries to parse each line of stdin (i.e. the test process output) as JSON, to verify that the overall output is JSON Lines.
We can perform the same check directly in `rmake.rs` using `serde_json`.
r? ````@jieyouxu````
Fix `is_val_statically_known` for floats
The LLVM intrinsic name for floats differs from the LLVM type name, so handle them explicitly. Also adds support for `f16` and `f128`.
`f16`/`f128` tracking issue: #116909
Re-enable more debuginfo tests on Windows
These tests used to be disabled on all Windows hosts. Now they're fully enabled or just disabled on windows-gnu with an issue citation that clearly explains why.
The changes in this PR are not tested by PR CI, but I've tested it using try-jobs below.
try-job: i686-msvc
try-job: i686-mingw
try-job: x86_64-mingw
try-job: x86_64-msvc
Re-enable `dump-ice-to-disk` for Windows
This test was previously flakey on `i686-mingw` (reason unknown), but since some modifications (quarantining each ICE test in separate tmp dirs, adding/removing `RUSTC_ICE` env vars as suitable to prevent any kind of environmental influence), I could no longer make it fail on `i686-mingw`.
I tried running this test (without the `ignore-windows` of course) a bunch of times via `i686-mingw` try jobs and it refused to fail (see #128958). I was also never able to reproduce the failure locally.
In any case, if this turns out to be still flakey on `i686-mingw`, we can revert the removal of `ignore-windows` but this time we'll have way more context for why the test failed.
Running the `i686-mingw` alongside some Windows jobs for basic santiy check. But the try jobs succeeding is insufficient to guarantee reproducibility.
cc #129115 for backlink.
try-job: x86_64-msvc
try-job: x86_64-mingw
try-job: i686-msvc
try-job: i686-mingw
Stabilize `unsafe_attributes`
# Stabilization report
## Summary
This is a tracking issue for the RFC 3325: unsafe attributes
We are stabilizing `#![feature(unsafe_attributes)]`, which makes certain attributes considered 'unsafe', meaning that they must be surrounded by an `unsafe(...)`, as in `#[unsafe(no_mangle)]`.
RFC: rust-lang/rfcs#3325
Tracking issue: #123757
## What is stabilized
### Summary of stabilization
Certain attributes will now be designated as unsafe attributes, namely, `no_mangle`, `export_name`, and `link_section` (stable only), and these attributes will need to be called by surrounding them in `unsafe(...)` syntax. On editions prior to 2024, this is simply an edition lint, but it will become a hard error in 2024. This also works in `cfg_attr`, but `unsafe` is not allowed for any other attributes, including proc-macros ones.
```rust
#[unsafe(no_mangle)]
fn a() {}
#[cfg_attr(any(), unsafe(export_name = "c"))]
fn b() {}
```
For a table showing the attributes that were considered to be included in the list to require unsafe, and subsequent reasoning about why each such attribute was or was not included, see [this comment here](https://github.com/rust-lang/rust/pull/124214#issuecomment-2124753464)
## Tests
The relevant tests are in `tests/ui/rust-2024/unsafe-attributes` and `tests/ui/attributes/unsafe`.
Fixes#126831.
Without this patch, type normalization is not always idempotent, which
leads to all sorts of bugs in places that assume that normalizing a
normalized type does nothing.
Use `FnSig` instead of raw `FnDecl` for `ForeignItemKind::Fn`, fix ICE for `Fn` trait error on safe foreign fn
Let's use `hir::FnSig` instead of `hir::FnDecl + hir::Safety` for `ForeignItemKind::Fn`. This consolidates some handling code between normal fns and foreign fns.
Separetly, fix an ICE where we weren't handling `Fn` trait errors for safe foreign fns.
If perf is bad for the first commit, I can rework the ICE fix to not rely on it. But if perf is good, I prefer we fix and clean up things all at once 👍
r? spastorino
Fixes#128764
Rollup of 6 pull requests
Successful merges:
- #128989 (Emit an error for invalid use of the linkage attribute)
- #129167 (mir/pretty: use `Option` instead of `Either<Once, Empty>`)
- #129168 (Return correct HirId when finding body owner in diagnostics)
- #129191 (rustdoc-json: Clean up serialization and printing.)
- #129192 (Remove useless attributes in merged doctest generated code)
- #129196 (Remove a useless ref/id/ref round-trip from `pattern_from_hir`)
r? `@ghost`
`@rustbot` modify labels: rollup
Return correct HirId when finding body owner in diagnostics
Fixes#129145Fixes#128810
r? ```@compiler-errors```
```rust
fn generic<const N: u32>() {}
trait Collate<const A: u32> {
type Pass;
fn collate(self) -> Self::Pass;
}
impl<const B: u32> Collate<B> for i32 {
type Pass = ();
fn collate(self) -> Self::Pass {
generic::<{ true }>()
//~^ ERROR: mismatched types
}
}
```
When type checking the `{ true }` anon const we would error with a type mismatch. This then results in diagnostics code attempting to check whether its due to a type mismatch with the return type. That logic was implemented by walking up the hir until we reached the body owner, except instead of using the `enclosing_body_owner` function it special cased various hir nodes incorrectly resulting in us walking out of the anon const and stopping at `fn collate` instead.
This then resulted in diagnostics logic inside of the anon consts `ParamEnv` attempting to do trait solving involving the `<i32 as Collate<B>>::Pass` type which ICEs because it is in the wrong environment.
I have rewritten this function to just walk up until it hits the `enclosing_body_owner` and made some other changes since I found this pretty hard to read/understand. Hopefully it's easier to understand now, it also makes it more obvious that this is not implemented in a very principled way and is definitely missing cases :)
Emit an error for invalid use of the linkage attribute
fixes#128486
Currently, the use of the linkage attribute for Mod, Impl,... is incorrectly permitted. This PR will correct this issue by generating errors, and I've also added some UI test cases for it.
Related: #128552.
Detect multiple crate versions on method not found
When a type comes indirectly from one crate version but the imported trait comes from a separate crate version, the called method won't be found. We now show additional context:
```
error[E0599]: no method named `foo` found for struct `dep_2_reexport::Type` in the current scope
--> multiple-dep-versions.rs:8:10
|
8 | Type.foo();
| ^^^ method not found in `Type`
|
note: there are multiple different versions of crate `dependency` in the dependency graph
--> multiple-dep-versions.rs:4:32
|
4 | use dependency::{do_something, Trait};
| ^^^^^ `dependency` imported here doesn't correspond to the right crate version
|
::: ~/rust/build/x86_64-unknown-linux-gnu/test/run-make/crate-loading/rmake_out/multiple-dep-versions-1.rs:4:1
|
4 | pub trait Trait {
| --------------- this is the trait that was imported
|
::: ~/rust/build/x86_64-unknown-linux-gnu/test/run-make/crate-loading/rmake_out/multiple-dep-versions-2.rs:4:1
|
4 | pub trait Trait {
| --------------- this is the trait that is needed
5 | fn foo(&self);
| --- the method is available for `dep_2_reexport::Type` here
```
Fix#128569, fix#110926, fix#109161, fix#81659, fix#51458, fix#32611. Follow up to #124944.
float to/from bits and classify: update for float semantics RFC
With https://github.com/rust-lang/rfcs/pull/3514 having been accepted, it is clear that hardware which e.g. flushes subnormal to zero is just non-conformant from a Rust perspective -- this is a hardware bug, or maybe an LLVM backend bug (where LLVM doesn't lower floating-point ops in a way that they have the standardized behavior). So update the comments here to make it clear that we don't have to do any of this, we're just being nice.
Also remove the subnormal/NaN checks from the (unstable) const-version of to/from-bits; they are not needed since we decided with the aforementioned RFC that it is okay to get a different result at const-time and at run-time.
r? `@workingjubilee` since I think you wrote many of the comments I am editing here.
This is a trivial Python script that simply tries to parse each line of stdin
(i.e. the test process output) as JSON, to verify that the overall output is
JSON Lines.
We can perform the same check directly in `rmake.rs` using `serde_json`.
Fix wrong source location for some incorrect macro definitions
Fixes#95463
Currently the code will consume the next token tree after `var` when trying to parse `$var:some_type` even when it's not a `:` (e.g. a `$` when input is `($foo $bar:tt) => {}`). Additionally it will return the wrong span when it's not a `:`.
This PR fixes these problems.
Migrate `validate_json.py` script to rust in `run-make/rustdoc-map-file` test
This PR fixes the FIXME I added for future-me who become present-me. :')
Since there are multiple `run-make` tests using python scripts, I suppose more of them will migrate to Rust, hence why I added the `jzon` public reexport to the `run-make-support` crate.
cc `@jieyouxu`
r? `@Kobzol`
Special-case alias ty during the delayed bug emission in `try_from_lit`
This PR tries to fix#116308.
A delayed bug in `try_from_lit` will not be emitted so that the compiler will not ICE when it sees the pair `(ast::LitKind::Int, ty::TyKind::Alias)` in `lit_to_const` (called from `try_from_lit`).
This PR is related to an unstable feature `adt_const_params` (#95174).
r? ``@BoxyUwU``
Enable debuginfo tests that have been "temporarily disabled" for the past 6 years
The PR history is a bit of a mess because I had to test this a lot with try-jobs, so I'll try to summarize the non-obvious changes here.
A number of tests now have `min-lldb-version: 1800`. Those tests should have gotten an lldb version jump either in https://github.com/rust-lang/rust/pull/124781 or long ago. Note that all such tests with that lldb version requirement do not run in Apple CI.
`tests/debuginfo/drop-locations.rs` is staying disabled for now because gdb doesn't know to stop on the drop calls produced by a `}`: https://github.com/rust-lang/rust/issues/128971
`tests/debuginfo/function-arg-initialization.rs` now has `-Zmir-enable-passes=-SingleUseConsts`; without that we initialize the const before the function prelude: https://github.com/rust-lang/rust/issues/128945
`tests/debuginfo/by-value-non-immediate-argument.rs` fails because we don't generate a function prelude for unused non-immediate arguments, even with all optimizations disabled, and this seems to confuse debuggers on aarch64: https://github.com/rust-lang/rust/issues/128973
`tests/debuginfo/pretty-std.rs` is staying disabled on windows-gnu because our test harness doesn't know how to load our pretty-printers on that target: https://github.com/rust-lang/rust/issues/128981
`tests/debuginfo/method-on-enum.rs` and `tests/debuginfo/option-like-enum.rs` encounter some kind of gdb bug on i686-pc-windows-gnu. I don't know enough about that situation to write a good issue.
I plan on doing more work on this test suite. There's clearly a lot more basic cleanup work to do here.
Rollup of 9 pull requests
Successful merges:
- #128064 (Improve docs for Waker::noop and LocalWaker::noop)
- #128922 (rust-analyzer: use in-tree `pattern_analysis` crate)
- #128965 (Remove `print::Pat` from the printing of `WitnessPat`)
- #129018 (Migrate `rlib-format-packed-bundled-libs` and `native-link-modifier-bundle` `run-make` tests to rmake)
- #129037 (Port `run-make/libtest-json` and `run-make/libtest-junit` to rmake)
- #129078 (`ParamEnvAnd::fully_perform`: we have an `ocx`, use it)
- #129110 (Add a comment explaining the return type of `Ty::kind`.)
- #129111 (Port the `sysroot-crates-are-unstable` Python script to rmake)
- #129135 (crashes: more tests)
r? `@ghost`
`@rustbot` modify labels: rollup
Port the `sysroot-crates-are-unstable` Python script to rmake
New version of #126231, and a follow-up to #129071.
One major difference is that the new version no longer tries to report *all* accidentally-stable crates, because the `run_make_support` helpers tend to halt the test as soon as something goes wrong. That's unfortunate, but I think it won't matter much in practice, and preserving the old behaviour doesn't seem worth the extra effort.
---
Part of #110479 (Python purge), with this being one of the non-trivial Python scripts that actually seems feasible and worthwhile to remove.
This is *not* part of #121876 (Makefile purge), because the underlying test is already using rmake; this PR just modifies the existing rmake recipe to do all the work itself instead of delegating to Python. So there's no particular urgency here.
r? ````@jieyouxu````
try-job: aarch64-gnu
try-job: aarch64-apple
try-job: test-various
try-job: armhf-gnu
try-job: x86_64-msvc
try-job: i686-mingw
Port `run-make/libtest-json` and `run-make/libtest-junit` to rmake
Unlike #126773, this is just a straightforward port to `rmake`, without attempting to switch to compiletest or get rid of the (trivial) Python scripts.
Part of #121876.
r? ````@jieyouxu````
try-job: x86_64-msvc
try-job: i686-mingw
try-job: test-various
try-job: aarch64-gnu
try-job: aarch64-apple
Fix problems with assoc expr token collection
There are several cases involving assoc exprs and attributes where the current code does the wrong thing. This PR adds some tests that demonstrate the problems and then fixes them.
r? `@petrochenkov`
This commit does the following.
- Renames `collect_tokens_trailing_token` as `collect_tokens`, because
(a) it's annoying long, and (b) the `_trailing_token` bit is less
accurate now that its types have changed.
- In `collect_tokens`, adds a `Option<CollectPos>` argument and a
`UsePreAttrPos` in the return type of `f`. These are used in
`parse_expr_force_collect` (for vanilla expressions) and in
`parse_stmt_without_recovery` (for two different cases of expression
statements). Together these ensure are enough to fix all the problems
with token collection and assoc expressions. The changes to the
`stringify.rs` test demonstrate some of these.
- Adds a new test. The code in this test was causing an assertion
failure prior to this commit, due to an invalid `NodeRange`.
The extra complexity is annoying, but necessary to fix the existing
problems.
Coalesce `dep-info`, `dep-info-spaces` and `dep-info-doesnt-run-much` `run-make` tests into `dep-info` rmake.rs
Part of #121876 and the associated [Google Summer of Code project](https://blog.rust-lang.org/2024/05/01/gsoc-2024-selected-projects.html).
This is one of the most ancient tests in the `run-make` directory and its Makefile does some unexpected things, like creating and deleting a `done` directory over and over, sleeping at certain times (this is the [commit](0d9fd8e2a1) that added the `sleep`).
I tried to preserve the intent of the test, which is smoke-testing that `dep-info` works.
try-job: x86_64-msvc
try-job: i686-mingw
try-job: aarch64-gnu
try-job: aarch64-apple
try-job: test-various
try-job: armhf-gnu
try-job: dist-various-1
Remove duplicated `Rustdoc::output` method from `run-make-support` lib
I discovered recently that `--output` is deprecated in rustdoc and that `--out-dir` is doing the exact same thing. To keep things along with the current rustdoc status, I removed the `Rustdoc::output` method.
cc `@jieyouxu`
r? `@Kobzol`
Fix projections when parent capture is by-ref but child capture is by-value in the `ByMoveBody` pass
This fixes a somewhat strange bug where we build the incorrect MIR in #129074. This one is weird, but I don't expect it to actually matter in practice since it almost certainly results in a move error in borrowck. However, let's not ICE.
Given the code:
```
#![feature(async_closure)]
// NOT copy.
struct Ty;
fn hello(x: &Ty) {
let c = async || {
*x;
//~^ ERROR cannot move out of `*x` which is behind a shared reference
};
}
fn main() {}
```
The parent coroutine-closure captures `x: &Ty` by-ref, resulting in an upvar of `&&Ty`. The child coroutine captures `x` by-value, resulting in an upvar of `&Ty`. When constructing the by-move body for the coroutine-closure, we weren't applying an additional deref projection to convert the parent capture into the child capture, resulting in an type error in assignment, which is a validation ICE.
As I said above, this only occurs (AFAICT) in code that eventually results in an error, because it is only triggered by HIR that attempts to move a non-copy value out of a ref. This doesn't occur if `Ty` is `Copy`, since we'd instead capture `x` by-ref in the child coroutine.
Fixes#129074
Infer async closure args from `Fn` bound even if there is no corresponding `Future` bound on return
In #127482, I implemented the functionality to infer an async closure signature when passed into a function that has `Fn` + `Future` where clauses that look like:
```
fn whatever(callback: F)
where
F: Fn(Arg) -> Fut,
Fut: Future<Output = Out>,
```
However, #127781 demonstrates that this is still incomplete to address the cases users care about. So let's not bail when we fail to find a `Future` bound, and try our best to just use the args from the `Fn` bound if we find it. This is *fine* since most users of closures only really care about the *argument* types for inference guidance, since we require the receiver of a `.` method call to be known in order to probe methods.
When I experimented with programmatically rewriting `|| async {}` to `async || {}` in #127827, this also seems to have fixed ~5000 regressions (probably all coming from usages `TryFuture`/`TryStream` from futures-rs): the [before](https://github.com/rust-lang/rust/pull/127827#issuecomment-2254061733) and [after](https://github.com/rust-lang/rust/pull/127827#issuecomment-2255470176) crater runs.
Fixes#127781.