owned this note
owned this note
Published
Linked with GitHub
# impl Trait everywhere
## Premise
* impl Trait is a crucial Rust enabler
* Our current support on stable is quite limited
* Only applies to:
* argument/return position for inherent functions/methods
* argument position in trait methods
* Disallows, I believe, [member constraints]
* Also important for async code in particular
* Allows one to return `async move` from within traits in some situations
* Some places impl Trait is not allowed on nightly
* Module level opaque types (`type Foo = impl Bar`)
* Associated types
* Some places impl Trait is not allowed on stable
* Where clauses ([playground](https://play.rust-lang.org/?version=nightly&mode=debug&edition=2018&gist=817d9ba7db6e43ba50edd1186315416a))
* Impl fn sugar like `impl Fn(impl Debug)` ([playground](https://play.rust-lang.org/?version=nightly&mode=debug&edition=2018&gist=17b0591c82617a397fd2727105e6397e))
* Dyn fn sugar like `dyn Fn(impl Debug)` ([playground](https://play.rust-lang.org/?version=nightly&mode=debug&edition=2018&gist=bc20ce970af1849c0c1e26fa0077da95))
* Trait method return types
* I would like to see an effort to stabilize impl Trait and "complete" it
* Key steps
* Make small-bore decisions (let's not discuss now)
* e.g., do we permit turbofish to specify `impl Trait`?
* If not, do we permit turbofish to specify the non-`impl Trait` type arguments of a function that uses `impl Trait`?
* Reconcile the implementation inference details and decide on what we want
* Stabilize `type Foo = impl Trait` at module level and as the value of associated types
* Extend to return position in traits
* Specify interaction of lifetime inference like `'_` with impl Trait (what does `T: impl Foo<'_>` mean?)
* Extend `impl Trait` to all positions where it makes sense
*
* write-up the principle behind that
* document why we have chosen not to extend it to the other positions
* Related sugar and convenience
* Eliding `type Foo = ...` in an impl if it is determined by a function return type
* Some language questions I'd like to discuss (not all in this meeting)
* Implementation inference differences
* Trait return position considerations
* impl Trait everywhere concept (I didn't get time to revisit this as I had hoped...)
## Prohibiting turbofish
* Prohibiting turbofish does mean that using `impl Trait` has a specific downside
* may become common wisdom that one should not use `impl Trait` in public APIs
* Ordering issue:
* relative to explicit type parameters
* have to define an order
* one possibility is just "syntactic order"
* (what are other reasonable possibilities? e.g. using names of params, or some other kind of "path" thing?)
* Does enable migration to/from impl Trait in simple cases
Complex example:
```rust
fn foo(x: impl Foo<Item = impl Bar, AnotherItem = impl Baz>);
```
Interacts with what we decide to do for `impl Trait` inside of `Fn(..)` style`
```rust
fn foo(x: impl Fn(impl Debug));
fn foo(x: impl for<T: Debug> Fn(T));
```
```rust
fn bar(x: impl IntoIterator<Item: Debug>);
bar(None::<u32>)
```
Arguments against:
* Never need it, because you can specify the value of the parameter
* modulo `impl Foo<impl Bar>`
* Nice to be able to have things that you can't specify
* No need to define the ordering
* Backwards compatible to make an (optional) extension
Value of turbofish in general:
* Usually I don't really want to specify the values of turbofish, except sometimes
Possible incremental steps:
- First support turbofishing explicit type parameters on a function that also uses `impl Trait`. (Requires deciding that *if* we support turbofishing `impl Trait` parameters,they come last.)
- Then support turbofishing the `impl Trait` parameters.
## Implementation inference differences
There are some limitations where the implementation doesn't seem to match the intent of the RFC. In particular, [RFC 2071 envisioned that](https://github.com/rust-lang/rfcs/blob/master/text/2071-impl-trait-existential-types.md#reference-existential-types)
* within the scope of the opaque type (i.e., containing module),
* any function that referenced it must completely specify its value,
* but it *did* allow for "pass through".
The actual implementation is more limited, and only really supports inferring the values for opaque types that appear in function return position.
### Const/static types
For example, **const/static types** ([playground](https://play.rust-lang.org/?version=nightly&mode=debug&edition=2018&gist=fb8eac6b44c730fa5f9afbe0066cac96)):
```rust
type Foo = impl std::fmt::Debug;
const X: Foo = 22_u32; // Currently, errors
static Y: Foo = 22_u32; // Also errors
```
#### Function arguments
But also **function arguments**. The RFC lists an example like this example, which errors in our implementation:
```rust
fn add_to_foo_2(x: Foo) {
// ^^^ the use of `Foo` in arguments is treated as opaque
let x: i32 = x;
}
```
Similarly, the following currently errors ([playground](https://play.rust-lang.org/?version=nightly&mode=debug&edition=2018&gist=a9c5ade8f7659f5216b4dae0d2fcc28e)):
```rust
#![feature(type_alias_impl_trait)]
type Foo = impl std::fmt::Debug;
fn test1(f: Foo) -> Foo {
// ^^^ ^^^ we know we are inferring the value for this
// |
// but we treat the value of this opaquely
let x: u32 = f; // and so we get an error here
22_u32
}
fn main() { }
```
### Partially inferred types
The RFC states that each "item" (e.g., a function) that constrains an associated type must independently define its value:
```rust
#![feature(type_alias_impl_trait)]
type Foo = impl Sized;
fn test1() -> Foo {
// Constrains `Foo` to be `Option<_>`.
None // Error -- both in RFC and in implementation
}
fn test2() -> Foo {
Some(22_u32) // Works -- both in RFC and implementation
}
fn main() { }
```
Why this rule?
* Reasoning complexity -- without this rule, you can have no single function that completely defines the type, rather than being able to reason about functions in isolation.
* Could allow a system where we need "one witness with the complete type", though
* Implementation complexity -- figuring out the value of an opaque type requires type-checking all the things in the module
* although this is effectively required anyway, so not sure how much this tells you --nikomatsakis
* Backwards compatible to remove it
Digression: Explicit syntax to name the hidden type? Possible add-on.
- Josh: having an explicit syntax for this would address all the use cases for which I'd normally want this kind of module-wide inference.
```rust
type Foo = u32 as impl Sized;
type Foo: Sized = u32;
type Foo = impl Sized where Self = u32; // (backward compat?)
// The `as` syntax is interesting:
fn foo() -> i64 as impl Debug { 5 }
// Should probably have `pub` somewhere to show which part of the type alias is public?
```
### Associated types
The RFC doesn't explicitly discuss associated types and impls, but there are interesting questions raised there as well. For example, do methods of an impl have to independently fully constrain the Opaque type?
```rust
type Opaque = impl Sized;
impl SomeTrait for () {
// This is a "reference" to Opaque, and does not contrain it.
type Item = Opaque;
type Item<U> where <vec::IntoIter<u32> as IntoIterator<Item = Opaque>> =
fn consume(x: Opaque) {
// within an impl, each function or const/static operates independently
}
}
```
### What do we know about `impl Trait` values before they are fully constrained?
Or for passthrough code. For example:
```rust
type Opaque = impl Debug;
fn foo(x: Opaque) {
format!("{:?}", x); // can we know that `Opaque: Debug` here?
let _: u32 = x; // even as figure out what `Opaque` is *here*?
}
```
Seems like the answer should be yes, but this will be mildly tricky for the implementation to resolve. Chalk could theoretically handle it but I'm not sure how well it would work in practice.
## Return position in traits
```rust
trait Foo {
fn foo(&self) -> impl Future;
}
trait Foo {
type FooFuture: Future;
fn foo(&self) -> Self::FooFuture;
}
where T: Foo<FooFuture: Send>
```
* type-of
* just make an associated with a name based on the method
* or a syntax like `Foo::foo::return`
* downside -- no transition path to an explicit associated type
* (unless `Foo::foo::return` can continue to work even after `foo` changes to use an associated type...) -- true
### Entangled issue: async fn in traits
* Need some way to specify that the returned future is Send
* don't have it, unless we address the above problem
* but still want a shorthand
## Syntactic niceties
* inferred associated types values when they appear in fn return position
```rust
impl Iterator for () {
fn foo(&self) -> X {
// defines `type Item = X` implicitly
}
}
// consider more complex examples like this one, that uses `impl Future`
impl tokio::Service for MyType {
fn request(&self) -> impl Future {
async move { .. }
}
}
```
* some complexities around lifetimes, bounds (because impl can be more generic)
## RFC Record and summary, tracking issues
* [RFC 1522] -- Conservative impl trait
* Permit `impl Trait` in function argument and return position (excluding trait methods).
* Estabished auto trait leakage and the basic principle of how the 'existential' type works.
* [RFC 1951] -- Expand impl trait
* Permit `impl Trait` in function argument position and function return position (excluding trait methods).
* Designated that all type parameters are in scope for `impl Trait` plus any lifetimes that are explicitly named.
* Did not propose any means of explicitly specifying the values for `impl Trait` in argument position (turbofish).
* [RFC 2071] -- Impl trait existential types
* Add the ability to create named existential types and support impl Trait in let, const, and static declarations.
* Specified details of how existential type inference works
*
* [RFC 2515] -- Type alias impl trait
* [Member constraints](https://github.com/rust-lang/rust/issues/61997)
* [#63066] -- Rust tracking issue
[RFC 1522]: https://github.com/rust-lang/rfcs/blob/master/text/1522-conservative-impl-trait.md
[RFC 1951]: https://github.com/rust-lang/rfcs/blob/master/text/1951-expand-impl-trait.md
[RFC 2071]: https://github.com/rust-lang/rfcs/blob/master/text/2071-impl-trait-existential-types.md
[RFC 2515]: https://github.com/rust-lang/rfcs/blob/master/text/2515-type_alias_impl_trait.md
[#61997]: https://github.com/rust-lang/rust/issues/61997
[#61773]: https://github.com/rust-lang/rust/issues/61773
[#60670]: https://github.com/rust-lang/rust/issues/60670
[#49287]: https://github.com/rust-lang/rust/issues/49287
[#45994]: https://github.com/rust-lang/rust/issues/45994
[#63066]: https://github.com/rust-lang/rust/issues/63066