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