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