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