Suggest bounds in more cases, accounting for type parameters referenced in predicate
Use a `ty::Visitor` to see if the failed predicate references a type parameter. If it does, then we only suggest adding a bound to an (associated) item only if the referenced parameter is present in its generics.
Provide adding bound suggestion in trait and impl associated functions in cases we previously weren't:
```
error[E0277]: `?` couldn't convert the error to `ApplicationError`
--> $DIR/suggest-complex-bound-on-method.rs:18:16
|
LL | t.run()?;
| -----^ the trait `From<<T as Trait>::Error>` is not implemented for `ApplicationError`
| |
| this can't be annotated with `?` because it has type `Result<_, <T as Trait>::Error>`
|
note: `ApplicationError` needs to implement `From<<T as Trait>::Error>`
--> $DIR/suggest-complex-bound-on-method.rs:12:1
|
LL | enum ApplicationError {
| ^^^^^^^^^^^^^^^^^^^^^
= note: the question mark operation (`?`) implicitly performs a conversion on the error value using the `From` trait
help: consider introducing a `where` clause, but there might be an alternative better way to express this requirement
|
LL | fn thing<T: Trait>(&self, t: T) -> Result<(), ApplicationError> where ApplicationError: From<<T as Trait>::Error> {
| +++++++++++++++++++++++++++++++++++++++++++++++++
```
Fixrust-lang/rust#144734.
cleanup and cache proof tree building
There's some cruft left over from when we had deep proof trees. We never encounter overflow when evaluating proof trees. Even if the recursion limit is `0`, we still only hit the overflow limit when evaluating nested goals of the root. The root goal simply inherits the `root_depth` of the `SearchGraph`.
Split `evaluate_root_goal_for_proof_tree` from the rest of the trait solver. This enables us to simplify the implementation of `evaluate_goal_raw` and the `ProofTreeBuilder` as we no longer need to manually track the state of the builder and can instead use separate types for that. It does require making a few internal methods into associated functions taking a `delegate` and a `span` instead of the `EvalCtxt` itself.
I've also split `SearchGraph::evaluate_goal` and `SearchGraph::evaluate_root_goal_for_proof_tree` for the same reason. Both functions don't actually share too much code, so by splitting them each version gets significantly easier to read.
Add a `query evaluate_root_goal_for_proof_tree_raw` to cache proof tree building. This requires arena allocating `inspect::Probe`. I've added a new type alias `I::ProbeRef` for this. We may need to adapt this for rust-analyzer? It would definitely be easy to remove the `Copy` bound here 🤔
This was done in #145740 and #145947. It is causing problems for people
using r-a on anything that uses the rustc-dev rustup package, e.g. Miri,
clippy.
This repository has lots of submodules and subtrees and various
different projects are carved out of pieces of it. It seems like
`[workspace.dependencies]` will just be more trouble than it's worth.
```
error[E0277]: the trait bound `usize: Neg` is not satisfied
--> $DIR/negative-literal-infered-to-unsigned.rs:2:14
|
LL | for x in -5..5 {
| ^^ the trait `Neg` is not implemented for `usize`
|
help: consider specifying an integer type that can be negative
|
LL | for x in -5isize..5 {
| +++++
```
When determining if a trait has no entries for the purposes of omitting vptrs from subtrait vtables, consider its transitive supertraits' entries, instead of just its own entries.
When determining if a non-first supertrait vptr can be omitted from a subtrait vtable, check if the supertrait or any of its (transitive) supertraits have methods, instead of only checking if the supertrait itself has methods.
This fixes the soundness issue where a vptr would be omitted for a supertrait with no methods but that itself had a supertrait with methods, while still optimizing the case where the supertrait is "truly" empty (it has no own vtable entries, and none of its (transitive) supertraits have any own vtable entries).
Fixes <https://github.com/rust-lang/rust/issues/145752>
-----
Old description:
~~Treat all non-auto traits as non-empty (possibly having methods) for purposes of determining if we need to emit a vptr for a non-direct supertrait (and for new "sibling" entries after a direct or non-direct supertrait).~~
This fixes (I believe) the soundness issue, ~~but regresses vtable sizes and possibly upcasting perf in some cases when using trait hierarchies with empty non-auto traits (see `tests/ui/traits/vtable/multiple-markers.stderr`) since we use vptrs in some cases where we could re-use the vtable.~~
Fixes <https://github.com/rust-lang/rust/issues/145752>
Re-opens (not anymore) <https://github.com/rust-lang/rust/issues/114942>
Should not affect <https://github.com/rust-lang/rust/issues/131813> (i.e. the soundness issue is still fixed, ~~though the relevant vtables in the `trait Evil` example will be larger now~~)
cc implementation history <https://github.com/rust-lang/rust/pull/131864> <https://github.com/rust-lang/rust/pull/113856>
-----
~~It should be possible to check if a trait has any methods from itself *or* supertraits (instead of just from itself), but to fix the immediate soundness issue, just assume any non-auto trait could have methods. A more optimistic check can be implemented later (or if someone does it soon it could just supercede this PR 😄).~~ Done in latest push
`@rustbot` label A-dyn-trait F-trait_upcasting
change HIR typeck region uniquification handling approach
rust-lang/rust#144405 causes structural lookup of opaque types to not work during HIR typeck, so instead avoid uniquifying goals and instead only reprove them if MIR borrowck actually encounters an error.
This doesn't perfectly maintain the property that HIR typeck succeeding implies that MIR typeck succeeds, instead weakening this check to only guarantee that HIR typeck implies that MIR typeck succeeds modulo region uniquification. This means we still get the actually desirable ICEs if we MIR building is broken or we forget to check some property in HIR typeck, without having to deal with the fallout of uniquification in HIR typeck itself.
We report errors using the original obligation sources of HIR typeck so diagnostics aren't that negatively impacted either.
Here's the history of region uniquification while working on the new trait solver:
- rust-lang/rust#107981
- rust-lang/rust#110180
- rust-lang/rust#114117
- rust-lang/rust#130821
- rust-lang/rust#144405
- rust-lang/rust#145706 <- we're here 🎉
r? `@BoxyUwU`
On E0277, point at type that doesn't implement bound
When encountering an unmet trait bound, point at local type that doesn't implement the trait:
```
error[E0277]: the trait bound `Bar<T>: Foo` is not satisfied
--> $DIR/issue-64855.rs:9:19
|
LL | pub struct Bar<T>(<Self as Foo>::Type) where Self: ;
| ^^^^^^^^^^^^^^^^^^^ unsatisfied trait bound
|
help: the trait `Foo` is not implemented for `Bar<T>`
--> $DIR/issue-64855.rs:9:1
|
LL | pub struct Bar<T>(<Self as Foo>::Type) where Self: ;
| ^^^^^^^^^^^^^^^^^
```
When encountering an unmet trait bound, point at local type that doesn't implement the trait:
```
error[E0277]: the trait bound `Bar<T>: Foo` is not satisfied
--> $DIR/issue-64855.rs:9:19
|
LL | pub struct Bar<T>(<Self as Foo>::Type) where Self: ;
| ^^^^^^^^^^^^^^^^^^^ unsatisfied trait bound
|
help: the trait `Foo` is not implemented for `Bar<T>`
--> $DIR/issue-64855.rs:9:1
|
LL | pub struct Bar<T>(<Self as Foo>::Type) where Self: ;
| ^^^^^^^^^^^^^^^^^
```
Do not use effective_visibilities query for Adt types of a local trait while proving a where-clause
Partially fixrust-lang/rust#145611, but we should do something make cycle in this situation ICE.
Instead of using a query, call `&tcx.resolutions(()).effective_visibilities`.
r? `````@lcnr`````
cc `````@compiler-errors`````
Unconditionally-const supertraits are considered not dyn compatible
Let's save some space in the design of const traits by making `dyn Trait` where `trait Trait: const Super` not dyn compatible.
Such a trait cannot satisfy `dyn Trait: Trait`; we could in the future make this dyn compatible but *NOT* implement `Trait`, but that's a bit weird and seems like it needs to be independently justified moving forward.
Fixes https://github.com/rust-lang/rust/issues/145198
r? fee1-dead
Do not consider a `T: !Sized` candidate to satisfy a `T: !MetaSized` obligation.
This example should fail to compile (and does under this PR, with the old and new solvers), but currently compiles successfully ([playground](https://play.rust-lang.org/?version=nightly&mode=debug&edition=2024&gist=6e0e5d0ae0cdf0571dea97938fb4a86d)), because (IIUC) the old solver's `lazily_elaborate_sizedness_candidate`/callers and the new solver's `TraitPredicate::fast_reject_assumption`/`match_assumption` consider a `T: _ Sized` candidate to satisfy a `T: _ MetaSized` obligation, for either polarity `_`, when that should only hold for positive polarity.
```rs
#![feature(negative_bounds)]
#![feature(sized_hierarchy)]
use std::marker::MetaSized;
fn foo<T: !MetaSized>() {}
fn bar<T: !Sized + MetaSized>() {
foo::<T>();
//~^ ERROR the trait bound `T: !MetaSized` is not satisfied // error under this PR
}
```
Only observable with the internal-only `feature(negative_bounds)`, so might just be "wontfix".
This example is added as a test in this PR (as well as testing that `foo<()>` and `foo<str>` are disallowed for `fn foo<T: !MetaSized`).
cc `@davidtwco` for `feature(sized_hierarchy)`
Maybe similar to 91c53c9 from <https://github.com/rust-lang/rust/pull/143307>
Print regions in `type_name`.
Currently they are skipped, which is a bit weird, and it sometimes causes malformed output like `Foo<>` and `dyn Bar<, A = u32>`.
Most regions are erased by the time `type_name` does its work. So all regions are now printed as `'_` in non-optional places. Not perfect, but better than the status quo.
`c_name` is updated to trim lifetimes from MIR pass names, so that the `PASS_NAMES` sanity check still works. It is also renamed as `simplify_pass_type_name` and made non-const, because it doesn't need to be const and the non-const implementation is much shorter.
The commit also renames `should_print_region` as `should_print_optional_region`, which makes it clearer that it only applies to some regions.
Fixesrust-lang/rust#145168.
r? `@lcnr`
Change the desugaring of `assert!` for better error output
In the desugaring of `assert!`, we now expand to a `match` expression instead of `if !cond {..}`.
The span of incorrect conditions will point only at the expression, and not the whole `assert!` invocation.
```
error[E0308]: mismatched types
--> $DIR/issue-14091.rs:2:13
|
LL | assert!(1,1);
| ^ expected `bool`, found integer
```
We no longer mention the expression needing to implement the `Not` trait.
```
error[E0308]: mismatched types
--> $DIR/issue-14091-2.rs:15:13
|
LL | assert!(x, x);
| ^ expected `bool`, found `BytePos`
```
Now `assert!(val)` desugars to:
```rust
match val {
true => {},
_ => $crate::panic::panic_2021!(),
}
```
Fix#122159.
Currently they are skipped, which is a bit weird, and it sometimes
causes malformed output like `Foo<>` and `dyn Bar<, A = u32>`.
Most regions are erased by the time `type_name` does its work. So all
regions are now printed as `'_` in non-optional places. Not perfect, but
better than the status quo.
`c_name` is updated to trim lifetimes from MIR pass names, so that the
`PASS_NAMES` sanity check still works. It is also renamed as
`simplify_pass_type_name` and made non-const, because it doesn't need
to be const and the non-const implementation is much shorter.
The commit also renames `should_print_region` as
`should_print_optional_region`, which makes it clearer that it only
applies to some regions.
Fixes#145168.
In the desugaring of `assert!`, we now expand to a `match` expression
instead of `if !cond {..}`.
The span of incorrect conditions will point only at the expression, and not
the whole `assert!` invocation.
```
error[E0308]: mismatched types
--> $DIR/issue-14091.rs:2:13
|
LL | assert!(1,1);
| ^ expected `bool`, found integer
```
We no longer mention the expression needing to implement the `Not` trait.
```
error[E0308]: mismatched types
--> $DIR/issue-14091-2.rs:15:13
|
LL | assert!(x, x);
| ^ expected `bool`, found `BytePos`
```
`assert!(val)` now desugars to:
```rust
match val {
true => {},
_ => $crate::panic::panic_2021!(),
}
```
Fix#122159.
We make some minor changes to some diagnostics to avoid span overlap on
type mismatch or inverted "expected"/"found" on type errors.
We remove some unnecessary parens from core, alloc and miri.
address review comments
Ignore coroutine witness type region args in auto trait confirmation
## The problem
Consider code like:
```
async fn process<'a>() {
Box::pin(process()).await;
}
fn require_send(_: impl Send) {}
fn main() {
require_send(process());
}
```
When proving that the coroutine `{coroutine@process}::<'?0>: Send`, we end up instantiating a nested goal `{witness@process}::<'?0>: Send` by synthesizing a witness type from the coroutine's args:
Proving a coroutine witness type implements an auto trait requires looking up the coroutine's witness types. The witness types are a binder that look like `for<'r> { Pin<Box<{coroutine@process}::<'r>>> }`. We instantiate this binder with placeholders and prove `Send` on the witness types. This ends up eventually needing to prove something like `{coroutine@process}::<'!1>: Send`. Repeat this process, and we end up in an overflow during fulfillment, since fulfillment does not use freshening.
This can be visualized with a trait stack that ends up looking like:
* `{coroutine@process}::<'?0>: Send`
* `{witness@process}::<'?0>: Send`
* `Pin<Box<{coroutine@process}::<'!1>>>: Send`
* `{coroutine@process}::<'!1>: Send`
* ...
* `{coroutine@process}::<'!2>: Send`
* `{witness@process}::<'!2>: Send`
* ...
* overflow!
The problem here specifically comes from the first step: synthesizing a witness type from the coroutine's args.
## Why wasn't this an issue before?
Specifically, before 63f6845e570305a92eaf855897768617366164d6, this wasn't an issue because we were instead extracting the witness from the coroutine type itself. It turns out that given some `{coroutine@process}::<'?0>`, the witness type was actually something like `{witness@process}::<'erased>`!
So why do we end up with a witness type with `'erased` in its args? This is due to the fact that opaque type inference erases all regions from the witness. This is actually explicitly part of opaque type inference -- changing this to actually visit the witness types actually replicates this overflow even with 63f6845e570305a92eaf855897768617366164d6 reverted:
ca77504943/compiler/rustc_borrowck/src/type_check/opaque_types.rs (L303-L313)
To better understand this difference and how it avoids a cycle, if you look at the trait stack before 63f6845e570305a92eaf855897768617366164d6, we end up with something like:
* `{coroutine@process}::<'?0>: Send`
* `{witness@process}::<'erased>: Send` **<-- THIS CHANGED**
* `Pin<Box<{coroutine@process}::<'!1>>>: Send`
* `{coroutine@process}::<'!1>: Send`
* ...
* `{coroutine@process}::<'erased>: Send` **<-- THIS CHANGED**
* `{witness@process}::<'erased>: Send` **<-- THIS CHANGED**
* coinductive cycle! 🎉
## So what's the fix?
This hack replicates the behavior in opaque type inference to erase regions from the witness type, but instead erasing the regions during auto trait confirmation. This is kinda a hack, but is sound. It does not need to be replicated in the new trait solver, of course.
---
I hope this explanation makes sense.
We could beta backport this instead of the revert https://github.com/rust-lang/rust/pull/145193, but then I'd like to un-revert that on master in this PR along with landing this this hack. Thoughts?
r? lcnr
Check coroutine upvars in dtorck constraint
Fixrust-lang/rust#144155.
This PR fixes an unsoundness where we were not considering coroutine upvars as drop-live if the coroutine interior types (witness types) had nothing which required drop.
In the case that the coroutine does not have any interior types that need to be dropped, then we don't need to treat all of the upvars as use-live; instead, this PR uses the same logic as closures, and descends into the upvar types to collect anything that must be drop-live. The rest of this PR is reworking the comment to explain the behavior here.
r? `@lcnr` or reassign 😸
---
Just some thoughts --- a proper fix for this whole situation would be to consider `TypingMode` in the `needs_drop` function, and just calling `coroutine_ty.needs_drop(tcx, typing_env)` in the dtorck constraint check.
During MIR building, we should probably use a typing mode that stalls the local coroutines and considers them to be unconditionally drop, or perhaps just stall *all* coroutines in analysis mode. Then in borrowck mode, we can re-check `needs_drop` but descend into witness types properly. https://github.com/rust-lang/rust/pull/144158 implements this experimentally.
This is a pretty involved fix, and conflicts with some in-flight changes (rust-lang/rust#144157) that I have around removing coroutine witnesses altogether. I'm happy to add a FIXME to rework this whole approach, but I don't want to block this quick fix since it's obviously more correct than the status-quo.