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