rust-lang / rust

Empowering everyone to build reliable and efficient software.
https://www.rust-lang.org
Other
98.28k stars 12.71k forks source link

Compiler forgets the trait bound on an associated type if the concrete type is known #130429

Open theemathas opened 1 month ago

theemathas commented 1 month ago

I tried this code:

trait SomeTrait {}

trait Foo {
    type Assoc: SomeTrait;
}

struct Wrap<T>(T);

fn require_trait<T: SomeTrait>() {}

fn works<T: Foo>() {
    require_trait::<<T as Foo>::Assoc>();
}

fn fails<T: Foo<Assoc = Wrap<T>>>() {
    require_trait::<<T as Foo>::Assoc>();
}

I expected the code to compile, but I got the following error instead:

   Compiling playground v0.0.1 (/playground)
error[E0277]: the trait bound `Wrap<T>: SomeTrait` is not satisfied
  --> src/lib.rs:16:21
   |
16 |     require_trait::<<T as Foo>::Assoc>();
   |                     ^^^^^^^^^^^^^^^^^ the trait `SomeTrait` is not implemented for `Wrap<T>`
   |
help: this trait has no implementations, consider adding one
  --> src/lib.rs:1:1
   |
1  | trait SomeTrait {}
   | ^^^^^^^^^^^^^^^
note: required by a bound in `require_trait`
  --> src/lib.rs:9:21
   |
9  | fn require_trait<T: SomeTrait>() {}
   |                     ^^^^^^^^^ required by this bound in `require_trait`

For more information about this error, try `rustc --explain E0277`.
error: could not compile `playground` (lib) due to 1 previous error

Note that the works function compiles, even though it's strictly more general than the fails function.

Discovered by sarah8389 on the rust community discord.

Meta

The issue reproduces on the playground with "Stable version: 1.81.0" and "1.83.0-nightly (2024-09-15 04a318787b39732e306f)"

compiler-errors commented 1 month ago

this is almost certainly duplicated at least a few times by other issues, this is a well known bug that is very difficult to fix