Skip to content

Commit 830d115

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

File tree

1 file changed

+150
-87
lines changed

1 file changed

+150
-87
lines changed
Lines changed: 150 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,67 @@ 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, because `Seq<T>` is an opaque type (`impl IntoIterator<Item = T>`) that
67+
has a bound for the trait. Similar to how a `U: Foo` where bound allows `U` to trivially satisfy `Foo`,
68+
opaque types' bounds are available to the type checker and are used to fulfill obligations.
69+
70+
The type of `elem` in the for loop is inferred to be `<Seq<T> as IntoIterator>::Item`, which is `T`.
71+
At no point is the type checker interested in the hidden type.
6372

6473
#### Type-checking the `is_send` call
6574

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

6986
```mermaid
7087
flowchart TD
7188
TypeChecking["type checking `main`"]
7289
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"]
90+
WalkModuleHir["Walk the HIR for the module `m`\nto find the hidden types from each\nfunction/const/static within"]
7491
VisitProduceSingleton["visit `produce_singleton`"]
7592
InterimType["`produce_singleton` hidden type is `Vec<T>`\nkeep searching"]
7693
VisitProduceDoubleton["visit `produce_doubleton`"]
7794
CompareType["`produce_doubleton` hidden type is also Vec<T>\nthis matches what we saw before ✅"]
78-
Done["Return `Vec<T>`"]
95+
Done["No more items to look at in scope\nReturn `Vec<T>`"]
7996
end
80-
97+
8198
BorrowCheckProduceSingleton["`borrow_check(produce_singleton)`"]
8299
TypeCheckProduceSingleton["`type_check(produce_singleton)`"]
83100
84101
BorrowCheckProduceDoubleton["`borrow_check(produce_doubleton)`"]
85102
TypeCheckProduceDoubleton["`type_check(produce_doubleton)`"]
86-
103+
87104
Substitute["Substitute `T => u32`,\nyielding `Vec<i32>` as the hidden type"]
88105
CheckSend["Check that `Vec<i32>: Send` ✅"]
89106
@@ -97,14 +114,14 @@ flowchart TD
97114
VisitProduceDoubleton --> BorrowCheckProduceDoubleton
98115
BorrowCheckProduceDoubleton --> TypeCheckProduceDoubleton
99116
TypeCheckProduceDoubleton --> CompareType --> Done
100-
Done --> Substitute --> CheckSend
117+
Done --> Substitute --> CheckSend
101118
```
102119

103120
### Within the `type_of` query
104121

105122
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.
123+
That hidden type is computed by combining the results
124+
from each constraining function within the defining scope of O.
108125

109126
```mermaid
110127
flowchart TD
@@ -124,12 +141,18 @@ flowchart TD
124141
ReportError["Report an error"]
125142
ReportError --> Complete["Item I complete"]
126143
Complete --> Iterate
127-
144+
128145
FindOpaqueTyConstraints -- All constraints found --> Done
129146
Done["Done"]
130147
```
131148

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

134157
```mermaid
135158
flowchart TD
@@ -138,78 +161,118 @@ flowchart TD
138161
sub.rs
139162
lub.rs
140163
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-
164+
165+
typecheck --> TwoSimul
166+
148167
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-
168+
156169
TwoSimul["Defining two opaque types simultaneously?"]
157-
170+
158171
TwoSimul -- Yes --> ReportError["Report error"]
159-
160-
TwoSimul -- No --> AlreadyHasValue
161-
172+
173+
TwoSimul -- No --> MayDefine -- Yes --> RegisterOpaqueType --> AlreadyHasValue
174+
175+
MayDefine -- No --> ReportError
176+
177+
MayDefine["In defining scope OR in query?"]
178+
162179
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-
```
171180
172-
### Interactions with queries
181+
AlreadyHasValue -- No --> Obligations["Register opaque type bounds\nas obligations for hidden type"]
173182
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.
183+
RegisterOpaqueType["Register opaque type with\nother type as value"]
177184
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"]
185+
AlreadyHasValue -- Yes --> EquateOpaqueTypes["Equate new hidden type\nwith old hidden type"]
193186
end
194187
```
195188

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

200199
When the `QueryResponse` is instantiated into the surrounding infcx in
201200
`query_response_substitution_guess`,
202201
we convert each hidden type constraint by invoking `handle_opaque_type` (as above).
203202

204203
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.
204+
The instantiated opaque types have an order
205+
(if one opaque type was compared with another,
206+
and we have to pick one opaque type to use as the one that gets its hidden type assigned).
207207
We use the one that is considered "expected".
208208
But really both of the opaque types may have defining uses.
209209
When the query result is instantiated,
210210
that will be re-evaluated from the context that is using the query.
211+
The final context (typeck of a function, mir borrowck or wf-checks)
212+
will know which opaque type can actually be instantiated
213+
and then handle it correctly.
211214

212215
### Within the MIR borrow checker
213216

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

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

0 commit comments

Comments
 (0)