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