]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/ty.rs
483f2873166c6cedb939f6dee4b9a4e4e4512551
[rust.git] / src / librustc / middle / ty.rs
1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 // FIXME: (@jroesch) @eddyb should remove this when he renames ctxt
12 #![allow(non_camel_case_types)]
13
14 pub use self::InferTy::*;
15 pub use self::ImplOrTraitItemId::*;
16 pub use self::ClosureKind::*;
17 pub use self::Variance::*;
18 pub use self::AutoAdjustment::*;
19 pub use self::Representability::*;
20 pub use self::AutoRef::*;
21 pub use self::DtorKind::*;
22 pub use self::ExplicitSelfCategory::*;
23 pub use self::FnOutput::*;
24 pub use self::Region::*;
25 pub use self::ImplOrTraitItemContainer::*;
26 pub use self::BorrowKind::*;
27 pub use self::ImplOrTraitItem::*;
28 pub use self::BoundRegion::*;
29 pub use self::TypeVariants::*;
30 pub use self::IntVarValue::*;
31 pub use self::CopyImplementationError::*;
32
33 pub use self::BuiltinBound::Send as BoundSend;
34 pub use self::BuiltinBound::Sized as BoundSized;
35 pub use self::BuiltinBound::Copy as BoundCopy;
36 pub use self::BuiltinBound::Sync as BoundSync;
37
38 use ast_map::{self, LinkedPath};
39 use back::svh::Svh;
40 use session::Session;
41 use lint;
42 use metadata::csearch;
43 use middle;
44 use middle::cast;
45 use middle::check_const;
46 use middle::const_eval::{self, ConstVal, ErrKind};
47 use middle::const_eval::EvalHint::UncheckedExprHint;
48 use middle::def::{self, DefMap, ExportMap};
49 use middle::def_id::{DefId, LOCAL_CRATE};
50 use middle::fast_reject;
51 use middle::free_region::FreeRegionMap;
52 use middle::lang_items::{FnTraitLangItem, FnMutTraitLangItem, FnOnceTraitLangItem};
53 use middle::region;
54 use middle::resolve_lifetime;
55 use middle::infer;
56 use middle::infer::type_variable;
57 use middle::pat_util;
58 use middle::region::RegionMaps;
59 use middle::stability;
60 use middle::subst::{self, ParamSpace, Subst, Substs, VecPerParamSpace};
61 use middle::traits;
62 use middle::ty;
63 use middle::ty_fold::{self, TypeFoldable, TypeFolder};
64 use middle::ty_walk::{self, TypeWalker};
65 use util::common::{memoized, ErrorReported};
66 use util::nodemap::{NodeMap, NodeSet, DefIdMap, DefIdSet};
67 use util::nodemap::FnvHashMap;
68 use util::num::ToPrimitive;
69
70 use arena::TypedArena;
71 use std::borrow::{Borrow, Cow};
72 use std::cell::{Cell, RefCell, Ref};
73 use std::cmp;
74 use std::fmt;
75 use std::hash::{Hash, SipHasher, Hasher};
76 use std::iter;
77 use std::marker::PhantomData;
78 use std::mem;
79 use std::ops;
80 use std::rc::Rc;
81 use std::slice;
82 use std::vec::IntoIter;
83 use collections::enum_set::{self, EnumSet, CLike};
84 use core::nonzero::NonZero;
85 use std::collections::{HashMap, HashSet};
86 use rustc_data_structures::ivar;
87 use syntax::abi;
88 use syntax::ast::{CrateNum, ItemImpl, ItemTrait};
89 use syntax::ast::{MutImmutable, MutMutable, Name, NodeId, Visibility};
90 use syntax::attr::{self, AttrMetaMethods, SignedInt, UnsignedInt};
91 use syntax::codemap::Span;
92 use syntax::parse::token::{InternedString, special_idents};
93 use syntax::ast;
94
95 pub type Disr = u64;
96
97 pub const INITIAL_DISCRIMINANT_VALUE: Disr = 0;
98
99 // Data types
100
101 /// The complete set of all analyses described in this module. This is
102 /// produced by the driver and fed to trans and later passes.
103 pub struct CrateAnalysis {
104     pub export_map: ExportMap,
105     pub exported_items: middle::privacy::ExportedItems,
106     pub public_items: middle::privacy::PublicItems,
107     pub reachable: NodeSet,
108     pub name: String,
109     pub glob_map: Option<GlobMap>,
110 }
111
112 #[derive(Copy, Clone)]
113 pub enum DtorKind {
114     NoDtor,
115     TraitDtor(bool)
116 }
117
118 impl DtorKind {
119     pub fn is_present(&self) -> bool {
120         match *self {
121             TraitDtor(..) => true,
122             _ => false
123         }
124     }
125
126     pub fn has_drop_flag(&self) -> bool {
127         match self {
128             &NoDtor => false,
129             &TraitDtor(flag) => flag
130         }
131     }
132 }
133
134 pub trait IntTypeExt {
135     fn to_ty<'tcx>(&self, cx: &ctxt<'tcx>) -> Ty<'tcx>;
136     fn i64_to_disr(&self, val: i64) -> Option<Disr>;
137     fn u64_to_disr(&self, val: u64) -> Option<Disr>;
138     fn disr_incr(&self, val: Disr) -> Option<Disr>;
139     fn disr_string(&self, val: Disr) -> String;
140     fn disr_wrap_incr(&self, val: Option<Disr>) -> Disr;
141 }
142
143 impl IntTypeExt for attr::IntType {
144     fn to_ty<'tcx>(&self, cx: &ctxt<'tcx>) -> Ty<'tcx> {
145         match *self {
146             SignedInt(ast::TyI8)      => cx.types.i8,
147             SignedInt(ast::TyI16)     => cx.types.i16,
148             SignedInt(ast::TyI32)     => cx.types.i32,
149             SignedInt(ast::TyI64)     => cx.types.i64,
150             SignedInt(ast::TyIs)   => cx.types.isize,
151             UnsignedInt(ast::TyU8)    => cx.types.u8,
152             UnsignedInt(ast::TyU16)   => cx.types.u16,
153             UnsignedInt(ast::TyU32)   => cx.types.u32,
154             UnsignedInt(ast::TyU64)   => cx.types.u64,
155             UnsignedInt(ast::TyUs) => cx.types.usize,
156         }
157     }
158
159     fn i64_to_disr(&self, val: i64) -> Option<Disr> {
160         match *self {
161             SignedInt(ast::TyI8)    => val.to_i8()  .map(|v| v as Disr),
162             SignedInt(ast::TyI16)   => val.to_i16() .map(|v| v as Disr),
163             SignedInt(ast::TyI32)   => val.to_i32() .map(|v| v as Disr),
164             SignedInt(ast::TyI64)   => val.to_i64() .map(|v| v as Disr),
165             UnsignedInt(ast::TyU8)  => val.to_u8()  .map(|v| v as Disr),
166             UnsignedInt(ast::TyU16) => val.to_u16() .map(|v| v as Disr),
167             UnsignedInt(ast::TyU32) => val.to_u32() .map(|v| v as Disr),
168             UnsignedInt(ast::TyU64) => val.to_u64() .map(|v| v as Disr),
169
170             UnsignedInt(ast::TyUs) |
171             SignedInt(ast::TyIs) => unreachable!(),
172         }
173     }
174
175     fn u64_to_disr(&self, val: u64) -> Option<Disr> {
176         match *self {
177             SignedInt(ast::TyI8)    => val.to_i8()  .map(|v| v as Disr),
178             SignedInt(ast::TyI16)   => val.to_i16() .map(|v| v as Disr),
179             SignedInt(ast::TyI32)   => val.to_i32() .map(|v| v as Disr),
180             SignedInt(ast::TyI64)   => val.to_i64() .map(|v| v as Disr),
181             UnsignedInt(ast::TyU8)  => val.to_u8()  .map(|v| v as Disr),
182             UnsignedInt(ast::TyU16) => val.to_u16() .map(|v| v as Disr),
183             UnsignedInt(ast::TyU32) => val.to_u32() .map(|v| v as Disr),
184             UnsignedInt(ast::TyU64) => val.to_u64() .map(|v| v as Disr),
185
186             UnsignedInt(ast::TyUs) |
187             SignedInt(ast::TyIs) => unreachable!(),
188         }
189     }
190
191     fn disr_incr(&self, val: Disr) -> Option<Disr> {
192         macro_rules! add1 {
193             ($e:expr) => { $e.and_then(|v|v.checked_add(1)).map(|v| v as Disr) }
194         }
195         match *self {
196             // SignedInt repr means we *want* to reinterpret the bits
197             // treating the highest bit of Disr as a sign-bit, so
198             // cast to i64 before range-checking.
199             SignedInt(ast::TyI8)    => add1!((val as i64).to_i8()),
200             SignedInt(ast::TyI16)   => add1!((val as i64).to_i16()),
201             SignedInt(ast::TyI32)   => add1!((val as i64).to_i32()),
202             SignedInt(ast::TyI64)   => add1!(Some(val as i64)),
203
204             UnsignedInt(ast::TyU8)  => add1!(val.to_u8()),
205             UnsignedInt(ast::TyU16) => add1!(val.to_u16()),
206             UnsignedInt(ast::TyU32) => add1!(val.to_u32()),
207             UnsignedInt(ast::TyU64) => add1!(Some(val)),
208
209             UnsignedInt(ast::TyUs) |
210             SignedInt(ast::TyIs) => unreachable!(),
211         }
212     }
213
214     // This returns a String because (1.) it is only used for
215     // rendering an error message and (2.) a string can represent the
216     // full range from `i64::MIN` through `u64::MAX`.
217     fn disr_string(&self, val: Disr) -> String {
218         match *self {
219             SignedInt(ast::TyI8)    => format!("{}", val as i8 ),
220             SignedInt(ast::TyI16)   => format!("{}", val as i16),
221             SignedInt(ast::TyI32)   => format!("{}", val as i32),
222             SignedInt(ast::TyI64)   => format!("{}", val as i64),
223             UnsignedInt(ast::TyU8)  => format!("{}", val as u8 ),
224             UnsignedInt(ast::TyU16) => format!("{}", val as u16),
225             UnsignedInt(ast::TyU32) => format!("{}", val as u32),
226             UnsignedInt(ast::TyU64) => format!("{}", val as u64),
227
228             UnsignedInt(ast::TyUs) |
229             SignedInt(ast::TyIs) => unreachable!(),
230         }
231     }
232
233     fn disr_wrap_incr(&self, val: Option<Disr>) -> Disr {
234         macro_rules! add1 {
235             ($e:expr) => { ($e).wrapping_add(1) as Disr }
236         }
237         let val = val.unwrap_or(ty::INITIAL_DISCRIMINANT_VALUE);
238         match *self {
239             SignedInt(ast::TyI8)    => add1!(val as i8 ),
240             SignedInt(ast::TyI16)   => add1!(val as i16),
241             SignedInt(ast::TyI32)   => add1!(val as i32),
242             SignedInt(ast::TyI64)   => add1!(val as i64),
243             UnsignedInt(ast::TyU8)  => add1!(val as u8 ),
244             UnsignedInt(ast::TyU16) => add1!(val as u16),
245             UnsignedInt(ast::TyU32) => add1!(val as u32),
246             UnsignedInt(ast::TyU64) => add1!(val as u64),
247
248             UnsignedInt(ast::TyUs) |
249             SignedInt(ast::TyIs) => unreachable!(),
250         }
251     }
252 }
253
254 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
255 pub enum ImplOrTraitItemContainer {
256     TraitContainer(DefId),
257     ImplContainer(DefId),
258 }
259
260 impl ImplOrTraitItemContainer {
261     pub fn id(&self) -> DefId {
262         match *self {
263             TraitContainer(id) => id,
264             ImplContainer(id) => id,
265         }
266     }
267 }
268
269 #[derive(Clone)]
270 pub enum ImplOrTraitItem<'tcx> {
271     ConstTraitItem(Rc<AssociatedConst<'tcx>>),
272     MethodTraitItem(Rc<Method<'tcx>>),
273     TypeTraitItem(Rc<AssociatedType<'tcx>>),
274 }
275
276 impl<'tcx> ImplOrTraitItem<'tcx> {
277     fn id(&self) -> ImplOrTraitItemId {
278         match *self {
279             ConstTraitItem(ref associated_const) => {
280                 ConstTraitItemId(associated_const.def_id)
281             }
282             MethodTraitItem(ref method) => MethodTraitItemId(method.def_id),
283             TypeTraitItem(ref associated_type) => {
284                 TypeTraitItemId(associated_type.def_id)
285             }
286         }
287     }
288
289     pub fn def_id(&self) -> DefId {
290         match *self {
291             ConstTraitItem(ref associated_const) => associated_const.def_id,
292             MethodTraitItem(ref method) => method.def_id,
293             TypeTraitItem(ref associated_type) => associated_type.def_id,
294         }
295     }
296
297     pub fn name(&self) -> ast::Name {
298         match *self {
299             ConstTraitItem(ref associated_const) => associated_const.name,
300             MethodTraitItem(ref method) => method.name,
301             TypeTraitItem(ref associated_type) => associated_type.name,
302         }
303     }
304
305     pub fn vis(&self) -> ast::Visibility {
306         match *self {
307             ConstTraitItem(ref associated_const) => associated_const.vis,
308             MethodTraitItem(ref method) => method.vis,
309             TypeTraitItem(ref associated_type) => associated_type.vis,
310         }
311     }
312
313     pub fn container(&self) -> ImplOrTraitItemContainer {
314         match *self {
315             ConstTraitItem(ref associated_const) => associated_const.container,
316             MethodTraitItem(ref method) => method.container,
317             TypeTraitItem(ref associated_type) => associated_type.container,
318         }
319     }
320
321     pub fn as_opt_method(&self) -> Option<Rc<Method<'tcx>>> {
322         match *self {
323             MethodTraitItem(ref m) => Some((*m).clone()),
324             _ => None,
325         }
326     }
327 }
328
329 #[derive(Clone, Copy, Debug)]
330 pub enum ImplOrTraitItemId {
331     ConstTraitItemId(DefId),
332     MethodTraitItemId(DefId),
333     TypeTraitItemId(DefId),
334 }
335
336 impl ImplOrTraitItemId {
337     pub fn def_id(&self) -> DefId {
338         match *self {
339             ConstTraitItemId(def_id) => def_id,
340             MethodTraitItemId(def_id) => def_id,
341             TypeTraitItemId(def_id) => def_id,
342         }
343     }
344 }
345
346 #[derive(Clone, Debug)]
347 pub struct Method<'tcx> {
348     pub name: ast::Name,
349     pub generics: Generics<'tcx>,
350     pub predicates: GenericPredicates<'tcx>,
351     pub fty: BareFnTy<'tcx>,
352     pub explicit_self: ExplicitSelfCategory,
353     pub vis: ast::Visibility,
354     pub def_id: DefId,
355     pub container: ImplOrTraitItemContainer,
356
357     // If this method is provided, we need to know where it came from
358     pub provided_source: Option<DefId>
359 }
360
361 impl<'tcx> Method<'tcx> {
362     pub fn new(name: ast::Name,
363                generics: ty::Generics<'tcx>,
364                predicates: GenericPredicates<'tcx>,
365                fty: BareFnTy<'tcx>,
366                explicit_self: ExplicitSelfCategory,
367                vis: ast::Visibility,
368                def_id: DefId,
369                container: ImplOrTraitItemContainer,
370                provided_source: Option<DefId>)
371                -> Method<'tcx> {
372        Method {
373             name: name,
374             generics: generics,
375             predicates: predicates,
376             fty: fty,
377             explicit_self: explicit_self,
378             vis: vis,
379             def_id: def_id,
380             container: container,
381             provided_source: provided_source
382         }
383     }
384
385     pub fn container_id(&self) -> DefId {
386         match self.container {
387             TraitContainer(id) => id,
388             ImplContainer(id) => id,
389         }
390     }
391 }
392
393 #[derive(Clone, Copy, Debug)]
394 pub struct AssociatedConst<'tcx> {
395     pub name: ast::Name,
396     pub ty: Ty<'tcx>,
397     pub vis: ast::Visibility,
398     pub def_id: DefId,
399     pub container: ImplOrTraitItemContainer,
400     pub default: Option<DefId>,
401 }
402
403 #[derive(Clone, Copy, Debug)]
404 pub struct AssociatedType<'tcx> {
405     pub name: ast::Name,
406     pub ty: Option<Ty<'tcx>>,
407     pub vis: ast::Visibility,
408     pub def_id: DefId,
409     pub container: ImplOrTraitItemContainer,
410 }
411
412 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
413 pub struct TypeAndMut<'tcx> {
414     pub ty: Ty<'tcx>,
415     pub mutbl: ast::Mutability,
416 }
417
418 #[derive(Clone, PartialEq, RustcDecodable, RustcEncodable)]
419 pub struct ItemVariances {
420     pub types: VecPerParamSpace<Variance>,
421     pub regions: VecPerParamSpace<Variance>,
422 }
423
424 #[derive(Clone, PartialEq, RustcDecodable, RustcEncodable, Copy)]
425 pub enum Variance {
426     Covariant,      // T<A> <: T<B> iff A <: B -- e.g., function return type
427     Invariant,      // T<A> <: T<B> iff B == A -- e.g., type of mutable cell
428     Contravariant,  // T<A> <: T<B> iff B <: A -- e.g., function param type
429     Bivariant,      // T<A> <: T<B>            -- e.g., unused type parameter
430 }
431
432 impl fmt::Debug for Variance {
433     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
434         f.write_str(match *self {
435             Covariant => "+",
436             Contravariant => "-",
437             Invariant => "o",
438             Bivariant => "*",
439         })
440     }
441 }
442
443 #[derive(Copy, Clone)]
444 pub enum AutoAdjustment<'tcx> {
445     AdjustReifyFnPointer,   // go from a fn-item type to a fn-pointer type
446     AdjustUnsafeFnPointer,  // go from a safe fn pointer to an unsafe fn pointer
447     AdjustDerefRef(AutoDerefRef<'tcx>),
448 }
449
450 /// Represents coercing a pointer to a different kind of pointer - where 'kind'
451 /// here means either or both of raw vs borrowed vs unique and fat vs thin.
452 ///
453 /// We transform pointers by following the following steps in order:
454 /// 1. Deref the pointer `self.autoderefs` times (may be 0).
455 /// 2. If `autoref` is `Some(_)`, then take the address and produce either a
456 ///    `&` or `*` pointer.
457 /// 3. If `unsize` is `Some(_)`, then apply the unsize transformation,
458 ///    which will do things like convert thin pointers to fat
459 ///    pointers, or convert structs containing thin pointers to
460 ///    structs containing fat pointers, or convert between fat
461 ///    pointers.  We don't store the details of how the transform is
462 ///    done (in fact, we don't know that, because it might depend on
463 ///    the precise type parameters). We just store the target
464 ///    type. Trans figures out what has to be done at monomorphization
465 ///    time based on the precise source/target type at hand.
466 ///
467 /// To make that more concrete, here are some common scenarios:
468 ///
469 /// 1. The simplest cases are where the pointer is not adjusted fat vs thin.
470 /// Here the pointer will be dereferenced N times (where a dereference can
471 /// happen to to raw or borrowed pointers or any smart pointer which implements
472 /// Deref, including Box<_>). The number of dereferences is given by
473 /// `autoderefs`.  It can then be auto-referenced zero or one times, indicated
474 /// by `autoref`, to either a raw or borrowed pointer. In these cases unsize is
475 /// None.
476 ///
477 /// 2. A thin-to-fat coercon involves unsizing the underlying data. We start
478 /// with a thin pointer, deref a number of times, unsize the underlying data,
479 /// then autoref. The 'unsize' phase may change a fixed length array to a
480 /// dynamically sized one, a concrete object to a trait object, or statically
481 /// sized struct to a dyncamically sized one. E.g., &[i32; 4] -> &[i32] is
482 /// represented by:
483 ///
484 /// ```
485 /// AutoDerefRef {
486 ///     autoderefs: 1,          // &[i32; 4] -> [i32; 4]
487 ///     autoref: Some(AutoPtr), // [i32] -> &[i32]
488 ///     unsize: Some([i32]),    // [i32; 4] -> [i32]
489 /// }
490 /// ```
491 ///
492 /// Note that for a struct, the 'deep' unsizing of the struct is not recorded.
493 /// E.g., `struct Foo<T> { x: T }` we can coerce &Foo<[i32; 4]> to &Foo<[i32]>
494 /// The autoderef and -ref are the same as in the above example, but the type
495 /// stored in `unsize` is `Foo<[i32]>`, we don't store any further detail about
496 /// the underlying conversions from `[i32; 4]` to `[i32]`.
497 ///
498 /// 3. Coercing a `Box<T>` to `Box<Trait>` is an interesting special case.  In
499 /// that case, we have the pointer we need coming in, so there are no
500 /// autoderefs, and no autoref. Instead we just do the `Unsize` transformation.
501 /// At some point, of course, `Box` should move out of the compiler, in which
502 /// case this is analogous to transformating a struct. E.g., Box<[i32; 4]> ->
503 /// Box<[i32]> is represented by:
504 ///
505 /// ```
506 /// AutoDerefRef {
507 ///     autoderefs: 0,
508 ///     autoref: None,
509 ///     unsize: Some(Box<[i32]>),
510 /// }
511 /// ```
512 #[derive(Copy, Clone)]
513 pub struct AutoDerefRef<'tcx> {
514     /// Step 1. Apply a number of dereferences, producing an lvalue.
515     pub autoderefs: usize,
516
517     /// Step 2. Optionally produce a pointer/reference from the value.
518     pub autoref: Option<AutoRef<'tcx>>,
519
520     /// Step 3. Unsize a pointer/reference value, e.g. `&[T; n]` to
521     /// `&[T]`. The stored type is the target pointer type. Note that
522     /// the source could be a thin or fat pointer.
523     pub unsize: Option<Ty<'tcx>>,
524 }
525
526 #[derive(Copy, Clone, PartialEq, Debug)]
527 pub enum AutoRef<'tcx> {
528     /// Convert from T to &T.
529     AutoPtr(&'tcx Region, ast::Mutability),
530
531     /// Convert from T to *T.
532     /// Value to thin pointer.
533     AutoUnsafe(ast::Mutability),
534 }
535
536 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug)]
537 pub enum CustomCoerceUnsized {
538     /// Records the index of the field being coerced.
539     Struct(usize)
540 }
541
542 #[derive(Clone, Copy, Debug)]
543 pub struct MethodCallee<'tcx> {
544     /// Impl method ID, for inherent methods, or trait method ID, otherwise.
545     pub def_id: DefId,
546     pub ty: Ty<'tcx>,
547     pub substs: &'tcx subst::Substs<'tcx>
548 }
549
550 /// With method calls, we store some extra information in
551 /// side tables (i.e method_map). We use
552 /// MethodCall as a key to index into these tables instead of
553 /// just directly using the expression's NodeId. The reason
554 /// for this being that we may apply adjustments (coercions)
555 /// with the resulting expression also needing to use the
556 /// side tables. The problem with this is that we don't
557 /// assign a separate NodeId to this new expression
558 /// and so it would clash with the base expression if both
559 /// needed to add to the side tables. Thus to disambiguate
560 /// we also keep track of whether there's an adjustment in
561 /// our key.
562 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
563 pub struct MethodCall {
564     pub expr_id: ast::NodeId,
565     pub autoderef: u32
566 }
567
568 impl MethodCall {
569     pub fn expr(id: ast::NodeId) -> MethodCall {
570         MethodCall {
571             expr_id: id,
572             autoderef: 0
573         }
574     }
575
576     pub fn autoderef(expr_id: ast::NodeId, autoderef: u32) -> MethodCall {
577         MethodCall {
578             expr_id: expr_id,
579             autoderef: 1 + autoderef
580         }
581     }
582 }
583
584 // maps from an expression id that corresponds to a method call to the details
585 // of the method to be invoked
586 pub type MethodMap<'tcx> = FnvHashMap<MethodCall, MethodCallee<'tcx>>;
587
588 // Contains information needed to resolve types and (in the future) look up
589 // the types of AST nodes.
590 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
591 pub struct CReaderCacheKey {
592     pub cnum: CrateNum,
593     pub pos: usize,
594     pub len: usize
595 }
596
597 /// A restriction that certain types must be the same size. The use of
598 /// `transmute` gives rise to these restrictions. These generally
599 /// cannot be checked until trans; therefore, each call to `transmute`
600 /// will push one or more such restriction into the
601 /// `transmute_restrictions` vector during `intrinsicck`. They are
602 /// then checked during `trans` by the fn `check_intrinsics`.
603 #[derive(Copy, Clone)]
604 pub struct TransmuteRestriction<'tcx> {
605     /// The span whence the restriction comes.
606     pub span: Span,
607
608     /// The type being transmuted from.
609     pub original_from: Ty<'tcx>,
610
611     /// The type being transmuted to.
612     pub original_to: Ty<'tcx>,
613
614     /// The type being transmuted from, with all type parameters
615     /// substituted for an arbitrary representative. Not to be shown
616     /// to the end user.
617     pub substituted_from: Ty<'tcx>,
618
619     /// The type being transmuted to, with all type parameters
620     /// substituted for an arbitrary representative. Not to be shown
621     /// to the end user.
622     pub substituted_to: Ty<'tcx>,
623
624     /// NodeId of the transmute intrinsic.
625     pub id: ast::NodeId,
626 }
627
628 /// Internal storage
629 pub struct CtxtArenas<'tcx> {
630     // internings
631     type_: TypedArena<TyS<'tcx>>,
632     substs: TypedArena<Substs<'tcx>>,
633     bare_fn: TypedArena<BareFnTy<'tcx>>,
634     region: TypedArena<Region>,
635     stability: TypedArena<attr::Stability>,
636
637     // references
638     trait_defs: TypedArena<TraitDef<'tcx>>,
639     adt_defs: TypedArena<AdtDefData<'tcx, 'tcx>>,
640 }
641
642 impl<'tcx> CtxtArenas<'tcx> {
643     pub fn new() -> CtxtArenas<'tcx> {
644         CtxtArenas {
645             type_: TypedArena::new(),
646             substs: TypedArena::new(),
647             bare_fn: TypedArena::new(),
648             region: TypedArena::new(),
649             stability: TypedArena::new(),
650
651             trait_defs: TypedArena::new(),
652             adt_defs: TypedArena::new()
653         }
654     }
655 }
656
657 pub struct CommonTypes<'tcx> {
658     pub bool: Ty<'tcx>,
659     pub char: Ty<'tcx>,
660     pub isize: Ty<'tcx>,
661     pub i8: Ty<'tcx>,
662     pub i16: Ty<'tcx>,
663     pub i32: Ty<'tcx>,
664     pub i64: Ty<'tcx>,
665     pub usize: Ty<'tcx>,
666     pub u8: Ty<'tcx>,
667     pub u16: Ty<'tcx>,
668     pub u32: Ty<'tcx>,
669     pub u64: Ty<'tcx>,
670     pub f32: Ty<'tcx>,
671     pub f64: Ty<'tcx>,
672     pub err: Ty<'tcx>,
673 }
674
675 pub struct Tables<'tcx> {
676     /// Stores the types for various nodes in the AST.  Note that this table
677     /// is not guaranteed to be populated until after typeck.  See
678     /// typeck::check::fn_ctxt for details.
679     pub node_types: NodeMap<Ty<'tcx>>,
680
681     /// Stores the type parameters which were substituted to obtain the type
682     /// of this node.  This only applies to nodes that refer to entities
683     /// parameterized by type parameters, such as generic fns, types, or
684     /// other items.
685     pub item_substs: NodeMap<ItemSubsts<'tcx>>,
686
687     pub adjustments: NodeMap<ty::AutoAdjustment<'tcx>>,
688
689     pub method_map: MethodMap<'tcx>,
690
691     /// Borrows
692     pub upvar_capture_map: UpvarCaptureMap,
693
694     /// Records the type of each closure. The def ID is the ID of the
695     /// expression defining the closure.
696     pub closure_tys: DefIdMap<ClosureTy<'tcx>>,
697
698     /// Records the type of each closure. The def ID is the ID of the
699     /// expression defining the closure.
700     pub closure_kinds: DefIdMap<ClosureKind>,
701 }
702
703 impl<'tcx> Tables<'tcx> {
704     pub fn empty() -> Tables<'tcx> {
705         Tables {
706             node_types: FnvHashMap(),
707             item_substs: NodeMap(),
708             adjustments: NodeMap(),
709             method_map: FnvHashMap(),
710             upvar_capture_map: FnvHashMap(),
711             closure_tys: DefIdMap(),
712             closure_kinds: DefIdMap(),
713         }
714     }
715 }
716
717 /// The data structure to keep track of all the information that typechecker
718 /// generates so that so that it can be reused and doesn't have to be redone
719 /// later on.
720 pub struct ctxt<'tcx> {
721     /// The arenas that types etc are allocated from.
722     arenas: &'tcx CtxtArenas<'tcx>,
723
724     /// Specifically use a speedy hash algorithm for this hash map, it's used
725     /// quite often.
726     // FIXME(eddyb) use a FnvHashSet<InternedTy<'tcx>> when equivalent keys can
727     // queried from a HashSet.
728     interner: RefCell<FnvHashMap<InternedTy<'tcx>, Ty<'tcx>>>,
729
730     // FIXME as above, use a hashset if equivalent elements can be queried.
731     substs_interner: RefCell<FnvHashMap<&'tcx Substs<'tcx>, &'tcx Substs<'tcx>>>,
732     bare_fn_interner: RefCell<FnvHashMap<&'tcx BareFnTy<'tcx>, &'tcx BareFnTy<'tcx>>>,
733     region_interner: RefCell<FnvHashMap<&'tcx Region, &'tcx Region>>,
734     stability_interner: RefCell<FnvHashMap<&'tcx attr::Stability, &'tcx attr::Stability>>,
735
736     /// Common types, pre-interned for your convenience.
737     pub types: CommonTypes<'tcx>,
738
739     pub sess: Session,
740     pub def_map: DefMap,
741
742     pub named_region_map: resolve_lifetime::NamedRegionMap,
743
744     pub region_maps: RegionMaps,
745
746     // For each fn declared in the local crate, type check stores the
747     // free-region relationships that were deduced from its where
748     // clauses and parameter types. These are then read-again by
749     // borrowck. (They are not used during trans, and hence are not
750     // serialized or needed for cross-crate fns.)
751     free_region_maps: RefCell<NodeMap<FreeRegionMap>>,
752     // FIXME: jroesch make this a refcell
753
754     pub tables: RefCell<Tables<'tcx>>,
755
756     /// Maps from a trait item to the trait item "descriptor"
757     pub impl_or_trait_items: RefCell<DefIdMap<ImplOrTraitItem<'tcx>>>,
758
759     /// Maps from a trait def-id to a list of the def-ids of its trait items
760     pub trait_item_def_ids: RefCell<DefIdMap<Rc<Vec<ImplOrTraitItemId>>>>,
761
762     /// A cache for the trait_items() routine
763     pub trait_items_cache: RefCell<DefIdMap<Rc<Vec<ImplOrTraitItem<'tcx>>>>>,
764
765     pub impl_trait_refs: RefCell<DefIdMap<Option<TraitRef<'tcx>>>>,
766     pub trait_defs: RefCell<DefIdMap<&'tcx TraitDef<'tcx>>>,
767     pub adt_defs: RefCell<DefIdMap<AdtDefMaster<'tcx>>>,
768
769     /// Maps from the def-id of an item (trait/struct/enum/fn) to its
770     /// associated predicates.
771     pub predicates: RefCell<DefIdMap<GenericPredicates<'tcx>>>,
772
773     /// Maps from the def-id of a trait to the list of
774     /// super-predicates. This is a subset of the full list of
775     /// predicates. We store these in a separate map because we must
776     /// evaluate them even during type conversion, often before the
777     /// full predicates are available (note that supertraits have
778     /// additional acyclicity requirements).
779     pub super_predicates: RefCell<DefIdMap<GenericPredicates<'tcx>>>,
780
781     pub map: ast_map::Map<'tcx>,
782     pub freevars: RefCell<FreevarMap>,
783     pub tcache: RefCell<DefIdMap<TypeScheme<'tcx>>>,
784     pub rcache: RefCell<FnvHashMap<CReaderCacheKey, Ty<'tcx>>>,
785     pub tc_cache: RefCell<FnvHashMap<Ty<'tcx>, TypeContents>>,
786     pub ast_ty_to_ty_cache: RefCell<NodeMap<Ty<'tcx>>>,
787     pub ty_param_defs: RefCell<NodeMap<TypeParameterDef<'tcx>>>,
788     pub normalized_cache: RefCell<FnvHashMap<Ty<'tcx>, Ty<'tcx>>>,
789     pub lang_items: middle::lang_items::LanguageItems,
790     /// A mapping of fake provided method def_ids to the default implementation
791     pub provided_method_sources: RefCell<DefIdMap<DefId>>,
792
793     /// Maps from def-id of a type or region parameter to its
794     /// (inferred) variance.
795     pub item_variance_map: RefCell<DefIdMap<Rc<ItemVariances>>>,
796
797     /// True if the variance has been computed yet; false otherwise.
798     pub variance_computed: Cell<bool>,
799
800     /// A method will be in this list if and only if it is a destructor.
801     pub destructors: RefCell<DefIdSet>,
802
803     /// Maps a DefId of a type to a list of its inherent impls.
804     /// Contains implementations of methods that are inherent to a type.
805     /// Methods in these implementations don't need to be exported.
806     pub inherent_impls: RefCell<DefIdMap<Rc<Vec<DefId>>>>,
807
808     /// Maps a DefId of an impl to a list of its items.
809     /// Note that this contains all of the impls that we know about,
810     /// including ones in other crates. It's not clear that this is the best
811     /// way to do it.
812     pub impl_items: RefCell<DefIdMap<Vec<ImplOrTraitItemId>>>,
813
814     /// Set of used unsafe nodes (functions or blocks). Unsafe nodes not
815     /// present in this set can be warned about.
816     pub used_unsafe: RefCell<NodeSet>,
817
818     /// Set of nodes which mark locals as mutable which end up getting used at
819     /// some point. Local variable definitions not in this set can be warned
820     /// about.
821     pub used_mut_nodes: RefCell<NodeSet>,
822
823     /// The set of external nominal types whose implementations have been read.
824     /// This is used for lazy resolution of methods.
825     pub populated_external_types: RefCell<DefIdSet>,
826     /// The set of external primitive types whose implementations have been read.
827     /// FIXME(arielb1): why is this separate from populated_external_types?
828     pub populated_external_primitive_impls: RefCell<DefIdSet>,
829
830     /// These caches are used by const_eval when decoding external constants.
831     pub extern_const_statics: RefCell<DefIdMap<ast::NodeId>>,
832     pub extern_const_variants: RefCell<DefIdMap<ast::NodeId>>,
833     pub extern_const_fns: RefCell<DefIdMap<ast::NodeId>>,
834
835     pub node_lint_levels: RefCell<FnvHashMap<(ast::NodeId, lint::LintId),
836                                               lint::LevelSource>>,
837
838     /// The types that must be asserted to be the same size for `transmute`
839     /// to be valid. We gather up these restrictions in the intrinsicck pass
840     /// and check them in trans.
841     pub transmute_restrictions: RefCell<Vec<TransmuteRestriction<'tcx>>>,
842
843     /// Maps any item's def-id to its stability index.
844     pub stability: RefCell<stability::Index<'tcx>>,
845
846     /// Caches the results of trait selection. This cache is used
847     /// for things that do not have to do with the parameters in scope.
848     pub selection_cache: traits::SelectionCache<'tcx>,
849
850     /// A set of predicates that have been fulfilled *somewhere*.
851     /// This is used to avoid duplicate work. Predicates are only
852     /// added to this set when they mention only "global" names
853     /// (i.e., no type or lifetime parameters).
854     pub fulfilled_predicates: RefCell<traits::FulfilledPredicates<'tcx>>,
855
856     /// Caches the representation hints for struct definitions.
857     pub repr_hint_cache: RefCell<DefIdMap<Rc<Vec<attr::ReprAttr>>>>,
858
859     /// Maps Expr NodeId's to their constant qualification.
860     pub const_qualif_map: RefCell<NodeMap<check_const::ConstQualif>>,
861
862     /// Caches CoerceUnsized kinds for impls on custom types.
863     pub custom_coerce_unsized_kinds: RefCell<DefIdMap<CustomCoerceUnsized>>,
864
865     /// Maps a cast expression to its kind. This is keyed on the
866     /// *from* expression of the cast, not the cast itself.
867     pub cast_kinds: RefCell<NodeMap<cast::CastKind>>,
868
869     /// Maps Fn items to a collection of fragment infos.
870     ///
871     /// The main goal is to identify data (each of which may be moved
872     /// or assigned) whose subparts are not moved nor assigned
873     /// (i.e. their state is *unfragmented*) and corresponding ast
874     /// nodes where the path to that data is moved or assigned.
875     ///
876     /// In the long term, unfragmented values will have their
877     /// destructor entirely driven by a single stack-local drop-flag,
878     /// and their parents, the collections of the unfragmented values
879     /// (or more simply, "fragmented values"), are mapped to the
880     /// corresponding collections of stack-local drop-flags.
881     ///
882     /// (However, in the short term that is not the case; e.g. some
883     /// unfragmented paths still need to be zeroed, namely when they
884     /// reference parent data from an outer scope that was not
885     /// entirely moved, and therefore that needs to be zeroed so that
886     /// we do not get double-drop when we hit the end of the parent
887     /// scope.)
888     ///
889     /// Also: currently the table solely holds keys for node-ids of
890     /// unfragmented values (see `FragmentInfo` enum definition), but
891     /// longer-term we will need to also store mappings from
892     /// fragmented data to the set of unfragmented pieces that
893     /// constitute it.
894     pub fragment_infos: RefCell<DefIdMap<Vec<FragmentInfo>>>,
895 }
896
897 /// Describes the fragment-state associated with a NodeId.
898 ///
899 /// Currently only unfragmented paths have entries in the table,
900 /// but longer-term this enum is expected to expand to also
901 /// include data for fragmented paths.
902 #[derive(Copy, Clone, Debug)]
903 pub enum FragmentInfo {
904     Moved { var: NodeId, move_expr: NodeId },
905     Assigned { var: NodeId, assign_expr: NodeId, assignee_id: NodeId },
906 }
907
908 impl<'tcx> ctxt<'tcx> {
909     pub fn node_types(&self) -> Ref<NodeMap<Ty<'tcx>>> {
910         fn projection<'a, 'tcx>(tables: &'a Tables<'tcx>) ->  &'a NodeMap<Ty<'tcx>> {
911             &tables.node_types
912         }
913
914         Ref::map(self.tables.borrow(), projection)
915     }
916
917     pub fn node_type_insert(&self, id: NodeId, ty: Ty<'tcx>) {
918         self.tables.borrow_mut().node_types.insert(id, ty);
919     }
920
921     pub fn intern_trait_def(&self, def: TraitDef<'tcx>) -> &'tcx TraitDef<'tcx> {
922         let did = def.trait_ref.def_id;
923         let interned = self.arenas.trait_defs.alloc(def);
924         self.trait_defs.borrow_mut().insert(did, interned);
925         interned
926     }
927
928     pub fn intern_adt_def(&self,
929                           did: DefId,
930                           kind: AdtKind,
931                           variants: Vec<VariantDefData<'tcx, 'tcx>>)
932                           -> AdtDefMaster<'tcx> {
933         let def = AdtDefData::new(self, did, kind, variants);
934         let interned = self.arenas.adt_defs.alloc(def);
935         // this will need a transmute when reverse-variance is removed
936         self.adt_defs.borrow_mut().insert(did, interned);
937         interned
938     }
939
940     pub fn intern_stability(&self, stab: attr::Stability) -> &'tcx attr::Stability {
941         if let Some(st) = self.stability_interner.borrow().get(&stab) {
942             return st;
943         }
944
945         let interned = self.arenas.stability.alloc(stab);
946         self.stability_interner.borrow_mut().insert(interned, interned);
947         interned
948     }
949
950     pub fn store_free_region_map(&self, id: NodeId, map: FreeRegionMap) {
951         self.free_region_maps.borrow_mut()
952                              .insert(id, map);
953     }
954
955     pub fn free_region_map(&self, id: NodeId) -> FreeRegionMap {
956         self.free_region_maps.borrow()[&id].clone()
957     }
958
959     pub fn lift<T: ?Sized + Lift<'tcx>>(&self, value: &T) -> Option<T::Lifted> {
960         value.lift_to_tcx(self)
961     }
962 }
963
964 /// A trait implemented for all X<'a> types which can be safely and
965 /// efficiently converted to X<'tcx> as long as they are part of the
966 /// provided ty::ctxt<'tcx>.
967 /// This can be done, for example, for Ty<'tcx> or &'tcx Substs<'tcx>
968 /// by looking them up in their respective interners.
969 /// None is returned if the value or one of the components is not part
970 /// of the provided context.
971 /// For Ty, None can be returned if either the type interner doesn't
972 /// contain the TypeVariants key or if the address of the interned
973 /// pointer differs. The latter case is possible if a primitive type,
974 /// e.g. `()` or `u8`, was interned in a different context.
975 pub trait Lift<'tcx> {
976     type Lifted;
977     fn lift_to_tcx(&self, tcx: &ctxt<'tcx>) -> Option<Self::Lifted>;
978 }
979
980 impl<'tcx, A: Lift<'tcx>, B: Lift<'tcx>> Lift<'tcx> for (A, B) {
981     type Lifted = (A::Lifted, B::Lifted);
982     fn lift_to_tcx(&self, tcx: &ctxt<'tcx>) -> Option<Self::Lifted> {
983         tcx.lift(&self.0).and_then(|a| tcx.lift(&self.1).map(|b| (a, b)))
984     }
985 }
986
987 impl<'tcx, T: Lift<'tcx>> Lift<'tcx> for [T] {
988     type Lifted = Vec<T::Lifted>;
989     fn lift_to_tcx(&self, tcx: &ctxt<'tcx>) -> Option<Self::Lifted> {
990         let mut result = Vec::with_capacity(self.len());
991         for x in self {
992             if let Some(value) = tcx.lift(x) {
993                 result.push(value);
994             } else {
995                 return None;
996             }
997         }
998         Some(result)
999     }
1000 }
1001
1002 impl<'tcx> Lift<'tcx> for Region {
1003     type Lifted = Self;
1004     fn lift_to_tcx(&self, _: &ctxt<'tcx>) -> Option<Region> {
1005         Some(*self)
1006     }
1007 }
1008
1009 impl<'a, 'tcx> Lift<'tcx> for Ty<'a> {
1010     type Lifted = Ty<'tcx>;
1011     fn lift_to_tcx(&self, tcx: &ctxt<'tcx>) -> Option<Ty<'tcx>> {
1012         if let Some(&ty) = tcx.interner.borrow().get(&self.sty) {
1013             if *self as *const _ == ty as *const _ {
1014                 return Some(ty);
1015             }
1016         }
1017         None
1018     }
1019 }
1020
1021 impl<'a, 'tcx> Lift<'tcx> for &'a Substs<'a> {
1022     type Lifted = &'tcx Substs<'tcx>;
1023     fn lift_to_tcx(&self, tcx: &ctxt<'tcx>) -> Option<&'tcx Substs<'tcx>> {
1024         if let Some(&substs) = tcx.substs_interner.borrow().get(*self) {
1025             if *self as *const _ == substs as *const _ {
1026                 return Some(substs);
1027             }
1028         }
1029         None
1030     }
1031 }
1032
1033 impl<'a, 'tcx> Lift<'tcx> for TraitRef<'a> {
1034     type Lifted = TraitRef<'tcx>;
1035     fn lift_to_tcx(&self, tcx: &ctxt<'tcx>) -> Option<TraitRef<'tcx>> {
1036         tcx.lift(&self.substs).map(|substs| TraitRef {
1037             def_id: self.def_id,
1038             substs: substs
1039         })
1040     }
1041 }
1042
1043 impl<'a, 'tcx> Lift<'tcx> for TraitPredicate<'a> {
1044     type Lifted = TraitPredicate<'tcx>;
1045     fn lift_to_tcx(&self, tcx: &ctxt<'tcx>) -> Option<TraitPredicate<'tcx>> {
1046         tcx.lift(&self.trait_ref).map(|trait_ref| TraitPredicate {
1047             trait_ref: trait_ref
1048         })
1049     }
1050 }
1051
1052 impl<'a, 'tcx> Lift<'tcx> for EquatePredicate<'a> {
1053     type Lifted = EquatePredicate<'tcx>;
1054     fn lift_to_tcx(&self, tcx: &ctxt<'tcx>) -> Option<EquatePredicate<'tcx>> {
1055         tcx.lift(&(self.0, self.1)).map(|(a, b)| EquatePredicate(a, b))
1056     }
1057 }
1058
1059 impl<'tcx, A: Copy+Lift<'tcx>, B: Copy+Lift<'tcx>> Lift<'tcx> for OutlivesPredicate<A, B> {
1060     type Lifted = OutlivesPredicate<A::Lifted, B::Lifted>;
1061     fn lift_to_tcx(&self, tcx: &ctxt<'tcx>) -> Option<Self::Lifted> {
1062         tcx.lift(&(self.0, self.1)).map(|(a, b)| OutlivesPredicate(a, b))
1063     }
1064 }
1065
1066 impl<'a, 'tcx> Lift<'tcx> for ProjectionPredicate<'a> {
1067     type Lifted = ProjectionPredicate<'tcx>;
1068     fn lift_to_tcx(&self, tcx: &ctxt<'tcx>) -> Option<ProjectionPredicate<'tcx>> {
1069         tcx.lift(&(self.projection_ty.trait_ref, self.ty)).map(|(trait_ref, ty)| {
1070             ProjectionPredicate {
1071                 projection_ty: ProjectionTy {
1072                     trait_ref: trait_ref,
1073                     item_name: self.projection_ty.item_name
1074                 },
1075                 ty: ty
1076             }
1077         })
1078     }
1079 }
1080
1081 impl<'tcx, T: Lift<'tcx>> Lift<'tcx> for Binder<T> {
1082     type Lifted = Binder<T::Lifted>;
1083     fn lift_to_tcx(&self, tcx: &ctxt<'tcx>) -> Option<Self::Lifted> {
1084         tcx.lift(&self.0).map(|x| Binder(x))
1085     }
1086 }
1087
1088 pub mod tls {
1089     use middle::ty;
1090     use session::Session;
1091
1092     use std::fmt;
1093     use syntax::codemap;
1094
1095     /// Marker type used for the scoped TLS slot.
1096     /// The type context cannot be used directly because the scoped TLS
1097     /// in libstd doesn't allow types generic over lifetimes.
1098     struct ThreadLocalTyCx;
1099
1100     scoped_thread_local!(static TLS_TCX: ThreadLocalTyCx);
1101
1102     fn span_debug(span: codemap::Span, f: &mut fmt::Formatter) -> fmt::Result {
1103         with(|tcx| {
1104             write!(f, "{}", tcx.sess.codemap().span_to_string(span))
1105         })
1106     }
1107
1108     pub fn enter<'tcx, F: FnOnce(&ty::ctxt<'tcx>) -> R, R>(tcx: ty::ctxt<'tcx>, f: F)
1109                                                            -> (Session, R) {
1110         let result = codemap::SPAN_DEBUG.with(|span_dbg| {
1111             let original_span_debug = span_dbg.get();
1112             span_dbg.set(span_debug);
1113             let tls_ptr = &tcx as *const _ as *const ThreadLocalTyCx;
1114             let result = TLS_TCX.set(unsafe { &*tls_ptr }, || f(&tcx));
1115             span_dbg.set(original_span_debug);
1116             result
1117         });
1118         (tcx.sess, result)
1119     }
1120
1121     pub fn with<F: FnOnce(&ty::ctxt) -> R, R>(f: F) -> R {
1122         TLS_TCX.with(|tcx| f(unsafe { &*(tcx as *const _ as *const ty::ctxt) }))
1123     }
1124
1125     pub fn with_opt<F: FnOnce(Option<&ty::ctxt>) -> R, R>(f: F) -> R {
1126         if TLS_TCX.is_set() {
1127             with(|v| f(Some(v)))
1128         } else {
1129             f(None)
1130         }
1131     }
1132 }
1133
1134 // Flags that we track on types. These flags are propagated upwards
1135 // through the type during type construction, so that we can quickly
1136 // check whether the type has various kinds of types in it without
1137 // recursing over the type itself.
1138 bitflags! {
1139     flags TypeFlags: u32 {
1140         const HAS_PARAMS         = 1 << 0,
1141         const HAS_SELF           = 1 << 1,
1142         const HAS_TY_INFER       = 1 << 2,
1143         const HAS_RE_INFER       = 1 << 3,
1144         const HAS_RE_EARLY_BOUND = 1 << 4,
1145         const HAS_FREE_REGIONS   = 1 << 5,
1146         const HAS_TY_ERR         = 1 << 6,
1147         const HAS_PROJECTION     = 1 << 7,
1148         const HAS_TY_CLOSURE     = 1 << 8,
1149
1150         // true if there are "names" of types and regions and so forth
1151         // that are local to a particular fn
1152         const HAS_LOCAL_NAMES   = 1 << 9,
1153
1154         const NEEDS_SUBST        = TypeFlags::HAS_PARAMS.bits |
1155                                    TypeFlags::HAS_SELF.bits |
1156                                    TypeFlags::HAS_RE_EARLY_BOUND.bits,
1157
1158         // Flags representing the nominal content of a type,
1159         // computed by FlagsComputation. If you add a new nominal
1160         // flag, it should be added here too.
1161         const NOMINAL_FLAGS     = TypeFlags::HAS_PARAMS.bits |
1162                                   TypeFlags::HAS_SELF.bits |
1163                                   TypeFlags::HAS_TY_INFER.bits |
1164                                   TypeFlags::HAS_RE_INFER.bits |
1165                                   TypeFlags::HAS_RE_EARLY_BOUND.bits |
1166                                   TypeFlags::HAS_FREE_REGIONS.bits |
1167                                   TypeFlags::HAS_TY_ERR.bits |
1168                                   TypeFlags::HAS_PROJECTION.bits |
1169                                   TypeFlags::HAS_TY_CLOSURE.bits |
1170                                   TypeFlags::HAS_LOCAL_NAMES.bits,
1171
1172         // Caches for type_is_sized, type_moves_by_default
1173         const SIZEDNESS_CACHED  = 1 << 16,
1174         const IS_SIZED          = 1 << 17,
1175         const MOVENESS_CACHED   = 1 << 18,
1176         const MOVES_BY_DEFAULT  = 1 << 19,
1177     }
1178 }
1179
1180 macro_rules! sty_debug_print {
1181     ($ctxt: expr, $($variant: ident),*) => {{
1182         // curious inner module to allow variant names to be used as
1183         // variable names.
1184         #[allow(non_snake_case)]
1185         mod inner {
1186             use middle::ty;
1187             #[derive(Copy, Clone)]
1188             struct DebugStat {
1189                 total: usize,
1190                 region_infer: usize,
1191                 ty_infer: usize,
1192                 both_infer: usize,
1193             }
1194
1195             pub fn go(tcx: &ty::ctxt) {
1196                 let mut total = DebugStat {
1197                     total: 0,
1198                     region_infer: 0, ty_infer: 0, both_infer: 0,
1199                 };
1200                 $(let mut $variant = total;)*
1201
1202
1203                 for (_, t) in tcx.interner.borrow().iter() {
1204                     let variant = match t.sty {
1205                         ty::TyBool | ty::TyChar | ty::TyInt(..) | ty::TyUint(..) |
1206                             ty::TyFloat(..) | ty::TyStr => continue,
1207                         ty::TyError => /* unimportant */ continue,
1208                         $(ty::$variant(..) => &mut $variant,)*
1209                     };
1210                     let region = t.flags.get().intersects(ty::TypeFlags::HAS_RE_INFER);
1211                     let ty = t.flags.get().intersects(ty::TypeFlags::HAS_TY_INFER);
1212
1213                     variant.total += 1;
1214                     total.total += 1;
1215                     if region { total.region_infer += 1; variant.region_infer += 1 }
1216                     if ty { total.ty_infer += 1; variant.ty_infer += 1 }
1217                     if region && ty { total.both_infer += 1; variant.both_infer += 1 }
1218                 }
1219                 println!("Ty interner             total           ty region  both");
1220                 $(println!("    {:18}: {uses:6} {usespc:4.1}%, \
1221 {ty:4.1}% {region:5.1}% {both:4.1}%",
1222                            stringify!($variant),
1223                            uses = $variant.total,
1224                            usespc = $variant.total as f64 * 100.0 / total.total as f64,
1225                            ty = $variant.ty_infer as f64 * 100.0  / total.total as f64,
1226                            region = $variant.region_infer as f64 * 100.0  / total.total as f64,
1227                            both = $variant.both_infer as f64 * 100.0  / total.total as f64);
1228                   )*
1229                 println!("                  total {uses:6}        \
1230 {ty:4.1}% {region:5.1}% {both:4.1}%",
1231                          uses = total.total,
1232                          ty = total.ty_infer as f64 * 100.0  / total.total as f64,
1233                          region = total.region_infer as f64 * 100.0  / total.total as f64,
1234                          both = total.both_infer as f64 * 100.0  / total.total as f64)
1235             }
1236         }
1237
1238         inner::go($ctxt)
1239     }}
1240 }
1241
1242 impl<'tcx> ctxt<'tcx> {
1243     pub fn print_debug_stats(&self) {
1244         sty_debug_print!(
1245             self,
1246             TyEnum, TyBox, TyArray, TySlice, TyRawPtr, TyRef, TyBareFn, TyTrait,
1247             TyStruct, TyClosure, TyTuple, TyParam, TyInfer, TyProjection);
1248
1249         println!("Substs interner: #{}", self.substs_interner.borrow().len());
1250         println!("BareFnTy interner: #{}", self.bare_fn_interner.borrow().len());
1251         println!("Region interner: #{}", self.region_interner.borrow().len());
1252         println!("Stability interner: #{}", self.stability_interner.borrow().len());
1253     }
1254 }
1255
1256 pub struct TyS<'tcx> {
1257     pub sty: TypeVariants<'tcx>,
1258     pub flags: Cell<TypeFlags>,
1259
1260     // the maximal depth of any bound regions appearing in this type.
1261     region_depth: u32,
1262 }
1263
1264 impl fmt::Debug for TypeFlags {
1265     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1266         write!(f, "{}", self.bits)
1267     }
1268 }
1269
1270 impl<'tcx> PartialEq for TyS<'tcx> {
1271     #[inline]
1272     fn eq(&self, other: &TyS<'tcx>) -> bool {
1273         // (self as *const _) == (other as *const _)
1274         (self as *const TyS<'tcx>) == (other as *const TyS<'tcx>)
1275     }
1276 }
1277 impl<'tcx> Eq for TyS<'tcx> {}
1278
1279 impl<'tcx> Hash for TyS<'tcx> {
1280     fn hash<H: Hasher>(&self, s: &mut H) {
1281         (self as *const TyS).hash(s)
1282     }
1283 }
1284
1285 pub type Ty<'tcx> = &'tcx TyS<'tcx>;
1286
1287 /// An IVar that contains a Ty. 'lt is a (reverse-variant) upper bound
1288 /// on the lifetime of the IVar. This is required because of variance
1289 /// problems: the IVar needs to be variant with respect to 'tcx (so
1290 /// it can be referred to from Ty) but can only be modified if its
1291 /// lifetime is exactly 'tcx.
1292 ///
1293 /// Safety invariants:
1294 ///     (A) self.0, if fulfilled, is a valid Ty<'tcx>
1295 ///     (B) no aliases to this value with a 'tcx longer than this
1296 ///         value's 'lt exist
1297 ///
1298 /// NonZero is used rather than Unique because Unique isn't Copy.
1299 pub struct TyIVar<'tcx, 'lt: 'tcx>(ivar::Ivar<NonZero<*const TyS<'static>>>,
1300                                    PhantomData<fn(TyS<'lt>)->TyS<'tcx>>);
1301
1302 impl<'tcx, 'lt> TyIVar<'tcx, 'lt> {
1303     #[inline]
1304     pub fn new() -> Self {
1305         // Invariant (A) satisfied because the IVar is unfulfilled
1306         // Invariant (B) because 'lt : 'tcx
1307         TyIVar(ivar::Ivar::new(), PhantomData)
1308     }
1309
1310     #[inline]
1311     pub fn get(&self) -> Option<Ty<'tcx>> {
1312         match self.0.get() {
1313             None => None,
1314             // valid because of invariant (A)
1315             Some(v) => Some(unsafe { &*(*v as *const TyS<'tcx>) })
1316         }
1317     }
1318     #[inline]
1319     pub fn unwrap(&self) -> Ty<'tcx> {
1320         self.get().unwrap()
1321     }
1322
1323     pub fn fulfill(&self, value: Ty<'lt>) {
1324         // Invariant (A) is fulfilled, because by (B), every alias
1325         // of this has a 'tcx longer than 'lt.
1326         let value: *const TyS<'lt> = value;
1327         // FIXME(27214): unneeded [as *const ()]
1328         let value = value as *const () as *const TyS<'static>;
1329         self.0.fulfill(unsafe { NonZero::new(value) })
1330     }
1331 }
1332
1333 impl<'tcx, 'lt> fmt::Debug for TyIVar<'tcx, 'lt> {
1334     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1335         match self.get() {
1336             Some(val) => write!(f, "TyIVar({:?})", val),
1337             None => f.write_str("TyIVar(<unfulfilled>)")
1338         }
1339     }
1340 }
1341
1342 /// An entry in the type interner.
1343 pub struct InternedTy<'tcx> {
1344     ty: Ty<'tcx>
1345 }
1346
1347 // NB: An InternedTy compares and hashes as a sty.
1348 impl<'tcx> PartialEq for InternedTy<'tcx> {
1349     fn eq(&self, other: &InternedTy<'tcx>) -> bool {
1350         self.ty.sty == other.ty.sty
1351     }
1352 }
1353
1354 impl<'tcx> Eq for InternedTy<'tcx> {}
1355
1356 impl<'tcx> Hash for InternedTy<'tcx> {
1357     fn hash<H: Hasher>(&self, s: &mut H) {
1358         self.ty.sty.hash(s)
1359     }
1360 }
1361
1362 impl<'tcx> Borrow<TypeVariants<'tcx>> for InternedTy<'tcx> {
1363     fn borrow<'a>(&'a self) -> &'a TypeVariants<'tcx> {
1364         &self.ty.sty
1365     }
1366 }
1367
1368 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
1369 pub struct BareFnTy<'tcx> {
1370     pub unsafety: ast::Unsafety,
1371     pub abi: abi::Abi,
1372     pub sig: PolyFnSig<'tcx>,
1373 }
1374
1375 #[derive(Clone, PartialEq, Eq, Hash)]
1376 pub struct ClosureTy<'tcx> {
1377     pub unsafety: ast::Unsafety,
1378     pub abi: abi::Abi,
1379     pub sig: PolyFnSig<'tcx>,
1380 }
1381
1382 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
1383 pub enum FnOutput<'tcx> {
1384     FnConverging(Ty<'tcx>),
1385     FnDiverging
1386 }
1387
1388 impl<'tcx> FnOutput<'tcx> {
1389     pub fn diverges(&self) -> bool {
1390         *self == FnDiverging
1391     }
1392
1393     pub fn unwrap(self) -> Ty<'tcx> {
1394         match self {
1395             ty::FnConverging(t) => t,
1396             ty::FnDiverging => unreachable!()
1397         }
1398     }
1399
1400     pub fn unwrap_or(self, def: Ty<'tcx>) -> Ty<'tcx> {
1401         match self {
1402             ty::FnConverging(t) => t,
1403             ty::FnDiverging => def
1404         }
1405     }
1406 }
1407
1408 pub type PolyFnOutput<'tcx> = Binder<FnOutput<'tcx>>;
1409
1410 impl<'tcx> PolyFnOutput<'tcx> {
1411     pub fn diverges(&self) -> bool {
1412         self.0.diverges()
1413     }
1414 }
1415
1416 /// Signature of a function type, which I have arbitrarily
1417 /// decided to use to refer to the input/output types.
1418 ///
1419 /// - `inputs` is the list of arguments and their modes.
1420 /// - `output` is the return type.
1421 /// - `variadic` indicates whether this is a variadic function. (only true for foreign fns)
1422 #[derive(Clone, PartialEq, Eq, Hash)]
1423 pub struct FnSig<'tcx> {
1424     pub inputs: Vec<Ty<'tcx>>,
1425     pub output: FnOutput<'tcx>,
1426     pub variadic: bool
1427 }
1428
1429 pub type PolyFnSig<'tcx> = Binder<FnSig<'tcx>>;
1430
1431 impl<'tcx> PolyFnSig<'tcx> {
1432     pub fn inputs(&self) -> ty::Binder<Vec<Ty<'tcx>>> {
1433         self.map_bound_ref(|fn_sig| fn_sig.inputs.clone())
1434     }
1435     pub fn input(&self, index: usize) -> ty::Binder<Ty<'tcx>> {
1436         self.map_bound_ref(|fn_sig| fn_sig.inputs[index])
1437     }
1438     pub fn output(&self) -> ty::Binder<FnOutput<'tcx>> {
1439         self.map_bound_ref(|fn_sig| fn_sig.output.clone())
1440     }
1441     pub fn variadic(&self) -> bool {
1442         self.skip_binder().variadic
1443     }
1444 }
1445
1446 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
1447 pub struct ParamTy {
1448     pub space: subst::ParamSpace,
1449     pub idx: u32,
1450     pub name: ast::Name,
1451 }
1452
1453 /// A [De Bruijn index][dbi] is a standard means of representing
1454 /// regions (and perhaps later types) in a higher-ranked setting. In
1455 /// particular, imagine a type like this:
1456 ///
1457 ///     for<'a> fn(for<'b> fn(&'b isize, &'a isize), &'a char)
1458 ///     ^          ^            |        |         |
1459 ///     |          |            |        |         |
1460 ///     |          +------------+ 1      |         |
1461 ///     |                                |         |
1462 ///     +--------------------------------+ 2       |
1463 ///     |                                          |
1464 ///     +------------------------------------------+ 1
1465 ///
1466 /// In this type, there are two binders (the outer fn and the inner
1467 /// fn). We need to be able to determine, for any given region, which
1468 /// fn type it is bound by, the inner or the outer one. There are
1469 /// various ways you can do this, but a De Bruijn index is one of the
1470 /// more convenient and has some nice properties. The basic idea is to
1471 /// count the number of binders, inside out. Some examples should help
1472 /// clarify what I mean.
1473 ///
1474 /// Let's start with the reference type `&'b isize` that is the first
1475 /// argument to the inner function. This region `'b` is assigned a De
1476 /// Bruijn index of 1, meaning "the innermost binder" (in this case, a
1477 /// fn). The region `'a` that appears in the second argument type (`&'a
1478 /// isize`) would then be assigned a De Bruijn index of 2, meaning "the
1479 /// second-innermost binder". (These indices are written on the arrays
1480 /// in the diagram).
1481 ///
1482 /// What is interesting is that De Bruijn index attached to a particular
1483 /// variable will vary depending on where it appears. For example,
1484 /// the final type `&'a char` also refers to the region `'a` declared on
1485 /// the outermost fn. But this time, this reference is not nested within
1486 /// any other binders (i.e., it is not an argument to the inner fn, but
1487 /// rather the outer one). Therefore, in this case, it is assigned a
1488 /// De Bruijn index of 1, because the innermost binder in that location
1489 /// is the outer fn.
1490 ///
1491 /// [dbi]: http://en.wikipedia.org/wiki/De_Bruijn_index
1492 #[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Debug, Copy)]
1493 pub struct DebruijnIndex {
1494     // We maintain the invariant that this is never 0. So 1 indicates
1495     // the innermost binder. To ensure this, create with `DebruijnIndex::new`.
1496     pub depth: u32,
1497 }
1498
1499 /// Representation of regions.
1500 ///
1501 /// Unlike types, most region variants are "fictitious", not concrete,
1502 /// regions. Among these, `ReStatic`, `ReEmpty` and `ReScope` are the only
1503 /// ones representing concrete regions.
1504 ///
1505 /// ## Bound Regions
1506 ///
1507 /// These are regions that are stored behind a binder and must be substituted
1508 /// with some concrete region before being used. There are 2 kind of
1509 /// bound regions: early-bound, which are bound in a TypeScheme/TraitDef,
1510 /// and are substituted by a Substs,  and late-bound, which are part of
1511 /// higher-ranked types (e.g. `for<'a> fn(&'a ())`) and are substituted by
1512 /// the likes of `liberate_late_bound_regions`. The distinction exists
1513 /// because higher-ranked lifetimes aren't supported in all places. See [1][2].
1514 ///
1515 /// Unlike TyParam-s, bound regions are not supposed to exist "in the wild"
1516 /// outside their binder, e.g. in types passed to type inference, and
1517 /// should first be substituted (by skolemized regions, free regions,
1518 /// or region variables).
1519 ///
1520 /// ## Skolemized and Free Regions
1521 ///
1522 /// One often wants to work with bound regions without knowing their precise
1523 /// identity. For example, when checking a function, the lifetime of a borrow
1524 /// can end up being assigned to some region parameter. In these cases,
1525 /// it must be ensured that bounds on the region can't be accidentally
1526 /// assumed without being checked.
1527 ///
1528 /// The process of doing that is called "skolemization". The bound regions
1529 /// are replaced by skolemized markers, which don't satisfy any relation
1530 /// not explicity provided.
1531 ///
1532 /// There are 2 kinds of skolemized regions in rustc: `ReFree` and
1533 /// `ReSkolemized`. When checking an item's body, `ReFree` is supposed
1534 /// to be used. These also support explicit bounds: both the internally-stored
1535 /// *scope*, which the region is assumed to outlive, as well as other
1536 /// relations stored in the `FreeRegionMap`. Note that these relations
1537 /// aren't checked when you `make_subregion` (or `mk_eqty`), only by
1538 /// `resolve_regions_and_report_errors`.
1539 ///
1540 /// When working with higher-ranked types, some region relations aren't
1541 /// yet known, so you can't just call `resolve_regions_and_report_errors`.
1542 /// `ReSkolemized` is designed for this purpose. In these contexts,
1543 /// there's also the risk that some inference variable laying around will
1544 /// get unified with your skolemized region: if you want to check whether
1545 /// `for<'a> Foo<'_>: 'a`, and you substitute your bound region `'a`
1546 /// with a skolemized region `'%a`, the variable `'_` would just be
1547 /// instantiated to the skolemized region `'%a`, which is wrong because
1548 /// the inference variable is supposed to satisfy the relation
1549 /// *for every value of the skolemized region*. To ensure that doesn't
1550 /// happen, you can use `leak_check`. This is more clearly explained
1551 /// by infer/higher_ranked/README.md.
1552 ///
1553 /// [1] http://smallcultfollowing.com/babysteps/blog/2013/10/29/intermingled-parameter-lists/
1554 /// [2] http://smallcultfollowing.com/babysteps/blog/2013/11/04/intermingled-parameter-lists/
1555 #[derive(Clone, PartialEq, Eq, Hash, Copy)]
1556 pub enum Region {
1557     // Region bound in a type or fn declaration which will be
1558     // substituted 'early' -- that is, at the same time when type
1559     // parameters are substituted.
1560     ReEarlyBound(EarlyBoundRegion),
1561
1562     // Region bound in a function scope, which will be substituted when the
1563     // function is called.
1564     ReLateBound(DebruijnIndex, BoundRegion),
1565
1566     /// When checking a function body, the types of all arguments and so forth
1567     /// that refer to bound region parameters are modified to refer to free
1568     /// region parameters.
1569     ReFree(FreeRegion),
1570
1571     /// A concrete region naming some statically determined extent
1572     /// (e.g. an expression or sequence of statements) within the
1573     /// current function.
1574     ReScope(region::CodeExtent),
1575
1576     /// Static data that has an "infinite" lifetime. Top in the region lattice.
1577     ReStatic,
1578
1579     /// A region variable.  Should not exist after typeck.
1580     ReVar(RegionVid),
1581
1582     /// A skolemized region - basically the higher-ranked version of ReFree.
1583     /// Should not exist after typeck.
1584     ReSkolemized(SkolemizedRegionVid, BoundRegion),
1585
1586     /// Empty lifetime is for data that is never accessed.
1587     /// Bottom in the region lattice. We treat ReEmpty somewhat
1588     /// specially; at least right now, we do not generate instances of
1589     /// it during the GLB computations, but rather
1590     /// generate an error instead. This is to improve error messages.
1591     /// The only way to get an instance of ReEmpty is to have a region
1592     /// variable with no constraints.
1593     ReEmpty,
1594 }
1595
1596 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Debug)]
1597 pub struct EarlyBoundRegion {
1598     pub param_id: ast::NodeId,
1599     pub space: subst::ParamSpace,
1600     pub index: u32,
1601     pub name: ast::Name,
1602 }
1603
1604 /// Upvars do not get their own node-id. Instead, we use the pair of
1605 /// the original var id (that is, the root variable that is referenced
1606 /// by the upvar) and the id of the closure expression.
1607 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
1608 pub struct UpvarId {
1609     pub var_id: ast::NodeId,
1610     pub closure_expr_id: ast::NodeId,
1611 }
1612
1613 #[derive(Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable, Copy)]
1614 pub enum BorrowKind {
1615     /// Data must be immutable and is aliasable.
1616     ImmBorrow,
1617
1618     /// Data must be immutable but not aliasable.  This kind of borrow
1619     /// cannot currently be expressed by the user and is used only in
1620     /// implicit closure bindings. It is needed when you the closure
1621     /// is borrowing or mutating a mutable referent, e.g.:
1622     ///
1623     ///    let x: &mut isize = ...;
1624     ///    let y = || *x += 5;
1625     ///
1626     /// If we were to try to translate this closure into a more explicit
1627     /// form, we'd encounter an error with the code as written:
1628     ///
1629     ///    struct Env { x: & &mut isize }
1630     ///    let x: &mut isize = ...;
1631     ///    let y = (&mut Env { &x }, fn_ptr);  // Closure is pair of env and fn
1632     ///    fn fn_ptr(env: &mut Env) { **env.x += 5; }
1633     ///
1634     /// This is then illegal because you cannot mutate a `&mut` found
1635     /// in an aliasable location. To solve, you'd have to translate with
1636     /// an `&mut` borrow:
1637     ///
1638     ///    struct Env { x: & &mut isize }
1639     ///    let x: &mut isize = ...;
1640     ///    let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
1641     ///    fn fn_ptr(env: &mut Env) { **env.x += 5; }
1642     ///
1643     /// Now the assignment to `**env.x` is legal, but creating a
1644     /// mutable pointer to `x` is not because `x` is not mutable. We
1645     /// could fix this by declaring `x` as `let mut x`. This is ok in
1646     /// user code, if awkward, but extra weird for closures, since the
1647     /// borrow is hidden.
1648     ///
1649     /// So we introduce a "unique imm" borrow -- the referent is
1650     /// immutable, but not aliasable. This solves the problem. For
1651     /// simplicity, we don't give users the way to express this
1652     /// borrow, it's just used when translating closures.
1653     UniqueImmBorrow,
1654
1655     /// Data is mutable and not aliasable.
1656     MutBorrow
1657 }
1658
1659 /// Information describing the capture of an upvar. This is computed
1660 /// during `typeck`, specifically by `regionck`.
1661 #[derive(PartialEq, Clone, Debug, Copy)]
1662 pub enum UpvarCapture {
1663     /// Upvar is captured by value. This is always true when the
1664     /// closure is labeled `move`, but can also be true in other cases
1665     /// depending on inference.
1666     ByValue,
1667
1668     /// Upvar is captured by reference.
1669     ByRef(UpvarBorrow),
1670 }
1671
1672 #[derive(PartialEq, Clone, Copy)]
1673 pub struct UpvarBorrow {
1674     /// The kind of borrow: by-ref upvars have access to shared
1675     /// immutable borrows, which are not part of the normal language
1676     /// syntax.
1677     pub kind: BorrowKind,
1678
1679     /// Region of the resulting reference.
1680     pub region: ty::Region,
1681 }
1682
1683 pub type UpvarCaptureMap = FnvHashMap<UpvarId, UpvarCapture>;
1684
1685 #[derive(Copy, Clone)]
1686 pub struct ClosureUpvar<'tcx> {
1687     pub def: def::Def,
1688     pub span: Span,
1689     pub ty: Ty<'tcx>,
1690 }
1691
1692 impl Region {
1693     pub fn is_bound(&self) -> bool {
1694         match *self {
1695             ty::ReEarlyBound(..) => true,
1696             ty::ReLateBound(..) => true,
1697             _ => false
1698         }
1699     }
1700
1701     pub fn needs_infer(&self) -> bool {
1702         match *self {
1703             ty::ReVar(..) | ty::ReSkolemized(..) => true,
1704             _ => false
1705         }
1706     }
1707
1708     pub fn escapes_depth(&self, depth: u32) -> bool {
1709         match *self {
1710             ty::ReLateBound(debruijn, _) => debruijn.depth > depth,
1711             _ => false,
1712         }
1713     }
1714
1715     /// Returns the depth of `self` from the (1-based) binding level `depth`
1716     pub fn from_depth(&self, depth: u32) -> Region {
1717         match *self {
1718             ty::ReLateBound(debruijn, r) => ty::ReLateBound(DebruijnIndex {
1719                 depth: debruijn.depth - (depth - 1)
1720             }, r),
1721             r => r
1722         }
1723     }
1724 }
1725
1726 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash,
1727          RustcEncodable, RustcDecodable, Copy)]
1728 /// A "free" region `fr` can be interpreted as "some region
1729 /// at least as big as the scope `fr.scope`".
1730 pub struct FreeRegion {
1731     pub scope: region::CodeExtent,
1732     pub bound_region: BoundRegion
1733 }
1734
1735 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash,
1736          RustcEncodable, RustcDecodable, Copy)]
1737 pub enum BoundRegion {
1738     /// An anonymous region parameter for a given fn (&T)
1739     BrAnon(u32),
1740
1741     /// Named region parameters for functions (a in &'a T)
1742     ///
1743     /// The def-id is needed to distinguish free regions in
1744     /// the event of shadowing.
1745     BrNamed(DefId, ast::Name),
1746
1747     /// Fresh bound identifiers created during GLB computations.
1748     BrFresh(u32),
1749
1750     // Anonymous region for the implicit env pointer parameter
1751     // to a closure
1752     BrEnv
1753 }
1754
1755 // NB: If you change this, you'll probably want to change the corresponding
1756 // AST structure in libsyntax/ast.rs as well.
1757 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
1758 pub enum TypeVariants<'tcx> {
1759     /// The primitive boolean type. Written as `bool`.
1760     TyBool,
1761
1762     /// The primitive character type; holds a Unicode scalar value
1763     /// (a non-surrogate code point).  Written as `char`.
1764     TyChar,
1765
1766     /// A primitive signed integer type. For example, `i32`.
1767     TyInt(ast::IntTy),
1768
1769     /// A primitive unsigned integer type. For example, `u32`.
1770     TyUint(ast::UintTy),
1771
1772     /// A primitive floating-point type. For example, `f64`.
1773     TyFloat(ast::FloatTy),
1774
1775     /// An enumerated type, defined with `enum`.
1776     ///
1777     /// Substs here, possibly against intuition, *may* contain `TyParam`s.
1778     /// That is, even after substitution it is possible that there are type
1779     /// variables. This happens when the `TyEnum` corresponds to an enum
1780     /// definition and not a concrete use of it. To get the correct `TyEnum`
1781     /// from the tcx, use the `NodeId` from the `ast::Ty` and look it up in
1782     /// the `ast_ty_to_ty_cache`. This is probably true for `TyStruct` as
1783     /// well.
1784     TyEnum(AdtDef<'tcx>, &'tcx Substs<'tcx>),
1785
1786     /// A structure type, defined with `struct`.
1787     ///
1788     /// See warning about substitutions for enumerated types.
1789     TyStruct(AdtDef<'tcx>, &'tcx Substs<'tcx>),
1790
1791     /// `Box<T>`; this is nominally a struct in the documentation, but is
1792     /// special-cased internally. For example, it is possible to implicitly
1793     /// move the contents of a box out of that box, and methods of any type
1794     /// can have type `Box<Self>`.
1795     TyBox(Ty<'tcx>),
1796
1797     /// The pointee of a string slice. Written as `str`.
1798     TyStr,
1799
1800     /// An array with the given length. Written as `[T; n]`.
1801     TyArray(Ty<'tcx>, usize),
1802
1803     /// The pointee of an array slice.  Written as `[T]`.
1804     TySlice(Ty<'tcx>),
1805
1806     /// A raw pointer. Written as `*mut T` or `*const T`
1807     TyRawPtr(TypeAndMut<'tcx>),
1808
1809     /// A reference; a pointer with an associated lifetime. Written as
1810     /// `&a mut T` or `&'a T`.
1811     TyRef(&'tcx Region, TypeAndMut<'tcx>),
1812
1813     /// If the def-id is Some(_), then this is the type of a specific
1814     /// fn item. Otherwise, if None(_), it a fn pointer type.
1815     ///
1816     /// FIXME: Conflating function pointers and the type of a
1817     /// function is probably a terrible idea; a function pointer is a
1818     /// value with a specific type, but a function can be polymorphic
1819     /// or dynamically dispatched.
1820     TyBareFn(Option<DefId>, &'tcx BareFnTy<'tcx>),
1821
1822     /// A trait, defined with `trait`.
1823     TyTrait(Box<TraitTy<'tcx>>),
1824
1825     /// The anonymous type of a closure. Used to represent the type of
1826     /// `|a| a`.
1827     TyClosure(DefId, Box<ClosureSubsts<'tcx>>),
1828
1829     /// A tuple type.  For example, `(i32, bool)`.
1830     TyTuple(Vec<Ty<'tcx>>),
1831
1832     /// The projection of an associated type.  For example,
1833     /// `<T as Trait<..>>::N`.
1834     TyProjection(ProjectionTy<'tcx>),
1835
1836     /// A type parameter; for example, `T` in `fn f<T>(x: T) {}
1837     TyParam(ParamTy),
1838
1839     /// A type variable used during type-checking.
1840     TyInfer(InferTy),
1841
1842     /// A placeholder for a type which could not be computed; this is
1843     /// propagated to avoid useless error messages.
1844     TyError,
1845 }
1846
1847 /// A closure can be modeled as a struct that looks like:
1848 ///
1849 ///     struct Closure<'l0...'li, T0...Tj, U0...Uk> {
1850 ///         upvar0: U0,
1851 ///         ...
1852 ///         upvark: Uk
1853 ///     }
1854 ///
1855 /// where 'l0...'li and T0...Tj are the lifetime and type parameters
1856 /// in scope on the function that defined the closure, and U0...Uk are
1857 /// type parameters representing the types of its upvars (borrowed, if
1858 /// appropriate).
1859 ///
1860 /// So, for example, given this function:
1861 ///
1862 ///     fn foo<'a, T>(data: &'a mut T) {
1863 ///          do(|| data.count += 1)
1864 ///     }
1865 ///
1866 /// the type of the closure would be something like:
1867 ///
1868 ///     struct Closure<'a, T, U0> {
1869 ///         data: U0
1870 ///     }
1871 ///
1872 /// Note that the type of the upvar is not specified in the struct.
1873 /// You may wonder how the impl would then be able to use the upvar,
1874 /// if it doesn't know it's type? The answer is that the impl is
1875 /// (conceptually) not fully generic over Closure but rather tied to
1876 /// instances with the expected upvar types:
1877 ///
1878 ///     impl<'b, 'a, T> FnMut() for Closure<'a, T, &'b mut &'a mut T> {
1879 ///         ...
1880 ///     }
1881 ///
1882 /// You can see that the *impl* fully specified the type of the upvar
1883 /// and thus knows full well that `data` has type `&'b mut &'a mut T`.
1884 /// (Here, I am assuming that `data` is mut-borrowed.)
1885 ///
1886 /// Now, the last question you may ask is: Why include the upvar types
1887 /// as extra type parameters? The reason for this design is that the
1888 /// upvar types can reference lifetimes that are internal to the
1889 /// creating function. In my example above, for example, the lifetime
1890 /// `'b` represents the extent of the closure itself; this is some
1891 /// subset of `foo`, probably just the extent of the call to the to
1892 /// `do()`. If we just had the lifetime/type parameters from the
1893 /// enclosing function, we couldn't name this lifetime `'b`. Note that
1894 /// there can also be lifetimes in the types of the upvars themselves,
1895 /// if one of them happens to be a reference to something that the
1896 /// creating fn owns.
1897 ///
1898 /// OK, you say, so why not create a more minimal set of parameters
1899 /// that just includes the extra lifetime parameters? The answer is
1900 /// primarily that it would be hard --- we don't know at the time when
1901 /// we create the closure type what the full types of the upvars are,
1902 /// nor do we know which are borrowed and which are not. In this
1903 /// design, we can just supply a fresh type parameter and figure that
1904 /// out later.
1905 ///
1906 /// All right, you say, but why include the type parameters from the
1907 /// original function then? The answer is that trans may need them
1908 /// when monomorphizing, and they may not appear in the upvars.  A
1909 /// closure could capture no variables but still make use of some
1910 /// in-scope type parameter with a bound (e.g., if our example above
1911 /// had an extra `U: Default`, and the closure called `U::default()`).
1912 ///
1913 /// There is another reason. This design (implicitly) prohibits
1914 /// closures from capturing themselves (except via a trait
1915 /// object). This simplifies closure inference considerably, since it
1916 /// means that when we infer the kind of a closure or its upvars, we
1917 /// don't have to handle cycles where the decisions we make for
1918 /// closure C wind up influencing the decisions we ought to make for
1919 /// closure C (which would then require fixed point iteration to
1920 /// handle). Plus it fixes an ICE. :P
1921 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
1922 pub struct ClosureSubsts<'tcx> {
1923     /// Lifetime and type parameters from the enclosing function.
1924     /// These are separated out because trans wants to pass them around
1925     /// when monomorphizing.
1926     pub func_substs: &'tcx Substs<'tcx>,
1927
1928     /// The types of the upvars. The list parallels the freevars and
1929     /// `upvar_borrows` lists. These are kept distinct so that we can
1930     /// easily index into them.
1931     pub upvar_tys: Vec<Ty<'tcx>>
1932 }
1933
1934 #[derive(Clone, PartialEq, Eq, Hash)]
1935 pub struct TraitTy<'tcx> {
1936     pub principal: ty::PolyTraitRef<'tcx>,
1937     pub bounds: ExistentialBounds<'tcx>,
1938 }
1939
1940 impl<'tcx> TraitTy<'tcx> {
1941     pub fn principal_def_id(&self) -> DefId {
1942         self.principal.0.def_id
1943     }
1944
1945     /// Object types don't have a self-type specified. Therefore, when
1946     /// we convert the principal trait-ref into a normal trait-ref,
1947     /// you must give *some* self-type. A common choice is `mk_err()`
1948     /// or some skolemized type.
1949     pub fn principal_trait_ref_with_self_ty(&self,
1950                                             tcx: &ctxt<'tcx>,
1951                                             self_ty: Ty<'tcx>)
1952                                             -> ty::PolyTraitRef<'tcx>
1953     {
1954         // otherwise the escaping regions would be captured by the binder
1955         assert!(!self_ty.has_escaping_regions());
1956
1957         ty::Binder(TraitRef {
1958             def_id: self.principal.0.def_id,
1959             substs: tcx.mk_substs(self.principal.0.substs.with_self_ty(self_ty)),
1960         })
1961     }
1962
1963     pub fn projection_bounds_with_self_ty(&self,
1964                                           tcx: &ctxt<'tcx>,
1965                                           self_ty: Ty<'tcx>)
1966                                           -> Vec<ty::PolyProjectionPredicate<'tcx>>
1967     {
1968         // otherwise the escaping regions would be captured by the binders
1969         assert!(!self_ty.has_escaping_regions());
1970
1971         self.bounds.projection_bounds.iter()
1972             .map(|in_poly_projection_predicate| {
1973                 let in_projection_ty = &in_poly_projection_predicate.0.projection_ty;
1974                 let substs = tcx.mk_substs(in_projection_ty.trait_ref.substs.with_self_ty(self_ty));
1975                 let trait_ref = ty::TraitRef::new(in_projection_ty.trait_ref.def_id,
1976                                               substs);
1977                 let projection_ty = ty::ProjectionTy {
1978                     trait_ref: trait_ref,
1979                     item_name: in_projection_ty.item_name
1980                 };
1981                 ty::Binder(ty::ProjectionPredicate {
1982                     projection_ty: projection_ty,
1983                     ty: in_poly_projection_predicate.0.ty
1984                 })
1985             })
1986             .collect()
1987     }
1988 }
1989
1990 /// A complete reference to a trait. These take numerous guises in syntax,
1991 /// but perhaps the most recognizable form is in a where clause:
1992 ///
1993 ///     T : Foo<U>
1994 ///
1995 /// This would be represented by a trait-reference where the def-id is the
1996 /// def-id for the trait `Foo` and the substs defines `T` as parameter 0 in the
1997 /// `SelfSpace` and `U` as parameter 0 in the `TypeSpace`.
1998 ///
1999 /// Trait references also appear in object types like `Foo<U>`, but in
2000 /// that case the `Self` parameter is absent from the substitutions.
2001 ///
2002 /// Note that a `TraitRef` introduces a level of region binding, to
2003 /// account for higher-ranked trait bounds like `T : for<'a> Foo<&'a
2004 /// U>` or higher-ranked object types.
2005 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
2006 pub struct TraitRef<'tcx> {
2007     pub def_id: DefId,
2008     pub substs: &'tcx Substs<'tcx>,
2009 }
2010
2011 pub type PolyTraitRef<'tcx> = Binder<TraitRef<'tcx>>;
2012
2013 impl<'tcx> PolyTraitRef<'tcx> {
2014     pub fn self_ty(&self) -> Ty<'tcx> {
2015         self.0.self_ty()
2016     }
2017
2018     pub fn def_id(&self) -> DefId {
2019         self.0.def_id
2020     }
2021
2022     pub fn substs(&self) -> &'tcx Substs<'tcx> {
2023         // FIXME(#20664) every use of this fn is probably a bug, it should yield Binder<>
2024         self.0.substs
2025     }
2026
2027     pub fn input_types(&self) -> &[Ty<'tcx>] {
2028         // FIXME(#20664) every use of this fn is probably a bug, it should yield Binder<>
2029         self.0.input_types()
2030     }
2031
2032     pub fn to_poly_trait_predicate(&self) -> PolyTraitPredicate<'tcx> {
2033         // Note that we preserve binding levels
2034         Binder(TraitPredicate { trait_ref: self.0.clone() })
2035     }
2036 }
2037
2038 /// Binder is a binder for higher-ranked lifetimes. It is part of the
2039 /// compiler's representation for things like `for<'a> Fn(&'a isize)`
2040 /// (which would be represented by the type `PolyTraitRef ==
2041 /// Binder<TraitRef>`). Note that when we skolemize, instantiate,
2042 /// erase, or otherwise "discharge" these bound regions, we change the
2043 /// type from `Binder<T>` to just `T` (see
2044 /// e.g. `liberate_late_bound_regions`).
2045 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
2046 pub struct Binder<T>(pub T);
2047
2048 impl<T> Binder<T> {
2049     /// Skips the binder and returns the "bound" value. This is a
2050     /// risky thing to do because it's easy to get confused about
2051     /// debruijn indices and the like. It is usually better to
2052     /// discharge the binder using `no_late_bound_regions` or
2053     /// `replace_late_bound_regions` or something like
2054     /// that. `skip_binder` is only valid when you are either
2055     /// extracting data that has nothing to do with bound regions, you
2056     /// are doing some sort of test that does not involve bound
2057     /// regions, or you are being very careful about your depth
2058     /// accounting.
2059     ///
2060     /// Some examples where `skip_binder` is reasonable:
2061     /// - extracting the def-id from a PolyTraitRef;
2062     /// - comparing the self type of a PolyTraitRef to see if it is equal to
2063     ///   a type parameter `X`, since the type `X`  does not reference any regions
2064     pub fn skip_binder(&self) -> &T {
2065         &self.0
2066     }
2067
2068     pub fn as_ref(&self) -> Binder<&T> {
2069         ty::Binder(&self.0)
2070     }
2071
2072     pub fn map_bound_ref<F,U>(&self, f: F) -> Binder<U>
2073         where F: FnOnce(&T) -> U
2074     {
2075         self.as_ref().map_bound(f)
2076     }
2077
2078     pub fn map_bound<F,U>(self, f: F) -> Binder<U>
2079         where F: FnOnce(T) -> U
2080     {
2081         ty::Binder(f(self.0))
2082     }
2083 }
2084
2085 #[derive(Clone, Copy, PartialEq)]
2086 pub enum IntVarValue {
2087     IntType(ast::IntTy),
2088     UintType(ast::UintTy),
2089 }
2090
2091 #[derive(Clone, Copy, Debug)]
2092 pub struct ExpectedFound<T> {
2093     pub expected: T,
2094     pub found: T
2095 }
2096
2097 // Data structures used in type unification
2098 #[derive(Clone, Debug)]
2099 pub enum TypeError<'tcx> {
2100     Mismatch,
2101     UnsafetyMismatch(ExpectedFound<ast::Unsafety>),
2102     AbiMismatch(ExpectedFound<abi::Abi>),
2103     Mutability,
2104     BoxMutability,
2105     PtrMutability,
2106     RefMutability,
2107     VecMutability,
2108     TupleSize(ExpectedFound<usize>),
2109     FixedArraySize(ExpectedFound<usize>),
2110     TyParamSize(ExpectedFound<usize>),
2111     ArgCount,
2112     RegionsDoesNotOutlive(Region, Region),
2113     RegionsNotSame(Region, Region),
2114     RegionsNoOverlap(Region, Region),
2115     RegionsInsufficientlyPolymorphic(BoundRegion, Region),
2116     RegionsOverlyPolymorphic(BoundRegion, Region),
2117     Sorts(ExpectedFound<Ty<'tcx>>),
2118     IntegerAsChar,
2119     IntMismatch(ExpectedFound<IntVarValue>),
2120     FloatMismatch(ExpectedFound<ast::FloatTy>),
2121     Traits(ExpectedFound<DefId>),
2122     BuiltinBoundsMismatch(ExpectedFound<BuiltinBounds>),
2123     VariadicMismatch(ExpectedFound<bool>),
2124     CyclicTy,
2125     ConvergenceMismatch(ExpectedFound<bool>),
2126     ProjectionNameMismatched(ExpectedFound<ast::Name>),
2127     ProjectionBoundsLength(ExpectedFound<usize>),
2128     TyParamDefaultMismatch(ExpectedFound<type_variable::Default<'tcx>>)
2129 }
2130
2131 /// Bounds suitable for an existentially quantified type parameter
2132 /// such as those that appear in object types or closure types.
2133 #[derive(PartialEq, Eq, Hash, Clone)]
2134 pub struct ExistentialBounds<'tcx> {
2135     pub region_bound: ty::Region,
2136     pub builtin_bounds: BuiltinBounds,
2137     pub projection_bounds: Vec<PolyProjectionPredicate<'tcx>>,
2138 }
2139
2140 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
2141 pub struct BuiltinBounds(EnumSet<BuiltinBound>);
2142
2143 impl BuiltinBounds {
2144     pub fn empty() -> BuiltinBounds {
2145         BuiltinBounds(EnumSet::new())
2146     }
2147
2148     pub fn iter(&self) -> enum_set::Iter<BuiltinBound> {
2149         self.into_iter()
2150     }
2151
2152     pub fn to_predicates<'tcx>(&self,
2153                                tcx: &ty::ctxt<'tcx>,
2154                                self_ty: Ty<'tcx>) -> Vec<Predicate<'tcx>> {
2155         self.iter().filter_map(|builtin_bound|
2156             match traits::trait_ref_for_builtin_bound(tcx, builtin_bound, self_ty) {
2157                 Ok(trait_ref) => Some(trait_ref.to_predicate()),
2158                 Err(ErrorReported) => { None }
2159             }
2160         ).collect()
2161     }
2162 }
2163
2164 impl ops::Deref for BuiltinBounds {
2165     type Target = EnumSet<BuiltinBound>;
2166     fn deref(&self) -> &Self::Target { &self.0 }
2167 }
2168
2169 impl ops::DerefMut for BuiltinBounds {
2170     fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 }
2171 }
2172
2173 impl<'a> IntoIterator for &'a BuiltinBounds {
2174     type Item = BuiltinBound;
2175     type IntoIter = enum_set::Iter<BuiltinBound>;
2176     fn into_iter(self) -> Self::IntoIter {
2177         (**self).into_iter()
2178     }
2179 }
2180
2181 #[derive(Clone, RustcEncodable, PartialEq, Eq, RustcDecodable, Hash,
2182            Debug, Copy)]
2183 #[repr(usize)]
2184 pub enum BuiltinBound {
2185     Send,
2186     Sized,
2187     Copy,
2188     Sync,
2189 }
2190
2191 impl CLike for BuiltinBound {
2192     fn to_usize(&self) -> usize {
2193         *self as usize
2194     }
2195     fn from_usize(v: usize) -> BuiltinBound {
2196         unsafe { mem::transmute(v) }
2197     }
2198 }
2199
2200 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
2201 pub struct TyVid {
2202     pub index: u32
2203 }
2204
2205 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
2206 pub struct IntVid {
2207     pub index: u32
2208 }
2209
2210 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
2211 pub struct FloatVid {
2212     pub index: u32
2213 }
2214
2215 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
2216 pub struct RegionVid {
2217     pub index: u32
2218 }
2219
2220 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
2221 pub struct SkolemizedRegionVid {
2222     pub index: u32
2223 }
2224
2225 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
2226 pub enum InferTy {
2227     TyVar(TyVid),
2228     IntVar(IntVid),
2229     FloatVar(FloatVid),
2230
2231     /// A `FreshTy` is one that is generated as a replacement for an
2232     /// unbound type variable. This is convenient for caching etc. See
2233     /// `middle::infer::freshen` for more details.
2234     FreshTy(u32),
2235     FreshIntTy(u32),
2236     FreshFloatTy(u32)
2237 }
2238
2239 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Debug, Copy)]
2240 pub enum UnconstrainedNumeric {
2241     UnconstrainedFloat,
2242     UnconstrainedInt,
2243     Neither,
2244 }
2245
2246
2247 impl fmt::Debug for TyVid {
2248     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2249         write!(f, "_#{}t", self.index)
2250     }
2251 }
2252
2253 impl fmt::Debug for IntVid {
2254     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2255         write!(f, "_#{}i", self.index)
2256     }
2257 }
2258
2259 impl fmt::Debug for FloatVid {
2260     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2261         write!(f, "_#{}f", self.index)
2262     }
2263 }
2264
2265 impl fmt::Debug for RegionVid {
2266     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2267         write!(f, "'_#{}r", self.index)
2268     }
2269 }
2270
2271 impl<'tcx> fmt::Debug for FnSig<'tcx> {
2272     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2273         write!(f, "({:?}; variadic: {})->{:?}", self.inputs, self.variadic, self.output)
2274     }
2275 }
2276
2277 impl fmt::Debug for InferTy {
2278     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2279         match *self {
2280             TyVar(ref v) => v.fmt(f),
2281             IntVar(ref v) => v.fmt(f),
2282             FloatVar(ref v) => v.fmt(f),
2283             FreshTy(v) => write!(f, "FreshTy({:?})", v),
2284             FreshIntTy(v) => write!(f, "FreshIntTy({:?})", v),
2285             FreshFloatTy(v) => write!(f, "FreshFloatTy({:?})", v)
2286         }
2287     }
2288 }
2289
2290 impl fmt::Debug for IntVarValue {
2291     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2292         match *self {
2293             IntType(ref v) => v.fmt(f),
2294             UintType(ref v) => v.fmt(f),
2295         }
2296     }
2297 }
2298
2299 /// Default region to use for the bound of objects that are
2300 /// supplied as the value for this type parameter. This is derived
2301 /// from `T:'a` annotations appearing in the type definition.  If
2302 /// this is `None`, then the default is inherited from the
2303 /// surrounding context. See RFC #599 for details.
2304 #[derive(Copy, Clone)]
2305 pub enum ObjectLifetimeDefault {
2306     /// Require an explicit annotation. Occurs when multiple
2307     /// `T:'a` constraints are found.
2308     Ambiguous,
2309
2310     /// Use the base default, typically 'static, but in a fn body it is a fresh variable
2311     BaseDefault,
2312
2313     /// Use the given region as the default.
2314     Specific(Region),
2315 }
2316
2317 #[derive(Clone)]
2318 pub struct TypeParameterDef<'tcx> {
2319     pub name: ast::Name,
2320     pub def_id: DefId,
2321     pub space: subst::ParamSpace,
2322     pub index: u32,
2323     pub default_def_id: DefId, // for use in error reporing about defaults
2324     pub default: Option<Ty<'tcx>>,
2325     pub object_lifetime_default: ObjectLifetimeDefault,
2326 }
2327
2328 #[derive(Clone)]
2329 pub struct RegionParameterDef {
2330     pub name: ast::Name,
2331     pub def_id: DefId,
2332     pub space: subst::ParamSpace,
2333     pub index: u32,
2334     pub bounds: Vec<ty::Region>,
2335 }
2336
2337 impl RegionParameterDef {
2338     pub fn to_early_bound_region(&self) -> ty::Region {
2339         ty::ReEarlyBound(ty::EarlyBoundRegion {
2340             param_id: self.def_id.node,
2341             space: self.space,
2342             index: self.index,
2343             name: self.name,
2344         })
2345     }
2346     pub fn to_bound_region(&self) -> ty::BoundRegion {
2347         ty::BoundRegion::BrNamed(self.def_id, self.name)
2348     }
2349 }
2350
2351 /// Information about the formal type/lifetime parameters associated
2352 /// with an item or method. Analogous to ast::Generics.
2353 #[derive(Clone, Debug)]
2354 pub struct Generics<'tcx> {
2355     pub types: VecPerParamSpace<TypeParameterDef<'tcx>>,
2356     pub regions: VecPerParamSpace<RegionParameterDef>,
2357 }
2358
2359 impl<'tcx> Generics<'tcx> {
2360     pub fn empty() -> Generics<'tcx> {
2361         Generics {
2362             types: VecPerParamSpace::empty(),
2363             regions: VecPerParamSpace::empty(),
2364         }
2365     }
2366
2367     pub fn is_empty(&self) -> bool {
2368         self.types.is_empty() && self.regions.is_empty()
2369     }
2370
2371     pub fn has_type_params(&self, space: subst::ParamSpace) -> bool {
2372         !self.types.is_empty_in(space)
2373     }
2374
2375     pub fn has_region_params(&self, space: subst::ParamSpace) -> bool {
2376         !self.regions.is_empty_in(space)
2377     }
2378 }
2379
2380 /// Bounds on generics.
2381 #[derive(Clone)]
2382 pub struct GenericPredicates<'tcx> {
2383     pub predicates: VecPerParamSpace<Predicate<'tcx>>,
2384 }
2385
2386 impl<'tcx> GenericPredicates<'tcx> {
2387     pub fn empty() -> GenericPredicates<'tcx> {
2388         GenericPredicates {
2389             predicates: VecPerParamSpace::empty(),
2390         }
2391     }
2392
2393     pub fn instantiate(&self, tcx: &ctxt<'tcx>, substs: &Substs<'tcx>)
2394                        -> InstantiatedPredicates<'tcx> {
2395         InstantiatedPredicates {
2396             predicates: self.predicates.subst(tcx, substs),
2397         }
2398     }
2399
2400     pub fn instantiate_supertrait(&self,
2401                                   tcx: &ctxt<'tcx>,
2402                                   poly_trait_ref: &ty::PolyTraitRef<'tcx>)
2403                                   -> InstantiatedPredicates<'tcx>
2404     {
2405         InstantiatedPredicates {
2406             predicates: self.predicates.map(|pred| pred.subst_supertrait(tcx, poly_trait_ref))
2407         }
2408     }
2409 }
2410
2411 #[derive(Clone, PartialEq, Eq, Hash)]
2412 pub enum Predicate<'tcx> {
2413     /// Corresponds to `where Foo : Bar<A,B,C>`. `Foo` here would be
2414     /// the `Self` type of the trait reference and `A`, `B`, and `C`
2415     /// would be the parameters in the `TypeSpace`.
2416     Trait(PolyTraitPredicate<'tcx>),
2417
2418     /// where `T1 == T2`.
2419     Equate(PolyEquatePredicate<'tcx>),
2420
2421     /// where 'a : 'b
2422     RegionOutlives(PolyRegionOutlivesPredicate),
2423
2424     /// where T : 'a
2425     TypeOutlives(PolyTypeOutlivesPredicate<'tcx>),
2426
2427     /// where <T as TraitRef>::Name == X, approximately.
2428     /// See `ProjectionPredicate` struct for details.
2429     Projection(PolyProjectionPredicate<'tcx>),
2430
2431     /// no syntax: T WF
2432     WellFormed(Ty<'tcx>),
2433
2434     /// trait must be object-safe
2435     ObjectSafe(DefId),
2436 }
2437
2438 impl<'tcx> Predicate<'tcx> {
2439     /// Performs a substitution suitable for going from a
2440     /// poly-trait-ref to supertraits that must hold if that
2441     /// poly-trait-ref holds. This is slightly different from a normal
2442     /// substitution in terms of what happens with bound regions.  See
2443     /// lengthy comment below for details.
2444     pub fn subst_supertrait(&self,
2445                             tcx: &ctxt<'tcx>,
2446                             trait_ref: &ty::PolyTraitRef<'tcx>)
2447                             -> ty::Predicate<'tcx>
2448     {
2449         // The interaction between HRTB and supertraits is not entirely
2450         // obvious. Let me walk you (and myself) through an example.
2451         //
2452         // Let's start with an easy case. Consider two traits:
2453         //
2454         //     trait Foo<'a> : Bar<'a,'a> { }
2455         //     trait Bar<'b,'c> { }
2456         //
2457         // Now, if we have a trait reference `for<'x> T : Foo<'x>`, then
2458         // we can deduce that `for<'x> T : Bar<'x,'x>`. Basically, if we
2459         // knew that `Foo<'x>` (for any 'x) then we also know that
2460         // `Bar<'x,'x>` (for any 'x). This more-or-less falls out from
2461         // normal substitution.
2462         //
2463         // In terms of why this is sound, the idea is that whenever there
2464         // is an impl of `T:Foo<'a>`, it must show that `T:Bar<'a,'a>`
2465         // holds.  So if there is an impl of `T:Foo<'a>` that applies to
2466         // all `'a`, then we must know that `T:Bar<'a,'a>` holds for all
2467         // `'a`.
2468         //
2469         // Another example to be careful of is this:
2470         //
2471         //     trait Foo1<'a> : for<'b> Bar1<'a,'b> { }
2472         //     trait Bar1<'b,'c> { }
2473         //
2474         // Here, if we have `for<'x> T : Foo1<'x>`, then what do we know?
2475         // The answer is that we know `for<'x,'b> T : Bar1<'x,'b>`. The
2476         // reason is similar to the previous example: any impl of
2477         // `T:Foo1<'x>` must show that `for<'b> T : Bar1<'x, 'b>`.  So
2478         // basically we would want to collapse the bound lifetimes from
2479         // the input (`trait_ref`) and the supertraits.
2480         //
2481         // To achieve this in practice is fairly straightforward. Let's
2482         // consider the more complicated scenario:
2483         //
2484         // - We start out with `for<'x> T : Foo1<'x>`. In this case, `'x`
2485         //   has a De Bruijn index of 1. We want to produce `for<'x,'b> T : Bar1<'x,'b>`,
2486         //   where both `'x` and `'b` would have a DB index of 1.
2487         //   The substitution from the input trait-ref is therefore going to be
2488         //   `'a => 'x` (where `'x` has a DB index of 1).
2489         // - The super-trait-ref is `for<'b> Bar1<'a,'b>`, where `'a` is an
2490         //   early-bound parameter and `'b' is a late-bound parameter with a
2491         //   DB index of 1.
2492         // - If we replace `'a` with `'x` from the input, it too will have
2493         //   a DB index of 1, and thus we'll have `for<'x,'b> Bar1<'x,'b>`
2494         //   just as we wanted.
2495         //
2496         // There is only one catch. If we just apply the substitution `'a
2497         // => 'x` to `for<'b> Bar1<'a,'b>`, the substitution code will
2498         // adjust the DB index because we substituting into a binder (it
2499         // tries to be so smart...) resulting in `for<'x> for<'b>
2500         // Bar1<'x,'b>` (we have no syntax for this, so use your
2501         // imagination). Basically the 'x will have DB index of 2 and 'b
2502         // will have DB index of 1. Not quite what we want. So we apply
2503         // the substitution to the *contents* of the trait reference,
2504         // rather than the trait reference itself (put another way, the
2505         // substitution code expects equal binding levels in the values
2506         // from the substitution and the value being substituted into, and
2507         // this trick achieves that).
2508
2509         let substs = &trait_ref.0.substs;
2510         match *self {
2511             Predicate::Trait(ty::Binder(ref data)) =>
2512                 Predicate::Trait(ty::Binder(data.subst(tcx, substs))),
2513             Predicate::Equate(ty::Binder(ref data)) =>
2514                 Predicate::Equate(ty::Binder(data.subst(tcx, substs))),
2515             Predicate::RegionOutlives(ty::Binder(ref data)) =>
2516                 Predicate::RegionOutlives(ty::Binder(data.subst(tcx, substs))),
2517             Predicate::TypeOutlives(ty::Binder(ref data)) =>
2518                 Predicate::TypeOutlives(ty::Binder(data.subst(tcx, substs))),
2519             Predicate::Projection(ty::Binder(ref data)) =>
2520                 Predicate::Projection(ty::Binder(data.subst(tcx, substs))),
2521             Predicate::WellFormed(data) =>
2522                 Predicate::WellFormed(data.subst(tcx, substs)),
2523             Predicate::ObjectSafe(trait_def_id) =>
2524                 Predicate::ObjectSafe(trait_def_id),
2525         }
2526     }
2527 }
2528
2529 #[derive(Clone, PartialEq, Eq, Hash)]
2530 pub struct TraitPredicate<'tcx> {
2531     pub trait_ref: TraitRef<'tcx>
2532 }
2533 pub type PolyTraitPredicate<'tcx> = ty::Binder<TraitPredicate<'tcx>>;
2534
2535 impl<'tcx> TraitPredicate<'tcx> {
2536     pub fn def_id(&self) -> DefId {
2537         self.trait_ref.def_id
2538     }
2539
2540     pub fn input_types(&self) -> &[Ty<'tcx>] {
2541         self.trait_ref.substs.types.as_slice()
2542     }
2543
2544     pub fn self_ty(&self) -> Ty<'tcx> {
2545         self.trait_ref.self_ty()
2546     }
2547 }
2548
2549 impl<'tcx> PolyTraitPredicate<'tcx> {
2550     pub fn def_id(&self) -> DefId {
2551         self.0.def_id()
2552     }
2553 }
2554
2555 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
2556 pub struct EquatePredicate<'tcx>(pub Ty<'tcx>, pub Ty<'tcx>); // `0 == 1`
2557 pub type PolyEquatePredicate<'tcx> = ty::Binder<EquatePredicate<'tcx>>;
2558
2559 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
2560 pub struct OutlivesPredicate<A,B>(pub A, pub B); // `A : B`
2561 pub type PolyOutlivesPredicate<A,B> = ty::Binder<OutlivesPredicate<A,B>>;
2562 pub type PolyRegionOutlivesPredicate = PolyOutlivesPredicate<ty::Region, ty::Region>;
2563 pub type PolyTypeOutlivesPredicate<'tcx> = PolyOutlivesPredicate<Ty<'tcx>, ty::Region>;
2564
2565 /// This kind of predicate has no *direct* correspondent in the
2566 /// syntax, but it roughly corresponds to the syntactic forms:
2567 ///
2568 /// 1. `T : TraitRef<..., Item=Type>`
2569 /// 2. `<T as TraitRef<...>>::Item == Type` (NYI)
2570 ///
2571 /// In particular, form #1 is "desugared" to the combination of a
2572 /// normal trait predicate (`T : TraitRef<...>`) and one of these
2573 /// predicates. Form #2 is a broader form in that it also permits
2574 /// equality between arbitrary types. Processing an instance of Form
2575 /// #2 eventually yields one of these `ProjectionPredicate`
2576 /// instances to normalize the LHS.
2577 #[derive(Clone, PartialEq, Eq, Hash)]
2578 pub struct ProjectionPredicate<'tcx> {
2579     pub projection_ty: ProjectionTy<'tcx>,
2580     pub ty: Ty<'tcx>,
2581 }
2582
2583 pub type PolyProjectionPredicate<'tcx> = Binder<ProjectionPredicate<'tcx>>;
2584
2585 impl<'tcx> PolyProjectionPredicate<'tcx> {
2586     pub fn item_name(&self) -> ast::Name {
2587         self.0.projection_ty.item_name // safe to skip the binder to access a name
2588     }
2589
2590     pub fn sort_key(&self) -> (DefId, ast::Name) {
2591         self.0.projection_ty.sort_key()
2592     }
2593 }
2594
2595 /// Represents the projection of an associated type. In explicit UFCS
2596 /// form this would be written `<T as Trait<..>>::N`.
2597 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
2598 pub struct ProjectionTy<'tcx> {
2599     /// The trait reference `T as Trait<..>`.
2600     pub trait_ref: ty::TraitRef<'tcx>,
2601
2602     /// The name `N` of the associated type.
2603     pub item_name: ast::Name,
2604 }
2605
2606 impl<'tcx> ProjectionTy<'tcx> {
2607     pub fn sort_key(&self) -> (DefId, ast::Name) {
2608         (self.trait_ref.def_id, self.item_name)
2609     }
2610 }
2611
2612 pub trait ToPolyTraitRef<'tcx> {
2613     fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx>;
2614 }
2615
2616 impl<'tcx> ToPolyTraitRef<'tcx> for TraitRef<'tcx> {
2617     fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
2618         assert!(!self.has_escaping_regions());
2619         ty::Binder(self.clone())
2620     }
2621 }
2622
2623 impl<'tcx> ToPolyTraitRef<'tcx> for PolyTraitPredicate<'tcx> {
2624     fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
2625         self.map_bound_ref(|trait_pred| trait_pred.trait_ref.clone())
2626     }
2627 }
2628
2629 impl<'tcx> ToPolyTraitRef<'tcx> for PolyProjectionPredicate<'tcx> {
2630     fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
2631         // Note: unlike with TraitRef::to_poly_trait_ref(),
2632         // self.0.trait_ref is permitted to have escaping regions.
2633         // This is because here `self` has a `Binder` and so does our
2634         // return value, so we are preserving the number of binding
2635         // levels.
2636         ty::Binder(self.0.projection_ty.trait_ref.clone())
2637     }
2638 }
2639
2640 pub trait ToPredicate<'tcx> {
2641     fn to_predicate(&self) -> Predicate<'tcx>;
2642 }
2643
2644 impl<'tcx> ToPredicate<'tcx> for TraitRef<'tcx> {
2645     fn to_predicate(&self) -> Predicate<'tcx> {
2646         // we're about to add a binder, so let's check that we don't
2647         // accidentally capture anything, or else that might be some
2648         // weird debruijn accounting.
2649         assert!(!self.has_escaping_regions());
2650
2651         ty::Predicate::Trait(ty::Binder(ty::TraitPredicate {
2652             trait_ref: self.clone()
2653         }))
2654     }
2655 }
2656
2657 impl<'tcx> ToPredicate<'tcx> for PolyTraitRef<'tcx> {
2658     fn to_predicate(&self) -> Predicate<'tcx> {
2659         ty::Predicate::Trait(self.to_poly_trait_predicate())
2660     }
2661 }
2662
2663 impl<'tcx> ToPredicate<'tcx> for PolyEquatePredicate<'tcx> {
2664     fn to_predicate(&self) -> Predicate<'tcx> {
2665         Predicate::Equate(self.clone())
2666     }
2667 }
2668
2669 impl<'tcx> ToPredicate<'tcx> for PolyRegionOutlivesPredicate {
2670     fn to_predicate(&self) -> Predicate<'tcx> {
2671         Predicate::RegionOutlives(self.clone())
2672     }
2673 }
2674
2675 impl<'tcx> ToPredicate<'tcx> for PolyTypeOutlivesPredicate<'tcx> {
2676     fn to_predicate(&self) -> Predicate<'tcx> {
2677         Predicate::TypeOutlives(self.clone())
2678     }
2679 }
2680
2681 impl<'tcx> ToPredicate<'tcx> for PolyProjectionPredicate<'tcx> {
2682     fn to_predicate(&self) -> Predicate<'tcx> {
2683         Predicate::Projection(self.clone())
2684     }
2685 }
2686
2687 impl<'tcx> Predicate<'tcx> {
2688     /// Iterates over the types in this predicate. Note that in all
2689     /// cases this is skipping over a binder, so late-bound regions
2690     /// with depth 0 are bound by the predicate.
2691     pub fn walk_tys(&self) -> IntoIter<Ty<'tcx>> {
2692         let vec: Vec<_> = match *self {
2693             ty::Predicate::Trait(ref data) => {
2694                 data.0.trait_ref.substs.types.as_slice().to_vec()
2695             }
2696             ty::Predicate::Equate(ty::Binder(ref data)) => {
2697                 vec![data.0, data.1]
2698             }
2699             ty::Predicate::TypeOutlives(ty::Binder(ref data)) => {
2700                 vec![data.0]
2701             }
2702             ty::Predicate::RegionOutlives(..) => {
2703                 vec![]
2704             }
2705             ty::Predicate::Projection(ref data) => {
2706                 let trait_inputs = data.0.projection_ty.trait_ref.substs.types.as_slice();
2707                 trait_inputs.iter()
2708                             .cloned()
2709                             .chain(Some(data.0.ty))
2710                             .collect()
2711             }
2712             ty::Predicate::WellFormed(data) => {
2713                 vec![data]
2714             }
2715             ty::Predicate::ObjectSafe(_trait_def_id) => {
2716                 vec![]
2717             }
2718         };
2719
2720         // The only reason to collect into a vector here is that I was
2721         // too lazy to make the full (somewhat complicated) iterator
2722         // type that would be needed here. But I wanted this fn to
2723         // return an iterator conceptually, rather than a `Vec`, so as
2724         // to be closer to `Ty::walk`.
2725         vec.into_iter()
2726     }
2727
2728     pub fn has_escaping_regions(&self) -> bool {
2729         match *self {
2730             Predicate::Trait(ref trait_ref) => trait_ref.has_escaping_regions(),
2731             Predicate::Equate(ref p) => p.has_escaping_regions(),
2732             Predicate::RegionOutlives(ref p) => p.has_escaping_regions(),
2733             Predicate::TypeOutlives(ref p) => p.has_escaping_regions(),
2734             Predicate::Projection(ref p) => p.has_escaping_regions(),
2735             Predicate::WellFormed(p) => p.has_escaping_regions(),
2736             Predicate::ObjectSafe(_trait_def_id) => false,
2737         }
2738     }
2739
2740     pub fn to_opt_poly_trait_ref(&self) -> Option<PolyTraitRef<'tcx>> {
2741         match *self {
2742             Predicate::Trait(ref t) => {
2743                 Some(t.to_poly_trait_ref())
2744             }
2745             Predicate::Projection(..) |
2746             Predicate::Equate(..) |
2747             Predicate::RegionOutlives(..) |
2748             Predicate::WellFormed(..) |
2749             Predicate::ObjectSafe(..) |
2750             Predicate::TypeOutlives(..) => {
2751                 None
2752             }
2753         }
2754     }
2755 }
2756
2757 /// Represents the bounds declared on a particular set of type
2758 /// parameters.  Should eventually be generalized into a flag list of
2759 /// where clauses.  You can obtain a `InstantiatedPredicates` list from a
2760 /// `GenericPredicates` by using the `instantiate` method. Note that this method
2761 /// reflects an important semantic invariant of `InstantiatedPredicates`: while
2762 /// the `GenericPredicates` are expressed in terms of the bound type
2763 /// parameters of the impl/trait/whatever, an `InstantiatedPredicates` instance
2764 /// represented a set of bounds for some particular instantiation,
2765 /// meaning that the generic parameters have been substituted with
2766 /// their values.
2767 ///
2768 /// Example:
2769 ///
2770 ///     struct Foo<T,U:Bar<T>> { ... }
2771 ///
2772 /// Here, the `GenericPredicates` for `Foo` would contain a list of bounds like
2773 /// `[[], [U:Bar<T>]]`.  Now if there were some particular reference
2774 /// like `Foo<isize,usize>`, then the `InstantiatedPredicates` would be `[[],
2775 /// [usize:Bar<isize>]]`.
2776 #[derive(Clone)]
2777 pub struct InstantiatedPredicates<'tcx> {
2778     pub predicates: VecPerParamSpace<Predicate<'tcx>>,
2779 }
2780
2781 impl<'tcx> InstantiatedPredicates<'tcx> {
2782     pub fn empty() -> InstantiatedPredicates<'tcx> {
2783         InstantiatedPredicates { predicates: VecPerParamSpace::empty() }
2784     }
2785
2786     pub fn has_escaping_regions(&self) -> bool {
2787         self.predicates.any(|p| p.has_escaping_regions())
2788     }
2789
2790     pub fn is_empty(&self) -> bool {
2791         self.predicates.is_empty()
2792     }
2793 }
2794
2795 impl<'tcx> TraitRef<'tcx> {
2796     pub fn new(def_id: DefId, substs: &'tcx Substs<'tcx>) -> TraitRef<'tcx> {
2797         TraitRef { def_id: def_id, substs: substs }
2798     }
2799
2800     pub fn self_ty(&self) -> Ty<'tcx> {
2801         self.substs.self_ty().unwrap()
2802     }
2803
2804     pub fn input_types(&self) -> &[Ty<'tcx>] {
2805         // Select only the "input types" from a trait-reference. For
2806         // now this is all the types that appear in the
2807         // trait-reference, but it should eventually exclude
2808         // associated types.
2809         self.substs.types.as_slice()
2810     }
2811 }
2812
2813 /// When type checking, we use the `ParameterEnvironment` to track
2814 /// details about the type/lifetime parameters that are in scope.
2815 /// It primarily stores the bounds information.
2816 ///
2817 /// Note: This information might seem to be redundant with the data in
2818 /// `tcx.ty_param_defs`, but it is not. That table contains the
2819 /// parameter definitions from an "outside" perspective, but this
2820 /// struct will contain the bounds for a parameter as seen from inside
2821 /// the function body. Currently the only real distinction is that
2822 /// bound lifetime parameters are replaced with free ones, but in the
2823 /// future I hope to refine the representation of types so as to make
2824 /// more distinctions clearer.
2825 #[derive(Clone)]
2826 pub struct ParameterEnvironment<'a, 'tcx:'a> {
2827     pub tcx: &'a ctxt<'tcx>,
2828
2829     /// See `construct_free_substs` for details.
2830     pub free_substs: Substs<'tcx>,
2831
2832     /// Each type parameter has an implicit region bound that
2833     /// indicates it must outlive at least the function body (the user
2834     /// may specify stronger requirements). This field indicates the
2835     /// region of the callee.
2836     pub implicit_region_bound: ty::Region,
2837
2838     /// Obligations that the caller must satisfy. This is basically
2839     /// the set of bounds on the in-scope type parameters, translated
2840     /// into Obligations, and elaborated and normalized.
2841     pub caller_bounds: Vec<ty::Predicate<'tcx>>,
2842
2843     /// Caches the results of trait selection. This cache is used
2844     /// for things that have to do with the parameters in scope.
2845     pub selection_cache: traits::SelectionCache<'tcx>,
2846
2847     /// Scope that is attached to free regions for this scope. This
2848     /// is usually the id of the fn body, but for more abstract scopes
2849     /// like structs we often use the node-id of the struct.
2850     ///
2851     /// FIXME(#3696). It would be nice to refactor so that free
2852     /// regions don't have this implicit scope and instead introduce
2853     /// relationships in the environment.
2854     pub free_id: ast::NodeId,
2855 }
2856
2857 impl<'a, 'tcx> ParameterEnvironment<'a, 'tcx> {
2858     pub fn with_caller_bounds(&self,
2859                               caller_bounds: Vec<ty::Predicate<'tcx>>)
2860                               -> ParameterEnvironment<'a,'tcx>
2861     {
2862         ParameterEnvironment {
2863             tcx: self.tcx,
2864             free_substs: self.free_substs.clone(),
2865             implicit_region_bound: self.implicit_region_bound,
2866             caller_bounds: caller_bounds,
2867             selection_cache: traits::SelectionCache::new(),
2868             free_id: self.free_id,
2869         }
2870     }
2871
2872     pub fn for_item(cx: &'a ctxt<'tcx>, id: NodeId) -> ParameterEnvironment<'a, 'tcx> {
2873         match cx.map.find(id) {
2874             Some(ast_map::NodeImplItem(ref impl_item)) => {
2875                 match impl_item.node {
2876                     ast::TypeImplItem(_) => {
2877                         // associated types don't have their own entry (for some reason),
2878                         // so for now just grab environment for the impl
2879                         let impl_id = cx.map.get_parent(id);
2880                         let impl_def_id = DefId::local(impl_id);
2881                         let scheme = cx.lookup_item_type(impl_def_id);
2882                         let predicates = cx.lookup_predicates(impl_def_id);
2883                         cx.construct_parameter_environment(impl_item.span,
2884                                                            &scheme.generics,
2885                                                            &predicates,
2886                                                            id)
2887                     }
2888                     ast::ConstImplItem(_, _) => {
2889                         let def_id = DefId::local(id);
2890                         let scheme = cx.lookup_item_type(def_id);
2891                         let predicates = cx.lookup_predicates(def_id);
2892                         cx.construct_parameter_environment(impl_item.span,
2893                                                            &scheme.generics,
2894                                                            &predicates,
2895                                                            id)
2896                     }
2897                     ast::MethodImplItem(_, ref body) => {
2898                         let method_def_id = DefId::local(id);
2899                         match cx.impl_or_trait_item(method_def_id) {
2900                             MethodTraitItem(ref method_ty) => {
2901                                 let method_generics = &method_ty.generics;
2902                                 let method_bounds = &method_ty.predicates;
2903                                 cx.construct_parameter_environment(
2904                                     impl_item.span,
2905                                     method_generics,
2906                                     method_bounds,
2907                                     body.id)
2908                             }
2909                             _ => {
2910                                 cx.sess
2911                                   .bug("ParameterEnvironment::for_item(): \
2912                                         got non-method item from impl method?!")
2913                             }
2914                         }
2915                     }
2916                     ast::MacImplItem(_) => cx.sess.bug("unexpanded macro")
2917                 }
2918             }
2919             Some(ast_map::NodeTraitItem(trait_item)) => {
2920                 match trait_item.node {
2921                     ast::TypeTraitItem(..) => {
2922                         // associated types don't have their own entry (for some reason),
2923                         // so for now just grab environment for the trait
2924                         let trait_id = cx.map.get_parent(id);
2925                         let trait_def_id = DefId::local(trait_id);
2926                         let trait_def = cx.lookup_trait_def(trait_def_id);
2927                         let predicates = cx.lookup_predicates(trait_def_id);
2928                         cx.construct_parameter_environment(trait_item.span,
2929                                                            &trait_def.generics,
2930                                                            &predicates,
2931                                                            id)
2932                     }
2933                     ast::ConstTraitItem(..) => {
2934                         let def_id = DefId::local(id);
2935                         let scheme = cx.lookup_item_type(def_id);
2936                         let predicates = cx.lookup_predicates(def_id);
2937                         cx.construct_parameter_environment(trait_item.span,
2938                                                            &scheme.generics,
2939                                                            &predicates,
2940                                                            id)
2941                     }
2942                     ast::MethodTraitItem(_, ref body) => {
2943                         // for the body-id, use the id of the body
2944                         // block, unless this is a trait method with
2945                         // no default, then fallback to the method id.
2946                         let body_id = body.as_ref().map(|b| b.id).unwrap_or(id);
2947                         let method_def_id = DefId::local(id);
2948                         match cx.impl_or_trait_item(method_def_id) {
2949                             MethodTraitItem(ref method_ty) => {
2950                                 let method_generics = &method_ty.generics;
2951                                 let method_bounds = &method_ty.predicates;
2952                                 cx.construct_parameter_environment(
2953                                     trait_item.span,
2954                                     method_generics,
2955                                     method_bounds,
2956                                     body_id)
2957                             }
2958                             _ => {
2959                                 cx.sess
2960                                   .bug("ParameterEnvironment::for_item(): \
2961                                         got non-method item from provided \
2962                                         method?!")
2963                             }
2964                         }
2965                     }
2966                 }
2967             }
2968             Some(ast_map::NodeItem(item)) => {
2969                 match item.node {
2970                     ast::ItemFn(_, _, _, _, _, ref body) => {
2971                         // We assume this is a function.
2972                         let fn_def_id = DefId::local(id);
2973                         let fn_scheme = cx.lookup_item_type(fn_def_id);
2974                         let fn_predicates = cx.lookup_predicates(fn_def_id);
2975
2976                         cx.construct_parameter_environment(item.span,
2977                                                            &fn_scheme.generics,
2978                                                            &fn_predicates,
2979                                                            body.id)
2980                     }
2981                     ast::ItemEnum(..) |
2982                     ast::ItemStruct(..) |
2983                     ast::ItemImpl(..) |
2984                     ast::ItemConst(..) |
2985                     ast::ItemStatic(..) => {
2986                         let def_id = DefId::local(id);
2987                         let scheme = cx.lookup_item_type(def_id);
2988                         let predicates = cx.lookup_predicates(def_id);
2989                         cx.construct_parameter_environment(item.span,
2990                                                            &scheme.generics,
2991                                                            &predicates,
2992                                                            id)
2993                     }
2994                     ast::ItemTrait(..) => {
2995                         let def_id = DefId::local(id);
2996                         let trait_def = cx.lookup_trait_def(def_id);
2997                         let predicates = cx.lookup_predicates(def_id);
2998                         cx.construct_parameter_environment(item.span,
2999                                                            &trait_def.generics,
3000                                                            &predicates,
3001                                                            id)
3002                     }
3003                     _ => {
3004                         cx.sess.span_bug(item.span,
3005                                          "ParameterEnvironment::from_item():
3006                                           can't create a parameter \
3007                                           environment for this kind of item")
3008                     }
3009                 }
3010             }
3011             Some(ast_map::NodeExpr(..)) => {
3012                 // This is a convenience to allow closures to work.
3013                 ParameterEnvironment::for_item(cx, cx.map.get_parent(id))
3014             }
3015             _ => {
3016                 cx.sess.bug(&format!("ParameterEnvironment::from_item(): \
3017                                      `{}` is not an item",
3018                                     cx.map.node_to_string(id)))
3019             }
3020         }
3021     }
3022
3023     pub fn can_type_implement_copy(&self, self_type: Ty<'tcx>, span: Span)
3024                                    -> Result<(),CopyImplementationError> {
3025         let tcx = self.tcx;
3026
3027         // FIXME: (@jroesch) float this code up
3028         let infcx = infer::new_infer_ctxt(tcx, &tcx.tables, Some(self.clone()), false);
3029
3030         let adt = match self_type.sty {
3031             ty::TyStruct(struct_def, substs) => {
3032                 for field in struct_def.all_fields() {
3033                     let field_ty = field.ty(tcx, substs);
3034                     if infcx.type_moves_by_default(field_ty, span) {
3035                         return Err(FieldDoesNotImplementCopy(field.name))
3036                     }
3037                 }
3038                 struct_def
3039             }
3040             ty::TyEnum(enum_def, substs) => {
3041                 for variant in &enum_def.variants {
3042                     for field in &variant.fields {
3043                         let field_ty = field.ty(tcx, substs);
3044                         if infcx.type_moves_by_default(field_ty, span) {
3045                             return Err(VariantDoesNotImplementCopy(variant.name))
3046                         }
3047                     }
3048                 }
3049                 enum_def
3050             }
3051             _ => return Err(TypeIsStructural),
3052         };
3053
3054         if adt.has_dtor() {
3055             return Err(TypeHasDestructor)
3056         }
3057
3058         Ok(())
3059     }
3060 }
3061
3062 #[derive(Copy, Clone)]
3063 pub enum CopyImplementationError {
3064     FieldDoesNotImplementCopy(ast::Name),
3065     VariantDoesNotImplementCopy(ast::Name),
3066     TypeIsStructural,
3067     TypeHasDestructor,
3068 }
3069
3070 /// A "type scheme", in ML terminology, is a type combined with some
3071 /// set of generic types that the type is, well, generic over. In Rust
3072 /// terms, it is the "type" of a fn item or struct -- this type will
3073 /// include various generic parameters that must be substituted when
3074 /// the item/struct is referenced. That is called converting the type
3075 /// scheme to a monotype.
3076 ///
3077 /// - `generics`: the set of type parameters and their bounds
3078 /// - `ty`: the base types, which may reference the parameters defined
3079 ///   in `generics`
3080 ///
3081 /// Note that TypeSchemes are also sometimes called "polytypes" (and
3082 /// in fact this struct used to carry that name, so you may find some
3083 /// stray references in a comment or something). We try to reserve the
3084 /// "poly" prefix to refer to higher-ranked things, as in
3085 /// `PolyTraitRef`.
3086 ///
3087 /// Note that each item also comes with predicates, see
3088 /// `lookup_predicates`.
3089 #[derive(Clone, Debug)]
3090 pub struct TypeScheme<'tcx> {
3091     pub generics: Generics<'tcx>,
3092     pub ty: Ty<'tcx>,
3093 }
3094
3095 bitflags! {
3096     flags TraitFlags: u32 {
3097         const NO_TRAIT_FLAGS        = 0,
3098         const HAS_DEFAULT_IMPL      = 1 << 0,
3099         const IS_OBJECT_SAFE        = 1 << 1,
3100         const OBJECT_SAFETY_VALID   = 1 << 2,
3101         const IMPLS_VALID           = 1 << 3,
3102     }
3103 }
3104
3105 /// As `TypeScheme` but for a trait ref.
3106 pub struct TraitDef<'tcx> {
3107     pub unsafety: ast::Unsafety,
3108
3109     /// If `true`, then this trait had the `#[rustc_paren_sugar]`
3110     /// attribute, indicating that it should be used with `Foo()`
3111     /// sugar. This is a temporary thing -- eventually any trait wil
3112     /// be usable with the sugar (or without it).
3113     pub paren_sugar: bool,
3114
3115     /// Generic type definitions. Note that `Self` is listed in here
3116     /// as having a single bound, the trait itself (e.g., in the trait
3117     /// `Eq`, there is a single bound `Self : Eq`). This is so that
3118     /// default methods get to assume that the `Self` parameters
3119     /// implements the trait.
3120     pub generics: Generics<'tcx>,
3121
3122     pub trait_ref: TraitRef<'tcx>,
3123
3124     /// A list of the associated types defined in this trait. Useful
3125     /// for resolving `X::Foo` type markers.
3126     pub associated_type_names: Vec<ast::Name>,
3127
3128     // Impls of this trait. To allow for quicker lookup, the impls are indexed
3129     // by a simplified version of their Self type: impls with a simplifiable
3130     // Self are stored in nonblanket_impls keyed by it, while all other impls
3131     // are stored in blanket_impls.
3132
3133     /// Impls of the trait.
3134     pub nonblanket_impls: RefCell<
3135         FnvHashMap<fast_reject::SimplifiedType, Vec<DefId>>
3136     >,
3137
3138     /// Blanket impls associated with the trait.
3139     pub blanket_impls: RefCell<Vec<DefId>>,
3140
3141     /// Various flags
3142     pub flags: Cell<TraitFlags>
3143 }
3144
3145 impl<'tcx> TraitDef<'tcx> {
3146     // returns None if not yet calculated
3147     pub fn object_safety(&self) -> Option<bool> {
3148         if self.flags.get().intersects(TraitFlags::OBJECT_SAFETY_VALID) {
3149             Some(self.flags.get().intersects(TraitFlags::IS_OBJECT_SAFE))
3150         } else {
3151             None
3152         }
3153     }
3154
3155     pub fn set_object_safety(&self, is_safe: bool) {
3156         assert!(self.object_safety().map(|cs| cs == is_safe).unwrap_or(true));
3157         self.flags.set(
3158             self.flags.get() | if is_safe {
3159                 TraitFlags::OBJECT_SAFETY_VALID | TraitFlags::IS_OBJECT_SAFE
3160             } else {
3161                 TraitFlags::OBJECT_SAFETY_VALID
3162             }
3163         );
3164     }
3165
3166     /// Records a trait-to-implementation mapping.
3167     pub fn record_impl(&self,
3168                        tcx: &ctxt<'tcx>,
3169                        impl_def_id: DefId,
3170                        impl_trait_ref: TraitRef<'tcx>) {
3171         debug!("TraitDef::record_impl for {:?}, from {:?}",
3172                self, impl_trait_ref);
3173
3174         // We don't want to borrow_mut after we already populated all impls,
3175         // so check if an impl is present with an immutable borrow first.
3176         if let Some(sty) = fast_reject::simplify_type(tcx,
3177                                                       impl_trait_ref.self_ty(), false) {
3178             if let Some(is) = self.nonblanket_impls.borrow().get(&sty) {
3179                 if is.contains(&impl_def_id) {
3180                     return // duplicate - skip
3181                 }
3182             }
3183
3184             self.nonblanket_impls.borrow_mut().entry(sty).or_insert(vec![]).push(impl_def_id)
3185         } else {
3186             if self.blanket_impls.borrow().contains(&impl_def_id) {
3187                 return // duplicate - skip
3188             }
3189             self.blanket_impls.borrow_mut().push(impl_def_id)
3190         }
3191     }
3192
3193
3194     pub fn for_each_impl<F: FnMut(DefId)>(&self, tcx: &ctxt<'tcx>, mut f: F)  {
3195         tcx.populate_implementations_for_trait_if_necessary(self.trait_ref.def_id);
3196
3197         for &impl_def_id in self.blanket_impls.borrow().iter() {
3198             f(impl_def_id);
3199         }
3200
3201         for v in self.nonblanket_impls.borrow().values() {
3202             for &impl_def_id in v {
3203                 f(impl_def_id);
3204             }
3205         }
3206     }
3207
3208     /// Iterate over every impl that could possibly match the
3209     /// self-type `self_ty`.
3210     pub fn for_each_relevant_impl<F: FnMut(DefId)>(&self,
3211                                                    tcx: &ctxt<'tcx>,
3212                                                    self_ty: Ty<'tcx>,
3213                                                    mut f: F)
3214     {
3215         tcx.populate_implementations_for_trait_if_necessary(self.trait_ref.def_id);
3216
3217         for &impl_def_id in self.blanket_impls.borrow().iter() {
3218             f(impl_def_id);
3219         }
3220
3221         // simplify_type(.., false) basically replaces type parameters and
3222         // projections with infer-variables. This is, of course, done on
3223         // the impl trait-ref when it is instantiated, but not on the
3224         // predicate trait-ref which is passed here.
3225         //
3226         // for example, if we match `S: Copy` against an impl like
3227         // `impl<T:Copy> Copy for Option<T>`, we replace the type variable
3228         // in `Option<T>` with an infer variable, to `Option<_>` (this
3229         // doesn't actually change fast_reject output), but we don't
3230         // replace `S` with anything - this impl of course can't be
3231         // selected, and as there are hundreds of similar impls,
3232         // considering them would significantly harm performance.
3233         if let Some(simp) = fast_reject::simplify_type(tcx, self_ty, true) {
3234             if let Some(impls) = self.nonblanket_impls.borrow().get(&simp) {
3235                 for &impl_def_id in impls {
3236                     f(impl_def_id);
3237                 }
3238             }
3239         } else {
3240             for v in self.nonblanket_impls.borrow().values() {
3241                 for &impl_def_id in v {
3242                     f(impl_def_id);
3243                 }
3244             }
3245         }
3246     }
3247
3248 }
3249
3250 bitflags! {
3251     flags AdtFlags: u32 {
3252         const NO_ADT_FLAGS        = 0,
3253         const IS_ENUM             = 1 << 0,
3254         const IS_DTORCK           = 1 << 1, // is this a dtorck type?
3255         const IS_DTORCK_VALID     = 1 << 2,
3256         const IS_PHANTOM_DATA     = 1 << 3,
3257         const IS_SIMD             = 1 << 4,
3258         const IS_FUNDAMENTAL      = 1 << 5,
3259         const IS_NO_DROP_FLAG     = 1 << 6,
3260     }
3261 }
3262
3263 pub type AdtDef<'tcx> = &'tcx AdtDefData<'tcx, 'static>;
3264 pub type VariantDef<'tcx> = &'tcx VariantDefData<'tcx, 'static>;
3265 pub type FieldDef<'tcx> = &'tcx FieldDefData<'tcx, 'static>;
3266
3267 // See comment on AdtDefData for explanation
3268 pub type AdtDefMaster<'tcx> = &'tcx AdtDefData<'tcx, 'tcx>;
3269 pub type VariantDefMaster<'tcx> = &'tcx VariantDefData<'tcx, 'tcx>;
3270 pub type FieldDefMaster<'tcx> = &'tcx FieldDefData<'tcx, 'tcx>;
3271
3272 pub struct VariantDefData<'tcx, 'container: 'tcx> {
3273     pub did: DefId,
3274     pub name: Name, // struct's name if this is a struct
3275     pub disr_val: Disr,
3276     pub fields: Vec<FieldDefData<'tcx, 'container>>
3277 }
3278
3279 pub struct FieldDefData<'tcx, 'container: 'tcx> {
3280     /// The field's DefId. NOTE: the fields of tuple-like enum variants
3281     /// are not real items, and don't have entries in tcache etc.
3282     pub did: DefId,
3283     /// special_idents::unnamed_field.name
3284     /// if this is a tuple-like field
3285     pub name: Name,
3286     pub vis: ast::Visibility,
3287     /// TyIVar is used here to allow for variance (see the doc at
3288     /// AdtDefData).
3289     ty: TyIVar<'tcx, 'container>
3290 }
3291
3292 /// The definition of an abstract data type - a struct or enum.
3293 ///
3294 /// These are all interned (by intern_adt_def) into the adt_defs
3295 /// table.
3296 ///
3297 /// Because of the possibility of nested tcx-s, this type
3298 /// needs 2 lifetimes: the traditional variant lifetime ('tcx)
3299 /// bounding the lifetime of the inner types is of course necessary.
3300 /// However, it is not sufficient - types from a child tcx must
3301 /// not be leaked into the master tcx by being stored in an AdtDefData.
3302 ///
3303 /// The 'container lifetime ensures that by outliving the container
3304 /// tcx and preventing shorter-lived types from being inserted. When
3305 /// write access is not needed, the 'container lifetime can be
3306 /// erased to 'static, which can be done by the AdtDef wrapper.
3307 pub struct AdtDefData<'tcx, 'container: 'tcx> {
3308     pub did: DefId,
3309     pub variants: Vec<VariantDefData<'tcx, 'container>>,
3310     destructor: Cell<Option<DefId>>,
3311     flags: Cell<AdtFlags>,
3312 }
3313
3314 impl<'tcx, 'container> PartialEq for AdtDefData<'tcx, 'container> {
3315     // AdtDefData are always interned and this is part of TyS equality
3316     #[inline]
3317     fn eq(&self, other: &Self) -> bool { self as *const _ == other as *const _ }
3318 }
3319
3320 impl<'tcx, 'container> Eq for AdtDefData<'tcx, 'container> {}
3321
3322 impl<'tcx, 'container> Hash for AdtDefData<'tcx, 'container> {
3323     #[inline]
3324     fn hash<H: Hasher>(&self, s: &mut H) {
3325         (self as *const AdtDefData).hash(s)
3326     }
3327 }
3328
3329
3330 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
3331 pub enum AdtKind { Struct, Enum }
3332
3333 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
3334 pub enum VariantKind { Dict, Tuple, Unit }
3335
3336 impl<'tcx, 'container> AdtDefData<'tcx, 'container> {
3337     fn new(tcx: &ctxt<'tcx>,
3338            did: DefId,
3339            kind: AdtKind,
3340            variants: Vec<VariantDefData<'tcx, 'container>>) -> Self {
3341         let mut flags = AdtFlags::NO_ADT_FLAGS;
3342         let attrs = tcx.get_attrs(did);
3343         if attr::contains_name(&attrs, "fundamental") {
3344             flags = flags | AdtFlags::IS_FUNDAMENTAL;
3345         }
3346         if attr::contains_name(&attrs, "unsafe_no_drop_flag") {
3347             flags = flags | AdtFlags::IS_NO_DROP_FLAG;
3348         }
3349         if tcx.lookup_simd(did) {
3350             flags = flags | AdtFlags::IS_SIMD;
3351         }
3352         if Some(did) == tcx.lang_items.phantom_data() {
3353             flags = flags | AdtFlags::IS_PHANTOM_DATA;
3354         }
3355         if let AdtKind::Enum = kind {
3356             flags = flags | AdtFlags::IS_ENUM;
3357         }
3358         AdtDefData {
3359             did: did,
3360             variants: variants,
3361             flags: Cell::new(flags),
3362             destructor: Cell::new(None)
3363         }
3364     }
3365
3366     fn calculate_dtorck(&'tcx self, tcx: &ctxt<'tcx>) {
3367         if tcx.is_adt_dtorck(self) {
3368             self.flags.set(self.flags.get() | AdtFlags::IS_DTORCK);
3369         }
3370         self.flags.set(self.flags.get() | AdtFlags::IS_DTORCK_VALID)
3371     }
3372
3373     /// Returns the kind of the ADT - Struct or Enum.
3374     #[inline]
3375     pub fn adt_kind(&self) -> AdtKind {
3376         if self.flags.get().intersects(AdtFlags::IS_ENUM) {
3377             AdtKind::Enum
3378         } else {
3379             AdtKind::Struct
3380         }
3381     }
3382
3383     /// Returns whether this is a dtorck type. If this returns
3384     /// true, this type being safe for destruction requires it to be
3385     /// alive; Otherwise, only the contents are required to be.
3386     #[inline]
3387     pub fn is_dtorck(&'tcx self, tcx: &ctxt<'tcx>) -> bool {
3388         if !self.flags.get().intersects(AdtFlags::IS_DTORCK_VALID) {
3389             self.calculate_dtorck(tcx)
3390         }
3391         self.flags.get().intersects(AdtFlags::IS_DTORCK)
3392     }
3393
3394     /// Returns whether this type is #[fundamental] for the purposes
3395     /// of coherence checking.
3396     #[inline]
3397     pub fn is_fundamental(&self) -> bool {
3398         self.flags.get().intersects(AdtFlags::IS_FUNDAMENTAL)
3399     }
3400
3401     #[inline]
3402     pub fn is_simd(&self) -> bool {
3403         self.flags.get().intersects(AdtFlags::IS_SIMD)
3404     }
3405
3406     /// Returns true if this is PhantomData<T>.
3407     #[inline]
3408     pub fn is_phantom_data(&self) -> bool {
3409         self.flags.get().intersects(AdtFlags::IS_PHANTOM_DATA)
3410     }
3411
3412     /// Returns whether this type has a destructor.
3413     pub fn has_dtor(&self) -> bool {
3414         match self.dtor_kind() {
3415             NoDtor => false,
3416             TraitDtor(..) => true
3417         }
3418     }
3419
3420     /// Asserts this is a struct and returns the struct's unique
3421     /// variant.
3422     pub fn struct_variant(&self) -> &VariantDefData<'tcx, 'container> {
3423         assert!(self.adt_kind() == AdtKind::Struct);
3424         &self.variants[0]
3425     }
3426
3427     #[inline]
3428     pub fn type_scheme(&self, tcx: &ctxt<'tcx>) -> TypeScheme<'tcx> {
3429         tcx.lookup_item_type(self.did)
3430     }
3431
3432     #[inline]
3433     pub fn predicates(&self, tcx: &ctxt<'tcx>) -> GenericPredicates<'tcx> {
3434         tcx.lookup_predicates(self.did)
3435     }
3436
3437     /// Returns an iterator over all fields contained
3438     /// by this ADT.
3439     #[inline]
3440     pub fn all_fields(&self) ->
3441             iter::FlatMap<
3442                 slice::Iter<VariantDefData<'tcx, 'container>>,
3443                 slice::Iter<FieldDefData<'tcx, 'container>>,
3444                 for<'s> fn(&'s VariantDefData<'tcx, 'container>)
3445                     -> slice::Iter<'s, FieldDefData<'tcx, 'container>>
3446             > {
3447         self.variants.iter().flat_map(VariantDefData::fields_iter)
3448     }
3449
3450     #[inline]
3451     pub fn is_empty(&self) -> bool {
3452         self.variants.is_empty()
3453     }
3454
3455     #[inline]
3456     pub fn is_univariant(&self) -> bool {
3457         self.variants.len() == 1
3458     }
3459
3460     pub fn is_payloadfree(&self) -> bool {
3461         !self.variants.is_empty() &&
3462             self.variants.iter().all(|v| v.fields.is_empty())
3463     }
3464
3465     pub fn variant_with_id(&self, vid: DefId) -> &VariantDefData<'tcx, 'container> {
3466         self.variants
3467             .iter()
3468             .find(|v| v.did == vid)
3469             .expect("variant_with_id: unknown variant")
3470     }
3471
3472     pub fn variant_of_def(&self, def: def::Def) -> &VariantDefData<'tcx, 'container> {
3473         match def {
3474             def::DefVariant(_, vid, _) => self.variant_with_id(vid),
3475             def::DefStruct(..) | def::DefTy(..) => self.struct_variant(),
3476             _ => panic!("unexpected def {:?} in variant_of_def", def)
3477         }
3478     }
3479
3480     pub fn destructor(&self) -> Option<DefId> {
3481         self.destructor.get()
3482     }
3483
3484     pub fn set_destructor(&self, dtor: DefId) {
3485         assert!(self.destructor.get().is_none());
3486         self.destructor.set(Some(dtor));
3487     }
3488
3489     pub fn dtor_kind(&self) -> DtorKind {
3490         match self.destructor.get() {
3491             Some(_) => {
3492                 TraitDtor(!self.flags.get().intersects(AdtFlags::IS_NO_DROP_FLAG))
3493             }
3494             None => NoDtor,
3495         }
3496     }
3497 }
3498
3499 impl<'tcx, 'container> VariantDefData<'tcx, 'container> {
3500     #[inline]
3501     fn fields_iter(&self) -> slice::Iter<FieldDefData<'tcx, 'container>> {
3502         self.fields.iter()
3503     }
3504
3505     pub fn kind(&self) -> VariantKind {
3506         match self.fields.get(0) {
3507             None => VariantKind::Unit,
3508             Some(&FieldDefData { name, .. }) if name == special_idents::unnamed_field.name => {
3509                 VariantKind::Tuple
3510             }
3511             Some(_) => VariantKind::Dict
3512         }
3513     }
3514
3515     pub fn is_tuple_struct(&self) -> bool {
3516         self.kind() == VariantKind::Tuple
3517     }
3518
3519     #[inline]
3520     pub fn find_field_named(&self,
3521                             name: ast::Name)
3522                             -> Option<&FieldDefData<'tcx, 'container>> {
3523         self.fields.iter().find(|f| f.name == name)
3524     }
3525
3526     #[inline]
3527     pub fn field_named(&self, name: ast::Name) -> &FieldDefData<'tcx, 'container> {
3528         self.find_field_named(name).unwrap()
3529     }
3530 }
3531
3532 impl<'tcx, 'container> FieldDefData<'tcx, 'container> {
3533     pub fn new(did: DefId,
3534                name: Name,
3535                vis: ast::Visibility) -> Self {
3536         FieldDefData {
3537             did: did,
3538             name: name,
3539             vis: vis,
3540             ty: TyIVar::new()
3541         }
3542     }
3543
3544     pub fn ty(&self, tcx: &ctxt<'tcx>, subst: &Substs<'tcx>) -> Ty<'tcx> {
3545         self.unsubst_ty().subst(tcx, subst)
3546     }
3547
3548     pub fn unsubst_ty(&self) -> Ty<'tcx> {
3549         self.ty.unwrap()
3550     }
3551
3552     pub fn fulfill_ty(&self, ty: Ty<'container>) {
3553         self.ty.fulfill(ty);
3554     }
3555 }
3556
3557 /// Records the substitutions used to translate the polytype for an
3558 /// item into the monotype of an item reference.
3559 #[derive(Clone)]
3560 pub struct ItemSubsts<'tcx> {
3561     pub substs: Substs<'tcx>,
3562 }
3563
3564 #[derive(Clone, Copy, PartialOrd, Ord, PartialEq, Eq, Debug, RustcEncodable, RustcDecodable)]
3565 pub enum ClosureKind {
3566     // Warning: Ordering is significant here! The ordering is chosen
3567     // because the trait Fn is a subtrait of FnMut and so in turn, and
3568     // hence we order it so that Fn < FnMut < FnOnce.
3569     FnClosureKind,
3570     FnMutClosureKind,
3571     FnOnceClosureKind,
3572 }
3573
3574 impl ClosureKind {
3575     pub fn trait_did(&self, cx: &ctxt) -> DefId {
3576         let result = match *self {
3577             FnClosureKind => cx.lang_items.require(FnTraitLangItem),
3578             FnMutClosureKind => {
3579                 cx.lang_items.require(FnMutTraitLangItem)
3580             }
3581             FnOnceClosureKind => {
3582                 cx.lang_items.require(FnOnceTraitLangItem)
3583             }
3584         };
3585         match result {
3586             Ok(trait_did) => trait_did,
3587             Err(err) => cx.sess.fatal(&err[..]),
3588         }
3589     }
3590
3591     /// True if this a type that impls this closure kind
3592     /// must also implement `other`.
3593     pub fn extends(self, other: ty::ClosureKind) -> bool {
3594         match (self, other) {
3595             (FnClosureKind, FnClosureKind) => true,
3596             (FnClosureKind, FnMutClosureKind) => true,
3597             (FnClosureKind, FnOnceClosureKind) => true,
3598             (FnMutClosureKind, FnMutClosureKind) => true,
3599             (FnMutClosureKind, FnOnceClosureKind) => true,
3600             (FnOnceClosureKind, FnOnceClosureKind) => true,
3601             _ => false,
3602         }
3603     }
3604 }
3605
3606 impl<'tcx> CommonTypes<'tcx> {
3607     fn new(arena: &'tcx TypedArena<TyS<'tcx>>,
3608            interner: &RefCell<FnvHashMap<InternedTy<'tcx>, Ty<'tcx>>>)
3609            -> CommonTypes<'tcx>
3610     {
3611         let mk = |sty| ctxt::intern_ty(arena, interner, sty);
3612         CommonTypes {
3613             bool: mk(TyBool),
3614             char: mk(TyChar),
3615             err: mk(TyError),
3616             isize: mk(TyInt(ast::TyIs)),
3617             i8: mk(TyInt(ast::TyI8)),
3618             i16: mk(TyInt(ast::TyI16)),
3619             i32: mk(TyInt(ast::TyI32)),
3620             i64: mk(TyInt(ast::TyI64)),
3621             usize: mk(TyUint(ast::TyUs)),
3622             u8: mk(TyUint(ast::TyU8)),
3623             u16: mk(TyUint(ast::TyU16)),
3624             u32: mk(TyUint(ast::TyU32)),
3625             u64: mk(TyUint(ast::TyU64)),
3626             f32: mk(TyFloat(ast::TyF32)),
3627             f64: mk(TyFloat(ast::TyF64)),
3628         }
3629     }
3630 }
3631
3632 struct FlagComputation {
3633     flags: TypeFlags,
3634
3635     // maximum depth of any bound region that we have seen thus far
3636     depth: u32,
3637 }
3638
3639 impl FlagComputation {
3640     fn new() -> FlagComputation {
3641         FlagComputation { flags: TypeFlags::empty(), depth: 0 }
3642     }
3643
3644     fn for_sty(st: &TypeVariants) -> FlagComputation {
3645         let mut result = FlagComputation::new();
3646         result.add_sty(st);
3647         result
3648     }
3649
3650     fn add_flags(&mut self, flags: TypeFlags) {
3651         self.flags = self.flags | (flags & TypeFlags::NOMINAL_FLAGS);
3652     }
3653
3654     fn add_depth(&mut self, depth: u32) {
3655         if depth > self.depth {
3656             self.depth = depth;
3657         }
3658     }
3659
3660     /// Adds the flags/depth from a set of types that appear within the current type, but within a
3661     /// region binder.
3662     fn add_bound_computation(&mut self, computation: &FlagComputation) {
3663         self.add_flags(computation.flags);
3664
3665         // The types that contributed to `computation` occurred within
3666         // a region binder, so subtract one from the region depth
3667         // within when adding the depth to `self`.
3668         let depth = computation.depth;
3669         if depth > 0 {
3670             self.add_depth(depth - 1);
3671         }
3672     }
3673
3674     fn add_sty(&mut self, st: &TypeVariants) {
3675         match st {
3676             &TyBool |
3677             &TyChar |
3678             &TyInt(_) |
3679             &TyFloat(_) |
3680             &TyUint(_) |
3681             &TyStr => {
3682             }
3683
3684             // You might think that we could just return TyError for
3685             // any type containing TyError as a component, and get
3686             // rid of the TypeFlags::HAS_TY_ERR flag -- likewise for ty_bot (with
3687             // the exception of function types that return bot).
3688             // But doing so caused sporadic memory corruption, and
3689             // neither I (tjc) nor nmatsakis could figure out why,
3690             // so we're doing it this way.
3691             &TyError => {
3692                 self.add_flags(TypeFlags::HAS_TY_ERR)
3693             }
3694
3695             &TyParam(ref p) => {
3696                 self.add_flags(TypeFlags::HAS_LOCAL_NAMES);
3697                 if p.space == subst::SelfSpace {
3698                     self.add_flags(TypeFlags::HAS_SELF);
3699                 } else {
3700                     self.add_flags(TypeFlags::HAS_PARAMS);
3701                 }
3702             }
3703
3704             &TyClosure(_, ref substs) => {
3705                 self.add_flags(TypeFlags::HAS_TY_CLOSURE);
3706                 self.add_flags(TypeFlags::HAS_LOCAL_NAMES);
3707                 self.add_substs(&substs.func_substs);
3708                 self.add_tys(&substs.upvar_tys);
3709             }
3710
3711             &TyInfer(_) => {
3712                 self.add_flags(TypeFlags::HAS_LOCAL_NAMES); // it might, right?
3713                 self.add_flags(TypeFlags::HAS_TY_INFER)
3714             }
3715
3716             &TyEnum(_, substs) | &TyStruct(_, substs) => {
3717                 self.add_substs(substs);
3718             }
3719
3720             &TyProjection(ref data) => {
3721                 self.add_flags(TypeFlags::HAS_PROJECTION);
3722                 self.add_projection_ty(data);
3723             }
3724
3725             &TyTrait(box TraitTy { ref principal, ref bounds }) => {
3726                 let mut computation = FlagComputation::new();
3727                 computation.add_substs(principal.0.substs);
3728                 for projection_bound in &bounds.projection_bounds {
3729                     let mut proj_computation = FlagComputation::new();
3730                     proj_computation.add_projection_predicate(&projection_bound.0);
3731                     self.add_bound_computation(&proj_computation);
3732                 }
3733                 self.add_bound_computation(&computation);
3734
3735                 self.add_bounds(bounds);
3736             }
3737
3738             &TyBox(tt) | &TyArray(tt, _) | &TySlice(tt) => {
3739                 self.add_ty(tt)
3740             }
3741
3742             &TyRawPtr(ref m) => {
3743                 self.add_ty(m.ty);
3744             }
3745
3746             &TyRef(r, ref m) => {
3747                 self.add_region(*r);
3748                 self.add_ty(m.ty);
3749             }
3750
3751             &TyTuple(ref ts) => {
3752                 self.add_tys(&ts[..]);
3753             }
3754
3755             &TyBareFn(_, ref f) => {
3756                 self.add_fn_sig(&f.sig);
3757             }
3758         }
3759     }
3760
3761     fn add_ty(&mut self, ty: Ty) {
3762         self.add_flags(ty.flags.get());
3763         self.add_depth(ty.region_depth);
3764     }
3765
3766     fn add_tys(&mut self, tys: &[Ty]) {
3767         for &ty in tys {
3768             self.add_ty(ty);
3769         }
3770     }
3771
3772     fn add_fn_sig(&mut self, fn_sig: &PolyFnSig) {
3773         let mut computation = FlagComputation::new();
3774
3775         computation.add_tys(&fn_sig.0.inputs);
3776
3777         if let ty::FnConverging(output) = fn_sig.0.output {
3778             computation.add_ty(output);
3779         }
3780
3781         self.add_bound_computation(&computation);
3782     }
3783
3784     fn add_region(&mut self, r: Region) {
3785         match r {
3786             ty::ReVar(..) |
3787             ty::ReSkolemized(..) => { self.add_flags(TypeFlags::HAS_RE_INFER); }
3788             ty::ReLateBound(debruijn, _) => { self.add_depth(debruijn.depth); }
3789             ty::ReEarlyBound(..) => { self.add_flags(TypeFlags::HAS_RE_EARLY_BOUND); }
3790             ty::ReStatic => {}
3791             _ => { self.add_flags(TypeFlags::HAS_FREE_REGIONS); }
3792         }
3793
3794         if !r.is_global() {
3795             self.add_flags(TypeFlags::HAS_LOCAL_NAMES);
3796         }
3797     }
3798
3799     fn add_projection_predicate(&mut self, projection_predicate: &ProjectionPredicate) {
3800         self.add_projection_ty(&projection_predicate.projection_ty);
3801         self.add_ty(projection_predicate.ty);
3802     }
3803
3804     fn add_projection_ty(&mut self, projection_ty: &ProjectionTy) {
3805         self.add_substs(projection_ty.trait_ref.substs);
3806     }
3807
3808     fn add_substs(&mut self, substs: &Substs) {
3809         self.add_tys(substs.types.as_slice());
3810         match substs.regions {
3811             subst::ErasedRegions => {}
3812             subst::NonerasedRegions(ref regions) => {
3813                 for &r in regions {
3814                     self.add_region(r);
3815                 }
3816             }
3817         }
3818     }
3819
3820     fn add_bounds(&mut self, bounds: &ExistentialBounds) {
3821         self.add_region(bounds.region_bound);
3822     }
3823 }
3824
3825 impl<'tcx> ctxt<'tcx> {
3826     /// Create a type context and call the closure with a `&ty::ctxt` reference
3827     /// to the context. The closure enforces that the type context and any interned
3828     /// value (types, substs, etc.) can only be used while `ty::tls` has a valid
3829     /// reference to the context, to allow formatting values that need it.
3830     pub fn create_and_enter<F, R>(s: Session,
3831                                  arenas: &'tcx CtxtArenas<'tcx>,
3832                                  def_map: DefMap,
3833                                  named_region_map: resolve_lifetime::NamedRegionMap,
3834                                  map: ast_map::Map<'tcx>,
3835                                  freevars: RefCell<FreevarMap>,
3836                                  region_maps: RegionMaps,
3837                                  lang_items: middle::lang_items::LanguageItems,
3838                                  stability: stability::Index<'tcx>,
3839                                  f: F) -> (Session, R)
3840                                  where F: FnOnce(&ctxt<'tcx>) -> R
3841     {
3842         let interner = RefCell::new(FnvHashMap());
3843         let common_types = CommonTypes::new(&arenas.type_, &interner);
3844
3845         tls::enter(ctxt {
3846             arenas: arenas,
3847             interner: interner,
3848             substs_interner: RefCell::new(FnvHashMap()),
3849             bare_fn_interner: RefCell::new(FnvHashMap()),
3850             region_interner: RefCell::new(FnvHashMap()),
3851             stability_interner: RefCell::new(FnvHashMap()),
3852             types: common_types,
3853             named_region_map: named_region_map,
3854             region_maps: region_maps,
3855             free_region_maps: RefCell::new(FnvHashMap()),
3856             item_variance_map: RefCell::new(DefIdMap()),
3857             variance_computed: Cell::new(false),
3858             sess: s,
3859             def_map: def_map,
3860             tables: RefCell::new(Tables::empty()),
3861             impl_trait_refs: RefCell::new(DefIdMap()),
3862             trait_defs: RefCell::new(DefIdMap()),
3863             adt_defs: RefCell::new(DefIdMap()),
3864             predicates: RefCell::new(DefIdMap()),
3865             super_predicates: RefCell::new(DefIdMap()),
3866             fulfilled_predicates: RefCell::new(traits::FulfilledPredicates::new()),
3867             map: map,
3868             freevars: freevars,
3869             tcache: RefCell::new(DefIdMap()),
3870             rcache: RefCell::new(FnvHashMap()),
3871             tc_cache: RefCell::new(FnvHashMap()),
3872             ast_ty_to_ty_cache: RefCell::new(NodeMap()),
3873             impl_or_trait_items: RefCell::new(DefIdMap()),
3874             trait_item_def_ids: RefCell::new(DefIdMap()),
3875             trait_items_cache: RefCell::new(DefIdMap()),
3876             ty_param_defs: RefCell::new(NodeMap()),
3877             normalized_cache: RefCell::new(FnvHashMap()),
3878             lang_items: lang_items,
3879             provided_method_sources: RefCell::new(DefIdMap()),
3880             destructors: RefCell::new(DefIdSet()),
3881             inherent_impls: RefCell::new(DefIdMap()),
3882             impl_items: RefCell::new(DefIdMap()),
3883             used_unsafe: RefCell::new(NodeSet()),
3884             used_mut_nodes: RefCell::new(NodeSet()),
3885             populated_external_types: RefCell::new(DefIdSet()),
3886             populated_external_primitive_impls: RefCell::new(DefIdSet()),
3887             extern_const_statics: RefCell::new(DefIdMap()),
3888             extern_const_variants: RefCell::new(DefIdMap()),
3889             extern_const_fns: RefCell::new(DefIdMap()),
3890             node_lint_levels: RefCell::new(FnvHashMap()),
3891             transmute_restrictions: RefCell::new(Vec::new()),
3892             stability: RefCell::new(stability),
3893             selection_cache: traits::SelectionCache::new(),
3894             repr_hint_cache: RefCell::new(DefIdMap()),
3895             const_qualif_map: RefCell::new(NodeMap()),
3896             custom_coerce_unsized_kinds: RefCell::new(DefIdMap()),
3897             cast_kinds: RefCell::new(NodeMap()),
3898             fragment_infos: RefCell::new(DefIdMap()),
3899        }, f)
3900     }
3901
3902     // Type constructors
3903
3904     pub fn mk_substs(&self, substs: Substs<'tcx>) -> &'tcx Substs<'tcx> {
3905         if let Some(substs) = self.substs_interner.borrow().get(&substs) {
3906             return *substs;
3907         }
3908
3909         let substs = self.arenas.substs.alloc(substs);
3910         self.substs_interner.borrow_mut().insert(substs, substs);
3911         substs
3912     }
3913
3914     /// Create an unsafe fn ty based on a safe fn ty.
3915     pub fn safe_to_unsafe_fn_ty(&self, bare_fn: &BareFnTy<'tcx>) -> Ty<'tcx> {
3916         assert_eq!(bare_fn.unsafety, ast::Unsafety::Normal);
3917         let unsafe_fn_ty_a = self.mk_bare_fn(ty::BareFnTy {
3918             unsafety: ast::Unsafety::Unsafe,
3919             abi: bare_fn.abi,
3920             sig: bare_fn.sig.clone()
3921         });
3922         self.mk_fn(None, unsafe_fn_ty_a)
3923     }
3924
3925     pub fn mk_bare_fn(&self, bare_fn: BareFnTy<'tcx>) -> &'tcx BareFnTy<'tcx> {
3926         if let Some(bare_fn) = self.bare_fn_interner.borrow().get(&bare_fn) {
3927             return *bare_fn;
3928         }
3929
3930         let bare_fn = self.arenas.bare_fn.alloc(bare_fn);
3931         self.bare_fn_interner.borrow_mut().insert(bare_fn, bare_fn);
3932         bare_fn
3933     }
3934
3935     pub fn mk_region(&self, region: Region) -> &'tcx Region {
3936         if let Some(region) = self.region_interner.borrow().get(&region) {
3937             return *region;
3938         }
3939
3940         let region = self.arenas.region.alloc(region);
3941         self.region_interner.borrow_mut().insert(region, region);
3942         region
3943     }
3944
3945     pub fn closure_kind(&self, def_id: DefId) -> ty::ClosureKind {
3946         *self.tables.borrow().closure_kinds.get(&def_id).unwrap()
3947     }
3948
3949     pub fn closure_type(&self,
3950                         def_id: DefId,
3951                         substs: &ClosureSubsts<'tcx>)
3952                         -> ty::ClosureTy<'tcx>
3953     {
3954         self.tables.borrow().closure_tys.get(&def_id).unwrap().subst(self, &substs.func_substs)
3955     }
3956
3957     pub fn type_parameter_def(&self,
3958                               node_id: ast::NodeId)
3959                               -> TypeParameterDef<'tcx>
3960     {
3961         self.ty_param_defs.borrow().get(&node_id).unwrap().clone()
3962     }
3963
3964     pub fn pat_contains_ref_binding(&self, pat: &ast::Pat) -> Option<ast::Mutability> {
3965         pat_util::pat_contains_ref_binding(&self.def_map, pat)
3966     }
3967
3968     pub fn arm_contains_ref_binding(&self, arm: &ast::Arm) -> Option<ast::Mutability> {
3969         pat_util::arm_contains_ref_binding(&self.def_map, arm)
3970     }
3971
3972     fn intern_ty(type_arena: &'tcx TypedArena<TyS<'tcx>>,
3973                  interner: &RefCell<FnvHashMap<InternedTy<'tcx>, Ty<'tcx>>>,
3974                  st: TypeVariants<'tcx>)
3975                  -> Ty<'tcx> {
3976         let ty: Ty /* don't be &mut TyS */ = {
3977             let mut interner = interner.borrow_mut();
3978             match interner.get(&st) {
3979                 Some(ty) => return *ty,
3980                 _ => ()
3981             }
3982
3983             let flags = FlagComputation::for_sty(&st);
3984
3985             let ty = match () {
3986                 () => type_arena.alloc(TyS { sty: st,
3987                                              flags: Cell::new(flags.flags),
3988                                              region_depth: flags.depth, }),
3989             };
3990
3991             interner.insert(InternedTy { ty: ty }, ty);
3992             ty
3993         };
3994
3995         debug!("Interned type: {:?} Pointer: {:?}",
3996             ty, ty as *const TyS);
3997         ty
3998     }
3999
4000     // Interns a type/name combination, stores the resulting box in cx.interner,
4001     // and returns the box as cast to an unsafe ptr (see comments for Ty above).
4002     pub fn mk_ty(&self, st: TypeVariants<'tcx>) -> Ty<'tcx> {
4003         ctxt::intern_ty(&self.arenas.type_, &self.interner, st)
4004     }
4005
4006     pub fn mk_mach_int(&self, tm: ast::IntTy) -> Ty<'tcx> {
4007         match tm {
4008             ast::TyIs   => self.types.isize,
4009             ast::TyI8   => self.types.i8,
4010             ast::TyI16  => self.types.i16,
4011             ast::TyI32  => self.types.i32,
4012             ast::TyI64  => self.types.i64,
4013         }
4014     }
4015
4016     pub fn mk_mach_uint(&self, tm: ast::UintTy) -> Ty<'tcx> {
4017         match tm {
4018             ast::TyUs   => self.types.usize,
4019             ast::TyU8   => self.types.u8,
4020             ast::TyU16  => self.types.u16,
4021             ast::TyU32  => self.types.u32,
4022             ast::TyU64  => self.types.u64,
4023         }
4024     }
4025
4026     pub fn mk_mach_float(&self, tm: ast::FloatTy) -> Ty<'tcx> {
4027         match tm {
4028             ast::TyF32  => self.types.f32,
4029             ast::TyF64  => self.types.f64,
4030         }
4031     }
4032
4033     pub fn mk_str(&self) -> Ty<'tcx> {
4034         self.mk_ty(TyStr)
4035     }
4036
4037     pub fn mk_static_str(&self) -> Ty<'tcx> {
4038         self.mk_imm_ref(self.mk_region(ty::ReStatic), self.mk_str())
4039     }
4040
4041     pub fn mk_enum(&self, def: AdtDef<'tcx>, substs: &'tcx Substs<'tcx>) -> Ty<'tcx> {
4042         // take a copy of substs so that we own the vectors inside
4043         self.mk_ty(TyEnum(def, substs))
4044     }
4045
4046     pub fn mk_box(&self, ty: Ty<'tcx>) -> Ty<'tcx> {
4047         self.mk_ty(TyBox(ty))
4048     }
4049
4050     pub fn mk_ptr(&self, tm: TypeAndMut<'tcx>) -> Ty<'tcx> {
4051         self.mk_ty(TyRawPtr(tm))
4052     }
4053
4054     pub fn mk_ref(&self, r: &'tcx Region, tm: TypeAndMut<'tcx>) -> Ty<'tcx> {
4055         self.mk_ty(TyRef(r, tm))
4056     }
4057
4058     pub fn mk_mut_ref(&self, r: &'tcx Region, ty: Ty<'tcx>) -> Ty<'tcx> {
4059         self.mk_ref(r, TypeAndMut {ty: ty, mutbl: ast::MutMutable})
4060     }
4061
4062     pub fn mk_imm_ref(&self, r: &'tcx Region, ty: Ty<'tcx>) -> Ty<'tcx> {
4063         self.mk_ref(r, TypeAndMut {ty: ty, mutbl: ast::MutImmutable})
4064     }
4065
4066     pub fn mk_mut_ptr(&self, ty: Ty<'tcx>) -> Ty<'tcx> {
4067         self.mk_ptr(TypeAndMut {ty: ty, mutbl: ast::MutMutable})
4068     }
4069
4070     pub fn mk_imm_ptr(&self, ty: Ty<'tcx>) -> Ty<'tcx> {
4071         self.mk_ptr(TypeAndMut {ty: ty, mutbl: ast::MutImmutable})
4072     }
4073
4074     pub fn mk_nil_ptr(&self) -> Ty<'tcx> {
4075         self.mk_imm_ptr(self.mk_nil())
4076     }
4077
4078     pub fn mk_array(&self, ty: Ty<'tcx>, n: usize) -> Ty<'tcx> {
4079         self.mk_ty(TyArray(ty, n))
4080     }
4081
4082     pub fn mk_slice(&self, ty: Ty<'tcx>) -> Ty<'tcx> {
4083         self.mk_ty(TySlice(ty))
4084     }
4085
4086     pub fn mk_tup(&self, ts: Vec<Ty<'tcx>>) -> Ty<'tcx> {
4087         self.mk_ty(TyTuple(ts))
4088     }
4089
4090     pub fn mk_nil(&self) -> Ty<'tcx> {
4091         self.mk_tup(Vec::new())
4092     }
4093
4094     pub fn mk_bool(&self) -> Ty<'tcx> {
4095         self.mk_ty(TyBool)
4096     }
4097
4098     pub fn mk_fn(&self,
4099                  opt_def_id: Option<DefId>,
4100                  fty: &'tcx BareFnTy<'tcx>) -> Ty<'tcx> {
4101         self.mk_ty(TyBareFn(opt_def_id, fty))
4102     }
4103
4104     pub fn mk_ctor_fn(&self,
4105                       def_id: DefId,
4106                       input_tys: &[Ty<'tcx>],
4107                       output: Ty<'tcx>) -> Ty<'tcx> {
4108         let input_args = input_tys.iter().cloned().collect();
4109         self.mk_fn(Some(def_id), self.mk_bare_fn(BareFnTy {
4110             unsafety: ast::Unsafety::Normal,
4111             abi: abi::Rust,
4112             sig: ty::Binder(FnSig {
4113                 inputs: input_args,
4114                 output: ty::FnConverging(output),
4115                 variadic: false
4116             })
4117         }))
4118     }
4119
4120     pub fn mk_trait(&self,
4121                     principal: ty::PolyTraitRef<'tcx>,
4122                     bounds: ExistentialBounds<'tcx>)
4123                     -> Ty<'tcx>
4124     {
4125         assert!(bound_list_is_sorted(&bounds.projection_bounds));
4126
4127         let inner = box TraitTy {
4128             principal: principal,
4129             bounds: bounds
4130         };
4131         self.mk_ty(TyTrait(inner))
4132     }
4133
4134     pub fn mk_projection(&self,
4135                          trait_ref: TraitRef<'tcx>,
4136                          item_name: ast::Name)
4137                          -> Ty<'tcx> {
4138         // take a copy of substs so that we own the vectors inside
4139         let inner = ProjectionTy { trait_ref: trait_ref, item_name: item_name };
4140         self.mk_ty(TyProjection(inner))
4141     }
4142
4143     pub fn mk_struct(&self, def: AdtDef<'tcx>, substs: &'tcx Substs<'tcx>) -> Ty<'tcx> {
4144         // take a copy of substs so that we own the vectors inside
4145         self.mk_ty(TyStruct(def, substs))
4146     }
4147
4148     pub fn mk_closure(&self,
4149                       closure_id: DefId,
4150                       substs: &'tcx Substs<'tcx>,
4151                       tys: Vec<Ty<'tcx>>)
4152                       -> Ty<'tcx> {
4153         self.mk_closure_from_closure_substs(closure_id, Box::new(ClosureSubsts {
4154             func_substs: substs,
4155             upvar_tys: tys
4156         }))
4157     }
4158
4159     pub fn mk_closure_from_closure_substs(&self,
4160                                           closure_id: DefId,
4161                                           closure_substs: Box<ClosureSubsts<'tcx>>)
4162                                           -> Ty<'tcx> {
4163         self.mk_ty(TyClosure(closure_id, closure_substs))
4164     }
4165
4166     pub fn mk_var(&self, v: TyVid) -> Ty<'tcx> {
4167         self.mk_infer(TyVar(v))
4168     }
4169
4170     pub fn mk_int_var(&self, v: IntVid) -> Ty<'tcx> {
4171         self.mk_infer(IntVar(v))
4172     }
4173
4174     pub fn mk_float_var(&self, v: FloatVid) -> Ty<'tcx> {
4175         self.mk_infer(FloatVar(v))
4176     }
4177
4178     pub fn mk_infer(&self, it: InferTy) -> Ty<'tcx> {
4179         self.mk_ty(TyInfer(it))
4180     }
4181
4182     pub fn mk_param(&self,
4183                     space: subst::ParamSpace,
4184                     index: u32,
4185                     name: ast::Name) -> Ty<'tcx> {
4186         self.mk_ty(TyParam(ParamTy { space: space, idx: index, name: name }))
4187     }
4188
4189     pub fn mk_self_type(&self) -> Ty<'tcx> {
4190         self.mk_param(subst::SelfSpace, 0, special_idents::type_self.name)
4191     }
4192
4193     pub fn mk_param_from_def(&self, def: &TypeParameterDef) -> Ty<'tcx> {
4194         self.mk_param(def.space, def.index, def.name)
4195     }
4196 }
4197
4198 fn bound_list_is_sorted(bounds: &[ty::PolyProjectionPredicate]) -> bool {
4199     bounds.is_empty() ||
4200         bounds[1..].iter().enumerate().all(
4201             |(index, bound)| bounds[index].sort_key() <= bound.sort_key())
4202 }
4203
4204 pub fn sort_bounds_list(bounds: &mut [ty::PolyProjectionPredicate]) {
4205     bounds.sort_by(|a, b| a.sort_key().cmp(&b.sort_key()))
4206 }
4207
4208 impl<'tcx> TyS<'tcx> {
4209     /// Iterator that walks `self` and any types reachable from
4210     /// `self`, in depth-first order. Note that just walks the types
4211     /// that appear in `self`, it does not descend into the fields of
4212     /// structs or variants. For example:
4213     ///
4214     /// ```notrust
4215     /// isize => { isize }
4216     /// Foo<Bar<isize>> => { Foo<Bar<isize>>, Bar<isize>, isize }
4217     /// [isize] => { [isize], isize }
4218     /// ```
4219     pub fn walk(&'tcx self) -> TypeWalker<'tcx> {
4220         TypeWalker::new(self)
4221     }
4222
4223     /// Iterator that walks the immediate children of `self`.  Hence
4224     /// `Foo<Bar<i32>, u32>` yields the sequence `[Bar<i32>, u32]`
4225     /// (but not `i32`, like `walk`).
4226     pub fn walk_shallow(&'tcx self) -> IntoIter<Ty<'tcx>> {
4227         ty_walk::walk_shallow(self)
4228     }
4229
4230     pub fn as_opt_param_ty(&self) -> Option<ty::ParamTy> {
4231         match self.sty {
4232             ty::TyParam(ref d) => Some(d.clone()),
4233             _ => None,
4234         }
4235     }
4236
4237     pub fn is_param(&self, space: ParamSpace, index: u32) -> bool {
4238         match self.sty {
4239             ty::TyParam(ref data) => data.space == space && data.idx == index,
4240             _ => false,
4241         }
4242     }
4243
4244     /// Returns the regions directly referenced from this type (but
4245     /// not types reachable from this type via `walk_tys`). This
4246     /// ignores late-bound regions binders.
4247     pub fn regions(&self) -> Vec<ty::Region> {
4248         match self.sty {
4249             TyRef(region, _) => {
4250                 vec![*region]
4251             }
4252             TyTrait(ref obj) => {
4253                 let mut v = vec![obj.bounds.region_bound];
4254                 v.push_all(obj.principal.skip_binder().substs.regions().as_slice());
4255                 v
4256             }
4257             TyEnum(_, substs) |
4258             TyStruct(_, substs) => {
4259                 substs.regions().as_slice().to_vec()
4260             }
4261             TyClosure(_, ref substs) => {
4262                 substs.func_substs.regions().as_slice().to_vec()
4263             }
4264             TyProjection(ref data) => {
4265                 data.trait_ref.substs.regions().as_slice().to_vec()
4266             }
4267             TyBareFn(..) |
4268             TyBool |
4269             TyChar |
4270             TyInt(_) |
4271             TyUint(_) |
4272             TyFloat(_) |
4273             TyBox(_) |
4274             TyStr |
4275             TyArray(_, _) |
4276             TySlice(_) |
4277             TyRawPtr(_) |
4278             TyTuple(_) |
4279             TyParam(_) |
4280             TyInfer(_) |
4281             TyError => {
4282                 vec![]
4283             }
4284         }
4285     }
4286
4287     /// Walks `ty` and any types appearing within `ty`, invoking the
4288     /// callback `f` on each type. If the callback returns false, then the
4289     /// children of the current type are ignored.
4290     ///
4291     /// Note: prefer `ty.walk()` where possible.
4292     pub fn maybe_walk<F>(&'tcx self, mut f: F)
4293         where F : FnMut(Ty<'tcx>) -> bool
4294     {
4295         let mut walker = self.walk();
4296         while let Some(ty) = walker.next() {
4297             if !f(ty) {
4298                 walker.skip_current_subtree();
4299             }
4300         }
4301     }
4302 }
4303
4304 impl ParamTy {
4305     pub fn new(space: subst::ParamSpace,
4306                index: u32,
4307                name: ast::Name)
4308                -> ParamTy {
4309         ParamTy { space: space, idx: index, name: name }
4310     }
4311
4312     pub fn for_self() -> ParamTy {
4313         ParamTy::new(subst::SelfSpace, 0, special_idents::type_self.name)
4314     }
4315
4316     pub fn for_def(def: &TypeParameterDef) -> ParamTy {
4317         ParamTy::new(def.space, def.index, def.name)
4318     }
4319
4320     pub fn to_ty<'tcx>(self, tcx: &ctxt<'tcx>) -> Ty<'tcx> {
4321         tcx.mk_param(self.space, self.idx, self.name)
4322     }
4323
4324     pub fn is_self(&self) -> bool {
4325         self.space == subst::SelfSpace && self.idx == 0
4326     }
4327 }
4328
4329 impl<'tcx> ItemSubsts<'tcx> {
4330     pub fn empty() -> ItemSubsts<'tcx> {
4331         ItemSubsts { substs: Substs::empty() }
4332     }
4333
4334     pub fn is_noop(&self) -> bool {
4335         self.substs.is_noop()
4336     }
4337 }
4338
4339 // Type utilities
4340 impl<'tcx> TyS<'tcx> {
4341     pub fn is_nil(&self) -> bool {
4342         match self.sty {
4343             TyTuple(ref tys) => tys.is_empty(),
4344             _ => false
4345         }
4346     }
4347
4348     pub fn is_empty(&self, _cx: &ctxt) -> bool {
4349         // FIXME(#24885): be smarter here
4350         match self.sty {
4351             TyEnum(def, _) | TyStruct(def, _) => def.is_empty(),
4352             _ => false
4353         }
4354     }
4355
4356     pub fn is_ty_var(&self) -> bool {
4357         match self.sty {
4358             TyInfer(TyVar(_)) => true,
4359             _ => false
4360         }
4361     }
4362
4363     pub fn is_bool(&self) -> bool { self.sty == TyBool }
4364
4365     pub fn is_self(&self) -> bool {
4366         match self.sty {
4367             TyParam(ref p) => p.space == subst::SelfSpace,
4368             _ => false
4369         }
4370     }
4371
4372     fn is_slice(&self) -> bool {
4373         match self.sty {
4374             TyRawPtr(mt) | TyRef(_, mt) => match mt.ty.sty {
4375                 TySlice(_) | TyStr => true,
4376                 _ => false,
4377             },
4378             _ => false
4379         }
4380     }
4381
4382     pub fn is_structural(&self) -> bool {
4383         match self.sty {
4384             TyStruct(..) | TyTuple(_) | TyEnum(..) |
4385             TyArray(..) | TyClosure(..) => true,
4386             _ => self.is_slice() | self.is_trait()
4387         }
4388     }
4389
4390     #[inline]
4391     pub fn is_simd(&self) -> bool {
4392         match self.sty {
4393             TyStruct(def, _) => def.is_simd(),
4394             _ => false
4395         }
4396     }
4397
4398     pub fn sequence_element_type(&self, cx: &ctxt<'tcx>) -> Ty<'tcx> {
4399         match self.sty {
4400             TyArray(ty, _) | TySlice(ty) => ty,
4401             TyStr => cx.mk_mach_uint(ast::TyU8),
4402             _ => cx.sess.bug(&format!("sequence_element_type called on non-sequence value: {}",
4403                                       self)),
4404         }
4405     }
4406
4407     pub fn simd_type(&self, cx: &ctxt<'tcx>) -> Ty<'tcx> {
4408         match self.sty {
4409             TyStruct(def, substs) => {
4410                 def.struct_variant().fields[0].ty(cx, substs)
4411             }
4412             _ => panic!("simd_type called on invalid type")
4413         }
4414     }
4415
4416     pub fn simd_size(&self, _cx: &ctxt) -> usize {
4417         match self.sty {
4418             TyStruct(def, _) => def.struct_variant().fields.len(),
4419             _ => panic!("simd_size called on invalid type")
4420         }
4421     }
4422
4423     pub fn is_region_ptr(&self) -> bool {
4424         match self.sty {
4425             TyRef(..) => true,
4426             _ => false
4427         }
4428     }
4429
4430     pub fn is_unsafe_ptr(&self) -> bool {
4431         match self.sty {
4432             TyRawPtr(_) => return true,
4433             _ => return false
4434         }
4435     }
4436
4437     pub fn is_unique(&self) -> bool {
4438         match self.sty {
4439             TyBox(_) => true,
4440             _ => false
4441         }
4442     }
4443
4444     /*
4445      A scalar type is one that denotes an atomic datum, with no sub-components.
4446      (A TyRawPtr is scalar because it represents a non-managed pointer, so its
4447      contents are abstract to rustc.)
4448     */
4449     pub fn is_scalar(&self) -> bool {
4450         match self.sty {
4451             TyBool | TyChar | TyInt(_) | TyFloat(_) | TyUint(_) |
4452             TyInfer(IntVar(_)) | TyInfer(FloatVar(_)) |
4453             TyBareFn(..) | TyRawPtr(_) => true,
4454             _ => false
4455         }
4456     }
4457
4458     /// Returns true if this type is a floating point type and false otherwise.
4459     pub fn is_floating_point(&self) -> bool {
4460         match self.sty {
4461             TyFloat(_) |
4462             TyInfer(FloatVar(_)) => true,
4463             _ => false,
4464         }
4465     }
4466
4467     pub fn ty_to_def_id(&self) -> Option<DefId> {
4468         match self.sty {
4469             TyTrait(ref tt) => Some(tt.principal_def_id()),
4470             TyStruct(def, _) |
4471             TyEnum(def, _) => Some(def.did),
4472             TyClosure(id, _) => Some(id),
4473             _ => None
4474         }
4475     }
4476
4477     pub fn ty_adt_def(&self) -> Option<AdtDef<'tcx>> {
4478         match self.sty {
4479             TyStruct(adt, _) | TyEnum(adt, _) => Some(adt),
4480             _ => None
4481         }
4482     }
4483 }
4484
4485 /// Type contents is how the type checker reasons about kinds.
4486 /// They track what kinds of things are found within a type.  You can
4487 /// think of them as kind of an "anti-kind".  They track the kinds of values
4488 /// and thinks that are contained in types.  Having a larger contents for
4489 /// a type tends to rule that type *out* from various kinds.  For example,
4490 /// a type that contains a reference is not sendable.
4491 ///
4492 /// The reason we compute type contents and not kinds is that it is
4493 /// easier for me (nmatsakis) to think about what is contained within
4494 /// a type than to think about what is *not* contained within a type.
4495 #[derive(Clone, Copy)]
4496 pub struct TypeContents {
4497     pub bits: u64
4498 }
4499
4500 macro_rules! def_type_content_sets {
4501     (mod $mname:ident { $($name:ident = $bits:expr),+ }) => {
4502         #[allow(non_snake_case)]
4503         mod $mname {
4504             use middle::ty::TypeContents;
4505             $(
4506                 #[allow(non_upper_case_globals)]
4507                 pub const $name: TypeContents = TypeContents { bits: $bits };
4508              )+
4509         }
4510     }
4511 }
4512
4513 def_type_content_sets! {
4514     mod TC {
4515         None                                = 0b0000_0000__0000_0000__0000,
4516
4517         // Things that are interior to the value (first nibble):
4518         InteriorUnsafe                      = 0b0000_0000__0000_0000__0010,
4519         InteriorParam                       = 0b0000_0000__0000_0000__0100,
4520         // InteriorAll                         = 0b00000000__00000000__1111,
4521
4522         // Things that are owned by the value (second and third nibbles):
4523         OwnsOwned                           = 0b0000_0000__0000_0001__0000,
4524         OwnsDtor                            = 0b0000_0000__0000_0010__0000,
4525         OwnsAll                             = 0b0000_0000__1111_1111__0000,
4526
4527         // Things that mean drop glue is necessary
4528         NeedsDrop                           = 0b0000_0000__0000_0111__0000,
4529
4530         // All bits
4531         All                                 = 0b1111_1111__1111_1111__1111
4532     }
4533 }
4534
4535 impl TypeContents {
4536     pub fn when(&self, cond: bool) -> TypeContents {
4537         if cond {*self} else {TC::None}
4538     }
4539
4540     pub fn intersects(&self, tc: TypeContents) -> bool {
4541         (self.bits & tc.bits) != 0
4542     }
4543
4544     pub fn owns_owned(&self) -> bool {
4545         self.intersects(TC::OwnsOwned)
4546     }
4547
4548     pub fn interior_param(&self) -> bool {
4549         self.intersects(TC::InteriorParam)
4550     }
4551
4552     pub fn interior_unsafe(&self) -> bool {
4553         self.intersects(TC::InteriorUnsafe)
4554     }
4555
4556     pub fn needs_drop(&self, _: &ctxt) -> bool {
4557         self.intersects(TC::NeedsDrop)
4558     }
4559
4560     /// Includes only those bits that still apply when indirected through a `Box` pointer
4561     pub fn owned_pointer(&self) -> TypeContents {
4562         TC::OwnsOwned | (*self & TC::OwnsAll)
4563     }
4564
4565     pub fn union<T, F>(v: &[T], mut f: F) -> TypeContents where
4566         F: FnMut(&T) -> TypeContents,
4567     {
4568         v.iter().fold(TC::None, |tc, ty| tc | f(ty))
4569     }
4570
4571     pub fn has_dtor(&self) -> bool {
4572         self.intersects(TC::OwnsDtor)
4573     }
4574 }
4575
4576 impl ops::BitOr for TypeContents {
4577     type Output = TypeContents;
4578
4579     fn bitor(self, other: TypeContents) -> TypeContents {
4580         TypeContents {bits: self.bits | other.bits}
4581     }
4582 }
4583
4584 impl ops::BitAnd for TypeContents {
4585     type Output = TypeContents;
4586
4587     fn bitand(self, other: TypeContents) -> TypeContents {
4588         TypeContents {bits: self.bits & other.bits}
4589     }
4590 }
4591
4592 impl ops::Sub for TypeContents {
4593     type Output = TypeContents;
4594
4595     fn sub(self, other: TypeContents) -> TypeContents {
4596         TypeContents {bits: self.bits & !other.bits}
4597     }
4598 }
4599
4600 impl fmt::Debug for TypeContents {
4601     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4602         write!(f, "TypeContents({:b})", self.bits)
4603     }
4604 }
4605
4606 impl<'tcx> TyS<'tcx> {
4607     pub fn type_contents(&'tcx self, cx: &ctxt<'tcx>) -> TypeContents {
4608         return memoized(&cx.tc_cache, self, |ty| {
4609             tc_ty(cx, ty, &mut FnvHashMap())
4610         });
4611
4612         fn tc_ty<'tcx>(cx: &ctxt<'tcx>,
4613                        ty: Ty<'tcx>,
4614                        cache: &mut FnvHashMap<Ty<'tcx>, TypeContents>) -> TypeContents
4615         {
4616             // Subtle: Note that we are *not* using cx.tc_cache here but rather a
4617             // private cache for this walk.  This is needed in the case of cyclic
4618             // types like:
4619             //
4620             //     struct List { next: Box<Option<List>>, ... }
4621             //
4622             // When computing the type contents of such a type, we wind up deeply
4623             // recursing as we go.  So when we encounter the recursive reference
4624             // to List, we temporarily use TC::None as its contents.  Later we'll
4625             // patch up the cache with the correct value, once we've computed it
4626             // (this is basically a co-inductive process, if that helps).  So in
4627             // the end we'll compute TC::OwnsOwned, in this case.
4628             //
4629             // The problem is, as we are doing the computation, we will also
4630             // compute an *intermediate* contents for, e.g., Option<List> of
4631             // TC::None.  This is ok during the computation of List itself, but if
4632             // we stored this intermediate value into cx.tc_cache, then later
4633             // requests for the contents of Option<List> would also yield TC::None
4634             // which is incorrect.  This value was computed based on the crutch
4635             // value for the type contents of list.  The correct value is
4636             // TC::OwnsOwned.  This manifested as issue #4821.
4637             match cache.get(&ty) {
4638                 Some(tc) => { return *tc; }
4639                 None => {}
4640             }
4641             match cx.tc_cache.borrow().get(&ty) {    // Must check both caches!
4642                 Some(tc) => { return *tc; }
4643                 None => {}
4644             }
4645             cache.insert(ty, TC::None);
4646
4647             let result = match ty.sty {
4648                 // usize and isize are ffi-unsafe
4649                 TyUint(ast::TyUs) | TyInt(ast::TyIs) => {
4650                     TC::None
4651                 }
4652
4653                 // Scalar and unique types are sendable, and durable
4654                 TyInfer(ty::FreshIntTy(_)) | TyInfer(ty::FreshFloatTy(_)) |
4655                 TyBool | TyInt(_) | TyUint(_) | TyFloat(_) |
4656                 TyBareFn(..) | ty::TyChar => {
4657                     TC::None
4658                 }
4659
4660                 TyBox(typ) => {
4661                     tc_ty(cx, typ, cache).owned_pointer()
4662                 }
4663
4664                 TyTrait(_) => {
4665                     TC::All - TC::InteriorParam
4666                 }
4667
4668                 TyRawPtr(_) => {
4669                     TC::None
4670                 }
4671
4672                 TyRef(_, _) => {
4673                     TC::None
4674                 }
4675
4676                 TyArray(ty, _) => {
4677                     tc_ty(cx, ty, cache)
4678                 }
4679
4680                 TySlice(ty) => {
4681                     tc_ty(cx, ty, cache)
4682                 }
4683                 TyStr => TC::None,
4684
4685                 TyClosure(_, ref substs) => {
4686                     TypeContents::union(&substs.upvar_tys, |ty| tc_ty(cx, &ty, cache))
4687                 }
4688
4689                 TyTuple(ref tys) => {
4690                     TypeContents::union(&tys[..],
4691                                         |ty| tc_ty(cx, *ty, cache))
4692                 }
4693
4694                 TyStruct(def, substs) | TyEnum(def, substs) => {
4695                     let mut res =
4696                         TypeContents::union(&def.variants, |v| {
4697                             TypeContents::union(&v.fields, |f| {
4698                                 tc_ty(cx, f.ty(cx, substs), cache)
4699                             })
4700                         });
4701
4702                     if def.has_dtor() {
4703                         res = res | TC::OwnsDtor;
4704                     }
4705
4706                     apply_lang_items(cx, def.did, res)
4707                 }
4708
4709                 TyProjection(..) |
4710                 TyParam(_) => {
4711                     TC::All
4712                 }
4713
4714                 TyInfer(_) |
4715                 TyError => {
4716                     cx.sess.bug("asked to compute contents of error type");
4717                 }
4718             };
4719
4720             cache.insert(ty, result);
4721             result
4722         }
4723
4724         fn apply_lang_items(cx: &ctxt, did: DefId, tc: TypeContents)
4725                             -> TypeContents {
4726             if Some(did) == cx.lang_items.unsafe_cell_type() {
4727                 tc | TC::InteriorUnsafe
4728             } else {
4729                 tc
4730             }
4731         }
4732     }
4733
4734     fn impls_bound<'a>(&'tcx self, param_env: &ParameterEnvironment<'a,'tcx>,
4735                        bound: ty::BuiltinBound,
4736                        span: Span)
4737                        -> bool
4738     {
4739         let tcx = param_env.tcx;
4740         let infcx = infer::new_infer_ctxt(tcx, &tcx.tables, Some(param_env.clone()), false);
4741
4742         let is_impld = traits::type_known_to_meet_builtin_bound(&infcx,
4743                                                                 self, bound, span);
4744
4745         debug!("Ty::impls_bound({:?}, {:?}) = {:?}",
4746                self, bound, is_impld);
4747
4748         is_impld
4749     }
4750
4751     // FIXME (@jroesch): I made this public to use it, not sure if should be private
4752     pub fn moves_by_default<'a>(&'tcx self, param_env: &ParameterEnvironment<'a,'tcx>,
4753                            span: Span) -> bool {
4754         if self.flags.get().intersects(TypeFlags::MOVENESS_CACHED) {
4755             return self.flags.get().intersects(TypeFlags::MOVES_BY_DEFAULT);
4756         }
4757
4758         assert!(!self.needs_infer());
4759
4760         // Fast-path for primitive types
4761         let result = match self.sty {
4762             TyBool | TyChar | TyInt(..) | TyUint(..) | TyFloat(..) |
4763             TyRawPtr(..) | TyBareFn(..) | TyRef(_, TypeAndMut {
4764                 mutbl: ast::MutImmutable, ..
4765             }) => Some(false),
4766
4767             TyStr | TyBox(..) | TyRef(_, TypeAndMut {
4768                 mutbl: ast::MutMutable, ..
4769             }) => Some(true),
4770
4771             TyArray(..) | TySlice(_) | TyTrait(..) | TyTuple(..) |
4772             TyClosure(..) | TyEnum(..) | TyStruct(..) |
4773             TyProjection(..) | TyParam(..) | TyInfer(..) | TyError => None
4774         }.unwrap_or_else(|| !self.impls_bound(param_env, ty::BoundCopy, span));
4775
4776         if !self.has_param_types() && !self.has_self_ty() {
4777             self.flags.set(self.flags.get() | if result {
4778                 TypeFlags::MOVENESS_CACHED | TypeFlags::MOVES_BY_DEFAULT
4779             } else {
4780                 TypeFlags::MOVENESS_CACHED
4781             });
4782         }
4783
4784         result
4785     }
4786
4787     #[inline]
4788     pub fn is_sized<'a>(&'tcx self, param_env: &ParameterEnvironment<'a,'tcx>,
4789                         span: Span) -> bool
4790     {
4791         if self.flags.get().intersects(TypeFlags::SIZEDNESS_CACHED) {
4792             return self.flags.get().intersects(TypeFlags::IS_SIZED);
4793         }
4794
4795         self.is_sized_uncached(param_env, span)
4796     }
4797
4798     fn is_sized_uncached<'a>(&'tcx self, param_env: &ParameterEnvironment<'a,'tcx>,
4799                              span: Span) -> bool {
4800         assert!(!self.needs_infer());
4801
4802         // Fast-path for primitive types
4803         let result = match self.sty {
4804             TyBool | TyChar | TyInt(..) | TyUint(..) | TyFloat(..) |
4805             TyBox(..) | TyRawPtr(..) | TyRef(..) | TyBareFn(..) |
4806             TyArray(..) | TyTuple(..) | TyClosure(..) => Some(true),
4807
4808             TyStr | TyTrait(..) | TySlice(_) => Some(false),
4809
4810             TyEnum(..) | TyStruct(..) | TyProjection(..) | TyParam(..) |
4811             TyInfer(..) | TyError => None
4812         }.unwrap_or_else(|| self.impls_bound(param_env, ty::BoundSized, span));
4813
4814         if !self.has_param_types() && !self.has_self_ty() {
4815             self.flags.set(self.flags.get() | if result {
4816                 TypeFlags::SIZEDNESS_CACHED | TypeFlags::IS_SIZED
4817             } else {
4818                 TypeFlags::SIZEDNESS_CACHED
4819             });
4820         }
4821
4822         result
4823     }
4824 }
4825
4826 /// Describes whether a type is representable. For types that are not
4827 /// representable, 'SelfRecursive' and 'ContainsRecursive' are used to
4828 /// distinguish between types that are recursive with themselves and types that
4829 /// contain a different recursive type. These cases can therefore be treated
4830 /// differently when reporting errors.
4831 ///
4832 /// The ordering of the cases is significant. They are sorted so that cmp::max
4833 /// will keep the "more erroneous" of two values.
4834 #[derive(Copy, Clone, PartialOrd, Ord, Eq, PartialEq, Debug)]
4835 pub enum Representability {
4836     Representable,
4837     ContainsRecursive,
4838     SelfRecursive,
4839 }
4840
4841 impl<'tcx> TyS<'tcx> {
4842     /// Check whether a type is representable. This means it cannot contain unboxed
4843     /// structural recursion. This check is needed for structs and enums.
4844     pub fn is_representable(&'tcx self, cx: &ctxt<'tcx>, sp: Span) -> Representability {
4845
4846         // Iterate until something non-representable is found
4847         fn find_nonrepresentable<'tcx, It: Iterator<Item=Ty<'tcx>>>(cx: &ctxt<'tcx>, sp: Span,
4848                                                                     seen: &mut Vec<Ty<'tcx>>,
4849                                                                     iter: It)
4850                                                                     -> Representability {
4851             iter.fold(Representable,
4852                       |r, ty| cmp::max(r, is_type_structurally_recursive(cx, sp, seen, ty)))
4853         }
4854
4855         fn are_inner_types_recursive<'tcx>(cx: &ctxt<'tcx>, sp: Span,
4856                                            seen: &mut Vec<Ty<'tcx>>, ty: Ty<'tcx>)
4857                                            -> Representability {
4858             match ty.sty {
4859                 TyTuple(ref ts) => {
4860                     find_nonrepresentable(cx, sp, seen, ts.iter().cloned())
4861                 }
4862                 // Fixed-length vectors.
4863                 // FIXME(#11924) Behavior undecided for zero-length vectors.
4864                 TyArray(ty, _) => {
4865                     is_type_structurally_recursive(cx, sp, seen, ty)
4866                 }
4867                 TyStruct(def, substs) | TyEnum(def, substs) => {
4868                     find_nonrepresentable(cx,
4869                                           sp,
4870                                           seen,
4871                                           def.all_fields().map(|f| f.ty(cx, substs)))
4872                 }
4873                 TyClosure(..) => {
4874                     // this check is run on type definitions, so we don't expect
4875                     // to see closure types
4876                     cx.sess.bug(&format!("requires check invoked on inapplicable type: {:?}", ty))
4877                 }
4878                 _ => Representable,
4879             }
4880         }
4881
4882         fn same_struct_or_enum<'tcx>(ty: Ty<'tcx>, def: AdtDef<'tcx>) -> bool {
4883             match ty.sty {
4884                 TyStruct(ty_def, _) | TyEnum(ty_def, _) => {
4885                      ty_def == def
4886                 }
4887                 _ => false
4888             }
4889         }
4890
4891         fn same_type<'tcx>(a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
4892             match (&a.sty, &b.sty) {
4893                 (&TyStruct(did_a, ref substs_a), &TyStruct(did_b, ref substs_b)) |
4894                 (&TyEnum(did_a, ref substs_a), &TyEnum(did_b, ref substs_b)) => {
4895                     if did_a != did_b {
4896                         return false;
4897                     }
4898
4899                     let types_a = substs_a.types.get_slice(subst::TypeSpace);
4900                     let types_b = substs_b.types.get_slice(subst::TypeSpace);
4901
4902                     let mut pairs = types_a.iter().zip(types_b);
4903
4904                     pairs.all(|(&a, &b)| same_type(a, b))
4905                 }
4906                 _ => {
4907                     a == b
4908                 }
4909             }
4910         }
4911
4912         // Does the type `ty` directly (without indirection through a pointer)
4913         // contain any types on stack `seen`?
4914         fn is_type_structurally_recursive<'tcx>(cx: &ctxt<'tcx>, sp: Span,
4915                                                 seen: &mut Vec<Ty<'tcx>>,
4916                                                 ty: Ty<'tcx>) -> Representability {
4917             debug!("is_type_structurally_recursive: {:?}", ty);
4918
4919             match ty.sty {
4920                 TyStruct(def, _) | TyEnum(def, _) => {
4921                     {
4922                         // Iterate through stack of previously seen types.
4923                         let mut iter = seen.iter();
4924
4925                         // The first item in `seen` is the type we are actually curious about.
4926                         // We want to return SelfRecursive if this type contains itself.
4927                         // It is important that we DON'T take generic parameters into account
4928                         // for this check, so that Bar<T> in this example counts as SelfRecursive:
4929                         //
4930                         // struct Foo;
4931                         // struct Bar<T> { x: Bar<Foo> }
4932
4933                         match iter.next() {
4934                             Some(&seen_type) => {
4935                                 if same_struct_or_enum(seen_type, def) {
4936                                     debug!("SelfRecursive: {:?} contains {:?}",
4937                                            seen_type,
4938                                            ty);
4939                                     return SelfRecursive;
4940                                 }
4941                             }
4942                             None => {}
4943                         }
4944
4945                         // We also need to know whether the first item contains other types
4946                         // that are structurally recursive. If we don't catch this case, we
4947                         // will recurse infinitely for some inputs.
4948                         //
4949                         // It is important that we DO take generic parameters into account
4950                         // here, so that code like this is considered SelfRecursive, not
4951                         // ContainsRecursive:
4952                         //
4953                         // struct Foo { Option<Option<Foo>> }
4954
4955                         for &seen_type in iter {
4956                             if same_type(ty, seen_type) {
4957                                 debug!("ContainsRecursive: {:?} contains {:?}",
4958                                        seen_type,
4959                                        ty);
4960                                 return ContainsRecursive;
4961                             }
4962                         }
4963                     }
4964
4965                     // For structs and enums, track all previously seen types by pushing them
4966                     // onto the 'seen' stack.
4967                     seen.push(ty);
4968                     let out = are_inner_types_recursive(cx, sp, seen, ty);
4969                     seen.pop();
4970                     out
4971                 }
4972                 _ => {
4973                     // No need to push in other cases.
4974                     are_inner_types_recursive(cx, sp, seen, ty)
4975                 }
4976             }
4977         }
4978
4979         debug!("is_type_representable: {:?}", self);
4980
4981         // To avoid a stack overflow when checking an enum variant or struct that
4982         // contains a different, structurally recursive type, maintain a stack
4983         // of seen types and check recursion for each of them (issues #3008, #3779).
4984         let mut seen: Vec<Ty> = Vec::new();
4985         let r = is_type_structurally_recursive(cx, sp, &mut seen, self);
4986         debug!("is_type_representable: {:?} is {:?}", self, r);
4987         r
4988     }
4989
4990     pub fn is_trait(&self) -> bool {
4991         match self.sty {
4992             TyTrait(..) => true,
4993             _ => false
4994         }
4995     }
4996
4997     pub fn is_integral(&self) -> bool {
4998         match self.sty {
4999             TyInfer(IntVar(_)) | TyInt(_) | TyUint(_) => true,
5000             _ => false
5001         }
5002     }
5003
5004     pub fn is_fresh(&self) -> bool {
5005         match self.sty {
5006             TyInfer(FreshTy(_)) => true,
5007             TyInfer(FreshIntTy(_)) => true,
5008             TyInfer(FreshFloatTy(_)) => true,
5009             _ => false
5010         }
5011     }
5012
5013     pub fn is_uint(&self) -> bool {
5014         match self.sty {
5015             TyInfer(IntVar(_)) | TyUint(ast::TyUs) => true,
5016             _ => false
5017         }
5018     }
5019
5020     pub fn is_char(&self) -> bool {
5021         match self.sty {
5022             TyChar => true,
5023             _ => false
5024         }
5025     }
5026
5027     pub fn is_bare_fn(&self) -> bool {
5028         match self.sty {
5029             TyBareFn(..) => true,
5030             _ => false
5031         }
5032     }
5033
5034     pub fn is_bare_fn_item(&self) -> bool {
5035         match self.sty {
5036             TyBareFn(Some(_), _) => true,
5037             _ => false
5038         }
5039     }
5040
5041     pub fn is_fp(&self) -> bool {
5042         match self.sty {
5043             TyInfer(FloatVar(_)) | TyFloat(_) => true,
5044             _ => false
5045         }
5046     }
5047
5048     pub fn is_numeric(&self) -> bool {
5049         self.is_integral() || self.is_fp()
5050     }
5051
5052     pub fn is_signed(&self) -> bool {
5053         match self.sty {
5054             TyInt(_) => true,
5055             _ => false
5056         }
5057     }
5058
5059     pub fn is_machine(&self) -> bool {
5060         match self.sty {
5061             TyInt(ast::TyIs) | TyUint(ast::TyUs) => false,
5062             TyInt(..) | TyUint(..) | TyFloat(..) => true,
5063             _ => false
5064         }
5065     }
5066
5067     // Returns the type and mutability of *ty.
5068     //
5069     // The parameter `explicit` indicates if this is an *explicit* dereference.
5070     // Some types---notably unsafe ptrs---can only be dereferenced explicitly.
5071     pub fn builtin_deref(&self, explicit: bool) -> Option<TypeAndMut<'tcx>> {
5072         match self.sty {
5073             TyBox(ty) => {
5074                 Some(TypeAndMut {
5075                     ty: ty,
5076                     mutbl: ast::MutImmutable,
5077                 })
5078             },
5079             TyRef(_, mt) => Some(mt),
5080             TyRawPtr(mt) if explicit => Some(mt),
5081             _ => None
5082         }
5083     }
5084
5085     // Returns the type of ty[i]
5086     pub fn builtin_index(&self) -> Option<Ty<'tcx>> {
5087         match self.sty {
5088             TyArray(ty, _) | TySlice(ty) => Some(ty),
5089             _ => None
5090         }
5091     }
5092
5093     pub fn fn_sig(&self) -> &'tcx PolyFnSig<'tcx> {
5094         match self.sty {
5095             TyBareFn(_, ref f) => &f.sig,
5096             _ => panic!("Ty::fn_sig() called on non-fn type: {:?}", self)
5097         }
5098     }
5099
5100     /// Returns the ABI of the given function.
5101     pub fn fn_abi(&self) -> abi::Abi {
5102         match self.sty {
5103             TyBareFn(_, ref f) => f.abi,
5104             _ => panic!("Ty::fn_abi() called on non-fn type"),
5105         }
5106     }
5107
5108     // Type accessors for substructures of types
5109     pub fn fn_args(&self) -> ty::Binder<Vec<Ty<'tcx>>> {
5110         self.fn_sig().inputs()
5111     }
5112
5113     pub fn fn_ret(&self) -> Binder<FnOutput<'tcx>> {
5114         self.fn_sig().output()
5115     }
5116
5117     pub fn is_fn(&self) -> bool {
5118         match self.sty {
5119             TyBareFn(..) => true,
5120             _ => false
5121         }
5122     }
5123
5124     /// See `expr_ty_adjusted`
5125     pub fn adjust<F>(&'tcx self, cx: &ctxt<'tcx>,
5126                      span: Span,
5127                      expr_id: ast::NodeId,
5128                      adjustment: Option<&AutoAdjustment<'tcx>>,
5129                      mut method_type: F)
5130                      -> Ty<'tcx> where
5131         F: FnMut(MethodCall) -> Option<Ty<'tcx>>,
5132     {
5133         if let TyError = self.sty {
5134             return self;
5135         }
5136
5137         return match adjustment {
5138             Some(adjustment) => {
5139                 match *adjustment {
5140                    AdjustReifyFnPointer => {
5141                         match self.sty {
5142                             ty::TyBareFn(Some(_), b) => {
5143                                 cx.mk_fn(None, b)
5144                             }
5145                             _ => {
5146                                 cx.sess.bug(
5147                                     &format!("AdjustReifyFnPointer adjustment on non-fn-item: \
5148                                               {:?}", self));
5149                             }
5150                         }
5151                     }
5152
5153                    AdjustUnsafeFnPointer => {
5154                         match self.sty {
5155                             ty::TyBareFn(None, b) => cx.safe_to_unsafe_fn_ty(b),
5156                             ref b => {
5157                                 cx.sess.bug(
5158                                     &format!("AdjustReifyFnPointer adjustment on non-fn-item: \
5159                                              {:?}",
5160                                             b));
5161                             }
5162                         }
5163                    }
5164
5165                     AdjustDerefRef(ref adj) => {
5166                         let mut adjusted_ty = self;
5167
5168                         if !adjusted_ty.references_error() {
5169                             for i in 0..adj.autoderefs {
5170                                 let method_call = MethodCall::autoderef(expr_id, i as u32);
5171                                 match method_type(method_call) {
5172                                     Some(method_ty) => {
5173                                         // Overloaded deref operators have all late-bound
5174                                         // regions fully instantiated and coverge.
5175                                         let fn_ret =
5176                                             cx.no_late_bound_regions(&method_ty.fn_ret()).unwrap();
5177                                         adjusted_ty = fn_ret.unwrap();
5178                                     }
5179                                     None => {}
5180                                 }
5181                                 match adjusted_ty.builtin_deref(true) {
5182                                     Some(mt) => { adjusted_ty = mt.ty; }
5183                                     None => {
5184                                         cx.sess.span_bug(
5185                                             span,
5186                                             &format!("the {}th autoderef failed: {}",
5187                                                     i,
5188                                                      adjusted_ty)
5189                                             );
5190                                     }
5191                                 }
5192                             }
5193                         }
5194
5195                         if let Some(target) = adj.unsize {
5196                             target
5197                         } else {
5198                             adjusted_ty.adjust_for_autoref(cx, adj.autoref)
5199                         }
5200                     }
5201                 }
5202             }
5203             None => self
5204         };
5205     }
5206
5207     pub fn adjust_for_autoref(&'tcx self, cx: &ctxt<'tcx>,
5208                               autoref: Option<AutoRef<'tcx>>)
5209                               -> Ty<'tcx> {
5210         match autoref {
5211             None => self,
5212             Some(AutoPtr(r, m)) => {
5213                 cx.mk_ref(r, TypeAndMut { ty: self, mutbl: m })
5214             }
5215             Some(AutoUnsafe(m)) => {
5216                 cx.mk_ptr(TypeAndMut { ty: self, mutbl: m })
5217             }
5218         }
5219     }
5220
5221     fn sort_string(&self, cx: &ctxt) -> String {
5222
5223         match self.sty {
5224             TyBool | TyChar | TyInt(_) |
5225             TyUint(_) | TyFloat(_) | TyStr => self.to_string(),
5226             TyTuple(ref tys) if tys.is_empty() => self.to_string(),
5227
5228             TyEnum(def, _) => format!("enum `{}`", cx.item_path_str(def.did)),
5229             TyBox(_) => "box".to_string(),
5230             TyArray(_, n) => format!("array of {} elements", n),
5231             TySlice(_) => "slice".to_string(),
5232             TyRawPtr(_) => "*-ptr".to_string(),
5233             TyRef(_, _) => "&-ptr".to_string(),
5234             TyBareFn(Some(_), _) => format!("fn item"),
5235             TyBareFn(None, _) => "fn pointer".to_string(),
5236             TyTrait(ref inner) => {
5237                 format!("trait {}", cx.item_path_str(inner.principal_def_id()))
5238             }
5239             TyStruct(def, _) => {
5240                 format!("struct `{}`", cx.item_path_str(def.did))
5241             }
5242             TyClosure(..) => "closure".to_string(),
5243             TyTuple(_) => "tuple".to_string(),
5244             TyInfer(TyVar(_)) => "inferred type".to_string(),
5245             TyInfer(IntVar(_)) => "integral variable".to_string(),
5246             TyInfer(FloatVar(_)) => "floating-point variable".to_string(),
5247             TyInfer(FreshTy(_)) => "skolemized type".to_string(),
5248             TyInfer(FreshIntTy(_)) => "skolemized integral type".to_string(),
5249             TyInfer(FreshFloatTy(_)) => "skolemized floating-point type".to_string(),
5250             TyProjection(_) => "associated type".to_string(),
5251             TyParam(ref p) => {
5252                 if p.space == subst::SelfSpace {
5253                     "Self".to_string()
5254                 } else {
5255                     "type parameter".to_string()
5256                 }
5257             }
5258             TyError => "type error".to_string(),
5259         }
5260     }
5261 }
5262 /// Explains the source of a type err in a short, human readable way. This is meant to be placed
5263 /// in parentheses after some larger message. You should also invoke `note_and_explain_type_err()`
5264 /// afterwards to present additional details, particularly when it comes to lifetime-related
5265 /// errors.
5266 impl<'tcx> fmt::Display for TypeError<'tcx> {
5267     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5268         use self::TypeError::*;
5269
5270         match *self {
5271             CyclicTy => write!(f, "cyclic type of infinite size"),
5272             Mismatch => write!(f, "types differ"),
5273             UnsafetyMismatch(values) => {
5274                 write!(f, "expected {} fn, found {} fn",
5275                        values.expected,
5276                        values.found)
5277             }
5278             AbiMismatch(values) => {
5279                 write!(f, "expected {} fn, found {} fn",
5280                        values.expected,
5281                        values.found)
5282             }
5283             Mutability => write!(f, "values differ in mutability"),
5284             BoxMutability => {
5285                 write!(f, "boxed values differ in mutability")
5286             }
5287             VecMutability => write!(f, "vectors differ in mutability"),
5288             PtrMutability => write!(f, "pointers differ in mutability"),
5289             RefMutability => write!(f, "references differ in mutability"),
5290             TyParamSize(values) => {
5291                 write!(f, "expected a type with {} type params, \
5292                            found one with {} type params",
5293                        values.expected,
5294                        values.found)
5295             }
5296             FixedArraySize(values) => {
5297                 write!(f, "expected an array with a fixed size of {} elements, \
5298                            found one with {} elements",
5299                        values.expected,
5300                        values.found)
5301             }
5302             TupleSize(values) => {
5303                 write!(f, "expected a tuple with {} elements, \
5304                            found one with {} elements",
5305                        values.expected,
5306                        values.found)
5307             }
5308             ArgCount => {
5309                 write!(f, "incorrect number of function parameters")
5310             }
5311             RegionsDoesNotOutlive(..) => {
5312                 write!(f, "lifetime mismatch")
5313             }
5314             RegionsNotSame(..) => {
5315                 write!(f, "lifetimes are not the same")
5316             }
5317             RegionsNoOverlap(..) => {
5318                 write!(f, "lifetimes do not intersect")
5319             }
5320             RegionsInsufficientlyPolymorphic(br, _) => {
5321                 write!(f, "expected bound lifetime parameter {}, \
5322                            found concrete lifetime", br)
5323             }
5324             RegionsOverlyPolymorphic(br, _) => {
5325                 write!(f, "expected concrete lifetime, \
5326                            found bound lifetime parameter {}", br)
5327             }
5328             Sorts(values) => tls::with(|tcx| {
5329                 // A naive approach to making sure that we're not reporting silly errors such as:
5330                 // (expected closure, found closure).
5331                 let expected_str = values.expected.sort_string(tcx);
5332                 let found_str = values.found.sort_string(tcx);
5333                 if expected_str == found_str {
5334                     write!(f, "expected {}, found a different {}", expected_str, found_str)
5335                 } else {
5336                     write!(f, "expected {}, found {}", expected_str, found_str)
5337                 }
5338             }),
5339             Traits(values) => tls::with(|tcx| {
5340                 write!(f, "expected trait `{}`, found trait `{}`",
5341                        tcx.item_path_str(values.expected),
5342                        tcx.item_path_str(values.found))
5343             }),
5344             BuiltinBoundsMismatch(values) => {
5345                 if values.expected.is_empty() {
5346                     write!(f, "expected no bounds, found `{}`",
5347                            values.found)
5348                 } else if values.found.is_empty() {
5349                     write!(f, "expected bounds `{}`, found no bounds",
5350                            values.expected)
5351                 } else {
5352                     write!(f, "expected bounds `{}`, found bounds `{}`",
5353                            values.expected,
5354                            values.found)
5355                 }
5356             }
5357             IntegerAsChar => {
5358                 write!(f, "expected an integral type, found `char`")
5359             }
5360             IntMismatch(ref values) => {
5361                 write!(f, "expected `{:?}`, found `{:?}`",
5362                        values.expected,
5363                        values.found)
5364             }
5365             FloatMismatch(ref values) => {
5366                 write!(f, "expected `{:?}`, found `{:?}`",
5367                        values.expected,
5368                        values.found)
5369             }
5370             VariadicMismatch(ref values) => {
5371                 write!(f, "expected {} fn, found {} function",
5372                        if values.expected { "variadic" } else { "non-variadic" },
5373                        if values.found { "variadic" } else { "non-variadic" })
5374             }
5375             ConvergenceMismatch(ref values) => {
5376                 write!(f, "expected {} fn, found {} function",
5377                        if values.expected { "converging" } else { "diverging" },
5378                        if values.found { "converging" } else { "diverging" })
5379             }
5380             ProjectionNameMismatched(ref values) => {
5381                 write!(f, "expected {}, found {}",
5382                        values.expected,
5383                        values.found)
5384             }
5385             ProjectionBoundsLength(ref values) => {
5386                 write!(f, "expected {} associated type bindings, found {}",
5387                        values.expected,
5388                        values.found)
5389             },
5390             TyParamDefaultMismatch(ref values) => {
5391                 write!(f, "conflicting type parameter defaults `{}` and `{}`",
5392                        values.expected.ty,
5393                        values.found.ty)
5394             }
5395         }
5396     }
5397 }
5398
5399 /// Helper for looking things up in the various maps that are populated during
5400 /// typeck::collect (e.g., `cx.impl_or_trait_items`, `cx.tcache`, etc).  All of
5401 /// these share the pattern that if the id is local, it should have been loaded
5402 /// into the map by the `typeck::collect` phase.  If the def-id is external,
5403 /// then we have to go consult the crate loading code (and cache the result for
5404 /// the future).
5405 fn lookup_locally_or_in_crate_store<V, F>(descr: &str,
5406                                           def_id: DefId,
5407                                           map: &RefCell<DefIdMap<V>>,
5408                                           load_external: F) -> V where
5409     V: Clone,
5410     F: FnOnce() -> V,
5411 {
5412     match map.borrow().get(&def_id).cloned() {
5413         Some(v) => { return v; }
5414         None => { }
5415     }
5416
5417     if def_id.is_local() {
5418         panic!("No def'n found for {:?} in tcx.{}", def_id, descr);
5419     }
5420     let v = load_external();
5421     map.borrow_mut().insert(def_id, v.clone());
5422     v
5423 }
5424
5425 impl BorrowKind {
5426     pub fn from_mutbl(m: ast::Mutability) -> BorrowKind {
5427         match m {
5428             ast::MutMutable => MutBorrow,
5429             ast::MutImmutable => ImmBorrow,
5430         }
5431     }
5432
5433     /// Returns a mutability `m` such that an `&m T` pointer could be used to obtain this borrow
5434     /// kind. Because borrow kinds are richer than mutabilities, we sometimes have to pick a
5435     /// mutability that is stronger than necessary so that it at least *would permit* the borrow in
5436     /// question.
5437     pub fn to_mutbl_lossy(self) -> ast::Mutability {
5438         match self {
5439             MutBorrow => ast::MutMutable,
5440             ImmBorrow => ast::MutImmutable,
5441
5442             // We have no type corresponding to a unique imm borrow, so
5443             // use `&mut`. It gives all the capabilities of an `&uniq`
5444             // and hence is a safe "over approximation".
5445             UniqueImmBorrow => ast::MutMutable,
5446         }
5447     }
5448
5449     pub fn to_user_str(&self) -> &'static str {
5450         match *self {
5451             MutBorrow => "mutable",
5452             ImmBorrow => "immutable",
5453             UniqueImmBorrow => "uniquely immutable",
5454         }
5455     }
5456 }
5457
5458 impl<'tcx> ctxt<'tcx> {
5459     /// Returns the type of element at index `i` in tuple or tuple-like type `t`.
5460     /// For an enum `t`, `variant` is None only if `t` is a univariant enum.
5461     pub fn positional_element_ty(&self,
5462                                  ty: Ty<'tcx>,
5463                                  i: usize,
5464                                  variant: Option<DefId>) -> Option<Ty<'tcx>> {
5465         match (&ty.sty, variant) {
5466             (&TyStruct(def, substs), None) => {
5467                 def.struct_variant().fields.get(i).map(|f| f.ty(self, substs))
5468             }
5469             (&TyEnum(def, substs), Some(vid)) => {
5470                 def.variant_with_id(vid).fields.get(i).map(|f| f.ty(self, substs))
5471             }
5472             (&TyEnum(def, substs), None) => {
5473                 assert!(def.is_univariant());
5474                 def.variants[0].fields.get(i).map(|f| f.ty(self, substs))
5475             }
5476             (&TyTuple(ref v), None) => v.get(i).cloned(),
5477             _ => None
5478         }
5479     }
5480
5481     /// Returns the type of element at field `n` in struct or struct-like type `t`.
5482     /// For an enum `t`, `variant` must be some def id.
5483     pub fn named_element_ty(&self,
5484                             ty: Ty<'tcx>,
5485                             n: ast::Name,
5486                             variant: Option<DefId>) -> Option<Ty<'tcx>> {
5487         match (&ty.sty, variant) {
5488             (&TyStruct(def, substs), None) => {
5489                 def.struct_variant().find_field_named(n).map(|f| f.ty(self, substs))
5490             }
5491             (&TyEnum(def, substs), Some(vid)) => {
5492                 def.variant_with_id(vid).find_field_named(n).map(|f| f.ty(self, substs))
5493             }
5494             _ => return None
5495         }
5496     }
5497
5498     pub fn node_id_to_type(&self, id: ast::NodeId) -> Ty<'tcx> {
5499         match self.node_id_to_type_opt(id) {
5500            Some(ty) => ty,
5501            None => self.sess.bug(
5502                &format!("node_id_to_type: no type for node `{}`",
5503                         self.map.node_to_string(id)))
5504         }
5505     }
5506
5507     pub fn node_id_to_type_opt(&self, id: ast::NodeId) -> Option<Ty<'tcx>> {
5508         self.tables.borrow().node_types.get(&id).cloned()
5509     }
5510
5511     pub fn node_id_item_substs(&self, id: ast::NodeId) -> ItemSubsts<'tcx> {
5512         match self.tables.borrow().item_substs.get(&id) {
5513             None => ItemSubsts::empty(),
5514             Some(ts) => ts.clone(),
5515         }
5516     }
5517
5518     // Returns the type of a pattern as a monotype. Like @expr_ty, this function
5519     // doesn't provide type parameter substitutions.
5520     pub fn pat_ty(&self, pat: &ast::Pat) -> Ty<'tcx> {
5521         self.node_id_to_type(pat.id)
5522     }
5523     pub fn pat_ty_opt(&self, pat: &ast::Pat) -> Option<Ty<'tcx>> {
5524         self.node_id_to_type_opt(pat.id)
5525     }
5526
5527     // Returns the type of an expression as a monotype.
5528     //
5529     // NB (1): This is the PRE-ADJUSTMENT TYPE for the expression.  That is, in
5530     // some cases, we insert `AutoAdjustment` annotations such as auto-deref or
5531     // auto-ref.  The type returned by this function does not consider such
5532     // adjustments.  See `expr_ty_adjusted()` instead.
5533     //
5534     // NB (2): This type doesn't provide type parameter substitutions; e.g. if you
5535     // ask for the type of "id" in "id(3)", it will return "fn(&isize) -> isize"
5536     // instead of "fn(ty) -> T with T = isize".
5537     pub fn expr_ty(&self, expr: &ast::Expr) -> Ty<'tcx> {
5538         self.node_id_to_type(expr.id)
5539     }
5540
5541     pub fn expr_ty_opt(&self, expr: &ast::Expr) -> Option<Ty<'tcx>> {
5542         self.node_id_to_type_opt(expr.id)
5543     }
5544
5545     /// Returns the type of `expr`, considering any `AutoAdjustment`
5546     /// entry recorded for that expression.
5547     ///
5548     /// It would almost certainly be better to store the adjusted ty in with
5549     /// the `AutoAdjustment`, but I opted not to do this because it would
5550     /// require serializing and deserializing the type and, although that's not
5551     /// hard to do, I just hate that code so much I didn't want to touch it
5552     /// unless it was to fix it properly, which seemed a distraction from the
5553     /// thread at hand! -nmatsakis
5554     pub fn expr_ty_adjusted(&self, expr: &ast::Expr) -> Ty<'tcx> {
5555         self.expr_ty(expr)
5556             .adjust(self, expr.span, expr.id,
5557                     self.tables.borrow().adjustments.get(&expr.id),
5558                     |method_call| {
5559             self.tables.borrow().method_map.get(&method_call).map(|method| method.ty)
5560         })
5561     }
5562
5563     pub fn expr_span(&self, id: NodeId) -> Span {
5564         match self.map.find(id) {
5565             Some(ast_map::NodeExpr(e)) => {
5566                 e.span
5567             }
5568             Some(f) => {
5569                 self.sess.bug(&format!("Node id {} is not an expr: {:?}",
5570                                        id, f));
5571             }
5572             None => {
5573                 self.sess.bug(&format!("Node id {} is not present \
5574                                         in the node map", id));
5575             }
5576         }
5577     }
5578
5579     pub fn local_var_name_str(&self, id: NodeId) -> InternedString {
5580         match self.map.find(id) {
5581             Some(ast_map::NodeLocal(pat)) => {
5582                 match pat.node {
5583                     ast::PatIdent(_, ref path1, _) => path1.node.name.as_str(),
5584                     _ => {
5585                         self.sess.bug(&format!("Variable id {} maps to {:?}, not local", id, pat));
5586                     },
5587                 }
5588             },
5589             r => self.sess.bug(&format!("Variable id {} maps to {:?}, not local", id, r)),
5590         }
5591     }
5592
5593     pub fn resolve_expr(&self, expr: &ast::Expr) -> def::Def {
5594         match self.def_map.borrow().get(&expr.id) {
5595             Some(def) => def.full_def(),
5596             None => {
5597                 self.sess.span_bug(expr.span, &format!(
5598                     "no def-map entry for expr {}", expr.id));
5599             }
5600         }
5601     }
5602
5603     pub fn expr_is_lval(&self, expr: &ast::Expr) -> bool {
5604          match expr.node {
5605             ast::ExprPath(..) => {
5606                 // We can't use resolve_expr here, as this needs to run on broken
5607                 // programs. We don't need to through - associated items are all
5608                 // rvalues.
5609                 match self.def_map.borrow().get(&expr.id) {
5610                     Some(&def::PathResolution {
5611                         base_def: def::DefStatic(..), ..
5612                     }) | Some(&def::PathResolution {
5613                         base_def: def::DefUpvar(..), ..
5614                     }) | Some(&def::PathResolution {
5615                         base_def: def::DefLocal(..), ..
5616                     }) => {
5617                         true
5618                     }
5619
5620                     Some(..) => false,
5621
5622                     None => self.sess.span_bug(expr.span, &format!(
5623                         "no def for path {}", expr.id))
5624                 }
5625             }
5626
5627             ast::ExprUnary(ast::UnDeref, _) |
5628             ast::ExprField(..) |
5629             ast::ExprTupField(..) |
5630             ast::ExprIndex(..) => {
5631                 true
5632             }
5633
5634             ast::ExprCall(..) |
5635             ast::ExprMethodCall(..) |
5636             ast::ExprStruct(..) |
5637             ast::ExprRange(..) |
5638             ast::ExprTup(..) |
5639             ast::ExprIf(..) |
5640             ast::ExprMatch(..) |
5641             ast::ExprClosure(..) |
5642             ast::ExprBlock(..) |
5643             ast::ExprRepeat(..) |
5644             ast::ExprVec(..) |
5645             ast::ExprBreak(..) |
5646             ast::ExprAgain(..) |
5647             ast::ExprRet(..) |
5648             ast::ExprWhile(..) |
5649             ast::ExprLoop(..) |
5650             ast::ExprAssign(..) |
5651             ast::ExprInlineAsm(..) |
5652             ast::ExprAssignOp(..) |
5653             ast::ExprLit(_) |
5654             ast::ExprUnary(..) |
5655             ast::ExprBox(..) |
5656             ast::ExprAddrOf(..) |
5657             ast::ExprBinary(..) |
5658             ast::ExprCast(..) => {
5659                 false
5660             }
5661
5662             ast::ExprParen(ref e) => self.expr_is_lval(e),
5663
5664             ast::ExprIfLet(..) |
5665             ast::ExprWhileLet(..) |
5666             ast::ExprForLoop(..) |
5667             ast::ExprMac(..) => {
5668                 self.sess.span_bug(
5669                     expr.span,
5670                     "macro expression remains after expansion");
5671             }
5672         }
5673     }
5674
5675     pub fn note_and_explain_type_err(&self, err: &TypeError<'tcx>, sp: Span) {
5676         use self::TypeError::*;
5677
5678         match err.clone() {
5679             RegionsDoesNotOutlive(subregion, superregion) => {
5680                 self.note_and_explain_region("", subregion, "...");
5681                 self.note_and_explain_region("...does not necessarily outlive ",
5682                                            superregion, "");
5683             }
5684             RegionsNotSame(region1, region2) => {
5685                 self.note_and_explain_region("", region1, "...");
5686                 self.note_and_explain_region("...is not the same lifetime as ",
5687                                            region2, "");
5688             }
5689             RegionsNoOverlap(region1, region2) => {
5690                 self.note_and_explain_region("", region1, "...");
5691                 self.note_and_explain_region("...does not overlap ",
5692                                            region2, "");
5693             }
5694             RegionsInsufficientlyPolymorphic(_, conc_region) => {
5695                 self.note_and_explain_region("concrete lifetime that was found is ",
5696                                            conc_region, "");
5697             }
5698             RegionsOverlyPolymorphic(_, ty::ReVar(_)) => {
5699                 // don't bother to print out the message below for
5700                 // inference variables, it's not very illuminating.
5701             }
5702             RegionsOverlyPolymorphic(_, conc_region) => {
5703                 self.note_and_explain_region("expected concrete lifetime is ",
5704                                            conc_region, "");
5705             }
5706             Sorts(values) => {
5707                 let expected_str = values.expected.sort_string(self);
5708                 let found_str = values.found.sort_string(self);
5709                 if expected_str == found_str && expected_str == "closure" {
5710                     self.sess.span_note(sp,
5711                         &format!("no two closures, even if identical, have the same type"));
5712                     self.sess.span_help(sp,
5713                         &format!("consider boxing your closure and/or \
5714                                   using it as a trait object"));
5715                 }
5716             },
5717             TyParamDefaultMismatch(values) => {
5718                 let expected = values.expected;
5719                 let found = values.found;
5720                 self.sess.span_note(sp,
5721                                     &format!("conflicting type parameter defaults `{}` and `{}`",
5722                                              expected.ty,
5723                                              found.ty));
5724
5725                 match (expected.def_id.is_local(),
5726                        self.map.opt_span(expected.def_id.node)) {
5727                     (true, Some(span)) => {
5728                         self.sess.span_note(span,
5729                                             &format!("a default was defined here..."));
5730                     }
5731                     (_, _) => {
5732                         self.sess.note(
5733                             &format!("a default is defined on `{}`",
5734                                      self.item_path_str(expected.def_id)));
5735                     }
5736                 }
5737
5738                 self.sess.span_note(
5739                     expected.origin_span,
5740                     &format!("...that was applied to an unconstrained type variable here"));
5741
5742                 match (found.def_id.is_local(),
5743                        self.map.opt_span(found.def_id.node)) {
5744                     (true, Some(span)) => {
5745                         self.sess.span_note(span,
5746                                             &format!("a second default was defined here..."));
5747                     }
5748                     (_, _) => {
5749                         self.sess.note(
5750                             &format!("a second default is defined on `{}`",
5751                                      self.item_path_str(found.def_id)));
5752                     }
5753                 }
5754
5755                 self.sess.span_note(
5756                     found.origin_span,
5757                     &format!("...that also applies to the same type variable here"));
5758             }
5759             _ => {}
5760         }
5761     }
5762
5763     pub fn provided_source(&self, id: DefId) -> Option<DefId> {
5764         self.provided_method_sources.borrow().get(&id).cloned()
5765     }
5766
5767     pub fn provided_trait_methods(&self, id: DefId) -> Vec<Rc<Method<'tcx>>> {
5768         if id.is_local() {
5769             if let ItemTrait(_, _, _, ref ms) = self.map.expect_item(id.node).node {
5770                 ms.iter().filter_map(|ti| {
5771                     if let ast::MethodTraitItem(_, Some(_)) = ti.node {
5772                         match self.impl_or_trait_item(DefId::local(ti.id)) {
5773                             MethodTraitItem(m) => Some(m),
5774                             _ => {
5775                                 self.sess.bug("provided_trait_methods(): \
5776                                                non-method item found from \
5777                                                looking up provided method?!")
5778                             }
5779                         }
5780                     } else {
5781                         None
5782                     }
5783                 }).collect()
5784             } else {
5785                 self.sess.bug(&format!("provided_trait_methods: `{:?}` is not a trait", id))
5786             }
5787         } else {
5788             csearch::get_provided_trait_methods(self, id)
5789         }
5790     }
5791
5792     pub fn associated_consts(&self, id: DefId) -> Vec<Rc<AssociatedConst<'tcx>>> {
5793         if id.is_local() {
5794             match self.map.expect_item(id.node).node {
5795                 ItemTrait(_, _, _, ref tis) => {
5796                     tis.iter().filter_map(|ti| {
5797                         if let ast::ConstTraitItem(_, _) = ti.node {
5798                             match self.impl_or_trait_item(DefId::local(ti.id)) {
5799                                 ConstTraitItem(ac) => Some(ac),
5800                                 _ => {
5801                                     self.sess.bug("associated_consts(): \
5802                                                    non-const item found from \
5803                                                    looking up a constant?!")
5804                                 }
5805                             }
5806                         } else {
5807                             None
5808                         }
5809                     }).collect()
5810                 }
5811                 ItemImpl(_, _, _, _, _, ref iis) => {
5812                     iis.iter().filter_map(|ii| {
5813                         if let ast::ConstImplItem(_, _) = ii.node {
5814                             match self.impl_or_trait_item(DefId::local(ii.id)) {
5815                                 ConstTraitItem(ac) => Some(ac),
5816                                 _ => {
5817                                     self.sess.bug("associated_consts(): \
5818                                                    non-const item found from \
5819                                                    looking up a constant?!")
5820                                 }
5821                             }
5822                         } else {
5823                             None
5824                         }
5825                     }).collect()
5826                 }
5827                 _ => {
5828                     self.sess.bug(&format!("associated_consts: `{:?}` is not a trait \
5829                                             or impl", id))
5830                 }
5831             }
5832         } else {
5833             csearch::get_associated_consts(self, id)
5834         }
5835     }
5836
5837     pub fn trait_items(&self, trait_did: DefId) -> Rc<Vec<ImplOrTraitItem<'tcx>>> {
5838         let mut trait_items = self.trait_items_cache.borrow_mut();
5839         match trait_items.get(&trait_did).cloned() {
5840             Some(trait_items) => trait_items,
5841             None => {
5842                 let def_ids = self.trait_item_def_ids(trait_did);
5843                 let items: Rc<Vec<ImplOrTraitItem>> =
5844                     Rc::new(def_ids.iter()
5845                                    .map(|d| self.impl_or_trait_item(d.def_id()))
5846                                    .collect());
5847                 trait_items.insert(trait_did, items.clone());
5848                 items
5849             }
5850         }
5851     }
5852
5853     pub fn trait_impl_polarity(&self, id: DefId) -> Option<ast::ImplPolarity> {
5854         if id.is_local() {
5855             match self.map.find(id.node) {
5856                 Some(ast_map::NodeItem(item)) => {
5857                     match item.node {
5858                         ast::ItemImpl(_, polarity, _, _, _, _) => Some(polarity),
5859                         _ => None
5860                     }
5861                 }
5862                 _ => None
5863             }
5864         } else {
5865             csearch::get_impl_polarity(self, id)
5866         }
5867     }
5868
5869     pub fn custom_coerce_unsized_kind(&self, did: DefId) -> CustomCoerceUnsized {
5870         memoized(&self.custom_coerce_unsized_kinds, did, |did: DefId| {
5871             let (kind, src) = if did.krate != LOCAL_CRATE {
5872                 (csearch::get_custom_coerce_unsized_kind(self, did), "external")
5873             } else {
5874                 (None, "local")
5875             };
5876
5877             match kind {
5878                 Some(kind) => kind,
5879                 None => {
5880                     self.sess.bug(&format!("custom_coerce_unsized_kind: \
5881                                             {} impl `{}` is missing its kind",
5882                                            src, self.item_path_str(did)));
5883                 }
5884             }
5885         })
5886     }
5887
5888     pub fn impl_or_trait_item(&self, id: DefId) -> ImplOrTraitItem<'tcx> {
5889         lookup_locally_or_in_crate_store(
5890             "impl_or_trait_items", id, &self.impl_or_trait_items,
5891             || csearch::get_impl_or_trait_item(self, id))
5892     }
5893
5894     pub fn trait_item_def_ids(&self, id: DefId) -> Rc<Vec<ImplOrTraitItemId>> {
5895         lookup_locally_or_in_crate_store(
5896             "trait_item_def_ids", id, &self.trait_item_def_ids,
5897             || Rc::new(csearch::get_trait_item_def_ids(&self.sess.cstore, id)))
5898     }
5899
5900     /// Returns the trait-ref corresponding to a given impl, or None if it is
5901     /// an inherent impl.
5902     pub fn impl_trait_ref(&self, id: DefId) -> Option<TraitRef<'tcx>> {
5903         lookup_locally_or_in_crate_store(
5904             "impl_trait_refs", id, &self.impl_trait_refs,
5905             || csearch::get_impl_trait(self, id))
5906     }
5907
5908     /// Returns whether this DefId refers to an impl
5909     pub fn is_impl(&self, id: DefId) -> bool {
5910         if id.is_local() {
5911             if let Some(ast_map::NodeItem(
5912                 &ast::Item { node: ast::ItemImpl(..), .. })) = self.map.find(id.node) {
5913                 true
5914             } else {
5915                 false
5916             }
5917         } else {
5918             csearch::is_impl(&self.sess.cstore, id)
5919         }
5920     }
5921
5922     pub fn trait_ref_to_def_id(&self, tr: &ast::TraitRef) -> DefId {
5923         self.def_map.borrow().get(&tr.ref_id).expect("no def-map entry for trait").def_id()
5924     }
5925
5926     pub fn try_add_builtin_trait(&self,
5927                                  trait_def_id: DefId,
5928                                  builtin_bounds: &mut EnumSet<BuiltinBound>)
5929                                  -> bool
5930     {
5931         //! Checks whether `trait_ref` refers to one of the builtin
5932         //! traits, like `Send`, and adds the corresponding
5933         //! bound to the set `builtin_bounds` if so. Returns true if `trait_ref`
5934         //! is a builtin trait.
5935
5936         match self.lang_items.to_builtin_kind(trait_def_id) {
5937             Some(bound) => { builtin_bounds.insert(bound); true }
5938             None => false
5939         }
5940     }
5941
5942     pub fn item_path_str(&self, id: DefId) -> String {
5943         self.with_path(id, |path| ast_map::path_to_string(path))
5944     }
5945
5946     pub fn with_path<T, F>(&self, id: DefId, f: F) -> T where
5947         F: FnOnce(ast_map::PathElems) -> T,
5948     {
5949         if id.is_local() {
5950             self.map.with_path(id.node, f)
5951         } else {
5952             f(csearch::get_item_path(self, id).iter().cloned().chain(LinkedPath::empty()))
5953         }
5954     }
5955
5956     pub fn item_name(&self, id: DefId) -> ast::Name {
5957         if id.is_local() {
5958             self.map.get_path_elem(id.node).name()
5959         } else {
5960             csearch::get_item_name(self, id)
5961         }
5962     }
5963
5964     /// Returns `(normalized_type, ty)`, where `normalized_type` is the
5965     /// IntType representation of one of {i64,i32,i16,i8,u64,u32,u16,u8},
5966     /// and `ty` is the original type (i.e. may include `isize` or
5967     /// `usize`).
5968     pub fn enum_repr_type(&self, opt_hint: Option<&attr::ReprAttr>)
5969                           -> (attr::IntType, Ty<'tcx>) {
5970         let repr_type = match opt_hint {
5971             // Feed in the given type
5972             Some(&attr::ReprInt(_, int_t)) => int_t,
5973             // ... but provide sensible default if none provided
5974             //
5975             // NB. Historically `fn enum_variants` generate i64 here, while
5976             // rustc_typeck::check would generate isize.
5977             _ => SignedInt(ast::TyIs),
5978         };
5979
5980         let repr_type_ty = repr_type.to_ty(self);
5981         let repr_type = match repr_type {
5982             SignedInt(ast::TyIs) =>
5983                 SignedInt(self.sess.target.int_type),
5984             UnsignedInt(ast::TyUs) =>
5985                 UnsignedInt(self.sess.target.uint_type),
5986             other => other
5987         };
5988
5989         (repr_type, repr_type_ty)
5990     }
5991
5992     // Register a given item type
5993     pub fn register_item_type(&self, did: DefId, ty: TypeScheme<'tcx>) {
5994         self.tcache.borrow_mut().insert(did, ty);
5995     }
5996
5997     // If the given item is in an external crate, looks up its type and adds it to
5998     // the type cache. Returns the type parameters and type.
5999     pub fn lookup_item_type(&self, did: DefId) -> TypeScheme<'tcx> {
6000         lookup_locally_or_in_crate_store(
6001             "tcache", did, &self.tcache,
6002             || csearch::get_type(self, did))
6003     }
6004
6005     /// Given the did of a trait, returns its canonical trait ref.
6006     pub fn lookup_trait_def(&self, did: DefId) -> &'tcx TraitDef<'tcx> {
6007         lookup_locally_or_in_crate_store(
6008             "trait_defs", did, &self.trait_defs,
6009             || self.arenas.trait_defs.alloc(csearch::get_trait_def(self, did))
6010         )
6011     }
6012
6013     /// Given the did of an ADT, return a master reference to its
6014     /// definition. Unless you are planning on fulfilling the ADT's fields,
6015     /// use lookup_adt_def instead.
6016     pub fn lookup_adt_def_master(&self, did: DefId) -> AdtDefMaster<'tcx> {
6017         lookup_locally_or_in_crate_store(
6018             "adt_defs", did, &self.adt_defs,
6019             || csearch::get_adt_def(self, did)
6020         )
6021     }
6022
6023     /// Given the did of an ADT, return a reference to its definition.
6024     pub fn lookup_adt_def(&self, did: DefId) -> AdtDef<'tcx> {
6025         // when reverse-variance goes away, a transmute::<AdtDefMaster,AdtDef>
6026         // woud be needed here.
6027         self.lookup_adt_def_master(did)
6028     }
6029
6030     /// Return the list of all interned ADT definitions
6031     pub fn adt_defs(&self) -> Vec<AdtDef<'tcx>> {
6032         self.adt_defs.borrow().values().cloned().collect()
6033     }
6034
6035     /// Given the did of an item, returns its full set of predicates.
6036     pub fn lookup_predicates(&self, did: DefId) -> GenericPredicates<'tcx> {
6037         lookup_locally_or_in_crate_store(
6038             "predicates", did, &self.predicates,
6039             || csearch::get_predicates(self, did))
6040     }
6041
6042     /// Given the did of a trait, returns its superpredicates.
6043     pub fn lookup_super_predicates(&self, did: DefId) -> GenericPredicates<'tcx> {
6044         lookup_locally_or_in_crate_store(
6045             "super_predicates", did, &self.super_predicates,
6046             || csearch::get_super_predicates(self, did))
6047     }
6048
6049     /// Get the attributes of a definition.
6050     pub fn get_attrs(&self, did: DefId) -> Cow<'tcx, [ast::Attribute]> {
6051         if did.is_local() {
6052             Cow::Borrowed(self.map.attrs(did.node))
6053         } else {
6054             Cow::Owned(csearch::get_item_attrs(&self.sess.cstore, did))
6055         }
6056     }
6057
6058     /// Determine whether an item is annotated with an attribute
6059     pub fn has_attr(&self, did: DefId, attr: &str) -> bool {
6060         self.get_attrs(did).iter().any(|item| item.check_name(attr))
6061     }
6062
6063     /// Determine whether an item is annotated with `#[repr(packed)]`
6064     pub fn lookup_packed(&self, did: DefId) -> bool {
6065         self.lookup_repr_hints(did).contains(&attr::ReprPacked)
6066     }
6067
6068     /// Determine whether an item is annotated with `#[simd]`
6069     pub fn lookup_simd(&self, did: DefId) -> bool {
6070         self.has_attr(did, "simd")
6071             || self.lookup_repr_hints(did).contains(&attr::ReprSimd)
6072     }
6073
6074     /// Obtain the representation annotation for a struct definition.
6075     pub fn lookup_repr_hints(&self, did: DefId) -> Rc<Vec<attr::ReprAttr>> {
6076         memoized(&self.repr_hint_cache, did, |did: DefId| {
6077             Rc::new(if did.is_local() {
6078                 self.get_attrs(did).iter().flat_map(|meta| {
6079                     attr::find_repr_attrs(self.sess.diagnostic(), meta).into_iter()
6080                 }).collect()
6081             } else {
6082                 csearch::get_repr_attrs(&self.sess.cstore, did)
6083             })
6084         })
6085     }
6086
6087     /// Returns the deeply last field of nested structures, or the same type,
6088     /// if not a structure at all. Corresponds to the only possible unsized
6089     /// field, and its type can be used to determine unsizing strategy.
6090     pub fn struct_tail(&self, mut ty: Ty<'tcx>) -> Ty<'tcx> {
6091         while let TyStruct(def, substs) = ty.sty {
6092             match def.struct_variant().fields.last() {
6093                 Some(f) => ty = f.ty(self, substs),
6094                 None => break
6095             }
6096         }
6097         ty
6098     }
6099
6100     /// Same as applying struct_tail on `source` and `target`, but only
6101     /// keeps going as long as the two types are instances of the same
6102     /// structure definitions.
6103     /// For `(Foo<Foo<T>>, Foo<Trait>)`, the result will be `(Foo<T>, Trait)`,
6104     /// whereas struct_tail produces `T`, and `Trait`, respectively.
6105     pub fn struct_lockstep_tails(&self,
6106                                  source: Ty<'tcx>,
6107                                  target: Ty<'tcx>)
6108                                  -> (Ty<'tcx>, Ty<'tcx>) {
6109         let (mut a, mut b) = (source, target);
6110         while let (&TyStruct(a_def, a_substs), &TyStruct(b_def, b_substs)) = (&a.sty, &b.sty) {
6111             if a_def != b_def {
6112                 break;
6113             }
6114             if let Some(f) = a_def.struct_variant().fields.last() {
6115                 a = f.ty(self, a_substs);
6116                 b = f.ty(self, b_substs);
6117             } else {
6118                 break;
6119             }
6120         }
6121         (a, b)
6122     }
6123
6124     // Returns the repeat count for a repeating vector expression.
6125     pub fn eval_repeat_count(&self, count_expr: &ast::Expr) -> usize {
6126         let hint = UncheckedExprHint(self.types.usize);
6127         match const_eval::eval_const_expr_partial(self, count_expr, hint) {
6128             Ok(val) => {
6129                 let found = match val {
6130                     ConstVal::Uint(count) => return count as usize,
6131                     ConstVal::Int(count) if count >= 0 => return count as usize,
6132                     const_val => const_val.description(),
6133                 };
6134                 span_err!(self.sess, count_expr.span, E0306,
6135                     "expected positive integer for repeat count, found {}",
6136                     found);
6137             }
6138             Err(err) => {
6139                 let err_msg = match count_expr.node {
6140                     ast::ExprPath(None, ast::Path {
6141                         global: false,
6142                         ref segments,
6143                         ..
6144                     }) if segments.len() == 1 =>
6145                         format!("found variable"),
6146                     _ => match err.kind {
6147                         ErrKind::MiscCatchAll => format!("but found {}", err.description()),
6148                         _ => format!("but {}", err.description())
6149                     }
6150                 };
6151                 span_err!(self.sess, count_expr.span, E0307,
6152                     "expected constant integer for repeat count, {}", err_msg);
6153             }
6154         }
6155         0
6156     }
6157
6158     // Iterate over a type parameter's bounded traits and any supertraits
6159     // of those traits, ignoring kinds.
6160     // Here, the supertraits are the transitive closure of the supertrait
6161     // relation on the supertraits from each bounded trait's constraint
6162     // list.
6163     pub fn each_bound_trait_and_supertraits<F>(&self,
6164                                                bounds: &[PolyTraitRef<'tcx>],
6165                                                mut f: F)
6166                                                -> bool where
6167         F: FnMut(PolyTraitRef<'tcx>) -> bool,
6168     {
6169         for bound_trait_ref in traits::transitive_bounds(self, bounds) {
6170             if !f(bound_trait_ref) {
6171                 return false;
6172             }
6173         }
6174         return true;
6175     }
6176
6177     /// Given a set of predicates that apply to an object type, returns
6178     /// the region bounds that the (erased) `Self` type must
6179     /// outlive. Precisely *because* the `Self` type is erased, the
6180     /// parameter `erased_self_ty` must be supplied to indicate what type
6181     /// has been used to represent `Self` in the predicates
6182     /// themselves. This should really be a unique type; `FreshTy(0)` is a
6183     /// popular choice.
6184     ///
6185     /// NB: in some cases, particularly around higher-ranked bounds,
6186     /// this function returns a kind of conservative approximation.
6187     /// That is, all regions returned by this function are definitely
6188     /// required, but there may be other region bounds that are not
6189     /// returned, as well as requirements like `for<'a> T: 'a`.
6190     ///
6191     /// Requires that trait definitions have been processed so that we can
6192     /// elaborate predicates and walk supertraits.
6193     pub fn required_region_bounds(&self,
6194                                   erased_self_ty: Ty<'tcx>,
6195                                   predicates: Vec<ty::Predicate<'tcx>>)
6196                                   -> Vec<ty::Region>    {
6197         debug!("required_region_bounds(erased_self_ty={:?}, predicates={:?})",
6198                erased_self_ty,
6199                predicates);
6200
6201         assert!(!erased_self_ty.has_escaping_regions());
6202
6203         traits::elaborate_predicates(self, predicates)
6204             .filter_map(|predicate| {
6205                 match predicate {
6206                     ty::Predicate::Projection(..) |
6207                     ty::Predicate::Trait(..) |
6208                     ty::Predicate::Equate(..) |
6209                     ty::Predicate::WellFormed(..) |
6210                     ty::Predicate::ObjectSafe(..) |
6211                     ty::Predicate::RegionOutlives(..) => {
6212                         None
6213                     }
6214                     ty::Predicate::TypeOutlives(ty::Binder(ty::OutlivesPredicate(t, r))) => {
6215                         // Search for a bound of the form `erased_self_ty
6216                         // : 'a`, but be wary of something like `for<'a>
6217                         // erased_self_ty : 'a` (we interpret a
6218                         // higher-ranked bound like that as 'static,
6219                         // though at present the code in `fulfill.rs`
6220                         // considers such bounds to be unsatisfiable, so
6221                         // it's kind of a moot point since you could never
6222                         // construct such an object, but this seems
6223                         // correct even if that code changes).
6224                         if t == erased_self_ty && !r.has_escaping_regions() {
6225                             Some(r)
6226                         } else {
6227                             None
6228                         }
6229                     }
6230                 }
6231             })
6232             .collect()
6233     }
6234
6235     pub fn item_variances(&self, item_id: DefId) -> Rc<ItemVariances> {
6236         lookup_locally_or_in_crate_store(
6237             "item_variance_map", item_id, &self.item_variance_map,
6238             || Rc::new(csearch::get_item_variances(&self.sess.cstore, item_id)))
6239     }
6240
6241     pub fn trait_has_default_impl(&self, trait_def_id: DefId) -> bool {
6242         self.populate_implementations_for_trait_if_necessary(trait_def_id);
6243
6244         let def = self.lookup_trait_def(trait_def_id);
6245         def.flags.get().intersects(TraitFlags::HAS_DEFAULT_IMPL)
6246     }
6247
6248     /// Records a trait-to-implementation mapping.
6249     pub fn record_trait_has_default_impl(&self, trait_def_id: DefId) {
6250         let def = self.lookup_trait_def(trait_def_id);
6251         def.flags.set(def.flags.get() | TraitFlags::HAS_DEFAULT_IMPL)
6252     }
6253
6254     /// Load primitive inherent implementations if necessary
6255     pub fn populate_implementations_for_primitive_if_necessary(&self,
6256                                                                primitive_def_id: DefId) {
6257         if primitive_def_id.is_local() {
6258             return
6259         }
6260
6261         if self.populated_external_primitive_impls.borrow().contains(&primitive_def_id) {
6262             return
6263         }
6264
6265         debug!("populate_implementations_for_primitive_if_necessary: searching for {:?}",
6266                primitive_def_id);
6267
6268         let impl_items = csearch::get_impl_items(&self.sess.cstore, primitive_def_id);
6269
6270         // Store the implementation info.
6271         self.impl_items.borrow_mut().insert(primitive_def_id, impl_items);
6272         self.populated_external_primitive_impls.borrow_mut().insert(primitive_def_id);
6273     }
6274
6275     /// Populates the type context with all the inherent implementations for
6276     /// the given type if necessary.
6277     pub fn populate_inherent_implementations_for_type_if_necessary(&self,
6278                                                                    type_id: DefId) {
6279         if type_id.is_local() {
6280             return
6281         }
6282
6283         if self.populated_external_types.borrow().contains(&type_id) {
6284             return
6285         }
6286
6287         debug!("populate_inherent_implementations_for_type_if_necessary: searching for {:?}",
6288                type_id);
6289
6290         let mut inherent_impls = Vec::new();
6291         csearch::each_inherent_implementation_for_type(&self.sess.cstore, type_id, |impl_def_id| {
6292             // Record the implementation.
6293             inherent_impls.push(impl_def_id);
6294
6295             // Store the implementation info.
6296             let impl_items = csearch::get_impl_items(&self.sess.cstore, impl_def_id);
6297             self.impl_items.borrow_mut().insert(impl_def_id, impl_items);
6298         });
6299
6300         self.inherent_impls.borrow_mut().insert(type_id, Rc::new(inherent_impls));
6301         self.populated_external_types.borrow_mut().insert(type_id);
6302     }
6303
6304     /// Populates the type context with all the implementations for the given
6305     /// trait if necessary.
6306     pub fn populate_implementations_for_trait_if_necessary(&self, trait_id: DefId) {
6307         if trait_id.is_local() {
6308             return
6309         }
6310
6311         let def = self.lookup_trait_def(trait_id);
6312         if def.flags.get().intersects(TraitFlags::IMPLS_VALID) {
6313             return;
6314         }
6315
6316         debug!("populate_implementations_for_trait_if_necessary: searching for {:?}", def);
6317
6318         if csearch::is_defaulted_trait(&self.sess.cstore, trait_id) {
6319             self.record_trait_has_default_impl(trait_id);
6320         }
6321
6322         csearch::each_implementation_for_trait(&self.sess.cstore, trait_id, |impl_def_id| {
6323             let impl_items = csearch::get_impl_items(&self.sess.cstore, impl_def_id);
6324             let trait_ref = self.impl_trait_ref(impl_def_id).unwrap();
6325             // Record the trait->implementation mapping.
6326             def.record_impl(self, impl_def_id, trait_ref);
6327
6328             // For any methods that use a default implementation, add them to
6329             // the map. This is a bit unfortunate.
6330             for impl_item_def_id in &impl_items {
6331                 let method_def_id = impl_item_def_id.def_id();
6332                 match self.impl_or_trait_item(method_def_id) {
6333                     MethodTraitItem(method) => {
6334                         if let Some(source) = method.provided_source {
6335                             self.provided_method_sources
6336                                 .borrow_mut()
6337                                 .insert(method_def_id, source);
6338                         }
6339                     }
6340                     _ => {}
6341                 }
6342             }
6343
6344             // Store the implementation info.
6345             self.impl_items.borrow_mut().insert(impl_def_id, impl_items);
6346         });
6347
6348         def.flags.set(def.flags.get() | TraitFlags::IMPLS_VALID);
6349     }
6350
6351     /// Given the def_id of an impl, return the def_id of the trait it implements.
6352     /// If it implements no trait, return `None`.
6353     pub fn trait_id_of_impl(&self, def_id: DefId) -> Option<DefId> {
6354         self.impl_trait_ref(def_id).map(|tr| tr.def_id)
6355     }
6356
6357     /// If the given def ID describes a method belonging to an impl, return the
6358     /// ID of the impl that the method belongs to. Otherwise, return `None`.
6359     pub fn impl_of_method(&self, def_id: DefId) -> Option<DefId> {
6360         if def_id.krate != LOCAL_CRATE {
6361             return match csearch::get_impl_or_trait_item(self,
6362                                                          def_id).container() {
6363                 TraitContainer(_) => None,
6364                 ImplContainer(def_id) => Some(def_id),
6365             };
6366         }
6367         match self.impl_or_trait_items.borrow().get(&def_id).cloned() {
6368             Some(trait_item) => {
6369                 match trait_item.container() {
6370                     TraitContainer(_) => None,
6371                     ImplContainer(def_id) => Some(def_id),
6372                 }
6373             }
6374             None => None
6375         }
6376     }
6377
6378     /// If the given def ID describes an item belonging to a trait (either a
6379     /// default method or an implementation of a trait method), return the ID of
6380     /// the trait that the method belongs to. Otherwise, return `None`.
6381     pub fn trait_of_item(&self, def_id: DefId) -> Option<DefId> {
6382         if def_id.krate != LOCAL_CRATE {
6383             return csearch::get_trait_of_item(&self.sess.cstore, def_id, self);
6384         }
6385         match self.impl_or_trait_items.borrow().get(&def_id).cloned() {
6386             Some(impl_or_trait_item) => {
6387                 match impl_or_trait_item.container() {
6388                     TraitContainer(def_id) => Some(def_id),
6389                     ImplContainer(def_id) => self.trait_id_of_impl(def_id),
6390                 }
6391             }
6392             None => None
6393         }
6394     }
6395
6396     /// If the given def ID describes an item belonging to a trait, (either a
6397     /// default method or an implementation of a trait method), return the ID of
6398     /// the method inside trait definition (this means that if the given def ID
6399     /// is already that of the original trait method, then the return value is
6400     /// the same).
6401     /// Otherwise, return `None`.
6402     pub fn trait_item_of_item(&self, def_id: DefId) -> Option<ImplOrTraitItemId> {
6403         let impl_item = match self.impl_or_trait_items.borrow().get(&def_id) {
6404             Some(m) => m.clone(),
6405             None => return None,
6406         };
6407         let name = impl_item.name();
6408         match self.trait_of_item(def_id) {
6409             Some(trait_did) => {
6410                 self.trait_items(trait_did).iter()
6411                     .find(|item| item.name() == name)
6412                     .map(|item| item.id())
6413             }
6414             None => None
6415         }
6416     }
6417
6418     /// Creates a hash of the type `Ty` which will be the same no matter what crate
6419     /// context it's calculated within. This is used by the `type_id` intrinsic.
6420     pub fn hash_crate_independent(&self, ty: Ty<'tcx>, svh: &Svh) -> u64 {
6421         let mut state = SipHasher::new();
6422         helper(self, ty, svh, &mut state);
6423         return state.finish();
6424
6425         fn helper<'tcx>(tcx: &ctxt<'tcx>, ty: Ty<'tcx>, svh: &Svh,
6426                         state: &mut SipHasher) {
6427             macro_rules! byte { ($b:expr) => { ($b as u8).hash(state) } }
6428             macro_rules! hash { ($e:expr) => { $e.hash(state) }  }
6429
6430             let region = |state: &mut SipHasher, r: Region| {
6431                 match r {
6432                     ReStatic => {}
6433                     ReLateBound(db, BrAnon(i)) => {
6434                         db.hash(state);
6435                         i.hash(state);
6436                     }
6437                     ReEmpty |
6438                     ReEarlyBound(..) |
6439                     ReLateBound(..) |
6440                     ReFree(..) |
6441                     ReScope(..) |
6442                     ReVar(..) |
6443                     ReSkolemized(..) => {
6444                         tcx.sess.bug("unexpected region found when hashing a type")
6445                     }
6446                 }
6447             };
6448             let did = |state: &mut SipHasher, did: DefId| {
6449                 let h = if did.is_local() {
6450                     svh.clone()
6451                 } else {
6452                     tcx.sess.cstore.get_crate_hash(did.krate)
6453                 };
6454                 h.as_str().hash(state);
6455                 did.node.hash(state);
6456             };
6457             let mt = |state: &mut SipHasher, mt: TypeAndMut| {
6458                 mt.mutbl.hash(state);
6459             };
6460             let fn_sig = |state: &mut SipHasher, sig: &Binder<FnSig<'tcx>>| {
6461                 let sig = tcx.anonymize_late_bound_regions(sig).0;
6462                 for a in &sig.inputs { helper(tcx, *a, svh, state); }
6463                 if let ty::FnConverging(output) = sig.output {
6464                     helper(tcx, output, svh, state);
6465                 }
6466             };
6467             ty.maybe_walk(|ty| {
6468                 match ty.sty {
6469                     TyBool => byte!(2),
6470                     TyChar => byte!(3),
6471                     TyInt(i) => {
6472                         byte!(4);
6473                         hash!(i);
6474                     }
6475                     TyUint(u) => {
6476                         byte!(5);
6477                         hash!(u);
6478                     }
6479                     TyFloat(f) => {
6480                         byte!(6);
6481                         hash!(f);
6482                     }
6483                     TyStr => {
6484                         byte!(7);
6485                     }
6486                     TyEnum(d, _) => {
6487                         byte!(8);
6488                         did(state, d.did);
6489                     }
6490                     TyBox(_) => {
6491                         byte!(9);
6492                     }
6493                     TyArray(_, n) => {
6494                         byte!(10);
6495                         n.hash(state);
6496                     }
6497                     TySlice(_) => {
6498                         byte!(11);
6499                     }
6500                     TyRawPtr(m) => {
6501                         byte!(12);
6502                         mt(state, m);
6503                     }
6504                     TyRef(r, m) => {
6505                         byte!(13);
6506                         region(state, *r);
6507                         mt(state, m);
6508                     }
6509                     TyBareFn(opt_def_id, ref b) => {
6510                         byte!(14);
6511                         hash!(opt_def_id);
6512                         hash!(b.unsafety);
6513                         hash!(b.abi);
6514                         fn_sig(state, &b.sig);
6515                         return false;
6516                     }
6517                     TyTrait(ref data) => {
6518                         byte!(17);
6519                         did(state, data.principal_def_id());
6520                         hash!(data.bounds);
6521
6522                         let principal = tcx.anonymize_late_bound_regions(&data.principal).0;
6523                         for subty in &principal.substs.types {
6524                             helper(tcx, subty, svh, state);
6525                         }
6526
6527                         return false;
6528                     }
6529                     TyStruct(d, _) => {
6530                         byte!(18);
6531                         did(state, d.did);
6532                     }
6533                     TyTuple(ref inner) => {
6534                         byte!(19);
6535                         hash!(inner.len());
6536                     }
6537                     TyParam(p) => {
6538                         byte!(20);
6539                         hash!(p.space);
6540                         hash!(p.idx);
6541                         hash!(p.name.as_str());
6542                     }
6543                     TyInfer(_) => unreachable!(),
6544                     TyError => byte!(21),
6545                     TyClosure(d, _) => {
6546                         byte!(22);
6547                         did(state, d);
6548                     }
6549                     TyProjection(ref data) => {
6550                         byte!(23);
6551                         did(state, data.trait_ref.def_id);
6552                         hash!(data.item_name.as_str());
6553                     }
6554                 }
6555                 true
6556             });
6557         }
6558     }
6559
6560     /// Construct a parameter environment suitable for static contexts or other contexts where there
6561     /// are no free type/lifetime parameters in scope.
6562     pub fn empty_parameter_environment<'a>(&'a self)
6563                                            -> ParameterEnvironment<'a,'tcx> {
6564         ty::ParameterEnvironment { tcx: self,
6565                                    free_substs: Substs::empty(),
6566                                    caller_bounds: Vec::new(),
6567                                    implicit_region_bound: ty::ReEmpty,
6568                                    selection_cache: traits::SelectionCache::new(),
6569
6570                                    // for an empty parameter
6571                                    // environment, there ARE no free
6572                                    // regions, so it shouldn't matter
6573                                    // what we use for the free id
6574                                    free_id: ast::DUMMY_NODE_ID }
6575     }
6576
6577     /// Constructs and returns a substitution that can be applied to move from
6578     /// the "outer" view of a type or method to the "inner" view.
6579     /// In general, this means converting from bound parameters to
6580     /// free parameters. Since we currently represent bound/free type
6581     /// parameters in the same way, this only has an effect on regions.
6582     pub fn construct_free_substs(&self, generics: &Generics<'tcx>,
6583                                  free_id: ast::NodeId) -> Substs<'tcx> {
6584         // map T => T
6585         let mut types = VecPerParamSpace::empty();
6586         for def in generics.types.as_slice() {
6587             debug!("construct_parameter_environment(): push_types_from_defs: def={:?}",
6588                     def);
6589             types.push(def.space, self.mk_param_from_def(def));
6590         }
6591
6592         let free_id_outlive = self.region_maps.item_extent(free_id);
6593
6594         // map bound 'a => free 'a
6595         let mut regions = VecPerParamSpace::empty();
6596         for def in generics.regions.as_slice() {
6597             let region =
6598                 ReFree(FreeRegion { scope: free_id_outlive,
6599                                     bound_region: BrNamed(def.def_id, def.name) });
6600             debug!("push_region_params {:?}", region);
6601             regions.push(def.space, region);
6602         }
6603
6604         Substs {
6605             types: types,
6606             regions: subst::NonerasedRegions(regions)
6607         }
6608     }
6609
6610     /// See `ParameterEnvironment` struct def'n for details
6611     pub fn construct_parameter_environment<'a>(&'a self,
6612                                                span: Span,
6613                                                generics: &ty::Generics<'tcx>,
6614                                                generic_predicates: &ty::GenericPredicates<'tcx>,
6615                                                free_id: ast::NodeId)
6616                                                -> ParameterEnvironment<'a, 'tcx>
6617     {
6618         //
6619         // Construct the free substs.
6620         //
6621
6622         let free_substs = self.construct_free_substs(generics, free_id);
6623         let free_id_outlive = self.region_maps.item_extent(free_id);
6624
6625         //
6626         // Compute the bounds on Self and the type parameters.
6627         //
6628
6629         let bounds = generic_predicates.instantiate(self, &free_substs);
6630         let bounds = self.liberate_late_bound_regions(free_id_outlive, &ty::Binder(bounds));
6631         let predicates = bounds.predicates.into_vec();
6632
6633         debug!("construct_parameter_environment: free_id={:?} free_subst={:?} predicates={:?}",
6634                free_id,
6635                free_substs,
6636                predicates);
6637
6638         //
6639         // Finally, we have to normalize the bounds in the environment, in
6640         // case they contain any associated type projections. This process
6641         // can yield errors if the put in illegal associated types, like
6642         // `<i32 as Foo>::Bar` where `i32` does not implement `Foo`. We
6643         // report these errors right here; this doesn't actually feel
6644         // right to me, because constructing the environment feels like a
6645         // kind of a "idempotent" action, but I'm not sure where would be
6646         // a better place. In practice, we construct environments for
6647         // every fn once during type checking, and we'll abort if there
6648         // are any errors at that point, so after type checking you can be
6649         // sure that this will succeed without errors anyway.
6650         //
6651
6652         let unnormalized_env = ty::ParameterEnvironment {
6653             tcx: self,
6654             free_substs: free_substs,
6655             implicit_region_bound: ty::ReScope(free_id_outlive),
6656             caller_bounds: predicates,
6657             selection_cache: traits::SelectionCache::new(),
6658             free_id: free_id,
6659         };
6660
6661         let cause = traits::ObligationCause::misc(span, free_id);
6662         traits::normalize_param_env_or_error(unnormalized_env, cause)
6663     }
6664
6665     pub fn is_method_call(&self, expr_id: ast::NodeId) -> bool {
6666         self.tables.borrow().method_map.contains_key(&MethodCall::expr(expr_id))
6667     }
6668
6669     pub fn is_overloaded_autoderef(&self, expr_id: ast::NodeId, autoderefs: u32) -> bool {
6670         self.tables.borrow().method_map.contains_key(&MethodCall::autoderef(expr_id,
6671                                                                             autoderefs))
6672     }
6673
6674     pub fn upvar_capture(&self, upvar_id: ty::UpvarId) -> Option<ty::UpvarCapture> {
6675         Some(self.tables.borrow().upvar_capture_map.get(&upvar_id).unwrap().clone())
6676     }
6677
6678
6679     /// Returns true if this ADT is a dtorck type, i.e. whether it being
6680     /// safe for destruction requires it to be alive
6681     fn is_adt_dtorck(&self, adt: AdtDef<'tcx>) -> bool {
6682         let dtor_method = match adt.destructor() {
6683             Some(dtor) => dtor,
6684             None => return false
6685         };
6686         let impl_did = self.impl_of_method(dtor_method).unwrap_or_else(|| {
6687             self.sess.bug(&format!("no Drop impl for the dtor of `{:?}`", adt))
6688         });
6689         let generics = adt.type_scheme(self).generics;
6690
6691         // In `impl<'a> Drop ...`, we automatically assume
6692         // `'a` is meaningful and thus represents a bound
6693         // through which we could reach borrowed data.
6694         //
6695         // FIXME (pnkfelix): In the future it would be good to
6696         // extend the language to allow the user to express,
6697         // in the impl signature, that a lifetime is not
6698         // actually used (something like `where 'a: ?Live`).
6699         if generics.has_region_params(subst::TypeSpace) {
6700             debug!("typ: {:?} has interesting dtor due to region params",
6701                    adt);
6702             return true;
6703         }
6704
6705         let mut seen_items = Vec::new();
6706         let mut items_to_inspect = vec![impl_did];
6707         while let Some(item_def_id) = items_to_inspect.pop() {
6708             if seen_items.contains(&item_def_id) {
6709                 continue;
6710             }
6711
6712             for pred in self.lookup_predicates(item_def_id).predicates {
6713                 let result = match pred {
6714                     ty::Predicate::Equate(..) |
6715                     ty::Predicate::RegionOutlives(..) |
6716                     ty::Predicate::TypeOutlives(..) |
6717                     ty::Predicate::WellFormed(..) |
6718                     ty::Predicate::ObjectSafe(..) |
6719                     ty::Predicate::Projection(..) => {
6720                         // For now, assume all these where-clauses
6721                         // may give drop implementation capabilty
6722                         // to access borrowed data.
6723                         true
6724                     }
6725
6726                     ty::Predicate::Trait(ty::Binder(ref t_pred)) => {
6727                         let def_id = t_pred.trait_ref.def_id;
6728                         if self.trait_items(def_id).len() != 0 {
6729                             // If trait has items, assume it adds
6730                             // capability to access borrowed data.
6731                             true
6732                         } else {
6733                             // Trait without items is itself
6734                             // uninteresting from POV of dropck.
6735                             //
6736                             // However, may have parent w/ items;
6737                             // so schedule checking of predicates,
6738                             items_to_inspect.push(def_id);
6739                             // and say "no capability found" for now.
6740                             false
6741                         }
6742                     }
6743                 };
6744
6745                 if result {
6746                     debug!("typ: {:?} has interesting dtor due to generic preds, e.g. {:?}",
6747                            adt, pred);
6748                     return true;
6749                 }
6750             }
6751
6752             seen_items.push(item_def_id);
6753         }
6754
6755         debug!("typ: {:?} is dtorck-safe", adt);
6756         false
6757     }
6758 }
6759
6760 /// The category of explicit self.
6761 #[derive(Clone, Copy, Eq, PartialEq, Debug)]
6762 pub enum ExplicitSelfCategory {
6763     StaticExplicitSelfCategory,
6764     ByValueExplicitSelfCategory,
6765     ByReferenceExplicitSelfCategory(Region, ast::Mutability),
6766     ByBoxExplicitSelfCategory,
6767 }
6768
6769 /// A free variable referred to in a function.
6770 #[derive(Copy, Clone, RustcEncodable, RustcDecodable)]
6771 pub struct Freevar {
6772     /// The variable being accessed free.
6773     pub def: def::Def,
6774
6775     // First span where it is accessed (there can be multiple).
6776     pub span: Span
6777 }
6778
6779 pub type FreevarMap = NodeMap<Vec<Freevar>>;
6780
6781 pub type CaptureModeMap = NodeMap<ast::CaptureClause>;
6782
6783 // Trait method resolution
6784 pub type TraitMap = NodeMap<Vec<DefId>>;
6785
6786 // Map from the NodeId of a glob import to a list of items which are actually
6787 // imported.
6788 pub type GlobMap = HashMap<NodeId, HashSet<Name>>;
6789
6790 impl<'tcx> AutoAdjustment<'tcx> {
6791     pub fn is_identity(&self) -> bool {
6792         match *self {
6793             AdjustReifyFnPointer |
6794             AdjustUnsafeFnPointer => false,
6795             AdjustDerefRef(ref r) => r.is_identity(),
6796         }
6797     }
6798 }
6799
6800 impl<'tcx> AutoDerefRef<'tcx> {
6801     pub fn is_identity(&self) -> bool {
6802         self.autoderefs == 0 && self.unsize.is_none() && self.autoref.is_none()
6803     }
6804 }
6805
6806 impl<'tcx> ctxt<'tcx> {
6807     pub fn with_freevars<T, F>(&self, fid: ast::NodeId, f: F) -> T where
6808         F: FnOnce(&[Freevar]) -> T,
6809     {
6810         match self.freevars.borrow().get(&fid) {
6811             None => f(&[]),
6812             Some(d) => f(&d[..])
6813         }
6814     }
6815
6816     /// Replace any late-bound regions bound in `value` with free variants attached to scope-id
6817     /// `scope_id`.
6818     pub fn liberate_late_bound_regions<T>(&self,
6819         all_outlive_scope: region::CodeExtent,
6820         value: &Binder<T>)
6821         -> T
6822         where T : TypeFoldable<'tcx>
6823     {
6824         ty_fold::replace_late_bound_regions(
6825             self, value,
6826             |br| ty::ReFree(ty::FreeRegion{scope: all_outlive_scope, bound_region: br})).0
6827     }
6828
6829     /// Flattens two binding levels into one. So `for<'a> for<'b> Foo`
6830     /// becomes `for<'a,'b> Foo`.
6831     pub fn flatten_late_bound_regions<T>(&self, bound2_value: &Binder<Binder<T>>)
6832                                          -> Binder<T>
6833         where T: TypeFoldable<'tcx>
6834     {
6835         let bound0_value = bound2_value.skip_binder().skip_binder();
6836         let value = ty_fold::fold_regions(self, bound0_value, &mut false,
6837                                           |region, current_depth| {
6838             match region {
6839                 ty::ReLateBound(debruijn, br) if debruijn.depth >= current_depth => {
6840                     // should be true if no escaping regions from bound2_value
6841                     assert!(debruijn.depth - current_depth <= 1);
6842                     ty::ReLateBound(DebruijnIndex::new(current_depth), br)
6843                 }
6844                 _ => {
6845                     region
6846                 }
6847             }
6848         });
6849         Binder(value)
6850     }
6851
6852     pub fn no_late_bound_regions<T>(&self, value: &Binder<T>) -> Option<T>
6853         where T : TypeFoldable<'tcx> + RegionEscape
6854     {
6855         if value.0.has_escaping_regions() {
6856             None
6857         } else {
6858             Some(value.0.clone())
6859         }
6860     }
6861
6862     /// Replace any late-bound regions bound in `value` with `'static`. Useful in trans but also
6863     /// method lookup and a few other places where precise region relationships are not required.
6864     pub fn erase_late_bound_regions<T>(&self, value: &Binder<T>) -> T
6865         where T : TypeFoldable<'tcx>
6866     {
6867         ty_fold::replace_late_bound_regions(self, value, |_| ty::ReStatic).0
6868     }
6869
6870     /// Rewrite any late-bound regions so that they are anonymous.  Region numbers are
6871     /// assigned starting at 1 and increasing monotonically in the order traversed
6872     /// by the fold operation.
6873     ///
6874     /// The chief purpose of this function is to canonicalize regions so that two
6875     /// `FnSig`s or `TraitRef`s which are equivalent up to region naming will become
6876     /// structurally identical.  For example, `for<'a, 'b> fn(&'a isize, &'b isize)` and
6877     /// `for<'a, 'b> fn(&'b isize, &'a isize)` will become identical after anonymization.
6878     pub fn anonymize_late_bound_regions<T>(&self, sig: &Binder<T>) -> Binder<T>
6879         where T : TypeFoldable<'tcx>,
6880     {
6881         let mut counter = 0;
6882         ty::Binder(ty_fold::replace_late_bound_regions(self, sig, |_| {
6883             counter += 1;
6884             ReLateBound(ty::DebruijnIndex::new(1), BrAnon(counter))
6885         }).0)
6886     }
6887
6888     pub fn make_substs_for_receiver_types(&self,
6889                                           trait_ref: &ty::TraitRef<'tcx>,
6890                                           method: &ty::Method<'tcx>)
6891                                           -> subst::Substs<'tcx>
6892     {
6893         /*!
6894          * Substitutes the values for the receiver's type parameters
6895          * that are found in method, leaving the method's type parameters
6896          * intact.
6897          */
6898
6899         let meth_tps: Vec<Ty> =
6900             method.generics.types.get_slice(subst::FnSpace)
6901                   .iter()
6902                   .map(|def| self.mk_param_from_def(def))
6903                   .collect();
6904         let meth_regions: Vec<ty::Region> =
6905             method.generics.regions.get_slice(subst::FnSpace)
6906                   .iter()
6907                   .map(|def| def.to_early_bound_region())
6908                   .collect();
6909         trait_ref.substs.clone().with_method(meth_tps, meth_regions)
6910     }
6911 }
6912
6913 impl DebruijnIndex {
6914     pub fn new(depth: u32) -> DebruijnIndex {
6915         assert!(depth > 0);
6916         DebruijnIndex { depth: depth }
6917     }
6918
6919     pub fn shifted(&self, amount: u32) -> DebruijnIndex {
6920         DebruijnIndex { depth: self.depth + amount }
6921     }
6922 }
6923
6924 impl<'tcx> fmt::Debug for AutoAdjustment<'tcx> {
6925     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
6926         match *self {
6927             AdjustReifyFnPointer => {
6928                 write!(f, "AdjustReifyFnPointer")
6929             }
6930             AdjustUnsafeFnPointer => {
6931                 write!(f, "AdjustUnsafeFnPointer")
6932             }
6933             AdjustDerefRef(ref data) => {
6934                 write!(f, "{:?}", data)
6935             }
6936         }
6937     }
6938 }
6939
6940 impl<'tcx> fmt::Debug for AutoDerefRef<'tcx> {
6941     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
6942         write!(f, "AutoDerefRef({}, unsize={:?}, {:?})",
6943                self.autoderefs, self.unsize, self.autoref)
6944     }
6945 }
6946
6947 impl<'tcx> fmt::Debug for TraitTy<'tcx> {
6948     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
6949         write!(f, "TraitTy({:?},{:?})",
6950                self.principal,
6951                self.bounds)
6952     }
6953 }
6954
6955 impl<'tcx> fmt::Debug for ty::Predicate<'tcx> {
6956     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
6957         match *self {
6958             Predicate::Trait(ref a) => write!(f, "{:?}", a),
6959             Predicate::Equate(ref pair) => write!(f, "{:?}", pair),
6960             Predicate::RegionOutlives(ref pair) => write!(f, "{:?}", pair),
6961             Predicate::TypeOutlives(ref pair) => write!(f, "{:?}", pair),
6962             Predicate::Projection(ref pair) => write!(f, "{:?}", pair),
6963             Predicate::WellFormed(ty) => write!(f, "WF({:?})", ty),
6964             Predicate::ObjectSafe(trait_def_id) => write!(f, "ObjectSafe({:?})", trait_def_id),
6965         }
6966     }
6967 }
6968
6969 // FIXME(#20298) -- all of these traits basically walk various
6970 // structures to test whether types/regions are reachable with various
6971 // properties. It should be possible to express them in terms of one
6972 // common "walker" trait or something.
6973
6974 /// An "escaping region" is a bound region whose binder is not part of `t`.
6975 ///
6976 /// So, for example, consider a type like the following, which has two binders:
6977 ///
6978 ///    for<'a> fn(x: for<'b> fn(&'a isize, &'b isize))
6979 ///    ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ outer scope
6980 ///                  ^~~~~~~~~~~~~~~~~~~~~~~~~~~~  inner scope
6981 ///
6982 /// This type has *bound regions* (`'a`, `'b`), but it does not have escaping regions, because the
6983 /// binders of both `'a` and `'b` are part of the type itself. However, if we consider the *inner
6984 /// fn type*, that type has an escaping region: `'a`.
6985 ///
6986 /// Note that what I'm calling an "escaping region" is often just called a "free region". However,
6987 /// we already use the term "free region". It refers to the regions that we use to represent bound
6988 /// regions on a fn definition while we are typechecking its body.
6989 ///
6990 /// To clarify, conceptually there is no particular difference between an "escaping" region and a
6991 /// "free" region. However, there is a big difference in practice. Basically, when "entering" a
6992 /// binding level, one is generally required to do some sort of processing to a bound region, such
6993 /// as replacing it with a fresh/skolemized region, or making an entry in the environment to
6994 /// represent the scope to which it is attached, etc. An escaping region represents a bound region
6995 /// for which this processing has not yet been done.
6996 pub trait RegionEscape {
6997     fn has_escaping_regions(&self) -> bool {
6998         self.has_regions_escaping_depth(0)
6999     }
7000
7001     fn has_regions_escaping_depth(&self, depth: u32) -> bool;
7002 }
7003
7004 impl<'tcx> RegionEscape for Ty<'tcx> {
7005     fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7006         self.region_depth > depth
7007     }
7008 }
7009
7010 impl<'tcx> RegionEscape for TraitTy<'tcx> {
7011     fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7012         self.principal.has_regions_escaping_depth(depth) ||
7013             self.bounds.has_regions_escaping_depth(depth)
7014     }
7015 }
7016
7017 impl<'tcx> RegionEscape for ExistentialBounds<'tcx> {
7018     fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7019         self.region_bound.has_regions_escaping_depth(depth) ||
7020             self.projection_bounds.has_regions_escaping_depth(depth)
7021     }
7022 }
7023
7024 impl<'tcx> RegionEscape for Substs<'tcx> {
7025     fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7026         self.types.has_regions_escaping_depth(depth) ||
7027             self.regions.has_regions_escaping_depth(depth)
7028     }
7029 }
7030
7031 impl<'tcx> RegionEscape for ClosureSubsts<'tcx> {
7032     fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7033         self.func_substs.has_regions_escaping_depth(depth) ||
7034             self.upvar_tys.iter().any(|t| t.has_regions_escaping_depth(depth))
7035     }
7036 }
7037
7038 impl<T:RegionEscape> RegionEscape for Vec<T> {
7039     fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7040         self.iter().any(|t| t.has_regions_escaping_depth(depth))
7041     }
7042 }
7043
7044 impl<'tcx> RegionEscape for FnSig<'tcx> {
7045     fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7046         self.inputs.has_regions_escaping_depth(depth) ||
7047             self.output.has_regions_escaping_depth(depth)
7048     }
7049 }
7050
7051 impl<'tcx,T:RegionEscape> RegionEscape for VecPerParamSpace<T> {
7052     fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7053         self.iter_enumerated().any(|(space, _, t)| {
7054             if space == subst::FnSpace {
7055                 t.has_regions_escaping_depth(depth+1)
7056             } else {
7057                 t.has_regions_escaping_depth(depth)
7058             }
7059         })
7060     }
7061 }
7062
7063 impl<'tcx> RegionEscape for TypeScheme<'tcx> {
7064     fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7065         self.ty.has_regions_escaping_depth(depth)
7066     }
7067 }
7068
7069 impl RegionEscape for Region {
7070     fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7071         self.escapes_depth(depth)
7072     }
7073 }
7074
7075 impl<'tcx> RegionEscape for GenericPredicates<'tcx> {
7076     fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7077         self.predicates.has_regions_escaping_depth(depth)
7078     }
7079 }
7080
7081 impl<'tcx> RegionEscape for Predicate<'tcx> {
7082     fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7083         match *self {
7084             Predicate::Trait(ref data) => data.has_regions_escaping_depth(depth),
7085             Predicate::Equate(ref data) => data.has_regions_escaping_depth(depth),
7086             Predicate::RegionOutlives(ref data) => data.has_regions_escaping_depth(depth),
7087             Predicate::TypeOutlives(ref data) => data.has_regions_escaping_depth(depth),
7088             Predicate::Projection(ref data) => data.has_regions_escaping_depth(depth),
7089             Predicate::WellFormed(ty) => ty.has_regions_escaping_depth(depth),
7090             Predicate::ObjectSafe(_trait_def_id) => false,
7091         }
7092     }
7093 }
7094
7095 impl<'tcx,P:RegionEscape> RegionEscape for traits::Obligation<'tcx,P> {
7096     fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7097         self.predicate.has_regions_escaping_depth(depth)
7098     }
7099 }
7100
7101 impl<'tcx> RegionEscape for TraitRef<'tcx> {
7102     fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7103         self.substs.types.iter().any(|t| t.has_regions_escaping_depth(depth)) ||
7104             self.substs.regions.has_regions_escaping_depth(depth)
7105     }
7106 }
7107
7108 impl<'tcx> RegionEscape for subst::RegionSubsts {
7109     fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7110         match *self {
7111             subst::ErasedRegions => false,
7112             subst::NonerasedRegions(ref r) => {
7113                 r.iter().any(|t| t.has_regions_escaping_depth(depth))
7114             }
7115         }
7116     }
7117 }
7118
7119 impl<'tcx,T:RegionEscape> RegionEscape for Binder<T> {
7120     fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7121         self.0.has_regions_escaping_depth(depth + 1)
7122     }
7123 }
7124
7125 impl<'tcx> RegionEscape for FnOutput<'tcx> {
7126     fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7127         match *self {
7128             FnConverging(t) => t.has_regions_escaping_depth(depth),
7129             FnDiverging => false
7130         }
7131     }
7132 }
7133
7134 impl<'tcx> RegionEscape for EquatePredicate<'tcx> {
7135     fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7136         self.0.has_regions_escaping_depth(depth) || self.1.has_regions_escaping_depth(depth)
7137     }
7138 }
7139
7140 impl<'tcx> RegionEscape for TraitPredicate<'tcx> {
7141     fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7142         self.trait_ref.has_regions_escaping_depth(depth)
7143     }
7144 }
7145
7146 impl<T:RegionEscape,U:RegionEscape> RegionEscape for OutlivesPredicate<T,U> {
7147     fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7148         self.0.has_regions_escaping_depth(depth) || self.1.has_regions_escaping_depth(depth)
7149     }
7150 }
7151
7152 impl<'tcx> RegionEscape for ProjectionPredicate<'tcx> {
7153     fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7154         self.projection_ty.has_regions_escaping_depth(depth) ||
7155             self.ty.has_regions_escaping_depth(depth)
7156     }
7157 }
7158
7159 impl<'tcx> RegionEscape for ProjectionTy<'tcx> {
7160     fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7161         self.trait_ref.has_regions_escaping_depth(depth)
7162     }
7163 }
7164
7165 pub trait HasTypeFlags {
7166     fn has_type_flags(&self, flags: TypeFlags) -> bool;
7167     fn has_projection_types(&self) -> bool {
7168         self.has_type_flags(TypeFlags::HAS_PROJECTION)
7169     }
7170     fn references_error(&self) -> bool {
7171         self.has_type_flags(TypeFlags::HAS_TY_ERR)
7172     }
7173     fn has_param_types(&self) -> bool {
7174         self.has_type_flags(TypeFlags::HAS_PARAMS)
7175     }
7176     fn has_self_ty(&self) -> bool {
7177         self.has_type_flags(TypeFlags::HAS_SELF)
7178     }
7179     fn has_infer_types(&self) -> bool {
7180         self.has_type_flags(TypeFlags::HAS_TY_INFER)
7181     }
7182     fn needs_infer(&self) -> bool {
7183         self.has_type_flags(TypeFlags::HAS_TY_INFER | TypeFlags::HAS_RE_INFER)
7184     }
7185     fn needs_subst(&self) -> bool {
7186         self.has_type_flags(TypeFlags::NEEDS_SUBST)
7187     }
7188     fn has_closure_types(&self) -> bool {
7189         self.has_type_flags(TypeFlags::HAS_TY_CLOSURE)
7190     }
7191     fn has_erasable_regions(&self) -> bool {
7192         self.has_type_flags(TypeFlags::HAS_RE_EARLY_BOUND |
7193                             TypeFlags::HAS_RE_INFER |
7194                             TypeFlags::HAS_FREE_REGIONS)
7195     }
7196     /// Indicates whether this value references only 'global'
7197     /// types/lifetimes that are the same regardless of what fn we are
7198     /// in. This is used for caching. Errs on the side of returning
7199     /// false.
7200     fn is_global(&self) -> bool {
7201         !self.has_type_flags(TypeFlags::HAS_LOCAL_NAMES)
7202     }
7203 }
7204
7205 impl<'tcx,T:HasTypeFlags> HasTypeFlags for Vec<T> {
7206     fn has_type_flags(&self, flags: TypeFlags) -> bool {
7207         self[..].has_type_flags(flags)
7208     }
7209 }
7210
7211 impl<'tcx,T:HasTypeFlags> HasTypeFlags for [T] {
7212     fn has_type_flags(&self, flags: TypeFlags) -> bool {
7213         self.iter().any(|p| p.has_type_flags(flags))
7214     }
7215 }
7216
7217 impl<'tcx,T:HasTypeFlags> HasTypeFlags for VecPerParamSpace<T> {
7218     fn has_type_flags(&self, flags: TypeFlags) -> bool {
7219         self.iter().any(|p| p.has_type_flags(flags))
7220     }
7221 }
7222
7223 impl HasTypeFlags for abi::Abi {
7224     fn has_type_flags(&self, _flags: TypeFlags) -> bool {
7225         false
7226     }
7227 }
7228
7229 impl HasTypeFlags for ast::Unsafety {
7230     fn has_type_flags(&self, _flags: TypeFlags) -> bool {
7231         false
7232     }
7233 }
7234
7235 impl HasTypeFlags for BuiltinBounds {
7236     fn has_type_flags(&self, _flags: TypeFlags) -> bool {
7237         false
7238     }
7239 }
7240
7241 impl<'tcx> HasTypeFlags for ClosureTy<'tcx> {
7242     fn has_type_flags(&self, flags: TypeFlags) -> bool {
7243         self.sig.has_type_flags(flags)
7244     }
7245 }
7246
7247 impl<'tcx> HasTypeFlags for ClosureUpvar<'tcx> {
7248     fn has_type_flags(&self, flags: TypeFlags) -> bool {
7249         self.ty.has_type_flags(flags)
7250     }
7251 }
7252
7253 impl<'tcx> HasTypeFlags for ExistentialBounds<'tcx> {
7254     fn has_type_flags(&self, flags: TypeFlags) -> bool {
7255         self.projection_bounds.has_type_flags(flags)
7256     }
7257 }
7258
7259 impl<'tcx> HasTypeFlags for ty::InstantiatedPredicates<'tcx> {
7260     fn has_type_flags(&self, flags: TypeFlags) -> bool {
7261         self.predicates.has_type_flags(flags)
7262     }
7263 }
7264
7265 impl<'tcx> HasTypeFlags for Predicate<'tcx> {
7266     fn has_type_flags(&self, flags: TypeFlags) -> bool {
7267         match *self {
7268             Predicate::Trait(ref data) => data.has_type_flags(flags),
7269             Predicate::Equate(ref data) => data.has_type_flags(flags),
7270             Predicate::RegionOutlives(ref data) => data.has_type_flags(flags),
7271             Predicate::TypeOutlives(ref data) => data.has_type_flags(flags),
7272             Predicate::Projection(ref data) => data.has_type_flags(flags),
7273             Predicate::WellFormed(data) => data.has_type_flags(flags),
7274             Predicate::ObjectSafe(_trait_def_id) => false,
7275         }
7276     }
7277 }
7278
7279 impl<'tcx> HasTypeFlags for TraitPredicate<'tcx> {
7280     fn has_type_flags(&self, flags: TypeFlags) -> bool {
7281         self.trait_ref.has_type_flags(flags)
7282     }
7283 }
7284
7285 impl<'tcx> HasTypeFlags for EquatePredicate<'tcx> {
7286     fn has_type_flags(&self, flags: TypeFlags) -> bool {
7287         self.0.has_type_flags(flags) || self.1.has_type_flags(flags)
7288     }
7289 }
7290
7291 impl HasTypeFlags for Region {
7292     fn has_type_flags(&self, flags: TypeFlags) -> bool {
7293         if flags.intersects(TypeFlags::HAS_LOCAL_NAMES) {
7294             // does this represent a region that cannot be named in a global
7295             // way? used in fulfillment caching.
7296             match *self {
7297                 ty::ReStatic | ty::ReEmpty => {}
7298                 _ => return true
7299             }
7300         }
7301         if flags.intersects(TypeFlags::HAS_RE_INFER) {
7302             match *self {
7303                 ty::ReVar(_) | ty::ReSkolemized(..) => { return true }
7304                 _ => {}
7305             }
7306         }
7307         false
7308     }
7309 }
7310
7311 impl<T:HasTypeFlags,U:HasTypeFlags> HasTypeFlags for OutlivesPredicate<T,U> {
7312     fn has_type_flags(&self, flags: TypeFlags) -> bool {
7313         self.0.has_type_flags(flags) || self.1.has_type_flags(flags)
7314     }
7315 }
7316
7317 impl<'tcx> HasTypeFlags for ProjectionPredicate<'tcx> {
7318     fn has_type_flags(&self, flags: TypeFlags) -> bool {
7319         self.projection_ty.has_type_flags(flags) || self.ty.has_type_flags(flags)
7320     }
7321 }
7322
7323 impl<'tcx> HasTypeFlags for ProjectionTy<'tcx> {
7324     fn has_type_flags(&self, flags: TypeFlags) -> bool {
7325         self.trait_ref.has_type_flags(flags)
7326     }
7327 }
7328
7329 impl<'tcx> HasTypeFlags for Ty<'tcx> {
7330     fn has_type_flags(&self, flags: TypeFlags) -> bool {
7331         self.flags.get().intersects(flags)
7332     }
7333 }
7334
7335 impl<'tcx> HasTypeFlags for TypeAndMut<'tcx> {
7336     fn has_type_flags(&self, flags: TypeFlags) -> bool {
7337         self.ty.has_type_flags(flags)
7338     }
7339 }
7340
7341 impl<'tcx> HasTypeFlags for TraitRef<'tcx> {
7342     fn has_type_flags(&self, flags: TypeFlags) -> bool {
7343         self.substs.has_type_flags(flags)
7344     }
7345 }
7346
7347 impl<'tcx> HasTypeFlags for subst::Substs<'tcx> {
7348     fn has_type_flags(&self, flags: TypeFlags) -> bool {
7349         self.types.has_type_flags(flags) || match self.regions {
7350             subst::ErasedRegions => false,
7351             subst::NonerasedRegions(ref r) => r.has_type_flags(flags)
7352         }
7353     }
7354 }
7355
7356 impl<'tcx,T> HasTypeFlags for Option<T>
7357     where T : HasTypeFlags
7358 {
7359     fn has_type_flags(&self, flags: TypeFlags) -> bool {
7360         self.iter().any(|t| t.has_type_flags(flags))
7361     }
7362 }
7363
7364 impl<'tcx,T> HasTypeFlags for Rc<T>
7365     where T : HasTypeFlags
7366 {
7367     fn has_type_flags(&self, flags: TypeFlags) -> bool {
7368         (**self).has_type_flags(flags)
7369     }
7370 }
7371
7372 impl<'tcx,T> HasTypeFlags for Box<T>
7373     where T : HasTypeFlags
7374 {
7375     fn has_type_flags(&self, flags: TypeFlags) -> bool {
7376         (**self).has_type_flags(flags)
7377     }
7378 }
7379
7380 impl<T> HasTypeFlags for Binder<T>
7381     where T : HasTypeFlags
7382 {
7383     fn has_type_flags(&self, flags: TypeFlags) -> bool {
7384         self.0.has_type_flags(flags)
7385     }
7386 }
7387
7388 impl<'tcx> HasTypeFlags for FnOutput<'tcx> {
7389     fn has_type_flags(&self, flags: TypeFlags) -> bool {
7390         match *self {
7391             FnConverging(t) => t.has_type_flags(flags),
7392             FnDiverging => false,
7393         }
7394     }
7395 }
7396
7397 impl<'tcx> HasTypeFlags for FnSig<'tcx> {
7398     fn has_type_flags(&self, flags: TypeFlags) -> bool {
7399         self.inputs.iter().any(|t| t.has_type_flags(flags)) ||
7400             self.output.has_type_flags(flags)
7401     }
7402 }
7403
7404 impl<'tcx> HasTypeFlags for BareFnTy<'tcx> {
7405     fn has_type_flags(&self, flags: TypeFlags) -> bool {
7406         self.sig.has_type_flags(flags)
7407     }
7408 }
7409
7410 impl<'tcx> HasTypeFlags for ClosureSubsts<'tcx> {
7411     fn has_type_flags(&self, flags: TypeFlags) -> bool {
7412         self.func_substs.has_type_flags(flags) ||
7413             self.upvar_tys.iter().any(|t| t.has_type_flags(flags))
7414     }
7415 }
7416
7417 impl<'tcx> fmt::Debug for ClosureTy<'tcx> {
7418     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
7419         write!(f, "ClosureTy({},{:?},{})",
7420                self.unsafety,
7421                self.sig,
7422                self.abi)
7423     }
7424 }
7425
7426 impl<'tcx> fmt::Debug for ClosureUpvar<'tcx> {
7427     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
7428         write!(f, "ClosureUpvar({:?},{:?})",
7429                self.def,
7430                self.ty)
7431     }
7432 }
7433
7434 impl<'a, 'tcx> fmt::Debug for ParameterEnvironment<'a, 'tcx> {
7435     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
7436         write!(f, "ParameterEnvironment(\
7437             free_substs={:?}, \
7438             implicit_region_bound={:?}, \
7439             caller_bounds={:?})",
7440             self.free_substs,
7441             self.implicit_region_bound,
7442             self.caller_bounds)
7443     }
7444 }
7445
7446 impl<'tcx> fmt::Debug for ObjectLifetimeDefault {
7447     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
7448         match *self {
7449             ObjectLifetimeDefault::Ambiguous => write!(f, "Ambiguous"),
7450             ObjectLifetimeDefault::BaseDefault => write!(f, "BaseDefault"),
7451             ObjectLifetimeDefault::Specific(ref r) => write!(f, "{:?}", r),
7452         }
7453     }
7454 }