Skip to content

Commit 7d16a20

Browse files
committed
sync with hackmd version
See https://hackmd.io/5t8pLdJcRDmqbfN9ZXje3g
1 parent 1684423 commit 7d16a20

File tree

1 file changed

+151
-87
lines changed

1 file changed

+151
-87
lines changed
Lines changed: 151 additions & 87 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,28 @@
1-
# Inference of opaque types (type alias `impl Trait`)
1+
# Inference of opaque types (`impl Trait`)
22

3-
This page describes how the compiler infers the hidden type for an opaque type.
3+
This page describes how the compiler infers the [hidden type] for an [opaque type].
44
This kind of type inference is particularly complex because,
55
unlike other kinds of type inference,
6-
it works across functions and function bodies.
6+
it can work across functions and function bodies.
7+
8+
[hidden type]: https://rustc-dev-guide.rust-lang.org/borrow_check/region_inference/member_constraints.html?highlight=%22hidden%20type%22#member-constraints
9+
[opaque type]: https://rustc-dev-guide.rust-lang.org/opaque-types-type-alias-impl-trait.html
710

811
## Running example
912

10-
To help explain how it works, let's start with a simple example.
13+
To help explain how it works, let's consider an example.
1114

1215
###
1316

1417
```rust
1518
mod m {
1619
pub type Seq<T> = impl IntoIterator<Item = T>;
17-
18-
pub fn produce_singleton<T>(t: T) -> Seq<T> {
20+
21+
pub fn produce_singleton<T>(t: T) -> Seq<T> {
1922
vec![t]
2023
}
2124

22-
pub fn produce_doubleton<T>(t: T, u: T) -> Seq<T> {
25+
pub fn produce_doubleton<T>(t: T, u: T) -> Seq<T> {
2326
vec![t, u]
2427
}
2528
}
@@ -28,7 +31,7 @@ fn is_send<T: Send>(_: &T) {}
2831

2932
pub fn main() {
3033
let elems = m::produce_singleton(22);
31-
34+
3235
is_send(&elems);
3336

3437
for elem in elems {
@@ -37,53 +40,68 @@ pub fn main() {
3740
}
3841
```
3942

40-
* In this example, the opaque type is `Seq<T>`:
41-
* Its defining scope is the module `m`.
42-
* Its hidden type is `Vec<T>`, which is inferred from:
43-
* `m::produce_singleton`
44-
* `m::produce_doubleton`
45-
* In the `main` function, the opaque type is out of scope:
46-
* When `main` calls `m::produce_singleton`,
47-
it gets back a reference to the opaque type `Seq<i32>`.
48-
* The `is_send` call checks that `Seq<i32>:
49-
Send`. `Send` is not listed amongst the bounds of the impl trait,
50-
but because of auto-trait leakage,
51-
we are able to infer that it holds.
52-
* The for loop desugaring requires that `Seq<T>: IntoIterator`,
53-
which is provable from the bounds declared on `Seq<T>`.
43+
In this code, the *opaque type* is `Seq<T>`.
44+
Its defining scope is the module `m`.
45+
Its *hidden type* is `Vec<T>`,
46+
which is inferred from `m::produce_singleton` and `m::produce_doubleton`.
47+
48+
In the `main` function, the opaque type is out of its defining scope.
49+
When `main` calls `m::produce_singleton`, it gets back a reference to the opaque type `Seq<i32>`.
50+
The `is_send` call checks that `Seq<i32>: Send`.
51+
`Send` is not listed amongst the bounds of the impl trait,
52+
but because of auto-trait leakage, we are able to infer that it holds.
53+
The `for` loop desugaring requires that `Seq<T>: IntoIterator`,
54+
which is provable from the bounds declared on `Seq<T>`.
5455

5556
### Type-checking `main`
5657

57-
Let's start by looking what happens when we type-check `main`. Initially we invoke `produce_singleton` and the return type is an opaque type [`OpaqueTy`](https://doc.rust-lang.org/nightly/nightly-rustc/rustc_hir/enum.ItemKind.html#variant.OpaqueTy).
58+
Let's start by looking what happens when we type-check `main`.
59+
Initially we invoke `produce_singleton` and the return type is an opaque type
60+
[`OpaqueTy`](https://doc.rust-lang.org/nightly/nightly-rustc/rustc_hir/enum.ItemKind.html#variant.OpaqueTy).
5861

5962
#### Type-checking the for loop
6063

61-
* Explain how the for loop works:
62-
* We look at the bounds, we are able to type check it as is
64+
The for loop desugars the `in elems` part to `IntoIterator::into_iter(elems)`.
65+
`elems` is of type `Seq<T>`, so the type checker registers a `Seq<T>: IntoIterator` obligation.
66+
This obligation is trivially satisfied,
67+
because `Seq<T>` is an opaque type (`impl IntoIterator<Item = T>`) that has a bound for the trait.
68+
Similar to how a `U: Foo` where bound allows `U` to trivially satisfy `Foo`,
69+
opaque types' bounds are available to the type checker and are used to fulfill obligations.
70+
71+
The type of `elem` in the for loop is inferred to be `<Seq<T> as IntoIterator>::Item`, which is `T`.
72+
At no point is the type checker interested in the hidden type.
6373

6474
#### Type-checking the `is_send` call
6575

66-
* Explain how it invokes `type_of`
67-
* We look at the bounds, we are able to type check it as is
76+
When trying to prove auto trait bounds,
77+
we first repeat the process as above,
78+
to see if the auto trait is in the bound list of the opaque type.
79+
If that fails, we reveal the hidden type of the opaque type,
80+
but only to prove this specific trait bound, not in general.
81+
Revealing is done by invoking the `type_of` query on the `DefId` of the opaque type.
82+
The query will internally request the hidden types from the defining function(s)
83+
and return that (see [the section on `type_of`](#Within-the-type_of-query) for more details).
84+
85+
#### Flowchart of type checking steps
6886

6987
```mermaid
7088
flowchart TD
7189
TypeChecking["type checking `main`"]
7290
subgraph TypeOfSeq["type_of(Seq<T>) query"]
73-
WalkModuleHir["Walk the HIR for the module `m`\nto find the hidden types from each\nfunction within"]
91+
WalkModuleHir["Walk the HIR for the module `m`\nto find the hidden types from each\nfunction/const/static within"]
7492
VisitProduceSingleton["visit `produce_singleton`"]
7593
InterimType["`produce_singleton` hidden type is `Vec<T>`\nkeep searching"]
7694
VisitProduceDoubleton["visit `produce_doubleton`"]
7795
CompareType["`produce_doubleton` hidden type is also Vec<T>\nthis matches what we saw before ✅"]
78-
Done["Return `Vec<T>`"]
96+
Done["No more items to look at in scope\nReturn `Vec<T>`"]
7997
end
80-
98+
8199
BorrowCheckProduceSingleton["`borrow_check(produce_singleton)`"]
82100
TypeCheckProduceSingleton["`type_check(produce_singleton)`"]
83101
84102
BorrowCheckProduceDoubleton["`borrow_check(produce_doubleton)`"]
85103
TypeCheckProduceDoubleton["`type_check(produce_doubleton)`"]
86-
104+
87105
Substitute["Substitute `T => u32`,\nyielding `Vec<i32>` as the hidden type"]
88106
CheckSend["Check that `Vec<i32>: Send` ✅"]
89107
@@ -97,14 +115,14 @@ flowchart TD
97115
VisitProduceDoubleton --> BorrowCheckProduceDoubleton
98116
BorrowCheckProduceDoubleton --> TypeCheckProduceDoubleton
99117
TypeCheckProduceDoubleton --> CompareType --> Done
100-
Done --> Substitute --> CheckSend
118+
Done --> Substitute --> CheckSend
101119
```
102120

103121
### Within the `type_of` query
104122

105123
The `type_of` query, when applied to an opaque type O, returns the hidden type.
106-
That hidden type is computed by combining the results from each constraining function
107-
within defining scope of O.
124+
That hidden type is computed by combining the results
125+
from each constraining function within the defining scope of O.
108126

109127
```mermaid
110128
flowchart TD
@@ -124,12 +142,18 @@ flowchart TD
124142
ReportError["Report an error"]
125143
ReportError --> Complete["Item I complete"]
126144
Complete --> Iterate
127-
145+
128146
FindOpaqueTyConstraints -- All constraints found --> Done
129147
Done["Done"]
130148
```
131149

132-
### Within the ordinary type check of a single function
150+
### Relating an opaque type to another type
151+
152+
There is one central place where an opaqe type gets its hidden type constrained,
153+
and that is the `handle_opaque_type` function.
154+
Amusingly it takes two types, so you can pass any two types,
155+
but one of them should be an opaque type.
156+
The order is only important for diagnostics.
133157

134158
```mermaid
135159
flowchart TD
@@ -138,78 +162,118 @@ flowchart TD
138162
sub.rs
139163
lub.rs
140164
end
141-
142-
typecheck -- infcx.opaque_ty_obligation --> Enqueue["Enqueue P of kind PredicateKind::OpaqueType"]
143-
144-
Enqueue -- ... some time later ... --> Fulfill
145-
146-
Fulfill["Fulfillment context dequeues P "]
147-
165+
166+
typecheck --> TwoSimul
167+
148168
subgraph handleopaquetype["infcx.handle_opaque_type"]
149-
Handle["Check anchor to determine if we are in a query"]
150-
151-
Handle -- Have anchor, not query --> TwoSimul
152-
Handle -- No anchor, in query --> Query
153-
154-
Query["See query section below"]
155-
169+
156170
TwoSimul["Defining two opaque types simultaneously?"]
157-
171+
158172
TwoSimul -- Yes --> ReportError["Report error"]
159-
160-
TwoSimul -- No --> AlreadyHasValue
161-
173+
174+
TwoSimul -- No --> MayDefine -- Yes --> RegisterOpaqueType --> AlreadyHasValue
175+
176+
MayDefine -- No --> ReportError
177+
178+
MayDefine["In defining scope OR in query?"]
179+
162180
AlreadyHasValue["Opaque type X already has\na registered value?"]
163-
164-
AlreadyHasValue -- No --> RegisterOpaqueType["Register opaque type with\nother type as value"]
165-
166-
AlreadyHasValue -- Yes --> EquateOpaqueTypes["Equate new hidden type with old hidden type"]
167-
end
168-
169-
Fulfill --> Handle
170-
```
171181
172-
### Interactions with queries
182+
AlreadyHasValue -- No --> Obligations["Register opaque type bounds\nas obligations for hidden type"]
173183
174-
When queries encounter a `opaque_ty_obligation`,
175-
they do not try to process them,
176-
but instead just store the constraints into the infcx.
184+
RegisterOpaqueType["Register opaque type with\nother type as value"]
177185
178-
```mermaid
179-
graph TD
180-
subgraph handleopaquetype["infcx.handle_opaque_type"]
181-
Handle["Check anchor to determine if we are in a query"]
182-
Handle -- Have anchor, not query --> NotQuery
183-
Handle -- No anchor, in query --> HavePrevious
184-
185-
NotQuery["See 'not query' case above"]
186-
HavePrevious["Have previous hidden type?"]
187-
188-
HavePrevious -- Yes --> Unify
189-
HavePrevious -- No --> Install
190-
191-
Unify["Equate new and previous hidden types"]
192-
Install["Install hidden type into table"]
186+
AlreadyHasValue -- Yes --> EquateOpaqueTypes["Equate new hidden type\nwith old hidden type"]
193187
end
194188
```
195189

196-
The registered hidden types are stored into the `QueryResponse` struct in
197-
the `opaque_types` field
198-
(the function `take_opaque_types_for_query_response` reads them out).
190+
### Interactions with queries
191+
192+
When queries handle opaque types,
193+
they cannot figure out whether they are in a defining scope,
194+
so they just assume they are.
195+
196+
The registered hidden types are stored into the `QueryResponse` struct
197+
in the `opaque_types` field (the function
198+
`take_opaque_types_for_query_response` reads them out).
199199

200200
When the `QueryResponse` is instantiated into the surrounding infcx in
201201
`query_response_substitution_guess`,
202202
we convert each hidden type constraint by invoking `handle_opaque_type` (as above).
203203

204204
There is one bit of "weirdness".
205-
The instantiated opaque types are stored in a *map*,
206-
and we have to pick one opaque type to use as the key of that map.
205+
The instantiated opaque types have an order
206+
(if one opaque type was compared with another,
207+
and we have to pick one opaque type to use as the one that gets its hidden type assigned).
207208
We use the one that is considered "expected".
208209
But really both of the opaque types may have defining uses.
209210
When the query result is instantiated,
210211
that will be re-evaluated from the context that is using the query.
212+
The final context (typeck of a function, mir borrowck or wf-checks)
213+
will know which opaque type can actually be instantiated
214+
and then handle it correctly.
211215

212216
### Within the MIR borrow checker
213217

214-
The MIR borrow checker relates things via `nll_relate`...
218+
The MIR borrow checker relates things via `nll_relate` and only cares about regions.
219+
Any type relation will trigger the binding of hidden types,
220+
so the borrow checker is doing the same thing as the type checker,
221+
but ignores obivously dead code (e.g. after a panic).
222+
The borrow checker is also the source of truth when it comes to hidden types,
223+
as it is the only one who can properly figure out what lifetimes on the hidden type correspond
224+
to which lifetimes on the opaque type declaration.
225+
226+
## Backwards compatibility hacks
227+
228+
`impl Trait` in return position has various quirks that were not part
229+
of any RFCs and are likely accidental stabilizations.
230+
To support these,
231+
the `replace_opaque_types_with_inference_vars` is being used to reintroduce the previous behaviour.
232+
233+
There are three backwards compatibility hacks:
234+
235+
1. All return sites share the same inference variable,
236+
so some return sites may only compile if another return site uses a concrete type.
237+
```rust
238+
fn foo() -> impl Debug {
239+
if false {
240+
return std::iter::empty().collect();
241+
}
242+
vec![42]
243+
}
244+
```
245+
2. Associated type equality constraints for `impl Trait` can be used
246+
as long as the hidden type satisfies the trait bounds on the associated type.
247+
The opaque `impl Trait` signature does not need to satisfy them.
248+
249+
```rust
250+
trait Duh {}
251+
252+
impl Duh for i32 {}
253+
254+
trait Trait {
255+
type Assoc: Duh;
256+
}
257+
258+
// the fact that `R` is the `::Output` projection on `F` causes
259+
// an intermediate inference var to be generated which is then later
260+
// compared against the actually found `Assoc` type.
261+
impl<R: Duh, F: FnMut() -> R> Trait for F {
262+
type Assoc = R;
263+
}
215264

265+
// The `impl Send` here is then later compared against the inference var
266+
// created, causing the inference var to be set to `impl Send` instead of
267+
// the hidden type. We already have obligations registered on the inference
268+
// var to make it uphold the `: Duh` bound on `Trait::Assoc`. The opaque
269+
// type does not implement `Duh`, even if its hidden type does.
270+
// Lazy TAIT would error out, but we inserted a hack to make it work again,
271+
// keeping backwards compatibility.
272+
fn foo() -> impl Trait<Assoc = impl Send> {
273+
|| 42
274+
}
275+
```
276+
3. Closures cannot create hidden types for their parent function's `impl Trait`.
277+
This point is mostly moot,
278+
because of point 1 introducing inference vars,
279+
so the closure only ever sees the inference var, but should we fix 1, this will become a problem.

0 commit comments

Comments
 (0)