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