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