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