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 #![allow(rustc::usage_of_ty_tykind)]
14 pub use self::fold::{FallibleTypeFolder, TypeFoldable, TypeFolder, TypeSuperFoldable};
15 pub use self::visit::{TypeSuperVisitable, TypeVisitable, TypeVisitor};
16 pub use self::AssocItemContainer::*;
17 pub use self::BorrowKind::*;
18 pub use self::IntVarValue::*;
19 pub use self::Variance::*;
20 use crate::error::{OpaqueHiddenTypeMismatch, TypeMismatchReason};
21 use crate::metadata::ModChild;
22 use crate::middle::privacy::EffectiveVisibilities;
23 use crate::mir::{Body, GeneratorLayout};
24 use crate::traits::{self, Reveal};
26 use crate::ty::fast_reject::SimplifiedType;
27 use crate::ty::util::Discr;
31 use hir::OpaqueTyOrigin;
33 use rustc_ast::node_id::NodeMap;
34 use rustc_attr as attr;
35 use rustc_data_structures::fingerprint::Fingerprint;
36 use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap, FxIndexSet};
37 use rustc_data_structures::intern::Interned;
38 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
39 use rustc_data_structures::tagged_ptr::CopyTaggedPtr;
41 use rustc_hir::def::{CtorKind, CtorOf, DefKind, LifetimeRes, Res};
42 use rustc_hir::def_id::{CrateNum, DefId, LocalDefId, LocalDefIdMap};
44 use rustc_index::vec::IndexVec;
45 use rustc_macros::HashStable;
46 use rustc_query_system::ich::StableHashingContext;
47 use rustc_serialize::{Decodable, Encodable};
48 use rustc_session::cstore::Untracked;
49 use rustc_span::hygiene::MacroKind;
50 use rustc_span::symbol::{kw, sym, Ident, Symbol};
51 use rustc_span::{ExpnId, Span};
52 use rustc_target::abi::{Align, Integer, IntegerType, VariantIdx};
53 pub use rustc_target::abi::{ReprFlags, ReprOptions};
54 use rustc_type_ir::WithCachedTypeInfo;
59 use std::hash::{Hash, Hasher};
60 use std::marker::PhantomData;
62 use std::num::NonZeroUsize;
63 use std::ops::ControlFlow;
66 pub use crate::ty::diagnostics::*;
67 pub use rustc_type_ir::DynKind::*;
68 pub use rustc_type_ir::InferTy::*;
69 pub use rustc_type_ir::RegionKind::*;
70 pub use rustc_type_ir::TyKind::*;
71 pub use rustc_type_ir::*;
73 pub use self::binding::BindingMode;
74 pub use self::binding::BindingMode::*;
75 pub use self::closure::{
76 is_ancestor_or_same_capture, place_to_string_for_capture, BorrowKind, CaptureInfo,
77 CapturedPlace, ClosureKind, MinCaptureInformationMap, MinCaptureList,
78 RootVariableMinCaptureList, UpvarCapture, UpvarCaptureMap, UpvarId, UpvarListMap, UpvarPath,
81 pub use self::consts::{
82 Const, ConstInt, ConstKind, ConstS, Expr, InferConst, ScalarInt, UnevaluatedConst, ValTree,
84 pub use self::context::{
85 tls, CanonicalUserType, CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations,
86 CtxtInterners, DeducedParamAttrs, FreeRegionInfo, GeneratorDiagnosticData,
87 GeneratorInteriorTypeCause, GlobalCtxt, Lift, OnDiskCache, TyCtxt, TyCtxtFeed, TypeckResults,
88 UserType, UserTypeAnnotationIndex,
90 pub use self::instance::{Instance, InstanceDef, ShortInstance};
91 pub use self::list::List;
92 pub use self::parameterized::ParameterizedOverTcx;
93 pub use self::rvalue_scopes::RvalueScopes;
94 pub use self::sty::BoundRegionKind::*;
96 Article, Binder, BoundRegion, BoundRegionKind, BoundTy, BoundTyKind, BoundVar,
97 BoundVariableKind, CanonicalPolyFnSig, ClosureSubsts, ClosureSubstsParts, ConstVid,
98 EarlyBoundRegion, ExistentialPredicate, ExistentialProjection, ExistentialTraitRef, FnSig,
99 FreeRegion, GenSig, GeneratorSubsts, GeneratorSubstsParts, InlineConstSubsts,
100 InlineConstSubstsParts, ParamConst, ParamTy, PolyExistentialPredicate,
101 PolyExistentialProjection, PolyExistentialTraitRef, PolyFnSig, PolyGenSig, PolyTraitRef,
102 ProjectionTy, Region, RegionKind, RegionVid, TraitRef, TyKind, TypeAndMut, UpvarSubsts,
105 pub use self::trait_def::TraitDef;
108 pub mod abstract_const;
117 pub mod inhabitedness;
119 pub mod normalize_erasing_regions;
144 mod structural_impls;
149 pub type RegisteredTools = FxHashSet<Ident>;
151 pub struct ResolverOutputs {
152 pub global_ctxt: ResolverGlobalCtxt,
153 pub ast_lowering: ResolverAstLowering,
154 pub untracked: Untracked,
158 pub struct ResolverGlobalCtxt {
159 pub visibilities: FxHashMap<LocalDefId, Visibility>,
160 /// This field is used to decide whether we should make `PRIVATE_IN_PUBLIC` a hard error.
161 pub has_pub_restricted: bool,
162 /// Item with a given `LocalDefId` was defined during macro expansion with ID `ExpnId`.
163 pub expn_that_defined: FxHashMap<LocalDefId, ExpnId>,
164 pub effective_visibilities: EffectiveVisibilities,
165 pub extern_crate_map: FxHashMap<LocalDefId, CrateNum>,
166 pub maybe_unused_trait_imports: FxIndexSet<LocalDefId>,
167 pub maybe_unused_extern_crates: Vec<(LocalDefId, Span)>,
168 pub reexport_map: FxHashMap<LocalDefId, Vec<ModChild>>,
169 pub glob_map: FxHashMap<LocalDefId, FxHashSet<Symbol>>,
170 /// Extern prelude entries. The value is `true` if the entry was introduced
171 /// via `extern crate` item and not `--extern` option or compiler built-in.
172 pub extern_prelude: FxHashMap<Symbol, bool>,
173 pub main_def: Option<MainDefinition>,
174 pub trait_impls: FxIndexMap<DefId, Vec<LocalDefId>>,
175 /// A list of proc macro LocalDefIds, written out in the order in which
176 /// they are declared in the static array generated by proc_macro_harness.
177 pub proc_macros: Vec<LocalDefId>,
178 /// Mapping from ident span to path span for paths that don't exist as written, but that
179 /// exist under `std`. For example, wrote `str::from_utf8` instead of `std::str::from_utf8`.
180 pub confused_type_with_std_module: FxHashMap<Span, Span>,
181 pub registered_tools: RegisteredTools,
184 /// Resolutions that should only be used for lowering.
185 /// This struct is meant to be consumed by lowering.
187 pub struct ResolverAstLowering {
188 pub legacy_const_generic_args: FxHashMap<DefId, Option<Vec<usize>>>,
190 /// Resolutions for nodes that have a single resolution.
191 pub partial_res_map: NodeMap<hir::def::PartialRes>,
192 /// Resolutions for import nodes, which have multiple resolutions in different namespaces.
193 pub import_res_map: NodeMap<hir::def::PerNS<Option<Res<ast::NodeId>>>>,
194 /// Resolutions for labels (node IDs of their corresponding blocks or loops).
195 pub label_res_map: NodeMap<ast::NodeId>,
196 /// Resolutions for lifetimes.
197 pub lifetimes_res_map: NodeMap<LifetimeRes>,
198 /// Lifetime parameters that lowering will have to introduce.
199 pub extra_lifetime_params_map: NodeMap<Vec<(Ident, ast::NodeId, LifetimeRes)>>,
201 pub next_node_id: ast::NodeId,
203 pub node_id_to_def_id: FxHashMap<ast::NodeId, LocalDefId>,
204 pub def_id_to_node_id: IndexVec<LocalDefId, ast::NodeId>,
206 pub trait_map: NodeMap<Vec<hir::TraitCandidate>>,
207 /// A small map keeping true kinds of built-in macros that appear to be fn-like on
208 /// the surface (`macro` items in libcore), but are actually attributes or derives.
209 pub builtin_macro_kinds: FxHashMap<LocalDefId, MacroKind>,
210 /// List functions and methods for which lifetime elision was successful.
211 pub lifetime_elision_allowed: FxHashSet<ast::NodeId>,
214 #[derive(Clone, Copy, Debug)]
215 pub struct MainDefinition {
216 pub res: Res<ast::NodeId>,
221 impl MainDefinition {
222 pub fn opt_fn_def_id(self) -> Option<DefId> {
223 if let Res::Def(DefKind::Fn, def_id) = self.res { Some(def_id) } else { None }
227 /// The "header" of an impl is everything outside the body: a Self type, a trait
228 /// ref (in the case of a trait impl), and a set of predicates (from the
229 /// bounds / where-clauses).
230 #[derive(Clone, Debug, TypeFoldable, TypeVisitable)]
231 pub struct ImplHeader<'tcx> {
232 pub impl_def_id: DefId,
233 pub self_ty: Ty<'tcx>,
234 pub trait_ref: Option<TraitRef<'tcx>>,
235 pub predicates: Vec<Predicate<'tcx>>,
238 #[derive(Copy, Clone, Debug, TypeFoldable, TypeVisitable)]
239 pub enum ImplSubject<'tcx> {
240 Trait(TraitRef<'tcx>),
244 #[derive(Copy, Clone, PartialEq, Eq, Hash, TyEncodable, TyDecodable, HashStable, Debug)]
245 #[derive(TypeFoldable, TypeVisitable)]
246 pub enum ImplPolarity {
247 /// `impl Trait for Type`
249 /// `impl !Trait for Type`
251 /// `#[rustc_reservation_impl] impl Trait for Type`
253 /// This is a "stability hack", not a real Rust feature.
254 /// See #64631 for details.
259 /// Flips polarity by turning `Positive` into `Negative` and `Negative` into `Positive`.
260 pub fn flip(&self) -> Option<ImplPolarity> {
262 ImplPolarity::Positive => Some(ImplPolarity::Negative),
263 ImplPolarity::Negative => Some(ImplPolarity::Positive),
264 ImplPolarity::Reservation => None,
269 impl fmt::Display for ImplPolarity {
270 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
272 Self::Positive => f.write_str("positive"),
273 Self::Negative => f.write_str("negative"),
274 Self::Reservation => f.write_str("reservation"),
279 #[derive(Clone, Debug, PartialEq, Eq, Copy, Hash, Encodable, Decodable, HashStable)]
280 pub enum Visibility<Id = LocalDefId> {
281 /// Visible everywhere (including in other crates).
283 /// Visible only in the given crate-local module.
287 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable, TyEncodable, TyDecodable)]
288 pub enum BoundConstness {
291 /// `T: ~const Trait`
293 /// Requires resolving to const only when we are in a const context.
297 impl BoundConstness {
298 /// Reduce `self` and `constness` to two possible combined states instead of four.
299 pub fn and(&mut self, constness: hir::Constness) -> hir::Constness {
300 match (constness, self) {
301 (hir::Constness::Const, BoundConstness::ConstIfConst) => hir::Constness::Const,
303 *this = BoundConstness::NotConst;
304 hir::Constness::NotConst
310 impl fmt::Display for BoundConstness {
311 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
313 Self::NotConst => f.write_str("normal"),
314 Self::ConstIfConst => f.write_str("`~const`"),
319 #[derive(Clone, Debug, PartialEq, Eq, Copy, Hash, TyEncodable, TyDecodable, HashStable)]
320 #[derive(TypeFoldable, TypeVisitable)]
321 pub struct ClosureSizeProfileData<'tcx> {
322 /// Tuple containing the types of closure captures before the feature `capture_disjoint_fields`
323 pub before_feature_tys: Ty<'tcx>,
324 /// Tuple containing the types of closure captures after the feature `capture_disjoint_fields`
325 pub after_feature_tys: Ty<'tcx>,
328 pub trait DefIdTree: Copy {
329 fn opt_parent(self, id: DefId) -> Option<DefId>;
333 fn parent(self, id: DefId) -> DefId {
334 match self.opt_parent(id) {
336 // not `unwrap_or_else` to avoid breaking caller tracking
337 None => bug!("{id:?} doesn't have a parent"),
343 fn opt_local_parent(self, id: LocalDefId) -> Option<LocalDefId> {
344 self.opt_parent(id.to_def_id()).map(DefId::expect_local)
349 fn local_parent(self, id: LocalDefId) -> LocalDefId {
350 self.parent(id.to_def_id()).expect_local()
353 fn is_descendant_of(self, mut descendant: DefId, ancestor: DefId) -> bool {
354 if descendant.krate != ancestor.krate {
358 while descendant != ancestor {
359 match self.opt_parent(descendant) {
360 Some(parent) => descendant = parent,
361 None => return false,
368 impl<'tcx> DefIdTree for TyCtxt<'tcx> {
370 fn opt_parent(self, id: DefId) -> Option<DefId> {
371 self.def_key(id).parent.map(|index| DefId { index, ..id })
375 impl<Id> Visibility<Id> {
376 pub fn is_public(self) -> bool {
377 matches!(self, Visibility::Public)
380 pub fn map_id<OutId>(self, f: impl FnOnce(Id) -> OutId) -> Visibility<OutId> {
382 Visibility::Public => Visibility::Public,
383 Visibility::Restricted(id) => Visibility::Restricted(f(id)),
388 impl<Id: Into<DefId>> Visibility<Id> {
389 pub fn to_def_id(self) -> Visibility<DefId> {
390 self.map_id(Into::into)
393 /// Returns `true` if an item with this visibility is accessible from the given module.
394 pub fn is_accessible_from(self, module: impl Into<DefId>, tree: impl DefIdTree) -> bool {
396 // Public items are visible everywhere.
397 Visibility::Public => true,
398 Visibility::Restricted(id) => tree.is_descendant_of(module.into(), id.into()),
402 /// Returns `true` if this visibility is at least as accessible as the given visibility
403 pub fn is_at_least(self, vis: Visibility<impl Into<DefId>>, tree: impl DefIdTree) -> bool {
405 Visibility::Public => self.is_public(),
406 Visibility::Restricted(id) => self.is_accessible_from(id, tree),
411 impl Visibility<DefId> {
412 pub fn expect_local(self) -> Visibility {
413 self.map_id(|id| id.expect_local())
416 /// Returns `true` if this item is visible anywhere in the local crate.
417 pub fn is_visible_locally(self) -> bool {
419 Visibility::Public => true,
420 Visibility::Restricted(def_id) => def_id.is_local(),
425 /// The crate variances map is computed during typeck and contains the
426 /// variance of every item in the local crate. You should not use it
427 /// directly, because to do so will make your pass dependent on the
428 /// HIR of every item in the local crate. Instead, use
429 /// `tcx.variances_of()` to get the variance for a *particular*
431 #[derive(HashStable, Debug)]
432 pub struct CrateVariancesMap<'tcx> {
433 /// For each item with generics, maps to a vector of the variance
434 /// of its generics. If an item has no generics, it will have no
436 pub variances: FxHashMap<DefId, &'tcx [ty::Variance]>,
439 // Contains information needed to resolve types and (in the future) look up
440 // the types of AST nodes.
441 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
442 pub struct CReaderCacheKey {
443 pub cnum: Option<CrateNum>,
447 /// Use this rather than `TyKind`, whenever possible.
448 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, HashStable)]
449 #[rustc_diagnostic_item = "Ty"]
450 #[rustc_pass_by_value]
451 pub struct Ty<'tcx>(Interned<'tcx, WithCachedTypeInfo<TyKind<'tcx>>>);
453 impl<'tcx> TyCtxt<'tcx> {
454 /// A "bool" type used in rustc_mir_transform unit tests when we
455 /// have not spun up a TyCtxt.
456 pub const BOOL_TY_FOR_UNIT_TESTING: Ty<'tcx> =
457 Ty(Interned::new_unchecked(&WithCachedTypeInfo {
459 stable_hash: Fingerprint::ZERO,
460 flags: TypeFlags::empty(),
461 outer_exclusive_binder: DebruijnIndex::from_usize(0),
465 impl ty::EarlyBoundRegion {
466 /// Does this early bound region have a name? Early bound regions normally
467 /// always have names except when using anonymous lifetimes (`'_`).
468 pub fn has_name(&self) -> bool {
469 self.name != kw::UnderscoreLifetime && self.name != kw::Empty
473 /// Use this rather than `PredicateKind`, whenever possible.
474 #[derive(Clone, Copy, PartialEq, Eq, Hash, HashStable)]
475 #[rustc_pass_by_value]
476 pub struct Predicate<'tcx>(
477 Interned<'tcx, WithCachedTypeInfo<ty::Binder<'tcx, PredicateKind<'tcx>>>>,
480 impl<'tcx> Predicate<'tcx> {
481 /// Gets the inner `Binder<'tcx, PredicateKind<'tcx>>`.
483 pub fn kind(self) -> Binder<'tcx, PredicateKind<'tcx>> {
488 pub fn flags(self) -> TypeFlags {
493 pub fn outer_exclusive_binder(self) -> DebruijnIndex {
494 self.0.outer_exclusive_binder
497 /// Flips the polarity of a Predicate.
499 /// Given `T: Trait` predicate it returns `T: !Trait` and given `T: !Trait` returns `T: Trait`.
500 pub fn flip_polarity(self, tcx: TyCtxt<'tcx>) -> Option<Predicate<'tcx>> {
503 .map_bound(|kind| match kind {
504 PredicateKind::Clause(Clause::Trait(TraitPredicate {
508 })) => Some(PredicateKind::Clause(Clause::Trait(TraitPredicate {
511 polarity: polarity.flip()?,
518 Some(tcx.mk_predicate(kind))
521 pub fn without_const(mut self, tcx: TyCtxt<'tcx>) -> Self {
522 if let PredicateKind::Clause(Clause::Trait(TraitPredicate { trait_ref, constness, polarity })) = self.kind().skip_binder()
523 && constness != BoundConstness::NotConst
525 self = tcx.mk_predicate(self.kind().rebind(PredicateKind::Clause(Clause::Trait(TraitPredicate {
527 constness: BoundConstness::NotConst,
534 /// Whether this projection can be soundly normalized.
536 /// Wf predicates must not be normalized, as normalization
537 /// can remove required bounds which would cause us to
538 /// unsoundly accept some programs. See #91068.
540 pub fn allow_normalization(self) -> bool {
541 match self.kind().skip_binder() {
542 PredicateKind::WellFormed(_) => false,
543 PredicateKind::Clause(Clause::Trait(_))
544 | PredicateKind::Clause(Clause::RegionOutlives(_))
545 | PredicateKind::Clause(Clause::TypeOutlives(_))
546 | PredicateKind::Clause(Clause::Projection(_))
547 | PredicateKind::ObjectSafe(_)
548 | PredicateKind::ClosureKind(_, _, _)
549 | PredicateKind::Subtype(_)
550 | PredicateKind::Coerce(_)
551 | PredicateKind::ConstEvaluatable(_)
552 | PredicateKind::ConstEquate(_, _)
553 | PredicateKind::Ambiguous
554 | PredicateKind::TypeWellFormedFromEnv(_) => true,
559 impl rustc_errors::IntoDiagnosticArg for Predicate<'_> {
560 fn into_diagnostic_arg(self) -> rustc_errors::DiagnosticArgValue<'static> {
561 rustc_errors::DiagnosticArgValue::Str(std::borrow::Cow::Owned(self.to_string()))
565 #[derive(Clone, Copy, PartialEq, Eq, Hash, TyEncodable, TyDecodable)]
566 #[derive(HashStable, TypeFoldable, TypeVisitable, Lift)]
567 /// A clause is something that can appear in where bounds or be inferred
568 /// by implied bounds.
569 pub enum Clause<'tcx> {
570 /// Corresponds to `where Foo: Bar<A, B, C>`. `Foo` here would be
571 /// the `Self` type of the trait reference and `A`, `B`, and `C`
572 /// would be the type parameters.
573 Trait(TraitPredicate<'tcx>),
576 RegionOutlives(RegionOutlivesPredicate<'tcx>),
579 TypeOutlives(TypeOutlivesPredicate<'tcx>),
581 /// `where <T as TraitRef>::Name == X`, approximately.
582 /// See the `ProjectionPredicate` struct for details.
583 Projection(ProjectionPredicate<'tcx>),
586 #[derive(Clone, Copy, PartialEq, Eq, Hash, TyEncodable, TyDecodable)]
587 #[derive(HashStable, TypeFoldable, TypeVisitable, Lift)]
588 pub enum PredicateKind<'tcx> {
590 Clause(Clause<'tcx>),
592 /// No syntax: `T` well-formed.
593 WellFormed(GenericArg<'tcx>),
595 /// Trait must be object-safe.
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),
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>),
610 /// `T1` coerced to `T2`
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
618 Coerce(CoercePredicate<'tcx>),
620 /// Constant initializer must evaluate successfully.
621 ConstEvaluatable(ty::Const<'tcx>),
623 /// Constants must be equal. The first component is the const that is expected.
624 ConstEquate(Const<'tcx>, Const<'tcx>),
626 /// Represents a type found in the environment that we can use for implied bounds.
628 /// Only used for Chalk.
629 TypeWellFormedFromEnv(Ty<'tcx>),
631 /// A marker predicate that is always ambiguous.
632 /// Used for coherence to mark opaque types as possibly equal to each other but ambiguous.
636 /// The crate outlives map is computed during typeck and contains the
637 /// outlives of every item in the local crate. You should not use it
638 /// directly, because to do so will make your pass dependent on the
639 /// HIR of every item in the local crate. Instead, use
640 /// `tcx.inferred_outlives_of()` to get the outlives for a *particular*
642 #[derive(HashStable, Debug)]
643 pub struct CratePredicatesMap<'tcx> {
644 /// For each struct with outlive bounds, maps to a vector of the
645 /// predicate of its outlive bounds. If an item has no outlives
646 /// bounds, it will have no entry.
647 pub predicates: FxHashMap<DefId, &'tcx [(Clause<'tcx>, Span)]>,
650 impl<'tcx> Predicate<'tcx> {
651 /// Performs a substitution suitable for going from a
652 /// poly-trait-ref to supertraits that must hold if that
653 /// poly-trait-ref holds. This is slightly different from a normal
654 /// substitution in terms of what happens with bound regions. See
655 /// lengthy comment below for details.
656 pub fn subst_supertrait(
659 trait_ref: &ty::PolyTraitRef<'tcx>,
660 ) -> Predicate<'tcx> {
661 // The interaction between HRTB and supertraits is not entirely
662 // obvious. Let me walk you (and myself) through an example.
664 // Let's start with an easy case. Consider two traits:
666 // trait Foo<'a>: Bar<'a,'a> { }
667 // trait Bar<'b,'c> { }
669 // Now, if we have a trait reference `for<'x> T: Foo<'x>`, then
670 // we can deduce that `for<'x> T: Bar<'x,'x>`. Basically, if we
671 // knew that `Foo<'x>` (for any 'x) then we also know that
672 // `Bar<'x,'x>` (for any 'x). This more-or-less falls out from
673 // normal substitution.
675 // In terms of why this is sound, the idea is that whenever there
676 // is an impl of `T:Foo<'a>`, it must show that `T:Bar<'a,'a>`
677 // holds. So if there is an impl of `T:Foo<'a>` that applies to
678 // all `'a`, then we must know that `T:Bar<'a,'a>` holds for all
681 // Another example to be careful of is this:
683 // trait Foo1<'a>: for<'b> Bar1<'a,'b> { }
684 // trait Bar1<'b,'c> { }
686 // Here, if we have `for<'x> T: Foo1<'x>`, then what do we know?
687 // The answer is that we know `for<'x,'b> T: Bar1<'x,'b>`. The
688 // reason is similar to the previous example: any impl of
689 // `T:Foo1<'x>` must show that `for<'b> T: Bar1<'x, 'b>`. So
690 // basically we would want to collapse the bound lifetimes from
691 // the input (`trait_ref`) and the supertraits.
693 // To achieve this in practice is fairly straightforward. Let's
694 // consider the more complicated scenario:
696 // - We start out with `for<'x> T: Foo1<'x>`. In this case, `'x`
697 // has a De Bruijn index of 1. We want to produce `for<'x,'b> T: Bar1<'x,'b>`,
698 // where both `'x` and `'b` would have a DB index of 1.
699 // The substitution from the input trait-ref is therefore going to be
700 // `'a => 'x` (where `'x` has a DB index of 1).
701 // - The supertrait-ref is `for<'b> Bar1<'a,'b>`, where `'a` is an
702 // early-bound parameter and `'b' is a late-bound parameter with a
704 // - If we replace `'a` with `'x` from the input, it too will have
705 // a DB index of 1, and thus we'll have `for<'x,'b> Bar1<'x,'b>`
706 // just as we wanted.
708 // There is only one catch. If we just apply the substitution `'a
709 // => 'x` to `for<'b> Bar1<'a,'b>`, the substitution code will
710 // adjust the DB index because we substituting into a binder (it
711 // tries to be so smart...) resulting in `for<'x> for<'b>
712 // Bar1<'x,'b>` (we have no syntax for this, so use your
713 // imagination). Basically the 'x will have DB index of 2 and 'b
714 // will have DB index of 1. Not quite what we want. So we apply
715 // the substitution to the *contents* of the trait reference,
716 // rather than the trait reference itself (put another way, the
717 // substitution code expects equal binding levels in the values
718 // from the substitution and the value being substituted into, and
719 // this trick achieves that).
721 // Working through the second example:
722 // trait_ref: for<'x> T: Foo1<'^0.0>; substs: [T, '^0.0]
723 // predicate: for<'b> Self: Bar1<'a, '^0.0>; substs: [Self, 'a, '^0.0]
724 // We want to end up with:
725 // for<'x, 'b> T: Bar1<'^0.0, '^0.1>
727 // 1) We must shift all bound vars in predicate by the length
728 // of trait ref's bound vars. So, we would end up with predicate like
729 // Self: Bar1<'a, '^0.1>
730 // 2) We can then apply the trait substs to this, ending up with
731 // T: Bar1<'^0.0, '^0.1>
732 // 3) Finally, to create the final bound vars, we concatenate the bound
733 // vars of the trait ref with those of the predicate:
735 let bound_pred = self.kind();
736 let pred_bound_vars = bound_pred.bound_vars();
737 let trait_bound_vars = trait_ref.bound_vars();
738 // 1) Self: Bar1<'a, '^0.0> -> Self: Bar1<'a, '^0.1>
740 tcx.shift_bound_var_indices(trait_bound_vars.len(), bound_pred.skip_binder());
741 // 2) Self: Bar1<'a, '^0.1> -> T: Bar1<'^0.0, '^0.1>
742 let new = EarlyBinder(shifted_pred).subst(tcx, trait_ref.skip_binder().substs);
743 // 3) ['x] + ['b] -> ['x, 'b]
745 tcx.mk_bound_variable_kinds(trait_bound_vars.iter().chain(pred_bound_vars));
746 tcx.reuse_or_mk_predicate(self, ty::Binder::bind_with_vars(new, bound_vars))
750 #[derive(Clone, Copy, PartialEq, Eq, Hash, TyEncodable, TyDecodable)]
751 #[derive(HashStable, TypeFoldable, TypeVisitable, Lift)]
752 pub struct TraitPredicate<'tcx> {
753 pub trait_ref: TraitRef<'tcx>,
755 pub constness: BoundConstness,
757 /// If polarity is Positive: we are proving that the trait is implemented.
759 /// If polarity is Negative: we are proving that a negative impl of this trait
760 /// exists. (Note that coherence also checks whether negative impls of supertraits
761 /// exist via a series of predicates.)
763 /// If polarity is Reserved: that's a bug.
764 pub polarity: ImplPolarity,
767 pub type PolyTraitPredicate<'tcx> = ty::Binder<'tcx, TraitPredicate<'tcx>>;
769 impl<'tcx> TraitPredicate<'tcx> {
770 pub fn remap_constness(&mut self, param_env: &mut ParamEnv<'tcx>) {
771 *param_env = param_env.with_constness(self.constness.and(param_env.constness()))
774 /// Remap the constness of this predicate before emitting it for diagnostics.
775 pub fn remap_constness_diag(&mut self, param_env: ParamEnv<'tcx>) {
776 // this is different to `remap_constness` that callees want to print this predicate
777 // in case of selection errors. `T: ~const Drop` bounds cannot end up here when the
778 // param_env is not const because it is always satisfied in non-const contexts.
779 if let hir::Constness::NotConst = param_env.constness() {
780 self.constness = ty::BoundConstness::NotConst;
784 pub fn with_self_type(self, tcx: TyCtxt<'tcx>, self_ty: Ty<'tcx>) -> Self {
785 Self { trait_ref: self.trait_ref.with_self_type(tcx, self_ty), ..self }
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
801 pub fn is_constness_satisfied_by(self, constness: hir::Constness) -> bool {
802 match (self.constness, constness) {
803 (BoundConstness::NotConst, _)
804 | (BoundConstness::ConstIfConst, hir::Constness::Const) => true,
805 (BoundConstness::ConstIfConst, hir::Constness::NotConst) => false,
809 pub fn without_const(mut self) -> Self {
810 self.constness = BoundConstness::NotConst;
815 impl<'tcx> PolyTraitPredicate<'tcx> {
816 pub fn def_id(self) -> DefId {
817 // Ok to skip binder since trait `DefId` does not care about regions.
818 self.skip_binder().def_id()
821 pub fn self_ty(self) -> ty::Binder<'tcx, Ty<'tcx>> {
822 self.map_bound(|trait_ref| trait_ref.self_ty())
825 /// Remap the constness of this predicate before emitting it for diagnostics.
826 pub fn remap_constness_diag(&mut self, param_env: ParamEnv<'tcx>) {
827 *self = self.map_bound(|mut p| {
828 p.remap_constness_diag(param_env);
834 pub fn is_const_if_const(self) -> bool {
835 self.skip_binder().is_const_if_const()
840 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, TyEncodable, TyDecodable)]
841 #[derive(HashStable, TypeFoldable, TypeVisitable, Lift)]
842 pub struct OutlivesPredicate<A, B>(pub A, pub B);
843 pub type RegionOutlivesPredicate<'tcx> = OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>;
844 pub type TypeOutlivesPredicate<'tcx> = OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>;
845 pub type PolyRegionOutlivesPredicate<'tcx> = ty::Binder<'tcx, RegionOutlivesPredicate<'tcx>>;
846 pub type PolyTypeOutlivesPredicate<'tcx> = ty::Binder<'tcx, TypeOutlivesPredicate<'tcx>>;
848 /// Encodes that `a` must be a subtype of `b`. The `a_is_expected` flag indicates
849 /// whether the `a` type is the type that we should label as "expected" when
850 /// presenting user diagnostics.
851 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, TyEncodable, TyDecodable)]
852 #[derive(HashStable, TypeFoldable, TypeVisitable, Lift)]
853 pub struct SubtypePredicate<'tcx> {
854 pub a_is_expected: bool,
858 pub type PolySubtypePredicate<'tcx> = ty::Binder<'tcx, SubtypePredicate<'tcx>>;
860 /// Encodes that we have to coerce *from* the `a` type to the `b` type.
861 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, TyEncodable, TyDecodable)]
862 #[derive(HashStable, TypeFoldable, TypeVisitable, Lift)]
863 pub struct CoercePredicate<'tcx> {
867 pub type PolyCoercePredicate<'tcx> = ty::Binder<'tcx, CoercePredicate<'tcx>>;
869 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
870 pub struct Term<'tcx> {
872 marker: PhantomData<(Ty<'tcx>, Const<'tcx>)>,
875 impl Debug for Term<'_> {
876 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
877 let data = if let Some(ty) = self.ty() {
878 format!("Term::Ty({:?})", ty)
879 } else if let Some(ct) = self.ct() {
880 format!("Term::Ct({:?})", ct)
888 impl<'tcx> From<Ty<'tcx>> for Term<'tcx> {
889 fn from(ty: Ty<'tcx>) -> Self {
890 TermKind::Ty(ty).pack()
894 impl<'tcx> From<Const<'tcx>> for Term<'tcx> {
895 fn from(c: Const<'tcx>) -> Self {
896 TermKind::Const(c).pack()
900 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for Term<'tcx> {
901 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
902 self.unpack().hash_stable(hcx, hasher);
906 impl<'tcx> TypeFoldable<'tcx> for Term<'tcx> {
907 fn try_fold_with<F: FallibleTypeFolder<'tcx>>(self, folder: &mut F) -> Result<Self, F::Error> {
908 Ok(self.unpack().try_fold_with(folder)?.pack())
912 impl<'tcx> TypeVisitable<'tcx> for Term<'tcx> {
913 fn visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> ControlFlow<V::BreakTy> {
914 self.unpack().visit_with(visitor)
918 impl<'tcx, E: TyEncoder<I = TyCtxt<'tcx>>> Encodable<E> for Term<'tcx> {
919 fn encode(&self, e: &mut E) {
920 self.unpack().encode(e)
924 impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> Decodable<D> for Term<'tcx> {
925 fn decode(d: &mut D) -> Self {
926 let res: TermKind<'tcx> = Decodable::decode(d);
931 impl<'tcx> Term<'tcx> {
933 pub fn unpack(self) -> TermKind<'tcx> {
934 let ptr = self.ptr.get();
935 // SAFETY: use of `Interned::new_unchecked` here is ok because these
936 // pointers were originally created from `Interned` types in `pack()`,
937 // and this is just going in the other direction.
939 match ptr & TAG_MASK {
940 TYPE_TAG => TermKind::Ty(Ty(Interned::new_unchecked(
941 &*((ptr & !TAG_MASK) as *const WithCachedTypeInfo<ty::TyKind<'tcx>>),
943 CONST_TAG => TermKind::Const(ty::Const(Interned::new_unchecked(
944 &*((ptr & !TAG_MASK) as *const ty::ConstS<'tcx>),
946 _ => core::intrinsics::unreachable(),
951 pub fn ty(&self) -> Option<Ty<'tcx>> {
952 if let TermKind::Ty(ty) = self.unpack() { Some(ty) } else { None }
955 pub fn ct(&self) -> Option<Const<'tcx>> {
956 if let TermKind::Const(c) = self.unpack() { Some(c) } else { None }
959 pub fn into_arg(self) -> GenericArg<'tcx> {
960 match self.unpack() {
961 TermKind::Ty(ty) => ty.into(),
962 TermKind::Const(c) => c.into(),
967 const TAG_MASK: usize = 0b11;
968 const TYPE_TAG: usize = 0b00;
969 const CONST_TAG: usize = 0b01;
971 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, TyEncodable, TyDecodable)]
972 #[derive(HashStable, TypeFoldable, TypeVisitable)]
973 pub enum TermKind<'tcx> {
978 impl<'tcx> TermKind<'tcx> {
980 fn pack(self) -> Term<'tcx> {
981 let (tag, ptr) = match self {
982 TermKind::Ty(ty) => {
983 // Ensure we can use the tag bits.
984 assert_eq!(mem::align_of_val(&*ty.0.0) & TAG_MASK, 0);
985 (TYPE_TAG, ty.0.0 as *const WithCachedTypeInfo<ty::TyKind<'tcx>> as usize)
987 TermKind::Const(ct) => {
988 // Ensure we can use the tag bits.
989 assert_eq!(mem::align_of_val(&*ct.0.0) & TAG_MASK, 0);
990 (CONST_TAG, ct.0.0 as *const ty::ConstS<'tcx> as usize)
994 Term { ptr: unsafe { NonZeroUsize::new_unchecked(ptr | tag) }, marker: PhantomData }
998 /// This kind of predicate has no *direct* correspondent in the
999 /// syntax, but it roughly corresponds to the syntactic forms:
1001 /// 1. `T: TraitRef<..., Item = Type>`
1002 /// 2. `<T as TraitRef<...>>::Item == Type` (NYI)
1004 /// In particular, form #1 is "desugared" to the combination of a
1005 /// normal trait predicate (`T: TraitRef<...>`) and one of these
1006 /// predicates. Form #2 is a broader form in that it also permits
1007 /// equality between arbitrary types. Processing an instance of
1008 /// Form #2 eventually yields one of these `ProjectionPredicate`
1009 /// instances to normalize the LHS.
1010 #[derive(Copy, Clone, PartialEq, Eq, Hash, TyEncodable, TyDecodable)]
1011 #[derive(HashStable, TypeFoldable, TypeVisitable, Lift)]
1012 pub struct ProjectionPredicate<'tcx> {
1013 pub projection_ty: ProjectionTy<'tcx>,
1014 pub term: Term<'tcx>,
1017 pub type PolyProjectionPredicate<'tcx> = Binder<'tcx, ProjectionPredicate<'tcx>>;
1019 impl<'tcx> PolyProjectionPredicate<'tcx> {
1020 /// Returns the `DefId` of the trait of the associated item being projected.
1022 pub fn trait_def_id(&self, tcx: TyCtxt<'tcx>) -> DefId {
1023 self.skip_binder().projection_ty.trait_def_id(tcx)
1026 /// Get the [PolyTraitRef] required for this projection to be well formed.
1027 /// Note that for generic associated types the predicates of the associated
1028 /// type also need to be checked.
1030 pub fn required_poly_trait_ref(&self, tcx: TyCtxt<'tcx>) -> PolyTraitRef<'tcx> {
1031 // Note: unlike with `TraitRef::to_poly_trait_ref()`,
1032 // `self.0.trait_ref` is permitted to have escaping regions.
1033 // This is because here `self` has a `Binder` and so does our
1034 // return value, so we are preserving the number of binding
1036 self.map_bound(|predicate| predicate.projection_ty.trait_ref(tcx))
1039 pub fn term(&self) -> Binder<'tcx, Term<'tcx>> {
1040 self.map_bound(|predicate| predicate.term)
1043 /// The `DefId` of the `TraitItem` for the associated type.
1045 /// Note that this is not the `DefId` of the `TraitRef` containing this
1046 /// associated type, which is in `tcx.associated_item(projection_def_id()).container`.
1047 pub fn projection_def_id(&self) -> DefId {
1048 // Ok to skip binder since trait `DefId` does not care about regions.
1049 self.skip_binder().projection_ty.item_def_id
1053 pub trait ToPolyTraitRef<'tcx> {
1054 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx>;
1057 impl<'tcx> ToPolyTraitRef<'tcx> for PolyTraitPredicate<'tcx> {
1058 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
1059 self.map_bound_ref(|trait_pred| trait_pred.trait_ref)
1063 pub trait ToPredicate<'tcx, P = Predicate<'tcx>> {
1064 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> P;
1067 impl<'tcx, T> ToPredicate<'tcx, T> for T {
1068 fn to_predicate(self, _tcx: TyCtxt<'tcx>) -> T {
1073 impl<'tcx> ToPredicate<'tcx> for Binder<'tcx, PredicateKind<'tcx>> {
1075 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1076 tcx.mk_predicate(self)
1080 impl<'tcx> ToPredicate<'tcx> for Clause<'tcx> {
1082 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1083 tcx.mk_predicate(ty::Binder::dummy(ty::PredicateKind::Clause(self)))
1087 impl<'tcx> ToPredicate<'tcx> for Binder<'tcx, TraitRef<'tcx>> {
1089 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1090 let pred: PolyTraitPredicate<'tcx> = self.to_predicate(tcx);
1091 pred.to_predicate(tcx)
1095 impl<'tcx> ToPredicate<'tcx, PolyTraitPredicate<'tcx>> for Binder<'tcx, TraitRef<'tcx>> {
1097 fn to_predicate(self, _: TyCtxt<'tcx>) -> PolyTraitPredicate<'tcx> {
1098 self.map_bound(|trait_ref| TraitPredicate {
1100 constness: ty::BoundConstness::NotConst,
1101 polarity: ty::ImplPolarity::Positive,
1106 impl<'tcx> ToPredicate<'tcx> for PolyTraitPredicate<'tcx> {
1107 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1108 self.map_bound(|p| PredicateKind::Clause(Clause::Trait(p))).to_predicate(tcx)
1112 impl<'tcx> ToPredicate<'tcx> for PolyRegionOutlivesPredicate<'tcx> {
1113 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1114 self.map_bound(|p| PredicateKind::Clause(Clause::RegionOutlives(p))).to_predicate(tcx)
1118 impl<'tcx> ToPredicate<'tcx> for PolyTypeOutlivesPredicate<'tcx> {
1119 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1120 self.map_bound(|p| PredicateKind::Clause(Clause::TypeOutlives(p))).to_predicate(tcx)
1124 impl<'tcx> ToPredicate<'tcx> for PolyProjectionPredicate<'tcx> {
1125 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1126 self.map_bound(|p| PredicateKind::Clause(Clause::Projection(p))).to_predicate(tcx)
1130 impl<'tcx> Predicate<'tcx> {
1131 pub fn to_opt_poly_trait_pred(self) -> Option<PolyTraitPredicate<'tcx>> {
1132 let predicate = self.kind();
1133 match predicate.skip_binder() {
1134 PredicateKind::Clause(Clause::Trait(t)) => Some(predicate.rebind(t)),
1135 PredicateKind::Clause(Clause::Projection(..))
1136 | PredicateKind::Subtype(..)
1137 | PredicateKind::Coerce(..)
1138 | PredicateKind::Clause(Clause::RegionOutlives(..))
1139 | PredicateKind::WellFormed(..)
1140 | PredicateKind::ObjectSafe(..)
1141 | PredicateKind::ClosureKind(..)
1142 | PredicateKind::Clause(Clause::TypeOutlives(..))
1143 | PredicateKind::ConstEvaluatable(..)
1144 | PredicateKind::ConstEquate(..)
1145 | PredicateKind::Ambiguous
1146 | PredicateKind::TypeWellFormedFromEnv(..) => None,
1150 pub fn to_opt_poly_projection_pred(self) -> Option<PolyProjectionPredicate<'tcx>> {
1151 let predicate = self.kind();
1152 match predicate.skip_binder() {
1153 PredicateKind::Clause(Clause::Projection(t)) => Some(predicate.rebind(t)),
1154 PredicateKind::Clause(Clause::Trait(..))
1155 | PredicateKind::Subtype(..)
1156 | PredicateKind::Coerce(..)
1157 | PredicateKind::Clause(Clause::RegionOutlives(..))
1158 | PredicateKind::WellFormed(..)
1159 | PredicateKind::ObjectSafe(..)
1160 | PredicateKind::ClosureKind(..)
1161 | PredicateKind::Clause(Clause::TypeOutlives(..))
1162 | PredicateKind::ConstEvaluatable(..)
1163 | PredicateKind::ConstEquate(..)
1164 | PredicateKind::Ambiguous
1165 | PredicateKind::TypeWellFormedFromEnv(..) => None,
1169 pub fn to_opt_type_outlives(self) -> Option<PolyTypeOutlivesPredicate<'tcx>> {
1170 let predicate = self.kind();
1171 match predicate.skip_binder() {
1172 PredicateKind::Clause(Clause::TypeOutlives(data)) => Some(predicate.rebind(data)),
1173 PredicateKind::Clause(Clause::Trait(..))
1174 | PredicateKind::Clause(Clause::Projection(..))
1175 | PredicateKind::Subtype(..)
1176 | PredicateKind::Coerce(..)
1177 | PredicateKind::Clause(Clause::RegionOutlives(..))
1178 | PredicateKind::WellFormed(..)
1179 | PredicateKind::ObjectSafe(..)
1180 | PredicateKind::ClosureKind(..)
1181 | PredicateKind::ConstEvaluatable(..)
1182 | PredicateKind::ConstEquate(..)
1183 | PredicateKind::Ambiguous
1184 | PredicateKind::TypeWellFormedFromEnv(..) => None,
1189 /// Represents the bounds declared on a particular set of type
1190 /// parameters. Should eventually be generalized into a flag list of
1191 /// where-clauses. You can obtain an `InstantiatedPredicates` list from a
1192 /// `GenericPredicates` by using the `instantiate` method. Note that this method
1193 /// reflects an important semantic invariant of `InstantiatedPredicates`: while
1194 /// the `GenericPredicates` are expressed in terms of the bound type
1195 /// parameters of the impl/trait/whatever, an `InstantiatedPredicates` instance
1196 /// represented a set of bounds for some particular instantiation,
1197 /// meaning that the generic parameters have been substituted with
1201 /// ```ignore (illustrative)
1202 /// struct Foo<T, U: Bar<T>> { ... }
1204 /// Here, the `GenericPredicates` for `Foo` would contain a list of bounds like
1205 /// `[[], [U:Bar<T>]]`. Now if there were some particular reference
1206 /// like `Foo<isize,usize>`, then the `InstantiatedPredicates` would be `[[],
1207 /// [usize:Bar<isize>]]`.
1208 #[derive(Clone, Debug, TypeFoldable, TypeVisitable)]
1209 pub struct InstantiatedPredicates<'tcx> {
1210 pub predicates: Vec<Predicate<'tcx>>,
1211 pub spans: Vec<Span>,
1214 impl<'tcx> InstantiatedPredicates<'tcx> {
1215 pub fn empty() -> InstantiatedPredicates<'tcx> {
1216 InstantiatedPredicates { predicates: vec![], spans: vec![] }
1219 pub fn is_empty(&self) -> bool {
1220 self.predicates.is_empty()
1224 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable, TyEncodable, TyDecodable, Lift)]
1225 #[derive(TypeFoldable, TypeVisitable)]
1226 pub struct OpaqueTypeKey<'tcx> {
1227 pub def_id: LocalDefId,
1228 pub substs: SubstsRef<'tcx>,
1231 #[derive(Copy, Clone, Debug, TypeFoldable, TypeVisitable, HashStable, TyEncodable, TyDecodable)]
1232 pub struct OpaqueHiddenType<'tcx> {
1233 /// The span of this particular definition of the opaque type. So
1236 /// ```ignore (incomplete snippet)
1237 /// type Foo = impl Baz;
1238 /// fn bar() -> Foo {
1239 /// // ^^^ This is the span we are looking for!
1243 /// In cases where the fn returns `(impl Trait, impl Trait)` or
1244 /// other such combinations, the result is currently
1245 /// over-approximated, but better than nothing.
1248 /// The type variable that represents the value of the opaque type
1249 /// that we require. In other words, after we compile this function,
1250 /// we will be created a constraint like:
1251 /// ```ignore (pseudo-rust)
1254 /// where `?C` is the value of this type variable. =) It may
1255 /// naturally refer to the type and lifetime parameters in scope
1256 /// in this function, though ultimately it should only reference
1257 /// those that are arguments to `Foo` in the constraint above. (In
1258 /// other words, `?C` should not include `'b`, even though it's a
1259 /// lifetime parameter on `foo`.)
1263 impl<'tcx> OpaqueHiddenType<'tcx> {
1264 pub fn report_mismatch(&self, other: &Self, tcx: TyCtxt<'tcx>) {
1265 // Found different concrete types for the opaque type.
1266 let sub_diag = if self.span == other.span {
1267 TypeMismatchReason::ConflictType { span: self.span }
1269 TypeMismatchReason::PreviousUse { span: self.span }
1271 tcx.sess.emit_err(OpaqueHiddenTypeMismatch {
1274 other_span: other.span,
1279 #[instrument(level = "debug", skip(tcx), ret)]
1280 pub fn remap_generic_params_to_declaration_params(
1282 opaque_type_key: OpaqueTypeKey<'tcx>,
1284 // typeck errors have subpar spans for opaque types, so delay error reporting until borrowck.
1285 ignore_errors: bool,
1286 origin: OpaqueTyOrigin,
1288 let OpaqueTypeKey { def_id, substs } = opaque_type_key;
1290 // Use substs to build up a reverse map from regions to their
1291 // identity mappings. This is necessary because of `impl
1292 // Trait` lifetimes are computed by replacing existing
1293 // lifetimes with 'static and remapping only those used in the
1294 // `impl Trait` return type, resulting in the parameters
1296 let id_substs = InternalSubsts::identity_for_item(tcx, def_id.to_def_id());
1299 // This zip may have several times the same lifetime in `substs` paired with a different
1300 // lifetime from `id_substs`. Simply `collect`ing the iterator is the correct behaviour:
1301 // it will pick the last one, which is the one we introduced in the impl-trait desugaring.
1302 let map = substs.iter().zip(id_substs);
1304 let map: FxHashMap<GenericArg<'tcx>, GenericArg<'tcx>> = match origin {
1305 // HACK: The HIR lowering for async fn does not generate
1306 // any `+ Captures<'x>` bounds for the `impl Future<...>`, so all async fns with lifetimes
1307 // would now fail to compile. We should probably just make hir lowering fill this in properly.
1308 OpaqueTyOrigin::AsyncFn(_) => map.collect(),
1309 OpaqueTyOrigin::FnReturn(_) | OpaqueTyOrigin::TyAlias => {
1310 // Opaque types may only use regions that are bound. So for
1312 // type Foo<'a, 'b, 'c> = impl Trait<'a> + 'b;
1314 // we may not use `'c` in the hidden type.
1315 let variances = tcx.variances_of(def_id);
1318 map.filter(|(_, v)| {
1319 let ty::GenericArgKind::Lifetime(lt) = v.unpack() else { return true };
1320 let ty::ReEarlyBound(ebr) = lt.kind() else { bug!() };
1321 variances[ebr.index as usize] == ty::Variance::Invariant
1326 debug!("map = {:#?}", map);
1328 // Convert the type from the function into a type valid outside
1329 // the function, by replacing invalid regions with 'static,
1330 // after producing an error for each of them.
1331 self.fold_with(&mut opaque_types::ReverseMapper::new(tcx, map, self.span, ignore_errors))
1335 /// The "placeholder index" fully defines a placeholder region, type, or const. Placeholders are
1336 /// identified by both a universe, as well as a name residing within that universe. Distinct bound
1337 /// regions/types/consts within the same universe simply have an unknown relationship to one
1339 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
1340 #[derive(HashStable, TyEncodable, TyDecodable)]
1341 pub struct Placeholder<T> {
1342 pub universe: UniverseIndex,
1346 pub type PlaceholderRegion = Placeholder<BoundRegionKind>;
1348 pub type PlaceholderType = Placeholder<BoundVar>;
1350 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable)]
1351 #[derive(TyEncodable, TyDecodable, PartialOrd, Ord)]
1352 pub struct BoundConst<'tcx> {
1357 pub type PlaceholderConst<'tcx> = Placeholder<BoundVar>;
1359 /// A `DefId` which, in case it is a const argument, is potentially bundled with
1360 /// the `DefId` of the generic parameter it instantiates.
1362 /// This is used to avoid calls to `type_of` for const arguments during typeck
1363 /// which cause cycle errors.
1368 /// fn foo<const N: usize>(&self) -> [u8; N] { [0; N] }
1369 /// // ^ const parameter
1373 /// fn foo<const M: u8>(&self) -> usize { 42 }
1374 /// // ^ const parameter
1379 /// let _b = a.foo::<{ 3 + 7 }>();
1380 /// // ^^^^^^^^^ const argument
1384 /// Let's look at the call `a.foo::<{ 3 + 7 }>()` here. We do not know
1385 /// which `foo` is used until we know the type of `a`.
1387 /// We only know the type of `a` once we are inside of `typeck(main)`.
1388 /// We also end up normalizing the type of `_b` during `typeck(main)` which
1389 /// requires us to evaluate the const argument.
1391 /// To evaluate that const argument we need to know its type,
1392 /// which we would get using `type_of(const_arg)`. This requires us to
1393 /// resolve `foo` as it can be either `usize` or `u8` in this example.
1394 /// However, resolving `foo` once again requires `typeck(main)` to get the type of `a`,
1395 /// which results in a cycle.
1397 /// In short we must not call `type_of(const_arg)` during `typeck(main)`.
1399 /// When first creating the `ty::Const` of the const argument inside of `typeck` we have
1400 /// already resolved `foo` so we know which const parameter this argument instantiates.
1401 /// This means that we also know the expected result of `type_of(const_arg)` even if we
1402 /// aren't allowed to call that query: it is equal to `type_of(const_param)` which is
1403 /// trivial to compute.
1405 /// If we now want to use that constant in a place which potentially needs its type
1406 /// we also pass the type of its `const_param`. This is the point of `WithOptConstParam`,
1407 /// except that instead of a `Ty` we bundle the `DefId` of the const parameter.
1408 /// Meaning that we need to use `type_of(const_param_did)` if `const_param_did` is `Some`
1409 /// to get the type of `did`.
1410 #[derive(Copy, Clone, Debug, TypeFoldable, TypeVisitable, Lift, TyEncodable, TyDecodable)]
1411 #[derive(PartialEq, Eq, PartialOrd, Ord)]
1412 #[derive(Hash, HashStable)]
1413 pub struct WithOptConstParam<T> {
1415 /// The `DefId` of the corresponding generic parameter in case `did` is
1416 /// a const argument.
1418 /// Note that even if `did` is a const argument, this may still be `None`.
1419 /// All queries taking `WithOptConstParam` start by calling `tcx.opt_const_param_of(def.did)`
1420 /// to potentially update `param_did` in the case it is `None`.
1421 pub const_param_did: Option<DefId>,
1424 impl<T> WithOptConstParam<T> {
1425 /// Creates a new `WithOptConstParam` setting `const_param_did` to `None`.
1427 pub fn unknown(did: T) -> WithOptConstParam<T> {
1428 WithOptConstParam { did, const_param_did: None }
1432 impl WithOptConstParam<LocalDefId> {
1433 /// Returns `Some((did, param_did))` if `def_id` is a const argument,
1434 /// `None` otherwise.
1436 pub fn try_lookup(did: LocalDefId, tcx: TyCtxt<'_>) -> Option<(LocalDefId, DefId)> {
1437 tcx.opt_const_param_of(did).map(|param_did| (did, param_did))
1440 /// In case `self` is unknown but `self.did` is a const argument, this returns
1441 /// a `WithOptConstParam` with the correct `const_param_did`.
1443 pub fn try_upgrade(self, tcx: TyCtxt<'_>) -> Option<WithOptConstParam<LocalDefId>> {
1444 if self.const_param_did.is_none() {
1445 if let const_param_did @ Some(_) = tcx.opt_const_param_of(self.did) {
1446 return Some(WithOptConstParam { did: self.did, const_param_did });
1453 pub fn to_global(self) -> WithOptConstParam<DefId> {
1454 WithOptConstParam { did: self.did.to_def_id(), const_param_did: self.const_param_did }
1457 pub fn def_id_for_type_of(self) -> DefId {
1458 if let Some(did) = self.const_param_did { did } else { self.did.to_def_id() }
1462 impl WithOptConstParam<DefId> {
1463 pub fn as_local(self) -> Option<WithOptConstParam<LocalDefId>> {
1466 .map(|did| WithOptConstParam { did, const_param_did: self.const_param_did })
1469 pub fn as_const_arg(self) -> Option<(LocalDefId, DefId)> {
1470 if let Some(param_did) = self.const_param_did {
1471 if let Some(did) = self.did.as_local() {
1472 return Some((did, param_did));
1479 pub fn is_local(self) -> bool {
1483 pub fn def_id_for_type_of(self) -> DefId {
1484 self.const_param_did.unwrap_or(self.did)
1488 /// When type checking, we use the `ParamEnv` to track
1489 /// details about the set of where-clauses that are in scope at this
1490 /// particular point.
1491 #[derive(Copy, Clone, Hash, PartialEq, Eq)]
1492 pub struct ParamEnv<'tcx> {
1493 /// This packs both caller bounds and the reveal enum into one pointer.
1495 /// Caller bounds are `Obligation`s that the caller must satisfy. This is
1496 /// basically the set of bounds on the in-scope type parameters, translated
1497 /// into `Obligation`s, and elaborated and normalized.
1499 /// Use the `caller_bounds()` method to access.
1501 /// Typically, this is `Reveal::UserFacing`, but during codegen we
1502 /// want `Reveal::All`.
1504 /// Note: This is packed, use the reveal() method to access it.
1505 packed: CopyTaggedPtr<&'tcx List<Predicate<'tcx>>, ParamTag, true>,
1508 #[derive(Copy, Clone)]
1510 reveal: traits::Reveal,
1511 constness: hir::Constness,
1514 unsafe impl rustc_data_structures::tagged_ptr::Tag for ParamTag {
1515 const BITS: usize = 2;
1517 fn into_usize(self) -> usize {
1519 Self { reveal: traits::Reveal::UserFacing, constness: hir::Constness::NotConst } => 0,
1520 Self { reveal: traits::Reveal::All, constness: hir::Constness::NotConst } => 1,
1521 Self { reveal: traits::Reveal::UserFacing, constness: hir::Constness::Const } => 2,
1522 Self { reveal: traits::Reveal::All, constness: hir::Constness::Const } => 3,
1526 unsafe fn from_usize(ptr: usize) -> Self {
1528 0 => Self { reveal: traits::Reveal::UserFacing, constness: hir::Constness::NotConst },
1529 1 => Self { reveal: traits::Reveal::All, constness: hir::Constness::NotConst },
1530 2 => Self { reveal: traits::Reveal::UserFacing, constness: hir::Constness::Const },
1531 3 => Self { reveal: traits::Reveal::All, constness: hir::Constness::Const },
1532 _ => std::hint::unreachable_unchecked(),
1537 impl<'tcx> fmt::Debug for ParamEnv<'tcx> {
1538 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1539 f.debug_struct("ParamEnv")
1540 .field("caller_bounds", &self.caller_bounds())
1541 .field("reveal", &self.reveal())
1542 .field("constness", &self.constness())
1547 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for ParamEnv<'tcx> {
1548 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
1549 self.caller_bounds().hash_stable(hcx, hasher);
1550 self.reveal().hash_stable(hcx, hasher);
1551 self.constness().hash_stable(hcx, hasher);
1555 impl<'tcx> TypeFoldable<'tcx> for ParamEnv<'tcx> {
1556 fn try_fold_with<F: ty::fold::FallibleTypeFolder<'tcx>>(
1559 ) -> Result<Self, F::Error> {
1561 self.caller_bounds().try_fold_with(folder)?,
1562 self.reveal().try_fold_with(folder)?,
1568 impl<'tcx> TypeVisitable<'tcx> for ParamEnv<'tcx> {
1569 fn visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> ControlFlow<V::BreakTy> {
1570 self.caller_bounds().visit_with(visitor)?;
1571 self.reveal().visit_with(visitor)
1575 impl<'tcx> ParamEnv<'tcx> {
1576 /// Construct a trait environment suitable for contexts where
1577 /// there are no where-clauses in scope. Hidden types (like `impl
1578 /// Trait`) are left hidden, so this is suitable for ordinary
1581 pub fn empty() -> Self {
1582 Self::new(List::empty(), Reveal::UserFacing, hir::Constness::NotConst)
1586 pub fn caller_bounds(self) -> &'tcx List<Predicate<'tcx>> {
1587 self.packed.pointer()
1591 pub fn reveal(self) -> traits::Reveal {
1592 self.packed.tag().reveal
1596 pub fn constness(self) -> hir::Constness {
1597 self.packed.tag().constness
1601 pub fn is_const(self) -> bool {
1602 self.packed.tag().constness == hir::Constness::Const
1605 /// Construct a trait environment with no where-clauses in scope
1606 /// where the values of all `impl Trait` and other hidden types
1607 /// are revealed. This is suitable for monomorphized, post-typeck
1608 /// environments like codegen or doing optimizations.
1610 /// N.B., if you want to have predicates in scope, use `ParamEnv::new`,
1611 /// or invoke `param_env.with_reveal_all()`.
1613 pub fn reveal_all() -> Self {
1614 Self::new(List::empty(), Reveal::All, hir::Constness::NotConst)
1617 /// Construct a trait environment with the given set of predicates.
1620 caller_bounds: &'tcx List<Predicate<'tcx>>,
1622 constness: hir::Constness,
1624 ty::ParamEnv { packed: CopyTaggedPtr::new(caller_bounds, ParamTag { reveal, constness }) }
1627 pub fn with_user_facing(mut self) -> Self {
1628 self.packed.set_tag(ParamTag { reveal: Reveal::UserFacing, ..self.packed.tag() });
1633 pub fn with_constness(mut self, constness: hir::Constness) -> Self {
1634 self.packed.set_tag(ParamTag { constness, ..self.packed.tag() });
1639 pub fn with_const(mut self) -> Self {
1640 self.packed.set_tag(ParamTag { constness: hir::Constness::Const, ..self.packed.tag() });
1645 pub fn without_const(mut self) -> Self {
1646 self.packed.set_tag(ParamTag { constness: hir::Constness::NotConst, ..self.packed.tag() });
1651 pub fn remap_constness_with(&mut self, mut constness: ty::BoundConstness) {
1652 *self = self.with_constness(constness.and(self.constness()))
1655 /// Returns a new parameter environment with the same clauses, but
1656 /// which "reveals" the true results of projections in all cases
1657 /// (even for associated types that are specializable). This is
1658 /// the desired behavior during codegen and certain other special
1659 /// contexts; normally though we want to use `Reveal::UserFacing`,
1660 /// which is the default.
1661 /// All opaque types in the caller_bounds of the `ParamEnv`
1662 /// will be normalized to their underlying types.
1663 /// See PR #65989 and issue #65918 for more details
1664 pub fn with_reveal_all_normalized(self, tcx: TyCtxt<'tcx>) -> Self {
1665 if self.packed.tag().reveal == traits::Reveal::All {
1670 tcx.reveal_opaque_types_in_bounds(self.caller_bounds()),
1676 /// Returns this same environment but with no caller bounds.
1678 pub fn without_caller_bounds(self) -> Self {
1679 Self::new(List::empty(), self.reveal(), self.constness())
1682 /// Creates a suitable environment in which to perform trait
1683 /// queries on the given value. When type-checking, this is simply
1684 /// the pair of the environment plus value. But when reveal is set to
1685 /// All, then if `value` does not reference any type parameters, we will
1686 /// pair it with the empty environment. This improves caching and is generally
1689 /// N.B., we preserve the environment when type-checking because it
1690 /// is possible for the user to have wacky where-clauses like
1691 /// `where Box<u32>: Copy`, which are clearly never
1692 /// satisfiable. We generally want to behave as if they were true,
1693 /// although the surrounding function is never reachable.
1694 pub fn and<T: TypeVisitable<'tcx>>(self, value: T) -> ParamEnvAnd<'tcx, T> {
1695 match self.reveal() {
1696 Reveal::UserFacing => ParamEnvAnd { param_env: self, value },
1699 if value.is_global() {
1700 ParamEnvAnd { param_env: self.without_caller_bounds(), value }
1702 ParamEnvAnd { param_env: self, value }
1709 // FIXME(ecstaticmorse): Audit all occurrences of `without_const().to_predicate(tcx)` to ensure that
1710 // the constness of trait bounds is being propagated correctly.
1711 impl<'tcx> PolyTraitRef<'tcx> {
1713 pub fn with_constness(self, constness: BoundConstness) -> PolyTraitPredicate<'tcx> {
1714 self.map_bound(|trait_ref| ty::TraitPredicate {
1717 polarity: ty::ImplPolarity::Positive,
1722 pub fn without_const(self) -> PolyTraitPredicate<'tcx> {
1723 self.with_constness(BoundConstness::NotConst)
1727 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TypeFoldable, TypeVisitable)]
1728 #[derive(HashStable, Lift)]
1729 pub struct ParamEnvAnd<'tcx, T> {
1730 pub param_env: ParamEnv<'tcx>,
1734 impl<'tcx, T> ParamEnvAnd<'tcx, T> {
1735 pub fn into_parts(self) -> (ParamEnv<'tcx>, T) {
1736 (self.param_env, self.value)
1740 pub fn without_const(mut self) -> Self {
1741 self.param_env = self.param_env.without_const();
1746 #[derive(Copy, Clone, Debug, HashStable, Encodable, Decodable)]
1747 pub struct Destructor {
1748 /// The `DefId` of the destructor method
1750 /// The constness of the destructor method
1751 pub constness: hir::Constness,
1755 #[derive(HashStable, TyEncodable, TyDecodable)]
1756 pub struct VariantFlags: u32 {
1757 const NO_VARIANT_FLAGS = 0;
1758 /// Indicates whether the field list of this variant is `#[non_exhaustive]`.
1759 const IS_FIELD_LIST_NON_EXHAUSTIVE = 1 << 0;
1760 /// Indicates whether this variant was obtained as part of recovering from
1761 /// a syntactic error. May be incomplete or bogus.
1762 const IS_RECOVERED = 1 << 1;
1766 /// Definition of a variant -- a struct's fields or an enum variant.
1767 #[derive(Debug, HashStable, TyEncodable, TyDecodable)]
1768 pub struct VariantDef {
1769 /// `DefId` that identifies the variant itself.
1770 /// If this variant belongs to a struct or union, then this is a copy of its `DefId`.
1772 /// `DefId` that identifies the variant's constructor.
1773 /// If this variant is a struct variant, then this is `None`.
1774 pub ctor: Option<(CtorKind, DefId)>,
1775 /// Variant or struct name.
1777 /// Discriminant of this variant.
1778 pub discr: VariantDiscr,
1779 /// Fields of this variant.
1780 pub fields: Vec<FieldDef>,
1781 /// Flags of the variant (e.g. is field list non-exhaustive)?
1782 flags: VariantFlags,
1786 /// Creates a new `VariantDef`.
1788 /// `variant_did` is the `DefId` that identifies the enum variant (if this `VariantDef`
1789 /// represents an enum variant).
1791 /// `ctor_did` is the `DefId` that identifies the constructor of unit or
1792 /// tuple-variants/structs. If this is a `struct`-variant then this should be `None`.
1794 /// `parent_did` is the `DefId` of the `AdtDef` representing the enum or struct that
1795 /// owns this variant. It is used for checking if a struct has `#[non_exhaustive]` w/out having
1796 /// to go through the redirect of checking the ctor's attributes - but compiling a small crate
1797 /// requires loading the `AdtDef`s for all the structs in the universe (e.g., coherence for any
1798 /// built-in trait), and we do not want to load attributes twice.
1800 /// If someone speeds up attribute loading to not be a performance concern, they can
1801 /// remove this hack and use the constructor `DefId` everywhere.
1804 variant_did: Option<DefId>,
1805 ctor: Option<(CtorKind, DefId)>,
1806 discr: VariantDiscr,
1807 fields: Vec<FieldDef>,
1811 is_field_list_non_exhaustive: bool,
1814 "VariantDef::new(name = {:?}, variant_did = {:?}, ctor = {:?}, discr = {:?},
1815 fields = {:?}, adt_kind = {:?}, parent_did = {:?})",
1816 name, variant_did, ctor, discr, fields, adt_kind, parent_did,
1819 let mut flags = VariantFlags::NO_VARIANT_FLAGS;
1820 if is_field_list_non_exhaustive {
1821 flags |= VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE;
1825 flags |= VariantFlags::IS_RECOVERED;
1828 VariantDef { def_id: variant_did.unwrap_or(parent_did), ctor, name, discr, fields, flags }
1831 /// Is this field list non-exhaustive?
1833 pub fn is_field_list_non_exhaustive(&self) -> bool {
1834 self.flags.intersects(VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE)
1837 /// Was this variant obtained as part of recovering from a syntactic error?
1839 pub fn is_recovered(&self) -> bool {
1840 self.flags.intersects(VariantFlags::IS_RECOVERED)
1843 /// Computes the `Ident` of this variant by looking up the `Span`
1844 pub fn ident(&self, tcx: TyCtxt<'_>) -> Ident {
1845 Ident::new(self.name, tcx.def_ident_span(self.def_id).unwrap())
1849 pub fn ctor_kind(&self) -> Option<CtorKind> {
1850 self.ctor.map(|(kind, _)| kind)
1854 pub fn ctor_def_id(&self) -> Option<DefId> {
1855 self.ctor.map(|(_, def_id)| def_id)
1859 impl PartialEq for VariantDef {
1861 fn eq(&self, other: &Self) -> bool {
1862 // There should be only one `VariantDef` for each `def_id`, therefore
1863 // it is fine to implement `PartialEq` only based on `def_id`.
1865 // Below, we exhaustively destructure `self` and `other` so that if the
1866 // definition of `VariantDef` changes, a compile-error will be produced,
1867 // reminding us to revisit this assumption.
1869 let Self { def_id: lhs_def_id, ctor: _, name: _, discr: _, fields: _, flags: _ } = &self;
1870 let Self { def_id: rhs_def_id, ctor: _, name: _, discr: _, fields: _, flags: _ } = other;
1871 lhs_def_id == rhs_def_id
1875 impl Eq for VariantDef {}
1877 impl Hash for VariantDef {
1879 fn hash<H: Hasher>(&self, s: &mut H) {
1880 // There should be only one `VariantDef` for each `def_id`, therefore
1881 // it is fine to implement `Hash` only based on `def_id`.
1883 // Below, we exhaustively destructure `self` so that if the definition
1884 // of `VariantDef` changes, a compile-error will be produced, reminding
1885 // us to revisit this assumption.
1887 let Self { def_id, ctor: _, name: _, discr: _, fields: _, flags: _ } = &self;
1892 #[derive(Copy, Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
1893 pub enum VariantDiscr {
1894 /// Explicit value for this variant, i.e., `X = 123`.
1895 /// The `DefId` corresponds to the embedded constant.
1898 /// The previous variant's discriminant plus one.
1899 /// For efficiency reasons, the distance from the
1900 /// last `Explicit` discriminant is being stored,
1901 /// or `0` for the first variant, if it has none.
1905 #[derive(Debug, HashStable, TyEncodable, TyDecodable)]
1906 pub struct FieldDef {
1909 pub vis: Visibility<DefId>,
1912 impl PartialEq for FieldDef {
1914 fn eq(&self, other: &Self) -> bool {
1915 // There should be only one `FieldDef` for each `did`, therefore it is
1916 // fine to implement `PartialEq` only based on `did`.
1918 // Below, we exhaustively destructure `self` so that if the definition
1919 // of `FieldDef` changes, a compile-error will be produced, reminding
1920 // us to revisit this assumption.
1922 let Self { did: lhs_did, name: _, vis: _ } = &self;
1924 let Self { did: rhs_did, name: _, vis: _ } = other;
1930 impl Eq for FieldDef {}
1932 impl Hash for FieldDef {
1934 fn hash<H: Hasher>(&self, s: &mut H) {
1935 // There should be only one `FieldDef` for each `did`, therefore it is
1936 // fine to implement `Hash` only based on `did`.
1938 // Below, we exhaustively destructure `self` so that if the definition
1939 // of `FieldDef` changes, a compile-error will be produced, reminding
1940 // us to revisit this assumption.
1942 let Self { did, name: _, vis: _ } = &self;
1948 impl<'tcx> FieldDef {
1949 /// Returns the type of this field. The resulting type is not normalized. The `subst` is
1950 /// typically obtained via the second field of [`TyKind::Adt`].
1951 pub fn ty(&self, tcx: TyCtxt<'tcx>, subst: SubstsRef<'tcx>) -> Ty<'tcx> {
1952 tcx.bound_type_of(self.did).subst(tcx, subst)
1955 /// Computes the `Ident` of this variant by looking up the `Span`
1956 pub fn ident(&self, tcx: TyCtxt<'_>) -> Ident {
1957 Ident::new(self.name, tcx.def_ident_span(self.did).unwrap())
1961 pub type Attributes<'tcx> = impl Iterator<Item = &'tcx ast::Attribute>;
1962 #[derive(Debug, PartialEq, Eq)]
1963 pub enum ImplOverlapKind {
1964 /// These impls are always allowed to overlap.
1966 /// Whether or not the impl is permitted due to the trait being a `#[marker]` trait
1969 /// These impls are allowed to overlap, but that raises
1970 /// an issue #33140 future-compatibility warning.
1972 /// Some background: in Rust 1.0, the trait-object types `Send + Sync` (today's
1973 /// `dyn Send + Sync`) and `Sync + Send` (now `dyn Sync + Send`) were different.
1975 /// The widely-used version 0.1.0 of the crate `traitobject` had accidentally relied
1976 /// that difference, making what reduces to the following set of impls:
1978 /// ```compile_fail,(E0119)
1980 /// impl Trait for dyn Send + Sync {}
1981 /// impl Trait for dyn Sync + Send {}
1984 /// Obviously, once we made these types be identical, that code causes a coherence
1985 /// error and a fairly big headache for us. However, luckily for us, the trait
1986 /// `Trait` used in this case is basically a marker trait, and therefore having
1987 /// overlapping impls for it is sound.
1989 /// To handle this, we basically regard the trait as a marker trait, with an additional
1990 /// future-compatibility warning. To avoid accidentally "stabilizing" this feature,
1991 /// it has the following restrictions:
1993 /// 1. The trait must indeed be a marker-like trait (i.e., no items), and must be
1995 /// 2. The trait-ref of both impls must be equal.
1996 /// 3. The trait-ref of both impls must be a trait object type consisting only of
1998 /// 4. Neither of the impls can have any where-clauses.
2000 /// Once `traitobject` 0.1.0 is no longer an active concern, this hack can be removed.
2004 impl<'tcx> TyCtxt<'tcx> {
2005 pub fn typeck_body(self, body: hir::BodyId) -> &'tcx TypeckResults<'tcx> {
2006 self.typeck(self.hir().body_owner_def_id(body))
2009 pub fn provided_trait_methods(self, id: DefId) -> impl 'tcx + Iterator<Item = &'tcx AssocItem> {
2010 self.associated_items(id)
2011 .in_definition_order()
2012 .filter(move |item| item.kind == AssocKind::Fn && item.defaultness(self).has_value())
2015 pub fn repr_options_of_def(self, did: DefId) -> ReprOptions {
2016 let mut flags = ReprFlags::empty();
2017 let mut size = None;
2018 let mut max_align: Option<Align> = None;
2019 let mut min_pack: Option<Align> = None;
2021 // Generate a deterministically-derived seed from the item's path hash
2022 // to allow for cross-crate compilation to actually work
2023 let mut field_shuffle_seed = self.def_path_hash(did).0.to_smaller_hash();
2025 // If the user defined a custom seed for layout randomization, xor the item's
2026 // path hash with the user defined seed, this will allowing determinism while
2027 // still allowing users to further randomize layout generation for e.g. fuzzing
2028 if let Some(user_seed) = self.sess.opts.unstable_opts.layout_seed {
2029 field_shuffle_seed ^= user_seed;
2032 for attr in self.get_attrs(did, sym::repr) {
2033 for r in attr::parse_repr_attr(&self.sess, attr) {
2034 flags.insert(match r {
2035 attr::ReprC => ReprFlags::IS_C,
2036 attr::ReprPacked(pack) => {
2037 let pack = Align::from_bytes(pack as u64).unwrap();
2038 min_pack = Some(if let Some(min_pack) = min_pack {
2045 attr::ReprTransparent => ReprFlags::IS_TRANSPARENT,
2046 attr::ReprSimd => ReprFlags::IS_SIMD,
2047 attr::ReprInt(i) => {
2048 size = Some(match i {
2049 attr::IntType::SignedInt(x) => match x {
2050 ast::IntTy::Isize => IntegerType::Pointer(true),
2051 ast::IntTy::I8 => IntegerType::Fixed(Integer::I8, true),
2052 ast::IntTy::I16 => IntegerType::Fixed(Integer::I16, true),
2053 ast::IntTy::I32 => IntegerType::Fixed(Integer::I32, true),
2054 ast::IntTy::I64 => IntegerType::Fixed(Integer::I64, true),
2055 ast::IntTy::I128 => IntegerType::Fixed(Integer::I128, true),
2057 attr::IntType::UnsignedInt(x) => match x {
2058 ast::UintTy::Usize => IntegerType::Pointer(false),
2059 ast::UintTy::U8 => IntegerType::Fixed(Integer::I8, false),
2060 ast::UintTy::U16 => IntegerType::Fixed(Integer::I16, false),
2061 ast::UintTy::U32 => IntegerType::Fixed(Integer::I32, false),
2062 ast::UintTy::U64 => IntegerType::Fixed(Integer::I64, false),
2063 ast::UintTy::U128 => IntegerType::Fixed(Integer::I128, false),
2068 attr::ReprAlign(align) => {
2069 max_align = max_align.max(Some(Align::from_bytes(align as u64).unwrap()));
2076 // If `-Z randomize-layout` was enabled for the type definition then we can
2077 // consider performing layout randomization
2078 if self.sess.opts.unstable_opts.randomize_layout {
2079 flags.insert(ReprFlags::RANDOMIZE_LAYOUT);
2082 // This is here instead of layout because the choice must make it into metadata.
2083 if !self.consider_optimizing(|| format!("Reorder fields of {:?}", self.def_path_str(did))) {
2084 flags.insert(ReprFlags::IS_LINEAR);
2087 ReprOptions { int: size, align: max_align, pack: min_pack, flags, field_shuffle_seed }
2090 /// Look up the name of a definition across crates. This does not look at HIR.
2091 pub fn opt_item_name(self, def_id: DefId) -> Option<Symbol> {
2092 if let Some(cnum) = def_id.as_crate_root() {
2093 Some(self.crate_name(cnum))
2095 let def_key = self.def_key(def_id);
2096 match def_key.disambiguated_data.data {
2097 // The name of a constructor is that of its parent.
2098 rustc_hir::definitions::DefPathData::Ctor => self
2099 .opt_item_name(DefId { krate: def_id.krate, index: def_key.parent.unwrap() }),
2100 // The name of opaque types only exists in HIR.
2101 rustc_hir::definitions::DefPathData::ImplTrait
2102 if let Some(def_id) = def_id.as_local() =>
2103 self.hir().opt_name(self.hir().local_def_id_to_hir_id(def_id)),
2104 _ => def_key.get_opt_name(),
2109 /// Look up the name of a definition across crates. This does not look at HIR.
2111 /// This method will ICE if the corresponding item does not have a name. In these cases, use
2112 /// [`opt_item_name`] instead.
2114 /// [`opt_item_name`]: Self::opt_item_name
2115 pub fn item_name(self, id: DefId) -> Symbol {
2116 self.opt_item_name(id).unwrap_or_else(|| {
2117 bug!("item_name: no name for {:?}", self.def_path(id));
2121 /// Look up the name and span of a definition.
2123 /// See [`item_name`][Self::item_name] for more information.
2124 pub fn opt_item_ident(self, def_id: DefId) -> Option<Ident> {
2125 let def = self.opt_item_name(def_id)?;
2128 .and_then(|id| self.def_ident_span(id))
2129 .unwrap_or(rustc_span::DUMMY_SP);
2130 Some(Ident::new(def, span))
2133 pub fn opt_associated_item(self, def_id: DefId) -> Option<&'tcx AssocItem> {
2134 if let DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy = self.def_kind(def_id) {
2135 Some(self.associated_item(def_id))
2141 pub fn find_field_index(self, ident: Ident, variant: &VariantDef) -> Option<usize> {
2145 .position(|field| self.hygienic_eq(ident, field.ident(self), variant.def_id))
2148 /// Returns `true` if the impls are the same polarity and the trait either
2149 /// has no items or is annotated `#[marker]` and prevents item overrides.
2150 pub fn impls_are_allowed_to_overlap(
2154 ) -> Option<ImplOverlapKind> {
2155 // If either trait impl references an error, they're allowed to overlap,
2156 // as one of them essentially doesn't exist.
2157 if self.impl_trait_ref(def_id1).map_or(false, |tr| tr.references_error())
2158 || self.impl_trait_ref(def_id2).map_or(false, |tr| tr.references_error())
2160 return Some(ImplOverlapKind::Permitted { marker: false });
2163 match (self.impl_polarity(def_id1), self.impl_polarity(def_id2)) {
2164 (ImplPolarity::Reservation, _) | (_, ImplPolarity::Reservation) => {
2165 // `#[rustc_reservation_impl]` impls don't overlap with anything
2167 "impls_are_allowed_to_overlap({:?}, {:?}) = Some(Permitted) (reservations)",
2170 return Some(ImplOverlapKind::Permitted { marker: false });
2172 (ImplPolarity::Positive, ImplPolarity::Negative)
2173 | (ImplPolarity::Negative, ImplPolarity::Positive) => {
2174 // `impl AutoTrait for Type` + `impl !AutoTrait for Type`
2176 "impls_are_allowed_to_overlap({:?}, {:?}) - None (differing polarities)",
2181 (ImplPolarity::Positive, ImplPolarity::Positive)
2182 | (ImplPolarity::Negative, ImplPolarity::Negative) => {}
2185 let is_marker_overlap = {
2186 let is_marker_impl = |def_id: DefId| -> bool {
2187 let trait_ref = self.impl_trait_ref(def_id);
2188 trait_ref.map_or(false, |tr| self.trait_def(tr.def_id).is_marker)
2190 is_marker_impl(def_id1) && is_marker_impl(def_id2)
2193 if is_marker_overlap {
2195 "impls_are_allowed_to_overlap({:?}, {:?}) = Some(Permitted) (marker overlap)",
2198 Some(ImplOverlapKind::Permitted { marker: true })
2200 if let Some(self_ty1) = self.issue33140_self_ty(def_id1) {
2201 if let Some(self_ty2) = self.issue33140_self_ty(def_id2) {
2202 if self_ty1 == self_ty2 {
2204 "impls_are_allowed_to_overlap({:?}, {:?}) - issue #33140 HACK",
2207 return Some(ImplOverlapKind::Issue33140);
2210 "impls_are_allowed_to_overlap({:?}, {:?}) - found {:?} != {:?}",
2211 def_id1, def_id2, self_ty1, self_ty2
2217 debug!("impls_are_allowed_to_overlap({:?}, {:?}) = None", def_id1, def_id2);
2222 /// Returns `ty::VariantDef` if `res` refers to a struct,
2223 /// or variant or their constructors, panics otherwise.
2224 pub fn expect_variant_res(self, res: Res) -> &'tcx VariantDef {
2226 Res::Def(DefKind::Variant, did) => {
2227 let enum_did = self.parent(did);
2228 self.adt_def(enum_did).variant_with_id(did)
2230 Res::Def(DefKind::Struct | DefKind::Union, did) => self.adt_def(did).non_enum_variant(),
2231 Res::Def(DefKind::Ctor(CtorOf::Variant, ..), variant_ctor_did) => {
2232 let variant_did = self.parent(variant_ctor_did);
2233 let enum_did = self.parent(variant_did);
2234 self.adt_def(enum_did).variant_with_ctor_id(variant_ctor_did)
2236 Res::Def(DefKind::Ctor(CtorOf::Struct, ..), ctor_did) => {
2237 let struct_did = self.parent(ctor_did);
2238 self.adt_def(struct_did).non_enum_variant()
2240 _ => bug!("expect_variant_res used with unexpected res {:?}", res),
2244 /// Returns the possibly-auto-generated MIR of a `(DefId, Subst)` pair.
2245 #[instrument(skip(self), level = "debug")]
2246 pub fn instance_mir(self, instance: ty::InstanceDef<'tcx>) -> &'tcx Body<'tcx> {
2248 ty::InstanceDef::Item(def) => {
2249 debug!("calling def_kind on def: {:?}", def);
2250 let def_kind = self.def_kind(def.did);
2251 debug!("returned from def_kind: {:?}", def_kind);
2254 | DefKind::Static(..)
2255 | DefKind::AssocConst
2257 | DefKind::AnonConst
2258 | DefKind::InlineConst => self.mir_for_ctfe_opt_const_arg(def),
2259 // If the caller wants `mir_for_ctfe` of a function they should not be using
2260 // `instance_mir`, so we'll assume const fn also wants the optimized version.
2262 assert_eq!(def.const_param_did, None);
2263 self.optimized_mir(def.did)
2267 ty::InstanceDef::VTableShim(..)
2268 | ty::InstanceDef::ReifyShim(..)
2269 | ty::InstanceDef::Intrinsic(..)
2270 | ty::InstanceDef::FnPtrShim(..)
2271 | ty::InstanceDef::Virtual(..)
2272 | ty::InstanceDef::ClosureOnceShim { .. }
2273 | ty::InstanceDef::DropGlue(..)
2274 | ty::InstanceDef::CloneShim(..) => self.mir_shims(instance),
2278 // FIXME(@lcnr): Remove this function.
2279 pub fn get_attrs_unchecked(self, did: DefId) -> &'tcx [ast::Attribute] {
2280 if let Some(did) = did.as_local() {
2281 self.hir().attrs(self.hir().local_def_id_to_hir_id(did))
2283 self.item_attrs(did)
2287 /// Gets all attributes with the given name.
2288 pub fn get_attrs(self, did: DefId, attr: Symbol) -> ty::Attributes<'tcx> {
2289 let filter_fn = move |a: &&ast::Attribute| a.has_name(attr);
2290 if let Some(did) = did.as_local() {
2291 self.hir().attrs(self.hir().local_def_id_to_hir_id(did)).iter().filter(filter_fn)
2292 } else if cfg!(debug_assertions) && rustc_feature::is_builtin_only_local(attr) {
2293 bug!("tried to access the `only_local` attribute `{}` from an extern crate", attr);
2295 self.item_attrs(did).iter().filter(filter_fn)
2299 pub fn get_attr(self, did: DefId, attr: Symbol) -> Option<&'tcx ast::Attribute> {
2300 if cfg!(debug_assertions) && !rustc_feature::is_valid_for_get_attr(attr) {
2301 bug!("get_attr: unexpected called with DefId `{:?}`, attr `{:?}`", did, attr);
2303 self.get_attrs(did, attr).next()
2307 /// Determines whether an item is annotated with an attribute.
2308 pub fn has_attr(self, did: DefId, attr: Symbol) -> bool {
2309 if cfg!(debug_assertions) && !did.is_local() && rustc_feature::is_builtin_only_local(attr) {
2310 bug!("tried to access the `only_local` attribute `{}` from an extern crate", attr);
2312 self.get_attrs(did, attr).next().is_some()
2316 /// Returns `true` if this is an `auto trait`.
2317 pub fn trait_is_auto(self, trait_def_id: DefId) -> bool {
2318 self.trait_def(trait_def_id).has_auto_impl
2321 pub fn trait_is_coinductive(self, trait_def_id: DefId) -> bool {
2322 self.trait_is_auto(trait_def_id) || self.lang_items().sized_trait() == Some(trait_def_id)
2325 /// Returns layout of a generator. Layout might be unavailable if the
2326 /// generator is tainted by errors.
2327 pub fn generator_layout(self, def_id: DefId) -> Option<&'tcx GeneratorLayout<'tcx>> {
2328 self.optimized_mir(def_id).generator_layout()
2331 /// Given the `DefId` of an impl, returns the `DefId` of the trait it implements.
2332 /// If it implements no trait, returns `None`.
2333 pub fn trait_id_of_impl(self, def_id: DefId) -> Option<DefId> {
2334 self.impl_trait_ref(def_id).map(|tr| tr.def_id)
2337 /// If the given `DefId` describes an item belonging to a trait,
2338 /// returns the `DefId` of the trait that the trait item belongs to;
2339 /// otherwise, returns `None`.
2340 pub fn trait_of_item(self, def_id: DefId) -> Option<DefId> {
2341 if let DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy = self.def_kind(def_id) {
2342 let parent = self.parent(def_id);
2343 if let DefKind::Trait | DefKind::TraitAlias = self.def_kind(parent) {
2344 return Some(parent);
2350 /// If the given `DefId` describes a method belonging to an impl, returns the
2351 /// `DefId` of the impl that the method belongs to; otherwise, returns `None`.
2352 pub fn impl_of_method(self, def_id: DefId) -> Option<DefId> {
2353 if let DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy = self.def_kind(def_id) {
2354 let parent = self.parent(def_id);
2355 if let DefKind::Impl = self.def_kind(parent) {
2356 return Some(parent);
2362 /// If the given `DefId` belongs to a trait that was automatically derived, returns `true`.
2363 pub fn is_builtin_derive(self, def_id: DefId) -> bool {
2364 self.has_attr(def_id, sym::automatically_derived)
2367 /// Looks up the span of `impl_did` if the impl is local; otherwise returns `Err`
2368 /// with the name of the crate containing the impl.
2369 pub fn span_of_impl(self, impl_def_id: DefId) -> Result<Span, Symbol> {
2370 if let Some(impl_def_id) = impl_def_id.as_local() {
2371 Ok(self.def_span(impl_def_id))
2373 Err(self.crate_name(impl_def_id.krate))
2377 /// Hygienically compares a use-site name (`use_name`) for a field or an associated item with
2378 /// its supposed definition name (`def_name`). The method also needs `DefId` of the supposed
2379 /// definition's parent/scope to perform comparison.
2380 pub fn hygienic_eq(self, use_name: Ident, def_name: Ident, def_parent_def_id: DefId) -> bool {
2381 // We could use `Ident::eq` here, but we deliberately don't. The name
2382 // comparison fails frequently, and we want to avoid the expensive
2383 // `normalize_to_macros_2_0()` calls required for the span comparison whenever possible.
2384 use_name.name == def_name.name
2388 .hygienic_eq(def_name.span.ctxt(), self.expn_that_defined(def_parent_def_id))
2391 pub fn adjust_ident(self, mut ident: Ident, scope: DefId) -> Ident {
2392 ident.span.normalize_to_macros_2_0_and_adjust(self.expn_that_defined(scope));
2396 pub fn adjust_ident_and_get_scope(
2401 ) -> (Ident, DefId) {
2404 .normalize_to_macros_2_0_and_adjust(self.expn_that_defined(scope))
2405 .and_then(|actual_expansion| actual_expansion.expn_data().parent_module)
2406 .unwrap_or_else(|| self.parent_module(block).to_def_id());
2410 /// Returns `true` if the debuginfo for `span` should be collapsed to the outermost expansion
2411 /// site. Only applies when `Span` is the result of macro expansion.
2413 /// - If the `collapse_debuginfo` feature is enabled then debuginfo is not collapsed by default
2414 /// and only when a macro definition is annotated with `#[collapse_debuginfo]`.
2415 /// - If `collapse_debuginfo` is not enabled, then debuginfo is collapsed by default.
2417 /// When `-Zdebug-macros` is provided then debuginfo will never be collapsed.
2418 pub fn should_collapse_debuginfo(self, span: Span) -> bool {
2419 !self.sess.opts.unstable_opts.debug_macros
2420 && if self.features().collapse_debuginfo {
2421 span.in_macro_expansion_with_collapse_debuginfo()
2423 // Inlined spans should not be collapsed as that leads to all of the
2424 // inlined code being attributed to the inline callsite.
2425 span.from_expansion() && !span.is_inlined()
2429 pub fn is_object_safe(self, key: DefId) -> bool {
2430 self.object_safety_violations(key).is_empty()
2434 pub fn is_const_fn_raw(self, def_id: DefId) -> bool {
2435 matches!(self.def_kind(def_id), DefKind::Fn | DefKind::AssocFn | DefKind::Ctor(..))
2436 && self.constness(def_id) == hir::Constness::Const
2440 pub fn is_const_default_method(self, def_id: DefId) -> bool {
2441 matches!(self.trait_of_item(def_id), Some(trait_id) if self.has_attr(trait_id, sym::const_trait))
2444 pub fn impl_trait_in_trait_parent(self, mut def_id: DefId) -> DefId {
2445 while let def_kind = self.def_kind(def_id) && def_kind != DefKind::AssocFn {
2446 debug_assert_eq!(def_kind, DefKind::ImplTraitPlaceholder);
2447 def_id = self.parent(def_id);
2453 /// Yields the parent function's `LocalDefId` if `def_id` is an `impl Trait` definition.
2454 pub fn is_impl_trait_defn(tcx: TyCtxt<'_>, def_id: DefId) -> Option<LocalDefId> {
2455 let def_id = def_id.as_local()?;
2456 if let Node::Item(item) = tcx.hir().get_by_def_id(def_id) {
2457 if let hir::ItemKind::OpaqueTy(ref opaque_ty) = item.kind {
2458 return match opaque_ty.origin {
2459 hir::OpaqueTyOrigin::FnReturn(parent) | hir::OpaqueTyOrigin::AsyncFn(parent) => {
2462 hir::OpaqueTyOrigin::TyAlias => None,
2469 pub fn int_ty(ity: ast::IntTy) -> IntTy {
2471 ast::IntTy::Isize => IntTy::Isize,
2472 ast::IntTy::I8 => IntTy::I8,
2473 ast::IntTy::I16 => IntTy::I16,
2474 ast::IntTy::I32 => IntTy::I32,
2475 ast::IntTy::I64 => IntTy::I64,
2476 ast::IntTy::I128 => IntTy::I128,
2480 pub fn uint_ty(uty: ast::UintTy) -> UintTy {
2482 ast::UintTy::Usize => UintTy::Usize,
2483 ast::UintTy::U8 => UintTy::U8,
2484 ast::UintTy::U16 => UintTy::U16,
2485 ast::UintTy::U32 => UintTy::U32,
2486 ast::UintTy::U64 => UintTy::U64,
2487 ast::UintTy::U128 => UintTy::U128,
2491 pub fn float_ty(fty: ast::FloatTy) -> FloatTy {
2493 ast::FloatTy::F32 => FloatTy::F32,
2494 ast::FloatTy::F64 => FloatTy::F64,
2498 pub fn ast_int_ty(ity: IntTy) -> ast::IntTy {
2500 IntTy::Isize => ast::IntTy::Isize,
2501 IntTy::I8 => ast::IntTy::I8,
2502 IntTy::I16 => ast::IntTy::I16,
2503 IntTy::I32 => ast::IntTy::I32,
2504 IntTy::I64 => ast::IntTy::I64,
2505 IntTy::I128 => ast::IntTy::I128,
2509 pub fn ast_uint_ty(uty: UintTy) -> ast::UintTy {
2511 UintTy::Usize => ast::UintTy::Usize,
2512 UintTy::U8 => ast::UintTy::U8,
2513 UintTy::U16 => ast::UintTy::U16,
2514 UintTy::U32 => ast::UintTy::U32,
2515 UintTy::U64 => ast::UintTy::U64,
2516 UintTy::U128 => ast::UintTy::U128,
2520 pub fn provide(providers: &mut ty::query::Providers) {
2521 closure::provide(providers);
2522 context::provide(providers);
2523 erase_regions::provide(providers);
2524 inhabitedness::provide(providers);
2525 util::provide(providers);
2526 print::provide(providers);
2527 super::util::bug::provide(providers);
2528 super::middle::provide(providers);
2529 *providers = ty::query::Providers {
2530 trait_impls_of: trait_def::trait_impls_of_provider,
2531 incoherent_impls: trait_def::incoherent_impls_provider,
2532 const_param_default: consts::const_param_default,
2533 vtable_allocation: vtable::vtable_allocation_provider,
2538 /// A map for the local crate mapping each type to a vector of its
2539 /// inherent impls. This is not meant to be used outside of coherence;
2540 /// rather, you should request the vector for a specific type via
2541 /// `tcx.inherent_impls(def_id)` so as to minimize your dependencies
2542 /// (constructing this map requires touching the entire crate).
2543 #[derive(Clone, Debug, Default, HashStable)]
2544 pub struct CrateInherentImpls {
2545 pub inherent_impls: LocalDefIdMap<Vec<DefId>>,
2546 pub incoherent_impls: FxHashMap<SimplifiedType, Vec<LocalDefId>>,
2549 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, HashStable)]
2550 pub struct SymbolName<'tcx> {
2551 /// `&str` gives a consistent ordering, which ensures reproducible builds.
2552 pub name: &'tcx str,
2555 impl<'tcx> SymbolName<'tcx> {
2556 pub fn new(tcx: TyCtxt<'tcx>, name: &str) -> SymbolName<'tcx> {
2558 name: unsafe { str::from_utf8_unchecked(tcx.arena.alloc_slice(name.as_bytes())) },
2563 impl<'tcx> fmt::Display for SymbolName<'tcx> {
2564 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2565 fmt::Display::fmt(&self.name, fmt)
2569 impl<'tcx> fmt::Debug for SymbolName<'tcx> {
2570 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2571 fmt::Display::fmt(&self.name, fmt)
2575 #[derive(Debug, Default, Copy, Clone)]
2576 pub struct FoundRelationships {
2577 /// This is true if we identified that this Ty (`?T`) is found in a `?T: Foo`
2578 /// obligation, where:
2580 /// * `Foo` is not `Sized`
2581 /// * `(): Foo` may be satisfied
2582 pub self_in_trait: bool,
2583 /// This is true if we identified that this Ty (`?T`) is found in a `<_ as
2584 /// _>::AssocType = ?T`
2588 /// The constituent parts of a type level constant of kind ADT or array.
2589 #[derive(Copy, Clone, Debug, HashStable)]
2590 pub struct DestructuredConst<'tcx> {
2591 pub variant: Option<VariantIdx>,
2592 pub fields: &'tcx [ty::Const<'tcx>],
2595 // Some types are used a lot. Make sure they don't unintentionally get bigger.
2596 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
2599 use rustc_data_structures::static_assert_size;
2600 // tidy-alphabetical-start
2601 static_assert_size!(PredicateKind<'_>, 32);
2602 static_assert_size!(WithCachedTypeInfo<TyKind<'_>>, 56);
2603 // tidy-alphabetical-end