]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/variance.rs
Delete the outdated source layout README
[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 *types*: structs,
22 //! enums, and traits. We do not infer variance for type parameters found
23 //! on fns or impls. This is because those things are not type definitions
24 //! and variance doesn't really make sense in that context.
25 //!
26 //! It is worth covering what variance means in each case. For structs and
27 //! enums, I think it is fairly straightforward. The variance of the type
28 //! or lifetime parameters defines whether `T<A>` is a subtype of `T<B>`
29 //! (resp. `T<'a>` and `T<'b>`) based on the relationship of `A` and `B`
30 //! (resp. `'a` and `'b`). (FIXME #3598 -- we do not currently make use of
31 //! the variances we compute for type parameters.)
32 //!
33 //! ### Variance on traits
34 //!
35 //! The meaning of variance for trait parameters is more subtle and worth
36 //! expanding upon. There are in fact two uses of the variance values we
37 //! compute.
38 //!
39 //! #### Trait variance and object types
40 //!
41 //! The first is for object types. Just as with structs and enums, we can
42 //! decide the subtyping relationship between two object types `&Trait<A>`
43 //! and `&Trait<B>` based on the relationship of `A` and `B`. Note that
44 //! for object types we ignore the `Self` type parameter -- it is unknown,
45 //! and the nature of dynamic dispatch ensures that we will always call a
46 //! function that is expected the appropriate `Self` type. However, we
47 //! must be careful with the other type parameters, or else we could end
48 //! up calling a function that is expecting one type but provided another.
49 //!
50 //! To see what I mean, consider a trait like so:
51 //!
52 //!     trait ConvertTo<A> {
53 //!         fn convertTo(&self) -> A;
54 //!     }
55 //!
56 //! Intuitively, If we had one object `O=&ConvertTo<Object>` and another
57 //! `S=&ConvertTo<String>`, then `S <: O` because `String <: Object`
58 //! (presuming Java-like "string" and "object" types, my go to examples
59 //! for subtyping). The actual algorithm would be to compare the
60 //! (explicit) type parameters pairwise respecting their variance: here,
61 //! the type parameter A is covariant (it appears only in a return
62 //! position), and hence we require that `String <: Object`.
63 //!
64 //! You'll note though that we did not consider the binding for the
65 //! (implicit) `Self` type parameter: in fact, it is unknown, so that's
66 //! good. The reason we can ignore that parameter is precisely because we
67 //! don't need to know its value until a call occurs, and at that time (as
68 //! you said) the dynamic nature of virtual dispatch means the code we run
69 //! will be correct for whatever value `Self` happens to be bound to for
70 //! the particular object whose method we called. `Self` is thus different
71 //! from `A`, because the caller requires that `A` be known in order to
72 //! know the return type of the method `convertTo()`. (As an aside, we
73 //! have rules preventing methods where `Self` appears outside of the
74 //! receiver position from being called via an object.)
75 //!
76 //! #### Trait variance and vtable resolution
77 //!
78 //! But traits aren't only used with objects. They're also used when
79 //! deciding whether a given impl satisfies a given trait bound. To set the
80 //! scene here, imagine I had a function:
81 //!
82 //!     fn convertAll<A,T:ConvertTo<A>>(v: &[T]) {
83 //!         ...
84 //!     }
85 //!
86 //! Now imagine that I have an implementation of `ConvertTo` for `Object`:
87 //!
88 //!     impl ConvertTo<int> for Object { ... }
89 //!
90 //! And I want to call `convertAll` on an array of strings. Suppose
91 //! further that for whatever reason I specifically supply the value of
92 //! `String` for the type parameter `T`:
93 //!
94 //!     let mut vector = ~["string", ...];
95 //!     convertAll::<int, String>(v);
96 //!
97 //! Is this legal? To put another way, can we apply the `impl` for
98 //! `Object` to the type `String`? The answer is yes, but to see why
99 //! we have to expand out what will happen:
100 //!
101 //! - `convertAll` will create a pointer to one of the entries in the
102 //!   vector, which will have type `&String`
103 //! - It will then call the impl of `convertTo()` that is intended
104 //!   for use with objects. This has the type:
105 //!
106 //!       fn(self: &Object) -> int
107 //!
108 //!   It is ok to provide a value for `self` of type `&String` because
109 //!   `&String <: &Object`.
110 //!
111 //! OK, so intuitively we want this to be legal, so let's bring this back
112 //! to variance and see whether we are computing the correct result. We
113 //! must first figure out how to phrase the question "is an impl for
114 //! `Object,int` usable where an impl for `String,int` is expected?"
115 //!
116 //! Maybe it's helpful to think of a dictionary-passing implementation of
117 //! type classes. In that case, `convertAll()` takes an implicit parameter
118 //! representing the impl. In short, we *have* an impl of type:
119 //!
120 //!     V_O = ConvertTo<int> for Object
121 //!
122 //! and the function prototype expects an impl of type:
123 //!
124 //!     V_S = ConvertTo<int> for String
125 //!
126 //! As with any argument, this is legal if the type of the value given
127 //! (`V_O`) is a subtype of the type expected (`V_S`). So is `V_O <: V_S`?
128 //! The answer will depend on the variance of the various parameters. In
129 //! this case, because the `Self` parameter is contravariant and `A` is
130 //! covariant, it means that:
131 //!
132 //!     V_O <: V_S iff
133 //!         int <: int
134 //!         String <: Object
135 //!
136 //! These conditions are satisfied and so we are happy.
137 //!
138 //! ### The algorithm
139 //!
140 //! The basic idea is quite straightforward. We iterate over the types
141 //! defined and, for each use of a type parameter X, accumulate a
142 //! constraint indicating that the variance of X must be valid for the
143 //! variance of that use site. We then iteratively refine the variance of
144 //! X until all constraints are met. There is *always* a sol'n, because at
145 //! the limit we can declare all type parameters to be invariant and all
146 //! constraints will be satisfied.
147 //!
148 //! As a simple example, consider:
149 //!
150 //!     enum Option<A> { Some(A), None }
151 //!     enum OptionalFn<B> { Some(|B|), None }
152 //!     enum OptionalMap<C> { Some(|C| -> C), None }
153 //!
154 //! Here, we will generate the constraints:
155 //!
156 //!     1. V(A) <= +
157 //!     2. V(B) <= -
158 //!     3. V(C) <= +
159 //!     4. V(C) <= -
160 //!
161 //! These indicate that (1) the variance of A must be at most covariant;
162 //! (2) the variance of B must be at most contravariant; and (3, 4) the
163 //! variance of C must be at most covariant *and* contravariant. All of these
164 //! results are based on a variance lattice defined as follows:
165 //!
166 //!       *      Top (bivariant)
167 //!    -     +
168 //!       o      Bottom (invariant)
169 //!
170 //! Based on this lattice, the solution V(A)=+, V(B)=-, V(C)=o is the
171 //! optimal solution. Note that there is always a naive solution which
172 //! just declares all variables to be invariant.
173 //!
174 //! You may be wondering why fixed-point iteration is required. The reason
175 //! is that the variance of a use site may itself be a function of the
176 //! variance of other type parameters. In full generality, our constraints
177 //! take the form:
178 //!
179 //!     V(X) <= Term
180 //!     Term := + | - | * | o | V(X) | Term x Term
181 //!
182 //! Here the notation V(X) indicates the variance of a type/region
183 //! parameter `X` with respect to its defining class. `Term x Term`
184 //! represents the "variance transform" as defined in the paper:
185 //!
186 //!   If the variance of a type variable `X` in type expression `E` is `V2`
187 //!   and the definition-site variance of the [corresponding] type parameter
188 //!   of a class `C` is `V1`, then the variance of `X` in the type expression
189 //!   `C<E>` is `V3 = V1.xform(V2)`.
190
191 use self::VarianceTerm::*;
192 use self::ParamKind::*;
193
194 use arena;
195 use arena::Arena;
196 use middle::resolve_lifetime as rl;
197 use middle::subst;
198 use middle::subst::{ParamSpace, FnSpace, TypeSpace, SelfSpace, VecPerParamSpace};
199 use middle::ty::{mod, Ty};
200 use std::fmt;
201 use std::rc::Rc;
202 use syntax::ast;
203 use syntax::ast_map;
204 use syntax::ast_util;
205 use syntax::visit;
206 use syntax::visit::Visitor;
207 use util::nodemap::NodeMap;
208 use util::ppaux::Repr;
209
210 pub fn infer_variance(tcx: &ty::ctxt) {
211     let krate = tcx.map.krate();
212     let mut arena = arena::Arena::new();
213     let terms_cx = determine_parameters_to_be_inferred(tcx, &mut arena, krate);
214     let constraints_cx = add_constraints_from_crate(terms_cx, krate);
215     solve_constraints(constraints_cx);
216     tcx.variance_computed.set(true);
217 }
218
219 // Representing terms
220 //
221 // Terms are structured as a straightforward tree. Rather than rely on
222 // GC, we allocate terms out of a bounded arena (the lifetime of this
223 // arena is the lifetime 'a that is threaded around).
224 //
225 // We assign a unique index to each type/region parameter whose variance
226 // is to be inferred. We refer to such variables as "inferreds". An
227 // `InferredIndex` is a newtype'd int representing the index of such
228 // a variable.
229
230 type VarianceTermPtr<'a> = &'a VarianceTerm<'a>;
231
232 #[deriving(Show)]
233 struct InferredIndex(uint);
234
235 enum VarianceTerm<'a> {
236     ConstantTerm(ty::Variance),
237     TransformTerm(VarianceTermPtr<'a>, VarianceTermPtr<'a>),
238     InferredTerm(InferredIndex),
239 }
240
241 impl<'a> fmt::Show for VarianceTerm<'a> {
242     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
243         match *self {
244             ConstantTerm(c1) => write!(f, "{}", c1),
245             TransformTerm(v1, v2) => write!(f, "({} \u00D7 {})", v1, v2),
246             InferredTerm(id) => write!(f, "[{}]", { let InferredIndex(i) = id; i })
247         }
248     }
249 }
250
251 // The first pass over the crate simply builds up the set of inferreds.
252
253 struct TermsContext<'a, 'tcx: 'a> {
254     tcx: &'a ty::ctxt<'tcx>,
255     arena: &'a Arena,
256
257     empty_variances: Rc<ty::ItemVariances>,
258
259     // Maps from the node id of a type/generic parameter to the
260     // corresponding inferred index.
261     inferred_map: NodeMap<InferredIndex>,
262
263     // Maps from an InferredIndex to the info for that variable.
264     inferred_infos: Vec<InferredInfo<'a>> ,
265 }
266
267 #[deriving(Show, PartialEq)]
268 enum ParamKind {
269     TypeParam,
270     RegionParam
271 }
272
273 struct InferredInfo<'a> {
274     item_id: ast::NodeId,
275     kind: ParamKind,
276     space: ParamSpace,
277     index: uint,
278     param_id: ast::NodeId,
279     term: VarianceTermPtr<'a>,
280 }
281
282 fn determine_parameters_to_be_inferred<'a, 'tcx>(tcx: &'a ty::ctxt<'tcx>,
283                                                  arena: &'a mut Arena,
284                                                  krate: &ast::Crate)
285                                                  -> TermsContext<'a, 'tcx> {
286     let mut terms_cx = TermsContext {
287         tcx: tcx,
288         arena: arena,
289         inferred_map: NodeMap::new(),
290         inferred_infos: Vec::new(),
291
292         // cache and share the variance struct used for items with
293         // no type/region parameters
294         empty_variances: Rc::new(ty::ItemVariances {
295             types: VecPerParamSpace::empty(),
296             regions: VecPerParamSpace::empty()
297         })
298     };
299
300     visit::walk_crate(&mut terms_cx, krate);
301
302     terms_cx
303 }
304
305 impl<'a, 'tcx> TermsContext<'a, 'tcx> {
306     fn add_inferred(&mut self,
307                     item_id: ast::NodeId,
308                     kind: ParamKind,
309                     space: ParamSpace,
310                     index: uint,
311                     param_id: ast::NodeId) {
312         let inf_index = InferredIndex(self.inferred_infos.len());
313         let term = self.arena.alloc(|| InferredTerm(inf_index));
314         self.inferred_infos.push(InferredInfo { item_id: item_id,
315                                                 kind: kind,
316                                                 space: space,
317                                                 index: index,
318                                                 param_id: param_id,
319                                                 term: term });
320         let newly_added = self.inferred_map.insert(param_id, inf_index).is_none();
321         assert!(newly_added);
322
323         debug!("add_inferred(item_id={}, \
324                 kind={}, \
325                 index={}, \
326                 param_id={},
327                 inf_index={})",
328                 item_id, kind, index, param_id, inf_index);
329     }
330
331     fn num_inferred(&self) -> uint {
332         self.inferred_infos.len()
333     }
334 }
335
336 impl<'a, 'tcx, 'v> Visitor<'v> for TermsContext<'a, 'tcx> {
337     fn visit_item(&mut self, item: &ast::Item) {
338         debug!("add_inferreds for item {}", item.repr(self.tcx));
339
340         let inferreds_on_entry = self.num_inferred();
341
342         // NB: In the code below for writing the results back into the
343         // tcx, we rely on the fact that all inferreds for a particular
344         // item are assigned continuous indices.
345         match item.node {
346             ast::ItemTrait(..) => {
347                 self.add_inferred(item.id, TypeParam, SelfSpace, 0, item.id);
348             }
349             _ => { }
350         }
351
352         match item.node {
353             ast::ItemEnum(_, ref generics) |
354             ast::ItemStruct(_, ref generics) |
355             ast::ItemTrait(ref generics, _, _, _) => {
356                 for (i, p) in generics.lifetimes.iter().enumerate() {
357                     let id = p.lifetime.id;
358                     self.add_inferred(item.id, RegionParam, TypeSpace, i, id);
359                 }
360                 for (i, p) in generics.ty_params.iter().enumerate() {
361                     self.add_inferred(item.id, TypeParam, TypeSpace, i, p.id);
362                 }
363
364                 // If this item has no type or lifetime parameters,
365                 // then there are no variances to infer, so just
366                 // insert an empty entry into the variance map.
367                 // Arguably we could just leave the map empty in this
368                 // case but it seems cleaner to be able to distinguish
369                 // "invalid item id" from "item id with no
370                 // parameters".
371                 if self.num_inferred() == inferreds_on_entry {
372                     let newly_added = self.tcx.item_variance_map.borrow_mut().insert(
373                         ast_util::local_def(item.id),
374                         self.empty_variances.clone()).is_none();
375                     assert!(newly_added);
376                 }
377
378                 visit::walk_item(self, item);
379             }
380
381             ast::ItemImpl(..) |
382             ast::ItemStatic(..) |
383             ast::ItemConst(..) |
384             ast::ItemFn(..) |
385             ast::ItemMod(..) |
386             ast::ItemForeignMod(..) |
387             ast::ItemTy(..) |
388             ast::ItemMac(..) => {
389                 visit::walk_item(self, item);
390             }
391         }
392     }
393 }
394
395 // Constraint construction and representation
396 //
397 // The second pass over the AST determines the set of constraints.
398 // We walk the set of items and, for each member, generate new constraints.
399
400 struct ConstraintContext<'a, 'tcx: 'a> {
401     terms_cx: TermsContext<'a, 'tcx>,
402
403     // These are the def-id of the std::kinds::marker::InvariantType,
404     // std::kinds::marker::InvariantLifetime, and so on. The arrays
405     // are indexed by the `ParamKind` (type, lifetime, self). Note
406     // that there are no marker types for self, so the entries for
407     // self are always None.
408     invariant_lang_items: [Option<ast::DefId>, ..2],
409     covariant_lang_items: [Option<ast::DefId>, ..2],
410     contravariant_lang_items: [Option<ast::DefId>, ..2],
411     unsafe_lang_item: Option<ast::DefId>,
412
413     // These are pointers to common `ConstantTerm` instances
414     covariant: VarianceTermPtr<'a>,
415     contravariant: VarianceTermPtr<'a>,
416     invariant: VarianceTermPtr<'a>,
417     bivariant: VarianceTermPtr<'a>,
418
419     constraints: Vec<Constraint<'a>> ,
420 }
421
422 /// Declares that the variable `decl_id` appears in a location with
423 /// variance `variance`.
424 struct Constraint<'a> {
425     inferred: InferredIndex,
426     variance: &'a VarianceTerm<'a>,
427 }
428
429 fn add_constraints_from_crate<'a, 'tcx>(terms_cx: TermsContext<'a, 'tcx>,
430                                         krate: &ast::Crate)
431                                         -> ConstraintContext<'a, 'tcx> {
432     let mut invariant_lang_items = [None, ..2];
433     let mut covariant_lang_items = [None, ..2];
434     let mut contravariant_lang_items = [None, ..2];
435
436     covariant_lang_items[TypeParam as uint] =
437         terms_cx.tcx.lang_items.covariant_type();
438     covariant_lang_items[RegionParam as uint] =
439         terms_cx.tcx.lang_items.covariant_lifetime();
440
441     contravariant_lang_items[TypeParam as uint] =
442         terms_cx.tcx.lang_items.contravariant_type();
443     contravariant_lang_items[RegionParam as uint] =
444         terms_cx.tcx.lang_items.contravariant_lifetime();
445
446     invariant_lang_items[TypeParam as uint] =
447         terms_cx.tcx.lang_items.invariant_type();
448     invariant_lang_items[RegionParam as uint] =
449         terms_cx.tcx.lang_items.invariant_lifetime();
450
451     let unsafe_lang_item = terms_cx.tcx.lang_items.unsafe_type();
452
453     let covariant = terms_cx.arena.alloc(|| ConstantTerm(ty::Covariant));
454     let contravariant = terms_cx.arena.alloc(|| ConstantTerm(ty::Contravariant));
455     let invariant = terms_cx.arena.alloc(|| ConstantTerm(ty::Invariant));
456     let bivariant = terms_cx.arena.alloc(|| ConstantTerm(ty::Bivariant));
457     let mut constraint_cx = ConstraintContext {
458         terms_cx: terms_cx,
459
460         invariant_lang_items: invariant_lang_items,
461         covariant_lang_items: covariant_lang_items,
462         contravariant_lang_items: contravariant_lang_items,
463         unsafe_lang_item: unsafe_lang_item,
464
465         covariant: covariant,
466         contravariant: contravariant,
467         invariant: invariant,
468         bivariant: bivariant,
469         constraints: Vec::new(),
470     };
471     visit::walk_crate(&mut constraint_cx, krate);
472     constraint_cx
473 }
474
475 impl<'a, 'tcx, 'v> Visitor<'v> for ConstraintContext<'a, 'tcx> {
476     fn visit_item(&mut self, item: &ast::Item) {
477         let did = ast_util::local_def(item.id);
478         let tcx = self.terms_cx.tcx;
479
480         match item.node {
481             ast::ItemEnum(ref enum_definition, _) => {
482                 // Hack: If we directly call `ty::enum_variants`, it
483                 // annoyingly takes it upon itself to run off and
484                 // evaluate the discriminants eagerly (*grumpy* that's
485                 // not the typical pattern). This results in double
486                 // error messages because typeck goes off and does
487                 // this at a later time. All we really care about is
488                 // the types of the variant arguments, so we just call
489                 // `ty::VariantInfo::from_ast_variant()` ourselves
490                 // here, mainly so as to mask the differences between
491                 // struct-like enums and so forth.
492                 for ast_variant in enum_definition.variants.iter() {
493                     let variant =
494                         ty::VariantInfo::from_ast_variant(tcx,
495                                                           &**ast_variant,
496                                                           /*discriminant*/ 0);
497                     for arg_ty in variant.args.iter() {
498                         self.add_constraints_from_ty(*arg_ty, self.covariant);
499                     }
500                 }
501             }
502
503             ast::ItemStruct(..) => {
504                 let struct_fields = ty::lookup_struct_fields(tcx, did);
505                 for field_info in struct_fields.iter() {
506                     assert_eq!(field_info.id.krate, ast::LOCAL_CRATE);
507                     let field_ty = ty::node_id_to_type(tcx, field_info.id.node);
508                     self.add_constraints_from_ty(field_ty, self.covariant);
509                 }
510             }
511
512             ast::ItemTrait(..) => {
513                 let trait_items = ty::trait_items(tcx, did);
514                 for trait_item in trait_items.iter() {
515                     match *trait_item {
516                         ty::MethodTraitItem(ref method) => {
517                             self.add_constraints_from_sig(&method.fty.sig,
518                                                           self.covariant);
519                         }
520                         ty::TypeTraitItem(_) => {}
521                     }
522                 }
523             }
524
525             ast::ItemStatic(..) |
526             ast::ItemConst(..) |
527             ast::ItemFn(..) |
528             ast::ItemMod(..) |
529             ast::ItemForeignMod(..) |
530             ast::ItemTy(..) |
531             ast::ItemImpl(..) |
532             ast::ItemMac(..) => {
533                 visit::walk_item(self, item);
534             }
535         }
536     }
537 }
538
539 /// Is `param_id` a lifetime according to `map`?
540 fn is_lifetime(map: &ast_map::Map, param_id: ast::NodeId) -> bool {
541     match map.find(param_id) {
542         Some(ast_map::NodeLifetime(..)) => true, _ => false
543     }
544 }
545
546 impl<'a, 'tcx> ConstraintContext<'a, 'tcx> {
547     fn tcx(&self) -> &'a ty::ctxt<'tcx> {
548         self.terms_cx.tcx
549     }
550
551     fn inferred_index(&self, param_id: ast::NodeId) -> InferredIndex {
552         match self.terms_cx.inferred_map.get(&param_id) {
553             Some(&index) => index,
554             None => {
555                 self.tcx().sess.bug(format!(
556                         "no inferred index entry for {}",
557                         self.tcx().map.node_to_string(param_id)).as_slice());
558             }
559         }
560     }
561
562     fn find_binding_for_lifetime(&self, param_id: ast::NodeId) -> ast::NodeId {
563         let tcx = self.terms_cx.tcx;
564         assert!(is_lifetime(&tcx.map, param_id));
565         match tcx.named_region_map.get(&param_id) {
566             Some(&rl::DefEarlyBoundRegion(_, _, lifetime_decl_id))
567                 => lifetime_decl_id,
568             Some(_) => panic!("should not encounter non early-bound cases"),
569
570             // The lookup should only fail when `param_id` is
571             // itself a lifetime binding: use it as the decl_id.
572             None    => param_id,
573         }
574
575     }
576
577     /// Is `param_id` a type parameter for which we infer variance?
578     fn is_to_be_inferred(&self, param_id: ast::NodeId) -> bool {
579         let result = self.terms_cx.inferred_map.contains_key(&param_id);
580
581         // To safe-guard against invalid inferred_map constructions,
582         // double-check if variance is inferred at some use of a type
583         // parameter (by inspecting parent of its binding declaration
584         // to see if it is introduced by a type or by a fn/impl).
585
586         let check_result = |this:&ConstraintContext| -> bool {
587             let tcx = this.terms_cx.tcx;
588             let decl_id = this.find_binding_for_lifetime(param_id);
589             // Currently only called on lifetimes; double-checking that.
590             assert!(is_lifetime(&tcx.map, param_id));
591             let parent_id = tcx.map.get_parent(decl_id);
592             let parent = tcx.map.find(parent_id).unwrap_or_else(
593                 || panic!("tcx.map missing entry for id: {}", parent_id));
594
595             let is_inferred;
596             macro_rules! cannot_happen { () => { {
597                 panic!("invalid parent: {} for {}",
598                       tcx.map.node_to_string(parent_id),
599                       tcx.map.node_to_string(param_id));
600             } } }
601
602             match parent {
603                 ast_map::NodeItem(p) => {
604                     match p.node {
605                         ast::ItemTy(..) |
606                         ast::ItemEnum(..) |
607                         ast::ItemStruct(..) |
608                         ast::ItemTrait(..)   => is_inferred = true,
609                         ast::ItemFn(..)      => is_inferred = false,
610                         _                    => cannot_happen!(),
611                     }
612                 }
613                 ast_map::NodeTraitItem(..)   => is_inferred = false,
614                 ast_map::NodeImplItem(..)    => is_inferred = false,
615                 _                            => cannot_happen!(),
616             }
617
618             return is_inferred;
619         };
620
621         assert_eq!(result, check_result(self));
622
623         return result;
624     }
625
626     /// Returns a variance term representing the declared variance of the type/region parameter
627     /// with the given id.
628     fn declared_variance(&self,
629                          param_def_id: ast::DefId,
630                          item_def_id: ast::DefId,
631                          kind: ParamKind,
632                          space: ParamSpace,
633                          index: uint)
634                          -> VarianceTermPtr<'a> {
635         assert_eq!(param_def_id.krate, item_def_id.krate);
636
637         if self.invariant_lang_items[kind as uint] == Some(item_def_id) {
638             self.invariant
639         } else if self.covariant_lang_items[kind as uint] == Some(item_def_id) {
640             self.covariant
641         } else if self.contravariant_lang_items[kind as uint] == Some(item_def_id) {
642             self.contravariant
643         } else if kind == TypeParam && Some(item_def_id) == self.unsafe_lang_item {
644             self.invariant
645         } else if param_def_id.krate == ast::LOCAL_CRATE {
646             // Parameter on an item defined within current crate:
647             // variance not yet inferred, so return a symbolic
648             // variance.
649             let InferredIndex(index) = self.inferred_index(param_def_id.node);
650             self.terms_cx.inferred_infos[index].term
651         } else {
652             // Parameter on an item defined within another crate:
653             // variance already inferred, just look it up.
654             let variances = ty::item_variances(self.tcx(), item_def_id);
655             let variance = match kind {
656                 TypeParam => *variances.types.get(space, index),
657                 RegionParam => *variances.regions.get(space, index),
658             };
659             self.constant_term(variance)
660         }
661     }
662
663     fn add_constraint(&mut self,
664                       InferredIndex(index): InferredIndex,
665                       variance: VarianceTermPtr<'a>) {
666         debug!("add_constraint(index={}, variance={})",
667                 index, variance.to_string());
668         self.constraints.push(Constraint { inferred: InferredIndex(index),
669                                            variance: variance });
670     }
671
672     fn contravariant(&mut self,
673                      variance: VarianceTermPtr<'a>)
674                      -> VarianceTermPtr<'a> {
675         self.xform(variance, self.contravariant)
676     }
677
678     fn invariant(&mut self,
679                  variance: VarianceTermPtr<'a>)
680                  -> VarianceTermPtr<'a> {
681         self.xform(variance, self.invariant)
682     }
683
684     fn constant_term(&self, v: ty::Variance) -> VarianceTermPtr<'a> {
685         match v {
686             ty::Covariant => self.covariant,
687             ty::Invariant => self.invariant,
688             ty::Contravariant => self.contravariant,
689             ty::Bivariant => self.bivariant,
690         }
691     }
692
693     fn xform(&mut self,
694              v1: VarianceTermPtr<'a>,
695              v2: VarianceTermPtr<'a>)
696              -> VarianceTermPtr<'a> {
697         match (*v1, *v2) {
698             (_, ConstantTerm(ty::Covariant)) => {
699                 // Applying a "covariant" transform is always a no-op
700                 v1
701             }
702
703             (ConstantTerm(c1), ConstantTerm(c2)) => {
704                 self.constant_term(c1.xform(c2))
705             }
706
707             _ => {
708                 &*self.terms_cx.arena.alloc(|| TransformTerm(v1, v2))
709             }
710         }
711     }
712
713     /// Adds constraints appropriate for an instance of `ty` appearing
714     /// in a context with ambient variance `variance`
715     fn add_constraints_from_ty(&mut self,
716                                ty: Ty<'tcx>,
717                                variance: VarianceTermPtr<'a>) {
718         debug!("add_constraints_from_ty(ty={})", ty.repr(self.tcx()));
719
720         match ty.sty {
721             ty::ty_bool |
722             ty::ty_char | ty::ty_int(_) | ty::ty_uint(_) |
723             ty::ty_float(_) | ty::ty_str => {
724                 /* leaf type -- noop */
725             }
726
727             ty::ty_unboxed_closure(..) => {
728                 self.tcx().sess.bug("Unexpected unboxed closure type in variance computation");
729             }
730
731             ty::ty_rptr(region, ref mt) => {
732                 let contra = self.contravariant(variance);
733                 self.add_constraints_from_region(region, contra);
734                 self.add_constraints_from_mt(mt, variance);
735             }
736
737             ty::ty_uniq(typ) | ty::ty_vec(typ, _) | ty::ty_open(typ) => {
738                 self.add_constraints_from_ty(typ, variance);
739             }
740
741             ty::ty_ptr(ref mt) => {
742                 self.add_constraints_from_mt(mt, variance);
743             }
744
745             ty::ty_tup(ref subtys) => {
746                 for &subty in subtys.iter() {
747                     self.add_constraints_from_ty(subty, variance);
748                 }
749             }
750
751             ty::ty_enum(def_id, ref substs) |
752             ty::ty_struct(def_id, ref substs) => {
753                 let item_type = ty::lookup_item_type(self.tcx(), def_id);
754                 let generics = &item_type.generics;
755
756                 // All type parameters on enums and structs should be
757                 // in the TypeSpace.
758                 assert!(generics.types.is_empty_in(subst::SelfSpace));
759                 assert!(generics.types.is_empty_in(subst::FnSpace));
760                 assert!(generics.regions.is_empty_in(subst::SelfSpace));
761                 assert!(generics.regions.is_empty_in(subst::FnSpace));
762
763                 self.add_constraints_from_substs(
764                     def_id,
765                     generics.types.get_slice(subst::TypeSpace),
766                     generics.regions.get_slice(subst::TypeSpace),
767                     substs,
768                     variance);
769             }
770
771             ty::ty_trait(box ty::TyTrait { ref principal, bounds }) => {
772                 let trait_def = ty::lookup_trait_def(self.tcx(), principal.def_id);
773                 let generics = &trait_def.generics;
774
775                 // Traits DO have a Self type parameter, but it is
776                 // erased from object types.
777                 assert!(!generics.types.is_empty_in(subst::SelfSpace) &&
778                         principal.substs.types.is_empty_in(subst::SelfSpace));
779
780                 // Traits never declare region parameters in the self
781                 // space.
782                 assert!(generics.regions.is_empty_in(subst::SelfSpace));
783
784                 // Traits never declare type/region parameters in the
785                 // fn space.
786                 assert!(generics.types.is_empty_in(subst::FnSpace));
787                 assert!(generics.regions.is_empty_in(subst::FnSpace));
788
789                 // The type `Foo<T+'a>` is contravariant w/r/t `'a`:
790                 let contra = self.contravariant(variance);
791                 self.add_constraints_from_region(bounds.region_bound, contra);
792
793                 self.add_constraints_from_substs(
794                     principal.def_id,
795                     generics.types.get_slice(subst::TypeSpace),
796                     generics.regions.get_slice(subst::TypeSpace),
797                     &principal.substs,
798                     variance);
799             }
800
801             ty::ty_param(ty::ParamTy { ref def_id, .. }) => {
802                 assert_eq!(def_id.krate, ast::LOCAL_CRATE);
803                 match self.terms_cx.inferred_map.get(&def_id.node) {
804                     Some(&index) => {
805                         self.add_constraint(index, variance);
806                     }
807                     None => {
808                         // We do not infer variance for type parameters
809                         // declared on methods. They will not be present
810                         // in the inferred_map.
811                     }
812                 }
813             }
814
815             ty::ty_bare_fn(ty::BareFnTy { ref sig, .. }) |
816             ty::ty_closure(box ty::ClosureTy {
817                     ref sig,
818                     store: ty::UniqTraitStore,
819                     ..
820                 }) => {
821                 self.add_constraints_from_sig(sig, variance);
822             }
823
824             ty::ty_closure(box ty::ClosureTy { ref sig,
825                     store: ty::RegionTraitStore(region, _), .. }) => {
826                 let contra = self.contravariant(variance);
827                 self.add_constraints_from_region(region, contra);
828                 self.add_constraints_from_sig(sig, variance);
829             }
830
831             ty::ty_infer(..) | ty::ty_err => {
832                 self.tcx().sess.bug(
833                     format!("unexpected type encountered in \
834                             variance inference: {}",
835                             ty.repr(self.tcx())).as_slice());
836             }
837         }
838     }
839
840
841     /// Adds constraints appropriate for a nominal type (enum, struct,
842     /// object, etc) appearing in a context with ambient variance `variance`
843     fn add_constraints_from_substs(&mut self,
844                                    def_id: ast::DefId,
845                                    type_param_defs: &[ty::TypeParameterDef<'tcx>],
846                                    region_param_defs: &[ty::RegionParameterDef],
847                                    substs: &subst::Substs<'tcx>,
848                                    variance: VarianceTermPtr<'a>) {
849         debug!("add_constraints_from_substs(def_id={})", def_id);
850
851         for p in type_param_defs.iter() {
852             let variance_decl =
853                 self.declared_variance(p.def_id, def_id, TypeParam,
854                                        p.space, p.index);
855             let variance_i = self.xform(variance, variance_decl);
856             let substs_ty = *substs.types.get(p.space, p.index);
857             self.add_constraints_from_ty(substs_ty, variance_i);
858         }
859
860         for p in region_param_defs.iter() {
861             let variance_decl =
862                 self.declared_variance(p.def_id, def_id,
863                                        RegionParam, p.space, p.index);
864             let variance_i = self.xform(variance, variance_decl);
865             let substs_r = *substs.regions().get(p.space, p.index);
866             self.add_constraints_from_region(substs_r, variance_i);
867         }
868     }
869
870     /// Adds constraints appropriate for a function with signature
871     /// `sig` appearing in a context with ambient variance `variance`
872     fn add_constraints_from_sig(&mut self,
873                                 sig: &ty::FnSig<'tcx>,
874                                 variance: VarianceTermPtr<'a>) {
875         let contra = self.contravariant(variance);
876         for &input in sig.inputs.iter() {
877             self.add_constraints_from_ty(input, contra);
878         }
879         if let ty::FnConverging(result_type) = sig.output {
880             self.add_constraints_from_ty(result_type, variance);
881         }
882     }
883
884     /// Adds constraints appropriate for a region appearing in a
885     /// context with ambient variance `variance`
886     fn add_constraints_from_region(&mut self,
887                                    region: ty::Region,
888                                    variance: VarianceTermPtr<'a>) {
889         match region {
890             ty::ReEarlyBound(param_id, _, _, _) => {
891                 if self.is_to_be_inferred(param_id) {
892                     let index = self.inferred_index(param_id);
893                     self.add_constraint(index, variance);
894                 }
895             }
896
897             ty::ReStatic => { }
898
899             ty::ReLateBound(..) => {
900                 // We do not infer variance for region parameters on
901                 // methods or in fn types.
902             }
903
904             ty::ReFree(..) | ty::ReScope(..) | ty::ReInfer(..) |
905             ty::ReEmpty => {
906                 // We don't expect to see anything but 'static or bound
907                 // regions when visiting member types or method types.
908                 self.tcx()
909                     .sess
910                     .bug(format!("unexpected region encountered in variance \
911                                   inference: {}",
912                                  region.repr(self.tcx())).as_slice());
913             }
914         }
915     }
916
917     /// Adds constraints appropriate for a mutability-type pair
918     /// appearing in a context with ambient variance `variance`
919     fn add_constraints_from_mt(&mut self,
920                                mt: &ty::mt<'tcx>,
921                                variance: VarianceTermPtr<'a>) {
922         match mt.mutbl {
923             ast::MutMutable => {
924                 let invar = self.invariant(variance);
925                 self.add_constraints_from_ty(mt.ty, invar);
926             }
927
928             ast::MutImmutable => {
929                 self.add_constraints_from_ty(mt.ty, variance);
930             }
931         }
932     }
933 }
934
935 // Constraint solving
936 //
937 // The final phase iterates over the constraints, refining the variance
938 // for each inferred until a fixed point is reached. This will be the
939 // optimal solution to the constraints. The final variance for each
940 // inferred is then written into the `variance_map` in the tcx.
941
942 struct SolveContext<'a, 'tcx: 'a> {
943     terms_cx: TermsContext<'a, 'tcx>,
944     constraints: Vec<Constraint<'a>> ,
945
946     // Maps from an InferredIndex to the inferred value for that variable.
947     solutions: Vec<ty::Variance> }
948
949 fn solve_constraints(constraints_cx: ConstraintContext) {
950     let ConstraintContext { terms_cx, constraints, .. } = constraints_cx;
951     let solutions = Vec::from_elem(terms_cx.num_inferred(), ty::Bivariant);
952     let mut solutions_cx = SolveContext {
953         terms_cx: terms_cx,
954         constraints: constraints,
955         solutions: solutions
956     };
957     solutions_cx.solve();
958     solutions_cx.write();
959 }
960
961 impl<'a, 'tcx> SolveContext<'a, 'tcx> {
962     fn solve(&mut self) {
963         // Propagate constraints until a fixed point is reached.  Note
964         // that the maximum number of iterations is 2C where C is the
965         // number of constraints (each variable can change values at most
966         // twice). Since number of constraints is linear in size of the
967         // input, so is the inference process.
968         let mut changed = true;
969         while changed {
970             changed = false;
971
972             for constraint in self.constraints.iter() {
973                 let Constraint { inferred, variance: term } = *constraint;
974                 let InferredIndex(inferred) = inferred;
975                 let variance = self.evaluate(term);
976                 let old_value = self.solutions[inferred];
977                 let new_value = glb(variance, old_value);
978                 if old_value != new_value {
979                     debug!("Updating inferred {} (node {}) \
980                             from {} to {} due to {}",
981                             inferred,
982                             self.terms_cx
983                                 .inferred_infos[inferred]
984                                 .param_id,
985                             old_value,
986                             new_value,
987                             term.to_string());
988
989                     self.solutions[inferred] = new_value;
990                     changed = true;
991                 }
992             }
993         }
994     }
995
996     fn write(&self) {
997         // Collect all the variances for a particular item and stick
998         // them into the variance map. We rely on the fact that we
999         // generate all the inferreds for a particular item
1000         // consecutively (that is, we collect solutions for an item
1001         // until we see a new item id, and we assume (1) the solutions
1002         // are in the same order as the type parameters were declared
1003         // and (2) all solutions or a given item appear before a new
1004         // item id).
1005
1006         let tcx = self.terms_cx.tcx;
1007         let solutions = &self.solutions;
1008         let inferred_infos = &self.terms_cx.inferred_infos;
1009         let mut index = 0;
1010         let num_inferred = self.terms_cx.num_inferred();
1011         while index < num_inferred {
1012             let item_id = inferred_infos[index].item_id;
1013             let mut types = VecPerParamSpace::empty();
1014             let mut regions = VecPerParamSpace::empty();
1015
1016             while index < num_inferred &&
1017                   inferred_infos[index].item_id == item_id {
1018                 let info = inferred_infos[index];
1019                 let variance = solutions[index];
1020                 debug!("Index {} Info {} / {} / {} Variance {}",
1021                        index, info.index, info.kind, info.space, variance);
1022                 match info.kind {
1023                     TypeParam => {
1024                         types.push(info.space, variance);
1025                     }
1026                     RegionParam => {
1027                         regions.push(info.space, variance);
1028                     }
1029                 }
1030                 index += 1;
1031             }
1032
1033             let item_variances = ty::ItemVariances {
1034                 types: types,
1035                 regions: regions
1036             };
1037             debug!("item_id={} item_variances={}",
1038                     item_id,
1039                     item_variances.repr(tcx));
1040
1041             let item_def_id = ast_util::local_def(item_id);
1042
1043             // For unit testing: check for a special "rustc_variance"
1044             // attribute and report an error with various results if found.
1045             if ty::has_attr(tcx, item_def_id, "rustc_variance") {
1046                 let found = item_variances.repr(tcx);
1047                 tcx.sess.span_err(tcx.map.span(item_id), found.as_slice());
1048             }
1049
1050             let newly_added = tcx.item_variance_map.borrow_mut()
1051                                  .insert(item_def_id, Rc::new(item_variances)).is_none();
1052             assert!(newly_added);
1053         }
1054     }
1055
1056     fn evaluate(&self, term: VarianceTermPtr<'a>) -> ty::Variance {
1057         match *term {
1058             ConstantTerm(v) => {
1059                 v
1060             }
1061
1062             TransformTerm(t1, t2) => {
1063                 let v1 = self.evaluate(t1);
1064                 let v2 = self.evaluate(t2);
1065                 v1.xform(v2)
1066             }
1067
1068             InferredTerm(InferredIndex(index)) => {
1069                 self.solutions[index]
1070             }
1071         }
1072     }
1073 }
1074
1075 // Miscellany transformations on variance
1076
1077 trait Xform {
1078     fn xform(self, v: Self) -> Self;
1079 }
1080
1081 impl Xform for ty::Variance {
1082     fn xform(self, v: ty::Variance) -> ty::Variance {
1083         // "Variance transformation", Figure 1 of The Paper
1084         match (self, v) {
1085             // Figure 1, column 1.
1086             (ty::Covariant, ty::Covariant) => ty::Covariant,
1087             (ty::Covariant, ty::Contravariant) => ty::Contravariant,
1088             (ty::Covariant, ty::Invariant) => ty::Invariant,
1089             (ty::Covariant, ty::Bivariant) => ty::Bivariant,
1090
1091             // Figure 1, column 2.
1092             (ty::Contravariant, ty::Covariant) => ty::Contravariant,
1093             (ty::Contravariant, ty::Contravariant) => ty::Covariant,
1094             (ty::Contravariant, ty::Invariant) => ty::Invariant,
1095             (ty::Contravariant, ty::Bivariant) => ty::Bivariant,
1096
1097             // Figure 1, column 3.
1098             (ty::Invariant, _) => ty::Invariant,
1099
1100             // Figure 1, column 4.
1101             (ty::Bivariant, _) => ty::Bivariant,
1102         }
1103     }
1104 }
1105
1106 fn glb(v1: ty::Variance, v2: ty::Variance) -> ty::Variance {
1107     // Greatest lower bound of the variance lattice as
1108     // defined in The Paper:
1109     //
1110     //       *
1111     //    -     +
1112     //       o
1113     match (v1, v2) {
1114         (ty::Invariant, _) | (_, ty::Invariant) => ty::Invariant,
1115
1116         (ty::Covariant, ty::Contravariant) => ty::Invariant,
1117         (ty::Contravariant, ty::Covariant) => ty::Invariant,
1118
1119         (ty::Covariant, ty::Covariant) => ty::Covariant,
1120
1121         (ty::Contravariant, ty::Contravariant) => ty::Contravariant,
1122
1123         (x, ty::Bivariant) | (ty::Bivariant, x) => x,
1124     }
1125 }