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