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