]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_middle/src/ty/mod.rs
Auto merge of #95399 - gilescope:plan_b, r=scottmcm
[rust.git] / compiler / rustc_middle / src / ty / mod.rs
1 //! Defines how the compiler represents types internally.
2 //!
3 //! Two important entities in this module are:
4 //!
5 //! - [`rustc_middle::ty::Ty`], used to represent the semantics of a type.
6 //! - [`rustc_middle::ty::TyCtxt`], the central data structure in the compiler.
7 //!
8 //! For more information, see ["The `ty` module: representing types"] in the rustc-dev-guide.
9 //!
10 //! ["The `ty` module: representing types"]: https://rustc-dev-guide.rust-lang.org/ty.html
11
12 pub use self::fold::{FallibleTypeFolder, TypeFoldable, TypeFolder, TypeVisitor};
13 pub use self::AssocItemContainer::*;
14 pub use self::BorrowKind::*;
15 pub use self::IntVarValue::*;
16 pub use self::Variance::*;
17 pub use adt::*;
18 pub use assoc::*;
19 pub use generics::*;
20 use rustc_data_structures::fingerprint::Fingerprint;
21 pub use vtable::*;
22
23 use crate::metadata::ModChild;
24 use crate::middle::privacy::AccessLevels;
25 use crate::mir::{Body, GeneratorLayout};
26 use crate::traits::{self, Reveal};
27 use crate::ty;
28 use crate::ty::fast_reject::SimplifiedType;
29 use crate::ty::subst::{GenericArg, InternalSubsts, Subst, SubstsRef};
30 use crate::ty::util::Discr;
31 use rustc_ast as ast;
32 use rustc_attr as attr;
33 use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap};
34 use rustc_data_structures::intern::{Interned, WithStableHash};
35 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
36 use rustc_data_structures::tagged_ptr::CopyTaggedPtr;
37 use rustc_hir as hir;
38 use rustc_hir::def::{CtorKind, CtorOf, DefKind, Res};
39 use rustc_hir::def_id::{CrateNum, DefId, LocalDefId, LocalDefIdMap, CRATE_DEF_INDEX};
40 use rustc_hir::Node;
41 use rustc_macros::HashStable;
42 use rustc_query_system::ich::StableHashingContext;
43 use rustc_session::cstore::CrateStoreDyn;
44 use rustc_span::symbol::{kw, sym, Ident, Symbol};
45 use rustc_span::Span;
46 use rustc_target::abi::Align;
47
48 use std::fmt::Debug;
49 use std::hash::Hash;
50 use std::ops::ControlFlow;
51 use std::{fmt, str};
52
53 pub use crate::ty::diagnostics::*;
54 pub use rustc_type_ir::InferTy::*;
55 pub use rustc_type_ir::*;
56
57 pub use self::binding::BindingMode;
58 pub use self::binding::BindingMode::*;
59 pub use self::closure::{
60     is_ancestor_or_same_capture, place_to_string_for_capture, BorrowKind, CaptureInfo,
61     CapturedPlace, ClosureKind, MinCaptureInformationMap, MinCaptureList,
62     RootVariableMinCaptureList, UpvarCapture, UpvarCaptureMap, UpvarId, UpvarListMap, UpvarPath,
63     CAPTURE_STRUCT_LOCAL,
64 };
65 pub use self::consts::{
66     Const, ConstInt, ConstKind, ConstS, InferConst, ScalarInt, Unevaluated, ValTree,
67 };
68 pub use self::context::{
69     tls, CanonicalUserType, CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations,
70     CtxtInterners, DelaySpanBugEmitted, FreeRegionInfo, GeneratorInteriorTypeCause, GlobalCtxt,
71     Lift, OnDiskCache, TyCtxt, TypeckResults, UserType, UserTypeAnnotationIndex,
72 };
73 pub use self::instance::{Instance, InstanceDef};
74 pub use self::list::List;
75 pub use self::sty::BoundRegionKind::*;
76 pub use self::sty::RegionKind::*;
77 pub use self::sty::TyKind::*;
78 pub use self::sty::{
79     Binder, BoundRegion, BoundRegionKind, BoundTy, BoundTyKind, BoundVar, BoundVariableKind,
80     CanonicalPolyFnSig, ClosureSubsts, ClosureSubstsParts, ConstVid, EarlyBoundRegion,
81     ExistentialPredicate, ExistentialProjection, ExistentialTraitRef, FnSig, FreeRegion, GenSig,
82     GeneratorSubsts, GeneratorSubstsParts, InlineConstSubsts, InlineConstSubstsParts, ParamConst,
83     ParamTy, PolyExistentialProjection, PolyExistentialTraitRef, PolyFnSig, PolyGenSig,
84     PolyTraitRef, ProjectionTy, Region, RegionKind, RegionVid, TraitRef, TyKind, TypeAndMut,
85     UpvarSubsts, VarianceDiagInfo,
86 };
87 pub use self::trait_def::TraitDef;
88
89 pub mod _match;
90 pub mod adjustment;
91 pub mod binding;
92 pub mod cast;
93 pub mod codec;
94 pub mod error;
95 pub mod fast_reject;
96 pub mod flags;
97 pub mod fold;
98 pub mod inhabitedness;
99 pub mod layout;
100 pub mod normalize_erasing_regions;
101 pub mod print;
102 pub mod query;
103 pub mod relate;
104 pub mod subst;
105 pub mod trait_def;
106 pub mod util;
107 pub mod vtable;
108 pub mod walk;
109
110 mod adt;
111 mod assoc;
112 mod closure;
113 mod consts;
114 mod context;
115 mod diagnostics;
116 mod erase_regions;
117 mod generics;
118 mod impls_ty;
119 mod instance;
120 mod list;
121 mod structural_impls;
122 mod sty;
123
124 // Data types
125
126 pub type RegisteredTools = FxHashSet<Ident>;
127
128 #[derive(Debug)]
129 pub struct ResolverOutputs {
130     pub definitions: rustc_hir::definitions::Definitions,
131     pub cstore: Box<CrateStoreDyn>,
132     pub visibilities: FxHashMap<LocalDefId, Visibility>,
133     pub access_levels: AccessLevels,
134     pub extern_crate_map: FxHashMap<LocalDefId, CrateNum>,
135     pub maybe_unused_trait_imports: FxHashSet<LocalDefId>,
136     pub maybe_unused_extern_crates: Vec<(LocalDefId, Span)>,
137     pub reexport_map: FxHashMap<LocalDefId, Vec<ModChild>>,
138     pub glob_map: FxHashMap<LocalDefId, FxHashSet<Symbol>>,
139     /// Extern prelude entries. The value is `true` if the entry was introduced
140     /// via `extern crate` item and not `--extern` option or compiler built-in.
141     pub extern_prelude: FxHashMap<Symbol, bool>,
142     pub main_def: Option<MainDefinition>,
143     pub trait_impls: FxIndexMap<DefId, Vec<LocalDefId>>,
144     /// A list of proc macro LocalDefIds, written out in the order in which
145     /// they are declared in the static array generated by proc_macro_harness.
146     pub proc_macros: Vec<LocalDefId>,
147     /// Mapping from ident span to path span for paths that don't exist as written, but that
148     /// exist under `std`. For example, wrote `str::from_utf8` instead of `std::str::from_utf8`.
149     pub confused_type_with_std_module: FxHashMap<Span, Span>,
150     pub registered_tools: RegisteredTools,
151 }
152
153 #[derive(Clone, Copy, Debug)]
154 pub struct MainDefinition {
155     pub res: Res<ast::NodeId>,
156     pub is_import: bool,
157     pub span: Span,
158 }
159
160 impl MainDefinition {
161     pub fn opt_fn_def_id(self) -> Option<DefId> {
162         if let Res::Def(DefKind::Fn, def_id) = self.res { Some(def_id) } else { None }
163     }
164 }
165
166 /// The "header" of an impl is everything outside the body: a Self type, a trait
167 /// ref (in the case of a trait impl), and a set of predicates (from the
168 /// bounds / where-clauses).
169 #[derive(Clone, Debug, TypeFoldable)]
170 pub struct ImplHeader<'tcx> {
171     pub impl_def_id: DefId,
172     pub self_ty: Ty<'tcx>,
173     pub trait_ref: Option<TraitRef<'tcx>>,
174     pub predicates: Vec<Predicate<'tcx>>,
175 }
176
177 #[derive(Copy, Clone, Debug, TypeFoldable)]
178 pub enum ImplSubject<'tcx> {
179     Trait(TraitRef<'tcx>),
180     Inherent(Ty<'tcx>),
181 }
182
183 #[derive(
184     Copy,
185     Clone,
186     PartialEq,
187     Eq,
188     Hash,
189     TyEncodable,
190     TyDecodable,
191     HashStable,
192     Debug,
193     TypeFoldable
194 )]
195 pub enum ImplPolarity {
196     /// `impl Trait for Type`
197     Positive,
198     /// `impl !Trait for Type`
199     Negative,
200     /// `#[rustc_reservation_impl] impl Trait for Type`
201     ///
202     /// This is a "stability hack", not a real Rust feature.
203     /// See #64631 for details.
204     Reservation,
205 }
206
207 impl ImplPolarity {
208     /// Flips polarity by turning `Positive` into `Negative` and `Negative` into `Positive`.
209     pub fn flip(&self) -> Option<ImplPolarity> {
210         match self {
211             ImplPolarity::Positive => Some(ImplPolarity::Negative),
212             ImplPolarity::Negative => Some(ImplPolarity::Positive),
213             ImplPolarity::Reservation => None,
214         }
215     }
216 }
217
218 impl fmt::Display for ImplPolarity {
219     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
220         match self {
221             Self::Positive => f.write_str("positive"),
222             Self::Negative => f.write_str("negative"),
223             Self::Reservation => f.write_str("reservation"),
224         }
225     }
226 }
227
228 #[derive(Clone, Debug, PartialEq, Eq, Copy, Hash, TyEncodable, TyDecodable, HashStable)]
229 pub enum Visibility {
230     /// Visible everywhere (including in other crates).
231     Public,
232     /// Visible only in the given crate-local module.
233     Restricted(DefId),
234     /// Not visible anywhere in the local crate. This is the visibility of private external items.
235     Invisible,
236 }
237
238 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable, TyEncodable, TyDecodable)]
239 pub enum BoundConstness {
240     /// `T: Trait`
241     NotConst,
242     /// `T: ~const Trait`
243     ///
244     /// Requires resolving to const only when we are in a const context.
245     ConstIfConst,
246 }
247
248 impl BoundConstness {
249     /// Reduce `self` and `constness` to two possible combined states instead of four.
250     pub fn and(&mut self, constness: hir::Constness) -> hir::Constness {
251         match (constness, self) {
252             (hir::Constness::Const, BoundConstness::ConstIfConst) => hir::Constness::Const,
253             (_, this) => {
254                 *this = BoundConstness::NotConst;
255                 hir::Constness::NotConst
256             }
257         }
258     }
259 }
260
261 impl fmt::Display for BoundConstness {
262     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
263         match self {
264             Self::NotConst => f.write_str("normal"),
265             Self::ConstIfConst => f.write_str("`~const`"),
266         }
267     }
268 }
269
270 #[derive(
271     Clone,
272     Debug,
273     PartialEq,
274     Eq,
275     Copy,
276     Hash,
277     TyEncodable,
278     TyDecodable,
279     HashStable,
280     TypeFoldable
281 )]
282 pub struct ClosureSizeProfileData<'tcx> {
283     /// Tuple containing the types of closure captures before the feature `capture_disjoint_fields`
284     pub before_feature_tys: Ty<'tcx>,
285     /// Tuple containing the types of closure captures after the feature `capture_disjoint_fields`
286     pub after_feature_tys: Ty<'tcx>,
287 }
288
289 pub trait DefIdTree: Copy {
290     fn parent(self, id: DefId) -> Option<DefId>;
291
292     #[inline]
293     fn local_parent(self, id: LocalDefId) -> Option<LocalDefId> {
294         Some(self.parent(id.to_def_id())?.expect_local())
295     }
296
297     fn is_descendant_of(self, mut descendant: DefId, ancestor: DefId) -> bool {
298         if descendant.krate != ancestor.krate {
299             return false;
300         }
301
302         while descendant != ancestor {
303             match self.parent(descendant) {
304                 Some(parent) => descendant = parent,
305                 None => return false,
306             }
307         }
308         true
309     }
310 }
311
312 impl<'tcx> DefIdTree for TyCtxt<'tcx> {
313     fn parent(self, id: DefId) -> Option<DefId> {
314         self.def_key(id).parent.map(|index| DefId { index, ..id })
315     }
316 }
317
318 impl Visibility {
319     pub fn from_hir(visibility: &hir::Visibility<'_>, id: hir::HirId, tcx: TyCtxt<'_>) -> Self {
320         match visibility.node {
321             hir::VisibilityKind::Public => Visibility::Public,
322             hir::VisibilityKind::Crate(_) => Visibility::Restricted(DefId::local(CRATE_DEF_INDEX)),
323             hir::VisibilityKind::Restricted { ref path, .. } => match path.res {
324                 // If there is no resolution, `resolve` will have already reported an error, so
325                 // assume that the visibility is public to avoid reporting more privacy errors.
326                 Res::Err => Visibility::Public,
327                 def => Visibility::Restricted(def.def_id()),
328             },
329             hir::VisibilityKind::Inherited => {
330                 Visibility::Restricted(tcx.parent_module(id).to_def_id())
331             }
332         }
333     }
334
335     /// Returns `true` if an item with this visibility is accessible from the given block.
336     pub fn is_accessible_from<T: DefIdTree>(self, module: DefId, tree: T) -> bool {
337         let restriction = match self {
338             // Public items are visible everywhere.
339             Visibility::Public => return true,
340             // Private items from other crates are visible nowhere.
341             Visibility::Invisible => return false,
342             // Restricted items are visible in an arbitrary local module.
343             Visibility::Restricted(other) if other.krate != module.krate => return false,
344             Visibility::Restricted(module) => module,
345         };
346
347         tree.is_descendant_of(module, restriction)
348     }
349
350     /// Returns `true` if this visibility is at least as accessible as the given visibility
351     pub fn is_at_least<T: DefIdTree>(self, vis: Visibility, tree: T) -> bool {
352         let vis_restriction = match vis {
353             Visibility::Public => return self == Visibility::Public,
354             Visibility::Invisible => return true,
355             Visibility::Restricted(module) => module,
356         };
357
358         self.is_accessible_from(vis_restriction, tree)
359     }
360
361     // Returns `true` if this item is visible anywhere in the local crate.
362     pub fn is_visible_locally(self) -> bool {
363         match self {
364             Visibility::Public => true,
365             Visibility::Restricted(def_id) => def_id.is_local(),
366             Visibility::Invisible => false,
367         }
368     }
369
370     pub fn is_public(self) -> bool {
371         matches!(self, Visibility::Public)
372     }
373 }
374
375 /// The crate variances map is computed during typeck and contains the
376 /// variance of every item in the local crate. You should not use it
377 /// directly, because to do so will make your pass dependent on the
378 /// HIR of every item in the local crate. Instead, use
379 /// `tcx.variances_of()` to get the variance for a *particular*
380 /// item.
381 #[derive(HashStable, Debug)]
382 pub struct CrateVariancesMap<'tcx> {
383     /// For each item with generics, maps to a vector of the variance
384     /// of its generics. If an item has no generics, it will have no
385     /// entry.
386     pub variances: FxHashMap<DefId, &'tcx [ty::Variance]>,
387 }
388
389 // Contains information needed to resolve types and (in the future) look up
390 // the types of AST nodes.
391 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
392 pub struct CReaderCacheKey {
393     pub cnum: Option<CrateNum>,
394     pub pos: usize,
395 }
396
397 /// Represents a type.
398 ///
399 /// IMPORTANT:
400 /// - This is a very "dumb" struct (with no derives and no `impls`).
401 /// - Values of this type are always interned and thus unique, and are stored
402 ///   as an `Interned<TyS>`.
403 /// - `Ty` (which contains a reference to a `Interned<TyS>`) or `Interned<TyS>`
404 ///   should be used everywhere instead of `TyS`. In particular, `Ty` has most
405 ///   of the relevant methods.
406 #[derive(PartialEq, Eq, PartialOrd, Ord)]
407 #[allow(rustc::usage_of_ty_tykind)]
408 crate struct TyS<'tcx> {
409     /// This field shouldn't be used directly and may be removed in the future.
410     /// Use `Ty::kind()` instead.
411     kind: TyKind<'tcx>,
412
413     /// This field provides fast access to information that is also contained
414     /// in `kind`.
415     ///
416     /// This field shouldn't be used directly and may be removed in the future.
417     /// Use `Ty::flags()` instead.
418     flags: TypeFlags,
419
420     /// This field provides fast access to information that is also contained
421     /// in `kind`.
422     ///
423     /// This is a kind of confusing thing: it stores the smallest
424     /// binder such that
425     ///
426     /// (a) the binder itself captures nothing but
427     /// (b) all the late-bound things within the type are captured
428     ///     by some sub-binder.
429     ///
430     /// So, for a type without any late-bound things, like `u32`, this
431     /// will be *innermost*, because that is the innermost binder that
432     /// captures nothing. But for a type `&'D u32`, where `'D` is a
433     /// late-bound region with De Bruijn index `D`, this would be `D + 1`
434     /// -- the binder itself does not capture `D`, but `D` is captured
435     /// by an inner binder.
436     ///
437     /// We call this concept an "exclusive" binder `D` because all
438     /// De Bruijn indices within the type are contained within `0..D`
439     /// (exclusive).
440     outer_exclusive_binder: ty::DebruijnIndex,
441 }
442
443 // `TyS` is used a lot. Make sure it doesn't unintentionally get bigger.
444 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
445 static_assert_size!(TyS<'_>, 40);
446
447 // We are actually storing a stable hash cache next to the type, so let's
448 // also check the full size
449 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
450 static_assert_size!(WithStableHash<TyS<'_>>, 56);
451
452 /// Use this rather than `TyS`, whenever possible.
453 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, HashStable)]
454 #[rustc_diagnostic_item = "Ty"]
455 #[rustc_pass_by_value]
456 pub struct Ty<'tcx>(Interned<'tcx, WithStableHash<TyS<'tcx>>>);
457
458 // Statics only used for internal testing.
459 pub static BOOL_TY: Ty<'static> = Ty(Interned::new_unchecked(&WithStableHash {
460     internee: BOOL_TYS,
461     stable_hash: Fingerprint::ZERO,
462 }));
463 const BOOL_TYS: TyS<'static> = TyS {
464     kind: ty::Bool,
465     flags: TypeFlags::empty(),
466     outer_exclusive_binder: DebruijnIndex::from_usize(0),
467 };
468
469 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for TyS<'tcx> {
470     #[inline]
471     fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
472         let TyS {
473             kind,
474
475             // The other fields just provide fast access to information that is
476             // also contained in `kind`, so no need to hash them.
477             flags: _,
478
479             outer_exclusive_binder: _,
480         } = self;
481
482         kind.hash_stable(hcx, hasher)
483     }
484 }
485
486 impl ty::EarlyBoundRegion {
487     /// Does this early bound region have a name? Early bound regions normally
488     /// always have names except when using anonymous lifetimes (`'_`).
489     pub fn has_name(&self) -> bool {
490         self.name != kw::UnderscoreLifetime
491     }
492 }
493
494 /// Represents a predicate.
495 ///
496 /// See comments on `TyS`, which apply here too (albeit for
497 /// `PredicateS`/`Predicate` rather than `TyS`/`Ty`).
498 #[derive(Debug)]
499 crate struct PredicateS<'tcx> {
500     kind: Binder<'tcx, PredicateKind<'tcx>>,
501     flags: TypeFlags,
502     /// See the comment for the corresponding field of [TyS].
503     outer_exclusive_binder: ty::DebruijnIndex,
504 }
505
506 // This type is used a lot. Make sure it doesn't unintentionally get bigger.
507 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
508 static_assert_size!(PredicateS<'_>, 56);
509
510 /// Use this rather than `PredicateS`, whenever possible.
511 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
512 #[rustc_pass_by_value]
513 pub struct Predicate<'tcx>(Interned<'tcx, PredicateS<'tcx>>);
514
515 impl<'tcx> Predicate<'tcx> {
516     /// Gets the inner `Binder<'tcx, PredicateKind<'tcx>>`.
517     #[inline]
518     pub fn kind(self) -> Binder<'tcx, PredicateKind<'tcx>> {
519         self.0.kind
520     }
521
522     #[inline(always)]
523     pub fn flags(self) -> TypeFlags {
524         self.0.flags
525     }
526
527     #[inline(always)]
528     pub fn outer_exclusive_binder(self) -> DebruijnIndex {
529         self.0.outer_exclusive_binder
530     }
531
532     /// Flips the polarity of a Predicate.
533     ///
534     /// Given `T: Trait` predicate it returns `T: !Trait` and given `T: !Trait` returns `T: Trait`.
535     pub fn flip_polarity(self, tcx: TyCtxt<'tcx>) -> Option<Predicate<'tcx>> {
536         let kind = self
537             .kind()
538             .map_bound(|kind| match kind {
539                 PredicateKind::Trait(TraitPredicate { trait_ref, constness, polarity }) => {
540                     Some(PredicateKind::Trait(TraitPredicate {
541                         trait_ref,
542                         constness,
543                         polarity: polarity.flip()?,
544                     }))
545                 }
546
547                 _ => None,
548             })
549             .transpose()?;
550
551         Some(tcx.mk_predicate(kind))
552     }
553 }
554
555 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for Predicate<'tcx> {
556     fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
557         let PredicateS {
558             ref kind,
559
560             // The other fields just provide fast access to information that is
561             // also contained in `kind`, so no need to hash them.
562             flags: _,
563             outer_exclusive_binder: _,
564         } = self.0.0;
565
566         kind.hash_stable(hcx, hasher);
567     }
568 }
569
570 #[derive(Clone, Copy, PartialEq, Eq, Hash, TyEncodable, TyDecodable)]
571 #[derive(HashStable, TypeFoldable)]
572 pub enum PredicateKind<'tcx> {
573     /// Corresponds to `where Foo: Bar<A, B, C>`. `Foo` here would be
574     /// the `Self` type of the trait reference and `A`, `B`, and `C`
575     /// would be the type parameters.
576     Trait(TraitPredicate<'tcx>),
577
578     /// `where 'a: 'b`
579     RegionOutlives(RegionOutlivesPredicate<'tcx>),
580
581     /// `where T: 'a`
582     TypeOutlives(TypeOutlivesPredicate<'tcx>),
583
584     /// `where <T as TraitRef>::Name == X`, approximately.
585     /// See the `ProjectionPredicate` struct for details.
586     Projection(ProjectionPredicate<'tcx>),
587
588     /// No syntax: `T` well-formed.
589     WellFormed(GenericArg<'tcx>),
590
591     /// Trait must be object-safe.
592     ObjectSafe(DefId),
593
594     /// No direct syntax. May be thought of as `where T: FnFoo<...>`
595     /// for some substitutions `...` and `T` being a closure type.
596     /// Satisfied (or refuted) once we know the closure's kind.
597     ClosureKind(DefId, SubstsRef<'tcx>, ClosureKind),
598
599     /// `T1 <: T2`
600     ///
601     /// This obligation is created most often when we have two
602     /// unresolved type variables and hence don't have enough
603     /// information to process the subtyping obligation yet.
604     Subtype(SubtypePredicate<'tcx>),
605
606     /// `T1` coerced to `T2`
607     ///
608     /// Like a subtyping obligation, this is created most often
609     /// when we have two unresolved type variables and hence
610     /// don't have enough information to process the coercion
611     /// obligation yet. At the moment, we actually process coercions
612     /// very much like subtyping and don't handle the full coercion
613     /// logic.
614     Coerce(CoercePredicate<'tcx>),
615
616     /// Constant initializer must evaluate successfully.
617     ConstEvaluatable(ty::Unevaluated<'tcx, ()>),
618
619     /// Constants must be equal. The first component is the const that is expected.
620     ConstEquate(Const<'tcx>, Const<'tcx>),
621
622     /// Represents a type found in the environment that we can use for implied bounds.
623     ///
624     /// Only used for Chalk.
625     TypeWellFormedFromEnv(Ty<'tcx>),
626 }
627
628 /// The crate outlives map is computed during typeck and contains the
629 /// outlives of every item in the local crate. You should not use it
630 /// directly, because to do so will make your pass dependent on the
631 /// HIR of every item in the local crate. Instead, use
632 /// `tcx.inferred_outlives_of()` to get the outlives for a *particular*
633 /// item.
634 #[derive(HashStable, Debug)]
635 pub struct CratePredicatesMap<'tcx> {
636     /// For each struct with outlive bounds, maps to a vector of the
637     /// predicate of its outlive bounds. If an item has no outlives
638     /// bounds, it will have no entry.
639     pub predicates: FxHashMap<DefId, &'tcx [(Predicate<'tcx>, Span)]>,
640 }
641
642 impl<'tcx> Predicate<'tcx> {
643     /// Performs a substitution suitable for going from a
644     /// poly-trait-ref to supertraits that must hold if that
645     /// poly-trait-ref holds. This is slightly different from a normal
646     /// substitution in terms of what happens with bound regions. See
647     /// lengthy comment below for details.
648     pub fn subst_supertrait(
649         self,
650         tcx: TyCtxt<'tcx>,
651         trait_ref: &ty::PolyTraitRef<'tcx>,
652     ) -> Predicate<'tcx> {
653         // The interaction between HRTB and supertraits is not entirely
654         // obvious. Let me walk you (and myself) through an example.
655         //
656         // Let's start with an easy case. Consider two traits:
657         //
658         //     trait Foo<'a>: Bar<'a,'a> { }
659         //     trait Bar<'b,'c> { }
660         //
661         // Now, if we have a trait reference `for<'x> T: Foo<'x>`, then
662         // we can deduce that `for<'x> T: Bar<'x,'x>`. Basically, if we
663         // knew that `Foo<'x>` (for any 'x) then we also know that
664         // `Bar<'x,'x>` (for any 'x). This more-or-less falls out from
665         // normal substitution.
666         //
667         // In terms of why this is sound, the idea is that whenever there
668         // is an impl of `T:Foo<'a>`, it must show that `T:Bar<'a,'a>`
669         // holds.  So if there is an impl of `T:Foo<'a>` that applies to
670         // all `'a`, then we must know that `T:Bar<'a,'a>` holds for all
671         // `'a`.
672         //
673         // Another example to be careful of is this:
674         //
675         //     trait Foo1<'a>: for<'b> Bar1<'a,'b> { }
676         //     trait Bar1<'b,'c> { }
677         //
678         // Here, if we have `for<'x> T: Foo1<'x>`, then what do we know?
679         // The answer is that we know `for<'x,'b> T: Bar1<'x,'b>`. The
680         // reason is similar to the previous example: any impl of
681         // `T:Foo1<'x>` must show that `for<'b> T: Bar1<'x, 'b>`.  So
682         // basically we would want to collapse the bound lifetimes from
683         // the input (`trait_ref`) and the supertraits.
684         //
685         // To achieve this in practice is fairly straightforward. Let's
686         // consider the more complicated scenario:
687         //
688         // - We start out with `for<'x> T: Foo1<'x>`. In this case, `'x`
689         //   has a De Bruijn index of 1. We want to produce `for<'x,'b> T: Bar1<'x,'b>`,
690         //   where both `'x` and `'b` would have a DB index of 1.
691         //   The substitution from the input trait-ref is therefore going to be
692         //   `'a => 'x` (where `'x` has a DB index of 1).
693         // - The supertrait-ref is `for<'b> Bar1<'a,'b>`, where `'a` is an
694         //   early-bound parameter and `'b' is a late-bound parameter with a
695         //   DB index of 1.
696         // - If we replace `'a` with `'x` from the input, it too will have
697         //   a DB index of 1, and thus we'll have `for<'x,'b> Bar1<'x,'b>`
698         //   just as we wanted.
699         //
700         // There is only one catch. If we just apply the substitution `'a
701         // => 'x` to `for<'b> Bar1<'a,'b>`, the substitution code will
702         // adjust the DB index because we substituting into a binder (it
703         // tries to be so smart...) resulting in `for<'x> for<'b>
704         // Bar1<'x,'b>` (we have no syntax for this, so use your
705         // imagination). Basically the 'x will have DB index of 2 and 'b
706         // will have DB index of 1. Not quite what we want. So we apply
707         // the substitution to the *contents* of the trait reference,
708         // rather than the trait reference itself (put another way, the
709         // substitution code expects equal binding levels in the values
710         // from the substitution and the value being substituted into, and
711         // this trick achieves that).
712
713         // Working through the second example:
714         // trait_ref: for<'x> T: Foo1<'^0.0>; substs: [T, '^0.0]
715         // predicate: for<'b> Self: Bar1<'a, '^0.0>; substs: [Self, 'a, '^0.0]
716         // We want to end up with:
717         //     for<'x, 'b> T: Bar1<'^0.0, '^0.1>
718         // To do this:
719         // 1) We must shift all bound vars in predicate by the length
720         //    of trait ref's bound vars. So, we would end up with predicate like
721         //    Self: Bar1<'a, '^0.1>
722         // 2) We can then apply the trait substs to this, ending up with
723         //    T: Bar1<'^0.0, '^0.1>
724         // 3) Finally, to create the final bound vars, we concatenate the bound
725         //    vars of the trait ref with those of the predicate:
726         //    ['x, 'b]
727         let bound_pred = self.kind();
728         let pred_bound_vars = bound_pred.bound_vars();
729         let trait_bound_vars = trait_ref.bound_vars();
730         // 1) Self: Bar1<'a, '^0.0> -> Self: Bar1<'a, '^0.1>
731         let shifted_pred =
732             tcx.shift_bound_var_indices(trait_bound_vars.len(), bound_pred.skip_binder());
733         // 2) Self: Bar1<'a, '^0.1> -> T: Bar1<'^0.0, '^0.1>
734         let new = shifted_pred.subst(tcx, trait_ref.skip_binder().substs);
735         // 3) ['x] + ['b] -> ['x, 'b]
736         let bound_vars =
737             tcx.mk_bound_variable_kinds(trait_bound_vars.iter().chain(pred_bound_vars));
738         tcx.reuse_or_mk_predicate(self, ty::Binder::bind_with_vars(new, bound_vars))
739     }
740 }
741
742 #[derive(Clone, Copy, PartialEq, Eq, Hash, TyEncodable, TyDecodable)]
743 #[derive(HashStable, TypeFoldable)]
744 pub struct TraitPredicate<'tcx> {
745     pub trait_ref: TraitRef<'tcx>,
746
747     pub constness: BoundConstness,
748
749     /// If polarity is Positive: we are proving that the trait is implemented.
750     ///
751     /// If polarity is Negative: we are proving that a negative impl of this trait
752     /// exists. (Note that coherence also checks whether negative impls of supertraits
753     /// exist via a series of predicates.)
754     ///
755     /// If polarity is Reserved: that's a bug.
756     pub polarity: ImplPolarity,
757 }
758
759 pub type PolyTraitPredicate<'tcx> = ty::Binder<'tcx, TraitPredicate<'tcx>>;
760
761 impl<'tcx> TraitPredicate<'tcx> {
762     pub fn remap_constness(&mut self, tcx: TyCtxt<'tcx>, param_env: &mut ParamEnv<'tcx>) {
763         if unlikely!(Some(self.trait_ref.def_id) == tcx.lang_items().drop_trait()) {
764             // remap without changing constness of this predicate.
765             // this is because `T: ~const Drop` has a different meaning to `T: Drop`
766             // FIXME(fee1-dead): remove this logic after beta bump
767             param_env.remap_constness_with(self.constness)
768         } else {
769             *param_env = param_env.with_constness(self.constness.and(param_env.constness()))
770         }
771     }
772
773     /// Remap the constness of this predicate before emitting it for diagnostics.
774     pub fn remap_constness_diag(&mut self, param_env: ParamEnv<'tcx>) {
775         // this is different to `remap_constness` that callees want to print this predicate
776         // in case of selection errors. `T: ~const Drop` bounds cannot end up here when the
777         // param_env is not const because we it is always satisfied in non-const contexts.
778         if let hir::Constness::NotConst = param_env.constness() {
779             self.constness = ty::BoundConstness::NotConst;
780         }
781     }
782
783     pub fn def_id(self) -> DefId {
784         self.trait_ref.def_id
785     }
786
787     pub fn self_ty(self) -> Ty<'tcx> {
788         self.trait_ref.self_ty()
789     }
790
791     #[inline]
792     pub fn is_const_if_const(self) -> bool {
793         self.constness == BoundConstness::ConstIfConst
794     }
795 }
796
797 impl<'tcx> PolyTraitPredicate<'tcx> {
798     pub fn def_id(self) -> DefId {
799         // Ok to skip binder since trait `DefId` does not care about regions.
800         self.skip_binder().def_id()
801     }
802
803     pub fn self_ty(self) -> ty::Binder<'tcx, Ty<'tcx>> {
804         self.map_bound(|trait_ref| trait_ref.self_ty())
805     }
806
807     /// Remap the constness of this predicate before emitting it for diagnostics.
808     pub fn remap_constness_diag(&mut self, param_env: ParamEnv<'tcx>) {
809         *self = self.map_bound(|mut p| {
810             p.remap_constness_diag(param_env);
811             p
812         });
813     }
814
815     #[inline]
816     pub fn is_const_if_const(self) -> bool {
817         self.skip_binder().is_const_if_const()
818     }
819 }
820
821 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, TyEncodable, TyDecodable)]
822 #[derive(HashStable, TypeFoldable)]
823 pub struct OutlivesPredicate<A, B>(pub A, pub B); // `A: B`
824 pub type RegionOutlivesPredicate<'tcx> = OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>;
825 pub type TypeOutlivesPredicate<'tcx> = OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>;
826 pub type PolyRegionOutlivesPredicate<'tcx> = ty::Binder<'tcx, RegionOutlivesPredicate<'tcx>>;
827 pub type PolyTypeOutlivesPredicate<'tcx> = ty::Binder<'tcx, TypeOutlivesPredicate<'tcx>>;
828
829 /// Encodes that `a` must be a subtype of `b`. The `a_is_expected` flag indicates
830 /// whether the `a` type is the type that we should label as "expected" when
831 /// presenting user diagnostics.
832 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, TyEncodable, TyDecodable)]
833 #[derive(HashStable, TypeFoldable)]
834 pub struct SubtypePredicate<'tcx> {
835     pub a_is_expected: bool,
836     pub a: Ty<'tcx>,
837     pub b: Ty<'tcx>,
838 }
839 pub type PolySubtypePredicate<'tcx> = ty::Binder<'tcx, SubtypePredicate<'tcx>>;
840
841 /// Encodes that we have to coerce *from* the `a` type to the `b` type.
842 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, TyEncodable, TyDecodable)]
843 #[derive(HashStable, TypeFoldable)]
844 pub struct CoercePredicate<'tcx> {
845     pub a: Ty<'tcx>,
846     pub b: Ty<'tcx>,
847 }
848 pub type PolyCoercePredicate<'tcx> = ty::Binder<'tcx, CoercePredicate<'tcx>>;
849
850 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, TyEncodable, TyDecodable)]
851 #[derive(HashStable, TypeFoldable)]
852 pub enum Term<'tcx> {
853     Ty(Ty<'tcx>),
854     Const(Const<'tcx>),
855 }
856
857 impl<'tcx> From<Ty<'tcx>> for Term<'tcx> {
858     fn from(ty: Ty<'tcx>) -> Self {
859         Term::Ty(ty)
860     }
861 }
862
863 impl<'tcx> From<Const<'tcx>> for Term<'tcx> {
864     fn from(c: Const<'tcx>) -> Self {
865         Term::Const(c)
866     }
867 }
868
869 impl<'tcx> Term<'tcx> {
870     pub fn ty(&self) -> Option<Ty<'tcx>> {
871         if let Term::Ty(ty) = self { Some(*ty) } else { None }
872     }
873     pub fn ct(&self) -> Option<Const<'tcx>> {
874         if let Term::Const(c) = self { Some(*c) } else { None }
875     }
876 }
877
878 /// This kind of predicate has no *direct* correspondent in the
879 /// syntax, but it roughly corresponds to the syntactic forms:
880 ///
881 /// 1. `T: TraitRef<..., Item = Type>`
882 /// 2. `<T as TraitRef<...>>::Item == Type` (NYI)
883 ///
884 /// In particular, form #1 is "desugared" to the combination of a
885 /// normal trait predicate (`T: TraitRef<...>`) and one of these
886 /// predicates. Form #2 is a broader form in that it also permits
887 /// equality between arbitrary types. Processing an instance of
888 /// Form #2 eventually yields one of these `ProjectionPredicate`
889 /// instances to normalize the LHS.
890 #[derive(Copy, Clone, PartialEq, Eq, Hash, TyEncodable, TyDecodable)]
891 #[derive(HashStable, TypeFoldable)]
892 pub struct ProjectionPredicate<'tcx> {
893     pub projection_ty: ProjectionTy<'tcx>,
894     pub term: Term<'tcx>,
895 }
896
897 pub type PolyProjectionPredicate<'tcx> = Binder<'tcx, ProjectionPredicate<'tcx>>;
898
899 impl<'tcx> PolyProjectionPredicate<'tcx> {
900     /// Returns the `DefId` of the trait of the associated item being projected.
901     #[inline]
902     pub fn trait_def_id(&self, tcx: TyCtxt<'tcx>) -> DefId {
903         self.skip_binder().projection_ty.trait_def_id(tcx)
904     }
905
906     /// Get the [PolyTraitRef] required for this projection to be well formed.
907     /// Note that for generic associated types the predicates of the associated
908     /// type also need to be checked.
909     #[inline]
910     pub fn required_poly_trait_ref(&self, tcx: TyCtxt<'tcx>) -> PolyTraitRef<'tcx> {
911         // Note: unlike with `TraitRef::to_poly_trait_ref()`,
912         // `self.0.trait_ref` is permitted to have escaping regions.
913         // This is because here `self` has a `Binder` and so does our
914         // return value, so we are preserving the number of binding
915         // levels.
916         self.map_bound(|predicate| predicate.projection_ty.trait_ref(tcx))
917     }
918
919     pub fn term(&self) -> Binder<'tcx, Term<'tcx>> {
920         self.map_bound(|predicate| predicate.term)
921     }
922
923     /// The `DefId` of the `TraitItem` for the associated type.
924     ///
925     /// Note that this is not the `DefId` of the `TraitRef` containing this
926     /// associated type, which is in `tcx.associated_item(projection_def_id()).container`.
927     pub fn projection_def_id(&self) -> DefId {
928         // Ok to skip binder since trait `DefId` does not care about regions.
929         self.skip_binder().projection_ty.item_def_id
930     }
931 }
932
933 pub trait ToPolyTraitRef<'tcx> {
934     fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx>;
935 }
936
937 impl<'tcx> ToPolyTraitRef<'tcx> for PolyTraitPredicate<'tcx> {
938     fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
939         self.map_bound_ref(|trait_pred| trait_pred.trait_ref)
940     }
941 }
942
943 pub trait ToPredicate<'tcx> {
944     fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx>;
945 }
946
947 impl<'tcx> ToPredicate<'tcx> for Binder<'tcx, PredicateKind<'tcx>> {
948     #[inline(always)]
949     fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
950         tcx.mk_predicate(self)
951     }
952 }
953
954 impl<'tcx> ToPredicate<'tcx> for PolyTraitPredicate<'tcx> {
955     fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
956         self.map_bound(PredicateKind::Trait).to_predicate(tcx)
957     }
958 }
959
960 impl<'tcx> ToPredicate<'tcx> for PolyRegionOutlivesPredicate<'tcx> {
961     fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
962         self.map_bound(PredicateKind::RegionOutlives).to_predicate(tcx)
963     }
964 }
965
966 impl<'tcx> ToPredicate<'tcx> for PolyTypeOutlivesPredicate<'tcx> {
967     fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
968         self.map_bound(PredicateKind::TypeOutlives).to_predicate(tcx)
969     }
970 }
971
972 impl<'tcx> ToPredicate<'tcx> for PolyProjectionPredicate<'tcx> {
973     fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
974         self.map_bound(PredicateKind::Projection).to_predicate(tcx)
975     }
976 }
977
978 impl<'tcx> Predicate<'tcx> {
979     pub fn to_opt_poly_trait_pred(self) -> Option<PolyTraitPredicate<'tcx>> {
980         let predicate = self.kind();
981         match predicate.skip_binder() {
982             PredicateKind::Trait(t) => Some(predicate.rebind(t)),
983             PredicateKind::Projection(..)
984             | PredicateKind::Subtype(..)
985             | PredicateKind::Coerce(..)
986             | PredicateKind::RegionOutlives(..)
987             | PredicateKind::WellFormed(..)
988             | PredicateKind::ObjectSafe(..)
989             | PredicateKind::ClosureKind(..)
990             | PredicateKind::TypeOutlives(..)
991             | PredicateKind::ConstEvaluatable(..)
992             | PredicateKind::ConstEquate(..)
993             | PredicateKind::TypeWellFormedFromEnv(..) => None,
994         }
995     }
996
997     pub fn to_opt_type_outlives(self) -> Option<PolyTypeOutlivesPredicate<'tcx>> {
998         let predicate = self.kind();
999         match predicate.skip_binder() {
1000             PredicateKind::TypeOutlives(data) => Some(predicate.rebind(data)),
1001             PredicateKind::Trait(..)
1002             | PredicateKind::Projection(..)
1003             | PredicateKind::Subtype(..)
1004             | PredicateKind::Coerce(..)
1005             | PredicateKind::RegionOutlives(..)
1006             | PredicateKind::WellFormed(..)
1007             | PredicateKind::ObjectSafe(..)
1008             | PredicateKind::ClosureKind(..)
1009             | PredicateKind::ConstEvaluatable(..)
1010             | PredicateKind::ConstEquate(..)
1011             | PredicateKind::TypeWellFormedFromEnv(..) => None,
1012         }
1013     }
1014 }
1015
1016 /// Represents the bounds declared on a particular set of type
1017 /// parameters. Should eventually be generalized into a flag list of
1018 /// where-clauses. You can obtain an `InstantiatedPredicates` list from a
1019 /// `GenericPredicates` by using the `instantiate` method. Note that this method
1020 /// reflects an important semantic invariant of `InstantiatedPredicates`: while
1021 /// the `GenericPredicates` are expressed in terms of the bound type
1022 /// parameters of the impl/trait/whatever, an `InstantiatedPredicates` instance
1023 /// represented a set of bounds for some particular instantiation,
1024 /// meaning that the generic parameters have been substituted with
1025 /// their values.
1026 ///
1027 /// Example:
1028 ///
1029 ///     struct Foo<T, U: Bar<T>> { ... }
1030 ///
1031 /// Here, the `GenericPredicates` for `Foo` would contain a list of bounds like
1032 /// `[[], [U:Bar<T>]]`. Now if there were some particular reference
1033 /// like `Foo<isize,usize>`, then the `InstantiatedPredicates` would be `[[],
1034 /// [usize:Bar<isize>]]`.
1035 #[derive(Clone, Debug, TypeFoldable)]
1036 pub struct InstantiatedPredicates<'tcx> {
1037     pub predicates: Vec<Predicate<'tcx>>,
1038     pub spans: Vec<Span>,
1039 }
1040
1041 impl<'tcx> InstantiatedPredicates<'tcx> {
1042     pub fn empty() -> InstantiatedPredicates<'tcx> {
1043         InstantiatedPredicates { predicates: vec![], spans: vec![] }
1044     }
1045
1046     pub fn is_empty(&self) -> bool {
1047         self.predicates.is_empty()
1048     }
1049 }
1050
1051 #[derive(
1052     Copy,
1053     Clone,
1054     Debug,
1055     PartialEq,
1056     Eq,
1057     HashStable,
1058     TyEncodable,
1059     TyDecodable,
1060     TypeFoldable,
1061     Lift
1062 )]
1063 pub struct OpaqueTypeKey<'tcx> {
1064     pub def_id: DefId,
1065     pub substs: SubstsRef<'tcx>,
1066 }
1067
1068 #[derive(Copy, Clone, Debug, TypeFoldable, HashStable, TyEncodable, TyDecodable)]
1069 pub struct OpaqueHiddenType<'tcx> {
1070     /// The span of this particular definition of the opaque type. So
1071     /// for example:
1072     ///
1073     /// ```ignore (incomplete snippet)
1074     /// type Foo = impl Baz;
1075     /// fn bar() -> Foo {
1076     /// //          ^^^ This is the span we are looking for!
1077     /// }
1078     /// ```
1079     ///
1080     /// In cases where the fn returns `(impl Trait, impl Trait)` or
1081     /// other such combinations, the result is currently
1082     /// over-approximated, but better than nothing.
1083     pub span: Span,
1084
1085     /// The type variable that represents the value of the opaque type
1086     /// that we require. In other words, after we compile this function,
1087     /// we will be created a constraint like:
1088     ///
1089     ///     Foo<'a, T> = ?C
1090     ///
1091     /// where `?C` is the value of this type variable. =) It may
1092     /// naturally refer to the type and lifetime parameters in scope
1093     /// in this function, though ultimately it should only reference
1094     /// those that are arguments to `Foo` in the constraint above. (In
1095     /// other words, `?C` should not include `'b`, even though it's a
1096     /// lifetime parameter on `foo`.)
1097     pub ty: Ty<'tcx>,
1098 }
1099
1100 impl<'tcx> OpaqueHiddenType<'tcx> {
1101     pub fn report_mismatch(&self, other: &Self, tcx: TyCtxt<'tcx>) {
1102         // Found different concrete types for the opaque type.
1103         let mut err = tcx.sess.struct_span_err(
1104             other.span,
1105             "concrete type differs from previous defining opaque type use",
1106         );
1107         err.span_label(other.span, format!("expected `{}`, got `{}`", self.ty, other.ty));
1108         if self.span == other.span {
1109             err.span_label(
1110                 self.span,
1111                 "this expression supplies two conflicting concrete types for the same opaque type",
1112             );
1113         } else {
1114             err.span_note(self.span, "previous use here");
1115         }
1116         err.emit();
1117     }
1118 }
1119
1120 rustc_index::newtype_index! {
1121     /// "Universes" are used during type- and trait-checking in the
1122     /// presence of `for<..>` binders to control what sets of names are
1123     /// visible. Universes are arranged into a tree: the root universe
1124     /// contains names that are always visible. Each child then adds a new
1125     /// set of names that are visible, in addition to those of its parent.
1126     /// We say that the child universe "extends" the parent universe with
1127     /// new names.
1128     ///
1129     /// To make this more concrete, consider this program:
1130     ///
1131     /// ```
1132     /// struct Foo { }
1133     /// fn bar<T>(x: T) {
1134     ///   let y: for<'a> fn(&'a u8, Foo) = ...;
1135     /// }
1136     /// ```
1137     ///
1138     /// The struct name `Foo` is in the root universe U0. But the type
1139     /// parameter `T`, introduced on `bar`, is in an extended universe U1
1140     /// -- i.e., within `bar`, we can name both `T` and `Foo`, but outside
1141     /// of `bar`, we cannot name `T`. Then, within the type of `y`, the
1142     /// region `'a` is in a universe U2 that extends U1, because we can
1143     /// name it inside the fn type but not outside.
1144     ///
1145     /// Universes are used to do type- and trait-checking around these
1146     /// "forall" binders (also called **universal quantification**). The
1147     /// idea is that when, in the body of `bar`, we refer to `T` as a
1148     /// type, we aren't referring to any type in particular, but rather a
1149     /// kind of "fresh" type that is distinct from all other types we have
1150     /// actually declared. This is called a **placeholder** type, and we
1151     /// use universes to talk about this. In other words, a type name in
1152     /// universe 0 always corresponds to some "ground" type that the user
1153     /// declared, but a type name in a non-zero universe is a placeholder
1154     /// type -- an idealized representative of "types in general" that we
1155     /// use for checking generic functions.
1156     pub struct UniverseIndex {
1157         derive [HashStable]
1158         DEBUG_FORMAT = "U{}",
1159     }
1160 }
1161
1162 impl UniverseIndex {
1163     pub const ROOT: UniverseIndex = UniverseIndex::from_u32(0);
1164
1165     /// Returns the "next" universe index in order -- this new index
1166     /// is considered to extend all previous universes. This
1167     /// corresponds to entering a `forall` quantifier. So, for
1168     /// example, suppose we have this type in universe `U`:
1169     ///
1170     /// ```
1171     /// for<'a> fn(&'a u32)
1172     /// ```
1173     ///
1174     /// Once we "enter" into this `for<'a>` quantifier, we are in a
1175     /// new universe that extends `U` -- in this new universe, we can
1176     /// name the region `'a`, but that region was not nameable from
1177     /// `U` because it was not in scope there.
1178     pub fn next_universe(self) -> UniverseIndex {
1179         UniverseIndex::from_u32(self.private.checked_add(1).unwrap())
1180     }
1181
1182     /// Returns `true` if `self` can name a name from `other` -- in other words,
1183     /// if the set of names in `self` is a superset of those in
1184     /// `other` (`self >= other`).
1185     pub fn can_name(self, other: UniverseIndex) -> bool {
1186         self.private >= other.private
1187     }
1188
1189     /// Returns `true` if `self` cannot name some names from `other` -- in other
1190     /// words, if the set of names in `self` is a strict subset of
1191     /// those in `other` (`self < other`).
1192     pub fn cannot_name(self, other: UniverseIndex) -> bool {
1193         self.private < other.private
1194     }
1195 }
1196
1197 /// The "placeholder index" fully defines a placeholder region, type, or const. Placeholders are
1198 /// identified by both a universe, as well as a name residing within that universe. Distinct bound
1199 /// regions/types/consts within the same universe simply have an unknown relationship to one
1200 /// another.
1201 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TyEncodable, TyDecodable, PartialOrd, Ord)]
1202 pub struct Placeholder<T> {
1203     pub universe: UniverseIndex,
1204     pub name: T,
1205 }
1206
1207 impl<'a, T> HashStable<StableHashingContext<'a>> for Placeholder<T>
1208 where
1209     T: HashStable<StableHashingContext<'a>>,
1210 {
1211     fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
1212         self.universe.hash_stable(hcx, hasher);
1213         self.name.hash_stable(hcx, hasher);
1214     }
1215 }
1216
1217 pub type PlaceholderRegion = Placeholder<BoundRegionKind>;
1218
1219 pub type PlaceholderType = Placeholder<BoundVar>;
1220
1221 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable)]
1222 #[derive(TyEncodable, TyDecodable, PartialOrd, Ord)]
1223 pub struct BoundConst<'tcx> {
1224     pub var: BoundVar,
1225     pub ty: Ty<'tcx>,
1226 }
1227
1228 pub type PlaceholderConst<'tcx> = Placeholder<BoundConst<'tcx>>;
1229
1230 /// A `DefId` which, in case it is a const argument, is potentially bundled with
1231 /// the `DefId` of the generic parameter it instantiates.
1232 ///
1233 /// This is used to avoid calls to `type_of` for const arguments during typeck
1234 /// which cause cycle errors.
1235 ///
1236 /// ```rust
1237 /// struct A;
1238 /// impl A {
1239 ///     fn foo<const N: usize>(&self) -> [u8; N] { [0; N] }
1240 ///     //           ^ const parameter
1241 /// }
1242 /// struct B;
1243 /// impl B {
1244 ///     fn foo<const M: u8>(&self) -> usize { 42 }
1245 ///     //           ^ const parameter
1246 /// }
1247 ///
1248 /// fn main() {
1249 ///     let a = A;
1250 ///     let _b = a.foo::<{ 3 + 7 }>();
1251 ///     //               ^^^^^^^^^ const argument
1252 /// }
1253 /// ```
1254 ///
1255 /// Let's look at the call `a.foo::<{ 3 + 7 }>()` here. We do not know
1256 /// which `foo` is used until we know the type of `a`.
1257 ///
1258 /// We only know the type of `a` once we are inside of `typeck(main)`.
1259 /// We also end up normalizing the type of `_b` during `typeck(main)` which
1260 /// requires us to evaluate the const argument.
1261 ///
1262 /// To evaluate that const argument we need to know its type,
1263 /// which we would get using `type_of(const_arg)`. This requires us to
1264 /// resolve `foo` as it can be either `usize` or `u8` in this example.
1265 /// However, resolving `foo` once again requires `typeck(main)` to get the type of `a`,
1266 /// which results in a cycle.
1267 ///
1268 /// In short we must not call `type_of(const_arg)` during `typeck(main)`.
1269 ///
1270 /// When first creating the `ty::Const` of the const argument inside of `typeck` we have
1271 /// already resolved `foo` so we know which const parameter this argument instantiates.
1272 /// This means that we also know the expected result of `type_of(const_arg)` even if we
1273 /// aren't allowed to call that query: it is equal to `type_of(const_param)` which is
1274 /// trivial to compute.
1275 ///
1276 /// If we now want to use that constant in a place which potentially needs its type
1277 /// we also pass the type of its `const_param`. This is the point of `WithOptConstParam`,
1278 /// except that instead of a `Ty` we bundle the `DefId` of the const parameter.
1279 /// Meaning that we need to use `type_of(const_param_did)` if `const_param_did` is `Some`
1280 /// to get the type of `did`.
1281 #[derive(Copy, Clone, Debug, TypeFoldable, Lift, TyEncodable, TyDecodable)]
1282 #[derive(PartialEq, Eq, PartialOrd, Ord)]
1283 #[derive(Hash, HashStable)]
1284 pub struct WithOptConstParam<T> {
1285     pub did: T,
1286     /// The `DefId` of the corresponding generic parameter in case `did` is
1287     /// a const argument.
1288     ///
1289     /// Note that even if `did` is a const argument, this may still be `None`.
1290     /// All queries taking `WithOptConstParam` start by calling `tcx.opt_const_param_of(def.did)`
1291     /// to potentially update `param_did` in the case it is `None`.
1292     pub const_param_did: Option<DefId>,
1293 }
1294
1295 impl<T> WithOptConstParam<T> {
1296     /// Creates a new `WithOptConstParam` setting `const_param_did` to `None`.
1297     #[inline(always)]
1298     pub fn unknown(did: T) -> WithOptConstParam<T> {
1299         WithOptConstParam { did, const_param_did: None }
1300     }
1301 }
1302
1303 impl WithOptConstParam<LocalDefId> {
1304     /// Returns `Some((did, param_did))` if `def_id` is a const argument,
1305     /// `None` otherwise.
1306     #[inline(always)]
1307     pub fn try_lookup(did: LocalDefId, tcx: TyCtxt<'_>) -> Option<(LocalDefId, DefId)> {
1308         tcx.opt_const_param_of(did).map(|param_did| (did, param_did))
1309     }
1310
1311     /// In case `self` is unknown but `self.did` is a const argument, this returns
1312     /// a `WithOptConstParam` with the correct `const_param_did`.
1313     #[inline(always)]
1314     pub fn try_upgrade(self, tcx: TyCtxt<'_>) -> Option<WithOptConstParam<LocalDefId>> {
1315         if self.const_param_did.is_none() {
1316             if let const_param_did @ Some(_) = tcx.opt_const_param_of(self.did) {
1317                 return Some(WithOptConstParam { did: self.did, const_param_did });
1318             }
1319         }
1320
1321         None
1322     }
1323
1324     pub fn to_global(self) -> WithOptConstParam<DefId> {
1325         WithOptConstParam { did: self.did.to_def_id(), const_param_did: self.const_param_did }
1326     }
1327
1328     pub fn def_id_for_type_of(self) -> DefId {
1329         if let Some(did) = self.const_param_did { did } else { self.did.to_def_id() }
1330     }
1331 }
1332
1333 impl WithOptConstParam<DefId> {
1334     pub fn as_local(self) -> Option<WithOptConstParam<LocalDefId>> {
1335         self.did
1336             .as_local()
1337             .map(|did| WithOptConstParam { did, const_param_did: self.const_param_did })
1338     }
1339
1340     pub fn as_const_arg(self) -> Option<(LocalDefId, DefId)> {
1341         if let Some(param_did) = self.const_param_did {
1342             if let Some(did) = self.did.as_local() {
1343                 return Some((did, param_did));
1344             }
1345         }
1346
1347         None
1348     }
1349
1350     pub fn is_local(self) -> bool {
1351         self.did.is_local()
1352     }
1353
1354     pub fn def_id_for_type_of(self) -> DefId {
1355         self.const_param_did.unwrap_or(self.did)
1356     }
1357 }
1358
1359 /// When type checking, we use the `ParamEnv` to track
1360 /// details about the set of where-clauses that are in scope at this
1361 /// particular point.
1362 #[derive(Copy, Clone, Hash, PartialEq, Eq)]
1363 pub struct ParamEnv<'tcx> {
1364     /// This packs both caller bounds and the reveal enum into one pointer.
1365     ///
1366     /// Caller bounds are `Obligation`s that the caller must satisfy. This is
1367     /// basically the set of bounds on the in-scope type parameters, translated
1368     /// into `Obligation`s, and elaborated and normalized.
1369     ///
1370     /// Use the `caller_bounds()` method to access.
1371     ///
1372     /// Typically, this is `Reveal::UserFacing`, but during codegen we
1373     /// want `Reveal::All`.
1374     ///
1375     /// Note: This is packed, use the reveal() method to access it.
1376     packed: CopyTaggedPtr<&'tcx List<Predicate<'tcx>>, ParamTag, true>,
1377 }
1378
1379 #[derive(Copy, Clone)]
1380 struct ParamTag {
1381     reveal: traits::Reveal,
1382     constness: hir::Constness,
1383 }
1384
1385 unsafe impl rustc_data_structures::tagged_ptr::Tag for ParamTag {
1386     const BITS: usize = 2;
1387     #[inline]
1388     fn into_usize(self) -> usize {
1389         match self {
1390             Self { reveal: traits::Reveal::UserFacing, constness: hir::Constness::NotConst } => 0,
1391             Self { reveal: traits::Reveal::All, constness: hir::Constness::NotConst } => 1,
1392             Self { reveal: traits::Reveal::UserFacing, constness: hir::Constness::Const } => 2,
1393             Self { reveal: traits::Reveal::All, constness: hir::Constness::Const } => 3,
1394         }
1395     }
1396     #[inline]
1397     unsafe fn from_usize(ptr: usize) -> Self {
1398         match ptr {
1399             0 => Self { reveal: traits::Reveal::UserFacing, constness: hir::Constness::NotConst },
1400             1 => Self { reveal: traits::Reveal::All, constness: hir::Constness::NotConst },
1401             2 => Self { reveal: traits::Reveal::UserFacing, constness: hir::Constness::Const },
1402             3 => Self { reveal: traits::Reveal::All, constness: hir::Constness::Const },
1403             _ => std::hint::unreachable_unchecked(),
1404         }
1405     }
1406 }
1407
1408 impl<'tcx> fmt::Debug for ParamEnv<'tcx> {
1409     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1410         f.debug_struct("ParamEnv")
1411             .field("caller_bounds", &self.caller_bounds())
1412             .field("reveal", &self.reveal())
1413             .field("constness", &self.constness())
1414             .finish()
1415     }
1416 }
1417
1418 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for ParamEnv<'tcx> {
1419     fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
1420         self.caller_bounds().hash_stable(hcx, hasher);
1421         self.reveal().hash_stable(hcx, hasher);
1422         self.constness().hash_stable(hcx, hasher);
1423     }
1424 }
1425
1426 impl<'tcx> TypeFoldable<'tcx> for ParamEnv<'tcx> {
1427     fn try_super_fold_with<F: ty::fold::FallibleTypeFolder<'tcx>>(
1428         self,
1429         folder: &mut F,
1430     ) -> Result<Self, F::Error> {
1431         Ok(ParamEnv::new(
1432             self.caller_bounds().try_fold_with(folder)?,
1433             self.reveal().try_fold_with(folder)?,
1434             self.constness().try_fold_with(folder)?,
1435         ))
1436     }
1437
1438     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> ControlFlow<V::BreakTy> {
1439         self.caller_bounds().visit_with(visitor)?;
1440         self.reveal().visit_with(visitor)?;
1441         self.constness().visit_with(visitor)
1442     }
1443 }
1444
1445 impl<'tcx> ParamEnv<'tcx> {
1446     /// Construct a trait environment suitable for contexts where
1447     /// there are no where-clauses in scope. Hidden types (like `impl
1448     /// Trait`) are left hidden, so this is suitable for ordinary
1449     /// type-checking.
1450     #[inline]
1451     pub fn empty() -> Self {
1452         Self::new(List::empty(), Reveal::UserFacing, hir::Constness::NotConst)
1453     }
1454
1455     #[inline]
1456     pub fn caller_bounds(self) -> &'tcx List<Predicate<'tcx>> {
1457         self.packed.pointer()
1458     }
1459
1460     #[inline]
1461     pub fn reveal(self) -> traits::Reveal {
1462         self.packed.tag().reveal
1463     }
1464
1465     #[inline]
1466     pub fn constness(self) -> hir::Constness {
1467         self.packed.tag().constness
1468     }
1469
1470     #[inline]
1471     pub fn is_const(self) -> bool {
1472         self.packed.tag().constness == hir::Constness::Const
1473     }
1474
1475     /// Construct a trait environment with no where-clauses in scope
1476     /// where the values of all `impl Trait` and other hidden types
1477     /// are revealed. This is suitable for monomorphized, post-typeck
1478     /// environments like codegen or doing optimizations.
1479     ///
1480     /// N.B., if you want to have predicates in scope, use `ParamEnv::new`,
1481     /// or invoke `param_env.with_reveal_all()`.
1482     #[inline]
1483     pub fn reveal_all() -> Self {
1484         Self::new(List::empty(), Reveal::All, hir::Constness::NotConst)
1485     }
1486
1487     /// Construct a trait environment with the given set of predicates.
1488     #[inline]
1489     pub fn new(
1490         caller_bounds: &'tcx List<Predicate<'tcx>>,
1491         reveal: Reveal,
1492         constness: hir::Constness,
1493     ) -> Self {
1494         ty::ParamEnv { packed: CopyTaggedPtr::new(caller_bounds, ParamTag { reveal, constness }) }
1495     }
1496
1497     pub fn with_user_facing(mut self) -> Self {
1498         self.packed.set_tag(ParamTag { reveal: Reveal::UserFacing, ..self.packed.tag() });
1499         self
1500     }
1501
1502     #[inline]
1503     pub fn with_constness(mut self, constness: hir::Constness) -> Self {
1504         self.packed.set_tag(ParamTag { constness, ..self.packed.tag() });
1505         self
1506     }
1507
1508     #[inline]
1509     pub fn with_const(mut self) -> Self {
1510         self.packed.set_tag(ParamTag { constness: hir::Constness::Const, ..self.packed.tag() });
1511         self
1512     }
1513
1514     #[inline]
1515     pub fn without_const(mut self) -> Self {
1516         self.packed.set_tag(ParamTag { constness: hir::Constness::NotConst, ..self.packed.tag() });
1517         self
1518     }
1519
1520     #[inline]
1521     pub fn remap_constness_with(&mut self, mut constness: ty::BoundConstness) {
1522         *self = self.with_constness(constness.and(self.constness()))
1523     }
1524
1525     /// Returns a new parameter environment with the same clauses, but
1526     /// which "reveals" the true results of projections in all cases
1527     /// (even for associated types that are specializable). This is
1528     /// the desired behavior during codegen and certain other special
1529     /// contexts; normally though we want to use `Reveal::UserFacing`,
1530     /// which is the default.
1531     /// All opaque types in the caller_bounds of the `ParamEnv`
1532     /// will be normalized to their underlying types.
1533     /// See PR #65989 and issue #65918 for more details
1534     pub fn with_reveal_all_normalized(self, tcx: TyCtxt<'tcx>) -> Self {
1535         if self.packed.tag().reveal == traits::Reveal::All {
1536             return self;
1537         }
1538
1539         ParamEnv::new(
1540             tcx.normalize_opaque_types(self.caller_bounds()),
1541             Reveal::All,
1542             self.constness(),
1543         )
1544     }
1545
1546     /// Returns this same environment but with no caller bounds.
1547     #[inline]
1548     pub fn without_caller_bounds(self) -> Self {
1549         Self::new(List::empty(), self.reveal(), self.constness())
1550     }
1551
1552     /// Creates a suitable environment in which to perform trait
1553     /// queries on the given value. When type-checking, this is simply
1554     /// the pair of the environment plus value. But when reveal is set to
1555     /// All, then if `value` does not reference any type parameters, we will
1556     /// pair it with the empty environment. This improves caching and is generally
1557     /// invisible.
1558     ///
1559     /// N.B., we preserve the environment when type-checking because it
1560     /// is possible for the user to have wacky where-clauses like
1561     /// `where Box<u32>: Copy`, which are clearly never
1562     /// satisfiable. We generally want to behave as if they were true,
1563     /// although the surrounding function is never reachable.
1564     pub fn and<T: TypeFoldable<'tcx>>(self, value: T) -> ParamEnvAnd<'tcx, T> {
1565         match self.reveal() {
1566             Reveal::UserFacing => ParamEnvAnd { param_env: self, value },
1567
1568             Reveal::All => {
1569                 if value.is_global() {
1570                     ParamEnvAnd { param_env: self.without_caller_bounds(), value }
1571                 } else {
1572                     ParamEnvAnd { param_env: self, value }
1573                 }
1574             }
1575         }
1576     }
1577 }
1578
1579 // FIXME(ecstaticmorse): Audit all occurrences of `without_const().to_predicate(tcx)` to ensure that
1580 // the constness of trait bounds is being propagated correctly.
1581 impl<'tcx> PolyTraitRef<'tcx> {
1582     #[inline]
1583     pub fn with_constness(self, constness: BoundConstness) -> PolyTraitPredicate<'tcx> {
1584         self.map_bound(|trait_ref| ty::TraitPredicate {
1585             trait_ref,
1586             constness,
1587             polarity: ty::ImplPolarity::Positive,
1588         })
1589     }
1590
1591     #[inline]
1592     pub fn without_const(self) -> PolyTraitPredicate<'tcx> {
1593         self.with_constness(BoundConstness::NotConst)
1594     }
1595 }
1596
1597 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TypeFoldable)]
1598 pub struct ParamEnvAnd<'tcx, T> {
1599     pub param_env: ParamEnv<'tcx>,
1600     pub value: T,
1601 }
1602
1603 impl<'tcx, T> ParamEnvAnd<'tcx, T> {
1604     pub fn into_parts(self) -> (ParamEnv<'tcx>, T) {
1605         (self.param_env, self.value)
1606     }
1607
1608     #[inline]
1609     pub fn without_const(mut self) -> Self {
1610         self.param_env = self.param_env.without_const();
1611         self
1612     }
1613 }
1614
1615 impl<'a, 'tcx, T> HashStable<StableHashingContext<'a>> for ParamEnvAnd<'tcx, T>
1616 where
1617     T: HashStable<StableHashingContext<'a>>,
1618 {
1619     fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
1620         let ParamEnvAnd { ref param_env, ref value } = *self;
1621
1622         param_env.hash_stable(hcx, hasher);
1623         value.hash_stable(hcx, hasher);
1624     }
1625 }
1626
1627 #[derive(Copy, Clone, Debug, HashStable)]
1628 pub struct Destructor {
1629     /// The `DefId` of the destructor method
1630     pub did: DefId,
1631     /// The constness of the destructor method
1632     pub constness: hir::Constness,
1633 }
1634
1635 bitflags! {
1636     #[derive(HashStable, TyEncodable, TyDecodable)]
1637     pub struct VariantFlags: u32 {
1638         const NO_VARIANT_FLAGS        = 0;
1639         /// Indicates whether the field list of this variant is `#[non_exhaustive]`.
1640         const IS_FIELD_LIST_NON_EXHAUSTIVE = 1 << 0;
1641         /// Indicates whether this variant was obtained as part of recovering from
1642         /// a syntactic error. May be incomplete or bogus.
1643         const IS_RECOVERED = 1 << 1;
1644     }
1645 }
1646
1647 /// Definition of a variant -- a struct's fields or an enum variant.
1648 #[derive(Debug, HashStable, TyEncodable, TyDecodable)]
1649 pub struct VariantDef {
1650     /// `DefId` that identifies the variant itself.
1651     /// If this variant belongs to a struct or union, then this is a copy of its `DefId`.
1652     pub def_id: DefId,
1653     /// `DefId` that identifies the variant's constructor.
1654     /// If this variant is a struct variant, then this is `None`.
1655     pub ctor_def_id: Option<DefId>,
1656     /// Variant or struct name.
1657     pub name: Symbol,
1658     /// Discriminant of this variant.
1659     pub discr: VariantDiscr,
1660     /// Fields of this variant.
1661     pub fields: Vec<FieldDef>,
1662     /// Type of constructor of variant.
1663     pub ctor_kind: CtorKind,
1664     /// Flags of the variant (e.g. is field list non-exhaustive)?
1665     flags: VariantFlags,
1666 }
1667
1668 impl VariantDef {
1669     /// Creates a new `VariantDef`.
1670     ///
1671     /// `variant_did` is the `DefId` that identifies the enum variant (if this `VariantDef`
1672     /// represents an enum variant).
1673     ///
1674     /// `ctor_did` is the `DefId` that identifies the constructor of unit or
1675     /// tuple-variants/structs. If this is a `struct`-variant then this should be `None`.
1676     ///
1677     /// `parent_did` is the `DefId` of the `AdtDef` representing the enum or struct that
1678     /// owns this variant. It is used for checking if a struct has `#[non_exhaustive]` w/out having
1679     /// to go through the redirect of checking the ctor's attributes - but compiling a small crate
1680     /// requires loading the `AdtDef`s for all the structs in the universe (e.g., coherence for any
1681     /// built-in trait), and we do not want to load attributes twice.
1682     ///
1683     /// If someone speeds up attribute loading to not be a performance concern, they can
1684     /// remove this hack and use the constructor `DefId` everywhere.
1685     pub fn new(
1686         name: Symbol,
1687         variant_did: Option<DefId>,
1688         ctor_def_id: Option<DefId>,
1689         discr: VariantDiscr,
1690         fields: Vec<FieldDef>,
1691         ctor_kind: CtorKind,
1692         adt_kind: AdtKind,
1693         parent_did: DefId,
1694         recovered: bool,
1695         is_field_list_non_exhaustive: bool,
1696     ) -> Self {
1697         debug!(
1698             "VariantDef::new(name = {:?}, variant_did = {:?}, ctor_def_id = {:?}, discr = {:?},
1699              fields = {:?}, ctor_kind = {:?}, adt_kind = {:?}, parent_did = {:?})",
1700             name, variant_did, ctor_def_id, discr, fields, ctor_kind, adt_kind, parent_did,
1701         );
1702
1703         let mut flags = VariantFlags::NO_VARIANT_FLAGS;
1704         if is_field_list_non_exhaustive {
1705             flags |= VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE;
1706         }
1707
1708         if recovered {
1709             flags |= VariantFlags::IS_RECOVERED;
1710         }
1711
1712         VariantDef {
1713             def_id: variant_did.unwrap_or(parent_did),
1714             ctor_def_id,
1715             name,
1716             discr,
1717             fields,
1718             ctor_kind,
1719             flags,
1720         }
1721     }
1722
1723     /// Is this field list non-exhaustive?
1724     #[inline]
1725     pub fn is_field_list_non_exhaustive(&self) -> bool {
1726         self.flags.intersects(VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE)
1727     }
1728
1729     /// Was this variant obtained as part of recovering from a syntactic error?
1730     #[inline]
1731     pub fn is_recovered(&self) -> bool {
1732         self.flags.intersects(VariantFlags::IS_RECOVERED)
1733     }
1734
1735     /// Computes the `Ident` of this variant by looking up the `Span`
1736     pub fn ident(&self, tcx: TyCtxt<'_>) -> Ident {
1737         Ident::new(self.name, tcx.def_ident_span(self.def_id).unwrap())
1738     }
1739 }
1740
1741 #[derive(Copy, Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
1742 pub enum VariantDiscr {
1743     /// Explicit value for this variant, i.e., `X = 123`.
1744     /// The `DefId` corresponds to the embedded constant.
1745     Explicit(DefId),
1746
1747     /// The previous variant's discriminant plus one.
1748     /// For efficiency reasons, the distance from the
1749     /// last `Explicit` discriminant is being stored,
1750     /// or `0` for the first variant, if it has none.
1751     Relative(u32),
1752 }
1753
1754 #[derive(Debug, HashStable, TyEncodable, TyDecodable)]
1755 pub struct FieldDef {
1756     pub did: DefId,
1757     pub name: Symbol,
1758     pub vis: Visibility,
1759 }
1760
1761 bitflags! {
1762     #[derive(TyEncodable, TyDecodable, Default, HashStable)]
1763     pub struct ReprFlags: u8 {
1764         const IS_C               = 1 << 0;
1765         const IS_SIMD            = 1 << 1;
1766         const IS_TRANSPARENT     = 1 << 2;
1767         // Internal only for now. If true, don't reorder fields.
1768         const IS_LINEAR          = 1 << 3;
1769         // If true, don't expose any niche to type's context.
1770         const HIDE_NICHE         = 1 << 4;
1771         // If true, the type's layout can be randomized using
1772         // the seed stored in `ReprOptions.layout_seed`
1773         const RANDOMIZE_LAYOUT   = 1 << 5;
1774         // Any of these flags being set prevent field reordering optimisation.
1775         const IS_UNOPTIMISABLE   = ReprFlags::IS_C.bits
1776                                  | ReprFlags::IS_SIMD.bits
1777                                  | ReprFlags::IS_LINEAR.bits;
1778     }
1779 }
1780
1781 /// Represents the repr options provided by the user,
1782 #[derive(Copy, Clone, Debug, Eq, PartialEq, TyEncodable, TyDecodable, Default, HashStable)]
1783 pub struct ReprOptions {
1784     pub int: Option<attr::IntType>,
1785     pub align: Option<Align>,
1786     pub pack: Option<Align>,
1787     pub flags: ReprFlags,
1788     /// The seed to be used for randomizing a type's layout
1789     ///
1790     /// Note: This could technically be a `[u8; 16]` (a `u128`) which would
1791     /// be the "most accurate" hash as it'd encompass the item and crate
1792     /// hash without loss, but it does pay the price of being larger.
1793     /// Everything's a tradeoff, a `u64` seed should be sufficient for our
1794     /// purposes (primarily `-Z randomize-layout`)
1795     pub field_shuffle_seed: u64,
1796 }
1797
1798 impl ReprOptions {
1799     pub fn new(tcx: TyCtxt<'_>, did: DefId) -> ReprOptions {
1800         let mut flags = ReprFlags::empty();
1801         let mut size = None;
1802         let mut max_align: Option<Align> = None;
1803         let mut min_pack: Option<Align> = None;
1804
1805         // Generate a deterministically-derived seed from the item's path hash
1806         // to allow for cross-crate compilation to actually work
1807         let mut field_shuffle_seed = tcx.def_path_hash(did).0.to_smaller_hash();
1808
1809         // If the user defined a custom seed for layout randomization, xor the item's
1810         // path hash with the user defined seed, this will allowing determinism while
1811         // still allowing users to further randomize layout generation for e.g. fuzzing
1812         if let Some(user_seed) = tcx.sess.opts.debugging_opts.layout_seed {
1813             field_shuffle_seed ^= user_seed;
1814         }
1815
1816         for attr in tcx.get_attrs(did).iter() {
1817             for r in attr::find_repr_attrs(&tcx.sess, attr) {
1818                 flags.insert(match r {
1819                     attr::ReprC => ReprFlags::IS_C,
1820                     attr::ReprPacked(pack) => {
1821                         let pack = Align::from_bytes(pack as u64).unwrap();
1822                         min_pack = Some(if let Some(min_pack) = min_pack {
1823                             min_pack.min(pack)
1824                         } else {
1825                             pack
1826                         });
1827                         ReprFlags::empty()
1828                     }
1829                     attr::ReprTransparent => ReprFlags::IS_TRANSPARENT,
1830                     attr::ReprNoNiche => ReprFlags::HIDE_NICHE,
1831                     attr::ReprSimd => ReprFlags::IS_SIMD,
1832                     attr::ReprInt(i) => {
1833                         size = Some(i);
1834                         ReprFlags::empty()
1835                     }
1836                     attr::ReprAlign(align) => {
1837                         max_align = max_align.max(Some(Align::from_bytes(align as u64).unwrap()));
1838                         ReprFlags::empty()
1839                     }
1840                 });
1841             }
1842         }
1843
1844         // If `-Z randomize-layout` was enabled for the type definition then we can
1845         // consider performing layout randomization
1846         if tcx.sess.opts.debugging_opts.randomize_layout {
1847             flags.insert(ReprFlags::RANDOMIZE_LAYOUT);
1848         }
1849
1850         // This is here instead of layout because the choice must make it into metadata.
1851         if !tcx.consider_optimizing(|| format!("Reorder fields of {:?}", tcx.def_path_str(did))) {
1852             flags.insert(ReprFlags::IS_LINEAR);
1853         }
1854
1855         Self { int: size, align: max_align, pack: min_pack, flags, field_shuffle_seed }
1856     }
1857
1858     #[inline]
1859     pub fn simd(&self) -> bool {
1860         self.flags.contains(ReprFlags::IS_SIMD)
1861     }
1862
1863     #[inline]
1864     pub fn c(&self) -> bool {
1865         self.flags.contains(ReprFlags::IS_C)
1866     }
1867
1868     #[inline]
1869     pub fn packed(&self) -> bool {
1870         self.pack.is_some()
1871     }
1872
1873     #[inline]
1874     pub fn transparent(&self) -> bool {
1875         self.flags.contains(ReprFlags::IS_TRANSPARENT)
1876     }
1877
1878     #[inline]
1879     pub fn linear(&self) -> bool {
1880         self.flags.contains(ReprFlags::IS_LINEAR)
1881     }
1882
1883     #[inline]
1884     pub fn hide_niche(&self) -> bool {
1885         self.flags.contains(ReprFlags::HIDE_NICHE)
1886     }
1887
1888     /// Returns the discriminant type, given these `repr` options.
1889     /// This must only be called on enums!
1890     pub fn discr_type(&self) -> attr::IntType {
1891         self.int.unwrap_or(attr::SignedInt(ast::IntTy::Isize))
1892     }
1893
1894     /// Returns `true` if this `#[repr()]` should inhabit "smart enum
1895     /// layout" optimizations, such as representing `Foo<&T>` as a
1896     /// single pointer.
1897     pub fn inhibit_enum_layout_opt(&self) -> bool {
1898         self.c() || self.int.is_some()
1899     }
1900
1901     /// Returns `true` if this `#[repr()]` should inhibit struct field reordering
1902     /// optimizations, such as with `repr(C)`, `repr(packed(1))`, or `repr(<int>)`.
1903     pub fn inhibit_struct_field_reordering_opt(&self) -> bool {
1904         if let Some(pack) = self.pack {
1905             if pack.bytes() == 1 {
1906                 return true;
1907             }
1908         }
1909
1910         self.flags.intersects(ReprFlags::IS_UNOPTIMISABLE) || self.int.is_some()
1911     }
1912
1913     /// Returns `true` if this type is valid for reordering and `-Z randomize-layout`
1914     /// was enabled for its declaration crate
1915     pub fn can_randomize_type_layout(&self) -> bool {
1916         !self.inhibit_struct_field_reordering_opt()
1917             && self.flags.contains(ReprFlags::RANDOMIZE_LAYOUT)
1918     }
1919
1920     /// Returns `true` if this `#[repr()]` should inhibit union ABI optimisations.
1921     pub fn inhibit_union_abi_opt(&self) -> bool {
1922         self.c()
1923     }
1924 }
1925
1926 impl<'tcx> FieldDef {
1927     /// Returns the type of this field. The resulting type is not normalized. The `subst` is
1928     /// typically obtained via the second field of [`TyKind::Adt`].
1929     pub fn ty(&self, tcx: TyCtxt<'tcx>, subst: SubstsRef<'tcx>) -> Ty<'tcx> {
1930         tcx.type_of(self.did).subst(tcx, subst)
1931     }
1932
1933     /// Computes the `Ident` of this variant by looking up the `Span`
1934     pub fn ident(&self, tcx: TyCtxt<'_>) -> Ident {
1935         Ident::new(self.name, tcx.def_ident_span(self.did).unwrap())
1936     }
1937 }
1938
1939 pub type Attributes<'tcx> = &'tcx [ast::Attribute];
1940
1941 #[derive(Debug, PartialEq, Eq)]
1942 pub enum ImplOverlapKind {
1943     /// These impls are always allowed to overlap.
1944     Permitted {
1945         /// Whether or not the impl is permitted due to the trait being a `#[marker]` trait
1946         marker: bool,
1947     },
1948     /// These impls are allowed to overlap, but that raises
1949     /// an issue #33140 future-compatibility warning.
1950     ///
1951     /// Some background: in Rust 1.0, the trait-object types `Send + Sync` (today's
1952     /// `dyn Send + Sync`) and `Sync + Send` (now `dyn Sync + Send`) were different.
1953     ///
1954     /// The widely-used version 0.1.0 of the crate `traitobject` had accidentally relied
1955     /// that difference, making what reduces to the following set of impls:
1956     ///
1957     /// ```
1958     /// trait Trait {}
1959     /// impl Trait for dyn Send + Sync {}
1960     /// impl Trait for dyn Sync + Send {}
1961     /// ```
1962     ///
1963     /// Obviously, once we made these types be identical, that code causes a coherence
1964     /// error and a fairly big headache for us. However, luckily for us, the trait
1965     /// `Trait` used in this case is basically a marker trait, and therefore having
1966     /// overlapping impls for it is sound.
1967     ///
1968     /// To handle this, we basically regard the trait as a marker trait, with an additional
1969     /// future-compatibility warning. To avoid accidentally "stabilizing" this feature,
1970     /// it has the following restrictions:
1971     ///
1972     /// 1. The trait must indeed be a marker-like trait (i.e., no items), and must be
1973     /// positive impls.
1974     /// 2. The trait-ref of both impls must be equal.
1975     /// 3. The trait-ref of both impls must be a trait object type consisting only of
1976     /// marker traits.
1977     /// 4. Neither of the impls can have any where-clauses.
1978     ///
1979     /// Once `traitobject` 0.1.0 is no longer an active concern, this hack can be removed.
1980     Issue33140,
1981 }
1982
1983 impl<'tcx> TyCtxt<'tcx> {
1984     pub fn typeck_body(self, body: hir::BodyId) -> &'tcx TypeckResults<'tcx> {
1985         self.typeck(self.hir().body_owner_def_id(body))
1986     }
1987
1988     pub fn provided_trait_methods(self, id: DefId) -> impl 'tcx + Iterator<Item = &'tcx AssocItem> {
1989         self.associated_items(id)
1990             .in_definition_order()
1991             .filter(|item| item.kind == AssocKind::Fn && item.defaultness.has_value())
1992     }
1993
1994     fn opt_item_name(self, def_id: DefId) -> Option<Symbol> {
1995         if def_id.index == CRATE_DEF_INDEX {
1996             Some(self.crate_name(def_id.krate))
1997         } else {
1998             let def_key = self.def_key(def_id);
1999             match def_key.disambiguated_data.data {
2000                 // The name of a constructor is that of its parent.
2001                 rustc_hir::definitions::DefPathData::Ctor => self
2002                     .opt_item_name(DefId { krate: def_id.krate, index: def_key.parent.unwrap() }),
2003                 // The name of opaque types only exists in HIR.
2004                 rustc_hir::definitions::DefPathData::ImplTrait
2005                     if let Some(def_id) = def_id.as_local() =>
2006                     self.hir().opt_name(self.hir().local_def_id_to_hir_id(def_id)),
2007                 _ => def_key.get_opt_name(),
2008             }
2009         }
2010     }
2011
2012     /// Look up the name of a definition across crates. This does not look at HIR.
2013     ///
2014     /// When possible, this function should be used for cross-crate lookups over
2015     /// [`opt_item_name`] to avoid invalidating the incremental cache. If you
2016     /// need to handle items without a name, or HIR items that will not be
2017     /// serialized cross-crate, or if you need the span of the item, use
2018     /// [`opt_item_name`] instead.
2019     ///
2020     /// [`opt_item_name`]: Self::opt_item_name
2021     pub fn item_name(self, id: DefId) -> Symbol {
2022         // Look at cross-crate items first to avoid invalidating the incremental cache
2023         // unless we have to.
2024         self.opt_item_name(id).unwrap_or_else(|| {
2025             bug!("item_name: no name for {:?}", self.def_path(id));
2026         })
2027     }
2028
2029     /// Look up the name and span of a definition.
2030     ///
2031     /// See [`item_name`][Self::item_name] for more information.
2032     pub fn opt_item_ident(self, def_id: DefId) -> Option<Ident> {
2033         let def = self.opt_item_name(def_id)?;
2034         let span = def_id
2035             .as_local()
2036             .and_then(|id| self.def_ident_span(id))
2037             .unwrap_or(rustc_span::DUMMY_SP);
2038         Some(Ident::new(def, span))
2039     }
2040
2041     pub fn opt_associated_item(self, def_id: DefId) -> Option<&'tcx AssocItem> {
2042         if let DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy = self.def_kind(def_id) {
2043             Some(self.associated_item(def_id))
2044         } else {
2045             None
2046         }
2047     }
2048
2049     pub fn field_index(self, hir_id: hir::HirId, typeck_results: &TypeckResults<'_>) -> usize {
2050         typeck_results.field_indices().get(hir_id).cloned().expect("no index for a field")
2051     }
2052
2053     pub fn find_field_index(self, ident: Ident, variant: &VariantDef) -> Option<usize> {
2054         variant
2055             .fields
2056             .iter()
2057             .position(|field| self.hygienic_eq(ident, field.ident(self), variant.def_id))
2058     }
2059
2060     /// Returns `true` if the impls are the same polarity and the trait either
2061     /// has no items or is annotated `#[marker]` and prevents item overrides.
2062     pub fn impls_are_allowed_to_overlap(
2063         self,
2064         def_id1: DefId,
2065         def_id2: DefId,
2066     ) -> Option<ImplOverlapKind> {
2067         // If either trait impl references an error, they're allowed to overlap,
2068         // as one of them essentially doesn't exist.
2069         if self.impl_trait_ref(def_id1).map_or(false, |tr| tr.references_error())
2070             || self.impl_trait_ref(def_id2).map_or(false, |tr| tr.references_error())
2071         {
2072             return Some(ImplOverlapKind::Permitted { marker: false });
2073         }
2074
2075         match (self.impl_polarity(def_id1), self.impl_polarity(def_id2)) {
2076             (ImplPolarity::Reservation, _) | (_, ImplPolarity::Reservation) => {
2077                 // `#[rustc_reservation_impl]` impls don't overlap with anything
2078                 debug!(
2079                     "impls_are_allowed_to_overlap({:?}, {:?}) = Some(Permitted) (reservations)",
2080                     def_id1, def_id2
2081                 );
2082                 return Some(ImplOverlapKind::Permitted { marker: false });
2083             }
2084             (ImplPolarity::Positive, ImplPolarity::Negative)
2085             | (ImplPolarity::Negative, ImplPolarity::Positive) => {
2086                 // `impl AutoTrait for Type` + `impl !AutoTrait for Type`
2087                 debug!(
2088                     "impls_are_allowed_to_overlap({:?}, {:?}) - None (differing polarities)",
2089                     def_id1, def_id2
2090                 );
2091                 return None;
2092             }
2093             (ImplPolarity::Positive, ImplPolarity::Positive)
2094             | (ImplPolarity::Negative, ImplPolarity::Negative) => {}
2095         };
2096
2097         let is_marker_overlap = {
2098             let is_marker_impl = |def_id: DefId| -> bool {
2099                 let trait_ref = self.impl_trait_ref(def_id);
2100                 trait_ref.map_or(false, |tr| self.trait_def(tr.def_id).is_marker)
2101             };
2102             is_marker_impl(def_id1) && is_marker_impl(def_id2)
2103         };
2104
2105         if is_marker_overlap {
2106             debug!(
2107                 "impls_are_allowed_to_overlap({:?}, {:?}) = Some(Permitted) (marker overlap)",
2108                 def_id1, def_id2
2109             );
2110             Some(ImplOverlapKind::Permitted { marker: true })
2111         } else {
2112             if let Some(self_ty1) = self.issue33140_self_ty(def_id1) {
2113                 if let Some(self_ty2) = self.issue33140_self_ty(def_id2) {
2114                     if self_ty1 == self_ty2 {
2115                         debug!(
2116                             "impls_are_allowed_to_overlap({:?}, {:?}) - issue #33140 HACK",
2117                             def_id1, def_id2
2118                         );
2119                         return Some(ImplOverlapKind::Issue33140);
2120                     } else {
2121                         debug!(
2122                             "impls_are_allowed_to_overlap({:?}, {:?}) - found {:?} != {:?}",
2123                             def_id1, def_id2, self_ty1, self_ty2
2124                         );
2125                     }
2126                 }
2127             }
2128
2129             debug!("impls_are_allowed_to_overlap({:?}, {:?}) = None", def_id1, def_id2);
2130             None
2131         }
2132     }
2133
2134     /// Returns `ty::VariantDef` if `res` refers to a struct,
2135     /// or variant or their constructors, panics otherwise.
2136     pub fn expect_variant_res(self, res: Res) -> &'tcx VariantDef {
2137         match res {
2138             Res::Def(DefKind::Variant, did) => {
2139                 let enum_did = self.parent(did).unwrap();
2140                 self.adt_def(enum_did).variant_with_id(did)
2141             }
2142             Res::Def(DefKind::Struct | DefKind::Union, did) => self.adt_def(did).non_enum_variant(),
2143             Res::Def(DefKind::Ctor(CtorOf::Variant, ..), variant_ctor_did) => {
2144                 let variant_did = self.parent(variant_ctor_did).unwrap();
2145                 let enum_did = self.parent(variant_did).unwrap();
2146                 self.adt_def(enum_did).variant_with_ctor_id(variant_ctor_did)
2147             }
2148             Res::Def(DefKind::Ctor(CtorOf::Struct, ..), ctor_did) => {
2149                 let struct_did = self.parent(ctor_did).expect("struct ctor has no parent");
2150                 self.adt_def(struct_did).non_enum_variant()
2151             }
2152             _ => bug!("expect_variant_res used with unexpected res {:?}", res),
2153         }
2154     }
2155
2156     /// Returns the possibly-auto-generated MIR of a `(DefId, Subst)` pair.
2157     pub fn instance_mir(self, instance: ty::InstanceDef<'tcx>) -> &'tcx Body<'tcx> {
2158         match instance {
2159             ty::InstanceDef::Item(def) => match self.def_kind(def.did) {
2160                 DefKind::Const
2161                 | DefKind::Static(..)
2162                 | DefKind::AssocConst
2163                 | DefKind::Ctor(..)
2164                 | DefKind::AnonConst
2165                 | DefKind::InlineConst => self.mir_for_ctfe_opt_const_arg(def),
2166                 // If the caller wants `mir_for_ctfe` of a function they should not be using
2167                 // `instance_mir`, so we'll assume const fn also wants the optimized version.
2168                 _ => {
2169                     assert_eq!(def.const_param_did, None);
2170                     self.optimized_mir(def.did)
2171                 }
2172             },
2173             ty::InstanceDef::VtableShim(..)
2174             | ty::InstanceDef::ReifyShim(..)
2175             | ty::InstanceDef::Intrinsic(..)
2176             | ty::InstanceDef::FnPtrShim(..)
2177             | ty::InstanceDef::Virtual(..)
2178             | ty::InstanceDef::ClosureOnceShim { .. }
2179             | ty::InstanceDef::DropGlue(..)
2180             | ty::InstanceDef::CloneShim(..) => self.mir_shims(instance),
2181         }
2182     }
2183
2184     /// Gets the attributes of a definition.
2185     pub fn get_attrs(self, did: DefId) -> Attributes<'tcx> {
2186         if let Some(did) = did.as_local() {
2187             self.hir().attrs(self.hir().local_def_id_to_hir_id(did))
2188         } else {
2189             self.item_attrs(did)
2190         }
2191     }
2192
2193     /// Determines whether an item is annotated with an attribute.
2194     pub fn has_attr(self, did: DefId, attr: Symbol) -> bool {
2195         self.sess.contains_name(&self.get_attrs(did), attr)
2196     }
2197
2198     /// Returns `true` if this is an `auto trait`.
2199     pub fn trait_is_auto(self, trait_def_id: DefId) -> bool {
2200         self.trait_def(trait_def_id).has_auto_impl
2201     }
2202
2203     /// Returns layout of a generator. Layout might be unavailable if the
2204     /// generator is tainted by errors.
2205     pub fn generator_layout(self, def_id: DefId) -> Option<&'tcx GeneratorLayout<'tcx>> {
2206         self.optimized_mir(def_id).generator_layout()
2207     }
2208
2209     /// Given the `DefId` of an impl, returns the `DefId` of the trait it implements.
2210     /// If it implements no trait, returns `None`.
2211     pub fn trait_id_of_impl(self, def_id: DefId) -> Option<DefId> {
2212         self.impl_trait_ref(def_id).map(|tr| tr.def_id)
2213     }
2214
2215     /// If the given `DefId` describes a method belonging to an impl, returns the
2216     /// `DefId` of the impl that the method belongs to; otherwise, returns `None`.
2217     pub fn impl_of_method(self, def_id: DefId) -> Option<DefId> {
2218         self.opt_associated_item(def_id).and_then(|trait_item| match trait_item.container {
2219             TraitContainer(_) => None,
2220             ImplContainer(def_id) => Some(def_id),
2221         })
2222     }
2223
2224     /// If the given `DefId` belongs to a trait that was automatically derived, returns `true`.
2225     pub fn is_builtin_derive(self, def_id: DefId) -> bool {
2226         self.has_attr(def_id, sym::automatically_derived)
2227     }
2228
2229     /// Looks up the span of `impl_did` if the impl is local; otherwise returns `Err`
2230     /// with the name of the crate containing the impl.
2231     pub fn span_of_impl(self, impl_did: DefId) -> Result<Span, Symbol> {
2232         if let Some(impl_did) = impl_did.as_local() {
2233             Ok(self.def_span(impl_did))
2234         } else {
2235             Err(self.crate_name(impl_did.krate))
2236         }
2237     }
2238
2239     /// Hygienically compares a use-site name (`use_name`) for a field or an associated item with
2240     /// its supposed definition name (`def_name`). The method also needs `DefId` of the supposed
2241     /// definition's parent/scope to perform comparison.
2242     pub fn hygienic_eq(self, use_name: Ident, def_name: Ident, def_parent_def_id: DefId) -> bool {
2243         // We could use `Ident::eq` here, but we deliberately don't. The name
2244         // comparison fails frequently, and we want to avoid the expensive
2245         // `normalize_to_macros_2_0()` calls required for the span comparison whenever possible.
2246         use_name.name == def_name.name
2247             && use_name
2248                 .span
2249                 .ctxt()
2250                 .hygienic_eq(def_name.span.ctxt(), self.expn_that_defined(def_parent_def_id))
2251     }
2252
2253     pub fn adjust_ident(self, mut ident: Ident, scope: DefId) -> Ident {
2254         ident.span.normalize_to_macros_2_0_and_adjust(self.expn_that_defined(scope));
2255         ident
2256     }
2257
2258     pub fn adjust_ident_and_get_scope(
2259         self,
2260         mut ident: Ident,
2261         scope: DefId,
2262         block: hir::HirId,
2263     ) -> (Ident, DefId) {
2264         let scope = ident
2265             .span
2266             .normalize_to_macros_2_0_and_adjust(self.expn_that_defined(scope))
2267             .and_then(|actual_expansion| actual_expansion.expn_data().parent_module)
2268             .unwrap_or_else(|| self.parent_module(block).to_def_id());
2269         (ident, scope)
2270     }
2271
2272     pub fn is_object_safe(self, key: DefId) -> bool {
2273         self.object_safety_violations(key).is_empty()
2274     }
2275
2276     #[inline]
2277     pub fn is_const_fn_raw(self, def_id: DefId) -> bool {
2278         matches!(self.def_kind(def_id), DefKind::Fn | DefKind::AssocFn | DefKind::Ctor(..))
2279             && self.impl_constness(def_id) == hir::Constness::Const
2280     }
2281 }
2282
2283 /// Yields the parent function's `LocalDefId` if `def_id` is an `impl Trait` definition.
2284 pub fn is_impl_trait_defn(tcx: TyCtxt<'_>, def_id: DefId) -> Option<LocalDefId> {
2285     let def_id = def_id.as_local()?;
2286     if let Node::Item(item) = tcx.hir().get_by_def_id(def_id) {
2287         if let hir::ItemKind::OpaqueTy(ref opaque_ty) = item.kind {
2288             return match opaque_ty.origin {
2289                 hir::OpaqueTyOrigin::FnReturn(parent) | hir::OpaqueTyOrigin::AsyncFn(parent) => {
2290                     Some(parent)
2291                 }
2292                 hir::OpaqueTyOrigin::TyAlias => None,
2293             };
2294         }
2295     }
2296     None
2297 }
2298
2299 pub fn int_ty(ity: ast::IntTy) -> IntTy {
2300     match ity {
2301         ast::IntTy::Isize => IntTy::Isize,
2302         ast::IntTy::I8 => IntTy::I8,
2303         ast::IntTy::I16 => IntTy::I16,
2304         ast::IntTy::I32 => IntTy::I32,
2305         ast::IntTy::I64 => IntTy::I64,
2306         ast::IntTy::I128 => IntTy::I128,
2307     }
2308 }
2309
2310 pub fn uint_ty(uty: ast::UintTy) -> UintTy {
2311     match uty {
2312         ast::UintTy::Usize => UintTy::Usize,
2313         ast::UintTy::U8 => UintTy::U8,
2314         ast::UintTy::U16 => UintTy::U16,
2315         ast::UintTy::U32 => UintTy::U32,
2316         ast::UintTy::U64 => UintTy::U64,
2317         ast::UintTy::U128 => UintTy::U128,
2318     }
2319 }
2320
2321 pub fn float_ty(fty: ast::FloatTy) -> FloatTy {
2322     match fty {
2323         ast::FloatTy::F32 => FloatTy::F32,
2324         ast::FloatTy::F64 => FloatTy::F64,
2325     }
2326 }
2327
2328 pub fn ast_int_ty(ity: IntTy) -> ast::IntTy {
2329     match ity {
2330         IntTy::Isize => ast::IntTy::Isize,
2331         IntTy::I8 => ast::IntTy::I8,
2332         IntTy::I16 => ast::IntTy::I16,
2333         IntTy::I32 => ast::IntTy::I32,
2334         IntTy::I64 => ast::IntTy::I64,
2335         IntTy::I128 => ast::IntTy::I128,
2336     }
2337 }
2338
2339 pub fn ast_uint_ty(uty: UintTy) -> ast::UintTy {
2340     match uty {
2341         UintTy::Usize => ast::UintTy::Usize,
2342         UintTy::U8 => ast::UintTy::U8,
2343         UintTy::U16 => ast::UintTy::U16,
2344         UintTy::U32 => ast::UintTy::U32,
2345         UintTy::U64 => ast::UintTy::U64,
2346         UintTy::U128 => ast::UintTy::U128,
2347     }
2348 }
2349
2350 pub fn provide(providers: &mut ty::query::Providers) {
2351     closure::provide(providers);
2352     context::provide(providers);
2353     erase_regions::provide(providers);
2354     layout::provide(providers);
2355     util::provide(providers);
2356     print::provide(providers);
2357     super::util::bug::provide(providers);
2358     super::middle::provide(providers);
2359     *providers = ty::query::Providers {
2360         trait_impls_of: trait_def::trait_impls_of_provider,
2361         incoherent_impls: trait_def::incoherent_impls_provider,
2362         type_uninhabited_from: inhabitedness::type_uninhabited_from,
2363         const_param_default: consts::const_param_default,
2364         vtable_allocation: vtable::vtable_allocation_provider,
2365         ..*providers
2366     };
2367 }
2368
2369 /// A map for the local crate mapping each type to a vector of its
2370 /// inherent impls. This is not meant to be used outside of coherence;
2371 /// rather, you should request the vector for a specific type via
2372 /// `tcx.inherent_impls(def_id)` so as to minimize your dependencies
2373 /// (constructing this map requires touching the entire crate).
2374 #[derive(Clone, Debug, Default, HashStable)]
2375 pub struct CrateInherentImpls {
2376     pub inherent_impls: LocalDefIdMap<Vec<DefId>>,
2377     pub incoherent_impls: FxHashMap<SimplifiedType, Vec<LocalDefId>>,
2378 }
2379
2380 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, HashStable)]
2381 pub struct SymbolName<'tcx> {
2382     /// `&str` gives a consistent ordering, which ensures reproducible builds.
2383     pub name: &'tcx str,
2384 }
2385
2386 impl<'tcx> SymbolName<'tcx> {
2387     pub fn new(tcx: TyCtxt<'tcx>, name: &str) -> SymbolName<'tcx> {
2388         SymbolName {
2389             name: unsafe { str::from_utf8_unchecked(tcx.arena.alloc_slice(name.as_bytes())) },
2390         }
2391     }
2392 }
2393
2394 impl<'tcx> fmt::Display for SymbolName<'tcx> {
2395     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2396         fmt::Display::fmt(&self.name, fmt)
2397     }
2398 }
2399
2400 impl<'tcx> fmt::Debug for SymbolName<'tcx> {
2401     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2402         fmt::Display::fmt(&self.name, fmt)
2403     }
2404 }
2405
2406 #[derive(Debug, Default, Copy, Clone)]
2407 pub struct FoundRelationships {
2408     /// This is true if we identified that this Ty (`?T`) is found in a `?T: Foo`
2409     /// obligation, where:
2410     ///
2411     ///  * `Foo` is not `Sized`
2412     ///  * `(): Foo` may be satisfied
2413     pub self_in_trait: bool,
2414     /// This is true if we identified that this Ty (`?T`) is found in a `<_ as
2415     /// _>::AssocType = ?T`
2416     pub output: bool,
2417 }