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