Skip to content

GAT with HRTB yields weird inference errors. #96750

Open
@aliemjay

Description

@aliemjay

I tried this code: (playground)

#![feature(generic_associated_types)]
use std::marker::PhantomData;

trait AsyncFn<Arg> { type Output; }
trait RequestFamily { type Type<'a>; }
trait Service {}

struct MyFn;
impl AsyncFn<String> for MyFn { type Output = (); }

impl RequestFamily for String { type Type<'a> = String; }

struct ServiceFromAsyncFn<F, Req>(F, PhantomData<Req>);

impl<F, Req, O> Service for ServiceFromAsyncFn<F, Req>
where
    Req: RequestFamily,
    F: AsyncFn<Req>,
    F: for<'a> AsyncFn<Req::Type<'a>, Output = O>,
{
}

fn assert_service() -> impl Service {
    ServiceFromAsyncFn(MyFn, PhantomData)
}

It fails type inference with the following error:

error[E0282]: type annotations needed
  --> src/lib.rs:23:24
   |
23 | fn assert_service() -> impl Service {
   |                        ^^^^^^^^^^^^ cannot infer type for type parameter `O`

This is super weird because type paramters that don't appear in Self type of the impl are not expected to fail inference.
Surprisingly, removing O makes it pass:

-impl<F, Req, O> Service for ServiceFromAsyncFn<F, Req>
+impl<F, Req> Service for ServiceFromAsyncFn<F, Req>
 where
     Req: RequestFamily,
     F: AsyncFn<Req>,
-    F: for<'a> AsyncFn<Req::Type<'a>, Output = O>,
+    F: for<'a> AsyncFn<Req::Type<'a>>,

Meta

Nightly version: 1.62.0-nightly

(2022-05-03 e1b71fe)

@rustbot label F-generic_associated_types T-compiler A-traits A-inference A-lifetimes

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-GATsArea: Generic associated types (GATs)A-higher-rankedArea: Higher-ranked things (e.g., lifetimes, types, trait bounds aka HRTBs)A-inferenceArea: Type inferenceA-lifetimesArea: Lifetimes / regionsA-trait-systemArea: Trait systemT-compilerRelevant to the compiler team, which will review and decide on the PR/issue.fixed-by-next-solverFixed by the next-generation trait solver, `-Znext-solver`.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions