auto_impl: Unable to use auto_impl with async-trait
I was trying to use auto_impl to delegate the implementation of Box<T> where T: Trait and Trait was a trait annotated with the async-trait procedural macro. I was using it like this:
#[async_trait]
#[auto_impl(Box)]
trait Foo: Sync {
async fn bar(&self) -> Result<u32, Error>;
}
The ordering of the above macros matters, as it ensures that async_trait transforms Foo into the following Rust code before auto_impl parses it:
#[auto_impl(Box)]
trait Foo: Sync {
fn bar<'life0, 'async_trait>(
&'life0 self
) -> Pin<Box<dyn Future<Output = Result<u32, Error>> + Send + 'async_trait>> where
'life0: 'async_trait,
Self: 'async_trait;
}
Provided that the Sync bound shown above is present as a supertrait of Foo, the above code should be object safe. I expected #[auto_impl(Box)] to emit the following implementation:
impl<T: Foo + ?Sized> Foo for Box<T>
where
Box<T>: Sync
However, it emitted the following implementation instead:
impl<T: Foo> Foo for Box<T>
where
Box<T>: Sync
This meant that the following code was able to compile with a manual Box implementation but failed under the auto_impl-generated implementation:
fn assert_impl<T: Foo>() {}
fn foo() {
assert_impl::<Box<dyn Foo>>(); // ERROR: Not object safe with `auto_impl`
}
Do you have an idea as to why the ?Sized bound was not applied in this case?
See https://github.com/ebkalderon/tower-lsp/pull/109 for the original pull request that inspired this issue.
About this issue
- Original URL
- State: closed
- Created 7 years ago
- Comments: 17 (7 by maintainers)
Sorry for the delayed response, @LukasKalbertodt! Indeed I was. I had checked out an incorrect commit ref and didn’t get the changes. It seems to work just fine now. 👍
I finally managed to take a closer look. I discovered the bug in my thoughts (i.e. why I was confused).
In short: if we access a field (or something like that) of
self, we cannot assumeself.fieldimplementsSomeTraiteven ifSelf: SomeTrait. That’s why #11 was a bug that needed fixing. However,self.fieldalways satisfies the same lifetime bounds asSelf, or more. In other words: if we haveSelf: 'a, thenself.fieldalways satisfies'aas well. That’s why we don’t need to add lifetime bounds onSelfspecified on methods to theTtype in the impl header. I hope that explanation made some sense.In any case, #67 should fix your problem. At least the following code compiles fine:
I’m currently pretty busy, but I’ll try to figure this out and fix this by the end of the month.