Skip to content

Commit 742fa62

Browse files
committed
add opaque-types-region-inference-restrictions
1 parent ffa246b commit 742fa62

File tree

1 file changed

+196
-0
lines changed

1 file changed

+196
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,196 @@
1+
# Opaque types region inference restrictions
2+
3+
In this chapter we discuss the various restrictions we impose on the generic arguments of opaque types when defining their hidden types
4+
`Opaque<'a, 'b, .., A, B, ..> := SomeHiddenType`.
5+
6+
These restrictions are implemented in borrow checking ([Source][source-borrowck-opaque]) as it is the final step opaque types inference.
7+
8+
[source-borrowck-opaque]: https://github.com/rust-lang/rust/blob/435b5255148617128f0a9b17bacd3cc10e032b23/compiler/rustc_borrowck/src/region_infer/opaque_types.rs
9+
10+
## Background: type and const generic arguments
11+
For type arguments, two restrictions are necessary: each type argument must be (1) a type parameter and (2) is unique among the generic arguments.
12+
The same is applied to const arguments.
13+
14+
Example of case (1):
15+
```rust
16+
type Opaque<X> = impl Sized;
17+
18+
// `T` is a type paramter.
19+
// Opaque<T> := ();
20+
fn good<T>() -> Opaque<T> {}
21+
22+
// `()` is not a type parameter.
23+
// Opaque<()> := ();
24+
fn bad() -> Opaque<()> {} //~ ERROR
25+
```
26+
27+
Example of case (2):
28+
```rust
29+
type Opaque<X, Y> = impl Sized;
30+
31+
// `T` and `U` are unique in the generic args.
32+
// Opaque<T, U> := T;
33+
fn good<T, U>(t: T, _u: U) -> Opaque<T, U> { t }
34+
35+
// `T` appears twice in the generic args.
36+
// Opaque<T, T> := T;
37+
fn bad<T>(t: T) -> Opaque<T, T> { t } //~ ERROR
38+
```
39+
**Motivation:** In the first case `Opaque<()> := ()`, the hidden type is ambiguous because it is compatible with two different interpretaions: `Opaque<X> := X` and `Opaque<X> := ()`. Similarily for the second case `Opaque<T, T> := T`, it is ambiguous whether it should be interpreted as `Opaque<X, Y> := X` or as `Opaque<X, Y> := Y`. Because of this ambiguity, both cases are rejected as invalid defining uses.
40+
41+
## Uniqueness restriction
42+
43+
Each lifetime argument must be unique in the arguments list and must not be `'static`. This is in order to avoid an ambiguity with hidden type inference similar to the case of type parameters. For example, the invalid defining use below `Opaque<'static> := Inv<'static>` is compatible with both `Opaque<'x> := Inv<'static>` and `Opaque<'x> := Inv<'x>`.
44+
45+
```rust
46+
type Opaque<'x> = impl Sized + 'x;
47+
type Inv<'a> = Option<*mut &'a ()>;
48+
49+
fn good<'a>() -> Opaque<'a> { Inv::<'static>::None }
50+
51+
fn bad() -> Opaque<'static> { Inv::<'static>::None }
52+
//~^ ERROR
53+
```
54+
55+
```rust
56+
type Opaque<'x, 'y> = impl Trait<'x, 'y>;
57+
58+
fn good<'a, 'b>() -> Opaque<'a, 'b> {}
59+
60+
fn bad<'a>() -> Opaque<'a, 'a> {}
61+
//~^ ERROR
62+
```
63+
64+
**Semantic lifetime equlity:** One complexity with lifetimes compared to type parameters is that two lifetimes that are syntactically different may be semantically equal. Therefore, we need to be cautious when verifying that the lifetimes are unique.
65+
66+
```rust
67+
// This is also invalid because `'a` is *semantically* equal to `'static`.
68+
fn still_bad_1<'a: 'static>() -> Opaque<'a> {}
69+
//~^ Should error!
70+
71+
// This is also invalid because `'a` and `'b` are *semantically* equal.
72+
fn still_bad_2<'a: 'b, 'b: 'a>() -> Opaque<'a, 'b> {}
73+
//~^ Should error!
74+
```
75+
76+
## An exception to uniqueness rule
77+
78+
An exception to the uniqueness rule above is when the bounds at the opaque type's definition require a lifetime parameter to be equal to another one or to the `'static` lifetime.
79+
```rust
80+
// The definition requires `'x` to be equal to `'static`.
81+
type Opaque<'x: 'static> = impl Sized + 'x;
82+
83+
fn good() -> Opaque<'static> {}
84+
```
85+
86+
**Motivation:** an attempt to implement the uniqueness restriction for RPITs resulted in a [breakage found via crater]( https://github.com/rust-lang/rust/pull/112842#issuecomment-1610057887). This can be mitigated by this exception to the rule. An example of the the code that would otherwise break:
87+
```rust
88+
struct Type<'a>(&'a ());
89+
impl<'a> Type<'a> {
90+
// `'b == 'a`
91+
fn do_stuff<'b: 'a>(&'b self) -> impl Trait<'a, 'b> {}
92+
}
93+
```
94+
95+
**Why this is correct:** for such a defining use like `Opaque<'a, 'a> := &'a str`, it can be interpreted in either way—either as `Opaque<'x, 'y> := &'x str` or as `Opaque<'x, 'y> := &'y str` and it wouldn't matter because every use of `Opaque` will guarantee that both parameters are equal as per the well-formedness rules.
96+
97+
## Universal lifetimes restriction
98+
99+
Only universally quantified lifetimes are allowed in the opaque type arguments. This includes lifetime parameters and placeholders.
100+
101+
```rust
102+
type Opaque<'x> = impl Sized + 'x;
103+
104+
fn test<'a>() -> Opaque<'a> {
105+
// `Opaque<'empty> := ()`
106+
let _: Opaque<'_> = ();
107+
//~^ ERROR
108+
}
109+
```
110+
111+
**Motivation:** This makes the lifetime and type arguments behave consistently but this is only as a bonus. The real reason behind this restriction is purely technical, as the [member constraints] algorithm faces a fundamental limitation: When encountering an opaque type definition `Opaque<'?1> := &'?2 u8`, a member constraint `'?2 member-of ['static, '?1]` is registered. In order for the algorithm to pick the right choice, the *complete* set of "outlives" relationships between the choice regions `['static, '?1]` must already be known *before* doing the region inference. This can be satisfied only if each choice region is either:
112+
1. a universal region, i.e. `RegionKind::Re{EarlyParam,LateParam,Placeholder,Static}`, because the relations between universal regions are completely known, prior to region inference, from the explicit and implied bounds.
113+
1. or an existential region that is "strictly equal" to a universal region. Strict lifetime equality is defined below and is required here because it is the only type of equality that can be evaluated prior to full region inference.
114+
115+
**Strict lifetime equality:** We say that two lifetimes are strictly equal if there are bidirectional outlives constraints between them. In NLL terms, this means the lifetimes are part of the same [SCC]. Importantly this type of equality can be evaluated prior to full region inference (but of course after constraint collection). The other type of equality is when region inference ends up giving two lifetimes variables the same value even if they are not strictly equal. See [#113971] for how we used to conflate the difference.
116+
117+
[#113971]: https://github.com/rust-lang/rust/issues/113971
118+
[SCC]: https://en.wikipedia.org/wiki/Strongly_connected_component
119+
[member constraints]: https://rustc-dev-guide.rust-lang.org/borrow_check/region_inference/member_constraints.html
120+
121+
**interaction with "once modulo regions" restriction** In the example above, note the opaque type in the signature is `Opaque<'a>` and the one in the invalid defining use is `Opaque<'empty>`. In the proposed MiniTAIT plan, namely the ["once modulo regions"][#116935] rule, we already disallow this.
122+
Although it might appear that "universal lifetimes" restriction becomes redundant as it logically follows from "MiniTAIT" restrictions, the subsequent related discussion on lifetime equality and closures remains relevant.
123+
124+
[#116935]: https://github.com/rust-lang/rust/pull/116935
125+
126+
127+
## Closure restrictions
128+
129+
When the opaque type is defined in a closure/coroutine/inline-const body, universal lifetimes that are "external" to the closure are not allowed in the opaque type arguments. External regions are defined in [`RegionClassification::External`](https://github.com/rust-lang/rust/blob/caf730043232affb6b10d1393895998cb4968520/compiler/rustc_borrowck/src/universal_regions.rs#L201).
130+
131+
Example: (This one happens to compile in the current nightly but more practical examples are already rejected with confusing errors. See [#105498][] for more).
132+
```rust
133+
type Opaque<'x> = impl Sized + 'x;
134+
135+
fn test<'a>() -> Opaque<'a> {
136+
let _ = || {
137+
// `'a` is external to the closure
138+
let _: Opaque<'a> = ();
139+
//~^ Should be an error!
140+
};
141+
()
142+
}
143+
```
144+
145+
**Motivation:** In closure bodies, external lifetimes, although being categorized as "universal" lifetimes, behave more like existential lifetimes in that the relations between them are not known ahead of time, instead their values are inferred just like existential lifetimes and the requirements are propagated back to the parent fn. This breaks the member constraints algorithm as described above:
146+
> In order for [the algorithm] to pick the right choice, the complete set of “outlives” relationships between the choice regions ['static, '?1] must already be known before doing the region inference
147+
148+
Here is an example that details how
149+
150+
```rust
151+
type Opaque<'x, 'y> = impl Sized;
152+
153+
//
154+
fn test<'a, 'b>(s: &'a str) -> impl FnOnce() -> Opaque<'a, 'b> {
155+
move || { s }
156+
//~^ ERROR hidden type for `Opaque<'_, '_>` captures lifetime that does not appear in bounds
157+
}
158+
159+
// The above closure body is desugared into something like:
160+
fn test::{closure#0}(_upvar: &'?8 str) -> Opaque<'?6, '?7> {
161+
return _upvar
162+
}
163+
164+
// where `['?8, '?6, ?7] are universal lifetimes *external* to the closure.
165+
// There are no known relations between them *inside* the closure.
166+
// But in the parent fn it is known that `'?6: '?8`.
167+
//
168+
// When encountering an opaque definition `Opaque<'?6, '?7> := &'8 str`,
169+
// The member constraints algotithm does not know enough to safely make `?8 = '?6`.
170+
// For this reason, it errors with a sensible message:
171+
// "hidden type captures lifetime that does not appear in bounds".
172+
```
173+
174+
Without this restrictions error messages are consfusing and, more impotantly, there is a risk that we accept code the we would likely break in the future because member constraints are super broken in closures.
175+
176+
**Output types:** I believe the most common scenario where this causes issues in real-world code is with closure/async-block output types. It is worth noting that there is a discrepancy betweeen closures and async blocks that further demonstrates this issue and is attributed to the [hack of `replace_opaque_types_with_inference_vars`](https://github.com/rust-lang/rust/blob/9cf18e98f82d85fa41141391d54485b8747da46f/compiler/rustc_hir_typeck/src/closure.rs#L743), which is applied to futures only.
177+
```rust
178+
type Opaque<'x> = impl Sized + 'x;
179+
fn test<'a>() -> impl FnOnce() -> Opaque<'a> {
180+
// Output type of the closure is Opaque<'a>
181+
// -> hidden type definition happens *inside* the closure
182+
// -> rejected.
183+
move || {}
184+
//~^ ERROR expected generic lifetime parameter, found `'_`
185+
}
186+
```
187+
```rust
188+
use std::future::Future;
189+
type Opaque<'x> = impl Sized + 'x;
190+
fn test<'a>() -> impl Future<Output = Opaque<'a>> {
191+
// Output type of the async block is unit `()`
192+
// -> hidden type definition happens in the parent fn
193+
// -> accepted.
194+
async move {}
195+
}
196+
```

0 commit comments

Comments
 (0)