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