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