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