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