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