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