]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/typeck/infer/higher_ranked/doc.rs
/*! -> //!
[rust.git] / src / librustc / middle / typeck / infer / higher_ranked / doc.rs
1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! # Skolemization and functions
12 //!
13 //! One of the trickiest and most subtle aspects of regions is dealing
14 //! with higher-ranked things which include bound region variables, such
15 //! as function types. I strongly suggest that if you want to understand
16 //! the situation, you read this paper (which is, admittedly, very long,
17 //! but you don't have to read the whole thing):
18 //!
19 //! http://research.microsoft.com/en-us/um/people/simonpj/papers/higher-rank/
20 //!
21 //! Although my explanation will never compete with SPJ's (for one thing,
22 //! his is approximately 100 pages), I will attempt to explain the basic
23 //! problem and also how we solve it. Note that the paper only discusses
24 //! subtyping, not the computation of LUB/GLB.
25 //!
26 //! The problem we are addressing is that there is a kind of subtyping
27 //! between functions with bound region parameters. Consider, for
28 //! example, whether the following relation holds:
29 //!
30 //!     for<'a> fn(&'a int) <: for<'b> fn(&'b int)? (Yes, a => b)
31 //!
32 //! The answer is that of course it does. These two types are basically
33 //! the same, except that in one we used the name `a` and one we used
34 //! the name `b`.
35 //!
36 //! In the examples that follow, it becomes very important to know whether
37 //! a lifetime is bound in a function type (that is, is a lifetime
38 //! parameter) or appears free (is defined in some outer scope).
39 //! Therefore, from now on I will always write the bindings explicitly,
40 //! using the Rust syntax `for<'a> fn(&'a int)` to indicate that `a` is a
41 //! lifetime parameter.
42 //!
43 //! Now let's consider two more function types. Here, we assume that the
44 //! `'b` lifetime is defined somewhere outside and hence is not a lifetime
45 //! parameter bound by the function type (it "appears free"):
46 //!
47 //!     for<'a> fn(&'a int) <: fn(&'b int)? (Yes, a => b)
48 //!
49 //! This subtyping relation does in fact hold. To see why, you have to
50 //! consider what subtyping means. One way to look at `T1 <: T2` is to
51 //! say that it means that it is always ok to treat an instance of `T1` as
52 //! if it had the type `T2`. So, with our functions, it is always ok to
53 //! treat a function that can take pointers with any lifetime as if it
54 //! were a function that can only take a pointer with the specific
55 //! lifetime `'b`. After all, `'b` is a lifetime, after all, and
56 //! the function can take values of any lifetime.
57 //!
58 //! You can also look at subtyping as the *is a* relationship. This amounts
59 //! to the same thing: a function that accepts pointers with any lifetime
60 //! *is a* function that accepts pointers with some specific lifetime.
61 //!
62 //! So, what if we reverse the order of the two function types, like this:
63 //!
64 //!     fn(&'b int) <: for<'a> fn(&'a int)? (No)
65 //!
66 //! Does the subtyping relationship still hold?  The answer of course is
67 //! no. In this case, the function accepts *only the lifetime `'b`*,
68 //! so it is not reasonable to treat it as if it were a function that
69 //! accepted any lifetime.
70 //!
71 //! What about these two examples:
72 //!
73 //!     for<'a,'b> fn(&'a int, &'b int) <: for<'a>    fn(&'a int, &'a int)? (Yes)
74 //!     for<'a>    fn(&'a int, &'a int) <: for<'a,'b> fn(&'a int, &'b int)? (No)
75 //!
76 //! Here, it is true that functions which take two pointers with any two
77 //! lifetimes can be treated as if they only accepted two pointers with
78 //! the same lifetime, but not the reverse.
79 //!
80 //! ## The algorithm
81 //!
82 //! Here is the algorithm we use to perform the subtyping check:
83 //!
84 //! 1. Replace all bound regions in the subtype with new variables
85 //! 2. Replace all bound regions in the supertype with skolemized
86 //!    equivalents. A "skolemized" region is just a new fresh region
87 //!    name.
88 //! 3. Check that the parameter and return types match as normal
89 //! 4. Ensure that no skolemized regions 'leak' into region variables
90 //!    visible from "the outside"
91 //!
92 //! Let's walk through some examples and see how this algorithm plays out.
93 //!
94 //! #### First example
95 //!
96 //! We'll start with the first example, which was:
97 //!
98 //!     1. for<'a> fn(&'a T) <: for<'b> fn(&'b T)?        Yes: a -> b
99 //!
100 //! After steps 1 and 2 of the algorithm we will have replaced the types
101 //! like so:
102 //!
103 //!     1. fn(&'A T) <: fn(&'x T)?
104 //!
105 //! Here the upper case `&A` indicates a *region variable*, that is, a
106 //! region whose value is being inferred by the system. I also replaced
107 //! `&b` with `&x`---I'll use letters late in the alphabet (`x`, `y`, `z`)
108 //! to indicate skolemized region names. We can assume they don't appear
109 //! elsewhere. Note that neither the sub- nor the supertype bind any
110 //! region names anymore (as indicated by the absence of `<` and `>`).
111 //!
112 //! The next step is to check that the parameter types match. Because
113 //! parameters are contravariant, this means that we check whether:
114 //!
115 //!     &'x T <: &'A T
116 //!
117 //! Region pointers are contravariant so this implies that
118 //!
119 //!     &A <= &x
120 //!
121 //! must hold, where `<=` is the subregion relationship. Processing
122 //! *this* constrain simply adds a constraint into our graph that `&A <=
123 //! &x` and is considered successful (it can, for example, be satisfied by
124 //! choosing the value `&x` for `&A`).
125 //!
126 //! So far we have encountered no error, so the subtype check succeeds.
127 //!
128 //! #### The third example
129 //!
130 //! Now let's look first at the third example, which was:
131 //!
132 //!     3. fn(&'a T)    <: for<'b> fn(&'b T)?        No!
133 //!
134 //! After steps 1 and 2 of the algorithm we will have replaced the types
135 //! like so:
136 //!
137 //!     3. fn(&'a T) <: fn(&'x T)?
138 //!
139 //! This looks pretty much the same as before, except that on the LHS
140 //! `'a` was not bound, and hence was left as-is and not replaced with
141 //! a variable. The next step is again to check that the parameter types
142 //! match. This will ultimately require (as before) that `'a` <= `&x`
143 //! must hold: but this does not hold. `self` and `x` are both distinct
144 //! free regions. So the subtype check fails.
145 //!
146 //! #### Checking for skolemization leaks
147 //!
148 //! You may be wondering about that mysterious last step in the algorithm.
149 //! So far it has not been relevant. The purpose of that last step is to
150 //! catch something like *this*:
151 //!
152 //!     for<'a> fn() -> fn(&'a T) <: fn() -> for<'b> fn(&'b T)?   No.
153 //!
154 //! Here the function types are the same but for where the binding occurs.
155 //! The subtype returns a function that expects a value in precisely one
156 //! region. The supertype returns a function that expects a value in any
157 //! region. If we allow an instance of the subtype to be used where the
158 //! supertype is expected, then, someone could call the fn and think that
159 //! the return value has type `fn<b>(&'b T)` when it really has type
160 //! `fn(&'a T)` (this is case #3, above). Bad.
161 //!
162 //! So let's step through what happens when we perform this subtype check.
163 //! We first replace the bound regions in the subtype (the supertype has
164 //! no bound regions). This gives us:
165 //!
166 //!     fn() -> fn(&'A T) <: fn() -> for<'b> fn(&'b T)?
167 //!
168 //! Now we compare the return types, which are covariant, and hence we have:
169 //!
170 //!     fn(&'A T) <: for<'b> fn(&'b T)?
171 //!
172 //! Here we skolemize the bound region in the supertype to yield:
173 //!
174 //!     fn(&'A T) <: fn(&'x T)?
175 //!
176 //! And then proceed to compare the argument types:
177 //!
178 //!     &'x T <: &'A T
179 //!     'A <= 'x
180 //!
181 //! Finally, this is where it gets interesting!  This is where an error
182 //! *should* be reported. But in fact this will not happen. The reason why
183 //! is that `A` is a variable: we will infer that its value is the fresh
184 //! region `x` and think that everything is happy. In fact, this behavior
185 //! is *necessary*, it was key to the first example we walked through.
186 //!
187 //! The difference between this example and the first one is that the variable
188 //! `A` already existed at the point where the skolemization occurred. In
189 //! the first example, you had two functions:
190 //!
191 //!     for<'a> fn(&'a T) <: for<'b> fn(&'b T)
192 //!
193 //! and hence `&A` and `&x` were created "together". In general, the
194 //! intention of the skolemized names is that they are supposed to be
195 //! fresh names that could never be equal to anything from the outside.
196 //! But when inference comes into play, we might not be respecting this
197 //! rule.
198 //!
199 //! So the way we solve this is to add a fourth step that examines the
200 //! constraints that refer to skolemized names. Basically, consider a
201 //! non-directed verison of the constraint graph. Let `Tainted(x)` be the
202 //! set of all things reachable from a skolemized variable `x`.
203 //! `Tainted(x)` should not contain any regions that existed before the
204 //! step at which the skolemization was performed. So this case here
205 //! would fail because `&x` was created alone, but is relatable to `&A`.
206 //!
207 //! ## Computing the LUB and GLB
208 //!
209 //! The paper I pointed you at is written for Haskell. It does not
210 //! therefore considering subtyping and in particular does not consider
211 //! LUB or GLB computation. We have to consider this. Here is the
212 //! algorithm I implemented.
213 //!
214 //! First though, let's discuss what we are trying to compute in more
215 //! detail. The LUB is basically the "common supertype" and the GLB is
216 //! "common subtype"; one catch is that the LUB should be the
217 //! *most-specific* common supertype and the GLB should be *most general*
218 //! common subtype (as opposed to any common supertype or any common
219 //! subtype).
220 //!
221 //! Anyway, to help clarify, here is a table containing some function
222 //! pairs and their LUB/GLB (for conciseness, in this table, I'm just
223 //! including the lifetimes here, not the rest of the types, and I'm
224 //! writing `fn<>` instead of `for<> fn`):
225 //!
226 //! ```
227 //! Type 1                Type 2                LUB                    GLB
228 //! fn<'a>('a)            fn('X)                fn('X)                 fn<'a>('a)
229 //! fn('a)                fn('X)                --                     fn<'a>('a)
230 //! fn<'a,'b>('a, 'b)     fn<'x>('x, 'x)        fn<'a>('a, 'a)         fn<'a,'b>('a, 'b)
231 //! fn<'a,'b>('a, 'b, 'a) fn<'x,'y>('x, 'y, 'y) fn<'a>('a, 'a, 'a)     fn<'a,'b,'c>('a,'b,'c)
232 //! ```
233 //!
234 //! ### Conventions
235 //!
236 //! I use lower-case letters (e.g., `&a`) for bound regions and upper-case
237 //! letters for free regions (`&A`).  Region variables written with a
238 //! dollar-sign (e.g., `$a`).  I will try to remember to enumerate the
239 //! bound-regions on the fn type as well (e.g., `for<'a> fn(&a)`).
240 //!
241 //! ### High-level summary
242 //!
243 //! Both the LUB and the GLB algorithms work in a similar fashion.  They
244 //! begin by replacing all bound regions (on both sides) with fresh region
245 //! inference variables.  Therefore, both functions are converted to types
246 //! that contain only free regions.  We can then compute the LUB/GLB in a
247 //! straightforward way, as described in `combine.rs`.  This results in an
248 //! interim type T.  The algorithms then examine the regions that appear
249 //! in T and try to, in some cases, replace them with bound regions to
250 //! yield the final result.
251 //!
252 //! To decide whether to replace a region `R` that appears in `T` with a
253 //! bound region, the algorithms make use of two bits of information.
254 //! First is a set `V` that contains all region variables created as part
255 //! of the LUB/GLB computation. `V` will contain the region variables
256 //! created to replace the bound regions in the input types, but it also
257 //! contains 'intermediate' variables created to represent the LUB/GLB of
258 //! individual regions.  Basically, when asked to compute the LUB/GLB of a
259 //! region variable with another region, the inferencer cannot oblige
260 //! immediately since the values of that variables are not known.
261 //! Therefore, it creates a new variable that is related to the two
262 //! regions.  For example, the LUB of two variables `$x` and `$y` is a
263 //! fresh variable `$z` that is constrained such that `$x <= $z` and `$y
264 //! <= $z`.  So `V` will contain these intermediate variables as well.
265 //!
266 //! The other important factor in deciding how to replace a region in T is
267 //! the function `Tainted($r)` which, for a region variable, identifies
268 //! all regions that the region variable is related to in some way
269 //! (`Tainted()` made an appearance in the subtype computation as well).
270 //!
271 //! ### LUB
272 //!
273 //! The LUB algorithm proceeds in three steps:
274 //!
275 //! 1. Replace all bound regions (on both sides) with fresh region
276 //!    inference variables.
277 //! 2. Compute the LUB "as normal", meaning compute the GLB of each
278 //!    pair of argument types and the LUB of the return types and
279 //!    so forth.  Combine those to a new function type `F`.
280 //! 3. Replace each region `R` that appears in `F` as follows:
281 //!    - Let `V` be the set of variables created during the LUB
282 //!      computational steps 1 and 2, as described in the previous section.
283 //!    - If `R` is not in `V`, replace `R` with itself.
284 //!    - If `Tainted(R)` contains a region that is not in `V`,
285 //!      replace `R` with itself.
286 //!    - Otherwise, select the earliest variable in `Tainted(R)` that originates
287 //!      from the left-hand side and replace `R` with the bound region that
288 //!      this variable was a replacement for.
289 //!
290 //! So, let's work through the simplest example: `fn(&A)` and `for<'a> fn(&a)`.
291 //! In this case, `&a` will be replaced with `$a` and the interim LUB type
292 //! `fn($b)` will be computed, where `$b=GLB(&A,$a)`.  Therefore, `V =
293 //! {$a, $b}` and `Tainted($b) = { $b, $a, &A }`.  When we go to replace
294 //! `$b`, we find that since `&A \in Tainted($b)` is not a member of `V`,
295 //! we leave `$b` as is.  When region inference happens, `$b` will be
296 //! resolved to `&A`, as we wanted.
297 //!
298 //! Let's look at a more complex one: `fn(&a, &b)` and `fn(&x, &x)`.  In
299 //! this case, we'll end up with a (pre-replacement) LUB type of `fn(&g,
300 //! &h)` and a graph that looks like:
301 //!
302 //! ```
303 //!      $a        $b     *--$x
304 //!        \        \    /  /
305 //!         \        $h-*  /
306 //!          $g-----------*
307 //! ```
308 //!
309 //! Here `$g` and `$h` are fresh variables that are created to represent
310 //! the LUB/GLB of things requiring inference.  This means that `V` and
311 //! `Tainted` will look like:
312 //!
313 //! ```
314 //! V = {$a, $b, $g, $h, $x}
315 //! Tainted($g) = Tainted($h) = { $a, $b, $h, $g, $x }
316 //! ```
317 //!
318 //! Therefore we replace both `$g` and `$h` with `$a`, and end up
319 //! with the type `fn(&a, &a)`.
320 //!
321 //! ### GLB
322 //!
323 //! The procedure for computing the GLB is similar.  The difference lies
324 //! in computing the replacements for the various variables. For each
325 //! region `R` that appears in the type `F`, we again compute `Tainted(R)`
326 //! and examine the results:
327 //!
328 //! 1. If `R` is not in `V`, it is not replaced.
329 //! 2. Else, if `Tainted(R)` contains only variables in `V`, and it
330 //!    contains exactly one variable from the LHS and one variable from
331 //!    the RHS, then `R` can be mapped to the bound version of the
332 //!    variable from the LHS.
333 //! 3. Else, if `Tainted(R)` contains no variable from the LHS and no
334 //!    variable from the RHS, then `R` can be mapped to itself.
335 //! 4. Else, `R` is mapped to a fresh bound variable.
336 //!
337 //! These rules are pretty complex.  Let's look at some examples to see
338 //! how they play out.
339 //!
340 //! Out first example was `fn(&a)` and `fn(&X)`.  In this case, `&a` will
341 //! be replaced with `$a` and we will ultimately compute a
342 //! (pre-replacement) GLB type of `fn($g)` where `$g=LUB($a,&X)`.
343 //! Therefore, `V={$a,$g}` and `Tainted($g)={$g,$a,&X}.  To find the
344 //! replacement for `$g` we consult the rules above:
345 //! - Rule (1) does not apply because `$g \in V`
346 //! - Rule (2) does not apply because `&X \in Tainted($g)`
347 //! - Rule (3) does not apply because `$a \in Tainted($g)`
348 //! - Hence, by rule (4), we replace `$g` with a fresh bound variable `&z`.
349 //! So our final result is `fn(&z)`, which is correct.
350 //!
351 //! The next example is `fn(&A)` and `fn(&Z)`. In this case, we will again
352 //! have a (pre-replacement) GLB of `fn(&g)`, where `$g = LUB(&A,&Z)`.
353 //! Therefore, `V={$g}` and `Tainted($g) = {$g, &A, &Z}`.  In this case,
354 //! by rule (3), `$g` is mapped to itself, and hence the result is
355 //! `fn($g)`.  This result is correct (in this case, at least), but it is
356 //! indicative of a case that *can* lead us into concluding that there is
357 //! no GLB when in fact a GLB does exist.  See the section "Questionable
358 //! Results" below for more details.
359 //!
360 //! The next example is `fn(&a, &b)` and `fn(&c, &c)`. In this case, as
361 //! before, we'll end up with `F=fn($g, $h)` where `Tainted($g) =
362 //! Tainted($h) = {$g, $h, $a, $b, $c}`.  Only rule (4) applies and hence
363 //! we'll select fresh bound variables `y` and `z` and wind up with
364 //! `fn(&y, &z)`.
365 //!
366 //! For the last example, let's consider what may seem trivial, but is
367 //! not: `fn(&a, &a)` and `fn(&b, &b)`.  In this case, we'll get `F=fn($g,
368 //! $h)` where `Tainted($g) = {$g, $a, $x}` and `Tainted($h) = {$h, $a,
369 //! $x}`.  Both of these sets contain exactly one bound variable from each
370 //! side, so we'll map them both to `&a`, resulting in `fn(&a, &a)`, which
371 //! is the desired result.
372 //!
373 //! ### Shortcomings and correctness
374 //!
375 //! You may be wondering whether this algorithm is correct.  The answer is
376 //! "sort of".  There are definitely cases where they fail to compute a
377 //! result even though a correct result exists.  I believe, though, that
378 //! if they succeed, then the result is valid, and I will attempt to
379 //! convince you.  The basic argument is that the "pre-replacement" step
380 //! computes a set of constraints.  The replacements, then, attempt to
381 //! satisfy those constraints, using bound identifiers where needed.
382 //!
383 //! For now I will briefly go over the cases for LUB/GLB and identify
384 //! their intent:
385 //!
386 //! - LUB:
387 //!   - The region variables that are substituted in place of bound regions
388 //!     are intended to collect constraints on those bound regions.
389 //!   - If Tainted(R) contains only values in V, then this region is unconstrained
390 //!     and can therefore be generalized, otherwise it cannot.
391 //! - GLB:
392 //!   - The region variables that are substituted in place of bound regions
393 //!     are intended to collect constraints on those bound regions.
394 //!   - If Tainted(R) contains exactly one variable from each side, and
395 //!     only variables in V, that indicates that those two bound regions
396 //!     must be equated.
397 //!   - Otherwise, if Tainted(R) references any variables from left or right
398 //!     side, then it is trying to combine a bound region with a free one or
399 //!     multiple bound regions, so we need to select fresh bound regions.
400 //!
401 //! Sorry this is more of a shorthand to myself.  I will try to write up something
402 //! more convincing in the future.
403 //!
404 //! #### Where are the algorithms wrong?
405 //!
406 //! - The pre-replacement computation can fail even though using a
407 //!   bound-region would have succeeded.
408 //! - We will compute GLB(fn(fn($a)), fn(fn($b))) as fn($c) where $c is the
409 //!   GLB of $a and $b.  But if inference finds that $a and $b must be mapped
410 //!   to regions without a GLB, then this is effectively a failure to compute
411 //!   the GLB.  However, the result `fn<$c>(fn($c))` is a valid GLB.