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