]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/variance.rs
Port a bunch of code new-visitor; all of these ports were
[rust.git] / src / librustc_typeck / variance.rs
1 // Copyright 2013 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 //! This file infers the variance of type and lifetime parameters. The
12 //! algorithm is taken from Section 4 of the paper "Taming the Wildcards:
13 //! Combining Definition- and Use-Site Variance" published in PLDI'11 and
14 //! written by Altidor et al., and hereafter referred to as The Paper.
15 //!
16 //! This inference is explicitly designed *not* to consider the uses of
17 //! types within code. To determine the variance of type parameters
18 //! defined on type `X`, we only consider the definition of the type `X`
19 //! and the definitions of any types it references.
20 //!
21 //! We only infer variance for type parameters found on *data types*
22 //! like structs and enums. In these cases, there is fairly straightforward
23 //! explanation for what variance means. The variance of the type
24 //! or lifetime parameters defines whether `T<A>` is a subtype of `T<B>`
25 //! (resp. `T<'a>` and `T<'b>`) based on the relationship of `A` and `B`
26 //! (resp. `'a` and `'b`).
27 //!
28 //! We do not infer variance for type parameters found on traits, fns,
29 //! or impls. Variance on trait parameters can make indeed make sense
30 //! (and we used to compute it) but it is actually rather subtle in
31 //! meaning and not that useful in practice, so we removed it. See the
32 //! addendum for some details. Variances on fn/impl parameters, otoh,
33 //! doesn't make sense because these parameters are instantiated and
34 //! then forgotten, they don't persist in types or compiled
35 //! byproducts.
36 //!
37 //! ### The algorithm
38 //!
39 //! The basic idea is quite straightforward. We iterate over the types
40 //! defined and, for each use of a type parameter X, accumulate a
41 //! constraint indicating that the variance of X must be valid for the
42 //! variance of that use site. We then iteratively refine the variance of
43 //! X until all constraints are met. There is *always* a sol'n, because at
44 //! the limit we can declare all type parameters to be invariant and all
45 //! constraints will be satisfied.
46 //!
47 //! As a simple example, consider:
48 //!
49 //!     enum Option<A> { Some(A), None }
50 //!     enum OptionalFn<B> { Some(|B|), None }
51 //!     enum OptionalMap<C> { Some(|C| -> C), None }
52 //!
53 //! Here, we will generate the constraints:
54 //!
55 //!     1. V(A) <= +
56 //!     2. V(B) <= -
57 //!     3. V(C) <= +
58 //!     4. V(C) <= -
59 //!
60 //! These indicate that (1) the variance of A must be at most covariant;
61 //! (2) the variance of B must be at most contravariant; and (3, 4) the
62 //! variance of C must be at most covariant *and* contravariant. All of these
63 //! results are based on a variance lattice defined as follows:
64 //!
65 //!       *      Top (bivariant)
66 //!    -     +
67 //!       o      Bottom (invariant)
68 //!
69 //! Based on this lattice, the solution V(A)=+, V(B)=-, V(C)=o is the
70 //! optimal solution. Note that there is always a naive solution which
71 //! just declares all variables to be invariant.
72 //!
73 //! You may be wondering why fixed-point iteration is required. The reason
74 //! is that the variance of a use site may itself be a function of the
75 //! variance of other type parameters. In full generality, our constraints
76 //! take the form:
77 //!
78 //!     V(X) <= Term
79 //!     Term := + | - | * | o | V(X) | Term x Term
80 //!
81 //! Here the notation V(X) indicates the variance of a type/region
82 //! parameter `X` with respect to its defining class. `Term x Term`
83 //! represents the "variance transform" as defined in the paper:
84 //!
85 //!   If the variance of a type variable `X` in type expression `E` is `V2`
86 //!   and the definition-site variance of the [corresponding] type parameter
87 //!   of a class `C` is `V1`, then the variance of `X` in the type expression
88 //!   `C<E>` is `V3 = V1.xform(V2)`.
89 //!
90 //! ### Constraints
91 //!
92 //! If I have a struct or enum with where clauses:
93 //!
94 //!     struct Foo<T:Bar> { ... }
95 //!
96 //! you might wonder whether the variance of `T` with respect to `Bar`
97 //! affects the variance `T` with respect to `Foo`. I claim no.  The
98 //! reason: assume that `T` is invariant w/r/t `Bar` but covariant w/r/t
99 //! `Foo`. And then we have a `Foo<X>` that is upcast to `Foo<Y>`, where
100 //! `X <: Y`. However, while `X : Bar`, `Y : Bar` does not hold.  In that
101 //! case, the upcast will be illegal, but not because of a variance
102 //! failure, but rather because the target type `Foo<Y>` is itself just
103 //! not well-formed. Basically we get to assume well-formedness of all
104 //! types involved before considering variance.
105 //!
106 //! ### Addendum: Variance on traits
107 //!
108 //! As mentioned above, we used to permit variance on traits. This was
109 //! computed based on the appearance of trait type parameters in
110 //! method signatures and was used to represent the compatibility of
111 //! vtables in trait objects (and also "virtual" vtables or dictionary
112 //! in trait bounds). One complication was that variance for
113 //! associated types is less obvious, since they can be projected out
114 //! and put to myriad uses, so it's not clear when it is safe to allow
115 //! `X<A>::Bar` to vary (or indeed just what that means). Moreover (as
116 //! covered below) all inputs on any trait with an associated type had
117 //! to be invariant, limiting the applicability. Finally, the
118 //! annotations (`MarkerTrait`, `PhantomFn`) needed to ensure that all
119 //! trait type parameters had a variance were confusing and annoying
120 //! for little benefit.
121 //!
122 //! Just for historical reference,I am going to preserve some text indicating
123 //! how one could interpret variance and trait matching.
124 //!
125 //! #### Variance and object types
126 //!
127 //! Just as with structs and enums, we can decide the subtyping
128 //! relationship between two object types `&Trait<A>` and `&Trait<B>`
129 //! based on the relationship of `A` and `B`. Note that for object
130 //! types we ignore the `Self` type parameter -- it is unknown, and
131 //! the nature of dynamic dispatch ensures that we will always call a
132 //! function that is expected the appropriate `Self` type. However, we
133 //! must be careful with the other type parameters, or else we could
134 //! end up calling a function that is expecting one type but provided
135 //! another.
136 //!
137 //! To see what I mean, consider a trait like so:
138 //!
139 //!     trait ConvertTo<A> {
140 //!         fn convertTo(&self) -> A;
141 //!     }
142 //!
143 //! Intuitively, If we had one object `O=&ConvertTo<Object>` and another
144 //! `S=&ConvertTo<String>`, then `S <: O` because `String <: Object`
145 //! (presuming Java-like "string" and "object" types, my go to examples
146 //! for subtyping). The actual algorithm would be to compare the
147 //! (explicit) type parameters pairwise respecting their variance: here,
148 //! the type parameter A is covariant (it appears only in a return
149 //! position), and hence we require that `String <: Object`.
150 //!
151 //! You'll note though that we did not consider the binding for the
152 //! (implicit) `Self` type parameter: in fact, it is unknown, so that's
153 //! good. The reason we can ignore that parameter is precisely because we
154 //! don't need to know its value until a call occurs, and at that time (as
155 //! you said) the dynamic nature of virtual dispatch means the code we run
156 //! will be correct for whatever value `Self` happens to be bound to for
157 //! the particular object whose method we called. `Self` is thus different
158 //! from `A`, because the caller requires that `A` be known in order to
159 //! know the return type of the method `convertTo()`. (As an aside, we
160 //! have rules preventing methods where `Self` appears outside of the
161 //! receiver position from being called via an object.)
162 //!
163 //! #### Trait variance and vtable resolution
164 //!
165 //! But traits aren't only used with objects. They're also used when
166 //! deciding whether a given impl satisfies a given trait bound. To set the
167 //! scene here, imagine I had a function:
168 //!
169 //!     fn convertAll<A,T:ConvertTo<A>>(v: &[T]) {
170 //!         ...
171 //!     }
172 //!
173 //! Now imagine that I have an implementation of `ConvertTo` for `Object`:
174 //!
175 //!     impl ConvertTo<int> for Object { ... }
176 //!
177 //! And I want to call `convertAll` on an array of strings. Suppose
178 //! further that for whatever reason I specifically supply the value of
179 //! `String` for the type parameter `T`:
180 //!
181 //!     let mut vector = vec!["string", ...];
182 //!     convertAll::<int, String>(vector);
183 //!
184 //! Is this legal? To put another way, can we apply the `impl` for
185 //! `Object` to the type `String`? The answer is yes, but to see why
186 //! we have to expand out what will happen:
187 //!
188 //! - `convertAll` will create a pointer to one of the entries in the
189 //!   vector, which will have type `&String`
190 //! - It will then call the impl of `convertTo()` that is intended
191 //!   for use with objects. This has the type:
192 //!
193 //!       fn(self: &Object) -> int
194 //!
195 //!   It is ok to provide a value for `self` of type `&String` because
196 //!   `&String <: &Object`.
197 //!
198 //! OK, so intuitively we want this to be legal, so let's bring this back
199 //! to variance and see whether we are computing the correct result. We
200 //! must first figure out how to phrase the question "is an impl for
201 //! `Object,int` usable where an impl for `String,int` is expected?"
202 //!
203 //! Maybe it's helpful to think of a dictionary-passing implementation of
204 //! type classes. In that case, `convertAll()` takes an implicit parameter
205 //! representing the impl. In short, we *have* an impl of type:
206 //!
207 //!     V_O = ConvertTo<int> for Object
208 //!
209 //! and the function prototype expects an impl of type:
210 //!
211 //!     V_S = ConvertTo<int> for String
212 //!
213 //! As with any argument, this is legal if the type of the value given
214 //! (`V_O`) is a subtype of the type expected (`V_S`). So is `V_O <: V_S`?
215 //! The answer will depend on the variance of the various parameters. In
216 //! this case, because the `Self` parameter is contravariant and `A` is
217 //! covariant, it means that:
218 //!
219 //!     V_O <: V_S iff
220 //!         int <: int
221 //!         String <: Object
222 //!
223 //! These conditions are satisfied and so we are happy.
224 //!
225 //! #### Variance and associated types
226 //!
227 //! Traits with associated types -- or at minimum projection
228 //! expressions -- must be invariant with respect to all of their
229 //! inputs. To see why this makes sense, consider what subtyping for a
230 //! trait reference means:
231 //!
232 //!    <T as Trait> <: <U as Trait>
233 //!
234 //! means that if I know that `T as Trait`, I also know that `U as
235 //! Trait`. Moreover, if you think of it as dictionary passing style,
236 //! it means that a dictionary for `<T as Trait>` is safe to use where
237 //! a dictionary for `<U as Trait>` is expected.
238 //!
239 //! The problem is that when you can project types out from `<T as
240 //! Trait>`, the relationship to types projected out of `<U as Trait>`
241 //! is completely unknown unless `T==U` (see #21726 for more
242 //! details). Making `Trait` invariant ensures that this is true.
243 //!
244 //! Another related reason is that if we didn't make traits with
245 //! associated types invariant, then projection is no longer a
246 //! function with a single result. Consider:
247 //!
248 //! ```
249 //! trait Identity { type Out; fn foo(&self); }
250 //! impl<T> Identity for T { type Out = T; ... }
251 //! ```
252 //!
253 //! Now if I have `<&'static () as Identity>::Out`, this can be
254 //! validly derived as `&'a ()` for any `'a`:
255 //!
256 //!    <&'a () as Identity> <: <&'static () as Identity>
257 //!    if &'static () < : &'a ()   -- Identity is contravariant in Self
258 //!    if 'static : 'a             -- Subtyping rules for relations
259 //!
260 //! This change otoh means that `<'static () as Identity>::Out` is
261 //! always `&'static ()` (which might then be upcast to `'a ()`,
262 //! separately). This was helpful in solving #21750.
263
264 use self::VarianceTerm::*;
265 use self::ParamKind::*;
266
267 use arena;
268 use arena::TypedArena;
269 use middle::def_id::DefId;
270 use middle::resolve_lifetime as rl;
271 use middle::subst;
272 use middle::subst::{ParamSpace, FnSpace, TypeSpace, SelfSpace, VecPerParamSpace};
273 use middle::ty::{self, Ty};
274 use rustc::front::map as hir_map;
275 use std::fmt;
276 use std::rc::Rc;
277 use syntax::ast;
278 use rustc_front::hir;
279 use rustc_front::intravisit::Visitor;
280 use util::nodemap::NodeMap;
281
282 pub fn infer_variance(tcx: &ty::ctxt) {
283     let krate = tcx.map.krate();
284     let mut arena = arena::TypedArena::new();
285     let terms_cx = determine_parameters_to_be_inferred(tcx, &mut arena, krate);
286     let constraints_cx = add_constraints_from_crate(terms_cx, krate);
287     solve_constraints(constraints_cx);
288     tcx.variance_computed.set(true);
289 }
290
291 // Representing terms
292 //
293 // Terms are structured as a straightforward tree. Rather than rely on
294 // GC, we allocate terms out of a bounded arena (the lifetime of this
295 // arena is the lifetime 'a that is threaded around).
296 //
297 // We assign a unique index to each type/region parameter whose variance
298 // is to be inferred. We refer to such variables as "inferreds". An
299 // `InferredIndex` is a newtype'd int representing the index of such
300 // a variable.
301
302 type VarianceTermPtr<'a> = &'a VarianceTerm<'a>;
303
304 #[derive(Copy, Clone, Debug)]
305 struct InferredIndex(usize);
306
307 #[derive(Copy, Clone)]
308 enum VarianceTerm<'a> {
309     ConstantTerm(ty::Variance),
310     TransformTerm(VarianceTermPtr<'a>, VarianceTermPtr<'a>),
311     InferredTerm(InferredIndex),
312 }
313
314 impl<'a> fmt::Debug for VarianceTerm<'a> {
315     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
316         match *self {
317             ConstantTerm(c1) => write!(f, "{:?}", c1),
318             TransformTerm(v1, v2) => write!(f, "({:?} \u{00D7} {:?})", v1, v2),
319             InferredTerm(id) => write!(f, "[{}]", { let InferredIndex(i) = id; i })
320         }
321     }
322 }
323
324 // The first pass over the crate simply builds up the set of inferreds.
325
326 struct TermsContext<'a, 'tcx: 'a> {
327     tcx: &'a ty::ctxt<'tcx>,
328     arena: &'a TypedArena<VarianceTerm<'a>>,
329
330     empty_variances: Rc<ty::ItemVariances>,
331
332     // For marker types, UnsafeCell, and other lang items where
333     // variance is hardcoded, records the item-id and the hardcoded
334     // variance.
335     lang_items: Vec<(ast::NodeId, Vec<ty::Variance>)>,
336
337     // Maps from the node id of a type/generic parameter to the
338     // corresponding inferred index.
339     inferred_map: NodeMap<InferredIndex>,
340
341     // Maps from an InferredIndex to the info for that variable.
342     inferred_infos: Vec<InferredInfo<'a>> ,
343 }
344
345 #[derive(Copy, Clone, Debug, PartialEq)]
346 enum ParamKind {
347     TypeParam,
348     RegionParam,
349 }
350
351 struct InferredInfo<'a> {
352     item_id: ast::NodeId,
353     kind: ParamKind,
354     space: ParamSpace,
355     index: usize,
356     param_id: ast::NodeId,
357     term: VarianceTermPtr<'a>,
358
359     // Initial value to use for this parameter when inferring
360     // variance. For most parameters, this is Bivariant. But for lang
361     // items and input type parameters on traits, it is different.
362     initial_variance: ty::Variance,
363 }
364
365 fn determine_parameters_to_be_inferred<'a, 'tcx>(tcx: &'a ty::ctxt<'tcx>,
366                                                  arena: &'a mut TypedArena<VarianceTerm<'a>>,
367                                                  krate: &hir::Crate)
368                                                  -> TermsContext<'a, 'tcx> {
369     let mut terms_cx = TermsContext {
370         tcx: tcx,
371         arena: arena,
372         inferred_map: NodeMap(),
373         inferred_infos: Vec::new(),
374
375         lang_items: lang_items(tcx),
376
377         // cache and share the variance struct used for items with
378         // no type/region parameters
379         empty_variances: Rc::new(ty::ItemVariances {
380             types: VecPerParamSpace::empty(),
381             regions: VecPerParamSpace::empty()
382         })
383     };
384
385     krate.visit_all_items(&mut terms_cx);
386
387     terms_cx
388 }
389
390 fn lang_items(tcx: &ty::ctxt) -> Vec<(ast::NodeId,Vec<ty::Variance>)> {
391     let all = vec![
392         (tcx.lang_items.phantom_data(), vec![ty::Covariant]),
393         (tcx.lang_items.unsafe_cell_type(), vec![ty::Invariant]),
394
395         // Deprecated:
396         (tcx.lang_items.covariant_type(), vec![ty::Covariant]),
397         (tcx.lang_items.contravariant_type(), vec![ty::Contravariant]),
398         (tcx.lang_items.invariant_type(), vec![ty::Invariant]),
399         (tcx.lang_items.covariant_lifetime(), vec![ty::Covariant]),
400         (tcx.lang_items.contravariant_lifetime(), vec![ty::Contravariant]),
401         (tcx.lang_items.invariant_lifetime(), vec![ty::Invariant]),
402
403         ];
404
405     all.into_iter() // iterating over (Option<DefId>, Variance)
406        .filter(|&(ref d,_)| d.is_some())
407        .map(|(d, v)| (d.unwrap(), v)) // (DefId, Variance)
408        .filter_map(|(d, v)| tcx.map.as_local_node_id(d).map(|n| (n, v))) // (NodeId, Variance)
409        .collect()
410 }
411
412 impl<'a, 'tcx> TermsContext<'a, 'tcx> {
413     fn add_inferreds_for_item(&mut self,
414                               item_id: ast::NodeId,
415                               has_self: bool,
416                               generics: &hir::Generics)
417     {
418         /*!
419          * Add "inferreds" for the generic parameters declared on this
420          * item. This has a lot of annoying parameters because we are
421          * trying to drive this from the AST, rather than the
422          * ty::Generics, so that we can get span info -- but this
423          * means we must accommodate syntactic distinctions.
424          */
425
426         // NB: In the code below for writing the results back into the
427         // tcx, we rely on the fact that all inferreds for a particular
428         // item are assigned continuous indices.
429
430         let inferreds_on_entry = self.num_inferred();
431
432         if has_self {
433             self.add_inferred(item_id, TypeParam, SelfSpace, 0, item_id);
434         }
435
436         for (i, p) in generics.lifetimes.iter().enumerate() {
437             let id = p.lifetime.id;
438             self.add_inferred(item_id, RegionParam, TypeSpace, i, id);
439         }
440
441         for (i, p) in generics.ty_params.iter().enumerate() {
442             self.add_inferred(item_id, TypeParam, TypeSpace, i, p.id);
443         }
444
445         // If this item has no type or lifetime parameters,
446         // then there are no variances to infer, so just
447         // insert an empty entry into the variance map.
448         // Arguably we could just leave the map empty in this
449         // case but it seems cleaner to be able to distinguish
450         // "invalid item id" from "item id with no
451         // parameters".
452         if self.num_inferred() == inferreds_on_entry {
453             let item_def_id = self.tcx.map.local_def_id(item_id);
454             let newly_added =
455                 self.tcx.item_variance_map.borrow_mut().insert(
456                     item_def_id,
457                     self.empty_variances.clone()).is_none();
458             assert!(newly_added);
459         }
460     }
461
462     fn add_inferred(&mut self,
463                     item_id: ast::NodeId,
464                     kind: ParamKind,
465                     space: ParamSpace,
466                     index: usize,
467                     param_id: ast::NodeId) {
468         let inf_index = InferredIndex(self.inferred_infos.len());
469         let term = self.arena.alloc(InferredTerm(inf_index));
470         let initial_variance = self.pick_initial_variance(item_id, space, index);
471         self.inferred_infos.push(InferredInfo { item_id: item_id,
472                                                 kind: kind,
473                                                 space: space,
474                                                 index: index,
475                                                 param_id: param_id,
476                                                 term: term,
477                                                 initial_variance: initial_variance });
478         let newly_added = self.inferred_map.insert(param_id, inf_index).is_none();
479         assert!(newly_added);
480
481         debug!("add_inferred(item_path={}, \
482                 item_id={}, \
483                 kind={:?}, \
484                 space={:?}, \
485                 index={}, \
486                 param_id={}, \
487                 inf_index={:?}, \
488                 initial_variance={:?})",
489                self.tcx.item_path_str(self.tcx.map.local_def_id(item_id)),
490                item_id, kind, space, index, param_id, inf_index,
491                initial_variance);
492     }
493
494     fn pick_initial_variance(&self,
495                              item_id: ast::NodeId,
496                              space: ParamSpace,
497                              index: usize)
498                              -> ty::Variance
499     {
500         match space {
501             SelfSpace | FnSpace => {
502                 ty::Bivariant
503             }
504
505             TypeSpace => {
506                 match self.lang_items.iter().find(|&&(n, _)| n == item_id) {
507                     Some(&(_, ref variances)) => variances[index],
508                     None => ty::Bivariant
509                 }
510             }
511         }
512     }
513
514     fn num_inferred(&self) -> usize {
515         self.inferred_infos.len()
516     }
517 }
518
519 impl<'a, 'tcx, 'v> Visitor<'v> for TermsContext<'a, 'tcx> {
520     fn visit_item(&mut self, item: &hir::Item) {
521         debug!("add_inferreds for item {}", self.tcx.map.node_to_string(item.id));
522
523         match item.node {
524             hir::ItemEnum(_, ref generics) |
525             hir::ItemStruct(_, ref generics) => {
526                 self.add_inferreds_for_item(item.id, false, generics);
527             }
528             hir::ItemTrait(_, ref generics, _, _) => {
529                 // Note: all inputs for traits are ultimately
530                 // constrained to be invariant. See `visit_item` in
531                 // the impl for `ConstraintContext` below.
532                 self.add_inferreds_for_item(item.id, true, generics);
533             }
534
535             hir::ItemExternCrate(_) |
536             hir::ItemUse(_) |
537             hir::ItemDefaultImpl(..) |
538             hir::ItemImpl(..) |
539             hir::ItemStatic(..) |
540             hir::ItemConst(..) |
541             hir::ItemFn(..) |
542             hir::ItemMod(..) |
543             hir::ItemForeignMod(..) |
544             hir::ItemTy(..) => {
545             }
546         }
547     }
548 }
549
550 // Constraint construction and representation
551 //
552 // The second pass over the AST determines the set of constraints.
553 // We walk the set of items and, for each member, generate new constraints.
554
555 struct ConstraintContext<'a, 'tcx: 'a> {
556     terms_cx: TermsContext<'a, 'tcx>,
557
558     // These are pointers to common `ConstantTerm` instances
559     covariant: VarianceTermPtr<'a>,
560     contravariant: VarianceTermPtr<'a>,
561     invariant: VarianceTermPtr<'a>,
562     bivariant: VarianceTermPtr<'a>,
563
564     constraints: Vec<Constraint<'a>> ,
565 }
566
567 /// Declares that the variable `decl_id` appears in a location with
568 /// variance `variance`.
569 #[derive(Copy, Clone)]
570 struct Constraint<'a> {
571     inferred: InferredIndex,
572     variance: &'a VarianceTerm<'a>,
573 }
574
575 fn add_constraints_from_crate<'a, 'tcx>(terms_cx: TermsContext<'a, 'tcx>,
576                                         krate: &hir::Crate)
577                                         -> ConstraintContext<'a, 'tcx>
578 {
579     let covariant = terms_cx.arena.alloc(ConstantTerm(ty::Covariant));
580     let contravariant = terms_cx.arena.alloc(ConstantTerm(ty::Contravariant));
581     let invariant = terms_cx.arena.alloc(ConstantTerm(ty::Invariant));
582     let bivariant = terms_cx.arena.alloc(ConstantTerm(ty::Bivariant));
583     let mut constraint_cx = ConstraintContext {
584         terms_cx: terms_cx,
585         covariant: covariant,
586         contravariant: contravariant,
587         invariant: invariant,
588         bivariant: bivariant,
589         constraints: Vec::new(),
590     };
591     krate.visit_all_items(&mut constraint_cx);
592     constraint_cx
593 }
594
595 impl<'a, 'tcx, 'v> Visitor<'v> for ConstraintContext<'a, 'tcx> {
596     fn visit_item(&mut self, item: &hir::Item) {
597         let tcx = self.terms_cx.tcx;
598         let did = tcx.map.local_def_id(item.id);
599
600         debug!("visit_item item={}", tcx.map.node_to_string(item.id));
601
602         match item.node {
603             hir::ItemEnum(..) | hir::ItemStruct(..) => {
604                 let scheme = tcx.lookup_item_type(did);
605
606                 // Not entirely obvious: constraints on structs/enums do not
607                 // affect the variance of their type parameters. See discussion
608                 // in comment at top of module.
609                 //
610                 // self.add_constraints_from_generics(&scheme.generics);
611
612                 for field in tcx.lookup_adt_def(did).all_fields() {
613                     self.add_constraints_from_ty(&scheme.generics,
614                                                  field.unsubst_ty(),
615                                                  self.covariant);
616                 }
617             }
618             hir::ItemTrait(..) => {
619                 let trait_def = tcx.lookup_trait_def(did);
620                 self.add_constraints_from_trait_ref(&trait_def.generics,
621                                                     trait_def.trait_ref,
622                                                     self.invariant);
623             }
624
625             hir::ItemExternCrate(_) |
626             hir::ItemUse(_) |
627             hir::ItemStatic(..) |
628             hir::ItemConst(..) |
629             hir::ItemFn(..) |
630             hir::ItemMod(..) |
631             hir::ItemForeignMod(..) |
632             hir::ItemTy(..) |
633             hir::ItemImpl(..) |
634             hir::ItemDefaultImpl(..) => {
635             }
636         }
637     }
638 }
639
640 /// Is `param_id` a lifetime according to `map`?
641 fn is_lifetime(map: &hir_map::Map, param_id: ast::NodeId) -> bool {
642     match map.find(param_id) {
643         Some(hir_map::NodeLifetime(..)) => true, _ => false
644     }
645 }
646
647 impl<'a, 'tcx> ConstraintContext<'a, 'tcx> {
648     fn tcx(&self) -> &'a ty::ctxt<'tcx> {
649         self.terms_cx.tcx
650     }
651
652     fn inferred_index(&self, param_id: ast::NodeId) -> InferredIndex {
653         match self.terms_cx.inferred_map.get(&param_id) {
654             Some(&index) => index,
655             None => {
656                 self.tcx().sess.bug(&format!(
657                         "no inferred index entry for {}",
658                         self.tcx().map.node_to_string(param_id)));
659             }
660         }
661     }
662
663     fn find_binding_for_lifetime(&self, param_id: ast::NodeId) -> ast::NodeId {
664         let tcx = self.terms_cx.tcx;
665         assert!(is_lifetime(&tcx.map, param_id));
666         match tcx.named_region_map.get(&param_id) {
667             Some(&rl::DefEarlyBoundRegion(_, _, lifetime_decl_id))
668                 => lifetime_decl_id,
669             Some(_) => panic!("should not encounter non early-bound cases"),
670
671             // The lookup should only fail when `param_id` is
672             // itself a lifetime binding: use it as the decl_id.
673             None    => param_id,
674         }
675
676     }
677
678     /// Is `param_id` a type parameter for which we infer variance?
679     fn is_to_be_inferred(&self, param_id: ast::NodeId) -> bool {
680         let result = self.terms_cx.inferred_map.contains_key(&param_id);
681
682         // To safe-guard against invalid inferred_map constructions,
683         // double-check if variance is inferred at some use of a type
684         // parameter (by inspecting parent of its binding declaration
685         // to see if it is introduced by a type or by a fn/impl).
686
687         let check_result = |this:&ConstraintContext| -> bool {
688             let tcx = this.terms_cx.tcx;
689             let decl_id = this.find_binding_for_lifetime(param_id);
690             // Currently only called on lifetimes; double-checking that.
691             assert!(is_lifetime(&tcx.map, param_id));
692             let parent_id = tcx.map.get_parent(decl_id);
693             let parent = tcx.map.find(parent_id).unwrap_or_else(
694                 || panic!("tcx.map missing entry for id: {}", parent_id));
695
696             let is_inferred;
697             macro_rules! cannot_happen { () => { {
698                 panic!("invalid parent: {} for {}",
699                       tcx.map.node_to_string(parent_id),
700                       tcx.map.node_to_string(param_id));
701             } } }
702
703             match parent {
704                 hir_map::NodeItem(p) => {
705                     match p.node {
706                         hir::ItemTy(..) |
707                         hir::ItemEnum(..) |
708                         hir::ItemStruct(..) |
709                         hir::ItemTrait(..)   => is_inferred = true,
710                         hir::ItemFn(..)      => is_inferred = false,
711                         _                    => cannot_happen!(),
712                     }
713                 }
714                 hir_map::NodeTraitItem(..)   => is_inferred = false,
715                 hir_map::NodeImplItem(..)    => is_inferred = false,
716                 _                            => cannot_happen!(),
717             }
718
719             return is_inferred;
720         };
721
722         assert_eq!(result, check_result(self));
723
724         return result;
725     }
726
727     /// Returns a variance term representing the declared variance of the type/region parameter
728     /// with the given id.
729     fn declared_variance(&self,
730                          param_def_id: DefId,
731                          item_def_id: DefId,
732                          kind: ParamKind,
733                          space: ParamSpace,
734                          index: usize)
735                          -> VarianceTermPtr<'a> {
736         assert_eq!(param_def_id.krate, item_def_id.krate);
737
738         if let Some(param_node_id) = self.tcx().map.as_local_node_id(param_def_id) {
739             // Parameter on an item defined within current crate:
740             // variance not yet inferred, so return a symbolic
741             // variance.
742             let InferredIndex(index) = self.inferred_index(param_node_id);
743             self.terms_cx.inferred_infos[index].term
744         } else {
745             // Parameter on an item defined within another crate:
746             // variance already inferred, just look it up.
747             let variances = self.tcx().item_variances(item_def_id);
748             let variance = match kind {
749                 TypeParam => *variances.types.get(space, index),
750                 RegionParam => *variances.regions.get(space, index),
751             };
752             self.constant_term(variance)
753         }
754     }
755
756     fn add_constraint(&mut self,
757                       InferredIndex(index): InferredIndex,
758                       variance: VarianceTermPtr<'a>) {
759         debug!("add_constraint(index={}, variance={:?})",
760                 index, variance);
761         self.constraints.push(Constraint { inferred: InferredIndex(index),
762                                            variance: variance });
763     }
764
765     fn contravariant(&mut self,
766                      variance: VarianceTermPtr<'a>)
767                      -> VarianceTermPtr<'a> {
768         self.xform(variance, self.contravariant)
769     }
770
771     fn invariant(&mut self,
772                  variance: VarianceTermPtr<'a>)
773                  -> VarianceTermPtr<'a> {
774         self.xform(variance, self.invariant)
775     }
776
777     fn constant_term(&self, v: ty::Variance) -> VarianceTermPtr<'a> {
778         match v {
779             ty::Covariant => self.covariant,
780             ty::Invariant => self.invariant,
781             ty::Contravariant => self.contravariant,
782             ty::Bivariant => self.bivariant,
783         }
784     }
785
786     fn xform(&mut self,
787              v1: VarianceTermPtr<'a>,
788              v2: VarianceTermPtr<'a>)
789              -> VarianceTermPtr<'a> {
790         match (*v1, *v2) {
791             (_, ConstantTerm(ty::Covariant)) => {
792                 // Applying a "covariant" transform is always a no-op
793                 v1
794             }
795
796             (ConstantTerm(c1), ConstantTerm(c2)) => {
797                 self.constant_term(c1.xform(c2))
798             }
799
800             _ => {
801                 &*self.terms_cx.arena.alloc(TransformTerm(v1, v2))
802             }
803         }
804     }
805
806     fn add_constraints_from_trait_ref(&mut self,
807                                       generics: &ty::Generics<'tcx>,
808                                       trait_ref: ty::TraitRef<'tcx>,
809                                       variance: VarianceTermPtr<'a>) {
810         debug!("add_constraints_from_trait_ref: trait_ref={:?} variance={:?}",
811                trait_ref,
812                variance);
813
814         let trait_def = self.tcx().lookup_trait_def(trait_ref.def_id);
815
816         self.add_constraints_from_substs(
817             generics,
818             trait_ref.def_id,
819             trait_def.generics.types.as_slice(),
820             trait_def.generics.regions.as_slice(),
821             trait_ref.substs,
822             variance);
823     }
824
825     /// Adds constraints appropriate for an instance of `ty` appearing
826     /// in a context with the generics defined in `generics` and
827     /// ambient variance `variance`
828     fn add_constraints_from_ty(&mut self,
829                                generics: &ty::Generics<'tcx>,
830                                ty: Ty<'tcx>,
831                                variance: VarianceTermPtr<'a>) {
832         debug!("add_constraints_from_ty(ty={:?}, variance={:?})",
833                ty,
834                variance);
835
836         match ty.sty {
837             ty::TyBool |
838             ty::TyChar | ty::TyInt(_) | ty::TyUint(_) |
839             ty::TyFloat(_) | ty::TyStr => {
840                 /* leaf type -- noop */
841             }
842
843             ty::TyClosure(..) => {
844                 self.tcx().sess.bug("Unexpected closure type in variance computation");
845             }
846
847             ty::TyRef(region, ref mt) => {
848                 let contra = self.contravariant(variance);
849                 self.add_constraints_from_region(generics, *region, contra);
850                 self.add_constraints_from_mt(generics, mt, variance);
851             }
852
853             ty::TyBox(typ) | ty::TyArray(typ, _) | ty::TySlice(typ) => {
854                 self.add_constraints_from_ty(generics, typ, variance);
855             }
856
857
858             ty::TyRawPtr(ref mt) => {
859                 self.add_constraints_from_mt(generics, mt, variance);
860             }
861
862             ty::TyTuple(ref subtys) => {
863                 for &subty in subtys {
864                     self.add_constraints_from_ty(generics, subty, variance);
865                 }
866             }
867
868             ty::TyEnum(def, substs) |
869             ty::TyStruct(def, substs) => {
870                 let item_type = self.tcx().lookup_item_type(def.did);
871
872                 // All type parameters on enums and structs should be
873                 // in the TypeSpace.
874                 assert!(item_type.generics.types.is_empty_in(subst::SelfSpace));
875                 assert!(item_type.generics.types.is_empty_in(subst::FnSpace));
876                 assert!(item_type.generics.regions.is_empty_in(subst::SelfSpace));
877                 assert!(item_type.generics.regions.is_empty_in(subst::FnSpace));
878
879                 self.add_constraints_from_substs(
880                     generics,
881                     def.did,
882                     item_type.generics.types.get_slice(subst::TypeSpace),
883                     item_type.generics.regions.get_slice(subst::TypeSpace),
884                     substs,
885                     variance);
886             }
887
888             ty::TyProjection(ref data) => {
889                 let trait_ref = &data.trait_ref;
890                 let trait_def = self.tcx().lookup_trait_def(trait_ref.def_id);
891                 self.add_constraints_from_substs(
892                     generics,
893                     trait_ref.def_id,
894                     trait_def.generics.types.as_slice(),
895                     trait_def.generics.regions.as_slice(),
896                     trait_ref.substs,
897                     variance);
898             }
899
900             ty::TyTrait(ref data) => {
901                 let poly_trait_ref =
902                     data.principal_trait_ref_with_self_ty(self.tcx(),
903                                                           self.tcx().types.err);
904
905                 // The type `Foo<T+'a>` is contravariant w/r/t `'a`:
906                 let contra = self.contravariant(variance);
907                 self.add_constraints_from_region(generics, data.bounds.region_bound, contra);
908
909                 // Ignore the SelfSpace, it is erased.
910                 self.add_constraints_from_trait_ref(generics, poly_trait_ref.0, variance);
911
912                 let projections = data.projection_bounds_with_self_ty(self.tcx(),
913                                                                       self.tcx().types.err);
914                 for projection in &projections {
915                     self.add_constraints_from_ty(generics, projection.0.ty, self.invariant);
916                 }
917             }
918
919             ty::TyParam(ref data) => {
920                 let def_id = generics.types.get(data.space, data.idx as usize).def_id;
921                 let node_id = self.tcx().map.as_local_node_id(def_id).unwrap();
922                 match self.terms_cx.inferred_map.get(&node_id) {
923                     Some(&index) => {
924                         self.add_constraint(index, variance);
925                     }
926                     None => {
927                         // We do not infer variance for type parameters
928                         // declared on methods. They will not be present
929                         // in the inferred_map.
930                     }
931                 }
932             }
933
934             ty::TyBareFn(_, &ty::BareFnTy { ref sig, .. }) => {
935                 self.add_constraints_from_sig(generics, sig, variance);
936             }
937
938             ty::TyError => {
939                 // we encounter this when walking the trait references for object
940                 // types, where we use TyError as the Self type
941             }
942
943             ty::TyInfer(..) => {
944                 self.tcx().sess.bug(
945                     &format!("unexpected type encountered in \
946                               variance inference: {}", ty));
947             }
948         }
949     }
950
951
952     /// Adds constraints appropriate for a nominal type (enum, struct,
953     /// object, etc) appearing in a context with ambient variance `variance`
954     fn add_constraints_from_substs(&mut self,
955                                    generics: &ty::Generics<'tcx>,
956                                    def_id: DefId,
957                                    type_param_defs: &[ty::TypeParameterDef<'tcx>],
958                                    region_param_defs: &[ty::RegionParameterDef],
959                                    substs: &subst::Substs<'tcx>,
960                                    variance: VarianceTermPtr<'a>) {
961         debug!("add_constraints_from_substs(def_id={:?}, substs={:?}, variance={:?})",
962                def_id,
963                substs,
964                variance);
965
966         for p in type_param_defs {
967             let variance_decl =
968                 self.declared_variance(p.def_id, def_id, TypeParam,
969                                        p.space, p.index as usize);
970             let variance_i = self.xform(variance, variance_decl);
971             let substs_ty = *substs.types.get(p.space, p.index as usize);
972             debug!("add_constraints_from_substs: variance_decl={:?} variance_i={:?}",
973                    variance_decl, variance_i);
974             self.add_constraints_from_ty(generics, substs_ty, variance_i);
975         }
976
977         for p in region_param_defs {
978             let variance_decl =
979                 self.declared_variance(p.def_id, def_id,
980                                        RegionParam, p.space, p.index as usize);
981             let variance_i = self.xform(variance, variance_decl);
982             let substs_r = *substs.regions().get(p.space, p.index as usize);
983             self.add_constraints_from_region(generics, substs_r, variance_i);
984         }
985     }
986
987     /// Adds constraints appropriate for a function with signature
988     /// `sig` appearing in a context with ambient variance `variance`
989     fn add_constraints_from_sig(&mut self,
990                                 generics: &ty::Generics<'tcx>,
991                                 sig: &ty::PolyFnSig<'tcx>,
992                                 variance: VarianceTermPtr<'a>) {
993         let contra = self.contravariant(variance);
994         for &input in &sig.0.inputs {
995             self.add_constraints_from_ty(generics, input, contra);
996         }
997         if let ty::FnConverging(result_type) = sig.0.output {
998             self.add_constraints_from_ty(generics, result_type, variance);
999         }
1000     }
1001
1002     /// Adds constraints appropriate for a region appearing in a
1003     /// context with ambient variance `variance`
1004     fn add_constraints_from_region(&mut self,
1005                                    _generics: &ty::Generics<'tcx>,
1006                                    region: ty::Region,
1007                                    variance: VarianceTermPtr<'a>) {
1008         match region {
1009             ty::ReEarlyBound(ref data) => {
1010                 let node_id = self.tcx().map.as_local_node_id(data.def_id).unwrap();
1011                 if self.is_to_be_inferred(node_id) {
1012                     let index = self.inferred_index(node_id);
1013                     self.add_constraint(index, variance);
1014                 }
1015             }
1016
1017             ty::ReStatic => { }
1018
1019             ty::ReLateBound(..) => {
1020                 // We do not infer variance for region parameters on
1021                 // methods or in fn types.
1022             }
1023
1024             ty::ReFree(..) | ty::ReScope(..) | ty::ReVar(..) |
1025             ty::ReSkolemized(..) | ty::ReEmpty => {
1026                 // We don't expect to see anything but 'static or bound
1027                 // regions when visiting member types or method types.
1028                 self.tcx()
1029                     .sess
1030                     .bug(&format!("unexpected region encountered in variance \
1031                                   inference: {:?}",
1032                                  region));
1033             }
1034         }
1035     }
1036
1037     /// Adds constraints appropriate for a mutability-type pair
1038     /// appearing in a context with ambient variance `variance`
1039     fn add_constraints_from_mt(&mut self,
1040                                generics: &ty::Generics<'tcx>,
1041                                mt: &ty::TypeAndMut<'tcx>,
1042                                variance: VarianceTermPtr<'a>) {
1043         match mt.mutbl {
1044             hir::MutMutable => {
1045                 let invar = self.invariant(variance);
1046                 self.add_constraints_from_ty(generics, mt.ty, invar);
1047             }
1048
1049             hir::MutImmutable => {
1050                 self.add_constraints_from_ty(generics, mt.ty, variance);
1051             }
1052         }
1053     }
1054 }
1055
1056 // Constraint solving
1057 //
1058 // The final phase iterates over the constraints, refining the variance
1059 // for each inferred until a fixed point is reached. This will be the
1060 // optimal solution to the constraints. The final variance for each
1061 // inferred is then written into the `variance_map` in the tcx.
1062
1063 struct SolveContext<'a, 'tcx: 'a> {
1064     terms_cx: TermsContext<'a, 'tcx>,
1065     constraints: Vec<Constraint<'a>> ,
1066
1067     // Maps from an InferredIndex to the inferred value for that variable.
1068     solutions: Vec<ty::Variance> }
1069
1070 fn solve_constraints(constraints_cx: ConstraintContext) {
1071     let ConstraintContext { terms_cx, constraints, .. } = constraints_cx;
1072
1073     let solutions =
1074         terms_cx.inferred_infos.iter()
1075                                .map(|ii| ii.initial_variance)
1076                                .collect();
1077
1078     let mut solutions_cx = SolveContext {
1079         terms_cx: terms_cx,
1080         constraints: constraints,
1081         solutions: solutions
1082     };
1083     solutions_cx.solve();
1084     solutions_cx.write();
1085 }
1086
1087 impl<'a, 'tcx> SolveContext<'a, 'tcx> {
1088     fn solve(&mut self) {
1089         // Propagate constraints until a fixed point is reached.  Note
1090         // that the maximum number of iterations is 2C where C is the
1091         // number of constraints (each variable can change values at most
1092         // twice). Since number of constraints is linear in size of the
1093         // input, so is the inference process.
1094         let mut changed = true;
1095         while changed {
1096             changed = false;
1097
1098             for constraint in &self.constraints {
1099                 let Constraint { inferred, variance: term } = *constraint;
1100                 let InferredIndex(inferred) = inferred;
1101                 let variance = self.evaluate(term);
1102                 let old_value = self.solutions[inferred];
1103                 let new_value = glb(variance, old_value);
1104                 if old_value != new_value {
1105                     debug!("Updating inferred {} (node {}) \
1106                             from {:?} to {:?} due to {:?}",
1107                             inferred,
1108                             self.terms_cx
1109                                 .inferred_infos[inferred]
1110                                 .param_id,
1111                             old_value,
1112                             new_value,
1113                             term);
1114
1115                     self.solutions[inferred] = new_value;
1116                     changed = true;
1117                 }
1118             }
1119         }
1120     }
1121
1122     fn write(&self) {
1123         // Collect all the variances for a particular item and stick
1124         // them into the variance map. We rely on the fact that we
1125         // generate all the inferreds for a particular item
1126         // consecutively (that is, we collect solutions for an item
1127         // until we see a new item id, and we assume (1) the solutions
1128         // are in the same order as the type parameters were declared
1129         // and (2) all solutions or a given item appear before a new
1130         // item id).
1131
1132         let tcx = self.terms_cx.tcx;
1133         let solutions = &self.solutions;
1134         let inferred_infos = &self.terms_cx.inferred_infos;
1135         let mut index = 0;
1136         let num_inferred = self.terms_cx.num_inferred();
1137         while index < num_inferred {
1138             let item_id = inferred_infos[index].item_id;
1139             let mut types = VecPerParamSpace::empty();
1140             let mut regions = VecPerParamSpace::empty();
1141
1142             while index < num_inferred && inferred_infos[index].item_id == item_id {
1143                 let info = &inferred_infos[index];
1144                 let variance = solutions[index];
1145                 debug!("Index {} Info {} / {:?} / {:?} Variance {:?}",
1146                        index, info.index, info.kind, info.space, variance);
1147                 match info.kind {
1148                     TypeParam => { types.push(info.space, variance); }
1149                     RegionParam => { regions.push(info.space, variance); }
1150                 }
1151
1152                 index += 1;
1153             }
1154
1155             let item_variances = ty::ItemVariances {
1156                 types: types,
1157                 regions: regions
1158             };
1159             debug!("item_id={} item_variances={:?}",
1160                     item_id,
1161                     item_variances);
1162
1163             let item_def_id = tcx.map.local_def_id(item_id);
1164
1165             // For unit testing: check for a special "rustc_variance"
1166             // attribute and report an error with various results if found.
1167             if tcx.has_attr(item_def_id, "rustc_variance") {
1168                 span_err!(tcx.sess, tcx.map.span(item_id), E0208, "{:?}", item_variances);
1169             }
1170
1171             let newly_added = tcx.item_variance_map.borrow_mut()
1172                                  .insert(item_def_id, Rc::new(item_variances)).is_none();
1173             assert!(newly_added);
1174         }
1175     }
1176
1177     fn evaluate(&self, term: VarianceTermPtr<'a>) -> ty::Variance {
1178         match *term {
1179             ConstantTerm(v) => {
1180                 v
1181             }
1182
1183             TransformTerm(t1, t2) => {
1184                 let v1 = self.evaluate(t1);
1185                 let v2 = self.evaluate(t2);
1186                 v1.xform(v2)
1187             }
1188
1189             InferredTerm(InferredIndex(index)) => {
1190                 self.solutions[index]
1191             }
1192         }
1193     }
1194 }
1195
1196 // Miscellany transformations on variance
1197
1198 trait Xform {
1199     fn xform(self, v: Self) -> Self;
1200 }
1201
1202 impl Xform for ty::Variance {
1203     fn xform(self, v: ty::Variance) -> ty::Variance {
1204         // "Variance transformation", Figure 1 of The Paper
1205         match (self, v) {
1206             // Figure 1, column 1.
1207             (ty::Covariant, ty::Covariant) => ty::Covariant,
1208             (ty::Covariant, ty::Contravariant) => ty::Contravariant,
1209             (ty::Covariant, ty::Invariant) => ty::Invariant,
1210             (ty::Covariant, ty::Bivariant) => ty::Bivariant,
1211
1212             // Figure 1, column 2.
1213             (ty::Contravariant, ty::Covariant) => ty::Contravariant,
1214             (ty::Contravariant, ty::Contravariant) => ty::Covariant,
1215             (ty::Contravariant, ty::Invariant) => ty::Invariant,
1216             (ty::Contravariant, ty::Bivariant) => ty::Bivariant,
1217
1218             // Figure 1, column 3.
1219             (ty::Invariant, _) => ty::Invariant,
1220
1221             // Figure 1, column 4.
1222             (ty::Bivariant, _) => ty::Bivariant,
1223         }
1224     }
1225 }
1226
1227 fn glb(v1: ty::Variance, v2: ty::Variance) -> ty::Variance {
1228     // Greatest lower bound of the variance lattice as
1229     // defined in The Paper:
1230     //
1231     //       *
1232     //    -     +
1233     //       o
1234     match (v1, v2) {
1235         (ty::Invariant, _) | (_, ty::Invariant) => ty::Invariant,
1236
1237         (ty::Covariant, ty::Contravariant) => ty::Invariant,
1238         (ty::Contravariant, ty::Covariant) => ty::Invariant,
1239
1240         (ty::Covariant, ty::Covariant) => ty::Covariant,
1241
1242         (ty::Contravariant, ty::Contravariant) => ty::Contravariant,
1243
1244         (x, ty::Bivariant) | (ty::Bivariant, x) => x,
1245     }
1246 }