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