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