]> git.lizzy.rs Git - rust.git/blob - src/librustc/ty/mod.rs
c915022351925f835a8afc49de54dd2b082425f7
[rust.git] / src / librustc / ty / mod.rs
1 // Copyright 2012-2015 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 pub use self::Variance::*;
12 pub use self::AssociatedItemContainer::*;
13 pub use self::BorrowKind::*;
14 pub use self::IntVarValue::*;
15 pub use self::fold::TypeFoldable;
16
17 use hir::{map as hir_map, FreevarMap, TraitMap};
18 use hir::def::{Def, CtorKind, ExportMap};
19 use hir::def_id::{CrateNum, DefId, LocalDefId, CRATE_DEF_INDEX, LOCAL_CRATE};
20 use hir::map::DefPathData;
21 use hir::svh::Svh;
22 use ich::Fingerprint;
23 use ich::StableHashingContext;
24 use middle::const_val::ConstVal;
25 use middle::lang_items::{FnTraitLangItem, FnMutTraitLangItem, FnOnceTraitLangItem};
26 use middle::privacy::AccessLevels;
27 use middle::resolve_lifetime::ObjectLifetimeDefault;
28 use mir::Mir;
29 use mir::interpret::{GlobalId, Value, PrimVal};
30 use mir::GeneratorLayout;
31 use session::CrateDisambiguator;
32 use traits::{self, Reveal};
33 use ty;
34 use ty::subst::{Subst, Substs};
35 use ty::util::{IntTypeExt, Discr};
36 use ty::walk::TypeWalker;
37 use util::nodemap::{NodeSet, DefIdMap, FxHashMap};
38
39 use serialize::{self, Encodable, Encoder};
40 use std::cell::RefCell;
41 use std::cmp;
42 use std::fmt;
43 use std::hash::{Hash, Hasher};
44 use std::ops::Deref;
45 use rustc_data_structures::sync::Lrc;
46 use std::slice;
47 use std::vec::IntoIter;
48 use std::mem;
49 use syntax::ast::{self, DUMMY_NODE_ID, Name, Ident, NodeId};
50 use syntax::attr;
51 use syntax::ext::hygiene::{Mark, SyntaxContext};
52 use syntax::symbol::{Symbol, InternedString};
53 use syntax_pos::{DUMMY_SP, Span};
54
55 use rustc_data_structures::accumulate_vec::IntoIter as AccIntoIter;
56 use rustc_data_structures::stable_hasher::{StableHasher, StableHasherResult,
57                                            HashStable};
58
59 use hir;
60
61 pub use self::sty::{Binder, CanonicalVar, DebruijnIndex};
62 pub use self::sty::{FnSig, GenSig, PolyFnSig, PolyGenSig};
63 pub use self::sty::{InferTy, ParamTy, ProjectionTy, ExistentialPredicate};
64 pub use self::sty::{ClosureSubsts, GeneratorInterior, TypeAndMut};
65 pub use self::sty::{TraitRef, TypeVariants, PolyTraitRef};
66 pub use self::sty::{ExistentialTraitRef, PolyExistentialTraitRef};
67 pub use self::sty::{ExistentialProjection, PolyExistentialProjection, Const};
68 pub use self::sty::{BoundRegion, EarlyBoundRegion, FreeRegion, Region};
69 pub use self::sty::RegionKind;
70 pub use self::sty::{TyVid, IntVid, FloatVid, RegionVid};
71 pub use self::sty::BoundRegion::*;
72 pub use self::sty::InferTy::*;
73 pub use self::sty::RegionKind::*;
74 pub use self::sty::TypeVariants::*;
75
76 pub use self::binding::BindingMode;
77 pub use self::binding::BindingMode::*;
78
79 pub use self::context::{TyCtxt, GlobalArenas, AllArenas, tls, keep_local};
80 pub use self::context::{Lift, TypeckTables, InterpretInterner};
81
82 pub use self::instance::{Instance, InstanceDef};
83
84 pub use self::trait_def::TraitDef;
85
86 pub use self::maps::queries;
87
88 pub mod adjustment;
89 pub mod binding;
90 pub mod cast;
91 #[macro_use]
92 pub mod codec;
93 pub mod error;
94 mod erase_regions;
95 pub mod fast_reject;
96 pub mod fold;
97 pub mod inhabitedness;
98 pub mod item_path;
99 pub mod layout;
100 pub mod _match;
101 pub mod maps;
102 pub mod outlives;
103 pub mod relate;
104 pub mod steal;
105 pub mod subst;
106 pub mod trait_def;
107 pub mod walk;
108 pub mod wf;
109 pub mod util;
110
111 mod context;
112 mod flags;
113 mod instance;
114 mod structural_impls;
115 mod sty;
116
117 // Data types
118
119 /// The complete set of all analyses described in this module. This is
120 /// produced by the driver and fed to trans and later passes.
121 ///
122 /// NB: These contents are being migrated into queries using the
123 /// *on-demand* infrastructure.
124 #[derive(Clone)]
125 pub struct CrateAnalysis {
126     pub access_levels: Lrc<AccessLevels>,
127     pub name: String,
128     pub glob_map: Option<hir::GlobMap>,
129 }
130
131 #[derive(Clone)]
132 pub struct Resolutions {
133     pub freevars: FreevarMap,
134     pub trait_map: TraitMap,
135     pub maybe_unused_trait_imports: NodeSet,
136     pub maybe_unused_extern_crates: Vec<(NodeId, Span)>,
137     pub export_map: ExportMap,
138 }
139
140 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
141 pub enum AssociatedItemContainer {
142     TraitContainer(DefId),
143     ImplContainer(DefId),
144 }
145
146 impl AssociatedItemContainer {
147     /// Asserts that this is the def-id of an associated item declared
148     /// in a trait, and returns the trait def-id.
149     pub fn assert_trait(&self) -> DefId {
150         match *self {
151             TraitContainer(id) => id,
152             _ => bug!("associated item has wrong container type: {:?}", self)
153         }
154     }
155
156     pub fn id(&self) -> DefId {
157         match *self {
158             TraitContainer(id) => id,
159             ImplContainer(id) => id,
160         }
161     }
162 }
163
164 /// The "header" of an impl is everything outside the body: a Self type, a trait
165 /// ref (in the case of a trait impl), and a set of predicates (from the
166 /// bounds/where clauses).
167 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
168 pub struct ImplHeader<'tcx> {
169     pub impl_def_id: DefId,
170     pub self_ty: Ty<'tcx>,
171     pub trait_ref: Option<TraitRef<'tcx>>,
172     pub predicates: Vec<Predicate<'tcx>>,
173 }
174
175 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
176 pub struct AssociatedItem {
177     pub def_id: DefId,
178     pub name: Name,
179     pub kind: AssociatedKind,
180     pub vis: Visibility,
181     pub defaultness: hir::Defaultness,
182     pub container: AssociatedItemContainer,
183
184     /// Whether this is a method with an explicit self
185     /// as its first argument, allowing method calls.
186     pub method_has_self_argument: bool,
187 }
188
189 #[derive(Copy, Clone, PartialEq, Eq, Debug, Hash, RustcEncodable, RustcDecodable)]
190 pub enum AssociatedKind {
191     Const,
192     Method,
193     Type
194 }
195
196 impl AssociatedItem {
197     pub fn def(&self) -> Def {
198         match self.kind {
199             AssociatedKind::Const => Def::AssociatedConst(self.def_id),
200             AssociatedKind::Method => Def::Method(self.def_id),
201             AssociatedKind::Type => Def::AssociatedTy(self.def_id),
202         }
203     }
204
205     /// Tests whether the associated item admits a non-trivial implementation
206     /// for !
207     pub fn relevant_for_never<'tcx>(&self) -> bool {
208         match self.kind {
209             AssociatedKind::Const => true,
210             AssociatedKind::Type => true,
211             // FIXME(canndrew): Be more thorough here, check if any argument is uninhabited.
212             AssociatedKind::Method => !self.method_has_self_argument,
213         }
214     }
215
216     pub fn signature<'a, 'tcx>(&self, tcx: &TyCtxt<'a, 'tcx, 'tcx>) -> String {
217         match self.kind {
218             ty::AssociatedKind::Method => {
219                 // We skip the binder here because the binder would deanonymize all
220                 // late-bound regions, and we don't want method signatures to show up
221                 // `as for<'r> fn(&'r MyType)`.  Pretty-printing handles late-bound
222                 // regions just fine, showing `fn(&MyType)`.
223                 format!("{}", tcx.fn_sig(self.def_id).skip_binder())
224             }
225             ty::AssociatedKind::Type => format!("type {};", self.name.to_string()),
226             ty::AssociatedKind::Const => {
227                 format!("const {}: {:?};", self.name.to_string(), tcx.type_of(self.def_id))
228             }
229         }
230     }
231 }
232
233 #[derive(Clone, Debug, PartialEq, Eq, Copy, RustcEncodable, RustcDecodable)]
234 pub enum Visibility {
235     /// Visible everywhere (including in other crates).
236     Public,
237     /// Visible only in the given crate-local module.
238     Restricted(DefId),
239     /// Not visible anywhere in the local crate. This is the visibility of private external items.
240     Invisible,
241 }
242
243 pub trait DefIdTree: Copy {
244     fn parent(self, id: DefId) -> Option<DefId>;
245
246     fn is_descendant_of(self, mut descendant: DefId, ancestor: DefId) -> bool {
247         if descendant.krate != ancestor.krate {
248             return false;
249         }
250
251         while descendant != ancestor {
252             match self.parent(descendant) {
253                 Some(parent) => descendant = parent,
254                 None => return false,
255             }
256         }
257         true
258     }
259 }
260
261 impl<'a, 'gcx, 'tcx> DefIdTree for TyCtxt<'a, 'gcx, 'tcx> {
262     fn parent(self, id: DefId) -> Option<DefId> {
263         self.def_key(id).parent.map(|index| DefId { index: index, ..id })
264     }
265 }
266
267 impl Visibility {
268     pub fn from_hir(visibility: &hir::Visibility, id: NodeId, tcx: TyCtxt) -> Self {
269         match *visibility {
270             hir::Public => Visibility::Public,
271             hir::Visibility::Crate => Visibility::Restricted(DefId::local(CRATE_DEF_INDEX)),
272             hir::Visibility::Restricted { ref path, .. } => match path.def {
273                 // If there is no resolution, `resolve` will have already reported an error, so
274                 // assume that the visibility is public to avoid reporting more privacy errors.
275                 Def::Err => Visibility::Public,
276                 def => Visibility::Restricted(def.def_id()),
277             },
278             hir::Inherited => {
279                 Visibility::Restricted(tcx.hir.get_module_parent(id))
280             }
281         }
282     }
283
284     /// Returns true if an item with this visibility is accessible from the given block.
285     pub fn is_accessible_from<T: DefIdTree>(self, module: DefId, tree: T) -> bool {
286         let restriction = match self {
287             // Public items are visible everywhere.
288             Visibility::Public => return true,
289             // Private items from other crates are visible nowhere.
290             Visibility::Invisible => return false,
291             // Restricted items are visible in an arbitrary local module.
292             Visibility::Restricted(other) if other.krate != module.krate => return false,
293             Visibility::Restricted(module) => module,
294         };
295
296         tree.is_descendant_of(module, restriction)
297     }
298
299     /// Returns true if this visibility is at least as accessible as the given visibility
300     pub fn is_at_least<T: DefIdTree>(self, vis: Visibility, tree: T) -> bool {
301         let vis_restriction = match vis {
302             Visibility::Public => return self == Visibility::Public,
303             Visibility::Invisible => return true,
304             Visibility::Restricted(module) => module,
305         };
306
307         self.is_accessible_from(vis_restriction, tree)
308     }
309
310     // Returns true if this item is visible anywhere in the local crate.
311     pub fn is_visible_locally(self) -> bool {
312         match self {
313             Visibility::Public => true,
314             Visibility::Restricted(def_id) => def_id.is_local(),
315             Visibility::Invisible => false,
316         }
317     }
318 }
319
320 #[derive(Clone, PartialEq, RustcDecodable, RustcEncodable, Copy)]
321 pub enum Variance {
322     Covariant,      // T<A> <: T<B> iff A <: B -- e.g., function return type
323     Invariant,      // T<A> <: T<B> iff B == A -- e.g., type of mutable cell
324     Contravariant,  // T<A> <: T<B> iff B <: A -- e.g., function param type
325     Bivariant,      // T<A> <: T<B>            -- e.g., unused type parameter
326 }
327
328 /// The crate variances map is computed during typeck and contains the
329 /// variance of every item in the local crate. You should not use it
330 /// directly, because to do so will make your pass dependent on the
331 /// HIR of every item in the local crate. Instead, use
332 /// `tcx.variances_of()` to get the variance for a *particular*
333 /// item.
334 pub struct CrateVariancesMap {
335     /// For each item with generics, maps to a vector of the variance
336     /// of its generics.  If an item has no generics, it will have no
337     /// entry.
338     pub variances: FxHashMap<DefId, Lrc<Vec<ty::Variance>>>,
339
340     /// An empty vector, useful for cloning.
341     pub empty_variance: Lrc<Vec<ty::Variance>>,
342 }
343
344 impl Variance {
345     /// `a.xform(b)` combines the variance of a context with the
346     /// variance of a type with the following meaning.  If we are in a
347     /// context with variance `a`, and we encounter a type argument in
348     /// a position with variance `b`, then `a.xform(b)` is the new
349     /// variance with which the argument appears.
350     ///
351     /// Example 1:
352     ///
353     ///     *mut Vec<i32>
354     ///
355     /// Here, the "ambient" variance starts as covariant. `*mut T` is
356     /// invariant with respect to `T`, so the variance in which the
357     /// `Vec<i32>` appears is `Covariant.xform(Invariant)`, which
358     /// yields `Invariant`. Now, the type `Vec<T>` is covariant with
359     /// respect to its type argument `T`, and hence the variance of
360     /// the `i32` here is `Invariant.xform(Covariant)`, which results
361     /// (again) in `Invariant`.
362     ///
363     /// Example 2:
364     ///
365     ///     fn(*const Vec<i32>, *mut Vec<i32)
366     ///
367     /// The ambient variance is covariant. A `fn` type is
368     /// contravariant with respect to its parameters, so the variance
369     /// within which both pointer types appear is
370     /// `Covariant.xform(Contravariant)`, or `Contravariant`.  `*const
371     /// T` is covariant with respect to `T`, so the variance within
372     /// which the first `Vec<i32>` appears is
373     /// `Contravariant.xform(Covariant)` or `Contravariant`.  The same
374     /// is true for its `i32` argument. In the `*mut T` case, the
375     /// variance of `Vec<i32>` is `Contravariant.xform(Invariant)`,
376     /// and hence the outermost type is `Invariant` with respect to
377     /// `Vec<i32>` (and its `i32` argument).
378     ///
379     /// Source: Figure 1 of "Taming the Wildcards:
380     /// Combining Definition- and Use-Site Variance" published in PLDI'11.
381     pub fn xform(self, v: ty::Variance) -> ty::Variance {
382         match (self, v) {
383             // Figure 1, column 1.
384             (ty::Covariant, ty::Covariant) => ty::Covariant,
385             (ty::Covariant, ty::Contravariant) => ty::Contravariant,
386             (ty::Covariant, ty::Invariant) => ty::Invariant,
387             (ty::Covariant, ty::Bivariant) => ty::Bivariant,
388
389             // Figure 1, column 2.
390             (ty::Contravariant, ty::Covariant) => ty::Contravariant,
391             (ty::Contravariant, ty::Contravariant) => ty::Covariant,
392             (ty::Contravariant, ty::Invariant) => ty::Invariant,
393             (ty::Contravariant, ty::Bivariant) => ty::Bivariant,
394
395             // Figure 1, column 3.
396             (ty::Invariant, _) => ty::Invariant,
397
398             // Figure 1, column 4.
399             (ty::Bivariant, _) => ty::Bivariant,
400         }
401     }
402 }
403
404 // Contains information needed to resolve types and (in the future) look up
405 // the types of AST nodes.
406 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
407 pub struct CReaderCacheKey {
408     pub cnum: CrateNum,
409     pub pos: usize,
410 }
411
412 // Flags that we track on types. These flags are propagated upwards
413 // through the type during type construction, so that we can quickly
414 // check whether the type has various kinds of types in it without
415 // recursing over the type itself.
416 bitflags! {
417     pub struct TypeFlags: u32 {
418         const HAS_PARAMS         = 1 << 0;
419         const HAS_SELF           = 1 << 1;
420         const HAS_TY_INFER       = 1 << 2;
421         const HAS_RE_INFER       = 1 << 3;
422         const HAS_RE_SKOL        = 1 << 4;
423
424         /// Does this have any `ReEarlyBound` regions? Used to
425         /// determine whether substitition is required, since those
426         /// represent regions that are bound in a `ty::Generics` and
427         /// hence may be substituted.
428         const HAS_RE_EARLY_BOUND = 1 << 5;
429
430         /// Does this have any region that "appears free" in the type?
431         /// Basically anything but `ReLateBound` and `ReErased`.
432         const HAS_FREE_REGIONS   = 1 << 6;
433
434         /// Is an error type reachable?
435         const HAS_TY_ERR         = 1 << 7;
436         const HAS_PROJECTION     = 1 << 8;
437
438         // FIXME: Rename this to the actual property since it's used for generators too
439         const HAS_TY_CLOSURE     = 1 << 9;
440
441         // true if there are "names" of types and regions and so forth
442         // that are local to a particular fn
443         const HAS_LOCAL_NAMES    = 1 << 10;
444
445         // Present if the type belongs in a local type context.
446         // Only set for TyInfer other than Fresh.
447         const KEEP_IN_LOCAL_TCX  = 1 << 11;
448
449         // Is there a projection that does not involve a bound region?
450         // Currently we can't normalize projections w/ bound regions.
451         const HAS_NORMALIZABLE_PROJECTION = 1 << 12;
452
453         // Set if this includes a "canonical" type or region var --
454         // ought to be true only for the results of canonicalization.
455         const HAS_CANONICAL_VARS = 1 << 13;
456
457         const NEEDS_SUBST        = TypeFlags::HAS_PARAMS.bits |
458                                    TypeFlags::HAS_SELF.bits |
459                                    TypeFlags::HAS_RE_EARLY_BOUND.bits;
460
461         // Flags representing the nominal content of a type,
462         // computed by FlagsComputation. If you add a new nominal
463         // flag, it should be added here too.
464         const NOMINAL_FLAGS     = TypeFlags::HAS_PARAMS.bits |
465                                   TypeFlags::HAS_SELF.bits |
466                                   TypeFlags::HAS_TY_INFER.bits |
467                                   TypeFlags::HAS_RE_INFER.bits |
468                                   TypeFlags::HAS_RE_SKOL.bits |
469                                   TypeFlags::HAS_RE_EARLY_BOUND.bits |
470                                   TypeFlags::HAS_FREE_REGIONS.bits |
471                                   TypeFlags::HAS_TY_ERR.bits |
472                                   TypeFlags::HAS_PROJECTION.bits |
473                                   TypeFlags::HAS_TY_CLOSURE.bits |
474                                   TypeFlags::HAS_LOCAL_NAMES.bits |
475                                   TypeFlags::KEEP_IN_LOCAL_TCX.bits |
476                                   TypeFlags::HAS_CANONICAL_VARS.bits;
477     }
478 }
479
480 pub struct TyS<'tcx> {
481     pub sty: TypeVariants<'tcx>,
482     pub flags: TypeFlags,
483
484     // the maximal depth of any bound regions appearing in this type.
485     region_depth: u32,
486 }
487
488 impl<'tcx> PartialEq for TyS<'tcx> {
489     #[inline]
490     fn eq(&self, other: &TyS<'tcx>) -> bool {
491         // (self as *const _) == (other as *const _)
492         (self as *const TyS<'tcx>) == (other as *const TyS<'tcx>)
493     }
494 }
495 impl<'tcx> Eq for TyS<'tcx> {}
496
497 impl<'tcx> Hash for TyS<'tcx> {
498     fn hash<H: Hasher>(&self, s: &mut H) {
499         (self as *const TyS).hash(s)
500     }
501 }
502
503 impl<'tcx> TyS<'tcx> {
504     pub fn is_primitive_ty(&self) -> bool {
505         match self.sty {
506             TypeVariants::TyBool |
507                 TypeVariants::TyChar |
508                 TypeVariants::TyInt(_) |
509                 TypeVariants::TyUint(_) |
510                 TypeVariants::TyFloat(_) |
511                 TypeVariants::TyInfer(InferTy::IntVar(_)) |
512                 TypeVariants::TyInfer(InferTy::FloatVar(_)) |
513                 TypeVariants::TyInfer(InferTy::FreshIntTy(_)) |
514                 TypeVariants::TyInfer(InferTy::FreshFloatTy(_)) => true,
515             TypeVariants::TyRef(_, x) => x.ty.is_primitive_ty(),
516             _ => false,
517         }
518     }
519
520     pub fn is_suggestable(&self) -> bool {
521         match self.sty {
522             TypeVariants::TyAnon(..) |
523             TypeVariants::TyFnDef(..) |
524             TypeVariants::TyFnPtr(..) |
525             TypeVariants::TyDynamic(..) |
526             TypeVariants::TyClosure(..) |
527             TypeVariants::TyInfer(..) |
528             TypeVariants::TyProjection(..) => false,
529             _ => true,
530         }
531     }
532 }
533
534 impl<'a, 'gcx> HashStable<StableHashingContext<'a>> for ty::TyS<'gcx> {
535     fn hash_stable<W: StableHasherResult>(&self,
536                                           hcx: &mut StableHashingContext<'a>,
537                                           hasher: &mut StableHasher<W>) {
538         let ty::TyS {
539             ref sty,
540
541             // The other fields just provide fast access to information that is
542             // also contained in `sty`, so no need to hash them.
543             flags: _,
544             region_depth: _,
545         } = *self;
546
547         sty.hash_stable(hcx, hasher);
548     }
549 }
550
551 pub type Ty<'tcx> = &'tcx TyS<'tcx>;
552
553 impl<'tcx> serialize::UseSpecializedEncodable for Ty<'tcx> {}
554 impl<'tcx> serialize::UseSpecializedDecodable for Ty<'tcx> {}
555
556 /// A wrapper for slices with the additional invariant
557 /// that the slice is interned and no other slice with
558 /// the same contents can exist in the same context.
559 /// This means we can use pointer + length for both
560 /// equality comparisons and hashing.
561 #[derive(Debug, RustcEncodable)]
562 pub struct Slice<T>([T]);
563
564 impl<T> PartialEq for Slice<T> {
565     #[inline]
566     fn eq(&self, other: &Slice<T>) -> bool {
567         (&self.0 as *const [T]) == (&other.0 as *const [T])
568     }
569 }
570 impl<T> Eq for Slice<T> {}
571
572 impl<T> Hash for Slice<T> {
573     fn hash<H: Hasher>(&self, s: &mut H) {
574         (self.as_ptr(), self.len()).hash(s)
575     }
576 }
577
578 impl<T> Deref for Slice<T> {
579     type Target = [T];
580     fn deref(&self) -> &[T] {
581         &self.0
582     }
583 }
584
585 impl<'a, T> IntoIterator for &'a Slice<T> {
586     type Item = &'a T;
587     type IntoIter = <&'a [T] as IntoIterator>::IntoIter;
588     fn into_iter(self) -> Self::IntoIter {
589         self[..].iter()
590     }
591 }
592
593 impl<'tcx> serialize::UseSpecializedDecodable for &'tcx Slice<Ty<'tcx>> {}
594
595 impl<T> Slice<T> {
596     pub fn empty<'a>() -> &'a Slice<T> {
597         unsafe {
598             mem::transmute(slice::from_raw_parts(0x1 as *const T, 0))
599         }
600     }
601 }
602
603 /// Upvars do not get their own node-id. Instead, we use the pair of
604 /// the original var id (that is, the root variable that is referenced
605 /// by the upvar) and the id of the closure expression.
606 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
607 pub struct UpvarId {
608     pub var_id: hir::HirId,
609     pub closure_expr_id: LocalDefId,
610 }
611
612 #[derive(Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable, Copy)]
613 pub enum BorrowKind {
614     /// Data must be immutable and is aliasable.
615     ImmBorrow,
616
617     /// Data must be immutable but not aliasable.  This kind of borrow
618     /// cannot currently be expressed by the user and is used only in
619     /// implicit closure bindings. It is needed when the closure
620     /// is borrowing or mutating a mutable referent, e.g.:
621     ///
622     ///    let x: &mut isize = ...;
623     ///    let y = || *x += 5;
624     ///
625     /// If we were to try to translate this closure into a more explicit
626     /// form, we'd encounter an error with the code as written:
627     ///
628     ///    struct Env { x: & &mut isize }
629     ///    let x: &mut isize = ...;
630     ///    let y = (&mut Env { &x }, fn_ptr);  // Closure is pair of env and fn
631     ///    fn fn_ptr(env: &mut Env) { **env.x += 5; }
632     ///
633     /// This is then illegal because you cannot mutate a `&mut` found
634     /// in an aliasable location. To solve, you'd have to translate with
635     /// an `&mut` borrow:
636     ///
637     ///    struct Env { x: & &mut isize }
638     ///    let x: &mut isize = ...;
639     ///    let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
640     ///    fn fn_ptr(env: &mut Env) { **env.x += 5; }
641     ///
642     /// Now the assignment to `**env.x` is legal, but creating a
643     /// mutable pointer to `x` is not because `x` is not mutable. We
644     /// could fix this by declaring `x` as `let mut x`. This is ok in
645     /// user code, if awkward, but extra weird for closures, since the
646     /// borrow is hidden.
647     ///
648     /// So we introduce a "unique imm" borrow -- the referent is
649     /// immutable, but not aliasable. This solves the problem. For
650     /// simplicity, we don't give users the way to express this
651     /// borrow, it's just used when translating closures.
652     UniqueImmBorrow,
653
654     /// Data is mutable and not aliasable.
655     MutBorrow
656 }
657
658 /// Information describing the capture of an upvar. This is computed
659 /// during `typeck`, specifically by `regionck`.
660 #[derive(PartialEq, Clone, Debug, Copy, RustcEncodable, RustcDecodable)]
661 pub enum UpvarCapture<'tcx> {
662     /// Upvar is captured by value. This is always true when the
663     /// closure is labeled `move`, but can also be true in other cases
664     /// depending on inference.
665     ByValue,
666
667     /// Upvar is captured by reference.
668     ByRef(UpvarBorrow<'tcx>),
669 }
670
671 #[derive(PartialEq, Clone, Copy, RustcEncodable, RustcDecodable)]
672 pub struct UpvarBorrow<'tcx> {
673     /// The kind of borrow: by-ref upvars have access to shared
674     /// immutable borrows, which are not part of the normal language
675     /// syntax.
676     pub kind: BorrowKind,
677
678     /// Region of the resulting reference.
679     pub region: ty::Region<'tcx>,
680 }
681
682 pub type UpvarCaptureMap<'tcx> = FxHashMap<UpvarId, UpvarCapture<'tcx>>;
683
684 #[derive(Copy, Clone)]
685 pub struct ClosureUpvar<'tcx> {
686     pub def: Def,
687     pub span: Span,
688     pub ty: Ty<'tcx>,
689 }
690
691 #[derive(Clone, Copy, PartialEq, Eq)]
692 pub enum IntVarValue {
693     IntType(ast::IntTy),
694     UintType(ast::UintTy),
695 }
696
697 #[derive(Clone, Copy, PartialEq, Eq)]
698 pub struct FloatVarValue(pub ast::FloatTy);
699
700 #[derive(Copy, Clone, RustcEncodable, RustcDecodable)]
701 pub struct TypeParameterDef {
702     pub name: Name,
703     pub def_id: DefId,
704     pub index: u32,
705     pub has_default: bool,
706     pub object_lifetime_default: ObjectLifetimeDefault,
707
708     /// `pure_wrt_drop`, set by the (unsafe) `#[may_dangle]` attribute
709     /// on generic parameter `T`, asserts data behind the parameter
710     /// `T` won't be accessed during the parent type's `Drop` impl.
711     pub pure_wrt_drop: bool,
712
713     pub synthetic: Option<hir::SyntheticTyParamKind>,
714 }
715
716 #[derive(Copy, Clone, RustcEncodable, RustcDecodable)]
717 pub struct RegionParameterDef {
718     pub name: Name,
719     pub def_id: DefId,
720     pub index: u32,
721
722     /// `pure_wrt_drop`, set by the (unsafe) `#[may_dangle]` attribute
723     /// on generic parameter `'a`, asserts data of lifetime `'a`
724     /// won't be accessed during the parent type's `Drop` impl.
725     pub pure_wrt_drop: bool,
726 }
727
728 impl RegionParameterDef {
729     pub fn to_early_bound_region_data(&self) -> ty::EarlyBoundRegion {
730         ty::EarlyBoundRegion {
731             def_id: self.def_id,
732             index: self.index,
733             name: self.name,
734         }
735     }
736
737     pub fn to_bound_region(&self) -> ty::BoundRegion {
738         self.to_early_bound_region_data().to_bound_region()
739     }
740 }
741
742 impl ty::EarlyBoundRegion {
743     pub fn to_bound_region(&self) -> ty::BoundRegion {
744         ty::BoundRegion::BrNamed(self.def_id, self.name)
745     }
746 }
747
748 /// Information about the formal type/lifetime parameters associated
749 /// with an item or method. Analogous to hir::Generics.
750 ///
751 /// Note that in the presence of a `Self` parameter, the ordering here
752 /// is different from the ordering in a Substs. Substs are ordered as
753 ///     Self, *Regions, *Other Type Params, (...child generics)
754 /// while this struct is ordered as
755 ///     regions = Regions
756 ///     types = [Self, *Other Type Params]
757 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
758 pub struct Generics {
759     pub parent: Option<DefId>,
760     pub parent_regions: u32,
761     pub parent_types: u32,
762     pub regions: Vec<RegionParameterDef>,
763     pub types: Vec<TypeParameterDef>,
764
765     /// Reverse map to each `TypeParameterDef`'s `index` field
766     pub type_param_to_index: FxHashMap<DefId, u32>,
767
768     pub has_self: bool,
769     pub has_late_bound_regions: Option<Span>,
770 }
771
772 impl<'a, 'gcx, 'tcx> Generics {
773     pub fn parent_count(&self) -> usize {
774         self.parent_regions as usize + self.parent_types as usize
775     }
776
777     pub fn own_count(&self) -> usize {
778         self.regions.len() + self.types.len()
779     }
780
781     pub fn count(&self) -> usize {
782         self.parent_count() + self.own_count()
783     }
784
785     pub fn region_param(&'tcx self,
786                         param: &EarlyBoundRegion,
787                         tcx: TyCtxt<'a, 'gcx, 'tcx>)
788                         -> &'tcx RegionParameterDef
789     {
790         if let Some(index) = param.index.checked_sub(self.parent_count() as u32) {
791             &self.regions[index as usize - self.has_self as usize]
792         } else {
793             tcx.generics_of(self.parent.expect("parent_count>0 but no parent?"))
794                 .region_param(param, tcx)
795         }
796     }
797
798     /// Returns the `TypeParameterDef` associated with this `ParamTy`.
799     pub fn type_param(&'tcx self,
800                       param: &ParamTy,
801                       tcx: TyCtxt<'a, 'gcx, 'tcx>)
802                       -> &TypeParameterDef {
803         if let Some(idx) = param.idx.checked_sub(self.parent_count() as u32) {
804             // non-Self type parameters are always offset by exactly
805             // `self.regions.len()`. In the absence of a Self, this is obvious,
806             // but even in the presence of a `Self` we just have to "compensate"
807             // for the regions:
808             //
809             // Without a `Self` (or in a nested generics that doesn't have
810             // a `Self` in itself, even through it parent does), for example
811             // for `fn foo<'a, T1, T2>()`, the situation is:
812             //     Substs:
813             //         0  1  2
814             //         'a T1 T2
815             //     generics.types:
816             //         0  1
817             //         T1 T2
818             //
819             // And with a `Self`, for example for `trait Foo<'a, 'b, T1, T2>`, the
820             // situation is:
821             //     Substs:
822             //         0   1  2  3  4
823             //       Self 'a 'b  T1 T2
824             //     generics.types:
825             //         0  1  2
826             //       Self T1 T2
827             //
828             // And it can be seen that in both cases, to move from a substs
829             // offset to a generics offset you just have to offset by the
830             // number of regions.
831             let type_param_offset = self.regions.len();
832
833             let has_self = self.has_self && self.parent.is_none();
834             let is_separated_self = type_param_offset != 0 && idx == 0 && has_self;
835
836             if let Some(idx) = (idx as usize).checked_sub(type_param_offset) {
837                 assert!(!is_separated_self, "found a Self after type_param_offset");
838                 &self.types[idx]
839             } else {
840                 assert!(is_separated_self, "non-Self param before type_param_offset");
841                 &self.types[0]
842             }
843         } else {
844             tcx.generics_of(self.parent.expect("parent_count>0 but no parent?"))
845                 .type_param(param, tcx)
846         }
847     }
848 }
849
850 /// Bounds on generics.
851 #[derive(Clone, Default)]
852 pub struct GenericPredicates<'tcx> {
853     pub parent: Option<DefId>,
854     pub predicates: Vec<Predicate<'tcx>>,
855 }
856
857 impl<'tcx> serialize::UseSpecializedEncodable for GenericPredicates<'tcx> {}
858 impl<'tcx> serialize::UseSpecializedDecodable for GenericPredicates<'tcx> {}
859
860 impl<'a, 'gcx, 'tcx> GenericPredicates<'tcx> {
861     pub fn instantiate(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, substs: &Substs<'tcx>)
862                        -> InstantiatedPredicates<'tcx> {
863         let mut instantiated = InstantiatedPredicates::empty();
864         self.instantiate_into(tcx, &mut instantiated, substs);
865         instantiated
866     }
867     pub fn instantiate_own(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, substs: &Substs<'tcx>)
868                            -> InstantiatedPredicates<'tcx> {
869         InstantiatedPredicates {
870             predicates: self.predicates.subst(tcx, substs)
871         }
872     }
873
874     fn instantiate_into(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
875                         instantiated: &mut InstantiatedPredicates<'tcx>,
876                         substs: &Substs<'tcx>) {
877         if let Some(def_id) = self.parent {
878             tcx.predicates_of(def_id).instantiate_into(tcx, instantiated, substs);
879         }
880         instantiated.predicates.extend(self.predicates.iter().map(|p| p.subst(tcx, substs)))
881     }
882
883     pub fn instantiate_identity(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>)
884                                 -> InstantiatedPredicates<'tcx> {
885         let mut instantiated = InstantiatedPredicates::empty();
886         self.instantiate_identity_into(tcx, &mut instantiated);
887         instantiated
888     }
889
890     fn instantiate_identity_into(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
891                                  instantiated: &mut InstantiatedPredicates<'tcx>) {
892         if let Some(def_id) = self.parent {
893             tcx.predicates_of(def_id).instantiate_identity_into(tcx, instantiated);
894         }
895         instantiated.predicates.extend(&self.predicates)
896     }
897
898     pub fn instantiate_supertrait(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
899                                   poly_trait_ref: &ty::PolyTraitRef<'tcx>)
900                                   -> InstantiatedPredicates<'tcx>
901     {
902         assert_eq!(self.parent, None);
903         InstantiatedPredicates {
904             predicates: self.predicates.iter().map(|pred| {
905                 pred.subst_supertrait(tcx, poly_trait_ref)
906             }).collect()
907         }
908     }
909 }
910
911 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
912 pub enum Predicate<'tcx> {
913     /// Corresponds to `where Foo : Bar<A,B,C>`. `Foo` here would be
914     /// the `Self` type of the trait reference and `A`, `B`, and `C`
915     /// would be the type parameters.
916     Trait(PolyTraitPredicate<'tcx>),
917
918     /// where 'a : 'b
919     RegionOutlives(PolyRegionOutlivesPredicate<'tcx>),
920
921     /// where T : 'a
922     TypeOutlives(PolyTypeOutlivesPredicate<'tcx>),
923
924     /// where <T as TraitRef>::Name == X, approximately.
925     /// See `ProjectionPredicate` struct for details.
926     Projection(PolyProjectionPredicate<'tcx>),
927
928     /// no syntax: T WF
929     WellFormed(Ty<'tcx>),
930
931     /// trait must be object-safe
932     ObjectSafe(DefId),
933
934     /// No direct syntax. May be thought of as `where T : FnFoo<...>`
935     /// for some substitutions `...` and T being a closure type.
936     /// Satisfied (or refuted) once we know the closure's kind.
937     ClosureKind(DefId, ClosureSubsts<'tcx>, ClosureKind),
938
939     /// `T1 <: T2`
940     Subtype(PolySubtypePredicate<'tcx>),
941
942     /// Constant initializer must evaluate successfully.
943     ConstEvaluatable(DefId, &'tcx Substs<'tcx>),
944 }
945
946 impl<'tcx> AsRef<Predicate<'tcx>> for Predicate<'tcx> {
947     fn as_ref(&self) -> &Predicate<'tcx> {
948         self
949     }
950 }
951
952 impl<'a, 'gcx, 'tcx> Predicate<'tcx> {
953     /// Performs a substitution suitable for going from a
954     /// poly-trait-ref to supertraits that must hold if that
955     /// poly-trait-ref holds. This is slightly different from a normal
956     /// substitution in terms of what happens with bound regions.  See
957     /// lengthy comment below for details.
958     pub fn subst_supertrait(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
959                             trait_ref: &ty::PolyTraitRef<'tcx>)
960                             -> ty::Predicate<'tcx>
961     {
962         // The interaction between HRTB and supertraits is not entirely
963         // obvious. Let me walk you (and myself) through an example.
964         //
965         // Let's start with an easy case. Consider two traits:
966         //
967         //     trait Foo<'a> : Bar<'a,'a> { }
968         //     trait Bar<'b,'c> { }
969         //
970         // Now, if we have a trait reference `for<'x> T : Foo<'x>`, then
971         // we can deduce that `for<'x> T : Bar<'x,'x>`. Basically, if we
972         // knew that `Foo<'x>` (for any 'x) then we also know that
973         // `Bar<'x,'x>` (for any 'x). This more-or-less falls out from
974         // normal substitution.
975         //
976         // In terms of why this is sound, the idea is that whenever there
977         // is an impl of `T:Foo<'a>`, it must show that `T:Bar<'a,'a>`
978         // holds.  So if there is an impl of `T:Foo<'a>` that applies to
979         // all `'a`, then we must know that `T:Bar<'a,'a>` holds for all
980         // `'a`.
981         //
982         // Another example to be careful of is this:
983         //
984         //     trait Foo1<'a> : for<'b> Bar1<'a,'b> { }
985         //     trait Bar1<'b,'c> { }
986         //
987         // Here, if we have `for<'x> T : Foo1<'x>`, then what do we know?
988         // The answer is that we know `for<'x,'b> T : Bar1<'x,'b>`. The
989         // reason is similar to the previous example: any impl of
990         // `T:Foo1<'x>` must show that `for<'b> T : Bar1<'x, 'b>`.  So
991         // basically we would want to collapse the bound lifetimes from
992         // the input (`trait_ref`) and the supertraits.
993         //
994         // To achieve this in practice is fairly straightforward. Let's
995         // consider the more complicated scenario:
996         //
997         // - We start out with `for<'x> T : Foo1<'x>`. In this case, `'x`
998         //   has a De Bruijn index of 1. We want to produce `for<'x,'b> T : Bar1<'x,'b>`,
999         //   where both `'x` and `'b` would have a DB index of 1.
1000         //   The substitution from the input trait-ref is therefore going to be
1001         //   `'a => 'x` (where `'x` has a DB index of 1).
1002         // - The super-trait-ref is `for<'b> Bar1<'a,'b>`, where `'a` is an
1003         //   early-bound parameter and `'b' is a late-bound parameter with a
1004         //   DB index of 1.
1005         // - If we replace `'a` with `'x` from the input, it too will have
1006         //   a DB index of 1, and thus we'll have `for<'x,'b> Bar1<'x,'b>`
1007         //   just as we wanted.
1008         //
1009         // There is only one catch. If we just apply the substitution `'a
1010         // => 'x` to `for<'b> Bar1<'a,'b>`, the substitution code will
1011         // adjust the DB index because we substituting into a binder (it
1012         // tries to be so smart...) resulting in `for<'x> for<'b>
1013         // Bar1<'x,'b>` (we have no syntax for this, so use your
1014         // imagination). Basically the 'x will have DB index of 2 and 'b
1015         // will have DB index of 1. Not quite what we want. So we apply
1016         // the substitution to the *contents* of the trait reference,
1017         // rather than the trait reference itself (put another way, the
1018         // substitution code expects equal binding levels in the values
1019         // from the substitution and the value being substituted into, and
1020         // this trick achieves that).
1021
1022         let substs = &trait_ref.0.substs;
1023         match *self {
1024             Predicate::Trait(ty::Binder(ref data)) =>
1025                 Predicate::Trait(ty::Binder(data.subst(tcx, substs))),
1026             Predicate::Subtype(ty::Binder(ref data)) =>
1027                 Predicate::Subtype(ty::Binder(data.subst(tcx, substs))),
1028             Predicate::RegionOutlives(ty::Binder(ref data)) =>
1029                 Predicate::RegionOutlives(ty::Binder(data.subst(tcx, substs))),
1030             Predicate::TypeOutlives(ty::Binder(ref data)) =>
1031                 Predicate::TypeOutlives(ty::Binder(data.subst(tcx, substs))),
1032             Predicate::Projection(ty::Binder(ref data)) =>
1033                 Predicate::Projection(ty::Binder(data.subst(tcx, substs))),
1034             Predicate::WellFormed(data) =>
1035                 Predicate::WellFormed(data.subst(tcx, substs)),
1036             Predicate::ObjectSafe(trait_def_id) =>
1037                 Predicate::ObjectSafe(trait_def_id),
1038             Predicate::ClosureKind(closure_def_id, closure_substs, kind) =>
1039                 Predicate::ClosureKind(closure_def_id, closure_substs.subst(tcx, substs), kind),
1040             Predicate::ConstEvaluatable(def_id, const_substs) =>
1041                 Predicate::ConstEvaluatable(def_id, const_substs.subst(tcx, substs)),
1042         }
1043     }
1044 }
1045
1046 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1047 pub struct TraitPredicate<'tcx> {
1048     pub trait_ref: TraitRef<'tcx>
1049 }
1050 pub type PolyTraitPredicate<'tcx> = ty::Binder<TraitPredicate<'tcx>>;
1051
1052 impl<'tcx> TraitPredicate<'tcx> {
1053     pub fn def_id(&self) -> DefId {
1054         self.trait_ref.def_id
1055     }
1056
1057     pub fn input_types<'a>(&'a self) -> impl DoubleEndedIterator<Item=Ty<'tcx>> + 'a {
1058         self.trait_ref.input_types()
1059     }
1060
1061     pub fn self_ty(&self) -> Ty<'tcx> {
1062         self.trait_ref.self_ty()
1063     }
1064 }
1065
1066 impl<'tcx> PolyTraitPredicate<'tcx> {
1067     pub fn def_id(&self) -> DefId {
1068         // ok to skip binder since trait def-id does not care about regions
1069         self.0.def_id()
1070     }
1071 }
1072
1073 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
1074 pub struct OutlivesPredicate<A,B>(pub A, pub B); // `A : B`
1075 pub type PolyOutlivesPredicate<A,B> = ty::Binder<OutlivesPredicate<A,B>>;
1076 pub type RegionOutlivesPredicate<'tcx> = OutlivesPredicate<ty::Region<'tcx>,
1077                                                            ty::Region<'tcx>>;
1078 pub type TypeOutlivesPredicate<'tcx> = OutlivesPredicate<Ty<'tcx>,
1079                                                          ty::Region<'tcx>>;
1080 pub type PolyRegionOutlivesPredicate<'tcx> = ty::Binder<RegionOutlivesPredicate<'tcx>>;
1081 pub type PolyTypeOutlivesPredicate<'tcx> = ty::Binder<TypeOutlivesPredicate<'tcx>>;
1082
1083 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
1084 pub struct SubtypePredicate<'tcx> {
1085     pub a_is_expected: bool,
1086     pub a: Ty<'tcx>,
1087     pub b: Ty<'tcx>
1088 }
1089 pub type PolySubtypePredicate<'tcx> = ty::Binder<SubtypePredicate<'tcx>>;
1090
1091 /// This kind of predicate has no *direct* correspondent in the
1092 /// syntax, but it roughly corresponds to the syntactic forms:
1093 ///
1094 /// 1. `T : TraitRef<..., Item=Type>`
1095 /// 2. `<T as TraitRef<...>>::Item == Type` (NYI)
1096 ///
1097 /// In particular, form #1 is "desugared" to the combination of a
1098 /// normal trait predicate (`T : TraitRef<...>`) and one of these
1099 /// predicates. Form #2 is a broader form in that it also permits
1100 /// equality between arbitrary types. Processing an instance of
1101 /// Form #2 eventually yields one of these `ProjectionPredicate`
1102 /// instances to normalize the LHS.
1103 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1104 pub struct ProjectionPredicate<'tcx> {
1105     pub projection_ty: ProjectionTy<'tcx>,
1106     pub ty: Ty<'tcx>,
1107 }
1108
1109 pub type PolyProjectionPredicate<'tcx> = Binder<ProjectionPredicate<'tcx>>;
1110
1111 impl<'tcx> PolyProjectionPredicate<'tcx> {
1112     pub fn to_poly_trait_ref(&self, tcx: TyCtxt) -> PolyTraitRef<'tcx> {
1113         // Note: unlike with TraitRef::to_poly_trait_ref(),
1114         // self.0.trait_ref is permitted to have escaping regions.
1115         // This is because here `self` has a `Binder` and so does our
1116         // return value, so we are preserving the number of binding
1117         // levels.
1118         ty::Binder(self.0.projection_ty.trait_ref(tcx))
1119     }
1120
1121     pub fn ty(&self) -> Binder<Ty<'tcx>> {
1122         Binder(self.skip_binder().ty) // preserves binding levels
1123     }
1124 }
1125
1126 pub trait ToPolyTraitRef<'tcx> {
1127     fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx>;
1128 }
1129
1130 impl<'tcx> ToPolyTraitRef<'tcx> for TraitRef<'tcx> {
1131     fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
1132         assert!(!self.has_escaping_regions());
1133         ty::Binder(self.clone())
1134     }
1135 }
1136
1137 impl<'tcx> ToPolyTraitRef<'tcx> for PolyTraitPredicate<'tcx> {
1138     fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
1139         self.map_bound_ref(|trait_pred| trait_pred.trait_ref)
1140     }
1141 }
1142
1143 pub trait ToPredicate<'tcx> {
1144     fn to_predicate(&self) -> Predicate<'tcx>;
1145 }
1146
1147 impl<'tcx> ToPredicate<'tcx> for TraitRef<'tcx> {
1148     fn to_predicate(&self) -> Predicate<'tcx> {
1149         // we're about to add a binder, so let's check that we don't
1150         // accidentally capture anything, or else that might be some
1151         // weird debruijn accounting.
1152         assert!(!self.has_escaping_regions());
1153
1154         ty::Predicate::Trait(ty::Binder(ty::TraitPredicate {
1155             trait_ref: self.clone()
1156         }))
1157     }
1158 }
1159
1160 impl<'tcx> ToPredicate<'tcx> for PolyTraitRef<'tcx> {
1161     fn to_predicate(&self) -> Predicate<'tcx> {
1162         ty::Predicate::Trait(self.to_poly_trait_predicate())
1163     }
1164 }
1165
1166 impl<'tcx> ToPredicate<'tcx> for PolyRegionOutlivesPredicate<'tcx> {
1167     fn to_predicate(&self) -> Predicate<'tcx> {
1168         Predicate::RegionOutlives(self.clone())
1169     }
1170 }
1171
1172 impl<'tcx> ToPredicate<'tcx> for PolyTypeOutlivesPredicate<'tcx> {
1173     fn to_predicate(&self) -> Predicate<'tcx> {
1174         Predicate::TypeOutlives(self.clone())
1175     }
1176 }
1177
1178 impl<'tcx> ToPredicate<'tcx> for PolyProjectionPredicate<'tcx> {
1179     fn to_predicate(&self) -> Predicate<'tcx> {
1180         Predicate::Projection(self.clone())
1181     }
1182 }
1183
1184 impl<'tcx> Predicate<'tcx> {
1185     /// Iterates over the types in this predicate. Note that in all
1186     /// cases this is skipping over a binder, so late-bound regions
1187     /// with depth 0 are bound by the predicate.
1188     pub fn walk_tys(&self) -> IntoIter<Ty<'tcx>> {
1189         let vec: Vec<_> = match *self {
1190             ty::Predicate::Trait(ref data) => {
1191                 data.skip_binder().input_types().collect()
1192             }
1193             ty::Predicate::Subtype(ty::Binder(SubtypePredicate { a, b, a_is_expected: _ })) => {
1194                 vec![a, b]
1195             }
1196             ty::Predicate::TypeOutlives(ty::Binder(ref data)) => {
1197                 vec![data.0]
1198             }
1199             ty::Predicate::RegionOutlives(..) => {
1200                 vec![]
1201             }
1202             ty::Predicate::Projection(ref data) => {
1203                 data.0.projection_ty.substs.types().chain(Some(data.0.ty)).collect()
1204             }
1205             ty::Predicate::WellFormed(data) => {
1206                 vec![data]
1207             }
1208             ty::Predicate::ObjectSafe(_trait_def_id) => {
1209                 vec![]
1210             }
1211             ty::Predicate::ClosureKind(_closure_def_id, closure_substs, _kind) => {
1212                 closure_substs.substs.types().collect()
1213             }
1214             ty::Predicate::ConstEvaluatable(_, substs) => {
1215                 substs.types().collect()
1216             }
1217         };
1218
1219         // The only reason to collect into a vector here is that I was
1220         // too lazy to make the full (somewhat complicated) iterator
1221         // type that would be needed here. But I wanted this fn to
1222         // return an iterator conceptually, rather than a `Vec`, so as
1223         // to be closer to `Ty::walk`.
1224         vec.into_iter()
1225     }
1226
1227     pub fn to_opt_poly_trait_ref(&self) -> Option<PolyTraitRef<'tcx>> {
1228         match *self {
1229             Predicate::Trait(ref t) => {
1230                 Some(t.to_poly_trait_ref())
1231             }
1232             Predicate::Projection(..) |
1233             Predicate::Subtype(..) |
1234             Predicate::RegionOutlives(..) |
1235             Predicate::WellFormed(..) |
1236             Predicate::ObjectSafe(..) |
1237             Predicate::ClosureKind(..) |
1238             Predicate::TypeOutlives(..) |
1239             Predicate::ConstEvaluatable(..) => {
1240                 None
1241             }
1242         }
1243     }
1244
1245     pub fn to_opt_type_outlives(&self) -> Option<PolyTypeOutlivesPredicate<'tcx>> {
1246         match *self {
1247             Predicate::TypeOutlives(data) => {
1248                 Some(data)
1249             }
1250             Predicate::Trait(..) |
1251             Predicate::Projection(..) |
1252             Predicate::Subtype(..) |
1253             Predicate::RegionOutlives(..) |
1254             Predicate::WellFormed(..) |
1255             Predicate::ObjectSafe(..) |
1256             Predicate::ClosureKind(..) |
1257             Predicate::ConstEvaluatable(..) => {
1258                 None
1259             }
1260         }
1261     }
1262 }
1263
1264 /// Represents the bounds declared on a particular set of type
1265 /// parameters.  Should eventually be generalized into a flag list of
1266 /// where clauses.  You can obtain a `InstantiatedPredicates` list from a
1267 /// `GenericPredicates` by using the `instantiate` method. Note that this method
1268 /// reflects an important semantic invariant of `InstantiatedPredicates`: while
1269 /// the `GenericPredicates` are expressed in terms of the bound type
1270 /// parameters of the impl/trait/whatever, an `InstantiatedPredicates` instance
1271 /// represented a set of bounds for some particular instantiation,
1272 /// meaning that the generic parameters have been substituted with
1273 /// their values.
1274 ///
1275 /// Example:
1276 ///
1277 ///     struct Foo<T,U:Bar<T>> { ... }
1278 ///
1279 /// Here, the `GenericPredicates` for `Foo` would contain a list of bounds like
1280 /// `[[], [U:Bar<T>]]`.  Now if there were some particular reference
1281 /// like `Foo<isize,usize>`, then the `InstantiatedPredicates` would be `[[],
1282 /// [usize:Bar<isize>]]`.
1283 #[derive(Clone)]
1284 pub struct InstantiatedPredicates<'tcx> {
1285     pub predicates: Vec<Predicate<'tcx>>,
1286 }
1287
1288 impl<'tcx> InstantiatedPredicates<'tcx> {
1289     pub fn empty() -> InstantiatedPredicates<'tcx> {
1290         InstantiatedPredicates { predicates: vec![] }
1291     }
1292
1293     pub fn is_empty(&self) -> bool {
1294         self.predicates.is_empty()
1295     }
1296 }
1297
1298 /// "Universes" are used during type- and trait-checking in the
1299 /// presence of `for<..>` binders to control what sets of names are
1300 /// visible. Universes are arranged into a tree: the root universe
1301 /// contains names that are always visible. But when you enter into
1302 /// some subuniverse, then it may add names that are only visible
1303 /// within that subtree (but it can still name the names of its
1304 /// ancestor universes).
1305 ///
1306 /// To make this more concrete, consider this program:
1307 ///
1308 /// ```
1309 /// struct Foo { }
1310 /// fn bar<T>(x: T) {
1311 ///   let y: for<'a> fn(&'a u8, Foo) = ...;
1312 /// }
1313 /// ```
1314 ///
1315 /// The struct name `Foo` is in the root universe U0. But the type
1316 /// parameter `T`, introduced on `bar`, is in a subuniverse U1 --
1317 /// i.e., within `bar`, we can name both `T` and `Foo`, but outside of
1318 /// `bar`, we cannot name `T`. Then, within the type of `y`, the
1319 /// region `'a` is in a subuniverse U2 of U1, because we can name it
1320 /// inside the fn type but not outside.
1321 ///
1322 /// Universes are related to **skolemization** -- which is a way of
1323 /// doing type- and trait-checking around these "forall" binders (also
1324 /// called **universal quantification**). The idea is that when, in
1325 /// the body of `bar`, we refer to `T` as a type, we aren't referring
1326 /// to any type in particular, but rather a kind of "fresh" type that
1327 /// is distinct from all other types we have actually declared. This
1328 /// is called a **skolemized** type, and we use universes to talk
1329 /// about this. In other words, a type name in universe 0 always
1330 /// corresponds to some "ground" type that the user declared, but a
1331 /// type name in a non-zero universe is a skolemized type -- an
1332 /// idealized representative of "types in general" that we use for
1333 /// checking generic functions.
1334 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
1335 pub struct UniverseIndex(u32);
1336
1337 impl UniverseIndex {
1338     /// The root universe, where things that the user defined are
1339     /// visible.
1340     pub const ROOT: UniverseIndex = UniverseIndex(0);
1341
1342     /// A "subuniverse" corresponds to being inside a `forall` quantifier.
1343     /// So, for example, suppose we have this type in universe `U`:
1344     ///
1345     /// ```
1346     /// for<'a> fn(&'a u32)
1347     /// ```
1348     ///
1349     /// Once we "enter" into this `for<'a>` quantifier, we are in a
1350     /// subuniverse of `U` -- in this new universe, we can name the
1351     /// region `'a`, but that region was not nameable from `U` because
1352     /// it was not in scope there.
1353     pub fn subuniverse(self) -> UniverseIndex {
1354         UniverseIndex(self.0.checked_add(1).unwrap())
1355     }
1356
1357     pub fn from(v: u32) -> UniverseIndex {
1358         UniverseIndex(v)
1359     }
1360
1361     pub fn as_u32(&self) -> u32 {
1362         self.0
1363     }
1364
1365     pub fn as_usize(&self) -> usize {
1366         self.0 as usize
1367     }
1368
1369     /// Gets the "depth" of this universe in the universe tree. This
1370     /// is not really useful except for e.g. the `HashStable`
1371     /// implementation
1372     pub fn depth(&self) -> u32 {
1373         self.0
1374     }
1375 }
1376
1377 /// When type checking, we use the `ParamEnv` to track
1378 /// details about the set of where-clauses that are in scope at this
1379 /// particular point.
1380 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1381 pub struct ParamEnv<'tcx> {
1382     /// Obligations that the caller must satisfy. This is basically
1383     /// the set of bounds on the in-scope type parameters, translated
1384     /// into Obligations, and elaborated and normalized.
1385     pub caller_bounds: &'tcx Slice<ty::Predicate<'tcx>>,
1386
1387     /// Typically, this is `Reveal::UserFacing`, but during trans we
1388     /// want `Reveal::All` -- note that this is always paired with an
1389     /// empty environment. To get that, use `ParamEnv::reveal()`.
1390     pub reveal: traits::Reveal,
1391
1392     /// What is the innermost universe we have created? Starts out as
1393     /// `UniverseIndex::root()` but grows from there as we enter
1394     /// universal quantifiers.
1395     ///
1396     /// NB: At present, we exclude the universal quantifiers on the
1397     /// item we are type-checking, and just consider those names as
1398     /// part of the root universe. So this would only get incremented
1399     /// when we enter into a higher-ranked (`for<..>`) type or trait
1400     /// bound.
1401     pub universe: UniverseIndex,
1402 }
1403
1404 impl<'tcx> ParamEnv<'tcx> {
1405     /// Construct a trait environment suitable for contexts where
1406     /// there are no where clauses in scope. Hidden types (like `impl
1407     /// Trait`) are left hidden, so this is suitable for ordinary
1408     /// type-checking.
1409     pub fn empty() -> Self {
1410         Self::new(ty::Slice::empty(), Reveal::UserFacing, ty::UniverseIndex::ROOT)
1411     }
1412
1413     /// Construct a trait environment with no where clauses in scope
1414     /// where the values of all `impl Trait` and other hidden types
1415     /// are revealed. This is suitable for monomorphized, post-typeck
1416     /// environments like trans or doing optimizations.
1417     ///
1418     /// NB. If you want to have predicates in scope, use `ParamEnv::new`,
1419     /// or invoke `param_env.with_reveal_all()`.
1420     pub fn reveal_all() -> Self {
1421         Self::new(ty::Slice::empty(), Reveal::All, ty::UniverseIndex::ROOT)
1422     }
1423
1424     /// Construct a trait environment with the given set of predicates.
1425     pub fn new(caller_bounds: &'tcx ty::Slice<ty::Predicate<'tcx>>,
1426                reveal: Reveal,
1427                universe: ty::UniverseIndex)
1428                -> Self {
1429         ty::ParamEnv { caller_bounds, reveal, universe }
1430     }
1431
1432     /// Returns a new parameter environment with the same clauses, but
1433     /// which "reveals" the true results of projections in all cases
1434     /// (even for associated types that are specializable).  This is
1435     /// the desired behavior during trans and certain other special
1436     /// contexts; normally though we want to use `Reveal::UserFacing`,
1437     /// which is the default.
1438     pub fn with_reveal_all(self) -> Self {
1439         ty::ParamEnv { reveal: Reveal::All, ..self }
1440     }
1441
1442     /// Returns this same environment but with no caller bounds.
1443     pub fn without_caller_bounds(self) -> Self {
1444         ty::ParamEnv { caller_bounds: ty::Slice::empty(), ..self }
1445     }
1446
1447     /// Creates a suitable environment in which to perform trait
1448     /// queries on the given value. When type-checking, this is simply
1449     /// the pair of the environment plus value. But when reveal is set to
1450     /// All, then if `value` does not reference any type parameters, we will
1451     /// pair it with the empty environment. This improves caching and is generally
1452     /// invisible.
1453     ///
1454     /// NB: We preserve the environment when type-checking because it
1455     /// is possible for the user to have wacky where-clauses like
1456     /// `where Box<u32>: Copy`, which are clearly never
1457     /// satisfiable. We generally want to behave as if they were true,
1458     /// although the surrounding function is never reachable.
1459     pub fn and<T: TypeFoldable<'tcx>>(self, value: T) -> ParamEnvAnd<'tcx, T> {
1460         match self.reveal {
1461             Reveal::UserFacing => {
1462                 ParamEnvAnd {
1463                     param_env: self,
1464                     value,
1465                 }
1466             }
1467
1468             Reveal::All => {
1469                 if value.needs_infer() || value.has_param_types() || value.has_self_ty() {
1470                     ParamEnvAnd {
1471                         param_env: self,
1472                         value,
1473                     }
1474                 } else {
1475                     ParamEnvAnd {
1476                         param_env: self.without_caller_bounds(),
1477                         value,
1478                     }
1479                 }
1480             }
1481         }
1482     }
1483 }
1484
1485 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1486 pub struct ParamEnvAnd<'tcx, T> {
1487     pub param_env: ParamEnv<'tcx>,
1488     pub value: T,
1489 }
1490
1491 impl<'tcx, T> ParamEnvAnd<'tcx, T> {
1492     pub fn into_parts(self) -> (ParamEnv<'tcx>, T) {
1493         (self.param_env, self.value)
1494     }
1495 }
1496
1497 impl<'a, 'gcx, T> HashStable<StableHashingContext<'a>> for ParamEnvAnd<'gcx, T>
1498     where T: HashStable<StableHashingContext<'a>>
1499 {
1500     fn hash_stable<W: StableHasherResult>(&self,
1501                                           hcx: &mut StableHashingContext<'a>,
1502                                           hasher: &mut StableHasher<W>) {
1503         let ParamEnvAnd {
1504             ref param_env,
1505             ref value
1506         } = *self;
1507
1508         param_env.hash_stable(hcx, hasher);
1509         value.hash_stable(hcx, hasher);
1510     }
1511 }
1512
1513 #[derive(Copy, Clone, Debug)]
1514 pub struct Destructor {
1515     /// The def-id of the destructor method
1516     pub did: DefId,
1517 }
1518
1519 bitflags! {
1520     pub struct AdtFlags: u32 {
1521         const NO_ADT_FLAGS        = 0;
1522         const IS_ENUM             = 1 << 0;
1523         const IS_PHANTOM_DATA     = 1 << 1;
1524         const IS_FUNDAMENTAL      = 1 << 2;
1525         const IS_UNION            = 1 << 3;
1526         const IS_BOX              = 1 << 4;
1527         /// Indicates whether this abstract data type will be expanded on in future (new
1528         /// fields/variants) and as such, whether downstream crates must match exhaustively on the
1529         /// fields/variants of this data type.
1530         ///
1531         /// See RFC 2008 (<https://github.com/rust-lang/rfcs/pull/2008>).
1532         const IS_NON_EXHAUSTIVE   = 1 << 5;
1533     }
1534 }
1535
1536 #[derive(Debug)]
1537 pub struct VariantDef {
1538     /// The variant's DefId. If this is a tuple-like struct,
1539     /// this is the DefId of the struct's ctor.
1540     pub did: DefId,
1541     pub name: Name, // struct's name if this is a struct
1542     pub discr: VariantDiscr,
1543     pub fields: Vec<FieldDef>,
1544     pub ctor_kind: CtorKind,
1545 }
1546
1547 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
1548 pub enum VariantDiscr {
1549     /// Explicit value for this variant, i.e. `X = 123`.
1550     /// The `DefId` corresponds to the embedded constant.
1551     Explicit(DefId),
1552
1553     /// The previous variant's discriminant plus one.
1554     /// For efficiency reasons, the distance from the
1555     /// last `Explicit` discriminant is being stored,
1556     /// or `0` for the first variant, if it has none.
1557     Relative(usize),
1558 }
1559
1560 #[derive(Debug)]
1561 pub struct FieldDef {
1562     pub did: DefId,
1563     pub name: Name,
1564     pub vis: Visibility,
1565 }
1566
1567 /// The definition of an abstract data type - a struct or enum.
1568 ///
1569 /// These are all interned (by intern_adt_def) into the adt_defs
1570 /// table.
1571 pub struct AdtDef {
1572     pub did: DefId,
1573     pub variants: Vec<VariantDef>,
1574     flags: AdtFlags,
1575     pub repr: ReprOptions,
1576 }
1577
1578 impl PartialEq for AdtDef {
1579     // AdtDef are always interned and this is part of TyS equality
1580     #[inline]
1581     fn eq(&self, other: &Self) -> bool { self as *const _ == other as *const _ }
1582 }
1583
1584 impl Eq for AdtDef {}
1585
1586 impl Hash for AdtDef {
1587     #[inline]
1588     fn hash<H: Hasher>(&self, s: &mut H) {
1589         (self as *const AdtDef).hash(s)
1590     }
1591 }
1592
1593 impl<'tcx> serialize::UseSpecializedEncodable for &'tcx AdtDef {
1594     fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1595         self.did.encode(s)
1596     }
1597 }
1598
1599 impl<'tcx> serialize::UseSpecializedDecodable for &'tcx AdtDef {}
1600
1601
1602 impl<'a> HashStable<StableHashingContext<'a>> for AdtDef {
1603     fn hash_stable<W: StableHasherResult>(&self,
1604                                           hcx: &mut StableHashingContext<'a>,
1605                                           hasher: &mut StableHasher<W>) {
1606         thread_local! {
1607             static CACHE: RefCell<FxHashMap<usize, Fingerprint>> =
1608                 RefCell::new(FxHashMap());
1609         }
1610
1611         let hash: Fingerprint = CACHE.with(|cache| {
1612             let addr = self as *const AdtDef as usize;
1613             *cache.borrow_mut().entry(addr).or_insert_with(|| {
1614                 let ty::AdtDef {
1615                     did,
1616                     ref variants,
1617                     ref flags,
1618                     ref repr,
1619                 } = *self;
1620
1621                 let mut hasher = StableHasher::new();
1622                 did.hash_stable(hcx, &mut hasher);
1623                 variants.hash_stable(hcx, &mut hasher);
1624                 flags.hash_stable(hcx, &mut hasher);
1625                 repr.hash_stable(hcx, &mut hasher);
1626
1627                 hasher.finish()
1628            })
1629         });
1630
1631         hash.hash_stable(hcx, hasher);
1632     }
1633 }
1634
1635 #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
1636 pub enum AdtKind { Struct, Union, Enum }
1637
1638 bitflags! {
1639     #[derive(RustcEncodable, RustcDecodable, Default)]
1640     pub struct ReprFlags: u8 {
1641         const IS_C               = 1 << 0;
1642         const IS_PACKED          = 1 << 1;
1643         const IS_SIMD            = 1 << 2;
1644         const IS_TRANSPARENT     = 1 << 3;
1645         // Internal only for now. If true, don't reorder fields.
1646         const IS_LINEAR          = 1 << 4;
1647
1648         // Any of these flags being set prevent field reordering optimisation.
1649         const IS_UNOPTIMISABLE   = ReprFlags::IS_C.bits |
1650                                    ReprFlags::IS_PACKED.bits |
1651                                    ReprFlags::IS_SIMD.bits |
1652                                    ReprFlags::IS_LINEAR.bits;
1653     }
1654 }
1655
1656 impl_stable_hash_for!(struct ReprFlags {
1657     bits
1658 });
1659
1660
1661
1662 /// Represents the repr options provided by the user,
1663 #[derive(Copy, Clone, Eq, PartialEq, RustcEncodable, RustcDecodable, Default)]
1664 pub struct ReprOptions {
1665     pub int: Option<attr::IntType>,
1666     pub align: u32,
1667     pub flags: ReprFlags,
1668 }
1669
1670 impl_stable_hash_for!(struct ReprOptions {
1671     align,
1672     int,
1673     flags
1674 });
1675
1676 impl ReprOptions {
1677     pub fn new(tcx: TyCtxt, did: DefId) -> ReprOptions {
1678         let mut flags = ReprFlags::empty();
1679         let mut size = None;
1680         let mut max_align = 0;
1681         for attr in tcx.get_attrs(did).iter() {
1682             for r in attr::find_repr_attrs(tcx.sess.diagnostic(), attr) {
1683                 flags.insert(match r {
1684                     attr::ReprC => ReprFlags::IS_C,
1685                     attr::ReprPacked => ReprFlags::IS_PACKED,
1686                     attr::ReprTransparent => ReprFlags::IS_TRANSPARENT,
1687                     attr::ReprSimd => ReprFlags::IS_SIMD,
1688                     attr::ReprInt(i) => {
1689                         size = Some(i);
1690                         ReprFlags::empty()
1691                     },
1692                     attr::ReprAlign(align) => {
1693                         max_align = cmp::max(align, max_align);
1694                         ReprFlags::empty()
1695                     },
1696                 });
1697             }
1698         }
1699
1700         // This is here instead of layout because the choice must make it into metadata.
1701         if !tcx.consider_optimizing(|| format!("Reorder fields of {:?}", tcx.item_path_str(did))) {
1702             flags.insert(ReprFlags::IS_LINEAR);
1703         }
1704         ReprOptions { int: size, align: max_align, flags: flags }
1705     }
1706
1707     #[inline]
1708     pub fn simd(&self) -> bool { self.flags.contains(ReprFlags::IS_SIMD) }
1709     #[inline]
1710     pub fn c(&self) -> bool { self.flags.contains(ReprFlags::IS_C) }
1711     #[inline]
1712     pub fn packed(&self) -> bool { self.flags.contains(ReprFlags::IS_PACKED) }
1713     #[inline]
1714     pub fn transparent(&self) -> bool { self.flags.contains(ReprFlags::IS_TRANSPARENT) }
1715     #[inline]
1716     pub fn linear(&self) -> bool { self.flags.contains(ReprFlags::IS_LINEAR) }
1717
1718     pub fn discr_type(&self) -> attr::IntType {
1719         self.int.unwrap_or(attr::SignedInt(ast::IntTy::Isize))
1720     }
1721
1722     /// Returns true if this `#[repr()]` should inhabit "smart enum
1723     /// layout" optimizations, such as representing `Foo<&T>` as a
1724     /// single pointer.
1725     pub fn inhibit_enum_layout_opt(&self) -> bool {
1726         self.c() || self.int.is_some()
1727     }
1728 }
1729
1730 impl<'a, 'gcx, 'tcx> AdtDef {
1731     fn new(tcx: TyCtxt,
1732            did: DefId,
1733            kind: AdtKind,
1734            variants: Vec<VariantDef>,
1735            repr: ReprOptions) -> Self {
1736         let mut flags = AdtFlags::NO_ADT_FLAGS;
1737         let attrs = tcx.get_attrs(did);
1738         if attr::contains_name(&attrs, "fundamental") {
1739             flags = flags | AdtFlags::IS_FUNDAMENTAL;
1740         }
1741         if Some(did) == tcx.lang_items().phantom_data() {
1742             flags = flags | AdtFlags::IS_PHANTOM_DATA;
1743         }
1744         if Some(did) == tcx.lang_items().owned_box() {
1745             flags = flags | AdtFlags::IS_BOX;
1746         }
1747         if tcx.has_attr(did, "non_exhaustive") {
1748             flags = flags | AdtFlags::IS_NON_EXHAUSTIVE;
1749         }
1750         match kind {
1751             AdtKind::Enum => flags = flags | AdtFlags::IS_ENUM,
1752             AdtKind::Union => flags = flags | AdtFlags::IS_UNION,
1753             AdtKind::Struct => {}
1754         }
1755         AdtDef {
1756             did,
1757             variants,
1758             flags,
1759             repr,
1760         }
1761     }
1762
1763     #[inline]
1764     pub fn is_struct(&self) -> bool {
1765         !self.is_union() && !self.is_enum()
1766     }
1767
1768     #[inline]
1769     pub fn is_union(&self) -> bool {
1770         self.flags.intersects(AdtFlags::IS_UNION)
1771     }
1772
1773     #[inline]
1774     pub fn is_enum(&self) -> bool {
1775         self.flags.intersects(AdtFlags::IS_ENUM)
1776     }
1777
1778     #[inline]
1779     pub fn is_non_exhaustive(&self) -> bool {
1780         self.flags.intersects(AdtFlags::IS_NON_EXHAUSTIVE)
1781     }
1782
1783     /// Returns the kind of the ADT - Struct or Enum.
1784     #[inline]
1785     pub fn adt_kind(&self) -> AdtKind {
1786         if self.is_enum() {
1787             AdtKind::Enum
1788         } else if self.is_union() {
1789             AdtKind::Union
1790         } else {
1791             AdtKind::Struct
1792         }
1793     }
1794
1795     pub fn descr(&self) -> &'static str {
1796         match self.adt_kind() {
1797             AdtKind::Struct => "struct",
1798             AdtKind::Union => "union",
1799             AdtKind::Enum => "enum",
1800         }
1801     }
1802
1803     pub fn variant_descr(&self) -> &'static str {
1804         match self.adt_kind() {
1805             AdtKind::Struct => "struct",
1806             AdtKind::Union => "union",
1807             AdtKind::Enum => "variant",
1808         }
1809     }
1810
1811     /// Returns whether this type is #[fundamental] for the purposes
1812     /// of coherence checking.
1813     #[inline]
1814     pub fn is_fundamental(&self) -> bool {
1815         self.flags.intersects(AdtFlags::IS_FUNDAMENTAL)
1816     }
1817
1818     /// Returns true if this is PhantomData<T>.
1819     #[inline]
1820     pub fn is_phantom_data(&self) -> bool {
1821         self.flags.intersects(AdtFlags::IS_PHANTOM_DATA)
1822     }
1823
1824     /// Returns true if this is Box<T>.
1825     #[inline]
1826     pub fn is_box(&self) -> bool {
1827         self.flags.intersects(AdtFlags::IS_BOX)
1828     }
1829
1830     /// Returns whether this type has a destructor.
1831     pub fn has_dtor(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> bool {
1832         self.destructor(tcx).is_some()
1833     }
1834
1835     /// Asserts this is a struct or union and returns its unique variant.
1836     pub fn non_enum_variant(&self) -> &VariantDef {
1837         assert!(self.is_struct() || self.is_union());
1838         &self.variants[0]
1839     }
1840
1841     #[inline]
1842     pub fn predicates(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> GenericPredicates<'gcx> {
1843         tcx.predicates_of(self.did)
1844     }
1845
1846     /// Returns an iterator over all fields contained
1847     /// by this ADT.
1848     #[inline]
1849     pub fn all_fields<'s>(&'s self) -> impl Iterator<Item = &'s FieldDef> {
1850         self.variants.iter().flat_map(|v| v.fields.iter())
1851     }
1852
1853     pub fn is_payloadfree(&self) -> bool {
1854         !self.variants.is_empty() &&
1855             self.variants.iter().all(|v| v.fields.is_empty())
1856     }
1857
1858     pub fn variant_with_id(&self, vid: DefId) -> &VariantDef {
1859         self.variants
1860             .iter()
1861             .find(|v| v.did == vid)
1862             .expect("variant_with_id: unknown variant")
1863     }
1864
1865     pub fn variant_index_with_id(&self, vid: DefId) -> usize {
1866         self.variants
1867             .iter()
1868             .position(|v| v.did == vid)
1869             .expect("variant_index_with_id: unknown variant")
1870     }
1871
1872     pub fn variant_of_def(&self, def: Def) -> &VariantDef {
1873         match def {
1874             Def::Variant(vid) | Def::VariantCtor(vid, ..) => self.variant_with_id(vid),
1875             Def::Struct(..) | Def::StructCtor(..) | Def::Union(..) |
1876             Def::TyAlias(..) | Def::AssociatedTy(..) | Def::SelfTy(..) => self.non_enum_variant(),
1877             _ => bug!("unexpected def {:?} in variant_of_def", def)
1878         }
1879     }
1880
1881     #[inline]
1882     pub fn eval_explicit_discr(
1883         &self,
1884         tcx: TyCtxt<'a, 'gcx, 'tcx>,
1885         expr_did: DefId,
1886     ) -> Option<Discr<'tcx>> {
1887         let param_env = ParamEnv::empty();
1888         let repr_type = self.repr.discr_type();
1889         let bit_size = layout::Integer::from_attr(tcx, repr_type).size().bits();
1890         let substs = Substs::identity_for_item(tcx.global_tcx(), expr_did);
1891         let instance = ty::Instance::new(expr_did, substs);
1892         let cid = GlobalId {
1893             instance,
1894             promoted: None
1895         };
1896         match tcx.const_eval(param_env.and(cid)) {
1897             Ok(&ty::Const {
1898                 val: ConstVal::Value(Value::ByVal(PrimVal::Bytes(b))),
1899                 ..
1900             }) => {
1901                 trace!("discriminants: {} ({:?})", b, repr_type);
1902                 let ty = repr_type.to_ty(tcx);
1903                 if repr_type.is_signed() {
1904                     let val = b as i128;
1905                     // sign extend to i128
1906                     let amt = 128 - bit_size;
1907                     let val = (val << amt) >> amt;
1908                     Some(Discr {
1909                         val: val as u128,
1910                         ty,
1911                     })
1912                 } else {
1913                     Some(Discr {
1914                         val: b,
1915                         ty,
1916                     })
1917                 }
1918             },
1919             Ok(&ty::Const {
1920                 val: ConstVal::Value(other),
1921                 ..
1922             }) => {
1923                 info!("invalid enum discriminant: {:#?}", other);
1924                 ::middle::const_val::struct_error(
1925                     tcx,
1926                     tcx.def_span(expr_did),
1927                     "constant evaluation of enum discriminant resulted in non-integer",
1928                 ).emit();
1929                 None
1930             }
1931             Err(err) => {
1932                 err.report(tcx, tcx.def_span(expr_did), "enum discriminant");
1933                 if !expr_did.is_local() {
1934                     span_bug!(tcx.def_span(expr_did),
1935                         "variant discriminant evaluation succeeded \
1936                             in its crate but failed locally");
1937                 }
1938                 None
1939             }
1940             _ => span_bug!(tcx.def_span(expr_did), "const eval "),
1941         }
1942     }
1943
1944     #[inline]
1945     pub fn discriminants(&'a self, tcx: TyCtxt<'a, 'gcx, 'tcx>)
1946                          -> impl Iterator<Item=Discr<'tcx>> + 'a {
1947         let repr_type = self.repr.discr_type();
1948         let initial = repr_type.initial_discriminant(tcx.global_tcx());
1949         let mut prev_discr = None::<Discr<'tcx>>;
1950         self.variants.iter().map(move |v| {
1951             let mut discr = prev_discr.map_or(initial, |d| d.wrap_incr(tcx));
1952             if let VariantDiscr::Explicit(expr_did) = v.discr {
1953                 if let Some(new_discr) = self.eval_explicit_discr(tcx, expr_did) {
1954                     discr = new_discr;
1955                 }
1956             }
1957             prev_discr = Some(discr);
1958
1959             discr
1960         })
1961     }
1962
1963     /// Compute the discriminant value used by a specific variant.
1964     /// Unlike `discriminants`, this is (amortized) constant-time,
1965     /// only doing at most one query for evaluating an explicit
1966     /// discriminant (the last one before the requested variant),
1967     /// assuming there are no constant-evaluation errors there.
1968     pub fn discriminant_for_variant(&self,
1969                                     tcx: TyCtxt<'a, 'gcx, 'tcx>,
1970                                     variant_index: usize)
1971                                     -> Discr<'tcx> {
1972         let repr_type = self.repr.discr_type();
1973         let mut explicit_value = repr_type.initial_discriminant(tcx.global_tcx());
1974         let mut explicit_index = variant_index;
1975         loop {
1976             match self.variants[explicit_index].discr {
1977                 ty::VariantDiscr::Relative(0) => break,
1978                 ty::VariantDiscr::Relative(distance) => {
1979                     explicit_index -= distance;
1980                 }
1981                 ty::VariantDiscr::Explicit(expr_did) => {
1982                     match self.eval_explicit_discr(tcx, expr_did) {
1983                         Some(discr) => {
1984                             explicit_value = discr;
1985                             break;
1986                         },
1987                         None => {
1988                             if explicit_index == 0 {
1989                                 break;
1990                             }
1991                             explicit_index -= 1;
1992                         }
1993                     }
1994                 }
1995             }
1996         }
1997         explicit_value.checked_add(tcx, (variant_index - explicit_index) as u128).0
1998     }
1999
2000     pub fn destructor(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Option<Destructor> {
2001         tcx.adt_destructor(self.did)
2002     }
2003
2004     /// Returns a list of types such that `Self: Sized` if and only
2005     /// if that type is Sized, or `TyErr` if this type is recursive.
2006     ///
2007     /// Oddly enough, checking that the sized-constraint is Sized is
2008     /// actually more expressive than checking all members:
2009     /// the Sized trait is inductive, so an associated type that references
2010     /// Self would prevent its containing ADT from being Sized.
2011     ///
2012     /// Due to normalization being eager, this applies even if
2013     /// the associated type is behind a pointer, e.g. issue #31299.
2014     pub fn sized_constraint(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> &'tcx [Ty<'tcx>] {
2015         match queries::adt_sized_constraint::try_get(tcx, DUMMY_SP, self.did) {
2016             Ok(tys) => tys,
2017             Err(mut bug) => {
2018                 debug!("adt_sized_constraint: {:?} is recursive", self);
2019                 // This should be reported as an error by `check_representable`.
2020                 //
2021                 // Consider the type as Sized in the meanwhile to avoid
2022                 // further errors. Delay our `bug` diagnostic here to get
2023                 // emitted later as well in case we accidentally otherwise don't
2024                 // emit an error.
2025                 bug.delay_as_bug();
2026                 tcx.intern_type_list(&[tcx.types.err])
2027             }
2028         }
2029     }
2030
2031     fn sized_constraint_for_ty(&self,
2032                                tcx: TyCtxt<'a, 'tcx, 'tcx>,
2033                                ty: Ty<'tcx>)
2034                                -> Vec<Ty<'tcx>> {
2035         let result = match ty.sty {
2036             TyBool | TyChar | TyInt(..) | TyUint(..) | TyFloat(..) |
2037             TyRawPtr(..) | TyRef(..) | TyFnDef(..) | TyFnPtr(_) |
2038             TyArray(..) | TyClosure(..) | TyGenerator(..) | TyNever => {
2039                 vec![]
2040             }
2041
2042             TyStr |
2043             TyDynamic(..) |
2044             TySlice(_) |
2045             TyForeign(..) |
2046             TyError |
2047             TyGeneratorWitness(..) => {
2048                 // these are never sized - return the target type
2049                 vec![ty]
2050             }
2051
2052             TyTuple(ref tys) => {
2053                 match tys.last() {
2054                     None => vec![],
2055                     Some(ty) => self.sized_constraint_for_ty(tcx, ty)
2056                 }
2057             }
2058
2059             TyAdt(adt, substs) => {
2060                 // recursive case
2061                 let adt_tys = adt.sized_constraint(tcx);
2062                 debug!("sized_constraint_for_ty({:?}) intermediate = {:?}",
2063                        ty, adt_tys);
2064                 adt_tys.iter()
2065                     .map(|ty| ty.subst(tcx, substs))
2066                     .flat_map(|ty| self.sized_constraint_for_ty(tcx, ty))
2067                     .collect()
2068             }
2069
2070             TyProjection(..) | TyAnon(..) => {
2071                 // must calculate explicitly.
2072                 // FIXME: consider special-casing always-Sized projections
2073                 vec![ty]
2074             }
2075
2076             TyParam(..) => {
2077                 // perf hack: if there is a `T: Sized` bound, then
2078                 // we know that `T` is Sized and do not need to check
2079                 // it on the impl.
2080
2081                 let sized_trait = match tcx.lang_items().sized_trait() {
2082                     Some(x) => x,
2083                     _ => return vec![ty]
2084                 };
2085                 let sized_predicate = Binder(TraitRef {
2086                     def_id: sized_trait,
2087                     substs: tcx.mk_substs_trait(ty, &[])
2088                 }).to_predicate();
2089                 let predicates = tcx.predicates_of(self.did).predicates;
2090                 if predicates.into_iter().any(|p| p == sized_predicate) {
2091                     vec![]
2092                 } else {
2093                     vec![ty]
2094                 }
2095             }
2096
2097             TyInfer(..) => {
2098                 bug!("unexpected type `{:?}` in sized_constraint_for_ty",
2099                      ty)
2100             }
2101         };
2102         debug!("sized_constraint_for_ty({:?}) = {:?}", ty, result);
2103         result
2104     }
2105 }
2106
2107 impl<'a, 'gcx, 'tcx> VariantDef {
2108     #[inline]
2109     pub fn find_field_named(&self, name: ast::Name) -> Option<&FieldDef> {
2110         self.index_of_field_named(name).map(|index| &self.fields[index])
2111     }
2112
2113     pub fn index_of_field_named(&self, name: ast::Name) -> Option<usize> {
2114         if let Some(index) = self.fields.iter().position(|f| f.name == name) {
2115             return Some(index);
2116         }
2117         let mut ident = name.to_ident();
2118         while ident.ctxt != SyntaxContext::empty() {
2119             ident.ctxt.remove_mark();
2120             if let Some(field) = self.fields.iter().position(|f| f.name.to_ident() == ident) {
2121                 return Some(field);
2122             }
2123         }
2124         None
2125     }
2126
2127     #[inline]
2128     pub fn field_named(&self, name: ast::Name) -> &FieldDef {
2129         self.find_field_named(name).unwrap()
2130     }
2131 }
2132
2133 impl<'a, 'gcx, 'tcx> FieldDef {
2134     pub fn ty(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, subst: &Substs<'tcx>) -> Ty<'tcx> {
2135         tcx.type_of(self.did).subst(tcx, subst)
2136     }
2137 }
2138
2139 /// Represents the various closure traits in the Rust language. This
2140 /// will determine the type of the environment (`self`, in the
2141 /// desuaring) argument that the closure expects.
2142 ///
2143 /// You can get the environment type of a closure using
2144 /// `tcx.closure_env_ty()`.
2145 #[derive(Clone, Copy, PartialOrd, Ord, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
2146 pub enum ClosureKind {
2147     // Warning: Ordering is significant here! The ordering is chosen
2148     // because the trait Fn is a subtrait of FnMut and so in turn, and
2149     // hence we order it so that Fn < FnMut < FnOnce.
2150     Fn,
2151     FnMut,
2152     FnOnce,
2153 }
2154
2155 impl<'a, 'tcx> ClosureKind {
2156     // This is the initial value used when doing upvar inference.
2157     pub const LATTICE_BOTTOM: ClosureKind = ClosureKind::Fn;
2158
2159     pub fn trait_did(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> DefId {
2160         match *self {
2161             ClosureKind::Fn => tcx.require_lang_item(FnTraitLangItem),
2162             ClosureKind::FnMut => {
2163                 tcx.require_lang_item(FnMutTraitLangItem)
2164             }
2165             ClosureKind::FnOnce => {
2166                 tcx.require_lang_item(FnOnceTraitLangItem)
2167             }
2168         }
2169     }
2170
2171     /// True if this a type that impls this closure kind
2172     /// must also implement `other`.
2173     pub fn extends(self, other: ty::ClosureKind) -> bool {
2174         match (self, other) {
2175             (ClosureKind::Fn, ClosureKind::Fn) => true,
2176             (ClosureKind::Fn, ClosureKind::FnMut) => true,
2177             (ClosureKind::Fn, ClosureKind::FnOnce) => true,
2178             (ClosureKind::FnMut, ClosureKind::FnMut) => true,
2179             (ClosureKind::FnMut, ClosureKind::FnOnce) => true,
2180             (ClosureKind::FnOnce, ClosureKind::FnOnce) => true,
2181             _ => false,
2182         }
2183     }
2184
2185     /// Returns the representative scalar type for this closure kind.
2186     /// See `TyS::to_opt_closure_kind` for more details.
2187     pub fn to_ty(self, tcx: TyCtxt<'_, '_, 'tcx>) -> Ty<'tcx> {
2188         match self {
2189             ty::ClosureKind::Fn => tcx.types.i8,
2190             ty::ClosureKind::FnMut => tcx.types.i16,
2191             ty::ClosureKind::FnOnce => tcx.types.i32,
2192         }
2193     }
2194 }
2195
2196 impl<'tcx> TyS<'tcx> {
2197     /// Iterator that walks `self` and any types reachable from
2198     /// `self`, in depth-first order. Note that just walks the types
2199     /// that appear in `self`, it does not descend into the fields of
2200     /// structs or variants. For example:
2201     ///
2202     /// ```notrust
2203     /// isize => { isize }
2204     /// Foo<Bar<isize>> => { Foo<Bar<isize>>, Bar<isize>, isize }
2205     /// [isize] => { [isize], isize }
2206     /// ```
2207     pub fn walk(&'tcx self) -> TypeWalker<'tcx> {
2208         TypeWalker::new(self)
2209     }
2210
2211     /// Iterator that walks the immediate children of `self`.  Hence
2212     /// `Foo<Bar<i32>, u32>` yields the sequence `[Bar<i32>, u32]`
2213     /// (but not `i32`, like `walk`).
2214     pub fn walk_shallow(&'tcx self) -> AccIntoIter<walk::TypeWalkerArray<'tcx>> {
2215         walk::walk_shallow(self)
2216     }
2217
2218     /// Walks `ty` and any types appearing within `ty`, invoking the
2219     /// callback `f` on each type. If the callback returns false, then the
2220     /// children of the current type are ignored.
2221     ///
2222     /// Note: prefer `ty.walk()` where possible.
2223     pub fn maybe_walk<F>(&'tcx self, mut f: F)
2224         where F : FnMut(Ty<'tcx>) -> bool
2225     {
2226         let mut walker = self.walk();
2227         while let Some(ty) = walker.next() {
2228             if !f(ty) {
2229                 walker.skip_current_subtree();
2230             }
2231         }
2232     }
2233 }
2234
2235 impl BorrowKind {
2236     pub fn from_mutbl(m: hir::Mutability) -> BorrowKind {
2237         match m {
2238             hir::MutMutable => MutBorrow,
2239             hir::MutImmutable => ImmBorrow,
2240         }
2241     }
2242
2243     /// Returns a mutability `m` such that an `&m T` pointer could be used to obtain this borrow
2244     /// kind. Because borrow kinds are richer than mutabilities, we sometimes have to pick a
2245     /// mutability that is stronger than necessary so that it at least *would permit* the borrow in
2246     /// question.
2247     pub fn to_mutbl_lossy(self) -> hir::Mutability {
2248         match self {
2249             MutBorrow => hir::MutMutable,
2250             ImmBorrow => hir::MutImmutable,
2251
2252             // We have no type corresponding to a unique imm borrow, so
2253             // use `&mut`. It gives all the capabilities of an `&uniq`
2254             // and hence is a safe "over approximation".
2255             UniqueImmBorrow => hir::MutMutable,
2256         }
2257     }
2258
2259     pub fn to_user_str(&self) -> &'static str {
2260         match *self {
2261             MutBorrow => "mutable",
2262             ImmBorrow => "immutable",
2263             UniqueImmBorrow => "uniquely immutable",
2264         }
2265     }
2266 }
2267
2268 #[derive(Debug, Clone)]
2269 pub enum Attributes<'gcx> {
2270     Owned(Lrc<[ast::Attribute]>),
2271     Borrowed(&'gcx [ast::Attribute])
2272 }
2273
2274 impl<'gcx> ::std::ops::Deref for Attributes<'gcx> {
2275     type Target = [ast::Attribute];
2276
2277     fn deref(&self) -> &[ast::Attribute] {
2278         match self {
2279             &Attributes::Owned(ref data) => &data,
2280             &Attributes::Borrowed(data) => data
2281         }
2282     }
2283 }
2284
2285 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
2286     pub fn body_tables(self, body: hir::BodyId) -> &'gcx TypeckTables<'gcx> {
2287         self.typeck_tables_of(self.hir.body_owner_def_id(body))
2288     }
2289
2290     /// Returns an iterator of the def-ids for all body-owners in this
2291     /// crate. If you would prefer to iterate over the bodies
2292     /// themselves, you can do `self.hir.krate().body_ids.iter()`.
2293     pub fn body_owners(self) -> impl Iterator<Item = DefId> + 'a {
2294         self.hir.krate()
2295                 .body_ids
2296                 .iter()
2297                 .map(move |&body_id| self.hir.body_owner_def_id(body_id))
2298     }
2299
2300     pub fn expr_span(self, id: NodeId) -> Span {
2301         match self.hir.find(id) {
2302             Some(hir_map::NodeExpr(e)) => {
2303                 e.span
2304             }
2305             Some(f) => {
2306                 bug!("Node id {} is not an expr: {:?}", id, f);
2307             }
2308             None => {
2309                 bug!("Node id {} is not present in the node map", id);
2310             }
2311         }
2312     }
2313
2314     pub fn provided_trait_methods(self, id: DefId) -> Vec<AssociatedItem> {
2315         self.associated_items(id)
2316             .filter(|item| item.kind == AssociatedKind::Method && item.defaultness.has_value())
2317             .collect()
2318     }
2319
2320     pub fn trait_relevant_for_never(self, did: DefId) -> bool {
2321         self.associated_items(did).any(|item| {
2322             item.relevant_for_never()
2323         })
2324     }
2325
2326     pub fn opt_associated_item(self, def_id: DefId) -> Option<AssociatedItem> {
2327         let is_associated_item = if let Some(node_id) = self.hir.as_local_node_id(def_id) {
2328             match self.hir.get(node_id) {
2329                 hir_map::NodeTraitItem(_) | hir_map::NodeImplItem(_) => true,
2330                 _ => false,
2331             }
2332         } else {
2333             match self.describe_def(def_id).expect("no def for def-id") {
2334                 Def::AssociatedConst(_) | Def::Method(_) | Def::AssociatedTy(_) => true,
2335                 _ => false,
2336             }
2337         };
2338
2339         if is_associated_item {
2340             Some(self.associated_item(def_id))
2341         } else {
2342             None
2343         }
2344     }
2345
2346     fn associated_item_from_trait_item_ref(self,
2347                                            parent_def_id: DefId,
2348                                            parent_vis: &hir::Visibility,
2349                                            trait_item_ref: &hir::TraitItemRef)
2350                                            -> AssociatedItem {
2351         let def_id = self.hir.local_def_id(trait_item_ref.id.node_id);
2352         let (kind, has_self) = match trait_item_ref.kind {
2353             hir::AssociatedItemKind::Const => (ty::AssociatedKind::Const, false),
2354             hir::AssociatedItemKind::Method { has_self } => {
2355                 (ty::AssociatedKind::Method, has_self)
2356             }
2357             hir::AssociatedItemKind::Type => (ty::AssociatedKind::Type, false),
2358         };
2359
2360         AssociatedItem {
2361             name: trait_item_ref.name,
2362             kind,
2363             // Visibility of trait items is inherited from their traits.
2364             vis: Visibility::from_hir(parent_vis, trait_item_ref.id.node_id, self),
2365             defaultness: trait_item_ref.defaultness,
2366             def_id,
2367             container: TraitContainer(parent_def_id),
2368             method_has_self_argument: has_self
2369         }
2370     }
2371
2372     fn associated_item_from_impl_item_ref(self,
2373                                           parent_def_id: DefId,
2374                                           impl_item_ref: &hir::ImplItemRef)
2375                                           -> AssociatedItem {
2376         let def_id = self.hir.local_def_id(impl_item_ref.id.node_id);
2377         let (kind, has_self) = match impl_item_ref.kind {
2378             hir::AssociatedItemKind::Const => (ty::AssociatedKind::Const, false),
2379             hir::AssociatedItemKind::Method { has_self } => {
2380                 (ty::AssociatedKind::Method, has_self)
2381             }
2382             hir::AssociatedItemKind::Type => (ty::AssociatedKind::Type, false),
2383         };
2384
2385         ty::AssociatedItem {
2386             name: impl_item_ref.name,
2387             kind,
2388             // Visibility of trait impl items doesn't matter.
2389             vis: ty::Visibility::from_hir(&impl_item_ref.vis, impl_item_ref.id.node_id, self),
2390             defaultness: impl_item_ref.defaultness,
2391             def_id,
2392             container: ImplContainer(parent_def_id),
2393             method_has_self_argument: has_self
2394         }
2395     }
2396
2397     #[inline] // FIXME(#35870) Avoid closures being unexported due to impl Trait.
2398     pub fn associated_items(self, def_id: DefId)
2399                             -> impl Iterator<Item = ty::AssociatedItem> + 'a {
2400         let def_ids = self.associated_item_def_ids(def_id);
2401         (0..def_ids.len()).map(move |i| self.associated_item(def_ids[i]))
2402     }
2403
2404     /// Returns true if the impls are the same polarity and are implementing
2405     /// a trait which contains no items
2406     pub fn impls_are_allowed_to_overlap(self, def_id1: DefId, def_id2: DefId) -> bool {
2407         if !self.features().overlapping_marker_traits {
2408             return false;
2409         }
2410         let trait1_is_empty = self.impl_trait_ref(def_id1)
2411             .map_or(false, |trait_ref| {
2412                 self.associated_item_def_ids(trait_ref.def_id).is_empty()
2413             });
2414         let trait2_is_empty = self.impl_trait_ref(def_id2)
2415             .map_or(false, |trait_ref| {
2416                 self.associated_item_def_ids(trait_ref.def_id).is_empty()
2417             });
2418         self.impl_polarity(def_id1) == self.impl_polarity(def_id2)
2419             && trait1_is_empty
2420             && trait2_is_empty
2421     }
2422
2423     // Returns `ty::VariantDef` if `def` refers to a struct,
2424     // or variant or their constructors, panics otherwise.
2425     pub fn expect_variant_def(self, def: Def) -> &'tcx VariantDef {
2426         match def {
2427             Def::Variant(did) | Def::VariantCtor(did, ..) => {
2428                 let enum_did = self.parent_def_id(did).unwrap();
2429                 self.adt_def(enum_did).variant_with_id(did)
2430             }
2431             Def::Struct(did) | Def::Union(did) => {
2432                 self.adt_def(did).non_enum_variant()
2433             }
2434             Def::StructCtor(ctor_did, ..) => {
2435                 let did = self.parent_def_id(ctor_did).expect("struct ctor has no parent");
2436                 self.adt_def(did).non_enum_variant()
2437             }
2438             _ => bug!("expect_variant_def used with unexpected def {:?}", def)
2439         }
2440     }
2441
2442     /// Given a `VariantDef`, returns the def-id of the `AdtDef` of which it is a part.
2443     pub fn adt_def_id_of_variant(self, variant_def: &'tcx VariantDef) -> DefId {
2444         let def_key = self.def_key(variant_def.did);
2445         match def_key.disambiguated_data.data {
2446             // for enum variants and tuple structs, the def-id of the ADT itself
2447             // is the *parent* of the variant
2448             DefPathData::EnumVariant(..) | DefPathData::StructCtor =>
2449                 DefId { krate: variant_def.did.krate, index: def_key.parent.unwrap() },
2450
2451             // otherwise, for structs and unions, they share a def-id
2452             _ => variant_def.did,
2453         }
2454     }
2455
2456     pub fn item_name(self, id: DefId) -> InternedString {
2457         if id.index == CRATE_DEF_INDEX {
2458             self.original_crate_name(id.krate).as_str()
2459         } else {
2460             let def_key = self.def_key(id);
2461             // The name of a StructCtor is that of its struct parent.
2462             if let hir_map::DefPathData::StructCtor = def_key.disambiguated_data.data {
2463                 self.item_name(DefId {
2464                     krate: id.krate,
2465                     index: def_key.parent.unwrap()
2466                 })
2467             } else {
2468                 def_key.disambiguated_data.data.get_opt_name().unwrap_or_else(|| {
2469                     bug!("item_name: no name for {:?}", self.def_path(id));
2470                 })
2471             }
2472         }
2473     }
2474
2475     /// Return the possibly-auto-generated MIR of a (DefId, Subst) pair.
2476     pub fn instance_mir(self, instance: ty::InstanceDef<'gcx>)
2477                         -> &'gcx Mir<'gcx>
2478     {
2479         match instance {
2480             ty::InstanceDef::Item(did) => {
2481                 self.optimized_mir(did)
2482             }
2483             ty::InstanceDef::Intrinsic(..) |
2484             ty::InstanceDef::FnPtrShim(..) |
2485             ty::InstanceDef::Virtual(..) |
2486             ty::InstanceDef::ClosureOnceShim { .. } |
2487             ty::InstanceDef::DropGlue(..) |
2488             ty::InstanceDef::CloneShim(..) => {
2489                 self.mir_shims(instance)
2490             }
2491         }
2492     }
2493
2494     /// Given the DefId of an item, returns its MIR, borrowed immutably.
2495     /// Returns None if there is no MIR for the DefId
2496     pub fn maybe_optimized_mir(self, did: DefId) -> Option<&'gcx Mir<'gcx>> {
2497         if self.is_mir_available(did) {
2498             Some(self.optimized_mir(did))
2499         } else {
2500             None
2501         }
2502     }
2503
2504     /// Get the attributes of a definition.
2505     pub fn get_attrs(self, did: DefId) -> Attributes<'gcx> {
2506         if let Some(id) = self.hir.as_local_node_id(did) {
2507             Attributes::Borrowed(self.hir.attrs(id))
2508         } else {
2509             Attributes::Owned(self.item_attrs(did))
2510         }
2511     }
2512
2513     /// Determine whether an item is annotated with an attribute
2514     pub fn has_attr(self, did: DefId, attr: &str) -> bool {
2515         attr::contains_name(&self.get_attrs(did), attr)
2516     }
2517
2518     /// Returns true if this is an `auto trait`.
2519     pub fn trait_is_auto(self, trait_def_id: DefId) -> bool {
2520         self.trait_def(trait_def_id).has_auto_impl
2521     }
2522
2523     pub fn generator_layout(self, def_id: DefId) -> &'tcx GeneratorLayout<'tcx> {
2524         self.optimized_mir(def_id).generator_layout.as_ref().unwrap()
2525     }
2526
2527     /// Given the def_id of an impl, return the def_id of the trait it implements.
2528     /// If it implements no trait, return `None`.
2529     pub fn trait_id_of_impl(self, def_id: DefId) -> Option<DefId> {
2530         self.impl_trait_ref(def_id).map(|tr| tr.def_id)
2531     }
2532
2533     /// If the given def ID describes a method belonging to an impl, return the
2534     /// ID of the impl that the method belongs to. Otherwise, return `None`.
2535     pub fn impl_of_method(self, def_id: DefId) -> Option<DefId> {
2536         let item = if def_id.krate != LOCAL_CRATE {
2537             if let Some(Def::Method(_)) = self.describe_def(def_id) {
2538                 Some(self.associated_item(def_id))
2539             } else {
2540                 None
2541             }
2542         } else {
2543             self.opt_associated_item(def_id)
2544         };
2545
2546         match item {
2547             Some(trait_item) => {
2548                 match trait_item.container {
2549                     TraitContainer(_) => None,
2550                     ImplContainer(def_id) => Some(def_id),
2551                 }
2552             }
2553             None => None
2554         }
2555     }
2556
2557     /// Looks up the span of `impl_did` if the impl is local; otherwise returns `Err`
2558     /// with the name of the crate containing the impl.
2559     pub fn span_of_impl(self, impl_did: DefId) -> Result<Span, Symbol> {
2560         if impl_did.is_local() {
2561             let node_id = self.hir.as_local_node_id(impl_did).unwrap();
2562             Ok(self.hir.span(node_id))
2563         } else {
2564             Err(self.crate_name(impl_did.krate))
2565         }
2566     }
2567
2568     // Hygienically compare a use-site name (`use_name`) for a field or an associated item with its
2569     // supposed definition name (`def_name`). The method also needs `DefId` of the supposed
2570     // definition's parent/scope to perform comparison.
2571     pub fn hygienic_eq(self, use_name: Name, def_name: Name, def_parent_def_id: DefId) -> bool {
2572         self.adjust(use_name, def_parent_def_id, DUMMY_NODE_ID).0 == def_name.to_ident()
2573     }
2574
2575     pub fn adjust(self, name: Name, scope: DefId, block: NodeId) -> (Ident, DefId) {
2576         self.adjust_ident(name.to_ident(), scope, block)
2577     }
2578
2579     pub fn adjust_ident(self, mut ident: Ident, scope: DefId, block: NodeId) -> (Ident, DefId) {
2580         let expansion = match scope.krate {
2581             LOCAL_CRATE => self.hir.definitions().expansion(scope.index),
2582             _ => Mark::root(),
2583         };
2584         let scope = match ident.ctxt.adjust(expansion) {
2585             Some(macro_def) => self.hir.definitions().macro_def_scope(macro_def),
2586             None if block == DUMMY_NODE_ID => DefId::local(CRATE_DEF_INDEX), // Dummy DefId
2587             None => self.hir.get_module_parent(block),
2588         };
2589         (ident, scope)
2590     }
2591 }
2592
2593 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
2594     pub fn with_freevars<T, F>(self, fid: NodeId, f: F) -> T where
2595         F: FnOnce(&[hir::Freevar]) -> T,
2596     {
2597         let def_id = self.hir.local_def_id(fid);
2598         match self.freevars(def_id) {
2599             None => f(&[]),
2600             Some(d) => f(&d),
2601         }
2602     }
2603 }
2604
2605 fn associated_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId)
2606     -> AssociatedItem
2607 {
2608     let id = tcx.hir.as_local_node_id(def_id).unwrap();
2609     let parent_id = tcx.hir.get_parent(id);
2610     let parent_def_id = tcx.hir.local_def_id(parent_id);
2611     let parent_item = tcx.hir.expect_item(parent_id);
2612     match parent_item.node {
2613         hir::ItemImpl(.., ref impl_item_refs) => {
2614             if let Some(impl_item_ref) = impl_item_refs.iter().find(|i| i.id.node_id == id) {
2615                 let assoc_item = tcx.associated_item_from_impl_item_ref(parent_def_id,
2616                                                                         impl_item_ref);
2617                 debug_assert_eq!(assoc_item.def_id, def_id);
2618                 return assoc_item;
2619             }
2620         }
2621
2622         hir::ItemTrait(.., ref trait_item_refs) => {
2623             if let Some(trait_item_ref) = trait_item_refs.iter().find(|i| i.id.node_id == id) {
2624                 let assoc_item = tcx.associated_item_from_trait_item_ref(parent_def_id,
2625                                                                          &parent_item.vis,
2626                                                                          trait_item_ref);
2627                 debug_assert_eq!(assoc_item.def_id, def_id);
2628                 return assoc_item;
2629             }
2630         }
2631
2632         _ => { }
2633     }
2634
2635     span_bug!(parent_item.span,
2636               "unexpected parent of trait or impl item or item not found: {:?}",
2637               parent_item.node)
2638 }
2639
2640 /// Calculates the Sized-constraint.
2641 ///
2642 /// In fact, there are only a few options for the types in the constraint:
2643 ///     - an obviously-unsized type
2644 ///     - a type parameter or projection whose Sizedness can't be known
2645 ///     - a tuple of type parameters or projections, if there are multiple
2646 ///       such.
2647 ///     - a TyError, if a type contained itself. The representability
2648 ///       check should catch this case.
2649 fn adt_sized_constraint<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
2650                                   def_id: DefId)
2651                                   -> &'tcx [Ty<'tcx>] {
2652     let def = tcx.adt_def(def_id);
2653
2654     let result = tcx.intern_type_list(&def.variants.iter().flat_map(|v| {
2655         v.fields.last()
2656     }).flat_map(|f| {
2657         def.sized_constraint_for_ty(tcx, tcx.type_of(f.did))
2658     }).collect::<Vec<_>>());
2659
2660     debug!("adt_sized_constraint: {:?} => {:?}", def, result);
2661
2662     result
2663 }
2664
2665 fn associated_item_def_ids<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
2666                                      def_id: DefId)
2667                                      -> Lrc<Vec<DefId>> {
2668     let id = tcx.hir.as_local_node_id(def_id).unwrap();
2669     let item = tcx.hir.expect_item(id);
2670     let vec: Vec<_> = match item.node {
2671         hir::ItemTrait(.., ref trait_item_refs) => {
2672             trait_item_refs.iter()
2673                            .map(|trait_item_ref| trait_item_ref.id)
2674                            .map(|id| tcx.hir.local_def_id(id.node_id))
2675                            .collect()
2676         }
2677         hir::ItemImpl(.., ref impl_item_refs) => {
2678             impl_item_refs.iter()
2679                           .map(|impl_item_ref| impl_item_ref.id)
2680                           .map(|id| tcx.hir.local_def_id(id.node_id))
2681                           .collect()
2682         }
2683         hir::ItemTraitAlias(..) => vec![],
2684         _ => span_bug!(item.span, "associated_item_def_ids: not impl or trait")
2685     };
2686     Lrc::new(vec)
2687 }
2688
2689 fn def_span<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> Span {
2690     tcx.hir.span_if_local(def_id).unwrap()
2691 }
2692
2693 /// If the given def ID describes an item belonging to a trait,
2694 /// return the ID of the trait that the trait item belongs to.
2695 /// Otherwise, return `None`.
2696 fn trait_of_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> Option<DefId> {
2697     tcx.opt_associated_item(def_id)
2698         .and_then(|associated_item| {
2699             match associated_item.container {
2700                 TraitContainer(def_id) => Some(def_id),
2701                 ImplContainer(_) => None
2702             }
2703         })
2704 }
2705
2706 /// See `ParamEnv` struct def'n for details.
2707 fn param_env<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
2708                        def_id: DefId)
2709                        -> ParamEnv<'tcx> {
2710     // Compute the bounds on Self and the type parameters.
2711
2712     let bounds = tcx.predicates_of(def_id).instantiate_identity(tcx);
2713     let predicates = bounds.predicates;
2714
2715     // Finally, we have to normalize the bounds in the environment, in
2716     // case they contain any associated type projections. This process
2717     // can yield errors if the put in illegal associated types, like
2718     // `<i32 as Foo>::Bar` where `i32` does not implement `Foo`. We
2719     // report these errors right here; this doesn't actually feel
2720     // right to me, because constructing the environment feels like a
2721     // kind of a "idempotent" action, but I'm not sure where would be
2722     // a better place. In practice, we construct environments for
2723     // every fn once during type checking, and we'll abort if there
2724     // are any errors at that point, so after type checking you can be
2725     // sure that this will succeed without errors anyway.
2726
2727     let unnormalized_env = ty::ParamEnv::new(tcx.intern_predicates(&predicates),
2728                                              traits::Reveal::UserFacing,
2729                                              ty::UniverseIndex::ROOT);
2730
2731     let body_id = tcx.hir.as_local_node_id(def_id).map_or(DUMMY_NODE_ID, |id| {
2732         tcx.hir.maybe_body_owned_by(id).map_or(id, |body| body.node_id)
2733     });
2734     let cause = traits::ObligationCause::misc(tcx.def_span(def_id), body_id);
2735     traits::normalize_param_env_or_error(tcx, def_id, unnormalized_env, cause)
2736 }
2737
2738 fn crate_disambiguator<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
2739                                  crate_num: CrateNum) -> CrateDisambiguator {
2740     assert_eq!(crate_num, LOCAL_CRATE);
2741     tcx.sess.local_crate_disambiguator()
2742 }
2743
2744 fn original_crate_name<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
2745                                  crate_num: CrateNum) -> Symbol {
2746     assert_eq!(crate_num, LOCAL_CRATE);
2747     tcx.crate_name.clone()
2748 }
2749
2750 fn crate_hash<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
2751                         crate_num: CrateNum)
2752                         -> Svh {
2753     assert_eq!(crate_num, LOCAL_CRATE);
2754     tcx.hir.crate_hash
2755 }
2756
2757 fn instance_def_size_estimate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
2758                                         instance_def: InstanceDef<'tcx>)
2759                                         -> usize {
2760     match instance_def {
2761         InstanceDef::Item(..) |
2762         InstanceDef::DropGlue(..) => {
2763             let mir = tcx.instance_mir(instance_def);
2764             mir.basic_blocks().iter().map(|bb| bb.statements.len()).sum()
2765         },
2766         // Estimate the size of other compiler-generated shims to be 1.
2767         _ => 1
2768     }
2769 }
2770
2771 pub fn provide(providers: &mut ty::maps::Providers) {
2772     context::provide(providers);
2773     erase_regions::provide(providers);
2774     layout::provide(providers);
2775     util::provide(providers);
2776     *providers = ty::maps::Providers {
2777         associated_item,
2778         associated_item_def_ids,
2779         adt_sized_constraint,
2780         def_span,
2781         param_env,
2782         trait_of_item,
2783         crate_disambiguator,
2784         original_crate_name,
2785         crate_hash,
2786         trait_impls_of: trait_def::trait_impls_of_provider,
2787         instance_def_size_estimate,
2788         ..*providers
2789     };
2790 }
2791
2792 /// A map for the local crate mapping each type to a vector of its
2793 /// inherent impls. This is not meant to be used outside of coherence;
2794 /// rather, you should request the vector for a specific type via
2795 /// `tcx.inherent_impls(def_id)` so as to minimize your dependencies
2796 /// (constructing this map requires touching the entire crate).
2797 #[derive(Clone, Debug)]
2798 pub struct CrateInherentImpls {
2799     pub inherent_impls: DefIdMap<Lrc<Vec<DefId>>>,
2800 }
2801
2802 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable)]
2803 pub struct SymbolName {
2804     // FIXME: we don't rely on interning or equality here - better have
2805     // this be a `&'tcx str`.
2806     pub name: InternedString
2807 }
2808
2809 impl_stable_hash_for!(struct self::SymbolName {
2810     name
2811 });
2812
2813 impl SymbolName {
2814     pub fn new(name: &str) -> SymbolName {
2815         SymbolName {
2816             name: Symbol::intern(name).as_str()
2817         }
2818     }
2819 }
2820
2821 impl Deref for SymbolName {
2822     type Target = str;
2823
2824     fn deref(&self) -> &str { &self.name }
2825 }
2826
2827 impl fmt::Display for SymbolName {
2828     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2829         fmt::Display::fmt(&self.name, fmt)
2830     }
2831 }
2832
2833 impl fmt::Debug for SymbolName {
2834     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2835         fmt::Display::fmt(&self.name, fmt)
2836     }
2837 }