1
- # Inference of opaque types (type alias ` impl Trait ` )
1
+ # Inference of opaque types (` impl Trait ` )
2
2
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] .
4
4
This kind of type inference is particularly complex because,
5
5
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
7
10
8
11
## Running example
9
12
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.
11
14
12
15
###
13
16
14
17
``` rust
15
18
mod m {
16
19
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 > {
19
22
vec! [t ]
20
23
}
21
24
22
- pub fn produce_doubleton <T >(t : T , u : T ) -> Seq <T > {
25
+ pub fn produce_doubleton <T >(t : T , u : T ) -> Seq <T > {
23
26
vec! [t , u ]
24
27
}
25
28
}
@@ -28,7 +31,7 @@ fn is_send<T: Send>(_: &T) {}
28
31
29
32
pub fn main () {
30
33
let elems = m :: produce_singleton (22 );
31
-
34
+
32
35
is_send (& elems );
33
36
34
37
for elem in elems {
@@ -37,53 +40,68 @@ pub fn main() {
37
40
}
38
41
```
39
42
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> ` .
54
55
55
56
### Type-checking ` main `
56
57
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 ) .
58
61
59
62
#### Type-checking the for loop
60
63
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.
63
73
64
74
#### Type-checking the ` is_send ` call
65
75
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
68
86
69
87
``` mermaid
70
88
flowchart TD
71
89
TypeChecking["type checking `main`"]
72
90
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"]
74
92
VisitProduceSingleton["visit `produce_singleton`"]
75
93
InterimType["`produce_singleton` hidden type is `Vec<T>`\nkeep searching"]
76
94
VisitProduceDoubleton["visit `produce_doubleton`"]
77
95
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>`"]
79
97
end
80
-
98
+
81
99
BorrowCheckProduceSingleton["`borrow_check(produce_singleton)`"]
82
100
TypeCheckProduceSingleton["`type_check(produce_singleton)`"]
83
101
84
102
BorrowCheckProduceDoubleton["`borrow_check(produce_doubleton)`"]
85
103
TypeCheckProduceDoubleton["`type_check(produce_doubleton)`"]
86
-
104
+
87
105
Substitute["Substitute `T => u32`,\nyielding `Vec<i32>` as the hidden type"]
88
106
CheckSend["Check that `Vec<i32>: Send` ✅"]
89
107
@@ -97,14 +115,14 @@ flowchart TD
97
115
VisitProduceDoubleton --> BorrowCheckProduceDoubleton
98
116
BorrowCheckProduceDoubleton --> TypeCheckProduceDoubleton
99
117
TypeCheckProduceDoubleton --> CompareType --> Done
100
- Done --> Substitute --> CheckSend
118
+ Done --> Substitute --> CheckSend
101
119
```
102
120
103
121
### Within the ` type_of ` query
104
122
105
123
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.
108
126
109
127
``` mermaid
110
128
flowchart TD
@@ -124,12 +142,18 @@ flowchart TD
124
142
ReportError["Report an error"]
125
143
ReportError --> Complete["Item I complete"]
126
144
Complete --> Iterate
127
-
145
+
128
146
FindOpaqueTyConstraints -- All constraints found --> Done
129
147
Done["Done"]
130
148
```
131
149
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.
133
157
134
158
``` mermaid
135
159
flowchart TD
@@ -138,78 +162,118 @@ flowchart TD
138
162
sub.rs
139
163
lub.rs
140
164
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
+
148
168
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
+
156
170
TwoSimul["Defining two opaque types simultaneously?"]
157
-
171
+
158
172
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
+
162
180
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
- ```
171
181
172
- ### Interactions with queries
182
+ AlreadyHasValue -- No --> Obligations["Register opaque type bounds\nas obligations for hidden type"]
173
183
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"]
177
185
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"]
193
187
end
194
188
```
195
189
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).
199
199
200
200
When the ` QueryResponse ` is instantiated into the surrounding infcx in
201
201
` query_response_substitution_guess ` ,
202
202
we convert each hidden type constraint by invoking ` handle_opaque_type ` (as above).
203
203
204
204
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).
207
208
We use the one that is considered "expected".
208
209
But really both of the opaque types may have defining uses.
209
210
When the query result is instantiated,
210
211
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.
211
215
212
216
### Within the MIR borrow checker
213
217
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
+ }
215
264
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