1 //! Defines how the compiler represents types internally.
3 //! Two important entities in this module are:
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.
8 //! For more information, see ["The `ty` module: representing types"] in the rustc-dev-guide.
10 //! ["The `ty` module: representing types"]: https://rustc-dev-guide.rust-lang.org/ty.html
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::*;
20 use rustc_data_structures::fingerprint::Fingerprint;
23 use crate::metadata::ModChild;
24 use crate::middle::privacy::AccessLevels;
25 use crate::mir::{Body, GeneratorLayout};
26 use crate::traits::{self, Reveal};
28 use crate::ty::fast_reject::SimplifiedType;
29 use crate::ty::subst::{GenericArg, InternalSubsts, Subst, SubstsRef};
30 use crate::ty::util::Discr;
32 use rustc_attr as attr;
33 use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap};
34 use rustc_data_structures::intern::{Interned, WithStableHash};
35 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
36 use rustc_data_structures::tagged_ptr::CopyTaggedPtr;
38 use rustc_hir::def::{CtorKind, CtorOf, DefKind, Res};
39 use rustc_hir::def_id::{CrateNum, DefId, LocalDefId, LocalDefIdMap};
41 use rustc_macros::HashStable;
42 use rustc_query_system::ich::StableHashingContext;
43 use rustc_session::cstore::CrateStoreDyn;
44 use rustc_span::symbol::{kw, sym, Ident, Symbol};
46 use rustc_target::abi::Align;
50 use std::ops::ControlFlow;
53 pub use crate::ty::diagnostics::*;
54 pub use rustc_type_ir::InferTy::*;
55 pub use rustc_type_ir::*;
57 pub use self::binding::BindingMode;
58 pub use self::binding::BindingMode::*;
59 pub use self::closure::{
60 is_ancestor_or_same_capture, place_to_string_for_capture, BorrowKind, CaptureInfo,
61 CapturedPlace, ClosureKind, MinCaptureInformationMap, MinCaptureList,
62 RootVariableMinCaptureList, UpvarCapture, UpvarCaptureMap, UpvarId, UpvarListMap, UpvarPath,
65 pub use self::consts::{
66 Const, ConstInt, ConstKind, ConstS, InferConst, ScalarInt, Unevaluated, ValTree,
68 pub use self::context::{
69 tls, CanonicalUserType, CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations,
70 CtxtInterners, DelaySpanBugEmitted, FreeRegionInfo, GeneratorDiagnosticData,
71 GeneratorInteriorTypeCause, GlobalCtxt, Lift, OnDiskCache, TyCtxt, TypeckResults, UserType,
72 UserTypeAnnotationIndex,
74 pub use self::instance::{Instance, InstanceDef};
75 pub use self::list::List;
76 pub use self::sty::BoundRegionKind::*;
77 pub use self::sty::RegionKind::*;
78 pub use self::sty::TyKind::*;
80 Binder, BoundRegion, BoundRegionKind, BoundTy, BoundTyKind, BoundVar, BoundVariableKind,
81 CanonicalPolyFnSig, ClosureSubsts, ClosureSubstsParts, ConstVid, EarlyBoundRegion,
82 ExistentialPredicate, ExistentialProjection, ExistentialTraitRef, FnSig, FreeRegion, GenSig,
83 GeneratorSubsts, GeneratorSubstsParts, InlineConstSubsts, InlineConstSubstsParts, ParamConst,
84 ParamTy, PolyExistentialProjection, PolyExistentialTraitRef, PolyFnSig, PolyGenSig,
85 PolyTraitRef, ProjectionTy, Region, RegionKind, RegionVid, TraitRef, TyKind, TypeAndMut,
86 UpvarSubsts, VarianceDiagInfo,
88 pub use self::trait_def::TraitDef;
99 pub mod inhabitedness;
101 pub mod normalize_erasing_regions;
122 mod structural_impls;
127 pub type RegisteredTools = FxHashSet<Ident>;
130 pub struct ResolverOutputs {
131 pub definitions: rustc_hir::definitions::Definitions,
132 pub cstore: Box<CrateStoreDyn>,
133 pub visibilities: FxHashMap<LocalDefId, Visibility>,
134 /// This field is used to decide whether we should make `PRIVATE_IN_PUBLIC` a hard error.
135 pub has_pub_restricted: bool,
136 pub access_levels: AccessLevels,
137 pub extern_crate_map: FxHashMap<LocalDefId, CrateNum>,
138 pub maybe_unused_trait_imports: FxHashSet<LocalDefId>,
139 pub maybe_unused_extern_crates: Vec<(LocalDefId, Span)>,
140 pub reexport_map: FxHashMap<LocalDefId, Vec<ModChild>>,
141 pub glob_map: FxHashMap<LocalDefId, FxHashSet<Symbol>>,
142 /// Extern prelude entries. The value is `true` if the entry was introduced
143 /// via `extern crate` item and not `--extern` option or compiler built-in.
144 pub extern_prelude: FxHashMap<Symbol, bool>,
145 pub main_def: Option<MainDefinition>,
146 pub trait_impls: FxIndexMap<DefId, Vec<LocalDefId>>,
147 /// A list of proc macro LocalDefIds, written out in the order in which
148 /// they are declared in the static array generated by proc_macro_harness.
149 pub proc_macros: Vec<LocalDefId>,
150 /// Mapping from ident span to path span for paths that don't exist as written, but that
151 /// exist under `std`. For example, wrote `str::from_utf8` instead of `std::str::from_utf8`.
152 pub confused_type_with_std_module: FxHashMap<Span, Span>,
153 pub registered_tools: RegisteredTools,
156 #[derive(Clone, Copy, Debug)]
157 pub struct MainDefinition {
158 pub res: Res<ast::NodeId>,
163 impl MainDefinition {
164 pub fn opt_fn_def_id(self) -> Option<DefId> {
165 if let Res::Def(DefKind::Fn, def_id) = self.res { Some(def_id) } else { None }
169 /// The "header" of an impl is everything outside the body: a Self type, a trait
170 /// ref (in the case of a trait impl), and a set of predicates (from the
171 /// bounds / where-clauses).
172 #[derive(Clone, Debug, TypeFoldable)]
173 pub struct ImplHeader<'tcx> {
174 pub impl_def_id: DefId,
175 pub self_ty: Ty<'tcx>,
176 pub trait_ref: Option<TraitRef<'tcx>>,
177 pub predicates: Vec<Predicate<'tcx>>,
180 #[derive(Copy, Clone, Debug, TypeFoldable)]
181 pub enum ImplSubject<'tcx> {
182 Trait(TraitRef<'tcx>),
198 pub enum ImplPolarity {
199 /// `impl Trait for Type`
201 /// `impl !Trait for Type`
203 /// `#[rustc_reservation_impl] impl Trait for Type`
205 /// This is a "stability hack", not a real Rust feature.
206 /// See #64631 for details.
211 /// Flips polarity by turning `Positive` into `Negative` and `Negative` into `Positive`.
212 pub fn flip(&self) -> Option<ImplPolarity> {
214 ImplPolarity::Positive => Some(ImplPolarity::Negative),
215 ImplPolarity::Negative => Some(ImplPolarity::Positive),
216 ImplPolarity::Reservation => None,
221 impl fmt::Display for ImplPolarity {
222 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
224 Self::Positive => f.write_str("positive"),
225 Self::Negative => f.write_str("negative"),
226 Self::Reservation => f.write_str("reservation"),
231 #[derive(Clone, Debug, PartialEq, Eq, Copy, Hash, TyEncodable, TyDecodable, HashStable)]
232 pub enum Visibility {
233 /// Visible everywhere (including in other crates).
235 /// Visible only in the given crate-local module.
237 /// Not visible anywhere in the local crate. This is the visibility of private external items.
241 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable, TyEncodable, TyDecodable)]
242 pub enum BoundConstness {
245 /// `T: ~const Trait`
247 /// Requires resolving to const only when we are in a const context.
251 impl BoundConstness {
252 /// Reduce `self` and `constness` to two possible combined states instead of four.
253 pub fn and(&mut self, constness: hir::Constness) -> hir::Constness {
254 match (constness, self) {
255 (hir::Constness::Const, BoundConstness::ConstIfConst) => hir::Constness::Const,
257 *this = BoundConstness::NotConst;
258 hir::Constness::NotConst
264 impl fmt::Display for BoundConstness {
265 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
267 Self::NotConst => f.write_str("normal"),
268 Self::ConstIfConst => f.write_str("`~const`"),
285 pub struct ClosureSizeProfileData<'tcx> {
286 /// Tuple containing the types of closure captures before the feature `capture_disjoint_fields`
287 pub before_feature_tys: Ty<'tcx>,
288 /// Tuple containing the types of closure captures after the feature `capture_disjoint_fields`
289 pub after_feature_tys: Ty<'tcx>,
292 pub trait DefIdTree: Copy {
293 fn opt_parent(self, id: DefId) -> Option<DefId>;
297 fn parent(self, id: DefId) -> DefId {
298 match self.opt_parent(id) {
300 // not `unwrap_or_else` to avoid breaking caller tracking
301 None => bug!("{id:?} doesn't have a parent"),
307 fn opt_local_parent(self, id: LocalDefId) -> Option<LocalDefId> {
308 self.opt_parent(id.to_def_id()).map(DefId::expect_local)
313 fn local_parent(self, id: LocalDefId) -> LocalDefId {
314 self.parent(id.to_def_id()).expect_local()
317 fn is_descendant_of(self, mut descendant: DefId, ancestor: DefId) -> bool {
318 if descendant.krate != ancestor.krate {
322 while descendant != ancestor {
323 match self.opt_parent(descendant) {
324 Some(parent) => descendant = parent,
325 None => return false,
332 impl<'tcx> DefIdTree for TyCtxt<'tcx> {
334 fn opt_parent(self, id: DefId) -> Option<DefId> {
335 self.def_key(id).parent.map(|index| DefId { index, ..id })
340 /// Returns `true` if an item with this visibility is accessible from the given block.
341 pub fn is_accessible_from<T: DefIdTree>(self, module: DefId, tree: T) -> bool {
342 let restriction = match self {
343 // Public items are visible everywhere.
344 Visibility::Public => return true,
345 // Private items from other crates are visible nowhere.
346 Visibility::Invisible => return false,
347 // Restricted items are visible in an arbitrary local module.
348 Visibility::Restricted(other) if other.krate != module.krate => return false,
349 Visibility::Restricted(module) => module,
352 tree.is_descendant_of(module, restriction)
355 /// Returns `true` if this visibility is at least as accessible as the given visibility
356 pub fn is_at_least<T: DefIdTree>(self, vis: Visibility, tree: T) -> bool {
357 let vis_restriction = match vis {
358 Visibility::Public => return self == Visibility::Public,
359 Visibility::Invisible => return true,
360 Visibility::Restricted(module) => module,
363 self.is_accessible_from(vis_restriction, tree)
366 // Returns `true` if this item is visible anywhere in the local crate.
367 pub fn is_visible_locally(self) -> bool {
369 Visibility::Public => true,
370 Visibility::Restricted(def_id) => def_id.is_local(),
371 Visibility::Invisible => false,
375 pub fn is_public(self) -> bool {
376 matches!(self, Visibility::Public)
380 /// The crate variances map is computed during typeck and contains the
381 /// variance of every item in the local crate. You should not use it
382 /// directly, because to do so will make your pass dependent on the
383 /// HIR of every item in the local crate. Instead, use
384 /// `tcx.variances_of()` to get the variance for a *particular*
386 #[derive(HashStable, Debug)]
387 pub struct CrateVariancesMap<'tcx> {
388 /// For each item with generics, maps to a vector of the variance
389 /// of its generics. If an item has no generics, it will have no
391 pub variances: FxHashMap<DefId, &'tcx [ty::Variance]>,
394 // Contains information needed to resolve types and (in the future) look up
395 // the types of AST nodes.
396 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
397 pub struct CReaderCacheKey {
398 pub cnum: Option<CrateNum>,
402 /// Represents a type.
405 /// - This is a very "dumb" struct (with no derives and no `impls`).
406 /// - Values of this type are always interned and thus unique, and are stored
407 /// as an `Interned<TyS>`.
408 /// - `Ty` (which contains a reference to a `Interned<TyS>`) or `Interned<TyS>`
409 /// should be used everywhere instead of `TyS`. In particular, `Ty` has most
410 /// of the relevant methods.
411 #[derive(PartialEq, Eq, PartialOrd, Ord)]
412 #[allow(rustc::usage_of_ty_tykind)]
413 crate struct TyS<'tcx> {
414 /// This field shouldn't be used directly and may be removed in the future.
415 /// Use `Ty::kind()` instead.
418 /// This field provides fast access to information that is also contained
421 /// This field shouldn't be used directly and may be removed in the future.
422 /// Use `Ty::flags()` instead.
425 /// This field provides fast access to information that is also contained
428 /// This is a kind of confusing thing: it stores the smallest
431 /// (a) the binder itself captures nothing but
432 /// (b) all the late-bound things within the type are captured
433 /// by some sub-binder.
435 /// So, for a type without any late-bound things, like `u32`, this
436 /// will be *innermost*, because that is the innermost binder that
437 /// captures nothing. But for a type `&'D u32`, where `'D` is a
438 /// late-bound region with De Bruijn index `D`, this would be `D + 1`
439 /// -- the binder itself does not capture `D`, but `D` is captured
440 /// by an inner binder.
442 /// We call this concept an "exclusive" binder `D` because all
443 /// De Bruijn indices within the type are contained within `0..D`
445 outer_exclusive_binder: ty::DebruijnIndex,
448 // `TyS` is used a lot. Make sure it doesn't unintentionally get bigger.
449 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
450 static_assert_size!(TyS<'_>, 40);
452 // We are actually storing a stable hash cache next to the type, so let's
453 // also check the full size
454 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
455 static_assert_size!(WithStableHash<TyS<'_>>, 56);
457 /// Use this rather than `TyS`, whenever possible.
458 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, HashStable)]
459 #[rustc_diagnostic_item = "Ty"]
460 #[rustc_pass_by_value]
461 pub struct Ty<'tcx>(Interned<'tcx, WithStableHash<TyS<'tcx>>>);
463 // Statics only used for internal testing.
464 pub static BOOL_TY: Ty<'static> = Ty(Interned::new_unchecked(&WithStableHash {
466 stable_hash: Fingerprint::ZERO,
468 const BOOL_TYS: TyS<'static> = TyS {
470 flags: TypeFlags::empty(),
471 outer_exclusive_binder: DebruijnIndex::from_usize(0),
474 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for TyS<'tcx> {
476 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
480 // The other fields just provide fast access to information that is
481 // also contained in `kind`, so no need to hash them.
484 outer_exclusive_binder: _,
487 kind.hash_stable(hcx, hasher)
491 impl ty::EarlyBoundRegion {
492 /// Does this early bound region have a name? Early bound regions normally
493 /// always have names except when using anonymous lifetimes (`'_`).
494 pub fn has_name(&self) -> bool {
495 self.name != kw::UnderscoreLifetime
499 /// Represents a predicate.
501 /// See comments on `TyS`, which apply here too (albeit for
502 /// `PredicateS`/`Predicate` rather than `TyS`/`Ty`).
504 crate struct PredicateS<'tcx> {
505 kind: Binder<'tcx, PredicateKind<'tcx>>,
507 /// See the comment for the corresponding field of [TyS].
508 outer_exclusive_binder: ty::DebruijnIndex,
511 // This type is used a lot. Make sure it doesn't unintentionally get bigger.
512 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
513 static_assert_size!(PredicateS<'_>, 56);
515 /// Use this rather than `PredicateS`, whenever possible.
516 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
517 #[rustc_pass_by_value]
518 pub struct Predicate<'tcx>(Interned<'tcx, PredicateS<'tcx>>);
520 impl<'tcx> Predicate<'tcx> {
521 /// Gets the inner `Binder<'tcx, PredicateKind<'tcx>>`.
523 pub fn kind(self) -> Binder<'tcx, PredicateKind<'tcx>> {
528 pub fn flags(self) -> TypeFlags {
533 pub fn outer_exclusive_binder(self) -> DebruijnIndex {
534 self.0.outer_exclusive_binder
537 /// Flips the polarity of a Predicate.
539 /// Given `T: Trait` predicate it returns `T: !Trait` and given `T: !Trait` returns `T: Trait`.
540 pub fn flip_polarity(self, tcx: TyCtxt<'tcx>) -> Option<Predicate<'tcx>> {
543 .map_bound(|kind| match kind {
544 PredicateKind::Trait(TraitPredicate { trait_ref, constness, polarity }) => {
545 Some(PredicateKind::Trait(TraitPredicate {
548 polarity: polarity.flip()?,
556 Some(tcx.mk_predicate(kind))
560 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for Predicate<'tcx> {
561 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
565 // The other fields just provide fast access to information that is
566 // also contained in `kind`, so no need to hash them.
568 outer_exclusive_binder: _,
571 kind.hash_stable(hcx, hasher);
575 #[derive(Clone, Copy, PartialEq, Eq, Hash, TyEncodable, TyDecodable)]
576 #[derive(HashStable, TypeFoldable)]
577 pub enum PredicateKind<'tcx> {
578 /// Corresponds to `where Foo: Bar<A, B, C>`. `Foo` here would be
579 /// the `Self` type of the trait reference and `A`, `B`, and `C`
580 /// would be the type parameters.
581 Trait(TraitPredicate<'tcx>),
584 RegionOutlives(RegionOutlivesPredicate<'tcx>),
587 TypeOutlives(TypeOutlivesPredicate<'tcx>),
589 /// `where <T as TraitRef>::Name == X`, approximately.
590 /// See the `ProjectionPredicate` struct for details.
591 Projection(ProjectionPredicate<'tcx>),
593 /// No syntax: `T` well-formed.
594 WellFormed(GenericArg<'tcx>),
596 /// Trait must be object-safe.
599 /// No direct syntax. May be thought of as `where T: FnFoo<...>`
600 /// for some substitutions `...` and `T` being a closure type.
601 /// Satisfied (or refuted) once we know the closure's kind.
602 ClosureKind(DefId, SubstsRef<'tcx>, ClosureKind),
606 /// This obligation is created most often when we have two
607 /// unresolved type variables and hence don't have enough
608 /// information to process the subtyping obligation yet.
609 Subtype(SubtypePredicate<'tcx>),
611 /// `T1` coerced to `T2`
613 /// Like a subtyping obligation, this is created most often
614 /// when we have two unresolved type variables and hence
615 /// don't have enough information to process the coercion
616 /// obligation yet. At the moment, we actually process coercions
617 /// very much like subtyping and don't handle the full coercion
619 Coerce(CoercePredicate<'tcx>),
621 /// Constant initializer must evaluate successfully.
622 ConstEvaluatable(ty::Unevaluated<'tcx, ()>),
624 /// Constants must be equal. The first component is the const that is expected.
625 ConstEquate(Const<'tcx>, Const<'tcx>),
627 /// Represents a type found in the environment that we can use for implied bounds.
629 /// Only used for Chalk.
630 TypeWellFormedFromEnv(Ty<'tcx>),
633 /// The crate outlives map is computed during typeck and contains the
634 /// outlives of every item in the local crate. You should not use it
635 /// directly, because to do so will make your pass dependent on the
636 /// HIR of every item in the local crate. Instead, use
637 /// `tcx.inferred_outlives_of()` to get the outlives for a *particular*
639 #[derive(HashStable, Debug)]
640 pub struct CratePredicatesMap<'tcx> {
641 /// For each struct with outlive bounds, maps to a vector of the
642 /// predicate of its outlive bounds. If an item has no outlives
643 /// bounds, it will have no entry.
644 pub predicates: FxHashMap<DefId, &'tcx [(Predicate<'tcx>, Span)]>,
647 impl<'tcx> Predicate<'tcx> {
648 /// Performs a substitution suitable for going from a
649 /// poly-trait-ref to supertraits that must hold if that
650 /// poly-trait-ref holds. This is slightly different from a normal
651 /// substitution in terms of what happens with bound regions. See
652 /// lengthy comment below for details.
653 pub fn subst_supertrait(
656 trait_ref: &ty::PolyTraitRef<'tcx>,
657 ) -> Predicate<'tcx> {
658 // The interaction between HRTB and supertraits is not entirely
659 // obvious. Let me walk you (and myself) through an example.
661 // Let's start with an easy case. Consider two traits:
663 // trait Foo<'a>: Bar<'a,'a> { }
664 // trait Bar<'b,'c> { }
666 // Now, if we have a trait reference `for<'x> T: Foo<'x>`, then
667 // we can deduce that `for<'x> T: Bar<'x,'x>`. Basically, if we
668 // knew that `Foo<'x>` (for any 'x) then we also know that
669 // `Bar<'x,'x>` (for any 'x). This more-or-less falls out from
670 // normal substitution.
672 // In terms of why this is sound, the idea is that whenever there
673 // is an impl of `T:Foo<'a>`, it must show that `T:Bar<'a,'a>`
674 // holds. So if there is an impl of `T:Foo<'a>` that applies to
675 // all `'a`, then we must know that `T:Bar<'a,'a>` holds for all
678 // Another example to be careful of is this:
680 // trait Foo1<'a>: for<'b> Bar1<'a,'b> { }
681 // trait Bar1<'b,'c> { }
683 // Here, if we have `for<'x> T: Foo1<'x>`, then what do we know?
684 // The answer is that we know `for<'x,'b> T: Bar1<'x,'b>`. The
685 // reason is similar to the previous example: any impl of
686 // `T:Foo1<'x>` must show that `for<'b> T: Bar1<'x, 'b>`. So
687 // basically we would want to collapse the bound lifetimes from
688 // the input (`trait_ref`) and the supertraits.
690 // To achieve this in practice is fairly straightforward. Let's
691 // consider the more complicated scenario:
693 // - We start out with `for<'x> T: Foo1<'x>`. In this case, `'x`
694 // has a De Bruijn index of 1. We want to produce `for<'x,'b> T: Bar1<'x,'b>`,
695 // where both `'x` and `'b` would have a DB index of 1.
696 // The substitution from the input trait-ref is therefore going to be
697 // `'a => 'x` (where `'x` has a DB index of 1).
698 // - The supertrait-ref is `for<'b> Bar1<'a,'b>`, where `'a` is an
699 // early-bound parameter and `'b' is a late-bound parameter with a
701 // - If we replace `'a` with `'x` from the input, it too will have
702 // a DB index of 1, and thus we'll have `for<'x,'b> Bar1<'x,'b>`
703 // just as we wanted.
705 // There is only one catch. If we just apply the substitution `'a
706 // => 'x` to `for<'b> Bar1<'a,'b>`, the substitution code will
707 // adjust the DB index because we substituting into a binder (it
708 // tries to be so smart...) resulting in `for<'x> for<'b>
709 // Bar1<'x,'b>` (we have no syntax for this, so use your
710 // imagination). Basically the 'x will have DB index of 2 and 'b
711 // will have DB index of 1. Not quite what we want. So we apply
712 // the substitution to the *contents* of the trait reference,
713 // rather than the trait reference itself (put another way, the
714 // substitution code expects equal binding levels in the values
715 // from the substitution and the value being substituted into, and
716 // this trick achieves that).
718 // Working through the second example:
719 // trait_ref: for<'x> T: Foo1<'^0.0>; substs: [T, '^0.0]
720 // predicate: for<'b> Self: Bar1<'a, '^0.0>; substs: [Self, 'a, '^0.0]
721 // We want to end up with:
722 // for<'x, 'b> T: Bar1<'^0.0, '^0.1>
724 // 1) We must shift all bound vars in predicate by the length
725 // of trait ref's bound vars. So, we would end up with predicate like
726 // Self: Bar1<'a, '^0.1>
727 // 2) We can then apply the trait substs to this, ending up with
728 // T: Bar1<'^0.0, '^0.1>
729 // 3) Finally, to create the final bound vars, we concatenate the bound
730 // vars of the trait ref with those of the predicate:
732 let bound_pred = self.kind();
733 let pred_bound_vars = bound_pred.bound_vars();
734 let trait_bound_vars = trait_ref.bound_vars();
735 // 1) Self: Bar1<'a, '^0.0> -> Self: Bar1<'a, '^0.1>
737 tcx.shift_bound_var_indices(trait_bound_vars.len(), bound_pred.skip_binder());
738 // 2) Self: Bar1<'a, '^0.1> -> T: Bar1<'^0.0, '^0.1>
739 let new = shifted_pred.subst(tcx, trait_ref.skip_binder().substs);
740 // 3) ['x] + ['b] -> ['x, 'b]
742 tcx.mk_bound_variable_kinds(trait_bound_vars.iter().chain(pred_bound_vars));
743 tcx.reuse_or_mk_predicate(self, ty::Binder::bind_with_vars(new, bound_vars))
747 #[derive(Clone, Copy, PartialEq, Eq, Hash, TyEncodable, TyDecodable)]
748 #[derive(HashStable, TypeFoldable)]
749 pub struct TraitPredicate<'tcx> {
750 pub trait_ref: TraitRef<'tcx>,
752 pub constness: BoundConstness,
754 /// If polarity is Positive: we are proving that the trait is implemented.
756 /// If polarity is Negative: we are proving that a negative impl of this trait
757 /// exists. (Note that coherence also checks whether negative impls of supertraits
758 /// exist via a series of predicates.)
760 /// If polarity is Reserved: that's a bug.
761 pub polarity: ImplPolarity,
764 pub type PolyTraitPredicate<'tcx> = ty::Binder<'tcx, TraitPredicate<'tcx>>;
766 impl<'tcx> TraitPredicate<'tcx> {
767 pub fn remap_constness(&mut self, tcx: TyCtxt<'tcx>, param_env: &mut ParamEnv<'tcx>) {
768 if unlikely!(Some(self.trait_ref.def_id) == tcx.lang_items().drop_trait()) {
769 // remap without changing constness of this predicate.
770 // this is because `T: ~const Drop` has a different meaning to `T: Drop`
771 // FIXME(fee1-dead): remove this logic after beta bump
772 param_env.remap_constness_with(self.constness)
774 *param_env = param_env.with_constness(self.constness.and(param_env.constness()))
778 /// Remap the constness of this predicate before emitting it for diagnostics.
779 pub fn remap_constness_diag(&mut self, param_env: ParamEnv<'tcx>) {
780 // this is different to `remap_constness` that callees want to print this predicate
781 // in case of selection errors. `T: ~const Drop` bounds cannot end up here when the
782 // param_env is not const because we it is always satisfied in non-const contexts.
783 if let hir::Constness::NotConst = param_env.constness() {
784 self.constness = ty::BoundConstness::NotConst;
788 pub fn def_id(self) -> DefId {
789 self.trait_ref.def_id
792 pub fn self_ty(self) -> Ty<'tcx> {
793 self.trait_ref.self_ty()
797 pub fn is_const_if_const(self) -> bool {
798 self.constness == BoundConstness::ConstIfConst
802 impl<'tcx> PolyTraitPredicate<'tcx> {
803 pub fn def_id(self) -> DefId {
804 // Ok to skip binder since trait `DefId` does not care about regions.
805 self.skip_binder().def_id()
808 pub fn self_ty(self) -> ty::Binder<'tcx, Ty<'tcx>> {
809 self.map_bound(|trait_ref| trait_ref.self_ty())
812 /// Remap the constness of this predicate before emitting it for diagnostics.
813 pub fn remap_constness_diag(&mut self, param_env: ParamEnv<'tcx>) {
814 *self = self.map_bound(|mut p| {
815 p.remap_constness_diag(param_env);
821 pub fn is_const_if_const(self) -> bool {
822 self.skip_binder().is_const_if_const()
826 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, TyEncodable, TyDecodable)]
827 #[derive(HashStable, TypeFoldable)]
828 pub struct OutlivesPredicate<A, B>(pub A, pub B); // `A: B`
829 pub type RegionOutlivesPredicate<'tcx> = OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>;
830 pub type TypeOutlivesPredicate<'tcx> = OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>;
831 pub type PolyRegionOutlivesPredicate<'tcx> = ty::Binder<'tcx, RegionOutlivesPredicate<'tcx>>;
832 pub type PolyTypeOutlivesPredicate<'tcx> = ty::Binder<'tcx, TypeOutlivesPredicate<'tcx>>;
834 /// Encodes that `a` must be a subtype of `b`. The `a_is_expected` flag indicates
835 /// whether the `a` type is the type that we should label as "expected" when
836 /// presenting user diagnostics.
837 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, TyEncodable, TyDecodable)]
838 #[derive(HashStable, TypeFoldable)]
839 pub struct SubtypePredicate<'tcx> {
840 pub a_is_expected: bool,
844 pub type PolySubtypePredicate<'tcx> = ty::Binder<'tcx, SubtypePredicate<'tcx>>;
846 /// Encodes that we have to coerce *from* the `a` type to the `b` type.
847 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, TyEncodable, TyDecodable)]
848 #[derive(HashStable, TypeFoldable)]
849 pub struct CoercePredicate<'tcx> {
853 pub type PolyCoercePredicate<'tcx> = ty::Binder<'tcx, CoercePredicate<'tcx>>;
855 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, TyEncodable, TyDecodable)]
856 #[derive(HashStable, TypeFoldable)]
857 pub enum Term<'tcx> {
862 impl<'tcx> From<Ty<'tcx>> for Term<'tcx> {
863 fn from(ty: Ty<'tcx>) -> Self {
868 impl<'tcx> From<Const<'tcx>> for Term<'tcx> {
869 fn from(c: Const<'tcx>) -> Self {
874 impl<'tcx> Term<'tcx> {
875 pub fn ty(&self) -> Option<Ty<'tcx>> {
876 if let Term::Ty(ty) = self { Some(*ty) } else { None }
878 pub fn ct(&self) -> Option<Const<'tcx>> {
879 if let Term::Const(c) = self { Some(*c) } else { None }
883 /// This kind of predicate has no *direct* correspondent in the
884 /// syntax, but it roughly corresponds to the syntactic forms:
886 /// 1. `T: TraitRef<..., Item = Type>`
887 /// 2. `<T as TraitRef<...>>::Item == Type` (NYI)
889 /// In particular, form #1 is "desugared" to the combination of a
890 /// normal trait predicate (`T: TraitRef<...>`) and one of these
891 /// predicates. Form #2 is a broader form in that it also permits
892 /// equality between arbitrary types. Processing an instance of
893 /// Form #2 eventually yields one of these `ProjectionPredicate`
894 /// instances to normalize the LHS.
895 #[derive(Copy, Clone, PartialEq, Eq, Hash, TyEncodable, TyDecodable)]
896 #[derive(HashStable, TypeFoldable)]
897 pub struct ProjectionPredicate<'tcx> {
898 pub projection_ty: ProjectionTy<'tcx>,
899 pub term: Term<'tcx>,
902 pub type PolyProjectionPredicate<'tcx> = Binder<'tcx, ProjectionPredicate<'tcx>>;
904 impl<'tcx> PolyProjectionPredicate<'tcx> {
905 /// Returns the `DefId` of the trait of the associated item being projected.
907 pub fn trait_def_id(&self, tcx: TyCtxt<'tcx>) -> DefId {
908 self.skip_binder().projection_ty.trait_def_id(tcx)
911 /// Get the [PolyTraitRef] required for this projection to be well formed.
912 /// Note that for generic associated types the predicates of the associated
913 /// type also need to be checked.
915 pub fn required_poly_trait_ref(&self, tcx: TyCtxt<'tcx>) -> PolyTraitRef<'tcx> {
916 // Note: unlike with `TraitRef::to_poly_trait_ref()`,
917 // `self.0.trait_ref` is permitted to have escaping regions.
918 // This is because here `self` has a `Binder` and so does our
919 // return value, so we are preserving the number of binding
921 self.map_bound(|predicate| predicate.projection_ty.trait_ref(tcx))
924 pub fn term(&self) -> Binder<'tcx, Term<'tcx>> {
925 self.map_bound(|predicate| predicate.term)
928 /// The `DefId` of the `TraitItem` for the associated type.
930 /// Note that this is not the `DefId` of the `TraitRef` containing this
931 /// associated type, which is in `tcx.associated_item(projection_def_id()).container`.
932 pub fn projection_def_id(&self) -> DefId {
933 // Ok to skip binder since trait `DefId` does not care about regions.
934 self.skip_binder().projection_ty.item_def_id
938 pub trait ToPolyTraitRef<'tcx> {
939 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx>;
942 impl<'tcx> ToPolyTraitRef<'tcx> for PolyTraitPredicate<'tcx> {
943 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
944 self.map_bound_ref(|trait_pred| trait_pred.trait_ref)
948 pub trait ToPredicate<'tcx> {
949 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx>;
952 impl<'tcx> ToPredicate<'tcx> for Binder<'tcx, PredicateKind<'tcx>> {
954 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
955 tcx.mk_predicate(self)
959 impl<'tcx> ToPredicate<'tcx> for PolyTraitPredicate<'tcx> {
960 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
961 self.map_bound(PredicateKind::Trait).to_predicate(tcx)
965 impl<'tcx> ToPredicate<'tcx> for PolyRegionOutlivesPredicate<'tcx> {
966 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
967 self.map_bound(PredicateKind::RegionOutlives).to_predicate(tcx)
971 impl<'tcx> ToPredicate<'tcx> for PolyTypeOutlivesPredicate<'tcx> {
972 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
973 self.map_bound(PredicateKind::TypeOutlives).to_predicate(tcx)
977 impl<'tcx> ToPredicate<'tcx> for PolyProjectionPredicate<'tcx> {
978 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
979 self.map_bound(PredicateKind::Projection).to_predicate(tcx)
983 impl<'tcx> Predicate<'tcx> {
984 pub fn to_opt_poly_trait_pred(self) -> Option<PolyTraitPredicate<'tcx>> {
985 let predicate = self.kind();
986 match predicate.skip_binder() {
987 PredicateKind::Trait(t) => Some(predicate.rebind(t)),
988 PredicateKind::Projection(..)
989 | PredicateKind::Subtype(..)
990 | PredicateKind::Coerce(..)
991 | PredicateKind::RegionOutlives(..)
992 | PredicateKind::WellFormed(..)
993 | PredicateKind::ObjectSafe(..)
994 | PredicateKind::ClosureKind(..)
995 | PredicateKind::TypeOutlives(..)
996 | PredicateKind::ConstEvaluatable(..)
997 | PredicateKind::ConstEquate(..)
998 | PredicateKind::TypeWellFormedFromEnv(..) => None,
1002 pub fn to_opt_type_outlives(self) -> Option<PolyTypeOutlivesPredicate<'tcx>> {
1003 let predicate = self.kind();
1004 match predicate.skip_binder() {
1005 PredicateKind::TypeOutlives(data) => Some(predicate.rebind(data)),
1006 PredicateKind::Trait(..)
1007 | PredicateKind::Projection(..)
1008 | PredicateKind::Subtype(..)
1009 | PredicateKind::Coerce(..)
1010 | PredicateKind::RegionOutlives(..)
1011 | PredicateKind::WellFormed(..)
1012 | PredicateKind::ObjectSafe(..)
1013 | PredicateKind::ClosureKind(..)
1014 | PredicateKind::ConstEvaluatable(..)
1015 | PredicateKind::ConstEquate(..)
1016 | PredicateKind::TypeWellFormedFromEnv(..) => None,
1021 /// Represents the bounds declared on a particular set of type
1022 /// parameters. Should eventually be generalized into a flag list of
1023 /// where-clauses. You can obtain an `InstantiatedPredicates` list from a
1024 /// `GenericPredicates` by using the `instantiate` method. Note that this method
1025 /// reflects an important semantic invariant of `InstantiatedPredicates`: while
1026 /// the `GenericPredicates` are expressed in terms of the bound type
1027 /// parameters of the impl/trait/whatever, an `InstantiatedPredicates` instance
1028 /// represented a set of bounds for some particular instantiation,
1029 /// meaning that the generic parameters have been substituted with
1033 /// ```ignore (illustrative)
1034 /// struct Foo<T, U: Bar<T>> { ... }
1036 /// Here, the `GenericPredicates` for `Foo` would contain a list of bounds like
1037 /// `[[], [U:Bar<T>]]`. Now if there were some particular reference
1038 /// like `Foo<isize,usize>`, then the `InstantiatedPredicates` would be `[[],
1039 /// [usize:Bar<isize>]]`.
1040 #[derive(Clone, Debug, TypeFoldable)]
1041 pub struct InstantiatedPredicates<'tcx> {
1042 pub predicates: Vec<Predicate<'tcx>>,
1043 pub spans: Vec<Span>,
1046 impl<'tcx> InstantiatedPredicates<'tcx> {
1047 pub fn empty() -> InstantiatedPredicates<'tcx> {
1048 InstantiatedPredicates { predicates: vec![], spans: vec![] }
1051 pub fn is_empty(&self) -> bool {
1052 self.predicates.is_empty()
1068 pub struct OpaqueTypeKey<'tcx> {
1070 pub substs: SubstsRef<'tcx>,
1073 #[derive(Copy, Clone, Debug, TypeFoldable, HashStable, TyEncodable, TyDecodable)]
1074 pub struct OpaqueHiddenType<'tcx> {
1075 /// The span of this particular definition of the opaque type. So
1078 /// ```ignore (incomplete snippet)
1079 /// type Foo = impl Baz;
1080 /// fn bar() -> Foo {
1081 /// // ^^^ This is the span we are looking for!
1085 /// In cases where the fn returns `(impl Trait, impl Trait)` or
1086 /// other such combinations, the result is currently
1087 /// over-approximated, but better than nothing.
1090 /// The type variable that represents the value of the opaque type
1091 /// that we require. In other words, after we compile this function,
1092 /// we will be created a constraint like:
1093 /// ```ignore (pseudo-rust)
1096 /// where `?C` is the value of this type variable. =) It may
1097 /// naturally refer to the type and lifetime parameters in scope
1098 /// in this function, though ultimately it should only reference
1099 /// those that are arguments to `Foo` in the constraint above. (In
1100 /// other words, `?C` should not include `'b`, even though it's a
1101 /// lifetime parameter on `foo`.)
1105 impl<'tcx> OpaqueHiddenType<'tcx> {
1106 pub fn report_mismatch(&self, other: &Self, tcx: TyCtxt<'tcx>) {
1107 // Found different concrete types for the opaque type.
1108 let mut err = tcx.sess.struct_span_err(
1110 "concrete type differs from previous defining opaque type use",
1112 err.span_label(other.span, format!("expected `{}`, got `{}`", self.ty, other.ty));
1113 if self.span == other.span {
1116 "this expression supplies two conflicting concrete types for the same opaque type",
1119 err.span_note(self.span, "previous use here");
1125 rustc_index::newtype_index! {
1126 /// "Universes" are used during type- and trait-checking in the
1127 /// presence of `for<..>` binders to control what sets of names are
1128 /// visible. Universes are arranged into a tree: the root universe
1129 /// contains names that are always visible. Each child then adds a new
1130 /// set of names that are visible, in addition to those of its parent.
1131 /// We say that the child universe "extends" the parent universe with
1134 /// To make this more concrete, consider this program:
1136 /// ```ignore (illustrative)
1138 /// fn bar<T>(x: T) {
1139 /// let y: for<'a> fn(&'a u8, Foo) = ...;
1143 /// The struct name `Foo` is in the root universe U0. But the type
1144 /// parameter `T`, introduced on `bar`, is in an extended universe U1
1145 /// -- i.e., within `bar`, we can name both `T` and `Foo`, but outside
1146 /// of `bar`, we cannot name `T`. Then, within the type of `y`, the
1147 /// region `'a` is in a universe U2 that extends U1, because we can
1148 /// name it inside the fn type but not outside.
1150 /// Universes are used to do type- and trait-checking around these
1151 /// "forall" binders (also called **universal quantification**). The
1152 /// idea is that when, in the body of `bar`, we refer to `T` as a
1153 /// type, we aren't referring to any type in particular, but rather a
1154 /// kind of "fresh" type that is distinct from all other types we have
1155 /// actually declared. This is called a **placeholder** type, and we
1156 /// use universes to talk about this. In other words, a type name in
1157 /// universe 0 always corresponds to some "ground" type that the user
1158 /// declared, but a type name in a non-zero universe is a placeholder
1159 /// type -- an idealized representative of "types in general" that we
1160 /// use for checking generic functions.
1161 pub struct UniverseIndex {
1163 DEBUG_FORMAT = "U{}",
1167 impl UniverseIndex {
1168 pub const ROOT: UniverseIndex = UniverseIndex::from_u32(0);
1170 /// Returns the "next" universe index in order -- this new index
1171 /// is considered to extend all previous universes. This
1172 /// corresponds to entering a `forall` quantifier. So, for
1173 /// example, suppose we have this type in universe `U`:
1175 /// ```ignore (illustrative)
1176 /// for<'a> fn(&'a u32)
1179 /// Once we "enter" into this `for<'a>` quantifier, we are in a
1180 /// new universe that extends `U` -- in this new universe, we can
1181 /// name the region `'a`, but that region was not nameable from
1182 /// `U` because it was not in scope there.
1183 pub fn next_universe(self) -> UniverseIndex {
1184 UniverseIndex::from_u32(self.private.checked_add(1).unwrap())
1187 /// Returns `true` if `self` can name a name from `other` -- in other words,
1188 /// if the set of names in `self` is a superset of those in
1189 /// `other` (`self >= other`).
1190 pub fn can_name(self, other: UniverseIndex) -> bool {
1191 self.private >= other.private
1194 /// Returns `true` if `self` cannot name some names from `other` -- in other
1195 /// words, if the set of names in `self` is a strict subset of
1196 /// those in `other` (`self < other`).
1197 pub fn cannot_name(self, other: UniverseIndex) -> bool {
1198 self.private < other.private
1202 /// The "placeholder index" fully defines a placeholder region, type, or const. Placeholders are
1203 /// identified by both a universe, as well as a name residing within that universe. Distinct bound
1204 /// regions/types/consts within the same universe simply have an unknown relationship to one
1206 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TyEncodable, TyDecodable, PartialOrd, Ord)]
1207 pub struct Placeholder<T> {
1208 pub universe: UniverseIndex,
1212 impl<'a, T> HashStable<StableHashingContext<'a>> for Placeholder<T>
1214 T: HashStable<StableHashingContext<'a>>,
1216 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
1217 self.universe.hash_stable(hcx, hasher);
1218 self.name.hash_stable(hcx, hasher);
1222 pub type PlaceholderRegion = Placeholder<BoundRegionKind>;
1224 pub type PlaceholderType = Placeholder<BoundVar>;
1226 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable)]
1227 #[derive(TyEncodable, TyDecodable, PartialOrd, Ord)]
1228 pub struct BoundConst<'tcx> {
1233 pub type PlaceholderConst<'tcx> = Placeholder<BoundConst<'tcx>>;
1235 /// A `DefId` which, in case it is a const argument, is potentially bundled with
1236 /// the `DefId` of the generic parameter it instantiates.
1238 /// This is used to avoid calls to `type_of` for const arguments during typeck
1239 /// which cause cycle errors.
1244 /// fn foo<const N: usize>(&self) -> [u8; N] { [0; N] }
1245 /// // ^ const parameter
1249 /// fn foo<const M: u8>(&self) -> usize { 42 }
1250 /// // ^ const parameter
1255 /// let _b = a.foo::<{ 3 + 7 }>();
1256 /// // ^^^^^^^^^ const argument
1260 /// Let's look at the call `a.foo::<{ 3 + 7 }>()` here. We do not know
1261 /// which `foo` is used until we know the type of `a`.
1263 /// We only know the type of `a` once we are inside of `typeck(main)`.
1264 /// We also end up normalizing the type of `_b` during `typeck(main)` which
1265 /// requires us to evaluate the const argument.
1267 /// To evaluate that const argument we need to know its type,
1268 /// which we would get using `type_of(const_arg)`. This requires us to
1269 /// resolve `foo` as it can be either `usize` or `u8` in this example.
1270 /// However, resolving `foo` once again requires `typeck(main)` to get the type of `a`,
1271 /// which results in a cycle.
1273 /// In short we must not call `type_of(const_arg)` during `typeck(main)`.
1275 /// When first creating the `ty::Const` of the const argument inside of `typeck` we have
1276 /// already resolved `foo` so we know which const parameter this argument instantiates.
1277 /// This means that we also know the expected result of `type_of(const_arg)` even if we
1278 /// aren't allowed to call that query: it is equal to `type_of(const_param)` which is
1279 /// trivial to compute.
1281 /// If we now want to use that constant in a place which potentially needs its type
1282 /// we also pass the type of its `const_param`. This is the point of `WithOptConstParam`,
1283 /// except that instead of a `Ty` we bundle the `DefId` of the const parameter.
1284 /// Meaning that we need to use `type_of(const_param_did)` if `const_param_did` is `Some`
1285 /// to get the type of `did`.
1286 #[derive(Copy, Clone, Debug, TypeFoldable, Lift, TyEncodable, TyDecodable)]
1287 #[derive(PartialEq, Eq, PartialOrd, Ord)]
1288 #[derive(Hash, HashStable)]
1289 pub struct WithOptConstParam<T> {
1291 /// The `DefId` of the corresponding generic parameter in case `did` is
1292 /// a const argument.
1294 /// Note that even if `did` is a const argument, this may still be `None`.
1295 /// All queries taking `WithOptConstParam` start by calling `tcx.opt_const_param_of(def.did)`
1296 /// to potentially update `param_did` in the case it is `None`.
1297 pub const_param_did: Option<DefId>,
1300 impl<T> WithOptConstParam<T> {
1301 /// Creates a new `WithOptConstParam` setting `const_param_did` to `None`.
1303 pub fn unknown(did: T) -> WithOptConstParam<T> {
1304 WithOptConstParam { did, const_param_did: None }
1308 impl WithOptConstParam<LocalDefId> {
1309 /// Returns `Some((did, param_did))` if `def_id` is a const argument,
1310 /// `None` otherwise.
1312 pub fn try_lookup(did: LocalDefId, tcx: TyCtxt<'_>) -> Option<(LocalDefId, DefId)> {
1313 tcx.opt_const_param_of(did).map(|param_did| (did, param_did))
1316 /// In case `self` is unknown but `self.did` is a const argument, this returns
1317 /// a `WithOptConstParam` with the correct `const_param_did`.
1319 pub fn try_upgrade(self, tcx: TyCtxt<'_>) -> Option<WithOptConstParam<LocalDefId>> {
1320 if self.const_param_did.is_none() {
1321 if let const_param_did @ Some(_) = tcx.opt_const_param_of(self.did) {
1322 return Some(WithOptConstParam { did: self.did, const_param_did });
1329 pub fn to_global(self) -> WithOptConstParam<DefId> {
1330 WithOptConstParam { did: self.did.to_def_id(), const_param_did: self.const_param_did }
1333 pub fn def_id_for_type_of(self) -> DefId {
1334 if let Some(did) = self.const_param_did { did } else { self.did.to_def_id() }
1338 impl WithOptConstParam<DefId> {
1339 pub fn as_local(self) -> Option<WithOptConstParam<LocalDefId>> {
1342 .map(|did| WithOptConstParam { did, const_param_did: self.const_param_did })
1345 pub fn as_const_arg(self) -> Option<(LocalDefId, DefId)> {
1346 if let Some(param_did) = self.const_param_did {
1347 if let Some(did) = self.did.as_local() {
1348 return Some((did, param_did));
1355 pub fn is_local(self) -> bool {
1359 pub fn def_id_for_type_of(self) -> DefId {
1360 self.const_param_did.unwrap_or(self.did)
1364 /// When type checking, we use the `ParamEnv` to track
1365 /// details about the set of where-clauses that are in scope at this
1366 /// particular point.
1367 #[derive(Copy, Clone, Hash, PartialEq, Eq)]
1368 pub struct ParamEnv<'tcx> {
1369 /// This packs both caller bounds and the reveal enum into one pointer.
1371 /// Caller bounds are `Obligation`s that the caller must satisfy. This is
1372 /// basically the set of bounds on the in-scope type parameters, translated
1373 /// into `Obligation`s, and elaborated and normalized.
1375 /// Use the `caller_bounds()` method to access.
1377 /// Typically, this is `Reveal::UserFacing`, but during codegen we
1378 /// want `Reveal::All`.
1380 /// Note: This is packed, use the reveal() method to access it.
1381 packed: CopyTaggedPtr<&'tcx List<Predicate<'tcx>>, ParamTag, true>,
1384 #[derive(Copy, Clone)]
1386 reveal: traits::Reveal,
1387 constness: hir::Constness,
1390 unsafe impl rustc_data_structures::tagged_ptr::Tag for ParamTag {
1391 const BITS: usize = 2;
1393 fn into_usize(self) -> usize {
1395 Self { reveal: traits::Reveal::UserFacing, constness: hir::Constness::NotConst } => 0,
1396 Self { reveal: traits::Reveal::All, constness: hir::Constness::NotConst } => 1,
1397 Self { reveal: traits::Reveal::UserFacing, constness: hir::Constness::Const } => 2,
1398 Self { reveal: traits::Reveal::All, constness: hir::Constness::Const } => 3,
1402 unsafe fn from_usize(ptr: usize) -> Self {
1404 0 => Self { reveal: traits::Reveal::UserFacing, constness: hir::Constness::NotConst },
1405 1 => Self { reveal: traits::Reveal::All, constness: hir::Constness::NotConst },
1406 2 => Self { reveal: traits::Reveal::UserFacing, constness: hir::Constness::Const },
1407 3 => Self { reveal: traits::Reveal::All, constness: hir::Constness::Const },
1408 _ => std::hint::unreachable_unchecked(),
1413 impl<'tcx> fmt::Debug for ParamEnv<'tcx> {
1414 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1415 f.debug_struct("ParamEnv")
1416 .field("caller_bounds", &self.caller_bounds())
1417 .field("reveal", &self.reveal())
1418 .field("constness", &self.constness())
1423 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for ParamEnv<'tcx> {
1424 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
1425 self.caller_bounds().hash_stable(hcx, hasher);
1426 self.reveal().hash_stable(hcx, hasher);
1427 self.constness().hash_stable(hcx, hasher);
1431 impl<'tcx> TypeFoldable<'tcx> for ParamEnv<'tcx> {
1432 fn try_super_fold_with<F: ty::fold::FallibleTypeFolder<'tcx>>(
1435 ) -> Result<Self, F::Error> {
1437 self.caller_bounds().try_fold_with(folder)?,
1438 self.reveal().try_fold_with(folder)?,
1439 self.constness().try_fold_with(folder)?,
1443 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> ControlFlow<V::BreakTy> {
1444 self.caller_bounds().visit_with(visitor)?;
1445 self.reveal().visit_with(visitor)?;
1446 self.constness().visit_with(visitor)
1450 impl<'tcx> ParamEnv<'tcx> {
1451 /// Construct a trait environment suitable for contexts where
1452 /// there are no where-clauses in scope. Hidden types (like `impl
1453 /// Trait`) are left hidden, so this is suitable for ordinary
1456 pub fn empty() -> Self {
1457 Self::new(List::empty(), Reveal::UserFacing, hir::Constness::NotConst)
1461 pub fn caller_bounds(self) -> &'tcx List<Predicate<'tcx>> {
1462 self.packed.pointer()
1466 pub fn reveal(self) -> traits::Reveal {
1467 self.packed.tag().reveal
1471 pub fn constness(self) -> hir::Constness {
1472 self.packed.tag().constness
1476 pub fn is_const(self) -> bool {
1477 self.packed.tag().constness == hir::Constness::Const
1480 /// Construct a trait environment with no where-clauses in scope
1481 /// where the values of all `impl Trait` and other hidden types
1482 /// are revealed. This is suitable for monomorphized, post-typeck
1483 /// environments like codegen or doing optimizations.
1485 /// N.B., if you want to have predicates in scope, use `ParamEnv::new`,
1486 /// or invoke `param_env.with_reveal_all()`.
1488 pub fn reveal_all() -> Self {
1489 Self::new(List::empty(), Reveal::All, hir::Constness::NotConst)
1492 /// Construct a trait environment with the given set of predicates.
1495 caller_bounds: &'tcx List<Predicate<'tcx>>,
1497 constness: hir::Constness,
1499 ty::ParamEnv { packed: CopyTaggedPtr::new(caller_bounds, ParamTag { reveal, constness }) }
1502 pub fn with_user_facing(mut self) -> Self {
1503 self.packed.set_tag(ParamTag { reveal: Reveal::UserFacing, ..self.packed.tag() });
1508 pub fn with_constness(mut self, constness: hir::Constness) -> Self {
1509 self.packed.set_tag(ParamTag { constness, ..self.packed.tag() });
1514 pub fn with_const(mut self) -> Self {
1515 self.packed.set_tag(ParamTag { constness: hir::Constness::Const, ..self.packed.tag() });
1520 pub fn without_const(mut self) -> Self {
1521 self.packed.set_tag(ParamTag { constness: hir::Constness::NotConst, ..self.packed.tag() });
1526 pub fn remap_constness_with(&mut self, mut constness: ty::BoundConstness) {
1527 *self = self.with_constness(constness.and(self.constness()))
1530 /// Returns a new parameter environment with the same clauses, but
1531 /// which "reveals" the true results of projections in all cases
1532 /// (even for associated types that are specializable). This is
1533 /// the desired behavior during codegen and certain other special
1534 /// contexts; normally though we want to use `Reveal::UserFacing`,
1535 /// which is the default.
1536 /// All opaque types in the caller_bounds of the `ParamEnv`
1537 /// will be normalized to their underlying types.
1538 /// See PR #65989 and issue #65918 for more details
1539 pub fn with_reveal_all_normalized(self, tcx: TyCtxt<'tcx>) -> Self {
1540 if self.packed.tag().reveal == traits::Reveal::All {
1545 tcx.normalize_opaque_types(self.caller_bounds()),
1551 /// Returns this same environment but with no caller bounds.
1553 pub fn without_caller_bounds(self) -> Self {
1554 Self::new(List::empty(), self.reveal(), self.constness())
1557 /// Creates a suitable environment in which to perform trait
1558 /// queries on the given value. When type-checking, this is simply
1559 /// the pair of the environment plus value. But when reveal is set to
1560 /// All, then if `value` does not reference any type parameters, we will
1561 /// pair it with the empty environment. This improves caching and is generally
1564 /// N.B., we preserve the environment when type-checking because it
1565 /// is possible for the user to have wacky where-clauses like
1566 /// `where Box<u32>: Copy`, which are clearly never
1567 /// satisfiable. We generally want to behave as if they were true,
1568 /// although the surrounding function is never reachable.
1569 pub fn and<T: TypeFoldable<'tcx>>(self, value: T) -> ParamEnvAnd<'tcx, T> {
1570 match self.reveal() {
1571 Reveal::UserFacing => ParamEnvAnd { param_env: self, value },
1574 if value.is_global() {
1575 ParamEnvAnd { param_env: self.without_caller_bounds(), value }
1577 ParamEnvAnd { param_env: self, value }
1584 // FIXME(ecstaticmorse): Audit all occurrences of `without_const().to_predicate(tcx)` to ensure that
1585 // the constness of trait bounds is being propagated correctly.
1586 impl<'tcx> PolyTraitRef<'tcx> {
1588 pub fn with_constness(self, constness: BoundConstness) -> PolyTraitPredicate<'tcx> {
1589 self.map_bound(|trait_ref| ty::TraitPredicate {
1592 polarity: ty::ImplPolarity::Positive,
1597 pub fn without_const(self) -> PolyTraitPredicate<'tcx> {
1598 self.with_constness(BoundConstness::NotConst)
1602 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TypeFoldable)]
1603 pub struct ParamEnvAnd<'tcx, T> {
1604 pub param_env: ParamEnv<'tcx>,
1608 impl<'tcx, T> ParamEnvAnd<'tcx, T> {
1609 pub fn into_parts(self) -> (ParamEnv<'tcx>, T) {
1610 (self.param_env, self.value)
1614 pub fn without_const(mut self) -> Self {
1615 self.param_env = self.param_env.without_const();
1620 impl<'a, 'tcx, T> HashStable<StableHashingContext<'a>> for ParamEnvAnd<'tcx, T>
1622 T: HashStable<StableHashingContext<'a>>,
1624 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
1625 let ParamEnvAnd { ref param_env, ref value } = *self;
1627 param_env.hash_stable(hcx, hasher);
1628 value.hash_stable(hcx, hasher);
1632 #[derive(Copy, Clone, Debug, HashStable)]
1633 pub struct Destructor {
1634 /// The `DefId` of the destructor method
1636 /// The constness of the destructor method
1637 pub constness: hir::Constness,
1641 #[derive(HashStable, TyEncodable, TyDecodable)]
1642 pub struct VariantFlags: u32 {
1643 const NO_VARIANT_FLAGS = 0;
1644 /// Indicates whether the field list of this variant is `#[non_exhaustive]`.
1645 const IS_FIELD_LIST_NON_EXHAUSTIVE = 1 << 0;
1646 /// Indicates whether this variant was obtained as part of recovering from
1647 /// a syntactic error. May be incomplete or bogus.
1648 const IS_RECOVERED = 1 << 1;
1652 /// Definition of a variant -- a struct's fields or an enum variant.
1653 #[derive(Debug, HashStable, TyEncodable, TyDecodable)]
1654 pub struct VariantDef {
1655 /// `DefId` that identifies the variant itself.
1656 /// If this variant belongs to a struct or union, then this is a copy of its `DefId`.
1658 /// `DefId` that identifies the variant's constructor.
1659 /// If this variant is a struct variant, then this is `None`.
1660 pub ctor_def_id: Option<DefId>,
1661 /// Variant or struct name.
1663 /// Discriminant of this variant.
1664 pub discr: VariantDiscr,
1665 /// Fields of this variant.
1666 pub fields: Vec<FieldDef>,
1667 /// Type of constructor of variant.
1668 pub ctor_kind: CtorKind,
1669 /// Flags of the variant (e.g. is field list non-exhaustive)?
1670 flags: VariantFlags,
1674 /// Creates a new `VariantDef`.
1676 /// `variant_did` is the `DefId` that identifies the enum variant (if this `VariantDef`
1677 /// represents an enum variant).
1679 /// `ctor_did` is the `DefId` that identifies the constructor of unit or
1680 /// tuple-variants/structs. If this is a `struct`-variant then this should be `None`.
1682 /// `parent_did` is the `DefId` of the `AdtDef` representing the enum or struct that
1683 /// owns this variant. It is used for checking if a struct has `#[non_exhaustive]` w/out having
1684 /// to go through the redirect of checking the ctor's attributes - but compiling a small crate
1685 /// requires loading the `AdtDef`s for all the structs in the universe (e.g., coherence for any
1686 /// built-in trait), and we do not want to load attributes twice.
1688 /// If someone speeds up attribute loading to not be a performance concern, they can
1689 /// remove this hack and use the constructor `DefId` everywhere.
1692 variant_did: Option<DefId>,
1693 ctor_def_id: Option<DefId>,
1694 discr: VariantDiscr,
1695 fields: Vec<FieldDef>,
1696 ctor_kind: CtorKind,
1700 is_field_list_non_exhaustive: bool,
1703 "VariantDef::new(name = {:?}, variant_did = {:?}, ctor_def_id = {:?}, discr = {:?},
1704 fields = {:?}, ctor_kind = {:?}, adt_kind = {:?}, parent_did = {:?})",
1705 name, variant_did, ctor_def_id, discr, fields, ctor_kind, adt_kind, parent_did,
1708 let mut flags = VariantFlags::NO_VARIANT_FLAGS;
1709 if is_field_list_non_exhaustive {
1710 flags |= VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE;
1714 flags |= VariantFlags::IS_RECOVERED;
1718 def_id: variant_did.unwrap_or(parent_did),
1728 /// Is this field list non-exhaustive?
1730 pub fn is_field_list_non_exhaustive(&self) -> bool {
1731 self.flags.intersects(VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE)
1734 /// Was this variant obtained as part of recovering from a syntactic error?
1736 pub fn is_recovered(&self) -> bool {
1737 self.flags.intersects(VariantFlags::IS_RECOVERED)
1740 /// Computes the `Ident` of this variant by looking up the `Span`
1741 pub fn ident(&self, tcx: TyCtxt<'_>) -> Ident {
1742 Ident::new(self.name, tcx.def_ident_span(self.def_id).unwrap())
1746 #[derive(Copy, Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
1747 pub enum VariantDiscr {
1748 /// Explicit value for this variant, i.e., `X = 123`.
1749 /// The `DefId` corresponds to the embedded constant.
1752 /// The previous variant's discriminant plus one.
1753 /// For efficiency reasons, the distance from the
1754 /// last `Explicit` discriminant is being stored,
1755 /// or `0` for the first variant, if it has none.
1759 #[derive(Debug, HashStable, TyEncodable, TyDecodable)]
1760 pub struct FieldDef {
1763 pub vis: Visibility,
1767 #[derive(TyEncodable, TyDecodable, Default, HashStable)]
1768 pub struct ReprFlags: u8 {
1769 const IS_C = 1 << 0;
1770 const IS_SIMD = 1 << 1;
1771 const IS_TRANSPARENT = 1 << 2;
1772 // Internal only for now. If true, don't reorder fields.
1773 const IS_LINEAR = 1 << 3;
1774 // If true, don't expose any niche to type's context.
1775 const HIDE_NICHE = 1 << 4;
1776 // If true, the type's layout can be randomized using
1777 // the seed stored in `ReprOptions.layout_seed`
1778 const RANDOMIZE_LAYOUT = 1 << 5;
1779 // Any of these flags being set prevent field reordering optimisation.
1780 const IS_UNOPTIMISABLE = ReprFlags::IS_C.bits
1781 | ReprFlags::IS_SIMD.bits
1782 | ReprFlags::IS_LINEAR.bits;
1786 /// Represents the repr options provided by the user,
1787 #[derive(Copy, Clone, Debug, Eq, PartialEq, TyEncodable, TyDecodable, Default, HashStable)]
1788 pub struct ReprOptions {
1789 pub int: Option<attr::IntType>,
1790 pub align: Option<Align>,
1791 pub pack: Option<Align>,
1792 pub flags: ReprFlags,
1793 /// The seed to be used for randomizing a type's layout
1795 /// Note: This could technically be a `[u8; 16]` (a `u128`) which would
1796 /// be the "most accurate" hash as it'd encompass the item and crate
1797 /// hash without loss, but it does pay the price of being larger.
1798 /// Everything's a tradeoff, a `u64` seed should be sufficient for our
1799 /// purposes (primarily `-Z randomize-layout`)
1800 pub field_shuffle_seed: u64,
1804 pub fn new(tcx: TyCtxt<'_>, did: DefId) -> ReprOptions {
1805 let mut flags = ReprFlags::empty();
1806 let mut size = None;
1807 let mut max_align: Option<Align> = None;
1808 let mut min_pack: Option<Align> = None;
1810 // Generate a deterministically-derived seed from the item's path hash
1811 // to allow for cross-crate compilation to actually work
1812 let mut field_shuffle_seed = tcx.def_path_hash(did).0.to_smaller_hash();
1814 // If the user defined a custom seed for layout randomization, xor the item's
1815 // path hash with the user defined seed, this will allowing determinism while
1816 // still allowing users to further randomize layout generation for e.g. fuzzing
1817 if let Some(user_seed) = tcx.sess.opts.debugging_opts.layout_seed {
1818 field_shuffle_seed ^= user_seed;
1821 for attr in tcx.get_attrs(did).iter() {
1822 for r in attr::find_repr_attrs(&tcx.sess, attr) {
1823 flags.insert(match r {
1824 attr::ReprC => ReprFlags::IS_C,
1825 attr::ReprPacked(pack) => {
1826 let pack = Align::from_bytes(pack as u64).unwrap();
1827 min_pack = Some(if let Some(min_pack) = min_pack {
1834 attr::ReprTransparent => ReprFlags::IS_TRANSPARENT,
1835 attr::ReprNoNiche => ReprFlags::HIDE_NICHE,
1836 attr::ReprSimd => ReprFlags::IS_SIMD,
1837 attr::ReprInt(i) => {
1841 attr::ReprAlign(align) => {
1842 max_align = max_align.max(Some(Align::from_bytes(align as u64).unwrap()));
1849 // If `-Z randomize-layout` was enabled for the type definition then we can
1850 // consider performing layout randomization
1851 if tcx.sess.opts.debugging_opts.randomize_layout {
1852 flags.insert(ReprFlags::RANDOMIZE_LAYOUT);
1855 // This is here instead of layout because the choice must make it into metadata.
1856 if !tcx.consider_optimizing(|| format!("Reorder fields of {:?}", tcx.def_path_str(did))) {
1857 flags.insert(ReprFlags::IS_LINEAR);
1860 Self { int: size, align: max_align, pack: min_pack, flags, field_shuffle_seed }
1864 pub fn simd(&self) -> bool {
1865 self.flags.contains(ReprFlags::IS_SIMD)
1869 pub fn c(&self) -> bool {
1870 self.flags.contains(ReprFlags::IS_C)
1874 pub fn packed(&self) -> bool {
1879 pub fn transparent(&self) -> bool {
1880 self.flags.contains(ReprFlags::IS_TRANSPARENT)
1884 pub fn linear(&self) -> bool {
1885 self.flags.contains(ReprFlags::IS_LINEAR)
1889 pub fn hide_niche(&self) -> bool {
1890 self.flags.contains(ReprFlags::HIDE_NICHE)
1893 /// Returns the discriminant type, given these `repr` options.
1894 /// This must only be called on enums!
1895 pub fn discr_type(&self) -> attr::IntType {
1896 self.int.unwrap_or(attr::SignedInt(ast::IntTy::Isize))
1899 /// Returns `true` if this `#[repr()]` should inhabit "smart enum
1900 /// layout" optimizations, such as representing `Foo<&T>` as a
1902 pub fn inhibit_enum_layout_opt(&self) -> bool {
1903 self.c() || self.int.is_some()
1906 /// Returns `true` if this `#[repr()]` should inhibit struct field reordering
1907 /// optimizations, such as with `repr(C)`, `repr(packed(1))`, or `repr(<int>)`.
1908 pub fn inhibit_struct_field_reordering_opt(&self) -> bool {
1909 if let Some(pack) = self.pack {
1910 if pack.bytes() == 1 {
1915 self.flags.intersects(ReprFlags::IS_UNOPTIMISABLE) || self.int.is_some()
1918 /// Returns `true` if this type is valid for reordering and `-Z randomize-layout`
1919 /// was enabled for its declaration crate
1920 pub fn can_randomize_type_layout(&self) -> bool {
1921 !self.inhibit_struct_field_reordering_opt()
1922 && self.flags.contains(ReprFlags::RANDOMIZE_LAYOUT)
1925 /// Returns `true` if this `#[repr()]` should inhibit union ABI optimisations.
1926 pub fn inhibit_union_abi_opt(&self) -> bool {
1931 impl<'tcx> FieldDef {
1932 /// Returns the type of this field. The resulting type is not normalized. The `subst` is
1933 /// typically obtained via the second field of [`TyKind::Adt`].
1934 pub fn ty(&self, tcx: TyCtxt<'tcx>, subst: SubstsRef<'tcx>) -> Ty<'tcx> {
1935 tcx.type_of(self.did).subst(tcx, subst)
1938 /// Computes the `Ident` of this variant by looking up the `Span`
1939 pub fn ident(&self, tcx: TyCtxt<'_>) -> Ident {
1940 Ident::new(self.name, tcx.def_ident_span(self.did).unwrap())
1944 pub type Attributes<'tcx> = &'tcx [ast::Attribute];
1946 #[derive(Debug, PartialEq, Eq)]
1947 pub enum ImplOverlapKind {
1948 /// These impls are always allowed to overlap.
1950 /// Whether or not the impl is permitted due to the trait being a `#[marker]` trait
1953 /// These impls are allowed to overlap, but that raises
1954 /// an issue #33140 future-compatibility warning.
1956 /// Some background: in Rust 1.0, the trait-object types `Send + Sync` (today's
1957 /// `dyn Send + Sync`) and `Sync + Send` (now `dyn Sync + Send`) were different.
1959 /// The widely-used version 0.1.0 of the crate `traitobject` had accidentally relied
1960 /// that difference, making what reduces to the following set of impls:
1962 /// ```compile_fail,(E0119)
1964 /// impl Trait for dyn Send + Sync {}
1965 /// impl Trait for dyn Sync + Send {}
1968 /// Obviously, once we made these types be identical, that code causes a coherence
1969 /// error and a fairly big headache for us. However, luckily for us, the trait
1970 /// `Trait` used in this case is basically a marker trait, and therefore having
1971 /// overlapping impls for it is sound.
1973 /// To handle this, we basically regard the trait as a marker trait, with an additional
1974 /// future-compatibility warning. To avoid accidentally "stabilizing" this feature,
1975 /// it has the following restrictions:
1977 /// 1. The trait must indeed be a marker-like trait (i.e., no items), and must be
1979 /// 2. The trait-ref of both impls must be equal.
1980 /// 3. The trait-ref of both impls must be a trait object type consisting only of
1982 /// 4. Neither of the impls can have any where-clauses.
1984 /// Once `traitobject` 0.1.0 is no longer an active concern, this hack can be removed.
1988 impl<'tcx> TyCtxt<'tcx> {
1989 pub fn typeck_body(self, body: hir::BodyId) -> &'tcx TypeckResults<'tcx> {
1990 self.typeck(self.hir().body_owner_def_id(body))
1993 pub fn provided_trait_methods(self, id: DefId) -> impl 'tcx + Iterator<Item = &'tcx AssocItem> {
1994 self.associated_items(id)
1995 .in_definition_order()
1996 .filter(|item| item.kind == AssocKind::Fn && item.defaultness.has_value())
1999 fn opt_item_name(self, def_id: DefId) -> Option<Symbol> {
2000 if let Some(cnum) = def_id.as_crate_root() {
2001 Some(self.crate_name(cnum))
2003 let def_key = self.def_key(def_id);
2004 match def_key.disambiguated_data.data {
2005 // The name of a constructor is that of its parent.
2006 rustc_hir::definitions::DefPathData::Ctor => self
2007 .opt_item_name(DefId { krate: def_id.krate, index: def_key.parent.unwrap() }),
2008 // The name of opaque types only exists in HIR.
2009 rustc_hir::definitions::DefPathData::ImplTrait
2010 if let Some(def_id) = def_id.as_local() =>
2011 self.hir().opt_name(self.hir().local_def_id_to_hir_id(def_id)),
2012 _ => def_key.get_opt_name(),
2017 /// Look up the name of a definition across crates. This does not look at HIR.
2019 /// When possible, this function should be used for cross-crate lookups over
2020 /// [`opt_item_name`] to avoid invalidating the incremental cache. If you
2021 /// need to handle items without a name, or HIR items that will not be
2022 /// serialized cross-crate, or if you need the span of the item, use
2023 /// [`opt_item_name`] instead.
2025 /// [`opt_item_name`]: Self::opt_item_name
2026 pub fn item_name(self, id: DefId) -> Symbol {
2027 // Look at cross-crate items first to avoid invalidating the incremental cache
2028 // unless we have to.
2029 self.opt_item_name(id).unwrap_or_else(|| {
2030 bug!("item_name: no name for {:?}", self.def_path(id));
2034 /// Look up the name and span of a definition.
2036 /// See [`item_name`][Self::item_name] for more information.
2037 pub fn opt_item_ident(self, def_id: DefId) -> Option<Ident> {
2038 let def = self.opt_item_name(def_id)?;
2041 .and_then(|id| self.def_ident_span(id))
2042 .unwrap_or(rustc_span::DUMMY_SP);
2043 Some(Ident::new(def, span))
2046 pub fn opt_associated_item(self, def_id: DefId) -> Option<&'tcx AssocItem> {
2047 if let DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy = self.def_kind(def_id) {
2048 Some(self.associated_item(def_id))
2054 pub fn field_index(self, hir_id: hir::HirId, typeck_results: &TypeckResults<'_>) -> usize {
2055 typeck_results.field_indices().get(hir_id).cloned().expect("no index for a field")
2058 pub fn find_field_index(self, ident: Ident, variant: &VariantDef) -> Option<usize> {
2062 .position(|field| self.hygienic_eq(ident, field.ident(self), variant.def_id))
2065 /// Returns `true` if the impls are the same polarity and the trait either
2066 /// has no items or is annotated `#[marker]` and prevents item overrides.
2067 pub fn impls_are_allowed_to_overlap(
2071 ) -> Option<ImplOverlapKind> {
2072 // If either trait impl references an error, they're allowed to overlap,
2073 // as one of them essentially doesn't exist.
2074 if self.impl_trait_ref(def_id1).map_or(false, |tr| tr.references_error())
2075 || self.impl_trait_ref(def_id2).map_or(false, |tr| tr.references_error())
2077 return Some(ImplOverlapKind::Permitted { marker: false });
2080 match (self.impl_polarity(def_id1), self.impl_polarity(def_id2)) {
2081 (ImplPolarity::Reservation, _) | (_, ImplPolarity::Reservation) => {
2082 // `#[rustc_reservation_impl]` impls don't overlap with anything
2084 "impls_are_allowed_to_overlap({:?}, {:?}) = Some(Permitted) (reservations)",
2087 return Some(ImplOverlapKind::Permitted { marker: false });
2089 (ImplPolarity::Positive, ImplPolarity::Negative)
2090 | (ImplPolarity::Negative, ImplPolarity::Positive) => {
2091 // `impl AutoTrait for Type` + `impl !AutoTrait for Type`
2093 "impls_are_allowed_to_overlap({:?}, {:?}) - None (differing polarities)",
2098 (ImplPolarity::Positive, ImplPolarity::Positive)
2099 | (ImplPolarity::Negative, ImplPolarity::Negative) => {}
2102 let is_marker_overlap = {
2103 let is_marker_impl = |def_id: DefId| -> bool {
2104 let trait_ref = self.impl_trait_ref(def_id);
2105 trait_ref.map_or(false, |tr| self.trait_def(tr.def_id).is_marker)
2107 is_marker_impl(def_id1) && is_marker_impl(def_id2)
2110 if is_marker_overlap {
2112 "impls_are_allowed_to_overlap({:?}, {:?}) = Some(Permitted) (marker overlap)",
2115 Some(ImplOverlapKind::Permitted { marker: true })
2117 if let Some(self_ty1) = self.issue33140_self_ty(def_id1) {
2118 if let Some(self_ty2) = self.issue33140_self_ty(def_id2) {
2119 if self_ty1 == self_ty2 {
2121 "impls_are_allowed_to_overlap({:?}, {:?}) - issue #33140 HACK",
2124 return Some(ImplOverlapKind::Issue33140);
2127 "impls_are_allowed_to_overlap({:?}, {:?}) - found {:?} != {:?}",
2128 def_id1, def_id2, self_ty1, self_ty2
2134 debug!("impls_are_allowed_to_overlap({:?}, {:?}) = None", def_id1, def_id2);
2139 /// Returns `ty::VariantDef` if `res` refers to a struct,
2140 /// or variant or their constructors, panics otherwise.
2141 pub fn expect_variant_res(self, res: Res) -> &'tcx VariantDef {
2143 Res::Def(DefKind::Variant, did) => {
2144 let enum_did = self.parent(did);
2145 self.adt_def(enum_did).variant_with_id(did)
2147 Res::Def(DefKind::Struct | DefKind::Union, did) => self.adt_def(did).non_enum_variant(),
2148 Res::Def(DefKind::Ctor(CtorOf::Variant, ..), variant_ctor_did) => {
2149 let variant_did = self.parent(variant_ctor_did);
2150 let enum_did = self.parent(variant_did);
2151 self.adt_def(enum_did).variant_with_ctor_id(variant_ctor_did)
2153 Res::Def(DefKind::Ctor(CtorOf::Struct, ..), ctor_did) => {
2154 let struct_did = self.parent(ctor_did);
2155 self.adt_def(struct_did).non_enum_variant()
2157 _ => bug!("expect_variant_res used with unexpected res {:?}", res),
2161 /// Returns the possibly-auto-generated MIR of a `(DefId, Subst)` pair.
2162 pub fn instance_mir(self, instance: ty::InstanceDef<'tcx>) -> &'tcx Body<'tcx> {
2164 ty::InstanceDef::Item(def) => match self.def_kind(def.did) {
2166 | DefKind::Static(..)
2167 | DefKind::AssocConst
2169 | DefKind::AnonConst
2170 | DefKind::InlineConst => self.mir_for_ctfe_opt_const_arg(def),
2171 // If the caller wants `mir_for_ctfe` of a function they should not be using
2172 // `instance_mir`, so we'll assume const fn also wants the optimized version.
2174 assert_eq!(def.const_param_did, None);
2175 self.optimized_mir(def.did)
2178 ty::InstanceDef::VtableShim(..)
2179 | ty::InstanceDef::ReifyShim(..)
2180 | ty::InstanceDef::Intrinsic(..)
2181 | ty::InstanceDef::FnPtrShim(..)
2182 | ty::InstanceDef::Virtual(..)
2183 | ty::InstanceDef::ClosureOnceShim { .. }
2184 | ty::InstanceDef::DropGlue(..)
2185 | ty::InstanceDef::CloneShim(..) => self.mir_shims(instance),
2189 /// Gets the attributes of a definition.
2190 pub fn get_attrs(self, did: DefId) -> Attributes<'tcx> {
2191 if let Some(did) = did.as_local() {
2192 self.hir().attrs(self.hir().local_def_id_to_hir_id(did))
2194 self.item_attrs(did)
2198 /// Determines whether an item is annotated with an attribute.
2199 pub fn has_attr(self, did: DefId, attr: Symbol) -> bool {
2200 self.sess.contains_name(&self.get_attrs(did), attr)
2203 /// Returns `true` if this is an `auto trait`.
2204 pub fn trait_is_auto(self, trait_def_id: DefId) -> bool {
2205 self.trait_def(trait_def_id).has_auto_impl
2208 /// Returns layout of a generator. Layout might be unavailable if the
2209 /// generator is tainted by errors.
2210 pub fn generator_layout(self, def_id: DefId) -> Option<&'tcx GeneratorLayout<'tcx>> {
2211 self.optimized_mir(def_id).generator_layout()
2214 /// Given the `DefId` of an impl, returns the `DefId` of the trait it implements.
2215 /// If it implements no trait, returns `None`.
2216 pub fn trait_id_of_impl(self, def_id: DefId) -> Option<DefId> {
2217 self.impl_trait_ref(def_id).map(|tr| tr.def_id)
2220 /// If the given `DefId` describes a method belonging to an impl, returns the
2221 /// `DefId` of the impl that the method belongs to; otherwise, returns `None`.
2222 pub fn impl_of_method(self, def_id: DefId) -> Option<DefId> {
2223 self.opt_associated_item(def_id).and_then(|trait_item| match trait_item.container {
2224 TraitContainer(_) => None,
2225 ImplContainer(def_id) => Some(def_id),
2229 /// If the given `DefId` belongs to a trait that was automatically derived, returns `true`.
2230 pub fn is_builtin_derive(self, def_id: DefId) -> bool {
2231 self.has_attr(def_id, sym::automatically_derived)
2234 /// Looks up the span of `impl_did` if the impl is local; otherwise returns `Err`
2235 /// with the name of the crate containing the impl.
2236 pub fn span_of_impl(self, impl_did: DefId) -> Result<Span, Symbol> {
2237 if let Some(impl_did) = impl_did.as_local() {
2238 Ok(self.def_span(impl_did))
2240 Err(self.crate_name(impl_did.krate))
2244 /// Hygienically compares a use-site name (`use_name`) for a field or an associated item with
2245 /// its supposed definition name (`def_name`). The method also needs `DefId` of the supposed
2246 /// definition's parent/scope to perform comparison.
2247 pub fn hygienic_eq(self, use_name: Ident, def_name: Ident, def_parent_def_id: DefId) -> bool {
2248 // We could use `Ident::eq` here, but we deliberately don't. The name
2249 // comparison fails frequently, and we want to avoid the expensive
2250 // `normalize_to_macros_2_0()` calls required for the span comparison whenever possible.
2251 use_name.name == def_name.name
2255 .hygienic_eq(def_name.span.ctxt(), self.expn_that_defined(def_parent_def_id))
2258 pub fn adjust_ident(self, mut ident: Ident, scope: DefId) -> Ident {
2259 ident.span.normalize_to_macros_2_0_and_adjust(self.expn_that_defined(scope));
2263 pub fn adjust_ident_and_get_scope(
2268 ) -> (Ident, DefId) {
2271 .normalize_to_macros_2_0_and_adjust(self.expn_that_defined(scope))
2272 .and_then(|actual_expansion| actual_expansion.expn_data().parent_module)
2273 .unwrap_or_else(|| self.parent_module(block).to_def_id());
2277 pub fn is_object_safe(self, key: DefId) -> bool {
2278 self.object_safety_violations(key).is_empty()
2282 pub fn is_const_fn_raw(self, def_id: DefId) -> bool {
2283 matches!(self.def_kind(def_id), DefKind::Fn | DefKind::AssocFn | DefKind::Ctor(..))
2284 && self.impl_constness(def_id) == hir::Constness::Const
2288 /// Yields the parent function's `LocalDefId` if `def_id` is an `impl Trait` definition.
2289 pub fn is_impl_trait_defn(tcx: TyCtxt<'_>, def_id: DefId) -> Option<LocalDefId> {
2290 let def_id = def_id.as_local()?;
2291 if let Node::Item(item) = tcx.hir().get_by_def_id(def_id) {
2292 if let hir::ItemKind::OpaqueTy(ref opaque_ty) = item.kind {
2293 return match opaque_ty.origin {
2294 hir::OpaqueTyOrigin::FnReturn(parent) | hir::OpaqueTyOrigin::AsyncFn(parent) => {
2297 hir::OpaqueTyOrigin::TyAlias => None,
2304 pub fn int_ty(ity: ast::IntTy) -> IntTy {
2306 ast::IntTy::Isize => IntTy::Isize,
2307 ast::IntTy::I8 => IntTy::I8,
2308 ast::IntTy::I16 => IntTy::I16,
2309 ast::IntTy::I32 => IntTy::I32,
2310 ast::IntTy::I64 => IntTy::I64,
2311 ast::IntTy::I128 => IntTy::I128,
2315 pub fn uint_ty(uty: ast::UintTy) -> UintTy {
2317 ast::UintTy::Usize => UintTy::Usize,
2318 ast::UintTy::U8 => UintTy::U8,
2319 ast::UintTy::U16 => UintTy::U16,
2320 ast::UintTy::U32 => UintTy::U32,
2321 ast::UintTy::U64 => UintTy::U64,
2322 ast::UintTy::U128 => UintTy::U128,
2326 pub fn float_ty(fty: ast::FloatTy) -> FloatTy {
2328 ast::FloatTy::F32 => FloatTy::F32,
2329 ast::FloatTy::F64 => FloatTy::F64,
2333 pub fn ast_int_ty(ity: IntTy) -> ast::IntTy {
2335 IntTy::Isize => ast::IntTy::Isize,
2336 IntTy::I8 => ast::IntTy::I8,
2337 IntTy::I16 => ast::IntTy::I16,
2338 IntTy::I32 => ast::IntTy::I32,
2339 IntTy::I64 => ast::IntTy::I64,
2340 IntTy::I128 => ast::IntTy::I128,
2344 pub fn ast_uint_ty(uty: UintTy) -> ast::UintTy {
2346 UintTy::Usize => ast::UintTy::Usize,
2347 UintTy::U8 => ast::UintTy::U8,
2348 UintTy::U16 => ast::UintTy::U16,
2349 UintTy::U32 => ast::UintTy::U32,
2350 UintTy::U64 => ast::UintTy::U64,
2351 UintTy::U128 => ast::UintTy::U128,
2355 pub fn provide(providers: &mut ty::query::Providers) {
2356 closure::provide(providers);
2357 context::provide(providers);
2358 erase_regions::provide(providers);
2359 layout::provide(providers);
2360 util::provide(providers);
2361 print::provide(providers);
2362 super::util::bug::provide(providers);
2363 super::middle::provide(providers);
2364 *providers = ty::query::Providers {
2365 trait_impls_of: trait_def::trait_impls_of_provider,
2366 incoherent_impls: trait_def::incoherent_impls_provider,
2367 type_uninhabited_from: inhabitedness::type_uninhabited_from,
2368 const_param_default: consts::const_param_default,
2369 vtable_allocation: vtable::vtable_allocation_provider,
2374 /// A map for the local crate mapping each type to a vector of its
2375 /// inherent impls. This is not meant to be used outside of coherence;
2376 /// rather, you should request the vector for a specific type via
2377 /// `tcx.inherent_impls(def_id)` so as to minimize your dependencies
2378 /// (constructing this map requires touching the entire crate).
2379 #[derive(Clone, Debug, Default, HashStable)]
2380 pub struct CrateInherentImpls {
2381 pub inherent_impls: LocalDefIdMap<Vec<DefId>>,
2382 pub incoherent_impls: FxHashMap<SimplifiedType, Vec<LocalDefId>>,
2385 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, HashStable)]
2386 pub struct SymbolName<'tcx> {
2387 /// `&str` gives a consistent ordering, which ensures reproducible builds.
2388 pub name: &'tcx str,
2391 impl<'tcx> SymbolName<'tcx> {
2392 pub fn new(tcx: TyCtxt<'tcx>, name: &str) -> SymbolName<'tcx> {
2394 name: unsafe { str::from_utf8_unchecked(tcx.arena.alloc_slice(name.as_bytes())) },
2399 impl<'tcx> fmt::Display for SymbolName<'tcx> {
2400 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2401 fmt::Display::fmt(&self.name, fmt)
2405 impl<'tcx> fmt::Debug for SymbolName<'tcx> {
2406 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2407 fmt::Display::fmt(&self.name, fmt)
2411 #[derive(Debug, Default, Copy, Clone)]
2412 pub struct FoundRelationships {
2413 /// This is true if we identified that this Ty (`?T`) is found in a `?T: Foo`
2414 /// obligation, where:
2416 /// * `Foo` is not `Sized`
2417 /// * `(): Foo` may be satisfied
2418 pub self_in_trait: bool,
2419 /// This is true if we identified that this Ty (`?T`) is found in a `<_ as
2420 /// _>::AssocType = ?T`