Add `-Zstack-protector` test for Windows targets
Add variants of the `stack-protector-heuristics-effect.rs` test for 32-bit and 64-bit MSVC Windows and update the original test to run on GNU Windows targets.
I added two tests instead of trying to modify the original because:
- MSVC uses a different function name (`__security_check_cookie` to perform the test rather than doing the test inline and calling `__stack_chk_fail`).
- LLVM's stack protection pass doesn't currently support generating checks for [frames with funclet based EH personality](37fd3c96b9/llvm/lib/CodeGen/StackProtector.cpp (L103C1-L109C4)).
- 32-bit Windows uses classic EH while 64-bit Windows uses table-based EH which results in slightly different codegen.
[CI run with test passing on {i686,x86_64}-{msvc,mingw}](https://github.com/rust-lang/rust/actions/runs/6275450644/job/17042958375?pr=116037)
Don't ICE when encountering unresolved regions in `fully_resolve`
We can encounter unresolved regions due to unconstrained impl lifetime arguments because `collect_return_position_impl_trait_in_trait_tys` runs before WF actually checks that the impl is well-formed.
Fixes#116525
Bump `COINDUCTIVE_OVERLAP_IN_COHERENCE` to deny + warn in deps
1.73 is the first place this shows up in stable (recall that there was only 1 regression), so let's bump this to deny on nightly.
r? lcnr
coverage: Move most per-function coverage info into `mir::Body`
Currently, all of the coverage information collected by the `InstrumentCoverage` pass is smuggled through MIR in the form of individual `StatementKind::Coverage` statements, which must then be reassembled by coverage codegen.
That's awkward for a number of reasons:
- While some of the coverage statements do care about their specific position in the MIR control-flow graph, many of them don't, and are just tacked onto the function's first BB as metadata carriers.
- MIR inlining can result in coverage statements being duplicated, so coverage codegen has to jump through hoops to avoid emitting duplicate mappings.
- MIR optimizations that would delete coverage statements need to carefully copy them into the function's first BB so as not to omit them from coverage reports.
- The order in which coverage codegen sees coverage statements is dependent on MIR optimizations/inlining, which can cause unnecessary churn in the emitted coverage mappings.
- We don't have a good way to annotate MIR-level functions with extra coverage info that doesn't belong in a statement.
---
This PR therefore takes most of the per-function coverage info and stores it in a field in `mir::Body` as `Option<Box<FunctionCoverageInfo>>`.
(This adds one pointer to the size of `mir::Body`, even when coverage is not enabled.)
Coverage statements still need to be injected into MIR in some cases, but only when they actually affect codegen (counters) or are needed to detect code that has been optimized away as unreachable (counters/expressions).
---
By the end of this PR, the information stored in `FunctionCoverageInfo` is:
- A hash of the function's source code (needed by LLVM's coverage map format)
- The number of coverage counters added by coverage instrumentation
- A table of coverage expressions, associating each expression ID with its operator (add or subtract) and its two operands
- The list of mappings, associating each covered code region with a counter/expression/zero value
---
~~This is built on top of #115301, so I'll rebase and roll a reviewer once that lands.~~
r? `@ghost`
`@rustbot` label +A-code-coverage
Even though expression details are now stored in the info structure, we still
need to inject `ExpressionUsed` statements into MIR, because if one is missing
during codegen then we know that it was optimized out and we can remap all of
its associated code regions to zero.
Previously, mappings were attached to individual coverage statements in MIR.
That necessitated special handling in MIR optimizations to avoid deleting those
statements, since otherwise codegen would be unable to reassemble the original
list of mappings.
With this change, a function's list of mappings is now attached to its MIR
body, and survives intact even if individual statements are deleted by
optimizations.
Use `YYYY-MM-DDTHH_MM_SS` as datetime format for ICE dump files
Windows paths do not support `:`, so use a datetime format in ICE dump paths that Windows will accept.
CC #116809, fix#115180.
Normalize alloc-id in tests.
AllocIds are globally numbered in a rustc invocation. This makes them very sensitive to changes unrelated to what is being tested. This commit normalizes them by renumbering, in order of appearance in the output.
The renumbering allows to keep the identity, that a simple `allocN` wouldn't. This is useful when we have memory dumps.
cc `@saethlin`
r? `@oli-obk`
Implement an internal lint encouraging use of `Span::eq_ctxt`
Adds a new Rustc internal lint that forbids use of `.ctxt() == .ctxt()` for spans, encouraging use of `.eq_ctxt()` instead (see https://github.com/rust-lang/rust/issues/49509).
Also fixed a few violations of the lint in the Rustc codebase (a fun additional way I could test my code). Edit: MIR opt folks I believe that's why you're CC'ed, just a heads up.
Two things I'm not sure about:
1. The way I chose to detect calls to `Span::ctxt`. I know adding diagnostic items to methods is generally discouraged, but after some searching and experimenting I couldn't find anything else that worked, so I went with it. That said, I'm happy to implement something different if there's a better way out there. (For what it's worth, if there is a better way, it might be worth documenting in the rustc-dev-guide, which I'm happy to take care of)
2. The error message for the lint. Ideally it would probably be good to give some context as to why the suggestion is made (e.g. `rustc::default_hash_types` tells the user that it's because of performance), but I don't have that context so I couldn't put it in the error message. Happy to iterate on the error message based on feedback during review.
r? ``@oli-obk``
Add MonoItems and Instance to stable_mir
Also add a few methods to instantiate instances and get an instance definition. We're still missing support to actually monomorphize the instance body.
This is related to https://github.com/rust-lang/project-stable-mir/issues/36
r? ``@oli-obk``
``@oli-obk`` is that what you were thinking? I incorporated ``@bjorn3`` idea of just adding a Shim instance definition in https://github.com/rust-lang/rust/pull/116465.
Special case iterator chain checks for suggestion
When encountering method call chains of `Iterator`, check for trailing `;` in the body of closures passed into `Iterator::map`, as well as calls to `<T as Clone>::clone` when `T` is a type param and `T: !Clone`.
Fix#9082.
Add new simpler and more explicit syntax for check-cfg
<details>
<summary>
Old proposition (before the MCP)
</summary>
This PR adds a new simpler and more explicit syntax for check-cfg. It consist of two new form:
- `exhaustive(names, values)`
- `configure(name, "value1", "value2", ... "valueN")`
The preview forms `names(...)` and `values(...)` have implicit meaning that are not strait-forward. In particular `values(foo)`&`values(bar)` and `names(foo, bar)` are not equivalent which has created [some confusions](https://github.com/rust-lang/rust/pull/98080).
Also the `names()` and `values()` form are not clear either and again created some confusions where peoples believed that `values()`&`values(foo)` could be reduced to just `values(foo)`.
To fix that the two new forms are made to be explicit and simpler. See the table of correspondence:
- `names()` -> `exhaustive(names)`
- `values()` -> `exhaustive(values)`
- `names(foo)` -> `exhaustive(names)`&`configure(foo)`
- `values(foo)` -> `configure(foo)`
- `values(feat, "foo", "bar")` -> `configure(feat, "foo", "bar")`
- `values(foo)`&`values(bar)` -> `configure(foo, bar)`
- `names()`&`values()`&`values(my_cfg)` -> `exhaustive(names, values)`&`configure(my_cfg)`
Another benefits of the new syntax is that it allow for further options (like conditional checking for --cfg, currently always on) without syntax change.
The two previous forms are deprecated and will be removed once cargo and beta rustc have the necessary support.
</details>
This PR is the first part of the implementation of [MCP636 - Simplify and improve explicitness of the check-cfg syntax](https://github.com/rust-lang/compiler-team/issues/636).
## New `cfg` form
It introduces the new [`cfg` form](https://github.com/rust-lang/compiler-team/issues/636) and deprecate the other two:
```
rustc --check-cfg 'cfg(name1, ..., nameN, values("value1", "value2", ... "valueN"))'
```
## Default built-in names and values
It also changes the default for the built-in names and values checking.
- Built-in values checking would always be activated as long as a `--check-cfg` argument is present
- Built-in names checking would always be activated as long as a `--check-cfg` argument is present **unless** if any `cfg(any())` arg is passed
~~**Note: depends on https://github.com/rust-lang/rust/pull/111068 but is reviewable (last two commits)!**~~
Resolve https://github.com/rust-lang/compiler-team/issues/636
r? `@petrochenkov`
MacOS (and all apple targets) have -Csplit-debuginfo=packed as default
instead of "off" like all other targets (well there is Windows, but we
don't test it in those tests), also -Csplit-debuginfo is not stable on
all targets so we only set in on Darwin where is matters.
Rollup of 6 pull requests
Successful merges:
- #116754 (coverage: Several small cleanups in `spans`)
- #116798 (Improve display of parallel jobs in rustdoc-gui tester script)
- #116800 (Fix implied outlives check for GAT in RPITIT)
- #116805 (Make `rustc_onunimplemented` export path agnostic)
- #116808 (Add myself to smir triage)
- #116811 (Preserve unicode escapes in format string literals when pretty-printing AST)
r? `@ghost`
`@rustbot` modify labels: rollup
Preserve unicode escapes in format string literals when pretty-printing AST
Fixes#116799
Thanks to `@Nilstrieb` for the pointer to the correct location, that was really helpful for someone unfamiliar with the codebase.
Fix implied outlives check for GAT in RPITIT
We enforce certain `Self: 'lt` bounds for GATs to save space for more sophisticated implied bounds, but those currently operate on the HIR. Code was easily reworked to operate on def-ids so that we can properly let these suggestions propagate through synthetic associated types like RPITITs and AFITs.
r? `@jackh726` or `@aliemjay`
Fixes#116789
Also add a few methods to instantiate instances and get an instance
definition.
We're still missing support to actually monomorphize the instance body.
Remove `DefiningAnchor::Bubble` from opaque wf check
Set the defining anchor to `DefiningAnchor::Bind(parent_def_id)` where `parent_def_id` is the first parent def-id that isn't an opaque.
This "fixes" some of the nested-return-type wf tests. If we *do* want these to be hard-errors for TAITs, we should probably make those error separately from this check (i.e. via some check like the code in the `OPAQUE_HIDDEN_INFERRED_BOUND` lint). The fact that some of these tests fail but not all of them seems kinda coincidental.
r? oli-obk
Suggest trait bounds for used associated type on type param
Fix#101351.
When an associated type on a type parameter is used, and the type parameter isn't constrained by the correct trait, suggest the appropriate trait bound:
```
error[E0220]: associated type `Associated` not found for `T`
--> file.rs:6:15
|
6 | field: T::Associated,
| ^^^^^^^^^^ there is a similarly named associated type `Associated` in the trait `Foo`
|
help: consider restricting type parameter `T`
|
5 | struct Generic<T: Foo> {
| +++++
```
When an associated type on a type parameter has a typo, suggest fixing
it:
```
error[E0220]: associated type `Baa` not found for `T`
--> $DIR/issue-55673.rs:9:8
|
LL | T::Baa: std::fmt::Debug,
| ^^^ there is a similarly named associated type `Bar` in the trait `Foo`
|
help: change the associated type name to use `Bar` from `Foo`
|
LL | T::Bar: std::fmt::Debug,
| ~~~
```
Add `Config::hash_untracked_state` callback
For context, I'm looking to use [late module passes](https://doc.rust-lang.org/nightly/nightly-rustc/rustc_lint/context/struct.LintStore.html#structfield.late_module_passes) in Clippy which unlike regular late passes run incrementally per module
However we have a config file which can change between runs, we need changes to that to invalidate the `lint_mod` query. This PR adds a side channel for us to hash some extra state into `Options` in order to do that
This does not make any changes to Clippy, I plan to do that in a PR to the Clippy repo along with some other required changes
An alternative implementation would be to add a new query to track this state and override the `lint_mod` query in Clippy to first call that
cc `@rust-lang/clippy`
THIR unsafety checking was getting a cycle of
function unsafety checking
-> building THIR for the function
-> evaluating pattern inline constants in the function
-> building MIR for the inline constant
-> checking unsafety of functions (so that THIR can be stolen)
This is fixed by not stealing THIR when generating MIR but instead when
unsafety checking.
This leaves an issue with pattern inline constants not being unsafety
checked because they are evaluated away when generating THIR.
To fix that we now represent inline constants in THIR patterns and
visit them in THIR unsafety checking.
don't UB on dangling ptr deref, instead check inbounds on projections
This implements https://github.com/rust-lang/reference/pull/1387 in Miri. See that PR for what the change is about.
Detecting dangling references in `let x = &...;` is now done by validity checking only, so some tests need to have validity checking enabled. There is no longer inherently a "nodangle" check in evaluating the expression `&*ptr` (aside from the aliasing model).
r? `@oli-obk`
Based on:
- https://github.com/rust-lang/reference/pull/1387
- https://github.com/rust-lang/rust/pull/115524
use `PatKind::Error` when an ADT const value has violation
Fixes#115599
Since the [to_pat](https://github.com/rust-lang/rust/pull/111913/files#diff-6d8d99538aca600d633270051580c7a9e40b35824ea2863d9dda2c85a733b5d9R126-R155) behavior has been changed in the #111913 update, the kind of `inlined_const_ast_pat` has transformed from `PatKind::Leaf { pattern: Pat { kind: Wild, ..} } ` to `PatKind::Constant`. This caused a scenario where there are no matched candidates, leading to a testing of the candidates. This process ultimately attempts to test the string const, triggering the `bug!` invocation finally.
r? ``@oli-obk``
Format all the let-chains in compiler crates
Since rust-lang/rustfmt#5910 has landed, soon we will have support for formatting let-chains (as soon as rustfmt syncs and beta gets bumped).
This PR applies the changes [from master rustfmt to rust-lang/rust eagerly](https://rust-lang.zulipchat.com/#narrow/stream/122651-general/topic/out.20formatting.20of.20prs/near/374997516), so that the next beta bump does not have to deal with a 200+ file diff and can remain concerned with other things like `cfg(bootstrap)` -- #113637 was a pain to land, for example, because of let-else.
I will also add this commit to the ignore list after it has landed.
The commands that were run -- I'm not great at bash-foo, but this applies rustfmt to every compiler crate, and then reverts the two crates that should probably be formatted out-of-tree.
```
~/rustfmt $ ls -1d ~/rust/compiler/* | xargs -I@ cargo run --bin rustfmt -- `@/src/lib.rs` --config-path ~/rust --edition=2021 # format all of the compiler crates
~/rust $ git checkout HEAD -- compiler/rustc_codegen_{gcc,cranelift} # revert changes to cg-gcc and cg-clif
```
cc `@rust-lang/rustfmt`
r? `@WaffleLapkin` or `@Nilstrieb` who said they may be able to review this purely mechanical PR :>
cc `@Mark-Simulacrum` and `@petrochenkov,` who had some thoughts on the order of operations with big formatting changes in https://github.com/rust-lang/rust/pull/95262#issue-1178993801. I think the situation has changed since then, given that let-chains support exists on master rustfmt now, and I'm fairly confident that this formatting PR should land even if *bootstrap* rustfmt doesn't yet format let-chains in order to lessen the burden of the next beta bump.
optimize zipping over array iterators
Fixes#115339 (somewhat)
the new assembly:
```asm
zip_arrays:
.cfi_startproc
vmovups (%rdx), %ymm0
leaq 32(%rsi), %rcx
vxorps %xmm1, %xmm1, %xmm1
vmovups %xmm1, -24(%rsp)
movq $0, -8(%rsp)
movq %rsi, -88(%rsp)
movq %rdi, %rax
movq %rcx, -80(%rsp)
vmovups %ymm0, -72(%rsp)
movq $0, -40(%rsp)
movq $32, -32(%rsp)
movq -24(%rsp), %rcx
vmovups (%rsi,%rcx), %ymm0
vorps -72(%rsp,%rcx), %ymm0, %ymm0
vmovups %ymm0, (%rsi,%rcx)
vmovups (%rsi), %ymm0
vmovups %ymm0, (%rdi)
vzeroupper
retq
```
This is still longer than the slice version given in the issue but at least it eliminates the terrible `vpextrb`/`orb` chain. I guess this is due to excessive memcpys again (haven't looked at the llvmir)?
The `TrustedLen` specialization is a drive-by change since I had to do something for the default impl anyway to be able to specialize the `TrustedRandomAccessNoCoerce` impl.
Rollup of 6 pull requests
Successful merges:
- #115439 (rustdoc: hide `#[repr(transparent)]` if it isn't part of the public ABI)
- #116591 (Don't accidentally detect the commit hash as an `fadd` instruction)
- #116603 (Reorganize `bootstrap/Cargo.toml`)
- #116715 (Prevent more spurious unreachable pattern lints)
- #116723 (Fix broken build on ESP-IDF caused by #115108)
- #116730 (Add some unsoundness tests for opaques capturing hidden regions not in substs)
r? `@ghost`
`@rustbot` modify labels: rollup
Prevent more spurious unreachable pattern lints
Continues the work of https://github.com/rust-lang/rust/pull/115937 by introducing `PatKind::Error`, to be used instead of `PatKind::Wild` when an error was raised during pattern lowering. Most of match checking lints are skipped when a `PatKind::Error` is encountered. This avoids confusing extra warnings when a pattern is malformed. Now `PatKind::Wild` should indicate an actual wildcard pattern.
r? `@oli-obk`
rustdoc: hide `#[repr(transparent)]` if it isn't part of the public ABI
Fixes#90435.
This hides `#[repr(transparent)]` when the non-1-ZST field the struct is "transparent" over is private.
CC `@RalfJung`
Tentatively nominating it for the release notes, feel free to remove the nomination.
`@rustbot` label needs-fcp relnotes A-rustdoc-ui
Fix AFIT lint message to mention pitfall
Addresses https://github.com/rust-lang/rust/pull/116184#issuecomment-1745194387 by adding a short note. Not sure exactly of the wording -- I don't think this should be a blocker for the stabilization PR since we can iterate on this lint's messaging in the next few weeks in the worst case.
r? `@tmandry` cc `@traviscross` `@jonhoo`
const_eval: allow function pointer signatures containing &mut T in const contexts
potentially fixes#114994
We utilize a `TypeVisitor` here in order to more easily handle control flow.
- In the event the typekind the Visitor sees is a function pointer, we skip over it
- However, otherwise we do one of two things:
- If we find a mutable reference, check it, then continue visiting types
- If we find any other type, continue visiting types
This means we will check if the function pointer _itself_ is mutable, but not if any of the types _within_ are.
Stabilize `async fn` and return-position `impl Trait` in trait
# Stabilization report
This report proposes the stabilization of `#![feature(return_position_impl_trait_in_trait)]` ([RPITIT][RFC 3425]) and `#![feature(async_fn_in_trait)]` ([AFIT][RFC 3185]). These are both long awaited features that increase the expressiveness of the Rust language and trait system.
Closes#91611
[RFC 3185]: https://rust-lang.github.io/rfcs/3185-static-async-fn-in-trait.html
[RFC 3425]: https://rust-lang.github.io/rfcs/3425-return-position-impl-trait-in-traits.html
## Updates from thread
The thread has covered two major concerns:
* [Given that we don't have RTN, what should we stabilize?](https://github.com/rust-lang/rust/pull/115822#issuecomment-1731149475) -- proposed resolution is [adding a lint](https://github.com/rust-lang/rust/pull/115822#issuecomment-1728354622) and [careful messaging](https://github.com/rust-lang/rust/pull/115822#issuecomment-1731136169)
* [Interaction between outlives bounds and capture semantics](https://github.com/rust-lang/rust/pull/115822#issuecomment-1731153952) -- This is fixable in a forwards-compatible way via #116040, and also eventually via ATPIT.
## Stabilization Summary
This stabilization allows the following examples to work.
### Example of return-position `impl Trait` in trait definition
```rust
trait Bar {
fn bar(self) -> impl Send;
}
```
This declares a trait method that returns *some* type that implements `Send`. It's similar to writing the following using an associated type, except that the associated type is anonymous.
```rust
trait Bar {
type _0: Send;
fn bar(self) -> Self::_0;
}
```
### Example of return-position `impl Trait` in trait implementation
```rust
impl Bar for () {
fn bar(self) -> impl Send {}
}
```
This defines a method implementation that returns an opaque type, just like [RPIT][RFC 1522] does, except that all in-scope lifetimes are captured in the opaque type (as is already true for `async fn` and as is expected to be true for RPIT in Rust Edition 2024), as described below.
[RFC 1522]: https://rust-lang.github.io/rfcs/1522-conservative-impl-trait.html
### Example of `async fn` in trait
```rust
trait Bar {
async fn bar(self);
}
impl Bar for () {
async fn bar(self) {}
}
```
This declares a trait method that returns *some* [`Future`](https://doc.rust-lang.org/core/future/trait.Future.html) and a corresponding method implementation. This is equivalent to writing the following using RPITIT.
```rust
use core::future::Future;
trait Bar {
fn bar(self) -> impl Future<Output = ()>;
}
impl Bar for () {
fn bar(self) -> impl Future<Output = ()> { async {} }
}
```
The desirability of this desugaring being available is part of why RPITIT and AFIT are being proposed for stabilization at the same time.
## Motivation
Long ago, Rust added [RPIT][RFC 1522] and [`async`/`await`][RFC 2394]. These are major features that are widely used in the ecosystem. However, until now, these feature could not be used in *traits* and trait implementations. This left traits as a kind of second-class citizen of the language. This stabilization fixes that.
[RFC 2394]: https://rust-lang.github.io/rfcs/2394-async_await.html
### `async fn` in trait
Async/await allows users to write asynchronous code much easier than they could before. However, it doesn't play nice with other core language features that make Rust the great language it is, like traits. Support for `async fn` in traits has been long anticipated and was not added before due to limitations in the compiler that have now been lifted.
`async fn` in traits will unblock a lot of work in the ecosystem and the standard library. It is not currently possible to write a trait that is implemented using `async fn`. The workarounds that exist are undesirable because they require allocation and dynamic dispatch, and any trait that uses them will become obsolete once native `async fn` in trait is stabilized.
We also have ample evidence that there is demand for this feature from the [`async-trait` crate][async-trait], which emulates the feature using dynamic dispatch. The async-trait crate is currently the #5 async crate on crates.io ranked by recent downloads, receiving over 78M all-time downloads. According to a [recent analysis][async-trait-analysis], 4% of all crates use the `#[async_trait]` macro it provides, representing 7% of all function and method signatures in trait definitions on crates.io. We think this is a *lower bound* on demand for the feature, because users are unlikely to use `#[async_trait]` on public traits on crates.io for the reasons already given.
[async-trait]: https://crates.io/crates/async-trait
[async-trait-analysis]: https://rust-lang.zulipchat.com/#narrow/stream/315482-t-compiler.2Fetc.2Fopaque-types/topic/RPIT.20capture.20rules.20.28capturing.20everything.29/near/389496292
### Return-position `impl Trait` in trait
`async fn` always desugars to a function that returns `impl Future`.
```rust!
async fn foo() -> i32 { 100 }
// Equivalent to:
fn foo() -> impl Future<Output = i32> { async { 100 } }
```
All `async fn`s today can be rewritten this way. This is useful because it allows adding behavior that runs at the time of the function call, before the first `.await` on the returned future.
In the spirit of supporting the same set of features on `async fn` in traits that we do outside of traits, it makes sense to stabilize this as well. As described by the [RPITIT RFC][rpitit-rfc], this includes the ability to mix and match the equivalent forms in traits and their corresponding impls:
```rust!
trait Foo {
async fn foo(self) -> i32;
}
// Can be implemented as:
impl Foo for MyType {
fn foo(self) -> impl Future<Output = i32> {
async { 100 }
}
}
```
Return-position `impl Trait` in trait is useful for cases beyond async, just as regular RPIT is. As a simple example, the RFC showed an alternative way of writing the `IntoIterator` trait with one fewer associated type.
```rust!
trait NewIntoIterator {
type Item;
fn new_into_iter(self) -> impl Iterator<Item = Self::Item>;
}
impl<T> NewIntoIterator for Vec<T> {
type Item = T;
fn new_into_iter(self) -> impl Iterator<Item = T> {
self.into_iter()
}
}
```
[rpitit-rfc]: https://rust-lang.github.io/rfcs/3425-return-position-impl-trait-in-traits.html
## Major design decisions
This section describes the major design decisions that were reached after the RFC was accepted:
- EDIT: Lint against async fn in trait definitions
- Until the [send bound problem](https://smallcultfollowing.com/babysteps/blog/2023/02/01/async-trait-send-bounds-part-1-intro/) is resolved, the use of `async fn` in trait definitions could lead to a bad experience for people using work-stealing executors (by far the most popular choice). However, there are significant use cases for which the current support is all that is needed (single-threaded executors, such as those used in embedded use cases, as well as thread-per-core setups). We are prioritizing serving users well over protecting people from misuse, and therefore, we opt to stabilize the full range of functionality; however, to help steer people correctly, we are will issue a warning on the use of `async fn` in trait definitions that advises users about the limitations. (See [this summary comment](https://github.com/rust-lang/rust/pull/115822#issuecomment-1731149475) for the details of the concern, and [this comment](https://github.com/rust-lang/rust/pull/115822#issuecomment-1728354622) for more details about the reasoning that led to this conclusion.)
- Capture rules:
- The RFC's initial capture rules for lifetimes in impls/traits were found to be imprecisely precise and to introduce various inconsistencies. After much discussion, the decision was reached to make `-> impl Trait` in traits/impls capture *all* in-scope parameters, including both lifetimes and types. This is a departure from the behavior of RPITs in other contexts; an RFC is currently being authored to change the behavior of RPITs in other contexts in a future edition.
- Major discussion links:
- [Lang team design meeting from 2023-07-26](https://hackmd.io/sFaSIMJOQcuwCdnUvCxtuQ?view)
- Refinement:
- The [refinement RFC] initially proposed that impl signatures that are more specific than their trait are not allowed unless the `#[refine]` attribute was included, but left it as an open question how to implement this. The stabilized proposal is that it is not a hard error to omit `#[refine]`, but there is a lint which fires if the impl's return type is more precise than the trait. This greatly simplified the desugaring and implementation while still achieving the original goal of ensuring that users do not accidentally commit to a more specific return type than they intended.
- Major discussion links:
- [Zulip thread](https://rust-lang.zulipchat.com/#narrow/stream/213817-t-lang/topic/.60.23.5Brefine.5D.60.20as.20a.20lint)
[refinement RFC]: https://rust-lang.github.io/rfcs/3245-refined-impls.html
## What is stabilized
### Async functions in traits and trait implementations
* `async fn` are now supported in traits and trait implementations.
* Associated functions in traits that are `async` may have default bodies.
### Return-position impl trait in traits and trait implementations
* Return-position `impl Trait`s are now supported in traits and trait implementations.
* Return-position `impl Trait` in implementations are treated like regular return-position `impl Trait`s, and therefore behave according to the same inference rules for hidden type inference and well-formedness.
* Associated functions in traits that name return-position `impl Trait`s may have default bodies.
* Implementations may provide either concrete types or `impl Trait` for each corresponding `impl Trait` in the trait method signature.
For a detailed exploration of the technical implementation of return-position `impl Trait` in traits, see [the dev guide](https://rustc-dev-guide.rust-lang.org/return-position-impl-trait-in-trait.html).
### Mixing `async fn` in trait and return-position `impl Trait` in trait
A trait function declaration that is `async fn ..() -> T` may be satisfied by an implementation function that returns `impl Future<Output = T>`, or vice versa.
```rust
trait Async {
async fn hello();
}
impl Async for () {
fn hello() -> impl Future<Output = ()> {
async {}
}
}
trait RPIT {
fn hello() -> impl Future<Output = String>;
}
impl RPIT for () {
async fn hello() -> String {
"hello".to_string()
}
}
```
### Return-position `impl Trait` in traits and trait implementations capture all in-scope lifetimes
Described above in "major design decisions".
### Return-position `impl Trait` in traits are "always revealing"
When a trait uses `-> impl Trait` in return position, it logically desugars to an associated type that represents the return (the actual implementation in the compiler is different, as described below). The value of this associated type is determined by the actual return type written in the impl; if the impl also uses `-> impl Trait` as the return type, then the value of the associated type is an opaque type scoped to the impl method (similar to what you would get when calling an inherent function returning `-> impl Trait`). As with any associated type, the value of this special associated type can be revealed by the compiler if the compiler can figure out what impl is being used.
For example, given this trait:
```rust
trait AsDebug {
fn as_debug(&self) -> impl Debug;
}
```
A function working with the trait generically is only able to see that the return value is `Debug`:
```rust
fn foo<T: AsDebug>(t: &T) {
let u = t.as_debug();
println!("{}", u); // ERROR: `u` is not known to implement `Display`
}
```
But if a function calls `as_debug` on a known type (say, `u32`), it may be able to resolve the return type more specifically, if that implementation specifies a concrete type as well:
```rust
impl AsDebug for u32 {
fn as_debug(&self) -> u32 {
*self
}
}
fn foo(t: &u32) {
let u: u32 = t.as_debug(); // OK!
println!("{}", t.as_debug()); // ALSO OK (since `u32: Display`).
}
```
The return type used in the impl therefore represents a **semver binding** promise from the impl author that the return type of `<u32 as AsDebug>::as_debug` will not change. This could come as a surprise to users, who might expect that they are free to change the return type to any other type that implements `Debug`. To address this, we include a [`refining_impl_trait` lint](https://github.com/rust-lang/rust/pull/115582) that warns if the impl uses a specific type -- the `impl AsDebug for u32` above, for example, would toggle the lint.
The lint message explains what is going on and encourages users to `allow` the lint to indicate that they meant to refine the return type:
```rust
impl AsDebug for u32 {
#[allow(refining_impl_trait)]
fn as_debug(&self) -> u32 {
*self
}
}
```
[RFC #3245](https://github.com/rust-lang/rfcs/pull/3245) proposed a new attribute, `#[refine]`, that could also be used to "opt-in" to refinements like this (and which would then silence the lint). That RFC is not currently implemented -- the `#[refine]` attribute is also expected to reveal other details from the signature and has not yet been fully implemented.
### Return-position `impl Trait` and `async fn` in traits are opted-out of object safety checks when the parent function has `Self: Sized`
```rust
trait IsObjectSafe {
fn rpit() -> impl Sized where Self: Sized;
async fn afit() where Self: Sized;
}
```
Traits that mention return-position `impl Trait` or `async fn` in trait when the associated function includes a `Self: Sized` bound will remain object safe. That is because the associated function that defines them will be opted-out of the vtable of the trait, and the associated types will be unnameable from any trait object.
This can alternatively be seen as a consequence of https://github.com/rust-lang/rust/pull/112319#issue-1742251747 and the desugaring of return-position `impl Trait` in traits to associated types which inherit the where-clauses of the associated function that defines them.
## What isn't stabilized (aka, potential future work)
### Dynamic dispatch
As stabilized, traits containing RPITIT and AFIT are **not dyn compatible**. This means that you cannot create `dyn Trait` objects from them and can only use static dispatch. The reason for this limitation is that dynamic dispatch support for RPITIT and AFIT is more complex than static dispatch, as described on the [async fundamentals page](https://rust-lang.github.io/async-fundamentals-initiative/evaluation/challenges/dyn_traits.html). The primary challenge to using `dyn Trait` in today's Rust is that **`dyn Trait` today must list the values of all associated types**. This means you would have to write `dyn for<'s> Trait<Foo<'s> = XXX>` where `XXX` is the future type defined by the impl, such as `F_A`. This is not only verbose (or impossible), it also uniquely ties the `dyn Trait` to a particular impl, defeating the whole point of `dyn Trait`.
The precise design for handling dynamic dispatch is not yet determined. Top candidates include:
- [callee site selection][], in which we permit unsized return values so that the return type for an `-> impl Foo` method be can be `dyn Foo`, but then users must specify the type of wide pointer at the call-site in some fashion.
- [`dyn*`][], where we create a built-in encapsulation of a "wide pointer" and map the associated type corresponding to an RPITIT to the corresponding `dyn*` type (`dyn*` itself is not exposed to users as a type in this proposal, though that could be a future extension).
[callee site selection]: https://smallcultfollowing.com/babysteps/blog/2022/09/21/dyn-async-traits-part-9-callee-site-selection/
[`dyn*`]: https://smallcultfollowing.com/babysteps/blog/2022/03/29/dyn-can-we-make-dyn-sized/
### Where-clause bounds on return-position `impl Trait` in traits or async futures (RTN/ART)
One limitation of async fn in traits and RPITIT as stabilized is that there is no way for users to write code that adds additional bounds beyond those listed in the `-> impl Trait`. The most common example is wanting to write a generic function that requires that the future returned from an `async fn` be `Send`:
```rust
trait Greet {
async fn greet(&self);
}
fn greet_in_parallel<G: Greet>(g: &G) {
runtime::spawn(async move {
g.greet().await; //~ ERROR: future returned by `greet` may not be `Send`
})
}
```
Currently, since the associated types added for the return type are anonymous, there is no where-clause that could be added to make this code compile.
There have been various proposals for how to address this problem (e.g., [return type notation][rtn] or having an annotation to give a name to the associated type), but we leave the selection of one of those mechanisms to future work.
[rtn]: https://smallcultfollowing.com/babysteps/blog/2023/02/13/return-type-notation-send-bounds-part-2/
In the meantime, there are workarounds that one can use to address this problem, listed below.
#### Require all futures to be `Send`
For many users, the trait may only ever be used with `Send` futures, in which case one can write an explicit `impl Future + Send`:
```rust
trait Greet {
fn greet(&self) -> impl Future<Output = ()> + Send;
}
```
The nice thing about this is that it is still compatible with using `async fn` in the trait impl. In the async working group case studies, we found that this could work for the [builder provider API](https://rust-lang.github.io/async-fundamentals-initiative/evaluation/case-studies/builder-provider-api.html). This is also the default approach used by the `#[async_trait]` crate which, as we have noted, has seen widespread adoption.
#### Avoid generics
This problem only applies when the `Self` type is generic. If the `Self` type is known, then the precise return type from an `async fn` is revealed, and the `Send` bound can be inferred thanks to auto-trait leakage. Even in cases where generics may appear to be required, it is sometimes possible to rewrite the code to avoid them. The [socket handler refactor](https://rust-lang.github.io/async-fundamentals-initiative/evaluation/case-studies/socket-handler.html) case study provides one such example.
### Unify capture behavior for `-> impl Trait` in inherent methods and traits
As stabilized, the capture behavior for `-> impl Trait` in a trait (whether as part of an async fn or a RPITIT) captures all types and lifetimes, whereas the existing behavior for inherent methods only captures types and lifetimes that are explicitly referenced. Capturing all lifetimes in traits was necessary to avoid various surprising inconsistencies; the expressed intent of the lang team is to extend that behavior so that we also capture all lifetimes in inherent methods, which would create more consistency and also address a common source of user confusion, but that will have to happen over the 2024 edition. The RFC is in progress. Should we opt not to accept that RFC, we can bring the capture behavior for `-> impl Trait` into alignment in other ways as part of the 2024 edition.
### `impl_trait_projections`
Orthgonal to `async_fn_in_trait` and `return_position_impl_trait_in_trait`, since it can be triggered on stable code. This will be stabilized separately in [#115659](https://github.com/rust-lang/rust/pull/115659).
<details>
If we try to write this code without `impl_trait_projections`, we will get an error:
```rust
#![feature(async_fn_in_trait)]
trait Foo {
type Error;
async fn foo(&mut self) -> Result<(), Self::Error>;
}
impl<T: Foo> Foo for &mut T {
type Error = T::Error;
async fn foo(&mut self) -> Result<(), Self::Error> {
T::foo(self).await
}
}
```
The error relates to the use of `Self` in a trait impl when the self type has a lifetime. It can be worked around by rewriting the impl not to use `Self`:
```rust
#![feature(async_fn_in_trait)]
trait Foo {
type Error;
async fn foo(&mut self) -> Result<(), Self::Error>;
}
impl<T: Foo> Foo for &mut T {
type Error = T::Error;
async fn foo(&mut self) -> Result<(), <&mut T as Foo>::Error> {
T::foo(self).await
}
}
```
</details>
## Tests
Tests are generally organized between return-position `impl Trait` and `async fn` in trait, when the distinction matters.
* RPITIT: https://github.com/rust-lang/rust/tree/master/tests/ui/impl-trait/in-trait
* AFIT: https://github.com/rust-lang/rust/tree/master/tests/ui/async-await/in-trait
## Remaining bugs and open issues
* #112047: Indirection introduced by `async fn` and return-position `impl Trait` in traits may hide cycles in opaque types, causing overflow errors that can only be discovered by monomorphization.
* #111105 - `async fn` in trait is susceptible to issues with checking auto traits on futures' generators, like regular `async`. This is a manifestation of #110338.
* This was deemed not blocking because fixing it is forwards-compatible, and regular `async` is subject to the same issues.
* #104689: `async fn` and return-position `impl Trait` in trait requires the late-bound lifetimes in a trait and impl function signature to be equal.
* This can be relaxed in the future with a smarter lexical region resolution algorithm.
* #102527: Nesting return-position `impl Trait` in trait deeply may result in slow compile times.
* This has only been reported once, and can be fixed in the future.
* #108362: Inference between return types and generics of a function may have difficulties when there's an `.await`.
* This isn't related to AFIT (https://github.com/rust-lang/rust/issues/108362#issuecomment-1717927918) -- using traits does mean that there's possibly easier ways to hit it.
* #112626: Because `async fn` and return-position `impl Trait` in traits lower to associated types, users may encounter strange behaviors when implementing circularly dependent traits.
* This is not specific to RPITIT, and is a limitation of associated types: https://github.com/rust-lang/rust/issues/112626#issuecomment-1603405105
* **(Nightly)** #108309: `async fn` and return-position `impl Trait` in trait do not support specialization. This was deemed not blocking, since it can be fixed in the future (e.g. #108321) and specialization is a nightly feature.
#### (Nightly) Return type notation bugs
RTN is not being stabilized here, but there are some interesting outstanding bugs. None of them are blockers for AFIT/RPITIT, but I'm noting them for completeness.
<details>
* #109924 is a bug that occurs when a higher-ranked trait bound has both inference variables and associated types. This is pre-existing -- RTN just gives you a more convenient way of producing them. This should be fixed by the new trait solver.
* #109924 is a manifestation of a more general issue with `async` and auto-trait bounds: #110338. RTN does not cause this issue, just allows us to put `Send` bounds on the anonymous futures that we have in traits.
* #112569 is a bug similar to associated type bounds, where nested bounds are not implied correctly.
</details>
## Alternatives
### Do nothing
We could choose not to stabilize these features. Users that can use the `#[async_trait]` macro would continue to do so. Library maintainers would continue to avoid async functions in traits, potentially blocking the stable release of many useful crates.
### Stabilize `impl Trait` in associated type instead
AFIT and RPITIT solve the problem of returning unnameable types from trait methods. It is also possible to solve this by using another unstable feature, `impl Trait` in an associated type. Users would need to define an associated type in both the trait and trait impl:
```rust!
trait Foo {
type Fut<'a>: Future<Output = i32> where Self: 'a;
fn foo(&self) -> Self::Fut<'_>;
}
impl Foo for MyType {
type Fut<'a> where Self: 'a = impl Future<Output = i32>;
fn foo(&self) -> Self::Fut<'_> {
async { 42 }
}
}
```
This also has the advantage of allowing generic code to bound the associated type. However, it is substantially less ergonomic than either `async fn` or `-> impl Future`, and users still expect to be able to use those features in traits. **Even if this feature were stable, we would still want to stabilize AFIT and RPITIT.**
That said, we can have both. `impl Trait` in associated types is desireable because it can be used in existing traits with explicit associated types, among other reasons. We *should* stabilize this feature once it is ready, but that's outside the scope of this proposal.
### Use the old capture semantics for RPITIT
We could choose to make the capture rules for RPITIT consistent with the existing rules for RPIT. However, there was strong consensus in a recent [lang team meeting](https://hackmd.io/sFaSIMJOQcuwCdnUvCxtuQ?view) that we should *change* these rules, and furthermore that new features should adopt the new rules.
This is consistent with the tenet in RFC 3085 of favoring ["Uniform behavior across editions"](https://rust-lang.github.io/rfcs/3085-edition-2021.html#uniform-behavior-across-editions) when possible. It greatly reduces the complexity of the feature by not requiring us to answer, or implement, the design questions that arise out of the interaction between the current capture rules and traits. This reduction in complexity – and eventual technical debt – is exactly in line with the motivation listed in the aforementioned RFC.
### Make refinement a hard error
Refinement (`refining_impl_trait`) is only a concern for library authors, and therefore doesn't really warrant making into a deny-by-default warning or an error.
Additionally, refinement is currently checked via a lint that compares bounds in the `impl Trait`s in the trait and impl syntactically. This is good enough for a warning that can be opted-out, but not if this were a hard error, which would ideally be implemented using fully semantic, implicational logic. This was implemented (#111931), but also is an unnecessary burden on the type system for little pay-off.
## History
- Dec 7, 2021: [RFC #3185: Static async fn in traits](https://rust-lang.github.io/rfcs/3185-static-async-fn-in-trait.html) merged
- Sep 9, 2022: [Initial implementation](https://github.com/rust-lang/rust/pull/101224) of AFIT and RPITIT landed
- Jun 13, 2023: [RFC #3425: Return position `impl Trait` in traits](https://rust-lang.github.io/rfcs/3425-return-position-impl-trait-in-traits.html) merged
<!--These will render pretty when pasted into github-->
Non-exhaustive list of PRs that are particularly relevant to the implementation:
- #101224
- #103491
- #104592
- #108141
- #108319
- #108672
- #112988
- #113182 (later made redundant by #114489)
- #113215
- #114489
- #115467
- #115582
Doc co-authored by `@nikomatsakis,` `@tmandry,` `@traviscross.` Thanks also to `@spastorino,` `@cjgillot` (for changes to opaque captures!), `@oli-obk` for many reviews, and many other contributors and issue-filers. Apologies if I left your name off 😺
When encountering method call chains of `Iterator`, check for trailing
`;` in the body of closures passed into `Iterator::map`, as well as
calls to `<T as Clone>::clone` when `T` is a type param and `T: !Clone`.
Fix#9082.
const-eval: make misalignment a hard error
It's been a future-incompat error (showing up in cargo's reports) since https://github.com/rust-lang/rust/pull/104616, Rust 1.68, released in March. That should be long enough.
The question for the lang team is simply -- should we move ahead with this, making const-eval alignment failures a hard error? (It turns out some of them accidentally already were hard errors since #104616. But not all so this is still a breaking change. Crater found no regression.)
Detect ruby-style closure in parser
When parsing a closure without a body that is surrounded by a block, suggest moving the opening brace after the closure head.
Fix#116608.
Fix#101351.
When an associated type on a type parameter is used, and the type
parameter isn't constrained by the correct trait, suggest the
appropriate trait bound:
```
error[E0220]: associated type `Associated` not found for `T`
--> file.rs:6:15
|
6 | field: T::Associated,
| ^^^^^^^^^^ there is a similarly named associated type `Associated` in the trait `Foo`
|
help: consider restricting type parameter `T`
|
5 | struct Generic<T: Foo> {
| +++++
```
When an associated type on a type parameter has a typo, suggest fixing
it:
```
error[E0220]: associated type `Baa` not found for `T`
--> $DIR/issue-55673.rs:9:8
|
LL | T::Baa: std::fmt::Debug,
| ^^^ there is a similarly named associated type `Bar` in the trait `Foo`
|
help: change the associated type name to use `Bar` from `Foo`
|
LL | T::Bar: std::fmt::Debug,
| ~~~
```
On type error involving closure, avoid ICE
When we encounter a type error involving a closure, we try to typeck prior closure invocations to see if they influenced the current expected type. When trying to do so, ensure that the closure was defined in our current scope.
Fix#116658.
Improve check-cfg diagnostics
This PR tries to improve some of the diagnostics of check-cfg.
The main changes is the unexpected name or value being added to the main diagnostic:
```diff
- warning: unexpected `cfg` condition name
+ warning: unexpected `cfg` condition name: `widnows`
```
It also cherry-pick the better sensible logic for when we print the list of expected values when we have a matching value for a very similar name.
Address https://github.com/rust-lang/rust/pull/111072#discussion_r1356818100
r? `@petrochenkov`
When we encounter a type error involving a closure, we try to typeck
prior closure invocations to see if they influenced the current expected
type. When trying to do so, ensure that the closure was defined in our
current scope.
Fix#116658.
exhaustiveness: Rework constructor splitting
`SplitWildcard` was pretty opaque. I replaced it with a more legible abstraction: `ConstructorSet` represents the set of constructors for patterns of a given type. This clarifies responsibilities: `ConstructorSet` handles one clear task, and diagnostic-related shenanigans can be done separately.
I'm quite excited, I had has this in mind for years but could never quite introduce it. This opens up possibilities, including type-specific optimisations (like using a `FxHashSet` to collect enum variants, which had been [hackily attempted some years ago](https://github.com/rust-lang/rust/pull/76918)), my one-pass rewrite (https://github.com/rust-lang/rust/pull/116042), and future librarification.
Copy 1-element arrays as scalars, not vectors
For `[T; 1]` it's silly to copy as `<1 x T>` when we can just copy as `T`.
Inspired by https://github.com/rust-lang/rust/issues/101210#issuecomment-1732470941, which pointed out that `Option<[u8; 1]>` was codegenning worse than `Option<u8>`.
(I'm not sure *why* LLVM doesn't optimize out `<1 x u8>`, but might as well just not emit it in the first place in this codepath.)
---
I think I bit off too much in #116479; let me try just the scalar case first.
r? `@ghost`
Handle several `#[diagnostic::on_unimplemented]` attributes correctly
This PR fixes an issues where rustc would ignore subsequent `#[diagnostic::on_unimplemented]` attributes. The [corresponding RFC](https://rust-lang.github.io/rfcs/3368-diagnostic-attribute-namespace.html) specifies that the first matching instance of each option is used. Invalid attributes are linted and otherwise ignored.
Show enum discriminant if a compatible repr is used
Follow-up of #116142.
It was mentioned in the [team meeting](https://rust-lang.zulipchat.com/#narrow/stream/393423-t-rustdoc.2Fmeetings/topic/meeting.2002-10-2023/near/394504024) that an enum with a `repr` should also get its discriminants displayed. Forgot to implement it in #116142...
It also allowed to uncover a bug: i was not providing the correct `DefId` in case it was a type alias to `render_enum_fields`. It's also fixed in this PR.
r? `@fmease`
Use structured suggestion for #113174
When encountering a for loop that is rejected by the borrow checker because it is being advanced within its body, provide a structured suggestion for `while let Some(pat) = iter.next()`.