Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Generic associated types (associated type constructors) #1598

Merged
merged 10 commits into from Sep 2, 2017

Conversation

withoutboats
Copy link
Contributor

@withoutboats withoutboats commented Apr 30, 2016

I definitely realize that this feature may not be prioritized right now, and I expect that some aspects of it probably present real implementation challenges (especially partial application of type operators and extending HRTBs), but I wanted to document and discuss what seems to me like the best incremental step toward higher-kinded polymorphism in Rust.

Rendered

}
```

`not has the type `bool -> bool` (my apologies for using a syntax different
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is a missing ` after the "not".

@glaebhoerl
Copy link
Contributor

I agree that this seems like the ideal starting point for adding higher-kinded capability to Rust. Even the idea of moving forward incrementally in this way, as opposed to "Adding Higher-Kinded Types" all at once in a "big bang", is something that hadn't occurred to me, but seems obvious in hindsight.

To stick with our own terminology consistently, instead having of a mishmash of vocabulary from Rust, Haskell, and the academic literature, I would probably prefer to call this feature "generic associated types" or "associated generic types". (I would also prefer to call "higher-kinded types" instead "higher-order generic types", contrasting with "higher-rank types" which are "higher-order generic functions", but the usage of "HKT" is incredibly widespread by this point.)

I also suspect that most of the difficult design work which needs to be done before this feature can move forward is on how to extend the type system to support it, which this RFC (self-admittedly) doesn't even attempt to address. Am I right?

@dwrensha
Copy link

Currently, an approximation of StreamingIterator can be defined like this:

trait StreamingIterator<'a> {
  type Item: 'a;
  fn next(&'a self) -> Option<Self::Item>;
}

You can then bound types as T: for<'a> StreamingIterator<'a> to avoid the lifetime parameter infecting everything StreamingIterator appears.

However, this only partially prevents the infectiveness of StreamingIterator, only allows for some of the types that associated type operators can express, and is in generally a hacky attempt to work around the limitation rather than an equivalent alternative.

I'm interested in seeing a concrete example of something that cannot be expressed using this hack. I've hit situations where I've wanted associated type operators as proposed in this RFC, but in every case it has sufficed hoist the the type parameters up to the trait itself. See, for example, these capnp traits. I agree that such hoisting can be ugly, and I feel like there are probably cases where it fails, but those cases are not immediately obvious to me.

@BurntSushi
Copy link
Member

I'm interested in seeing a concrete example of something that cannot be expressed using this hack.

Ideally, the StreamingIterator trait should be expanded to contain many of the same utility adapter methods that the Iterator trait has.

@eddyb
Copy link
Member

eddyb commented Apr 30, 2016

AFAIK the bulk of the implementation work needed here is removing the constraints on the "3 application levels" in the current compiler (type/trait parameters, Self and fn/method parameters).

The actual resolution of non-monomorphic associated types won't actually be that big of a problem, we already have to do that sort of transformation for generic methods.

And lastly, what I'm worried most about is checking uses of such a trait with polymorphic associated types without providing concrete bindings.
We've had a few stages of adjustment to all the problems associated types can cause in various edge cases.
I suspect this is the "difficult design work" @glaebhoerl was talking about, in which case I agree.

But overall, I like this RFC and @rust-lang/compiler will continue to work towards making such advances possible, regardless of which exact syntactic or semantic choices we end up accepting.

@krdln
Copy link
Contributor

krdln commented Apr 30, 2016

@dwrensha
I think that it's currently impossible to express something like owning_ref, but generic over reference type. Eg. the interface of generic reference could look like:

unsafe trait Ref {
    type Item<'a>;
    unsafe fn erase_lifetime<'a>(x: Item<'a>) -> Item<'static> { transmute(x) }
    unsafe fn introduce_lifetime<'a>(x: Item<'static>) -> Item<'a> { transmute(x) }
}

The main benefit from this RFC here would be that compiler would know that all types created by the same & → * constructor are transmute-compatible, and that it can apply that constructor for any lifetime. Unfortunately, the trait would have to be implemented for some phantom type, since this RFC doesn't allow traits to be implemented for type constructors, but I think it's only a minor issue.

It seems that the main benefit from this RFC comes from allowing lifetime (& → *) constructors, so I'd be happy to see it accepted even if it doesn't allow full-featured * → * ones. (analogicaly, as we have for<'a> syntax only for lifetimes)

@eddyb
Copy link
Member

eddyb commented Apr 30, 2016

@krdln Actually, right now you can't even use transmute there, although I would be inclined to accept a same-type exception (we already erase lifetimes, so it should just see Item<'static> on both sides).

@krdln
Copy link
Contributor

krdln commented Apr 30, 2016

@eddyb Your example doesn't compile, since you can't apply an lifetime paremeter to Self::Item. Maybe you've meant to use Ref<'a> somewhere there? I've tried, but I couldn't make it compile. So I'm still not convinced that thing is possible in today's Rust (but I won't be surprised if it was possible, Rust can be really surprising).

Using your suggestion, I came up with this, so this use case might be supported in current Rust, with some fixes for transmute behaviour.

@eddyb
Copy link
Member

eddyb commented Apr 30, 2016

@krdln Hah, that was dumb of me. Totally missed the fact that you were applying multiple times within the trait itself. It could work via free functions with R: Ref<'a> + Ref<'static> but that's probably not useful to you.

@soltanmm
Copy link

soltanmm commented Apr 30, 2016

@krdln I think there does exist an injection between what is proposed here and the syntax that exists today, but it requires a few more pieces than what @dwrensha pointed out.

use std::mem;

// '* -> *
trait R2T<'a> {
    type T;
}

// * -> *
trait T2T<A> {
    type T;
}

// ('* -> *)('*)
type AppR<'a, T> where T: R2T<'a> = <T as R2T<'a>>::T;
// (* -> *)(*)
type AppT<A, T> where T: T2T<A> = <T as T2T<A>>::T;

// A trait with a higher kinded operator
unsafe trait Ref {
    type Item: for<'a> R2T<'a>;
    unsafe fn erase_lifetime<'a>(x: AppR<'a, Self::Item>) -> AppR<'static, Self::Item> { mem::transmute(x) }
    unsafe fn introduce_lifetime<'a>(x: AppR<'static, Self::Item>) -> AppR<'a, Self::Item> { mem::transmute(x) }
}

// A type with a '* -> '* -> * HKT
trait MyType
    where
        for<'a> Self::BiRefItem: R2T<'a>,
        for<'a, 'b> AppR<'a, Self::BiRefItem>: R2T<'b>
{
    type BiRefItem;
}

// Use of partial application by currying (which can always be extended to full partial application with helpers)
trait PartiallyApplied<'a, T: MyType>
    where
        Self::Ref: Ref<Item=AppR<'a, T::BiRefItem>>
{
    type Ref;
    // ...
}

fn main() {}

However, it is excessively verbose, highly error prone, works only for lifetimes in certain use-cases (because it depends on HRTBs), and there're some issues with the compiler that prevent it from compiling (see rust-lang/rust#30472 and rust-lang/rust#31580).

For a more practical application of the general approach that does work today, see #1403 (comment).

For background on the general approach, see the fine-print in the associated items RFC. n.b. the RFC uses non-existent syntax in its example.

and I am in no way suggesting that one take a syntax-sugar approach implementing this :-P

@soltanmm
Copy link

soltanmm commented Apr 30, 2016

Actually, now that I think about it... Unless this RFC is limited to kinds that look like '* -> *, doesn't it require extending HRTBs to types (in mechanism, not necessarily in syntax) to be useful? Otherwise we can't put bounds on the outputs of HKTs like * -> *. Seems like doing that first could be a reasonable alternative.

@eddyb
Copy link
Member

eddyb commented Apr 30, 2016

@soltanmm It is limited to '* -> *. However, this brings an interesting point I didn't realize: T: Trait<Item<'a> = &'a [u8]> is sugar for T: Trait and for<'a> <T as Trait>::Item<'a> = &'a [u8] so still HRTB in nature, just packaged away neatly.

@withoutboats
Copy link
Contributor Author

To stick with our own terminology consistently, instead having of a mishmash of vocabulary from Rust, Haskell, and the academic literature, I would probably prefer to call this feature "generic associated types" or "associated generic types". (I would also prefer to call "higher-kinded types" instead "higher-order generic types", contrasting with "higher-rank types" which are "higher-order generic functions", but the usage of "HKT" is incredibly widespread by this point.)

I don't feel strongly about the terminology, but I'll note that I avoided the term "higher-kinded type" in this RFC because I found it very confusing before I read TaPL, which avoids that terminology. A big part of my confusion was that calling type operators "types" suggests to me that this is a language feature that allows one to create values of a "type" of a higher kinded, like let x: Vec.

I also don't think we use the term generics that much, do we? I usually see 'type parameter' or 'parameterized type.'

I'm interested in seeing a concrete example of something that cannot be expressed using this hack.

I think others have answered this well (the most obvious thing is: * -> *), but I want to add that the real point is to make this feature easier and more intuitive to use, just as adding const parameters would be an easier easier and more intuitive feature than the type-level peano number hacks that we have right now.

You are talking about allowing any operators, but the syntax seems only defined for constructors. If you plan to support any operators, could you give an example of using * → * → * associated operator (not (*, *) → *)?

I used the term operator throughout the text, but its correct that this would only allow associated type constructors.

Actually, now that I think about it... Unless this RFC is limited to kinds that look like '* -> *, doesn't it require extending HRTBs to types (in mechanism, not necessarily in syntax) to be useful? Otherwise we can't put bounds on the outputs of HKTs like * -> *. Seems like doing that first could be a reasonable alternative.

I don't know anything about how HRTBs are implemented, some of eddyb's comments suggest this might be an easy extension, but the higher-ranked parameter is being applied in a different position in these two expressions:

for<'a> Type<'a>: Trait
Type: for<'a> Trait<'a>

This RFC explicitly says it doesn't propose allowing for<'a> Type<'a>: Trait, though obviously that would be the most useful thing to add next. I this RFC is useful even if you can't bound this new kind of associated item.

Also, this RFC only discusses lifetime -> type associated items, but I don't think there's anything in the RFC that doesn't apply equivalently to all kinds of type constructor. The main reason lifetime -> type is the only kind discussed is its the only kind for which I know of obvious, valuable use cases. Not coincidentally, I think its also the kind which can be easily explained without type theory concepts: it lets the trait define "view" types for its receiver.

Extending HRTB to be used with associated items of a kind other than lifetime -> type would require more work, though, of course.

@withoutboats
Copy link
Contributor Author

Thinking about the syntactic and semantic complexities of bounds using associated type constructors, and the fact that all of this seems to be conceivable as just an extension of HRTBs, I think it might be a good idea to not even discuss bounds using associated type constructors in this RFC, and instead delegate that to an RFC about extending HRTBs.

@eddyb
Copy link
Member

eddyb commented Apr 30, 2016

@withoutboats Both of those forms are allowed right now and the for<'a> actually gets lifted to the whole bound (if you don't mean (for<'a> Type<'a>): Trait, of course).

In a way, for<'a> is only syntactical, at the semantic level debruijn indices are used for "late-bound lifetimes" with "binders" which define the boundaries where they apply.

So for<'a> (for<'b> fn(&'b T) -> (&'b U, &'a V)): Trait<'a> ends up being something like fn(&'2 T) -> (&'2 U, &'1 V): Trait<'1> with a binder around the signature of the fn type and another one around the whole bound.

it might be a good idea to not even discuss bounds using associated type constructors in this RFC

It's not a good idea to punt on this matter, because the T: Trait<Assoc = U> syntax is sugar for a <T as Trait>::Assoc = U bound (which we can't express right now syntactically, sadly).

@withoutboats
Copy link
Contributor Author

It's not a good idea to punt on this matter, because the T: Trait<Assoc = U> syntax is sugar for a <T as Trait>::Assoc = U bound (which we can't express right now syntactically, sadly).

I'm not sure why this makes it bad to punt, but I think the important takeaway is that we (yet) don't need to be able to put type constructors in where clauses, because we can use HRTB. Obviously this won't be sufficient for later use cases involving higher-kinded traits.

@withoutboats
Copy link
Contributor Author

withoutboats commented Apr 30, 2016

Another issue has occurred to me just now. We would probably also want some sort of implicit HRTBs at the declaration site of the associated type, as in:

trait Collection {
    type Elem;
    type Iter<'a>: Iterator<Item=&'a Self::Elem>;
    type IterMut<'a>: Iterator<Item=&'a mut Self::Elem>;
    ...
}

@eddyb
Copy link
Member

eddyb commented Apr 30, 2016

@withoutboats I wonder if we should agree on using "polymorphic" or some other "painfully clear" term because I thought you meant <T as Trait>::PolyAssoc<'a>: RegularTrait instead of <T as Trait>::PolyAssoc: SomethingNew, and the latter is HKT territory as far as I'm concerned, so we're in violent agreement, I suppose.

@withoutboats
Copy link
Contributor Author

withoutboats commented Apr 30, 2016

@eddyb: Right, the RFC currently discusses <T as Trait>::PolyAssoc=TypeConstructor, but instead of allowing that that we can just use for<'a> <T as Trait>::PolyAssoc<'a>=TypeConstructor<'a>

@withoutboats
Copy link
Contributor Author

I've edited and expanded the RFC in response to the comments so far, mainly clarifications and adding content about how this would require HRTB changes.

@withoutboats withoutboats force-pushed the associated_hkts branch 2 times, most recently from 188eaeb to c73b60e Compare May 2, 2016 00:38
@nrc nrc added the T-lang Relevant to the language team, which will review and decide on the RFC. label May 2, 2016
@withoutboats withoutboats changed the title Associated type operators (a form of higher-kinded polymorphism). Associated type constructors (a form of higher-kinded polymorphism). May 2, 2016
1. First, allowing HRTBs to applied to type constructors on the left-hand side
of the bound. Currently they are only available to traits on the right-hand
side of the bound.
2. Second, allowing HRTBs to introduce type parameters, instead of only
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When's the RFC to spec out the syntax of bounds/where-clauses on HRTB-quantified types coming out? 😃

aaand obligatory cc #1481

@eefriedman
Copy link
Contributor

The syntax struct Foo<T> where T: for<'a> StreamingIterator<Item=&'a mut [u8]> from the example in the RFC doesn't seem right. The following expanded example is legal on nightly Rust:

trait StreamingIterator {
    type Item;
}
struct Foo<T> where T: for<'a> StreamingIterator<Item=&'a mut [u8]> {
    x: T
}

Granted, as far as I can tell there is no way to write T which satisfies this constraint at the moment, but as far as I can tell that's orthogonal to this RFC.

I think what you actually want is something closer to struct Foo<T> where T: StreamingIterator<Item<'a>=&'a mut [u8]>, with no for<>.

@withoutboats
Copy link
Contributor Author

withoutboats commented May 2, 2016

You're right that its wrong, but it needs both the <'a> and the for<'a>. Without the for<'a>, it would search the surrounding scope for a lifetime parameter called 'a and fail.

EDIT: Fixed.

jgouly added a commit to jgouly/keyboard-app that referenced this pull request Oct 6, 2017
This is needed so that get_row_pin/get_column_pin's return value can borrow
from &self.

This could be solved more ergonomically using a HKT constructor, as defined
in this Rust RFC: rust-lang/rfcs#1598
@ExpHP
Copy link

ExpHP commented Oct 17, 2017

new rendered link

@samsartor samsartor mentioned this pull request Oct 30, 2017
@Boscop
Copy link

Boscop commented Nov 3, 2017

Is there already a plan how HKTs will look outside of traits, so that there is still "design space" to make the syntax the same as in traits?

How would it look in functions, like this?

fn foo<M<type, const usize>, T, const N: usize>() -> M<T, N>;

fn foo<M<type, const usize>, T, const N: usize>()
where for<T, N> M<T, N>: Default
-> M<T, N> {
    Default::default()
}

@gbutler69
Copy link

gbutler69 commented Mar 11, 2018

It would be nice if any RFC that uses an acronym provides a link or definition upon first use. HRTB for example. So, this:

Users can bound parameters by the type constructed by that trait's associated type constructor of a trait using HRTB. Both type equality bounds and trait bounds of this kind are valid:

Would become this:

Users can bound parameters by the type constructed by that trait's associated type constructor of a trait using HRTB. Both type equality bounds and trait bounds of this kind are valid:

@dylanede
Copy link

I haven't seen any mention of variance with respect to GATs yet. The RFC should note whether associated types are invariant, covariant or contravariant in their type parameters. My experiments with poor-man's GATs (for<'a> bounds and dummy traits) suggest that GATs will be severely limiting without some way of specifying variance constraints on associated types within a trait definition.

@Boscop
Copy link

Boscop commented Apr 21, 2018

@dwrensha

I'm interested in seeing a concrete example of something that cannot be expressed using this hack.

How about this?
https://play.rust-lang.org/?gist=32e56d762c3ade7439cdb6796f21569f&version=stable

That's a real-world example I'm running into:

error[E0212]: cannot extract an associated type from a higher-ranked trait bound in this context
  --> src/main.rs:50:17
   |
50 |     device: Option<T::Dev>,
   |                    ^^^^^^

Does anyone of you have any idea how I can make this work? :)

I need to be able to instantiate/store AppMgr before the lifetime 'a that process() will becalled with even exists (it needs to live in an outer scope as a member of a struct, so I have to specify the type. (The 'a that process() will be called with only starts to exist shortly before calling process().)

Or is there any way I can express/enforce that DeviceApp<'a>::Dev should be the same type for all 'a? So that rustc can determine the (for<'a> DeviceApp<'a>)::Dev because there would be only one possibility for it.


AFAIK, to do this I'd either need the ability to express the above statement (and I'd need rustc to then allow me to use T::Dev), or I need GATs.

I tried to do it with GATs like this:

impl DeviceApp for MyAppState {
	type BorrowedState<'a> = MyBorrowedState<'a>;

but I run into this ICE:
https://play.rust-lang.org/?gist=b0614c07a45df09e1b2a3cd2bc789e7a&version=nightly

error: internal compiler error: librustc/ty/subst.rs:439: Region parameter out of range when substituting in region 'a (root type=Some(MyBorrowedState<'a>)) (index=0)
thread 'main' panicked at 'Box', librustc_errors/lib.rs:491:9
rust-lang/rust#50115

I really need this to work. What would be the recommended way to do this before this ICE issue gets fixed? :)

Btw, how long do you think it will take until this issue gets fixed?

@Boscop
Copy link

Boscop commented Apr 21, 2018

I found a workaround, pulling Dev outside of the <'a> quantification scope:

https://play.rust-lang.org/?gist=9b7907d94dfc28aabe12f5f90f8c4592&version=stable

pub trait DeviceSpecific {
	type Dev: Device;
}

pub trait DeviceApp<'a>: DeviceSpecific {
// 	type Dev: Device;

This compiles, but it's a combo of 2 ugly workarounds (I'd prefer not to split the trait like that) that wouldn't be necessary with proper (working) GATs, right?

Can you think of any solution that doesn't require me to split the trait like that? :)

@Boscop
Copy link

Boscop commented Apr 21, 2018

Ah no, it doesn't work with the impl of AppMgr :(

pub struct AppMgr<T: for<'a> DeviceApp<'a>> {
	device: Option<T::Dev>,
	check_connection: AtFps,
	in_port_name: String,
	out_port_name: String,
	app: T,
}

impl<T: for<'a> DeviceApp<'a>> AppMgr<T> {

	// error: cannot extract an associated type from a higher-ranked trait bound in this context

	pub fn process(&mut self, now: u64, v: &mut T::BorrowedState) -> Vec<T::Event> {
	//                                          ^^^^^^^^^^^^^^^^
		if self.check_connection.is_due(now) {
			let should_reconnect = if let Some(ref mut device) = self.device {
				!device.is_connected()
			} else {
				true
			};
			if should_reconnect {
				self.device = T::Dev::connect(&self.in_port_name, &self.out_port_name).ok();
			}
		}
		if let Some(ref mut device) = self.device {
			let app = &mut self.app;
			device.frame(now, |device, input| { app.process(device, input, v) })
		} else {
			vec![]
		}
	}
}

What I need is this:

// pub struct AppMgr<T: for<'a> DeviceApp<'a>> {
pub struct AppMgr<T: DeviceApp> { // DeviceApp not depending on the lifetime 'a that process() gets called with
	// ...
}

// impl<T: for<'a> DeviceApp<'a>> AppMgr<T> {
impl<T: DeviceApp> AppMgr<T> {
	// instantiating T::BorrowedState with <'a> from the scope that process() is called in
	pub fn process<'a>(&mut self, now: u64, v: &'a mut T::BorrowedState<'a>) -> Vec<T::Event> {
		// ...
	}
}

Is there any way to do this now? If not, will this work with proper working GATs?

@Boscop
Copy link

Boscop commented Apr 21, 2018

I found a way to impl AppMgr that works:

pub struct AppMgr<T: for<'a> DeviceApp<'a>> {
	device: Option<T::Dev>,
	// ...
}

impl<T: for<'a> DeviceApp<'a>> AppMgr<T> {
	pub fn process<'a>(&mut self, now: u64, msgs: Vec<<T as DeviceApp<'a>>::Msg>, v: &'a mut <T as DeviceApp<'a>>::BorrowedState) -> Vec<<T as DeviceApp<'a>>::Event> {
		// ...

Here as reduced working example:
https://play.rust-lang.org/?gist=7522f287efe68c7b73efcddef1c5dd2a&version=stable

But I still wasn't happy about having to split the trait, so I thought, if I mandate that Dev: 'static, the compiler will be able to infer that for all 'a, <T as DeviceApp<'a>>::Dev will be the same, namely the same as <T as DeviceApp<'static>>::Dev (because Dev: 'static means it won't depend on 'a).
So I tried that, bringing Dev back into the DeviceApp trait:

/*
pub trait DeviceSpecific {
	type Dev: Device;
}

pub trait DeviceApp<'a>: DeviceSpecific {
*/
pub trait DeviceApp<'a> {
	type Dev: Device + 'static;

// ...

pub struct AppMgr<T: for<'a> DeviceApp<'a>> {
	// device: Option<T::Dev>,
	device: Option<<T as DeviceApp<'static>>::Dev>, // because Dev: 'static, i thought it will be unifyable with any 'a
	app: T,
	// ...
}

But now I get this error:

error[E0495]: cannot infer an appropriate lifetime for lifetime parameter 'a in function call due to conflicting requirements
  --> src/main.rs:79:53
   |
79 |             device.frame(now, |device, input| { app.process(device, input, v) })
   |                                                     ^^^^^^^
   |
note: first, the lifetime cannot outlive the lifetime 'a as defined on the method body at 75:5...
  --> src/main.rs:75:5
   |
75 |     pub fn process<'a>(&mut self, now: u64, msgs: Vec<<T as DeviceApp<'a>>::Msg>, v: &'a mut <T as DeviceApp<'a>>::BorrowedState) -> Vec<<T as DeviceApp<'a>>::Event> {
   |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   = note: ...so that the expression is assignable:
           expected &mut <T as DeviceApp<'_>>::BorrowedState
              found &mut <T as DeviceApp<'a>>::BorrowedState
   = note: but, the lifetime must be valid for the static lifetime...
   = note: ...so that the expression is assignable:
           expected &mut <T as DeviceApp<'_>>::Dev
              found &mut <T as DeviceApp<'static>>::Dev

https://play.rust-lang.org/?gist=d4084c0a87890d4ed17d0491e453565b&version=stable

Why can't rustc unify <T as DeviceApp<'static>>::Dev> with <T as DeviceApp<'a>>::Dev> for all 'a, when it KNOWS that Dev: 'static (the type doesn't depend on 'a, so it can only be the same for all 'a)?


Actually, for some reason, in my real code I get a different (similar) error instead (with nightly 2018-03-06):

error: free region `'a` does not outlive free region `'static`
   --> src\devices\mod.rs:132:15
    |
132 |         if let Some(ref mut device) = self.device {
    |                     ^^^^^^^^^^^^^^

Any idea how to make it work with Dev inside the DeviceApp trait? :)

@burdges
Copy link

burdges commented Aug 6, 2018

I quite like the StreamingIterator example here, but another question: Should we permit higher kinded type parameters? As an example, you could borrow a data structure and use mut reborrows to iterate over it several times like:

fn process_elements<V: ?Sized,II>(x &mut V,f: fn<'a>(&mut V) -> II)
where
    II<'a>: Iterator<Item=&mut X>

or

fn process_elements<F,II>(f: &mut F)
where 
    for<'a> &'a mut F: Into<II<a'>>,
    for<'a> II<'a>: Iterator<Item=&'a mut X>

In principle, these could be done with impl Trait in certain positions, but this feature seems logically prior.

@Centril Centril added A-syntax Syntax related proposals & ideas A-traits Trait system related proposals & ideas A-typesystem Type system related proposals & ideas A-associated-types Proposals relating to associated types labels Nov 23, 2018
@dhardy
Copy link
Contributor

dhardy commented Dec 6, 2019

Re-link the tracking issue, which is not mentioned at either the top/bottom of this thread.

@dhardy dhardy mentioned this pull request Dec 7, 2019
6 tasks
bors added a commit to rust-lang-ci/rust that referenced this pull request Sep 13, 2022
…er-errors

Stabilize generic associated types

Closes rust-lang#44265

r? `@nikomatsakis`

# ⚡ Status of the discussion ⚡

* [x] There have been several serious concerns raised, [summarized here](rust-lang#96709 (comment)).
* [x] There has also been a [deep-dive comment](rust-lang#96709 (comment)) explaining some of the "patterns of code" that are enabled by GATs, based on use-cases posted to this thread or on the tracking issue.
* [x] We have modeled some aspects of GATs in [a-mir-formality](https://github.com/nikomatsakis/a-mir-formality) to give better confidence in how they will be resolved in the future. [You can read a write-up here](https://github.com/rust-lang/types-team/blob/master/minutes/2022-07-08-implied-bounds-and-wf-checking.md).
* [x] The major points of the discussion have been [summarized on the GAT initiative repository](https://rust-lang.github.io/generic-associated-types-initiative/mvp.html).
* [x] [FCP has been proposed](rust-lang#96709 (comment)) and we are awaiting final decisions and discussion amidst the relevant team members.

# Stabilization proposal

This PR proposes the stabilization of `#![feature(generic_associated_types)]`. While there a number of future additions to be made and bugs to be fixed (both discussed below), properly doing these will require significant language design and will ultimately likely be backwards-compatible. Given the overwhelming desire to have some form of generic associated types (GATs) available on stable and the stability of the "simple" uses, stabilizing the current subset of GAT features is almost certainly the correct next step.

Tracking issue: rust-lang#44265
Initiative: https://rust-lang.github.io/generic-associated-types-initiative/
RFC: https://github.com/rust-lang/rfcs/blob/master/text/1598-generic_associated_types.md
Version: 1.65 (2022-08-22 => beta, 2022-11-03 => stable).

## Motivation

There are a myriad of potential use cases for GATs. Stabilization unblocks probable future language features (e.g. async functions in traits), potential future standard library features (e.g. a `LendingIterator` or some form of `Iterator` with a lifetime generic), and a plethora of user use cases (some of which can be seen just by scrolling through the tracking issue and looking at all the issues linking to it).

There are a myriad of potential use cases for GATs. First, there are many users that have chosen to not use GATs primarily because they are not stable (some of which can be seen just by scrolling through the tracking issue and looking at all the issues linking to it). Second, while language feature desugaring isn't *blocked* on stabilization, it gives more confidence on using the feature. Likewise, library features like `LendingIterator` are not necessarily blocked on stabilization to be implemented unstably; however few, if any, public-facing APIs actually use unstable features.

This feature has a long history of design, discussion, and developement - the RFC was first introduced roughly 6 years ago. While there are still a number of features left to implement and bugs left to fix, it's clear that it's unlikely those will have backwards-incompatibility concerns. Additionally, the bugs that do exist do not strongly impede the most-common use cases.

## What is stabilized

The primary language feature stabilized here is the ability to have generics on associated types, as so. Additionally, where clauses on associated types will now be accepted, regardless if the associated type is generic or not.

```rust
trait ATraitWithGATs {
    type Assoc<'a, T> where T: 'a;
}

trait ATraitWithoutGATs<'a, T> {
    type Assoc where T: 'a;
}
```

When adding an impl for a trait with generic associated types, the generics for the associated type are copied as well. Note that where clauses are allowed both after the specified type and before the equals sign; however, the latter is a warn-by-default deprecation.

```rust
struct X;
struct Y;

impl ATraitWithGATs for X {
    type Assoc<'a, T> = &'a T
      where T: 'a;
}
impl ATraitWithGATs for Y {
    type Assoc<'a, T>
      where T: 'a
    = &'a T;
}
```

To use a GAT in a function, generics are specified on the associated type, as if it was a struct or enum. GATs can also be specified in trait bounds:

```rust
fn accepts_gat<'a, T>(t: &'a T) -> T::Assoc<'a, T>
  where for<'x> T: ATraitWithGATs<Assoc<'a, T> = &'a T> {
    ...
}
```

GATs can also appear in trait methods. However, depending on how they are used, they may confer where clauses on the associated type definition. More information can be found [here](rust-lang#87479). Briefly, where clauses are required when those bounds can be proven in the methods that *construct* the GAT or other associated types that use the GAT in the trait. This allows impls to have maximum flexibility in the types defined for the associated type.

To take a relatively simple example:

```rust
trait Iterable {
    type Item<'a>;
    type Iterator<'a>: Iterator<Item = Self::Item<'a>>;

    fn iter<'x>(&'x self) -> Self::Iterator<'x>;
    //^ We know that `Self: 'a` for `Iterator<'a>`, so we require that bound on `Iterator`
    //  `Iterator` uses `Self::Item`, so we also require a `Self: 'a` on `Item` too
}
```

A couple well-explained examples are available in a previous [blog post](https://blog.rust-lang.org/2021/08/03/GATs-stabilization-push.html).

## What isn't stabilized/implemented

### Universal type/const quantification

Currently, you can write a bound like `X: for<'a> Trait<Assoc<'a> = &'a ()>`. However, you cannot currently write `for<T> X: Trait<Assoc<T> = T>` or `for<const N> X: Trait<Assoc<N> = [usize; N]>`.

Here is an example where this is needed:

```rust
trait Foo {}

trait Trait {
    type Assoc<F: Foo>;
}

trait Trait2: Sized {
    fn foo<F: Foo, T: Trait<Assoc<F> = F>>(_t: T);
}
```

In the above example, the *caller* must specify `F`, which is likely not what is desired.

### Object-safe GATs

Unlike non-generic associated types, traits with GATs are not currently object-safe. In other words the following are not allowed:

```rust
trait Trait {
    type Assoc<'a>;
}

fn foo(t: &dyn for<'a> Trait<Assoc<'a> = &'a ()>) {}
         //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not allowed

let ty: Box<dyn for<'a> Trait<Assoc<'a> = &'a ()>>;
          //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not allowed
```

### Higher-kinded types

You cannot write currently (and there are no current plans to implement this):

```rust
struct Struct<'a> {}

fn foo(s: for<'a> Struct<'a>) {}
```

## Tests

There are many tests covering GATs that can be found in  `src/test/ui/generic-associated-types`. Here, I'll list (in alphanumeric order) tests highlight some important behavior or contain important patterns.

- `./parse/*`: Parsing of GATs in traits and impls, and the trait path with GATs
- `./collections-project-default.rs`: Interaction with associated type defaults
- `./collections.rs`: The `Collection` pattern
- `./const-generics-gat-in-trait-return-type-*.rs`: Const parameters
- `./constraint-assoc-type-suggestion.rs`: Emit correct syntax in suggestion
- `./cross-crate-bounds.rs`: Ensure we handles bounds across crates the same
- `./elided-in-expr-position.rs`: Disallow lifetime elision in return position
- `./gat-in-trait-path-undeclared-lifetime.rs`: Ensure we error on undeclared lifetime in trait path
- `./gat-in-trait-path.rs`: Base trait path case
- `./gat-trait-path-generic-type-arg.rs`: Don't allow shadowing of parameters
- `./gat-trait-path-parenthesised-args.rs`: Don't allow paranthesized args in trait path
- `./generic-associated-types-where.rs`: Ensure that we require where clauses from trait to be met on impl
- `./impl_bounds.rs`: Check that the bounds on GATs in an impl are checked
- `./issue-76826.rs`: `Windows` pattern
- `./issue-78113-lifetime-mismatch-dyn-trait-box.rs`: Implicit 'static diagnostics
- `./issue-84931.rs`: Ensure that we have a where clause on GAT to ensure trait parameter lives long enough
- `./issue-87258_a.rs`: Unconstrained opaque type with TAITs
- `./issue-87429-2.rs`: Ensure we can use bound vars in the bounds
- `./issue-87429-associated-type-default.rs`: Ensure bounds hold with associated type defaults, for both trait and impl
- `./issue-87429-specialization.rs`: Check that bounds hold under specialization
- `./issue-88595.rs`: Under the outlives lint, we require a bound for both trait and GAT lifetime when trait lifetime is used in function
- `./issue-90014.rs`: Lifetime bounds are checked with TAITs
- `./issue-91139.rs`: Under migrate mode, but not NLL, we don't capture implied bounds from HRTB lifetimes used in a function and GATs
- `./issue-91762.rs`: We used to too eagerly pick param env candidates when normalizing with GATs. We now require explicit parameters specified.
- `./issue-95305.rs`: Disallow lifetime elision in trait paths
- `./iterable.rs`: `Iterable` pattern
- `./method-unsatified-assoc-type-predicate.rs`: Print predicates with GATs correctly in method resolve error
- `./missing_lifetime_const.rs`: Ensure we must specify lifetime args (not elidable)
- `./missing-where-clause-on-trait.rs`: Ensure we don't allow stricter bounds on impl than trait
- `./parameter_number_and_kind_impl.rs`: Ensure paramters on GAT in impl match GAT in trait
- `./pointer_family.rs`: `PointerFamily` pattern
- `./projection-bound-cycle.rs`: Don't allow invalid cycles to prove bounds
- `./self-outlives-lint.rs`: Ensures that an e.g. `Self: 'a` is written on the traits GAT if that bound can be implied from the GAT usage in the trait
- `./shadowing.rs`: Don't allow lifetime shadowing in params
- `./streaming_iterator.rs`: `StreamingIterator`(`LendingIterator`) pattern
- `./trait-objects.rs`: Disallow trait objects for traits with GATs
- `./variance_constraints.rs`: Require that GAT substs be invariant

## Remaining bugs and open issues

A full list of remaining open issues can be found at: https://github.com/rust-lang/rust/labels/F-generic_associated_types

There are some `known-bug` tests in-tree at `src/test/ui/generic-associated-types/bugs`.

Here I'll categorize most of those that GAT bugs (or involve a pattern found more with GATs), but not those that include GATs but not a GAT issue in and of itself. (I also won't include issues directly for things listed elsewhere here.)

Using the concrete type of a GAT instead of the projection type can give errors, since lifetimes are chosen to be early-bound vs late-bound.
- rust-lang#85533
- rust-lang#87803

In certain cases, we can run into cycle or overflow errors. This is more generally a problem with associated types.
- rust-lang#87755
- rust-lang#87758

Bounds on an associatd type need to be proven by an impl, but where clauses need to be proven by the usage. This can lead to confusion when users write one when they mean the other.
- rust-lang#87831
- rust-lang#90573

We sometimes can't normalize closure signatures fully. Really an asociated types issue, but might happen a bit more frequently with GATs, since more obvious place for HRTB lifetimes.
- rust-lang#88382

When calling a function, we assign types to parameters "too late", after we already try (and fail) to normalize projections. Another associated types issue that might pop up more with GATs.
- rust-lang#88460
- rust-lang#96230

We don't fully have implied bounds for lifetimes appearing in GAT trait paths, which can lead to unconstrained type errors.
- rust-lang#88526

Suggestion for adding lifetime bounds can suggest unhelpful fixes (`T: 'a` instead of `Self: 'a`), but the next compiler error after making the suggested change is helpful.
- rust-lang#90816
- rust-lang#92096
- rust-lang#95268

We can end up requiring that `for<'a> I: 'a` when we really want `for<'a where I: 'a> I: 'a`. This can leave unhelpful errors than effectively can't be satisfied unless `I: 'static`. Requires bigger changes and not only GATs.
- rust-lang#91693

Unlike with non-generic associated types, we don't eagerly normalize with param env candidates. This is intended behavior (for now), to avoid accidentaly stabilizing picking arbitrary impls.
- rust-lang#91762

Some Iterator adapter patterns (namely `filter`) require Polonius or unsafe to work.
- rust-lang#92985

## Potential Future work

### Universal type/const quantification

No work has been done to implement this. There are also some questions around implied bounds.

###  Object-safe GATs

The intention is to make traits with GATs object-safe. There are some design work to be done around well-formedness rules and general implementation.

### GATified std lib types

It would be helpful to either introduce new std lib traits (like `LendingIterator`) or to modify existing ones (adding a `'a` generic to `Iterator::Item`). There also a number of other candidates, like `Index`/`IndexMut` and `Fn`/`FnMut`/`FnOnce`.

### Reduce the need for `for<'a>`

Seen [here](rust-lang/rfcs#1598 (comment)). One possible syntax:

```rust
trait Iterable {
    type Iter<'a>: Iterator<Item = Self::Item<'a>>;
}

fn foo<T>() where T: Iterable, T::Item<let 'a>: Display { } //note the `let`!
```

### Better implied bounds on higher-ranked things

Currently if we have a `type Item<'a> where self: 'a`, and a `for<'a> T: Iterator<Item<'a> = &'a ()`, this requires `for<'a> Self: 'a`. Really, we want `for<'a where T: 'a> ...`

There was some mentions of this all the back in the RFC thread [here](rust-lang/rfcs#1598 (comment)).

## Alternatives

### Make generics on associated type in bounds a binder

Imagine the bound `for<'a> T: Trait<Item<'a>= &'a ()>`. It might be that `for<'a>` is "too large" and it should instead be `T: Trait<for<'a> Item<'a>= &'a ()>`. Brought up in RFC thread [here](rust-lang/rfcs#1598 (comment)) and in a few places since.

Another related question: Is `for<'a>` the right syntax? Maybe `where<'a>`? Also originally found in RFC thread [here](rust-lang/rfcs#1598 (comment)).

### Stabilize lifetime GATs first

This has been brought up a few times. The idea is to only allow GATs with lifetime parameters to in initial stabilization. This was probably most useful prior to actual implementation. At this point, lifetimes, types, and consts are all implemented and work. It feels like an arbitrary split without strong reason.

## History

* On 2016-04-30, [RFC opened](rust-lang/rfcs#1598)
* On 2017-09-02, RFC merged and [tracking issue opened](rust-lang#44265)
* On 2017-10-23, [Move Generics from MethodSig to TraitItem and ImplItem](rust-lang#44766)
* On 2017-12-01, [Generic Associated Types Parsing & Name Resolution](rust-lang#45904)
* On 2017-12-15, [rust-lang#46706
* On 2018-04-23, [Feature gate where clauses on associated types](rust-lang#49368)
* On 2018-05-10, [Extend tests for RFC1598 (GAT)](rust-lang#49423)
* On 2018-05-24, [Finish implementing GATs (Chalk)](rust-lang/chalk#134)
* On 2019-12-21, [Make GATs less ICE-prone](rust-lang#67160)
* On 2020-02-13, [fix lifetime shadowing check in GATs](rust-lang#68938)
* On 2020-06-20, [Projection bound validation](rust-lang#72788)
* On 2020-10-06, [Separate projection bounds and predicates](rust-lang#73905)
* On 2021-02-05, [Generic associated types in trait paths](rust-lang#79554)
* On 2021-02-06, [Trait objects do not work with generic associated types](rust-lang#81823)
* On 2021-04-28, [Make traits with GATs not object safe](rust-lang#84622)
* On 2021-05-11, [Improve diagnostics for GATs](rust-lang#82272)
* On 2021-07-16, [Make GATs no longer an incomplete feature](rust-lang#84623)
* On 2021-07-16, [Replace associated item bound vars with placeholders when projecting](rust-lang#86993)
* On 2021-07-26, [GATs: Decide whether to have defaults for `where Self: 'a`](rust-lang#87479)
* On 2021-08-25, [Normalize projections under binders](rust-lang#85499)
* On 2021-08-03, [The push for GATs stabilization](https://blog.rust-lang.org/2021/08/03/GATs-stabilization-push.html)
* On 2021-08-12, [Detect stricter constraints on gats where clauses in impls vs trait](rust-lang#88336)
* On 2021-09-20, [Proposal: Change syntax of where clauses on type aliases](rust-lang#89122)
* On 2021-11-06, [Implementation of GATs outlives lint](rust-lang#89970)
* On 2021-12-29. [Parse and suggest moving where clauses after equals for type aliases](rust-lang#92118)
* On 2022-01-15, [Ignore static lifetimes for GATs outlives lint](rust-lang#92865)
* On 2022-02-08, [Don't constrain projection predicates with inference vars in GAT substs](rust-lang#92917)
* On 2022-02-15, [Rework GAT where clause check](rust-lang#93820)
* On 2022-02-19, [Only mark projection as ambiguous if GAT substs are constrained](rust-lang#93892)
* On 2022-03-03, [Support GATs in Rustdoc](rust-lang#94009)
* On 2022-03-06, [Change location of where clause on GATs](rust-lang#90076)
* On 2022-05-04, [A shiny future with GATs blog post](https://jackh726.github.io/rust/2022/05/04/a-shiny-future-with-gats.html)
* On 2022-05-04, [Stabilization PR](rust-lang#96709)
calebcartwright pushed a commit to calebcartwright/rustfmt that referenced this pull request Jan 24, 2023
Stabilize generic associated types

Closes #44265

r? `@nikomatsakis`

# ⚡ Status of the discussion ⚡

* [x] There have been several serious concerns raised, [summarized here](rust-lang/rust#96709 (comment)).
* [x] There has also been a [deep-dive comment](rust-lang/rust#96709 (comment)) explaining some of the "patterns of code" that are enabled by GATs, based on use-cases posted to this thread or on the tracking issue.
* [x] We have modeled some aspects of GATs in [a-mir-formality](https://github.com/nikomatsakis/a-mir-formality) to give better confidence in how they will be resolved in the future. [You can read a write-up here](https://github.com/rust-lang/types-team/blob/master/minutes/2022-07-08-implied-bounds-and-wf-checking.md).
* [x] The major points of the discussion have been [summarized on the GAT initiative repository](https://rust-lang.github.io/generic-associated-types-initiative/mvp.html).
* [x] [FCP has been proposed](rust-lang/rust#96709 (comment)) and we are awaiting final decisions and discussion amidst the relevant team members.

# Stabilization proposal

This PR proposes the stabilization of `#![feature(generic_associated_types)]`. While there a number of future additions to be made and bugs to be fixed (both discussed below), properly doing these will require significant language design and will ultimately likely be backwards-compatible. Given the overwhelming desire to have some form of generic associated types (GATs) available on stable and the stability of the "simple" uses, stabilizing the current subset of GAT features is almost certainly the correct next step.

Tracking issue: #44265
Initiative: https://rust-lang.github.io/generic-associated-types-initiative/
RFC: https://github.com/rust-lang/rfcs/blob/master/text/1598-generic_associated_types.md
Version: 1.65 (2022-08-22 => beta, 2022-11-03 => stable).

## Motivation

There are a myriad of potential use cases for GATs. Stabilization unblocks probable future language features (e.g. async functions in traits), potential future standard library features (e.g. a `LendingIterator` or some form of `Iterator` with a lifetime generic), and a plethora of user use cases (some of which can be seen just by scrolling through the tracking issue and looking at all the issues linking to it).

There are a myriad of potential use cases for GATs. First, there are many users that have chosen to not use GATs primarily because they are not stable (some of which can be seen just by scrolling through the tracking issue and looking at all the issues linking to it). Second, while language feature desugaring isn't *blocked* on stabilization, it gives more confidence on using the feature. Likewise, library features like `LendingIterator` are not necessarily blocked on stabilization to be implemented unstably; however few, if any, public-facing APIs actually use unstable features.

This feature has a long history of design, discussion, and developement - the RFC was first introduced roughly 6 years ago. While there are still a number of features left to implement and bugs left to fix, it's clear that it's unlikely those will have backwards-incompatibility concerns. Additionally, the bugs that do exist do not strongly impede the most-common use cases.

## What is stabilized

The primary language feature stabilized here is the ability to have generics on associated types, as so. Additionally, where clauses on associated types will now be accepted, regardless if the associated type is generic or not.

```rust
trait ATraitWithGATs {
    type Assoc<'a, T> where T: 'a;
}

trait ATraitWithoutGATs<'a, T> {
    type Assoc where T: 'a;
}
```

When adding an impl for a trait with generic associated types, the generics for the associated type are copied as well. Note that where clauses are allowed both after the specified type and before the equals sign; however, the latter is a warn-by-default deprecation.

```rust
struct X;
struct Y;

impl ATraitWithGATs for X {
    type Assoc<'a, T> = &'a T
      where T: 'a;
}
impl ATraitWithGATs for Y {
    type Assoc<'a, T>
      where T: 'a
    = &'a T;
}
```

To use a GAT in a function, generics are specified on the associated type, as if it was a struct or enum. GATs can also be specified in trait bounds:

```rust
fn accepts_gat<'a, T>(t: &'a T) -> T::Assoc<'a, T>
  where for<'x> T: ATraitWithGATs<Assoc<'a, T> = &'a T> {
    ...
}
```

GATs can also appear in trait methods. However, depending on how they are used, they may confer where clauses on the associated type definition. More information can be found [here](rust-lang/rust#87479). Briefly, where clauses are required when those bounds can be proven in the methods that *construct* the GAT or other associated types that use the GAT in the trait. This allows impls to have maximum flexibility in the types defined for the associated type.

To take a relatively simple example:

```rust
trait Iterable {
    type Item<'a>;
    type Iterator<'a>: Iterator<Item = Self::Item<'a>>;

    fn iter<'x>(&'x self) -> Self::Iterator<'x>;
    //^ We know that `Self: 'a` for `Iterator<'a>`, so we require that bound on `Iterator`
    //  `Iterator` uses `Self::Item`, so we also require a `Self: 'a` on `Item` too
}
```

A couple well-explained examples are available in a previous [blog post](https://blog.rust-lang.org/2021/08/03/GATs-stabilization-push.html).

## What isn't stabilized/implemented

### Universal type/const quantification

Currently, you can write a bound like `X: for<'a> Trait<Assoc<'a> = &'a ()>`. However, you cannot currently write `for<T> X: Trait<Assoc<T> = T>` or `for<const N> X: Trait<Assoc<N> = [usize; N]>`.

Here is an example where this is needed:

```rust
trait Foo {}

trait Trait {
    type Assoc<F: Foo>;
}

trait Trait2: Sized {
    fn foo<F: Foo, T: Trait<Assoc<F> = F>>(_t: T);
}
```

In the above example, the *caller* must specify `F`, which is likely not what is desired.

### Object-safe GATs

Unlike non-generic associated types, traits with GATs are not currently object-safe. In other words the following are not allowed:

```rust
trait Trait {
    type Assoc<'a>;
}

fn foo(t: &dyn for<'a> Trait<Assoc<'a> = &'a ()>) {}
         //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not allowed

let ty: Box<dyn for<'a> Trait<Assoc<'a> = &'a ()>>;
          //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not allowed
```

### Higher-kinded types

You cannot write currently (and there are no current plans to implement this):

```rust
struct Struct<'a> {}

fn foo(s: for<'a> Struct<'a>) {}
```

## Tests

There are many tests covering GATs that can be found in  `src/test/ui/generic-associated-types`. Here, I'll list (in alphanumeric order) tests highlight some important behavior or contain important patterns.

- `./parse/*`: Parsing of GATs in traits and impls, and the trait path with GATs
- `./collections-project-default.rs`: Interaction with associated type defaults
- `./collections.rs`: The `Collection` pattern
- `./const-generics-gat-in-trait-return-type-*.rs`: Const parameters
- `./constraint-assoc-type-suggestion.rs`: Emit correct syntax in suggestion
- `./cross-crate-bounds.rs`: Ensure we handles bounds across crates the same
- `./elided-in-expr-position.rs`: Disallow lifetime elision in return position
- `./gat-in-trait-path-undeclared-lifetime.rs`: Ensure we error on undeclared lifetime in trait path
- `./gat-in-trait-path.rs`: Base trait path case
- `./gat-trait-path-generic-type-arg.rs`: Don't allow shadowing of parameters
- `./gat-trait-path-parenthesised-args.rs`: Don't allow paranthesized args in trait path
- `./generic-associated-types-where.rs`: Ensure that we require where clauses from trait to be met on impl
- `./impl_bounds.rs`: Check that the bounds on GATs in an impl are checked
- `./issue-76826.rs`: `Windows` pattern
- `./issue-78113-lifetime-mismatch-dyn-trait-box.rs`: Implicit 'static diagnostics
- `./issue-84931.rs`: Ensure that we have a where clause on GAT to ensure trait parameter lives long enough
- `./issue-87258_a.rs`: Unconstrained opaque type with TAITs
- `./issue-87429-2.rs`: Ensure we can use bound vars in the bounds
- `./issue-87429-associated-type-default.rs`: Ensure bounds hold with associated type defaults, for both trait and impl
- `./issue-87429-specialization.rs`: Check that bounds hold under specialization
- `./issue-88595.rs`: Under the outlives lint, we require a bound for both trait and GAT lifetime when trait lifetime is used in function
- `./issue-90014.rs`: Lifetime bounds are checked with TAITs
- `./issue-91139.rs`: Under migrate mode, but not NLL, we don't capture implied bounds from HRTB lifetimes used in a function and GATs
- `./issue-91762.rs`: We used to too eagerly pick param env candidates when normalizing with GATs. We now require explicit parameters specified.
- `./issue-95305.rs`: Disallow lifetime elision in trait paths
- `./iterable.rs`: `Iterable` pattern
- `./method-unsatified-assoc-type-predicate.rs`: Print predicates with GATs correctly in method resolve error
- `./missing_lifetime_const.rs`: Ensure we must specify lifetime args (not elidable)
- `./missing-where-clause-on-trait.rs`: Ensure we don't allow stricter bounds on impl than trait
- `./parameter_number_and_kind_impl.rs`: Ensure paramters on GAT in impl match GAT in trait
- `./pointer_family.rs`: `PointerFamily` pattern
- `./projection-bound-cycle.rs`: Don't allow invalid cycles to prove bounds
- `./self-outlives-lint.rs`: Ensures that an e.g. `Self: 'a` is written on the traits GAT if that bound can be implied from the GAT usage in the trait
- `./shadowing.rs`: Don't allow lifetime shadowing in params
- `./streaming_iterator.rs`: `StreamingIterator`(`LendingIterator`) pattern
- `./trait-objects.rs`: Disallow trait objects for traits with GATs
- `./variance_constraints.rs`: Require that GAT substs be invariant

## Remaining bugs and open issues

A full list of remaining open issues can be found at: https://github.com/rust-lang/rust/labels/F-generic_associated_types

There are some `known-bug` tests in-tree at `src/test/ui/generic-associated-types/bugs`.

Here I'll categorize most of those that GAT bugs (or involve a pattern found more with GATs), but not those that include GATs but not a GAT issue in and of itself. (I also won't include issues directly for things listed elsewhere here.)

Using the concrete type of a GAT instead of the projection type can give errors, since lifetimes are chosen to be early-bound vs late-bound.
- #85533
- #87803

In certain cases, we can run into cycle or overflow errors. This is more generally a problem with associated types.
- #87755
- #87758

Bounds on an associatd type need to be proven by an impl, but where clauses need to be proven by the usage. This can lead to confusion when users write one when they mean the other.
- #87831
- #90573

We sometimes can't normalize closure signatures fully. Really an asociated types issue, but might happen a bit more frequently with GATs, since more obvious place for HRTB lifetimes.
- #88382

When calling a function, we assign types to parameters "too late", after we already try (and fail) to normalize projections. Another associated types issue that might pop up more with GATs.
- #88460
- #96230

We don't fully have implied bounds for lifetimes appearing in GAT trait paths, which can lead to unconstrained type errors.
- #88526

Suggestion for adding lifetime bounds can suggest unhelpful fixes (`T: 'a` instead of `Self: 'a`), but the next compiler error after making the suggested change is helpful.
- #90816
- #92096
- #95268

We can end up requiring that `for<'a> I: 'a` when we really want `for<'a where I: 'a> I: 'a`. This can leave unhelpful errors than effectively can't be satisfied unless `I: 'static`. Requires bigger changes and not only GATs.
- #91693

Unlike with non-generic associated types, we don't eagerly normalize with param env candidates. This is intended behavior (for now), to avoid accidentaly stabilizing picking arbitrary impls.
- #91762

Some Iterator adapter patterns (namely `filter`) require Polonius or unsafe to work.
- #92985

## Potential Future work

### Universal type/const quantification

No work has been done to implement this. There are also some questions around implied bounds.

###  Object-safe GATs

The intention is to make traits with GATs object-safe. There are some design work to be done around well-formedness rules and general implementation.

### GATified std lib types

It would be helpful to either introduce new std lib traits (like `LendingIterator`) or to modify existing ones (adding a `'a` generic to `Iterator::Item`). There also a number of other candidates, like `Index`/`IndexMut` and `Fn`/`FnMut`/`FnOnce`.

### Reduce the need for `for<'a>`

Seen [here](rust-lang/rfcs#1598 (comment)). One possible syntax:

```rust
trait Iterable {
    type Iter<'a>: Iterator<Item = Self::Item<'a>>;
}

fn foo<T>() where T: Iterable, T::Item<let 'a>: Display { } //note the `let`!
```

### Better implied bounds on higher-ranked things

Currently if we have a `type Item<'a> where self: 'a`, and a `for<'a> T: Iterator<Item<'a> = &'a ()`, this requires `for<'a> Self: 'a`. Really, we want `for<'a where T: 'a> ...`

There was some mentions of this all the back in the RFC thread [here](rust-lang/rfcs#1598 (comment)).

## Alternatives

### Make generics on associated type in bounds a binder

Imagine the bound `for<'a> T: Trait<Item<'a>= &'a ()>`. It might be that `for<'a>` is "too large" and it should instead be `T: Trait<for<'a> Item<'a>= &'a ()>`. Brought up in RFC thread [here](rust-lang/rfcs#1598 (comment)) and in a few places since.

Another related question: Is `for<'a>` the right syntax? Maybe `where<'a>`? Also originally found in RFC thread [here](rust-lang/rfcs#1598 (comment)).

### Stabilize lifetime GATs first

This has been brought up a few times. The idea is to only allow GATs with lifetime parameters to in initial stabilization. This was probably most useful prior to actual implementation. At this point, lifetimes, types, and consts are all implemented and work. It feels like an arbitrary split without strong reason.

## History

* On 2016-04-30, [RFC opened](rust-lang/rfcs#1598)
* On 2017-09-02, RFC merged and [tracking issue opened](rust-lang/rust#44265)
* On 2017-10-23, [Move Generics from MethodSig to TraitItem and ImplItem](rust-lang/rust#44766)
* On 2017-12-01, [Generic Associated Types Parsing & Name Resolution](rust-lang/rust#45904)
* On 2017-12-15, [rust-lang/rust#46706
* On 2018-04-23, [Feature gate where clauses on associated types](rust-lang/rust#49368)
* On 2018-05-10, [Extend tests for RFC1598 (GAT)](rust-lang/rust#49423)
* On 2018-05-24, [Finish implementing GATs (Chalk)](rust-lang/chalk#134)
* On 2019-12-21, [Make GATs less ICE-prone](rust-lang/rust#67160)
* On 2020-02-13, [fix lifetime shadowing check in GATs](rust-lang/rust#68938)
* On 2020-06-20, [Projection bound validation](rust-lang/rust#72788)
* On 2020-10-06, [Separate projection bounds and predicates](rust-lang/rust#73905)
* On 2021-02-05, [Generic associated types in trait paths](rust-lang/rust#79554)
* On 2021-02-06, [Trait objects do not work with generic associated types](rust-lang/rust#81823)
* On 2021-04-28, [Make traits with GATs not object safe](rust-lang/rust#84622)
* On 2021-05-11, [Improve diagnostics for GATs](rust-lang/rust#82272)
* On 2021-07-16, [Make GATs no longer an incomplete feature](rust-lang/rust#84623)
* On 2021-07-16, [Replace associated item bound vars with placeholders when projecting](rust-lang/rust#86993)
* On 2021-07-26, [GATs: Decide whether to have defaults for `where Self: 'a`](rust-lang/rust#87479)
* On 2021-08-25, [Normalize projections under binders](rust-lang/rust#85499)
* On 2021-08-03, [The push for GATs stabilization](https://blog.rust-lang.org/2021/08/03/GATs-stabilization-push.html)
* On 2021-08-12, [Detect stricter constraints on gats where clauses in impls vs trait](rust-lang/rust#88336)
* On 2021-09-20, [Proposal: Change syntax of where clauses on type aliases](rust-lang/rust#89122)
* On 2021-11-06, [Implementation of GATs outlives lint](rust-lang/rust#89970)
* On 2021-12-29. [Parse and suggest moving where clauses after equals for type aliases](rust-lang/rust#92118)
* On 2022-01-15, [Ignore static lifetimes for GATs outlives lint](rust-lang/rust#92865)
* On 2022-02-08, [Don't constrain projection predicates with inference vars in GAT substs](rust-lang/rust#92917)
* On 2022-02-15, [Rework GAT where clause check](rust-lang/rust#93820)
* On 2022-02-19, [Only mark projection as ambiguous if GAT substs are constrained](rust-lang/rust#93892)
* On 2022-03-03, [Support GATs in Rustdoc](rust-lang/rust#94009)
* On 2022-03-06, [Change location of where clause on GATs](rust-lang/rust#90076)
* On 2022-05-04, [A shiny future with GATs blog post](https://jackh726.github.io/rust/2022/05/04/a-shiny-future-with-gats.html)
* On 2022-05-04, [Stabilization PR](rust-lang/rust#96709)
RalfJung pushed a commit to RalfJung/rust-analyzer that referenced this pull request Apr 20, 2024
Stabilize generic associated types

Closes #44265

r? `@nikomatsakis`

# ⚡ Status of the discussion ⚡

* [x] There have been several serious concerns raised, [summarized here](rust-lang/rust#96709 (comment)).
* [x] There has also been a [deep-dive comment](rust-lang/rust#96709 (comment)) explaining some of the "patterns of code" that are enabled by GATs, based on use-cases posted to this thread or on the tracking issue.
* [x] We have modeled some aspects of GATs in [a-mir-formality](https://github.com/nikomatsakis/a-mir-formality) to give better confidence in how they will be resolved in the future. [You can read a write-up here](https://github.com/rust-lang/types-team/blob/master/minutes/2022-07-08-implied-bounds-and-wf-checking.md).
* [x] The major points of the discussion have been [summarized on the GAT initiative repository](https://rust-lang.github.io/generic-associated-types-initiative/mvp.html).
* [x] [FCP has been proposed](rust-lang/rust#96709 (comment)) and we are awaiting final decisions and discussion amidst the relevant team members.

# Stabilization proposal

This PR proposes the stabilization of `#![feature(generic_associated_types)]`. While there a number of future additions to be made and bugs to be fixed (both discussed below), properly doing these will require significant language design and will ultimately likely be backwards-compatible. Given the overwhelming desire to have some form of generic associated types (GATs) available on stable and the stability of the "simple" uses, stabilizing the current subset of GAT features is almost certainly the correct next step.

Tracking issue: #44265
Initiative: https://rust-lang.github.io/generic-associated-types-initiative/
RFC: https://github.com/rust-lang/rfcs/blob/master/text/1598-generic_associated_types.md
Version: 1.65 (2022-08-22 => beta, 2022-11-03 => stable).

## Motivation

There are a myriad of potential use cases for GATs. Stabilization unblocks probable future language features (e.g. async functions in traits), potential future standard library features (e.g. a `LendingIterator` or some form of `Iterator` with a lifetime generic), and a plethora of user use cases (some of which can be seen just by scrolling through the tracking issue and looking at all the issues linking to it).

There are a myriad of potential use cases for GATs. First, there are many users that have chosen to not use GATs primarily because they are not stable (some of which can be seen just by scrolling through the tracking issue and looking at all the issues linking to it). Second, while language feature desugaring isn't *blocked* on stabilization, it gives more confidence on using the feature. Likewise, library features like `LendingIterator` are not necessarily blocked on stabilization to be implemented unstably; however few, if any, public-facing APIs actually use unstable features.

This feature has a long history of design, discussion, and developement - the RFC was first introduced roughly 6 years ago. While there are still a number of features left to implement and bugs left to fix, it's clear that it's unlikely those will have backwards-incompatibility concerns. Additionally, the bugs that do exist do not strongly impede the most-common use cases.

## What is stabilized

The primary language feature stabilized here is the ability to have generics on associated types, as so. Additionally, where clauses on associated types will now be accepted, regardless if the associated type is generic or not.

```rust
trait ATraitWithGATs {
    type Assoc<'a, T> where T: 'a;
}

trait ATraitWithoutGATs<'a, T> {
    type Assoc where T: 'a;
}
```

When adding an impl for a trait with generic associated types, the generics for the associated type are copied as well. Note that where clauses are allowed both after the specified type and before the equals sign; however, the latter is a warn-by-default deprecation.

```rust
struct X;
struct Y;

impl ATraitWithGATs for X {
    type Assoc<'a, T> = &'a T
      where T: 'a;
}
impl ATraitWithGATs for Y {
    type Assoc<'a, T>
      where T: 'a
    = &'a T;
}
```

To use a GAT in a function, generics are specified on the associated type, as if it was a struct or enum. GATs can also be specified in trait bounds:

```rust
fn accepts_gat<'a, T>(t: &'a T) -> T::Assoc<'a, T>
  where for<'x> T: ATraitWithGATs<Assoc<'a, T> = &'a T> {
    ...
}
```

GATs can also appear in trait methods. However, depending on how they are used, they may confer where clauses on the associated type definition. More information can be found [here](rust-lang/rust#87479). Briefly, where clauses are required when those bounds can be proven in the methods that *construct* the GAT or other associated types that use the GAT in the trait. This allows impls to have maximum flexibility in the types defined for the associated type.

To take a relatively simple example:

```rust
trait Iterable {
    type Item<'a>;
    type Iterator<'a>: Iterator<Item = Self::Item<'a>>;

    fn iter<'x>(&'x self) -> Self::Iterator<'x>;
    //^ We know that `Self: 'a` for `Iterator<'a>`, so we require that bound on `Iterator`
    //  `Iterator` uses `Self::Item`, so we also require a `Self: 'a` on `Item` too
}
```

A couple well-explained examples are available in a previous [blog post](https://blog.rust-lang.org/2021/08/03/GATs-stabilization-push.html).

## What isn't stabilized/implemented

### Universal type/const quantification

Currently, you can write a bound like `X: for<'a> Trait<Assoc<'a> = &'a ()>`. However, you cannot currently write `for<T> X: Trait<Assoc<T> = T>` or `for<const N> X: Trait<Assoc<N> = [usize; N]>`.

Here is an example where this is needed:

```rust
trait Foo {}

trait Trait {
    type Assoc<F: Foo>;
}

trait Trait2: Sized {
    fn foo<F: Foo, T: Trait<Assoc<F> = F>>(_t: T);
}
```

In the above example, the *caller* must specify `F`, which is likely not what is desired.

### Object-safe GATs

Unlike non-generic associated types, traits with GATs are not currently object-safe. In other words the following are not allowed:

```rust
trait Trait {
    type Assoc<'a>;
}

fn foo(t: &dyn for<'a> Trait<Assoc<'a> = &'a ()>) {}
         //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not allowed

let ty: Box<dyn for<'a> Trait<Assoc<'a> = &'a ()>>;
          //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not allowed
```

### Higher-kinded types

You cannot write currently (and there are no current plans to implement this):

```rust
struct Struct<'a> {}

fn foo(s: for<'a> Struct<'a>) {}
```

## Tests

There are many tests covering GATs that can be found in  `src/test/ui/generic-associated-types`. Here, I'll list (in alphanumeric order) tests highlight some important behavior or contain important patterns.

- `./parse/*`: Parsing of GATs in traits and impls, and the trait path with GATs
- `./collections-project-default.rs`: Interaction with associated type defaults
- `./collections.rs`: The `Collection` pattern
- `./const-generics-gat-in-trait-return-type-*.rs`: Const parameters
- `./constraint-assoc-type-suggestion.rs`: Emit correct syntax in suggestion
- `./cross-crate-bounds.rs`: Ensure we handles bounds across crates the same
- `./elided-in-expr-position.rs`: Disallow lifetime elision in return position
- `./gat-in-trait-path-undeclared-lifetime.rs`: Ensure we error on undeclared lifetime in trait path
- `./gat-in-trait-path.rs`: Base trait path case
- `./gat-trait-path-generic-type-arg.rs`: Don't allow shadowing of parameters
- `./gat-trait-path-parenthesised-args.rs`: Don't allow paranthesized args in trait path
- `./generic-associated-types-where.rs`: Ensure that we require where clauses from trait to be met on impl
- `./impl_bounds.rs`: Check that the bounds on GATs in an impl are checked
- `./issue-76826.rs`: `Windows` pattern
- `./issue-78113-lifetime-mismatch-dyn-trait-box.rs`: Implicit 'static diagnostics
- `./issue-84931.rs`: Ensure that we have a where clause on GAT to ensure trait parameter lives long enough
- `./issue-87258_a.rs`: Unconstrained opaque type with TAITs
- `./issue-87429-2.rs`: Ensure we can use bound vars in the bounds
- `./issue-87429-associated-type-default.rs`: Ensure bounds hold with associated type defaults, for both trait and impl
- `./issue-87429-specialization.rs`: Check that bounds hold under specialization
- `./issue-88595.rs`: Under the outlives lint, we require a bound for both trait and GAT lifetime when trait lifetime is used in function
- `./issue-90014.rs`: Lifetime bounds are checked with TAITs
- `./issue-91139.rs`: Under migrate mode, but not NLL, we don't capture implied bounds from HRTB lifetimes used in a function and GATs
- `./issue-91762.rs`: We used to too eagerly pick param env candidates when normalizing with GATs. We now require explicit parameters specified.
- `./issue-95305.rs`: Disallow lifetime elision in trait paths
- `./iterable.rs`: `Iterable` pattern
- `./method-unsatified-assoc-type-predicate.rs`: Print predicates with GATs correctly in method resolve error
- `./missing_lifetime_const.rs`: Ensure we must specify lifetime args (not elidable)
- `./missing-where-clause-on-trait.rs`: Ensure we don't allow stricter bounds on impl than trait
- `./parameter_number_and_kind_impl.rs`: Ensure paramters on GAT in impl match GAT in trait
- `./pointer_family.rs`: `PointerFamily` pattern
- `./projection-bound-cycle.rs`: Don't allow invalid cycles to prove bounds
- `./self-outlives-lint.rs`: Ensures that an e.g. `Self: 'a` is written on the traits GAT if that bound can be implied from the GAT usage in the trait
- `./shadowing.rs`: Don't allow lifetime shadowing in params
- `./streaming_iterator.rs`: `StreamingIterator`(`LendingIterator`) pattern
- `./trait-objects.rs`: Disallow trait objects for traits with GATs
- `./variance_constraints.rs`: Require that GAT substs be invariant

## Remaining bugs and open issues

A full list of remaining open issues can be found at: https://github.com/rust-lang/rust/labels/F-generic_associated_types

There are some `known-bug` tests in-tree at `src/test/ui/generic-associated-types/bugs`.

Here I'll categorize most of those that GAT bugs (or involve a pattern found more with GATs), but not those that include GATs but not a GAT issue in and of itself. (I also won't include issues directly for things listed elsewhere here.)

Using the concrete type of a GAT instead of the projection type can give errors, since lifetimes are chosen to be early-bound vs late-bound.
- #85533
- #87803

In certain cases, we can run into cycle or overflow errors. This is more generally a problem with associated types.
- #87755
- #87758

Bounds on an associatd type need to be proven by an impl, but where clauses need to be proven by the usage. This can lead to confusion when users write one when they mean the other.
- #87831
- #90573

We sometimes can't normalize closure signatures fully. Really an asociated types issue, but might happen a bit more frequently with GATs, since more obvious place for HRTB lifetimes.
- #88382

When calling a function, we assign types to parameters "too late", after we already try (and fail) to normalize projections. Another associated types issue that might pop up more with GATs.
- #88460
- #96230

We don't fully have implied bounds for lifetimes appearing in GAT trait paths, which can lead to unconstrained type errors.
- #88526

Suggestion for adding lifetime bounds can suggest unhelpful fixes (`T: 'a` instead of `Self: 'a`), but the next compiler error after making the suggested change is helpful.
- #90816
- #92096
- #95268

We can end up requiring that `for<'a> I: 'a` when we really want `for<'a where I: 'a> I: 'a`. This can leave unhelpful errors than effectively can't be satisfied unless `I: 'static`. Requires bigger changes and not only GATs.
- #91693

Unlike with non-generic associated types, we don't eagerly normalize with param env candidates. This is intended behavior (for now), to avoid accidentaly stabilizing picking arbitrary impls.
- #91762

Some Iterator adapter patterns (namely `filter`) require Polonius or unsafe to work.
- #92985

## Potential Future work

### Universal type/const quantification

No work has been done to implement this. There are also some questions around implied bounds.

###  Object-safe GATs

The intention is to make traits with GATs object-safe. There are some design work to be done around well-formedness rules and general implementation.

### GATified std lib types

It would be helpful to either introduce new std lib traits (like `LendingIterator`) or to modify existing ones (adding a `'a` generic to `Iterator::Item`). There also a number of other candidates, like `Index`/`IndexMut` and `Fn`/`FnMut`/`FnOnce`.

### Reduce the need for `for<'a>`

Seen [here](rust-lang/rfcs#1598 (comment)). One possible syntax:

```rust
trait Iterable {
    type Iter<'a>: Iterator<Item = Self::Item<'a>>;
}

fn foo<T>() where T: Iterable, T::Item<let 'a>: Display { } //note the `let`!
```

### Better implied bounds on higher-ranked things

Currently if we have a `type Item<'a> where self: 'a`, and a `for<'a> T: Iterator<Item<'a> = &'a ()`, this requires `for<'a> Self: 'a`. Really, we want `for<'a where T: 'a> ...`

There was some mentions of this all the back in the RFC thread [here](rust-lang/rfcs#1598 (comment)).

## Alternatives

### Make generics on associated type in bounds a binder

Imagine the bound `for<'a> T: Trait<Item<'a>= &'a ()>`. It might be that `for<'a>` is "too large" and it should instead be `T: Trait<for<'a> Item<'a>= &'a ()>`. Brought up in RFC thread [here](rust-lang/rfcs#1598 (comment)) and in a few places since.

Another related question: Is `for<'a>` the right syntax? Maybe `where<'a>`? Also originally found in RFC thread [here](rust-lang/rfcs#1598 (comment)).

### Stabilize lifetime GATs first

This has been brought up a few times. The idea is to only allow GATs with lifetime parameters to in initial stabilization. This was probably most useful prior to actual implementation. At this point, lifetimes, types, and consts are all implemented and work. It feels like an arbitrary split without strong reason.

## History

* On 2016-04-30, [RFC opened](rust-lang/rfcs#1598)
* On 2017-09-02, RFC merged and [tracking issue opened](rust-lang/rust#44265)
* On 2017-10-23, [Move Generics from MethodSig to TraitItem and ImplItem](rust-lang/rust#44766)
* On 2017-12-01, [Generic Associated Types Parsing & Name Resolution](rust-lang/rust#45904)
* On 2017-12-15, [rust-lang/rust#46706
* On 2018-04-23, [Feature gate where clauses on associated types](rust-lang/rust#49368)
* On 2018-05-10, [Extend tests for RFC1598 (GAT)](rust-lang/rust#49423)
* On 2018-05-24, [Finish implementing GATs (Chalk)](rust-lang/chalk#134)
* On 2019-12-21, [Make GATs less ICE-prone](rust-lang/rust#67160)
* On 2020-02-13, [fix lifetime shadowing check in GATs](rust-lang/rust#68938)
* On 2020-06-20, [Projection bound validation](rust-lang/rust#72788)
* On 2020-10-06, [Separate projection bounds and predicates](rust-lang/rust#73905)
* On 2021-02-05, [Generic associated types in trait paths](rust-lang/rust#79554)
* On 2021-02-06, [Trait objects do not work with generic associated types](rust-lang/rust#81823)
* On 2021-04-28, [Make traits with GATs not object safe](rust-lang/rust#84622)
* On 2021-05-11, [Improve diagnostics for GATs](rust-lang/rust#82272)
* On 2021-07-16, [Make GATs no longer an incomplete feature](rust-lang/rust#84623)
* On 2021-07-16, [Replace associated item bound vars with placeholders when projecting](rust-lang/rust#86993)
* On 2021-07-26, [GATs: Decide whether to have defaults for `where Self: 'a`](rust-lang/rust#87479)
* On 2021-08-25, [Normalize projections under binders](rust-lang/rust#85499)
* On 2021-08-03, [The push for GATs stabilization](https://blog.rust-lang.org/2021/08/03/GATs-stabilization-push.html)
* On 2021-08-12, [Detect stricter constraints on gats where clauses in impls vs trait](rust-lang/rust#88336)
* On 2021-09-20, [Proposal: Change syntax of where clauses on type aliases](rust-lang/rust#89122)
* On 2021-11-06, [Implementation of GATs outlives lint](rust-lang/rust#89970)
* On 2021-12-29. [Parse and suggest moving where clauses after equals for type aliases](rust-lang/rust#92118)
* On 2022-01-15, [Ignore static lifetimes for GATs outlives lint](rust-lang/rust#92865)
* On 2022-02-08, [Don't constrain projection predicates with inference vars in GAT substs](rust-lang/rust#92917)
* On 2022-02-15, [Rework GAT where clause check](rust-lang/rust#93820)
* On 2022-02-19, [Only mark projection as ambiguous if GAT substs are constrained](rust-lang/rust#93892)
* On 2022-03-03, [Support GATs in Rustdoc](rust-lang/rust#94009)
* On 2022-03-06, [Change location of where clause on GATs](rust-lang/rust#90076)
* On 2022-05-04, [A shiny future with GATs blog post](https://jackh726.github.io/rust/2022/05/04/a-shiny-future-with-gats.html)
* On 2022-05-04, [Stabilization PR](rust-lang/rust#96709)
RalfJung pushed a commit to RalfJung/rust-analyzer that referenced this pull request Apr 27, 2024
Stabilize generic associated types

Closes #44265

r? `@nikomatsakis`

# ⚡ Status of the discussion ⚡

* [x] There have been several serious concerns raised, [summarized here](rust-lang/rust#96709 (comment)).
* [x] There has also been a [deep-dive comment](rust-lang/rust#96709 (comment)) explaining some of the "patterns of code" that are enabled by GATs, based on use-cases posted to this thread or on the tracking issue.
* [x] We have modeled some aspects of GATs in [a-mir-formality](https://github.com/nikomatsakis/a-mir-formality) to give better confidence in how they will be resolved in the future. [You can read a write-up here](https://github.com/rust-lang/types-team/blob/master/minutes/2022-07-08-implied-bounds-and-wf-checking.md).
* [x] The major points of the discussion have been [summarized on the GAT initiative repository](https://rust-lang.github.io/generic-associated-types-initiative/mvp.html).
* [x] [FCP has been proposed](rust-lang/rust#96709 (comment)) and we are awaiting final decisions and discussion amidst the relevant team members.

# Stabilization proposal

This PR proposes the stabilization of `#![feature(generic_associated_types)]`. While there a number of future additions to be made and bugs to be fixed (both discussed below), properly doing these will require significant language design and will ultimately likely be backwards-compatible. Given the overwhelming desire to have some form of generic associated types (GATs) available on stable and the stability of the "simple" uses, stabilizing the current subset of GAT features is almost certainly the correct next step.

Tracking issue: #44265
Initiative: https://rust-lang.github.io/generic-associated-types-initiative/
RFC: https://github.com/rust-lang/rfcs/blob/master/text/1598-generic_associated_types.md
Version: 1.65 (2022-08-22 => beta, 2022-11-03 => stable).

## Motivation

There are a myriad of potential use cases for GATs. Stabilization unblocks probable future language features (e.g. async functions in traits), potential future standard library features (e.g. a `LendingIterator` or some form of `Iterator` with a lifetime generic), and a plethora of user use cases (some of which can be seen just by scrolling through the tracking issue and looking at all the issues linking to it).

There are a myriad of potential use cases for GATs. First, there are many users that have chosen to not use GATs primarily because they are not stable (some of which can be seen just by scrolling through the tracking issue and looking at all the issues linking to it). Second, while language feature desugaring isn't *blocked* on stabilization, it gives more confidence on using the feature. Likewise, library features like `LendingIterator` are not necessarily blocked on stabilization to be implemented unstably; however few, if any, public-facing APIs actually use unstable features.

This feature has a long history of design, discussion, and developement - the RFC was first introduced roughly 6 years ago. While there are still a number of features left to implement and bugs left to fix, it's clear that it's unlikely those will have backwards-incompatibility concerns. Additionally, the bugs that do exist do not strongly impede the most-common use cases.

## What is stabilized

The primary language feature stabilized here is the ability to have generics on associated types, as so. Additionally, where clauses on associated types will now be accepted, regardless if the associated type is generic or not.

```rust
trait ATraitWithGATs {
    type Assoc<'a, T> where T: 'a;
}

trait ATraitWithoutGATs<'a, T> {
    type Assoc where T: 'a;
}
```

When adding an impl for a trait with generic associated types, the generics for the associated type are copied as well. Note that where clauses are allowed both after the specified type and before the equals sign; however, the latter is a warn-by-default deprecation.

```rust
struct X;
struct Y;

impl ATraitWithGATs for X {
    type Assoc<'a, T> = &'a T
      where T: 'a;
}
impl ATraitWithGATs for Y {
    type Assoc<'a, T>
      where T: 'a
    = &'a T;
}
```

To use a GAT in a function, generics are specified on the associated type, as if it was a struct or enum. GATs can also be specified in trait bounds:

```rust
fn accepts_gat<'a, T>(t: &'a T) -> T::Assoc<'a, T>
  where for<'x> T: ATraitWithGATs<Assoc<'a, T> = &'a T> {
    ...
}
```

GATs can also appear in trait methods. However, depending on how they are used, they may confer where clauses on the associated type definition. More information can be found [here](rust-lang/rust#87479). Briefly, where clauses are required when those bounds can be proven in the methods that *construct* the GAT or other associated types that use the GAT in the trait. This allows impls to have maximum flexibility in the types defined for the associated type.

To take a relatively simple example:

```rust
trait Iterable {
    type Item<'a>;
    type Iterator<'a>: Iterator<Item = Self::Item<'a>>;

    fn iter<'x>(&'x self) -> Self::Iterator<'x>;
    //^ We know that `Self: 'a` for `Iterator<'a>`, so we require that bound on `Iterator`
    //  `Iterator` uses `Self::Item`, so we also require a `Self: 'a` on `Item` too
}
```

A couple well-explained examples are available in a previous [blog post](https://blog.rust-lang.org/2021/08/03/GATs-stabilization-push.html).

## What isn't stabilized/implemented

### Universal type/const quantification

Currently, you can write a bound like `X: for<'a> Trait<Assoc<'a> = &'a ()>`. However, you cannot currently write `for<T> X: Trait<Assoc<T> = T>` or `for<const N> X: Trait<Assoc<N> = [usize; N]>`.

Here is an example where this is needed:

```rust
trait Foo {}

trait Trait {
    type Assoc<F: Foo>;
}

trait Trait2: Sized {
    fn foo<F: Foo, T: Trait<Assoc<F> = F>>(_t: T);
}
```

In the above example, the *caller* must specify `F`, which is likely not what is desired.

### Object-safe GATs

Unlike non-generic associated types, traits with GATs are not currently object-safe. In other words the following are not allowed:

```rust
trait Trait {
    type Assoc<'a>;
}

fn foo(t: &dyn for<'a> Trait<Assoc<'a> = &'a ()>) {}
         //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not allowed

let ty: Box<dyn for<'a> Trait<Assoc<'a> = &'a ()>>;
          //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not allowed
```

### Higher-kinded types

You cannot write currently (and there are no current plans to implement this):

```rust
struct Struct<'a> {}

fn foo(s: for<'a> Struct<'a>) {}
```

## Tests

There are many tests covering GATs that can be found in  `src/test/ui/generic-associated-types`. Here, I'll list (in alphanumeric order) tests highlight some important behavior or contain important patterns.

- `./parse/*`: Parsing of GATs in traits and impls, and the trait path with GATs
- `./collections-project-default.rs`: Interaction with associated type defaults
- `./collections.rs`: The `Collection` pattern
- `./const-generics-gat-in-trait-return-type-*.rs`: Const parameters
- `./constraint-assoc-type-suggestion.rs`: Emit correct syntax in suggestion
- `./cross-crate-bounds.rs`: Ensure we handles bounds across crates the same
- `./elided-in-expr-position.rs`: Disallow lifetime elision in return position
- `./gat-in-trait-path-undeclared-lifetime.rs`: Ensure we error on undeclared lifetime in trait path
- `./gat-in-trait-path.rs`: Base trait path case
- `./gat-trait-path-generic-type-arg.rs`: Don't allow shadowing of parameters
- `./gat-trait-path-parenthesised-args.rs`: Don't allow paranthesized args in trait path
- `./generic-associated-types-where.rs`: Ensure that we require where clauses from trait to be met on impl
- `./impl_bounds.rs`: Check that the bounds on GATs in an impl are checked
- `./issue-76826.rs`: `Windows` pattern
- `./issue-78113-lifetime-mismatch-dyn-trait-box.rs`: Implicit 'static diagnostics
- `./issue-84931.rs`: Ensure that we have a where clause on GAT to ensure trait parameter lives long enough
- `./issue-87258_a.rs`: Unconstrained opaque type with TAITs
- `./issue-87429-2.rs`: Ensure we can use bound vars in the bounds
- `./issue-87429-associated-type-default.rs`: Ensure bounds hold with associated type defaults, for both trait and impl
- `./issue-87429-specialization.rs`: Check that bounds hold under specialization
- `./issue-88595.rs`: Under the outlives lint, we require a bound for both trait and GAT lifetime when trait lifetime is used in function
- `./issue-90014.rs`: Lifetime bounds are checked with TAITs
- `./issue-91139.rs`: Under migrate mode, but not NLL, we don't capture implied bounds from HRTB lifetimes used in a function and GATs
- `./issue-91762.rs`: We used to too eagerly pick param env candidates when normalizing with GATs. We now require explicit parameters specified.
- `./issue-95305.rs`: Disallow lifetime elision in trait paths
- `./iterable.rs`: `Iterable` pattern
- `./method-unsatified-assoc-type-predicate.rs`: Print predicates with GATs correctly in method resolve error
- `./missing_lifetime_const.rs`: Ensure we must specify lifetime args (not elidable)
- `./missing-where-clause-on-trait.rs`: Ensure we don't allow stricter bounds on impl than trait
- `./parameter_number_and_kind_impl.rs`: Ensure paramters on GAT in impl match GAT in trait
- `./pointer_family.rs`: `PointerFamily` pattern
- `./projection-bound-cycle.rs`: Don't allow invalid cycles to prove bounds
- `./self-outlives-lint.rs`: Ensures that an e.g. `Self: 'a` is written on the traits GAT if that bound can be implied from the GAT usage in the trait
- `./shadowing.rs`: Don't allow lifetime shadowing in params
- `./streaming_iterator.rs`: `StreamingIterator`(`LendingIterator`) pattern
- `./trait-objects.rs`: Disallow trait objects for traits with GATs
- `./variance_constraints.rs`: Require that GAT substs be invariant

## Remaining bugs and open issues

A full list of remaining open issues can be found at: https://github.com/rust-lang/rust/labels/F-generic_associated_types

There are some `known-bug` tests in-tree at `src/test/ui/generic-associated-types/bugs`.

Here I'll categorize most of those that GAT bugs (or involve a pattern found more with GATs), but not those that include GATs but not a GAT issue in and of itself. (I also won't include issues directly for things listed elsewhere here.)

Using the concrete type of a GAT instead of the projection type can give errors, since lifetimes are chosen to be early-bound vs late-bound.
- #85533
- #87803

In certain cases, we can run into cycle or overflow errors. This is more generally a problem with associated types.
- #87755
- #87758

Bounds on an associatd type need to be proven by an impl, but where clauses need to be proven by the usage. This can lead to confusion when users write one when they mean the other.
- #87831
- #90573

We sometimes can't normalize closure signatures fully. Really an asociated types issue, but might happen a bit more frequently with GATs, since more obvious place for HRTB lifetimes.
- #88382

When calling a function, we assign types to parameters "too late", after we already try (and fail) to normalize projections. Another associated types issue that might pop up more with GATs.
- #88460
- #96230

We don't fully have implied bounds for lifetimes appearing in GAT trait paths, which can lead to unconstrained type errors.
- #88526

Suggestion for adding lifetime bounds can suggest unhelpful fixes (`T: 'a` instead of `Self: 'a`), but the next compiler error after making the suggested change is helpful.
- #90816
- #92096
- #95268

We can end up requiring that `for<'a> I: 'a` when we really want `for<'a where I: 'a> I: 'a`. This can leave unhelpful errors than effectively can't be satisfied unless `I: 'static`. Requires bigger changes and not only GATs.
- #91693

Unlike with non-generic associated types, we don't eagerly normalize with param env candidates. This is intended behavior (for now), to avoid accidentaly stabilizing picking arbitrary impls.
- #91762

Some Iterator adapter patterns (namely `filter`) require Polonius or unsafe to work.
- #92985

## Potential Future work

### Universal type/const quantification

No work has been done to implement this. There are also some questions around implied bounds.

###  Object-safe GATs

The intention is to make traits with GATs object-safe. There are some design work to be done around well-formedness rules and general implementation.

### GATified std lib types

It would be helpful to either introduce new std lib traits (like `LendingIterator`) or to modify existing ones (adding a `'a` generic to `Iterator::Item`). There also a number of other candidates, like `Index`/`IndexMut` and `Fn`/`FnMut`/`FnOnce`.

### Reduce the need for `for<'a>`

Seen [here](rust-lang/rfcs#1598 (comment)). One possible syntax:

```rust
trait Iterable {
    type Iter<'a>: Iterator<Item = Self::Item<'a>>;
}

fn foo<T>() where T: Iterable, T::Item<let 'a>: Display { } //note the `let`!
```

### Better implied bounds on higher-ranked things

Currently if we have a `type Item<'a> where self: 'a`, and a `for<'a> T: Iterator<Item<'a> = &'a ()`, this requires `for<'a> Self: 'a`. Really, we want `for<'a where T: 'a> ...`

There was some mentions of this all the back in the RFC thread [here](rust-lang/rfcs#1598 (comment)).

## Alternatives

### Make generics on associated type in bounds a binder

Imagine the bound `for<'a> T: Trait<Item<'a>= &'a ()>`. It might be that `for<'a>` is "too large" and it should instead be `T: Trait<for<'a> Item<'a>= &'a ()>`. Brought up in RFC thread [here](rust-lang/rfcs#1598 (comment)) and in a few places since.

Another related question: Is `for<'a>` the right syntax? Maybe `where<'a>`? Also originally found in RFC thread [here](rust-lang/rfcs#1598 (comment)).

### Stabilize lifetime GATs first

This has been brought up a few times. The idea is to only allow GATs with lifetime parameters to in initial stabilization. This was probably most useful prior to actual implementation. At this point, lifetimes, types, and consts are all implemented and work. It feels like an arbitrary split without strong reason.

## History

* On 2016-04-30, [RFC opened](rust-lang/rfcs#1598)
* On 2017-09-02, RFC merged and [tracking issue opened](rust-lang/rust#44265)
* On 2017-10-23, [Move Generics from MethodSig to TraitItem and ImplItem](rust-lang/rust#44766)
* On 2017-12-01, [Generic Associated Types Parsing & Name Resolution](rust-lang/rust#45904)
* On 2017-12-15, [rust-lang/rust#46706
* On 2018-04-23, [Feature gate where clauses on associated types](rust-lang/rust#49368)
* On 2018-05-10, [Extend tests for RFC1598 (GAT)](rust-lang/rust#49423)
* On 2018-05-24, [Finish implementing GATs (Chalk)](rust-lang/chalk#134)
* On 2019-12-21, [Make GATs less ICE-prone](rust-lang/rust#67160)
* On 2020-02-13, [fix lifetime shadowing check in GATs](rust-lang/rust#68938)
* On 2020-06-20, [Projection bound validation](rust-lang/rust#72788)
* On 2020-10-06, [Separate projection bounds and predicates](rust-lang/rust#73905)
* On 2021-02-05, [Generic associated types in trait paths](rust-lang/rust#79554)
* On 2021-02-06, [Trait objects do not work with generic associated types](rust-lang/rust#81823)
* On 2021-04-28, [Make traits with GATs not object safe](rust-lang/rust#84622)
* On 2021-05-11, [Improve diagnostics for GATs](rust-lang/rust#82272)
* On 2021-07-16, [Make GATs no longer an incomplete feature](rust-lang/rust#84623)
* On 2021-07-16, [Replace associated item bound vars with placeholders when projecting](rust-lang/rust#86993)
* On 2021-07-26, [GATs: Decide whether to have defaults for `where Self: 'a`](rust-lang/rust#87479)
* On 2021-08-25, [Normalize projections under binders](rust-lang/rust#85499)
* On 2021-08-03, [The push for GATs stabilization](https://blog.rust-lang.org/2021/08/03/GATs-stabilization-push.html)
* On 2021-08-12, [Detect stricter constraints on gats where clauses in impls vs trait](rust-lang/rust#88336)
* On 2021-09-20, [Proposal: Change syntax of where clauses on type aliases](rust-lang/rust#89122)
* On 2021-11-06, [Implementation of GATs outlives lint](rust-lang/rust#89970)
* On 2021-12-29. [Parse and suggest moving where clauses after equals for type aliases](rust-lang/rust#92118)
* On 2022-01-15, [Ignore static lifetimes for GATs outlives lint](rust-lang/rust#92865)
* On 2022-02-08, [Don't constrain projection predicates with inference vars in GAT substs](rust-lang/rust#92917)
* On 2022-02-15, [Rework GAT where clause check](rust-lang/rust#93820)
* On 2022-02-19, [Only mark projection as ambiguous if GAT substs are constrained](rust-lang/rust#93892)
* On 2022-03-03, [Support GATs in Rustdoc](rust-lang/rust#94009)
* On 2022-03-06, [Change location of where clause on GATs](rust-lang/rust#90076)
* On 2022-05-04, [A shiny future with GATs blog post](https://jackh726.github.io/rust/2022/05/04/a-shiny-future-with-gats.html)
* On 2022-05-04, [Stabilization PR](rust-lang/rust#96709)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
A-associated-types Proposals relating to associated types A-syntax Syntax related proposals & ideas A-traits Trait system related proposals & ideas A-typesystem Type system related proposals & ideas final-comment-period Will be merged/postponed/closed in ~10 calendar days unless new substational objections are raised. T-lang Relevant to the language team, which will review and decide on the RFC.
Projects
No open projects
Tracker
Merge proposed
Development

Successfully merging this pull request may close these issues.

None yet