Unable to write blanket impl for subtrait on RPITIT trait #124729
Description
If we have a trait that uses RPITIT, e.g.:
trait Trait {
fn f() -> impl Sized;
}
It's currently impossible to define a subtrait and to write a blanket impl for that subtrait, e.g.:
trait Sub: Trait</* Need bound here, but how? */> {}
impl<T: Sub> Trait for T {
fn f() -> impl Sized {}
//~^ ERROR method `f` has an incompatible type for trait
//~| ERROR expected associated type, found opaque type
//~| ERROR help: change the output type to match the trait: `impl Sized`
}
The error we give here is, of course, particularly bad since we suggest that the user change the type to what is already written there syntactically.
We can simplify the example a bit by refining the impl:
#![allow(refining_impl_trait)]
trait Trait {
fn f() -> impl Sized;
}
trait Sub: Trait</* Need bound here, but how? */> {}
impl<T: Sub> Trait for T {
fn f() -> () {}
//~^ ERROR method `f` has an incompatible type for trait
//~| ERROR expected associated type, found `()`
//~| ERROR help: change the output type to match the trait: `impl Sized`
}
If we desugar this, we can see more clearly what's going on:
trait Trait {
type _0: Sized;
fn f() -> Self::_0;
}
trait Sub: Trait</* Need bound here. */> {}
impl<T: Sub> Trait for T {
type _0 = ();
fn f() -> () {}
//~^ ERROR method `f` has an incompatible type for trait
//~| ERROR expected associated type, found `()`
//~| ERROR help: change the output type to match the trait: `impl Sized`
}
We need to bound the associated type of the trait when defining the subtrait. If we do that, then it works:
trait Trait {
type _0: Sized;
fn f() -> Self::_0;
}
trait Sub: Trait<_0 = ()> {}
impl<T: Sub> Trait for T {
type _0 = ();
fn f() -> () {}
}
The trouble for RPITIT is that 1) there's no way to bound the associated type in that way, and 2) even if there were (e.g. with RTN with type equality bounds), we probably don't want to require that people do that.
Because of the special relationship between a function with an RPITIT and the implicit associated type, we may be able to make this just work in the case of RPITITs.
This is related to some existing issues, but is probably a more minimal statement of the underlying issue here, so we're filing it separately.
Activity