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