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