Skip to content

Cannot refer to associated type of generics of the same trait (illegal recursive type) #18655

@kennytm

Description

@kennytm
Member

This code:

#![feature(associated_types)]

trait Factory {
    type Product;
    fn create(&self) -> <Self as Factory>::Product;
}

impl Factory for f64 {
    type Product = f64;
    fn create(&self) -> f64 { *self * *self }
}

impl<A: Factory, B: Factory> Factory for (A, B) {
    type Product = (<A as Factory>::Product, <B as Factory>::Product); // line 14
    fn create(&self) -> (<A as Factory>::Product, <B as Factory>::Product) {
        let (ref a, ref b) = *self;
        (a.create(), b.create())
    }
}

fn main() {
    println!("{}", (4.0f64, 5.0f64).create());
    // ^ should print (16, 25)
}

Failed to compile with error:

1.rs:14:20: 14:70 error: illegal recursive type; insert an enum or struct in the cycle, if this is desired
1.rs:14     type Product = (<A as Factory>::Product, <B as Factory>::Product);
                           ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

I think this should be allowed.

Activity

jroesch

jroesch commented on Dec 22, 2014

@jroesch
Member

@nikomatsakis This seems like a bug to me as well. I just encountered it trying to get this code to compile: https://github.com/jroesch/molten/blob/master/src/hlist.rs#L76.

The way I see it the expansion should be as follows.

Given a HList of type: HCons<int, HCons<int, HNil>> a call to take(S { pred: Z }) should result in solving an obligation for an impl of Take<S<Z>> for HCons<int, HCons<int, HNil>> which incurs a sub obligation to produce an instance of Take<Z> for HCons<int, HNil>.

When checking this we should know Take<_>::R always resolve to an HList (in this case to HNil) and then HCons<int, <T as Take<Z>>::R> should be equivalent to HCons<int, H0: HList> for the representability check. So forall T, H: HList. HCons<T, H> can be represented as HCons { head: T, tail: Box<H> } which looks finite to me.

added a commit that references this issue on Jun 22, 2015
ba7f79e
added a commit that references this issue on Feb 1, 2021
69f0364
added a commit that references this issue on Feb 1, 2021
11eb176
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      Participants

      @steveklabnik@kennytm@jroesch

      Issue actions

        Cannot refer to associated type of generics of the same trait (illegal recursive type) · Issue #18655 · rust-lang/rust