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::AliasKind::*;
68 pub use rustc_type_ir::DynKind::*;
69 pub use rustc_type_ir::InferTy::*;
70 pub use rustc_type_ir::RegionKind::*;
71 pub use rustc_type_ir::TyKind::*;
72 pub use rustc_type_ir::*;
74 pub use self::binding::BindingMode;
75 pub use self::binding::BindingMode::*;
76 pub use self::closure::{
77 is_ancestor_or_same_capture, place_to_string_for_capture, BorrowKind, CaptureInfo,
78 CapturedPlace, ClosureKind, MinCaptureInformationMap, MinCaptureList,
79 RootVariableMinCaptureList, UpvarCapture, UpvarCaptureMap, UpvarId, UpvarListMap, UpvarPath,
82 pub use self::consts::{
83 Const, ConstData, ConstInt, ConstKind, Expr, InferConst, ScalarInt, UnevaluatedConst, ValTree,
85 pub use self::context::{
86 tls, CtxtInterners, DeducedParamAttrs, FreeRegionInfo, GlobalCtxt, Lift, OnDiskCache, TyCtxt,
89 pub use self::instance::{Instance, InstanceDef, ShortInstance};
90 pub use self::list::List;
91 pub use self::parameterized::ParameterizedOverTcx;
92 pub use self::rvalue_scopes::RvalueScopes;
93 pub use self::sty::BoundRegionKind::*;
95 AliasTy, Article, Binder, BoundRegion, BoundRegionKind, BoundTy, BoundTyKind, BoundVar,
96 BoundVariableKind, CanonicalPolyFnSig, ClosureSubsts, ClosureSubstsParts, ConstVid,
97 EarlyBoundRegion, ExistentialPredicate, ExistentialProjection, ExistentialTraitRef, FnSig,
98 FreeRegion, GenSig, GeneratorSubsts, GeneratorSubstsParts, InlineConstSubsts,
99 InlineConstSubstsParts, ParamConst, ParamTy, PolyExistentialPredicate,
100 PolyExistentialProjection, PolyExistentialTraitRef, PolyFnSig, PolyGenSig, PolyTraitRef,
101 Region, RegionKind, RegionVid, TraitRef, TyKind, TypeAndMut, UpvarSubsts, VarianceDiagInfo,
103 pub use self::trait_def::TraitDef;
104 pub use self::typeck_results::{
105 CanonicalUserType, CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations,
106 GeneratorDiagnosticData, GeneratorInteriorTypeCause, TypeckResults, UserType,
107 UserTypeAnnotationIndex,
111 pub mod abstract_const;
120 pub mod inhabitedness;
122 pub mod normalize_erasing_regions;
147 mod structural_impls;
153 pub type RegisteredTools = FxHashSet<Ident>;
155 pub struct ResolverOutputs {
156 pub global_ctxt: ResolverGlobalCtxt,
157 pub ast_lowering: ResolverAstLowering,
158 pub untracked: Untracked,
162 pub struct ResolverGlobalCtxt {
163 pub visibilities: FxHashMap<LocalDefId, Visibility>,
164 /// This field is used to decide whether we should make `PRIVATE_IN_PUBLIC` a hard error.
165 pub has_pub_restricted: bool,
166 /// Item with a given `LocalDefId` was defined during macro expansion with ID `ExpnId`.
167 pub expn_that_defined: FxHashMap<LocalDefId, ExpnId>,
168 pub effective_visibilities: EffectiveVisibilities,
169 pub extern_crate_map: FxHashMap<LocalDefId, CrateNum>,
170 pub maybe_unused_trait_imports: FxIndexSet<LocalDefId>,
171 pub maybe_unused_extern_crates: Vec<(LocalDefId, Span)>,
172 pub reexport_map: FxHashMap<LocalDefId, Vec<ModChild>>,
173 pub glob_map: FxHashMap<LocalDefId, FxHashSet<Symbol>>,
174 /// Extern prelude entries. The value is `true` if the entry was introduced
175 /// via `extern crate` item and not `--extern` option or compiler built-in.
176 pub extern_prelude: FxHashMap<Symbol, bool>,
177 pub main_def: Option<MainDefinition>,
178 pub trait_impls: FxIndexMap<DefId, Vec<LocalDefId>>,
179 /// A list of proc macro LocalDefIds, written out in the order in which
180 /// they are declared in the static array generated by proc_macro_harness.
181 pub proc_macros: Vec<LocalDefId>,
182 /// Mapping from ident span to path span for paths that don't exist as written, but that
183 /// exist under `std`. For example, wrote `str::from_utf8` instead of `std::str::from_utf8`.
184 pub confused_type_with_std_module: FxHashMap<Span, Span>,
185 pub registered_tools: RegisteredTools,
188 /// Resolutions that should only be used for lowering.
189 /// This struct is meant to be consumed by lowering.
191 pub struct ResolverAstLowering {
192 pub legacy_const_generic_args: FxHashMap<DefId, Option<Vec<usize>>>,
194 /// Resolutions for nodes that have a single resolution.
195 pub partial_res_map: NodeMap<hir::def::PartialRes>,
196 /// Resolutions for import nodes, which have multiple resolutions in different namespaces.
197 pub import_res_map: NodeMap<hir::def::PerNS<Option<Res<ast::NodeId>>>>,
198 /// Resolutions for labels (node IDs of their corresponding blocks or loops).
199 pub label_res_map: NodeMap<ast::NodeId>,
200 /// Resolutions for lifetimes.
201 pub lifetimes_res_map: NodeMap<LifetimeRes>,
202 /// Lifetime parameters that lowering will have to introduce.
203 pub extra_lifetime_params_map: NodeMap<Vec<(Ident, ast::NodeId, LifetimeRes)>>,
205 pub next_node_id: ast::NodeId,
207 pub node_id_to_def_id: FxHashMap<ast::NodeId, LocalDefId>,
208 pub def_id_to_node_id: IndexVec<LocalDefId, ast::NodeId>,
210 pub trait_map: NodeMap<Vec<hir::TraitCandidate>>,
211 /// A small map keeping true kinds of built-in macros that appear to be fn-like on
212 /// the surface (`macro` items in libcore), but are actually attributes or derives.
213 pub builtin_macro_kinds: FxHashMap<LocalDefId, MacroKind>,
214 /// List functions and methods for which lifetime elision was successful.
215 pub lifetime_elision_allowed: FxHashSet<ast::NodeId>,
218 #[derive(Clone, Copy, Debug)]
219 pub struct MainDefinition {
220 pub res: Res<ast::NodeId>,
225 impl MainDefinition {
226 pub fn opt_fn_def_id(self) -> Option<DefId> {
227 if let Res::Def(DefKind::Fn, def_id) = self.res { Some(def_id) } else { None }
231 /// The "header" of an impl is everything outside the body: a Self type, a trait
232 /// ref (in the case of a trait impl), and a set of predicates (from the
233 /// bounds / where-clauses).
234 #[derive(Clone, Debug, TypeFoldable, TypeVisitable)]
235 pub struct ImplHeader<'tcx> {
236 pub impl_def_id: DefId,
237 pub self_ty: Ty<'tcx>,
238 pub trait_ref: Option<TraitRef<'tcx>>,
239 pub predicates: Vec<Predicate<'tcx>>,
242 #[derive(Copy, Clone, PartialEq, Eq, Debug, TypeFoldable, TypeVisitable)]
243 pub enum ImplSubject<'tcx> {
244 Trait(TraitRef<'tcx>),
248 #[derive(Copy, Clone, PartialEq, Eq, Hash, TyEncodable, TyDecodable, HashStable, Debug)]
249 #[derive(TypeFoldable, TypeVisitable)]
250 pub enum ImplPolarity {
251 /// `impl Trait for Type`
253 /// `impl !Trait for Type`
255 /// `#[rustc_reservation_impl] impl Trait for Type`
257 /// This is a "stability hack", not a real Rust feature.
258 /// See #64631 for details.
263 /// Flips polarity by turning `Positive` into `Negative` and `Negative` into `Positive`.
264 pub fn flip(&self) -> Option<ImplPolarity> {
266 ImplPolarity::Positive => Some(ImplPolarity::Negative),
267 ImplPolarity::Negative => Some(ImplPolarity::Positive),
268 ImplPolarity::Reservation => None,
273 impl fmt::Display for ImplPolarity {
274 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
276 Self::Positive => f.write_str("positive"),
277 Self::Negative => f.write_str("negative"),
278 Self::Reservation => f.write_str("reservation"),
283 #[derive(Clone, Debug, PartialEq, Eq, Copy, Hash, Encodable, Decodable, HashStable)]
284 pub enum Visibility<Id = LocalDefId> {
285 /// Visible everywhere (including in other crates).
287 /// Visible only in the given crate-local module.
291 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable, TyEncodable, TyDecodable)]
292 pub enum BoundConstness {
295 /// `T: ~const Trait`
297 /// Requires resolving to const only when we are in a const context.
301 impl BoundConstness {
302 /// Reduce `self` and `constness` to two possible combined states instead of four.
303 pub fn and(&mut self, constness: hir::Constness) -> hir::Constness {
304 match (constness, self) {
305 (hir::Constness::Const, BoundConstness::ConstIfConst) => hir::Constness::Const,
307 *this = BoundConstness::NotConst;
308 hir::Constness::NotConst
314 impl fmt::Display for BoundConstness {
315 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
317 Self::NotConst => f.write_str("normal"),
318 Self::ConstIfConst => f.write_str("`~const`"),
323 #[derive(Clone, Debug, PartialEq, Eq, Copy, Hash, TyEncodable, TyDecodable, HashStable)]
324 #[derive(TypeFoldable, TypeVisitable)]
325 pub struct ClosureSizeProfileData<'tcx> {
326 /// Tuple containing the types of closure captures before the feature `capture_disjoint_fields`
327 pub before_feature_tys: Ty<'tcx>,
328 /// Tuple containing the types of closure captures after the feature `capture_disjoint_fields`
329 pub after_feature_tys: Ty<'tcx>,
332 pub trait DefIdTree: Copy {
333 fn opt_parent(self, id: DefId) -> Option<DefId>;
337 fn parent(self, id: DefId) -> DefId {
338 match self.opt_parent(id) {
340 // not `unwrap_or_else` to avoid breaking caller tracking
341 None => bug!("{id:?} doesn't have a parent"),
347 fn opt_local_parent(self, id: LocalDefId) -> Option<LocalDefId> {
348 self.opt_parent(id.to_def_id()).map(DefId::expect_local)
353 fn local_parent(self, id: LocalDefId) -> LocalDefId {
354 self.parent(id.to_def_id()).expect_local()
357 fn is_descendant_of(self, mut descendant: DefId, ancestor: DefId) -> bool {
358 if descendant.krate != ancestor.krate {
362 while descendant != ancestor {
363 match self.opt_parent(descendant) {
364 Some(parent) => descendant = parent,
365 None => return false,
372 impl<'tcx> DefIdTree for TyCtxt<'tcx> {
374 fn opt_parent(self, id: DefId) -> Option<DefId> {
375 self.def_key(id).parent.map(|index| DefId { index, ..id })
379 impl<Id> Visibility<Id> {
380 pub fn is_public(self) -> bool {
381 matches!(self, Visibility::Public)
384 pub fn map_id<OutId>(self, f: impl FnOnce(Id) -> OutId) -> Visibility<OutId> {
386 Visibility::Public => Visibility::Public,
387 Visibility::Restricted(id) => Visibility::Restricted(f(id)),
392 impl<Id: Into<DefId>> Visibility<Id> {
393 pub fn to_def_id(self) -> Visibility<DefId> {
394 self.map_id(Into::into)
397 /// Returns `true` if an item with this visibility is accessible from the given module.
398 pub fn is_accessible_from(self, module: impl Into<DefId>, tree: impl DefIdTree) -> bool {
400 // Public items are visible everywhere.
401 Visibility::Public => true,
402 Visibility::Restricted(id) => tree.is_descendant_of(module.into(), id.into()),
406 /// Returns `true` if this visibility is at least as accessible as the given visibility
407 pub fn is_at_least(self, vis: Visibility<impl Into<DefId>>, tree: impl DefIdTree) -> bool {
409 Visibility::Public => self.is_public(),
410 Visibility::Restricted(id) => self.is_accessible_from(id, tree),
415 impl Visibility<DefId> {
416 pub fn expect_local(self) -> Visibility {
417 self.map_id(|id| id.expect_local())
420 /// Returns `true` if this item is visible anywhere in the local crate.
421 pub fn is_visible_locally(self) -> bool {
423 Visibility::Public => true,
424 Visibility::Restricted(def_id) => def_id.is_local(),
429 /// The crate variances map is computed during typeck and contains the
430 /// variance of every item in the local crate. You should not use it
431 /// directly, because to do so will make your pass dependent on the
432 /// HIR of every item in the local crate. Instead, use
433 /// `tcx.variances_of()` to get the variance for a *particular*
435 #[derive(HashStable, Debug)]
436 pub struct CrateVariancesMap<'tcx> {
437 /// For each item with generics, maps to a vector of the variance
438 /// of its generics. If an item has no generics, it will have no
440 pub variances: FxHashMap<DefId, &'tcx [ty::Variance]>,
443 // Contains information needed to resolve types and (in the future) look up
444 // the types of AST nodes.
445 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
446 pub struct CReaderCacheKey {
447 pub cnum: Option<CrateNum>,
451 /// Use this rather than `TyKind`, whenever possible.
452 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, HashStable)]
453 #[rustc_diagnostic_item = "Ty"]
454 #[rustc_pass_by_value]
455 pub struct Ty<'tcx>(Interned<'tcx, WithCachedTypeInfo<TyKind<'tcx>>>);
457 impl<'tcx> TyCtxt<'tcx> {
458 /// A "bool" type used in rustc_mir_transform unit tests when we
459 /// have not spun up a TyCtxt.
460 pub const BOOL_TY_FOR_UNIT_TESTING: Ty<'tcx> =
461 Ty(Interned::new_unchecked(&WithCachedTypeInfo {
463 stable_hash: Fingerprint::ZERO,
464 flags: TypeFlags::empty(),
465 outer_exclusive_binder: DebruijnIndex::from_usize(0),
469 impl ty::EarlyBoundRegion {
470 /// Does this early bound region have a name? Early bound regions normally
471 /// always have names except when using anonymous lifetimes (`'_`).
472 pub fn has_name(&self) -> bool {
473 self.name != kw::UnderscoreLifetime && self.name != kw::Empty
477 /// Use this rather than `PredicateKind`, whenever possible.
478 #[derive(Clone, Copy, PartialEq, Eq, Hash, HashStable)]
479 #[rustc_pass_by_value]
480 pub struct Predicate<'tcx>(
481 Interned<'tcx, WithCachedTypeInfo<ty::Binder<'tcx, PredicateKind<'tcx>>>>,
484 impl<'tcx> Predicate<'tcx> {
485 /// Gets the inner `Binder<'tcx, PredicateKind<'tcx>>`.
487 pub fn kind(self) -> Binder<'tcx, PredicateKind<'tcx>> {
492 pub fn flags(self) -> TypeFlags {
497 pub fn outer_exclusive_binder(self) -> DebruijnIndex {
498 self.0.outer_exclusive_binder
501 /// Flips the polarity of a Predicate.
503 /// Given `T: Trait` predicate it returns `T: !Trait` and given `T: !Trait` returns `T: Trait`.
504 pub fn flip_polarity(self, tcx: TyCtxt<'tcx>) -> Option<Predicate<'tcx>> {
507 .map_bound(|kind| match kind {
508 PredicateKind::Clause(Clause::Trait(TraitPredicate {
512 })) => Some(PredicateKind::Clause(Clause::Trait(TraitPredicate {
515 polarity: polarity.flip()?,
522 Some(tcx.mk_predicate(kind))
525 pub fn without_const(mut self, tcx: TyCtxt<'tcx>) -> Self {
526 if let PredicateKind::Clause(Clause::Trait(TraitPredicate { trait_ref, constness, polarity })) = self.kind().skip_binder()
527 && constness != BoundConstness::NotConst
529 self = tcx.mk_predicate(self.kind().rebind(PredicateKind::Clause(Clause::Trait(TraitPredicate {
531 constness: BoundConstness::NotConst,
538 #[instrument(level = "debug", skip(tcx), ret)]
539 pub fn is_coinductive(self, tcx: TyCtxt<'tcx>) -> bool {
540 match self.kind().skip_binder() {
541 ty::PredicateKind::Clause(ty::Clause::Trait(data)) => {
542 tcx.trait_is_coinductive(data.def_id())
544 ty::PredicateKind::WellFormed(_) => true,
549 /// Whether this projection can be soundly normalized.
551 /// Wf predicates must not be normalized, as normalization
552 /// can remove required bounds which would cause us to
553 /// unsoundly accept some programs. See #91068.
555 pub fn allow_normalization(self) -> bool {
556 match self.kind().skip_binder() {
557 PredicateKind::WellFormed(_) => false,
558 PredicateKind::Clause(Clause::Trait(_))
559 | PredicateKind::Clause(Clause::RegionOutlives(_))
560 | PredicateKind::Clause(Clause::TypeOutlives(_))
561 | PredicateKind::Clause(Clause::Projection(_))
562 | PredicateKind::ObjectSafe(_)
563 | PredicateKind::ClosureKind(_, _, _)
564 | PredicateKind::Subtype(_)
565 | PredicateKind::Coerce(_)
566 | PredicateKind::ConstEvaluatable(_)
567 | PredicateKind::ConstEquate(_, _)
568 | PredicateKind::Ambiguous
569 | PredicateKind::TypeWellFormedFromEnv(_) => true,
574 impl rustc_errors::IntoDiagnosticArg for Predicate<'_> {
575 fn into_diagnostic_arg(self) -> rustc_errors::DiagnosticArgValue<'static> {
576 rustc_errors::DiagnosticArgValue::Str(std::borrow::Cow::Owned(self.to_string()))
580 #[derive(Clone, Copy, PartialEq, Eq, Hash, TyEncodable, TyDecodable)]
581 #[derive(HashStable, TypeFoldable, TypeVisitable, Lift)]
582 /// A clause is something that can appear in where bounds or be inferred
583 /// by implied bounds.
584 pub enum Clause<'tcx> {
585 /// Corresponds to `where Foo: Bar<A, B, C>`. `Foo` here would be
586 /// the `Self` type of the trait reference and `A`, `B`, and `C`
587 /// would be the type parameters.
588 Trait(TraitPredicate<'tcx>),
591 RegionOutlives(RegionOutlivesPredicate<'tcx>),
594 TypeOutlives(TypeOutlivesPredicate<'tcx>),
596 /// `where <T as TraitRef>::Name == X`, approximately.
597 /// See the `ProjectionPredicate` struct for details.
598 Projection(ProjectionPredicate<'tcx>),
601 #[derive(Clone, Copy, PartialEq, Eq, Hash, TyEncodable, TyDecodable)]
602 #[derive(HashStable, TypeFoldable, TypeVisitable, Lift)]
603 pub enum PredicateKind<'tcx> {
605 Clause(Clause<'tcx>),
607 /// No syntax: `T` well-formed.
608 WellFormed(GenericArg<'tcx>),
610 /// Trait must be object-safe.
613 /// No direct syntax. May be thought of as `where T: FnFoo<...>`
614 /// for some substitutions `...` and `T` being a closure type.
615 /// Satisfied (or refuted) once we know the closure's kind.
616 ClosureKind(DefId, SubstsRef<'tcx>, ClosureKind),
620 /// This obligation is created most often when we have two
621 /// unresolved type variables and hence don't have enough
622 /// information to process the subtyping obligation yet.
623 Subtype(SubtypePredicate<'tcx>),
625 /// `T1` coerced to `T2`
627 /// Like a subtyping obligation, this is created most often
628 /// when we have two unresolved type variables and hence
629 /// don't have enough information to process the coercion
630 /// obligation yet. At the moment, we actually process coercions
631 /// very much like subtyping and don't handle the full coercion
633 Coerce(CoercePredicate<'tcx>),
635 /// Constant initializer must evaluate successfully.
636 ConstEvaluatable(ty::Const<'tcx>),
638 /// Constants must be equal. The first component is the const that is expected.
639 ConstEquate(Const<'tcx>, Const<'tcx>),
641 /// Represents a type found in the environment that we can use for implied bounds.
643 /// Only used for Chalk.
644 TypeWellFormedFromEnv(Ty<'tcx>),
646 /// A marker predicate that is always ambiguous.
647 /// Used for coherence to mark opaque types as possibly equal to each other but ambiguous.
651 /// The crate outlives map is computed during typeck and contains the
652 /// outlives of every item in the local crate. You should not use it
653 /// directly, because to do so will make your pass dependent on the
654 /// HIR of every item in the local crate. Instead, use
655 /// `tcx.inferred_outlives_of()` to get the outlives for a *particular*
657 #[derive(HashStable, Debug)]
658 pub struct CratePredicatesMap<'tcx> {
659 /// For each struct with outlive bounds, maps to a vector of the
660 /// predicate of its outlive bounds. If an item has no outlives
661 /// bounds, it will have no entry.
662 pub predicates: FxHashMap<DefId, &'tcx [(Clause<'tcx>, Span)]>,
665 impl<'tcx> Predicate<'tcx> {
666 /// Performs a substitution suitable for going from a
667 /// poly-trait-ref to supertraits that must hold if that
668 /// poly-trait-ref holds. This is slightly different from a normal
669 /// substitution in terms of what happens with bound regions. See
670 /// lengthy comment below for details.
671 pub fn subst_supertrait(
674 trait_ref: &ty::PolyTraitRef<'tcx>,
675 ) -> Predicate<'tcx> {
676 // The interaction between HRTB and supertraits is not entirely
677 // obvious. Let me walk you (and myself) through an example.
679 // Let's start with an easy case. Consider two traits:
681 // trait Foo<'a>: Bar<'a,'a> { }
682 // trait Bar<'b,'c> { }
684 // Now, if we have a trait reference `for<'x> T: Foo<'x>`, then
685 // we can deduce that `for<'x> T: Bar<'x,'x>`. Basically, if we
686 // knew that `Foo<'x>` (for any 'x) then we also know that
687 // `Bar<'x,'x>` (for any 'x). This more-or-less falls out from
688 // normal substitution.
690 // In terms of why this is sound, the idea is that whenever there
691 // is an impl of `T:Foo<'a>`, it must show that `T:Bar<'a,'a>`
692 // holds. So if there is an impl of `T:Foo<'a>` that applies to
693 // all `'a`, then we must know that `T:Bar<'a,'a>` holds for all
696 // Another example to be careful of is this:
698 // trait Foo1<'a>: for<'b> Bar1<'a,'b> { }
699 // trait Bar1<'b,'c> { }
701 // Here, if we have `for<'x> T: Foo1<'x>`, then what do we know?
702 // The answer is that we know `for<'x,'b> T: Bar1<'x,'b>`. The
703 // reason is similar to the previous example: any impl of
704 // `T:Foo1<'x>` must show that `for<'b> T: Bar1<'x, 'b>`. So
705 // basically we would want to collapse the bound lifetimes from
706 // the input (`trait_ref`) and the supertraits.
708 // To achieve this in practice is fairly straightforward. Let's
709 // consider the more complicated scenario:
711 // - We start out with `for<'x> T: Foo1<'x>`. In this case, `'x`
712 // has a De Bruijn index of 1. We want to produce `for<'x,'b> T: Bar1<'x,'b>`,
713 // where both `'x` and `'b` would have a DB index of 1.
714 // The substitution from the input trait-ref is therefore going to be
715 // `'a => 'x` (where `'x` has a DB index of 1).
716 // - The supertrait-ref is `for<'b> Bar1<'a,'b>`, where `'a` is an
717 // early-bound parameter and `'b' is a late-bound parameter with a
719 // - If we replace `'a` with `'x` from the input, it too will have
720 // a DB index of 1, and thus we'll have `for<'x,'b> Bar1<'x,'b>`
721 // just as we wanted.
723 // There is only one catch. If we just apply the substitution `'a
724 // => 'x` to `for<'b> Bar1<'a,'b>`, the substitution code will
725 // adjust the DB index because we substituting into a binder (it
726 // tries to be so smart...) resulting in `for<'x> for<'b>
727 // Bar1<'x,'b>` (we have no syntax for this, so use your
728 // imagination). Basically the 'x will have DB index of 2 and 'b
729 // will have DB index of 1. Not quite what we want. So we apply
730 // the substitution to the *contents* of the trait reference,
731 // rather than the trait reference itself (put another way, the
732 // substitution code expects equal binding levels in the values
733 // from the substitution and the value being substituted into, and
734 // this trick achieves that).
736 // Working through the second example:
737 // trait_ref: for<'x> T: Foo1<'^0.0>; substs: [T, '^0.0]
738 // predicate: for<'b> Self: Bar1<'a, '^0.0>; substs: [Self, 'a, '^0.0]
739 // We want to end up with:
740 // for<'x, 'b> T: Bar1<'^0.0, '^0.1>
742 // 1) We must shift all bound vars in predicate by the length
743 // of trait ref's bound vars. So, we would end up with predicate like
744 // Self: Bar1<'a, '^0.1>
745 // 2) We can then apply the trait substs to this, ending up with
746 // T: Bar1<'^0.0, '^0.1>
747 // 3) Finally, to create the final bound vars, we concatenate the bound
748 // vars of the trait ref with those of the predicate:
750 let bound_pred = self.kind();
751 let pred_bound_vars = bound_pred.bound_vars();
752 let trait_bound_vars = trait_ref.bound_vars();
753 // 1) Self: Bar1<'a, '^0.0> -> Self: Bar1<'a, '^0.1>
755 tcx.shift_bound_var_indices(trait_bound_vars.len(), bound_pred.skip_binder());
756 // 2) Self: Bar1<'a, '^0.1> -> T: Bar1<'^0.0, '^0.1>
757 let new = EarlyBinder(shifted_pred).subst(tcx, trait_ref.skip_binder().substs);
758 // 3) ['x] + ['b] -> ['x, 'b]
760 tcx.mk_bound_variable_kinds(trait_bound_vars.iter().chain(pred_bound_vars));
761 tcx.reuse_or_mk_predicate(self, ty::Binder::bind_with_vars(new, bound_vars))
765 #[derive(Clone, Copy, PartialEq, Eq, Hash, TyEncodable, TyDecodable)]
766 #[derive(HashStable, TypeFoldable, TypeVisitable, Lift)]
767 pub struct TraitPredicate<'tcx> {
768 pub trait_ref: TraitRef<'tcx>,
770 pub constness: BoundConstness,
772 /// If polarity is Positive: we are proving that the trait is implemented.
774 /// If polarity is Negative: we are proving that a negative impl of this trait
775 /// exists. (Note that coherence also checks whether negative impls of supertraits
776 /// exist via a series of predicates.)
778 /// If polarity is Reserved: that's a bug.
779 pub polarity: ImplPolarity,
782 pub type PolyTraitPredicate<'tcx> = ty::Binder<'tcx, TraitPredicate<'tcx>>;
784 impl<'tcx> TraitPredicate<'tcx> {
785 pub fn remap_constness(&mut self, param_env: &mut ParamEnv<'tcx>) {
786 *param_env = param_env.with_constness(self.constness.and(param_env.constness()))
789 /// Remap the constness of this predicate before emitting it for diagnostics.
790 pub fn remap_constness_diag(&mut self, param_env: ParamEnv<'tcx>) {
791 // this is different to `remap_constness` that callees want to print this predicate
792 // in case of selection errors. `T: ~const Drop` bounds cannot end up here when the
793 // param_env is not const because it is always satisfied in non-const contexts.
794 if let hir::Constness::NotConst = param_env.constness() {
795 self.constness = ty::BoundConstness::NotConst;
799 pub fn with_self_ty(self, tcx: TyCtxt<'tcx>, self_ty: Ty<'tcx>) -> Self {
800 Self { trait_ref: self.trait_ref.with_self_ty(tcx, self_ty), ..self }
803 pub fn def_id(self) -> DefId {
804 self.trait_ref.def_id
807 pub fn self_ty(self) -> Ty<'tcx> {
808 self.trait_ref.self_ty()
812 pub fn is_const_if_const(self) -> bool {
813 self.constness == BoundConstness::ConstIfConst
816 pub fn is_constness_satisfied_by(self, constness: hir::Constness) -> bool {
817 match (self.constness, constness) {
818 (BoundConstness::NotConst, _)
819 | (BoundConstness::ConstIfConst, hir::Constness::Const) => true,
820 (BoundConstness::ConstIfConst, hir::Constness::NotConst) => false,
824 pub fn without_const(mut self) -> Self {
825 self.constness = BoundConstness::NotConst;
830 impl<'tcx> PolyTraitPredicate<'tcx> {
831 pub fn def_id(self) -> DefId {
832 // Ok to skip binder since trait `DefId` does not care about regions.
833 self.skip_binder().def_id()
836 pub fn self_ty(self) -> ty::Binder<'tcx, Ty<'tcx>> {
837 self.map_bound(|trait_ref| trait_ref.self_ty())
840 /// Remap the constness of this predicate before emitting it for diagnostics.
841 pub fn remap_constness_diag(&mut self, param_env: ParamEnv<'tcx>) {
842 *self = self.map_bound(|mut p| {
843 p.remap_constness_diag(param_env);
849 pub fn is_const_if_const(self) -> bool {
850 self.skip_binder().is_const_if_const()
855 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, TyEncodable, TyDecodable)]
856 #[derive(HashStable, TypeFoldable, TypeVisitable, Lift)]
857 pub struct OutlivesPredicate<A, B>(pub A, pub B);
858 pub type RegionOutlivesPredicate<'tcx> = OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>;
859 pub type TypeOutlivesPredicate<'tcx> = OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>;
860 pub type PolyRegionOutlivesPredicate<'tcx> = ty::Binder<'tcx, RegionOutlivesPredicate<'tcx>>;
861 pub type PolyTypeOutlivesPredicate<'tcx> = ty::Binder<'tcx, TypeOutlivesPredicate<'tcx>>;
863 /// Encodes that `a` must be a subtype of `b`. The `a_is_expected` flag indicates
864 /// whether the `a` type is the type that we should label as "expected" when
865 /// presenting user diagnostics.
866 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, TyEncodable, TyDecodable)]
867 #[derive(HashStable, TypeFoldable, TypeVisitable, Lift)]
868 pub struct SubtypePredicate<'tcx> {
869 pub a_is_expected: bool,
873 pub type PolySubtypePredicate<'tcx> = ty::Binder<'tcx, SubtypePredicate<'tcx>>;
875 /// Encodes that we have to coerce *from* the `a` type to the `b` type.
876 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, TyEncodable, TyDecodable)]
877 #[derive(HashStable, TypeFoldable, TypeVisitable, Lift)]
878 pub struct CoercePredicate<'tcx> {
882 pub type PolyCoercePredicate<'tcx> = ty::Binder<'tcx, CoercePredicate<'tcx>>;
884 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
885 pub struct Term<'tcx> {
887 marker: PhantomData<(Ty<'tcx>, Const<'tcx>)>,
890 impl Debug for Term<'_> {
891 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
892 let data = if let Some(ty) = self.ty() {
893 format!("Term::Ty({:?})", ty)
894 } else if let Some(ct) = self.ct() {
895 format!("Term::Ct({:?})", ct)
903 impl<'tcx> From<Ty<'tcx>> for Term<'tcx> {
904 fn from(ty: Ty<'tcx>) -> Self {
905 TermKind::Ty(ty).pack()
909 impl<'tcx> From<Const<'tcx>> for Term<'tcx> {
910 fn from(c: Const<'tcx>) -> Self {
911 TermKind::Const(c).pack()
915 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for Term<'tcx> {
916 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
917 self.unpack().hash_stable(hcx, hasher);
921 impl<'tcx> TypeFoldable<'tcx> for Term<'tcx> {
922 fn try_fold_with<F: FallibleTypeFolder<'tcx>>(self, folder: &mut F) -> Result<Self, F::Error> {
923 Ok(self.unpack().try_fold_with(folder)?.pack())
927 impl<'tcx> TypeVisitable<'tcx> for Term<'tcx> {
928 fn visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> ControlFlow<V::BreakTy> {
929 self.unpack().visit_with(visitor)
933 impl<'tcx, E: TyEncoder<I = TyCtxt<'tcx>>> Encodable<E> for Term<'tcx> {
934 fn encode(&self, e: &mut E) {
935 self.unpack().encode(e)
939 impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> Decodable<D> for Term<'tcx> {
940 fn decode(d: &mut D) -> Self {
941 let res: TermKind<'tcx> = Decodable::decode(d);
946 impl<'tcx> Term<'tcx> {
948 pub fn unpack(self) -> TermKind<'tcx> {
949 let ptr = self.ptr.get();
950 // SAFETY: use of `Interned::new_unchecked` here is ok because these
951 // pointers were originally created from `Interned` types in `pack()`,
952 // and this is just going in the other direction.
954 match ptr & TAG_MASK {
955 TYPE_TAG => TermKind::Ty(Ty(Interned::new_unchecked(
956 &*((ptr & !TAG_MASK) as *const WithCachedTypeInfo<ty::TyKind<'tcx>>),
958 CONST_TAG => TermKind::Const(ty::Const(Interned::new_unchecked(
959 &*((ptr & !TAG_MASK) as *const ty::ConstData<'tcx>),
961 _ => core::intrinsics::unreachable(),
966 pub fn ty(&self) -> Option<Ty<'tcx>> {
967 if let TermKind::Ty(ty) = self.unpack() { Some(ty) } else { None }
970 pub fn ct(&self) -> Option<Const<'tcx>> {
971 if let TermKind::Const(c) = self.unpack() { Some(c) } else { None }
974 pub fn into_arg(self) -> GenericArg<'tcx> {
975 match self.unpack() {
976 TermKind::Ty(ty) => ty.into(),
977 TermKind::Const(c) => c.into(),
982 const TAG_MASK: usize = 0b11;
983 const TYPE_TAG: usize = 0b00;
984 const CONST_TAG: usize = 0b01;
986 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, TyEncodable, TyDecodable)]
987 #[derive(HashStable, TypeFoldable, TypeVisitable)]
988 pub enum TermKind<'tcx> {
993 impl<'tcx> TermKind<'tcx> {
995 fn pack(self) -> Term<'tcx> {
996 let (tag, ptr) = match self {
997 TermKind::Ty(ty) => {
998 // Ensure we can use the tag bits.
999 assert_eq!(mem::align_of_val(&*ty.0.0) & TAG_MASK, 0);
1000 (TYPE_TAG, ty.0.0 as *const WithCachedTypeInfo<ty::TyKind<'tcx>> as usize)
1002 TermKind::Const(ct) => {
1003 // Ensure we can use the tag bits.
1004 assert_eq!(mem::align_of_val(&*ct.0.0) & TAG_MASK, 0);
1005 (CONST_TAG, ct.0.0 as *const ty::ConstData<'tcx> as usize)
1009 Term { ptr: unsafe { NonZeroUsize::new_unchecked(ptr | tag) }, marker: PhantomData }
1013 /// This kind of predicate has no *direct* correspondent in the
1014 /// syntax, but it roughly corresponds to the syntactic forms:
1016 /// 1. `T: TraitRef<..., Item = Type>`
1017 /// 2. `<T as TraitRef<...>>::Item == Type` (NYI)
1019 /// In particular, form #1 is "desugared" to the combination of a
1020 /// normal trait predicate (`T: TraitRef<...>`) and one of these
1021 /// predicates. Form #2 is a broader form in that it also permits
1022 /// equality between arbitrary types. Processing an instance of
1023 /// Form #2 eventually yields one of these `ProjectionPredicate`
1024 /// instances to normalize the LHS.
1025 #[derive(Copy, Clone, PartialEq, Eq, Hash, TyEncodable, TyDecodable)]
1026 #[derive(HashStable, TypeFoldable, TypeVisitable, Lift)]
1027 pub struct ProjectionPredicate<'tcx> {
1028 pub projection_ty: AliasTy<'tcx>,
1029 pub term: Term<'tcx>,
1032 impl<'tcx> ProjectionPredicate<'tcx> {
1033 pub fn self_ty(self) -> Ty<'tcx> {
1034 self.projection_ty.self_ty()
1037 pub fn with_self_ty(self, tcx: TyCtxt<'tcx>, self_ty: Ty<'tcx>) -> ProjectionPredicate<'tcx> {
1038 Self { projection_ty: self.projection_ty.with_self_ty(tcx, self_ty), ..self }
1041 pub fn trait_def_id(self, tcx: TyCtxt<'tcx>) -> DefId {
1042 self.projection_ty.trait_def_id(tcx)
1045 pub fn def_id(self) -> DefId {
1046 self.projection_ty.def_id
1050 pub type PolyProjectionPredicate<'tcx> = Binder<'tcx, ProjectionPredicate<'tcx>>;
1052 impl<'tcx> PolyProjectionPredicate<'tcx> {
1053 /// Returns the `DefId` of the trait of the associated item being projected.
1055 pub fn trait_def_id(&self, tcx: TyCtxt<'tcx>) -> DefId {
1056 self.skip_binder().projection_ty.trait_def_id(tcx)
1059 /// Get the [PolyTraitRef] required for this projection to be well formed.
1060 /// Note that for generic associated types the predicates of the associated
1061 /// type also need to be checked.
1063 pub fn required_poly_trait_ref(&self, tcx: TyCtxt<'tcx>) -> PolyTraitRef<'tcx> {
1064 // Note: unlike with `TraitRef::to_poly_trait_ref()`,
1065 // `self.0.trait_ref` is permitted to have escaping regions.
1066 // This is because here `self` has a `Binder` and so does our
1067 // return value, so we are preserving the number of binding
1069 self.map_bound(|predicate| predicate.projection_ty.trait_ref(tcx))
1072 pub fn term(&self) -> Binder<'tcx, Term<'tcx>> {
1073 self.map_bound(|predicate| predicate.term)
1076 /// The `DefId` of the `TraitItem` for the associated type.
1078 /// Note that this is not the `DefId` of the `TraitRef` containing this
1079 /// associated type, which is in `tcx.associated_item(projection_def_id()).container`.
1080 pub fn projection_def_id(&self) -> DefId {
1081 // Ok to skip binder since trait `DefId` does not care about regions.
1082 self.skip_binder().projection_ty.def_id
1086 pub trait ToPolyTraitRef<'tcx> {
1087 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx>;
1090 impl<'tcx> ToPolyTraitRef<'tcx> for PolyTraitPredicate<'tcx> {
1091 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
1092 self.map_bound_ref(|trait_pred| trait_pred.trait_ref)
1096 pub trait ToPredicate<'tcx, P = Predicate<'tcx>> {
1097 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> P;
1100 impl<'tcx, T> ToPredicate<'tcx, T> for T {
1101 fn to_predicate(self, _tcx: TyCtxt<'tcx>) -> T {
1106 impl<'tcx> ToPredicate<'tcx> for Binder<'tcx, PredicateKind<'tcx>> {
1108 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1109 tcx.mk_predicate(self)
1113 impl<'tcx> ToPredicate<'tcx> for Clause<'tcx> {
1115 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1116 tcx.mk_predicate(ty::Binder::dummy(ty::PredicateKind::Clause(self)))
1120 impl<'tcx> ToPredicate<'tcx> for Binder<'tcx, TraitRef<'tcx>> {
1122 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1123 let pred: PolyTraitPredicate<'tcx> = self.to_predicate(tcx);
1124 pred.to_predicate(tcx)
1128 impl<'tcx> ToPredicate<'tcx, PolyTraitPredicate<'tcx>> for Binder<'tcx, TraitRef<'tcx>> {
1130 fn to_predicate(self, _: TyCtxt<'tcx>) -> PolyTraitPredicate<'tcx> {
1131 self.map_bound(|trait_ref| TraitPredicate {
1133 constness: ty::BoundConstness::NotConst,
1134 polarity: ty::ImplPolarity::Positive,
1139 impl<'tcx> ToPredicate<'tcx> for PolyTraitPredicate<'tcx> {
1140 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1141 self.map_bound(|p| PredicateKind::Clause(Clause::Trait(p))).to_predicate(tcx)
1145 impl<'tcx> ToPredicate<'tcx> for PolyRegionOutlivesPredicate<'tcx> {
1146 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1147 self.map_bound(|p| PredicateKind::Clause(Clause::RegionOutlives(p))).to_predicate(tcx)
1151 impl<'tcx> ToPredicate<'tcx> for PolyTypeOutlivesPredicate<'tcx> {
1152 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1153 self.map_bound(|p| PredicateKind::Clause(Clause::TypeOutlives(p))).to_predicate(tcx)
1157 impl<'tcx> ToPredicate<'tcx> for PolyProjectionPredicate<'tcx> {
1158 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1159 self.map_bound(|p| PredicateKind::Clause(Clause::Projection(p))).to_predicate(tcx)
1163 impl<'tcx> Predicate<'tcx> {
1164 pub fn to_opt_poly_trait_pred(self) -> Option<PolyTraitPredicate<'tcx>> {
1165 let predicate = self.kind();
1166 match predicate.skip_binder() {
1167 PredicateKind::Clause(Clause::Trait(t)) => Some(predicate.rebind(t)),
1168 PredicateKind::Clause(Clause::Projection(..))
1169 | PredicateKind::Subtype(..)
1170 | PredicateKind::Coerce(..)
1171 | PredicateKind::Clause(Clause::RegionOutlives(..))
1172 | PredicateKind::WellFormed(..)
1173 | PredicateKind::ObjectSafe(..)
1174 | PredicateKind::ClosureKind(..)
1175 | PredicateKind::Clause(Clause::TypeOutlives(..))
1176 | PredicateKind::ConstEvaluatable(..)
1177 | PredicateKind::ConstEquate(..)
1178 | PredicateKind::Ambiguous
1179 | PredicateKind::TypeWellFormedFromEnv(..) => None,
1183 pub fn to_opt_poly_projection_pred(self) -> Option<PolyProjectionPredicate<'tcx>> {
1184 let predicate = self.kind();
1185 match predicate.skip_binder() {
1186 PredicateKind::Clause(Clause::Projection(t)) => Some(predicate.rebind(t)),
1187 PredicateKind::Clause(Clause::Trait(..))
1188 | PredicateKind::Subtype(..)
1189 | PredicateKind::Coerce(..)
1190 | PredicateKind::Clause(Clause::RegionOutlives(..))
1191 | PredicateKind::WellFormed(..)
1192 | PredicateKind::ObjectSafe(..)
1193 | PredicateKind::ClosureKind(..)
1194 | PredicateKind::Clause(Clause::TypeOutlives(..))
1195 | PredicateKind::ConstEvaluatable(..)
1196 | PredicateKind::ConstEquate(..)
1197 | PredicateKind::Ambiguous
1198 | PredicateKind::TypeWellFormedFromEnv(..) => None,
1202 pub fn to_opt_type_outlives(self) -> Option<PolyTypeOutlivesPredicate<'tcx>> {
1203 let predicate = self.kind();
1204 match predicate.skip_binder() {
1205 PredicateKind::Clause(Clause::TypeOutlives(data)) => Some(predicate.rebind(data)),
1206 PredicateKind::Clause(Clause::Trait(..))
1207 | PredicateKind::Clause(Clause::Projection(..))
1208 | PredicateKind::Subtype(..)
1209 | PredicateKind::Coerce(..)
1210 | PredicateKind::Clause(Clause::RegionOutlives(..))
1211 | PredicateKind::WellFormed(..)
1212 | PredicateKind::ObjectSafe(..)
1213 | PredicateKind::ClosureKind(..)
1214 | PredicateKind::ConstEvaluatable(..)
1215 | PredicateKind::ConstEquate(..)
1216 | PredicateKind::Ambiguous
1217 | PredicateKind::TypeWellFormedFromEnv(..) => None,
1222 /// Represents the bounds declared on a particular set of type
1223 /// parameters. Should eventually be generalized into a flag list of
1224 /// where-clauses. You can obtain an `InstantiatedPredicates` list from a
1225 /// `GenericPredicates` by using the `instantiate` method. Note that this method
1226 /// reflects an important semantic invariant of `InstantiatedPredicates`: while
1227 /// the `GenericPredicates` are expressed in terms of the bound type
1228 /// parameters of the impl/trait/whatever, an `InstantiatedPredicates` instance
1229 /// represented a set of bounds for some particular instantiation,
1230 /// meaning that the generic parameters have been substituted with
1234 /// ```ignore (illustrative)
1235 /// struct Foo<T, U: Bar<T>> { ... }
1237 /// Here, the `GenericPredicates` for `Foo` would contain a list of bounds like
1238 /// `[[], [U:Bar<T>]]`. Now if there were some particular reference
1239 /// like `Foo<isize,usize>`, then the `InstantiatedPredicates` would be `[[],
1240 /// [usize:Bar<isize>]]`.
1241 #[derive(Clone, Debug, TypeFoldable, TypeVisitable)]
1242 pub struct InstantiatedPredicates<'tcx> {
1243 pub predicates: Vec<Predicate<'tcx>>,
1244 pub spans: Vec<Span>,
1247 impl<'tcx> InstantiatedPredicates<'tcx> {
1248 pub fn empty() -> InstantiatedPredicates<'tcx> {
1249 InstantiatedPredicates { predicates: vec![], spans: vec![] }
1252 pub fn is_empty(&self) -> bool {
1253 self.predicates.is_empty()
1257 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable, TyEncodable, TyDecodable, Lift)]
1258 #[derive(TypeFoldable, TypeVisitable)]
1259 pub struct OpaqueTypeKey<'tcx> {
1260 pub def_id: LocalDefId,
1261 pub substs: SubstsRef<'tcx>,
1264 #[derive(Copy, Clone, Debug, TypeFoldable, TypeVisitable, HashStable, TyEncodable, TyDecodable)]
1265 pub struct OpaqueHiddenType<'tcx> {
1266 /// The span of this particular definition of the opaque type. So
1269 /// ```ignore (incomplete snippet)
1270 /// type Foo = impl Baz;
1271 /// fn bar() -> Foo {
1272 /// // ^^^ This is the span we are looking for!
1276 /// In cases where the fn returns `(impl Trait, impl Trait)` or
1277 /// other such combinations, the result is currently
1278 /// over-approximated, but better than nothing.
1281 /// The type variable that represents the value of the opaque type
1282 /// that we require. In other words, after we compile this function,
1283 /// we will be created a constraint like:
1284 /// ```ignore (pseudo-rust)
1287 /// where `?C` is the value of this type variable. =) It may
1288 /// naturally refer to the type and lifetime parameters in scope
1289 /// in this function, though ultimately it should only reference
1290 /// those that are arguments to `Foo` in the constraint above. (In
1291 /// other words, `?C` should not include `'b`, even though it's a
1292 /// lifetime parameter on `foo`.)
1296 impl<'tcx> OpaqueHiddenType<'tcx> {
1297 pub fn report_mismatch(&self, other: &Self, tcx: TyCtxt<'tcx>) {
1298 // Found different concrete types for the opaque type.
1299 let sub_diag = if self.span == other.span {
1300 TypeMismatchReason::ConflictType { span: self.span }
1302 TypeMismatchReason::PreviousUse { span: self.span }
1304 tcx.sess.emit_err(OpaqueHiddenTypeMismatch {
1307 other_span: other.span,
1312 #[instrument(level = "debug", skip(tcx), ret)]
1313 pub fn remap_generic_params_to_declaration_params(
1315 opaque_type_key: OpaqueTypeKey<'tcx>,
1317 // typeck errors have subpar spans for opaque types, so delay error reporting until borrowck.
1318 ignore_errors: bool,
1319 origin: OpaqueTyOrigin,
1321 let OpaqueTypeKey { def_id, substs } = opaque_type_key;
1323 // Use substs to build up a reverse map from regions to their
1324 // identity mappings. This is necessary because of `impl
1325 // Trait` lifetimes are computed by replacing existing
1326 // lifetimes with 'static and remapping only those used in the
1327 // `impl Trait` return type, resulting in the parameters
1329 let id_substs = InternalSubsts::identity_for_item(tcx, def_id.to_def_id());
1332 // This zip may have several times the same lifetime in `substs` paired with a different
1333 // lifetime from `id_substs`. Simply `collect`ing the iterator is the correct behaviour:
1334 // it will pick the last one, which is the one we introduced in the impl-trait desugaring.
1335 let map = substs.iter().zip(id_substs);
1337 let map: FxHashMap<GenericArg<'tcx>, GenericArg<'tcx>> = match origin {
1338 // HACK: The HIR lowering for async fn does not generate
1339 // any `+ Captures<'x>` bounds for the `impl Future<...>`, so all async fns with lifetimes
1340 // would now fail to compile. We should probably just make hir lowering fill this in properly.
1341 OpaqueTyOrigin::AsyncFn(_) => map.collect(),
1342 OpaqueTyOrigin::FnReturn(_) | OpaqueTyOrigin::TyAlias => {
1343 // Opaque types may only use regions that are bound. So for
1345 // type Foo<'a, 'b, 'c> = impl Trait<'a> + 'b;
1347 // we may not use `'c` in the hidden type.
1348 let variances = tcx.variances_of(def_id);
1351 map.filter(|(_, v)| {
1352 let ty::GenericArgKind::Lifetime(lt) = v.unpack() else { return true };
1353 let ty::ReEarlyBound(ebr) = lt.kind() else { bug!() };
1354 variances[ebr.index as usize] == ty::Variance::Invariant
1359 debug!("map = {:#?}", map);
1361 // Convert the type from the function into a type valid outside
1362 // the function, by replacing invalid regions with 'static,
1363 // after producing an error for each of them.
1364 self.fold_with(&mut opaque_types::ReverseMapper::new(tcx, map, self.span, ignore_errors))
1368 /// The "placeholder index" fully defines a placeholder region, type, or const. Placeholders are
1369 /// identified by both a universe, as well as a name residing within that universe. Distinct bound
1370 /// regions/types/consts within the same universe simply have an unknown relationship to one
1372 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
1373 #[derive(HashStable, TyEncodable, TyDecodable)]
1374 pub struct Placeholder<T> {
1375 pub universe: UniverseIndex,
1379 pub type PlaceholderRegion = Placeholder<BoundRegionKind>;
1381 pub type PlaceholderType = Placeholder<BoundVar>;
1383 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable)]
1384 #[derive(TyEncodable, TyDecodable, PartialOrd, Ord)]
1385 pub struct BoundConst<'tcx> {
1390 pub type PlaceholderConst<'tcx> = Placeholder<BoundVar>;
1392 /// A `DefId` which, in case it is a const argument, is potentially bundled with
1393 /// the `DefId` of the generic parameter it instantiates.
1395 /// This is used to avoid calls to `type_of` for const arguments during typeck
1396 /// which cause cycle errors.
1401 /// fn foo<const N: usize>(&self) -> [u8; N] { [0; N] }
1402 /// // ^ const parameter
1406 /// fn foo<const M: u8>(&self) -> usize { 42 }
1407 /// // ^ const parameter
1412 /// let _b = a.foo::<{ 3 + 7 }>();
1413 /// // ^^^^^^^^^ const argument
1417 /// Let's look at the call `a.foo::<{ 3 + 7 }>()` here. We do not know
1418 /// which `foo` is used until we know the type of `a`.
1420 /// We only know the type of `a` once we are inside of `typeck(main)`.
1421 /// We also end up normalizing the type of `_b` during `typeck(main)` which
1422 /// requires us to evaluate the const argument.
1424 /// To evaluate that const argument we need to know its type,
1425 /// which we would get using `type_of(const_arg)`. This requires us to
1426 /// resolve `foo` as it can be either `usize` or `u8` in this example.
1427 /// However, resolving `foo` once again requires `typeck(main)` to get the type of `a`,
1428 /// which results in a cycle.
1430 /// In short we must not call `type_of(const_arg)` during `typeck(main)`.
1432 /// When first creating the `ty::Const` of the const argument inside of `typeck` we have
1433 /// already resolved `foo` so we know which const parameter this argument instantiates.
1434 /// This means that we also know the expected result of `type_of(const_arg)` even if we
1435 /// aren't allowed to call that query: it is equal to `type_of(const_param)` which is
1436 /// trivial to compute.
1438 /// If we now want to use that constant in a place which potentially needs its type
1439 /// we also pass the type of its `const_param`. This is the point of `WithOptConstParam`,
1440 /// except that instead of a `Ty` we bundle the `DefId` of the const parameter.
1441 /// Meaning that we need to use `type_of(const_param_did)` if `const_param_did` is `Some`
1442 /// to get the type of `did`.
1443 #[derive(Copy, Clone, Debug, TypeFoldable, TypeVisitable, Lift, TyEncodable, TyDecodable)]
1444 #[derive(PartialEq, Eq, PartialOrd, Ord)]
1445 #[derive(Hash, HashStable)]
1446 pub struct WithOptConstParam<T> {
1448 /// The `DefId` of the corresponding generic parameter in case `did` is
1449 /// a const argument.
1451 /// Note that even if `did` is a const argument, this may still be `None`.
1452 /// All queries taking `WithOptConstParam` start by calling `tcx.opt_const_param_of(def.did)`
1453 /// to potentially update `param_did` in the case it is `None`.
1454 pub const_param_did: Option<DefId>,
1457 impl<T> WithOptConstParam<T> {
1458 /// Creates a new `WithOptConstParam` setting `const_param_did` to `None`.
1460 pub fn unknown(did: T) -> WithOptConstParam<T> {
1461 WithOptConstParam { did, const_param_did: None }
1465 impl WithOptConstParam<LocalDefId> {
1466 /// Returns `Some((did, param_did))` if `def_id` is a const argument,
1467 /// `None` otherwise.
1469 pub fn try_lookup(did: LocalDefId, tcx: TyCtxt<'_>) -> Option<(LocalDefId, DefId)> {
1470 tcx.opt_const_param_of(did).map(|param_did| (did, param_did))
1473 /// In case `self` is unknown but `self.did` is a const argument, this returns
1474 /// a `WithOptConstParam` with the correct `const_param_did`.
1476 pub fn try_upgrade(self, tcx: TyCtxt<'_>) -> Option<WithOptConstParam<LocalDefId>> {
1477 if self.const_param_did.is_none() {
1478 if let const_param_did @ Some(_) = tcx.opt_const_param_of(self.did) {
1479 return Some(WithOptConstParam { did: self.did, const_param_did });
1486 pub fn to_global(self) -> WithOptConstParam<DefId> {
1487 WithOptConstParam { did: self.did.to_def_id(), const_param_did: self.const_param_did }
1490 pub fn def_id_for_type_of(self) -> DefId {
1491 if let Some(did) = self.const_param_did { did } else { self.did.to_def_id() }
1495 impl WithOptConstParam<DefId> {
1496 pub fn as_local(self) -> Option<WithOptConstParam<LocalDefId>> {
1499 .map(|did| WithOptConstParam { did, const_param_did: self.const_param_did })
1502 pub fn as_const_arg(self) -> Option<(LocalDefId, DefId)> {
1503 if let Some(param_did) = self.const_param_did {
1504 if let Some(did) = self.did.as_local() {
1505 return Some((did, param_did));
1512 pub fn is_local(self) -> bool {
1516 pub fn def_id_for_type_of(self) -> DefId {
1517 self.const_param_did.unwrap_or(self.did)
1521 /// When type checking, we use the `ParamEnv` to track
1522 /// details about the set of where-clauses that are in scope at this
1523 /// particular point.
1524 #[derive(Copy, Clone, Hash, PartialEq, Eq)]
1525 pub struct ParamEnv<'tcx> {
1526 /// This packs both caller bounds and the reveal enum into one pointer.
1528 /// Caller bounds are `Obligation`s that the caller must satisfy. This is
1529 /// basically the set of bounds on the in-scope type parameters, translated
1530 /// into `Obligation`s, and elaborated and normalized.
1532 /// Use the `caller_bounds()` method to access.
1534 /// Typically, this is `Reveal::UserFacing`, but during codegen we
1535 /// want `Reveal::All`.
1537 /// Note: This is packed, use the reveal() method to access it.
1538 packed: CopyTaggedPtr<&'tcx List<Predicate<'tcx>>, ParamTag, true>,
1541 #[derive(Copy, Clone)]
1543 reveal: traits::Reveal,
1544 constness: hir::Constness,
1547 unsafe impl rustc_data_structures::tagged_ptr::Tag for ParamTag {
1548 const BITS: usize = 2;
1550 fn into_usize(self) -> usize {
1552 Self { reveal: traits::Reveal::UserFacing, constness: hir::Constness::NotConst } => 0,
1553 Self { reveal: traits::Reveal::All, constness: hir::Constness::NotConst } => 1,
1554 Self { reveal: traits::Reveal::UserFacing, constness: hir::Constness::Const } => 2,
1555 Self { reveal: traits::Reveal::All, constness: hir::Constness::Const } => 3,
1559 unsafe fn from_usize(ptr: usize) -> Self {
1561 0 => Self { reveal: traits::Reveal::UserFacing, constness: hir::Constness::NotConst },
1562 1 => Self { reveal: traits::Reveal::All, constness: hir::Constness::NotConst },
1563 2 => Self { reveal: traits::Reveal::UserFacing, constness: hir::Constness::Const },
1564 3 => Self { reveal: traits::Reveal::All, constness: hir::Constness::Const },
1565 _ => std::hint::unreachable_unchecked(),
1570 impl<'tcx> fmt::Debug for ParamEnv<'tcx> {
1571 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1572 f.debug_struct("ParamEnv")
1573 .field("caller_bounds", &self.caller_bounds())
1574 .field("reveal", &self.reveal())
1575 .field("constness", &self.constness())
1580 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for ParamEnv<'tcx> {
1581 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
1582 self.caller_bounds().hash_stable(hcx, hasher);
1583 self.reveal().hash_stable(hcx, hasher);
1584 self.constness().hash_stable(hcx, hasher);
1588 impl<'tcx> TypeFoldable<'tcx> for ParamEnv<'tcx> {
1589 fn try_fold_with<F: ty::fold::FallibleTypeFolder<'tcx>>(
1592 ) -> Result<Self, F::Error> {
1594 self.caller_bounds().try_fold_with(folder)?,
1595 self.reveal().try_fold_with(folder)?,
1601 impl<'tcx> TypeVisitable<'tcx> for ParamEnv<'tcx> {
1602 fn visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> ControlFlow<V::BreakTy> {
1603 self.caller_bounds().visit_with(visitor)?;
1604 self.reveal().visit_with(visitor)
1608 impl<'tcx> ParamEnv<'tcx> {
1609 /// Construct a trait environment suitable for contexts where
1610 /// there are no where-clauses in scope. Hidden types (like `impl
1611 /// Trait`) are left hidden, so this is suitable for ordinary
1614 pub fn empty() -> Self {
1615 Self::new(List::empty(), Reveal::UserFacing, hir::Constness::NotConst)
1619 pub fn caller_bounds(self) -> &'tcx List<Predicate<'tcx>> {
1620 self.packed.pointer()
1624 pub fn reveal(self) -> traits::Reveal {
1625 self.packed.tag().reveal
1629 pub fn constness(self) -> hir::Constness {
1630 self.packed.tag().constness
1634 pub fn is_const(self) -> bool {
1635 self.packed.tag().constness == hir::Constness::Const
1638 /// Construct a trait environment with no where-clauses in scope
1639 /// where the values of all `impl Trait` and other hidden types
1640 /// are revealed. This is suitable for monomorphized, post-typeck
1641 /// environments like codegen or doing optimizations.
1643 /// N.B., if you want to have predicates in scope, use `ParamEnv::new`,
1644 /// or invoke `param_env.with_reveal_all()`.
1646 pub fn reveal_all() -> Self {
1647 Self::new(List::empty(), Reveal::All, hir::Constness::NotConst)
1650 /// Construct a trait environment with the given set of predicates.
1653 caller_bounds: &'tcx List<Predicate<'tcx>>,
1655 constness: hir::Constness,
1657 ty::ParamEnv { packed: CopyTaggedPtr::new(caller_bounds, ParamTag { reveal, constness }) }
1660 pub fn with_user_facing(mut self) -> Self {
1661 self.packed.set_tag(ParamTag { reveal: Reveal::UserFacing, ..self.packed.tag() });
1666 pub fn with_constness(mut self, constness: hir::Constness) -> Self {
1667 self.packed.set_tag(ParamTag { constness, ..self.packed.tag() });
1672 pub fn with_const(mut self) -> Self {
1673 self.packed.set_tag(ParamTag { constness: hir::Constness::Const, ..self.packed.tag() });
1678 pub fn without_const(mut self) -> Self {
1679 self.packed.set_tag(ParamTag { constness: hir::Constness::NotConst, ..self.packed.tag() });
1684 pub fn remap_constness_with(&mut self, mut constness: ty::BoundConstness) {
1685 *self = self.with_constness(constness.and(self.constness()))
1688 /// Returns a new parameter environment with the same clauses, but
1689 /// which "reveals" the true results of projections in all cases
1690 /// (even for associated types that are specializable). This is
1691 /// the desired behavior during codegen and certain other special
1692 /// contexts; normally though we want to use `Reveal::UserFacing`,
1693 /// which is the default.
1694 /// All opaque types in the caller_bounds of the `ParamEnv`
1695 /// will be normalized to their underlying types.
1696 /// See PR #65989 and issue #65918 for more details
1697 pub fn with_reveal_all_normalized(self, tcx: TyCtxt<'tcx>) -> Self {
1698 if self.packed.tag().reveal == traits::Reveal::All {
1703 tcx.reveal_opaque_types_in_bounds(self.caller_bounds()),
1709 /// Returns this same environment but with no caller bounds.
1711 pub fn without_caller_bounds(self) -> Self {
1712 Self::new(List::empty(), self.reveal(), self.constness())
1715 /// Creates a suitable environment in which to perform trait
1716 /// queries on the given value. When type-checking, this is simply
1717 /// the pair of the environment plus value. But when reveal is set to
1718 /// All, then if `value` does not reference any type parameters, we will
1719 /// pair it with the empty environment. This improves caching and is generally
1722 /// N.B., we preserve the environment when type-checking because it
1723 /// is possible for the user to have wacky where-clauses like
1724 /// `where Box<u32>: Copy`, which are clearly never
1725 /// satisfiable. We generally want to behave as if they were true,
1726 /// although the surrounding function is never reachable.
1727 pub fn and<T: TypeVisitable<'tcx>>(self, value: T) -> ParamEnvAnd<'tcx, T> {
1728 match self.reveal() {
1729 Reveal::UserFacing => ParamEnvAnd { param_env: self, value },
1732 if value.is_global() {
1733 ParamEnvAnd { param_env: self.without_caller_bounds(), value }
1735 ParamEnvAnd { param_env: self, value }
1742 // FIXME(ecstaticmorse): Audit all occurrences of `without_const().to_predicate(tcx)` to ensure that
1743 // the constness of trait bounds is being propagated correctly.
1744 impl<'tcx> PolyTraitRef<'tcx> {
1746 pub fn with_constness(self, constness: BoundConstness) -> PolyTraitPredicate<'tcx> {
1747 self.map_bound(|trait_ref| ty::TraitPredicate {
1750 polarity: ty::ImplPolarity::Positive,
1755 pub fn without_const(self) -> PolyTraitPredicate<'tcx> {
1756 self.with_constness(BoundConstness::NotConst)
1760 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TypeFoldable, TypeVisitable)]
1761 #[derive(HashStable, Lift)]
1762 pub struct ParamEnvAnd<'tcx, T> {
1763 pub param_env: ParamEnv<'tcx>,
1767 impl<'tcx, T> ParamEnvAnd<'tcx, T> {
1768 pub fn into_parts(self) -> (ParamEnv<'tcx>, T) {
1769 (self.param_env, self.value)
1773 pub fn without_const(mut self) -> Self {
1774 self.param_env = self.param_env.without_const();
1779 #[derive(Copy, Clone, Debug, HashStable, Encodable, Decodable)]
1780 pub struct Destructor {
1781 /// The `DefId` of the destructor method
1783 /// The constness of the destructor method
1784 pub constness: hir::Constness,
1788 #[derive(HashStable, TyEncodable, TyDecodable)]
1789 pub struct VariantFlags: u32 {
1790 const NO_VARIANT_FLAGS = 0;
1791 /// Indicates whether the field list of this variant is `#[non_exhaustive]`.
1792 const IS_FIELD_LIST_NON_EXHAUSTIVE = 1 << 0;
1793 /// Indicates whether this variant was obtained as part of recovering from
1794 /// a syntactic error. May be incomplete or bogus.
1795 const IS_RECOVERED = 1 << 1;
1799 /// Definition of a variant -- a struct's fields or an enum variant.
1800 #[derive(Debug, HashStable, TyEncodable, TyDecodable)]
1801 pub struct VariantDef {
1802 /// `DefId` that identifies the variant itself.
1803 /// If this variant belongs to a struct or union, then this is a copy of its `DefId`.
1805 /// `DefId` that identifies the variant's constructor.
1806 /// If this variant is a struct variant, then this is `None`.
1807 pub ctor: Option<(CtorKind, DefId)>,
1808 /// Variant or struct name.
1810 /// Discriminant of this variant.
1811 pub discr: VariantDiscr,
1812 /// Fields of this variant.
1813 pub fields: Vec<FieldDef>,
1814 /// Flags of the variant (e.g. is field list non-exhaustive)?
1815 flags: VariantFlags,
1819 /// Creates a new `VariantDef`.
1821 /// `variant_did` is the `DefId` that identifies the enum variant (if this `VariantDef`
1822 /// represents an enum variant).
1824 /// `ctor_did` is the `DefId` that identifies the constructor of unit or
1825 /// tuple-variants/structs. If this is a `struct`-variant then this should be `None`.
1827 /// `parent_did` is the `DefId` of the `AdtDef` representing the enum or struct that
1828 /// owns this variant. It is used for checking if a struct has `#[non_exhaustive]` w/out having
1829 /// to go through the redirect of checking the ctor's attributes - but compiling a small crate
1830 /// requires loading the `AdtDef`s for all the structs in the universe (e.g., coherence for any
1831 /// built-in trait), and we do not want to load attributes twice.
1833 /// If someone speeds up attribute loading to not be a performance concern, they can
1834 /// remove this hack and use the constructor `DefId` everywhere.
1837 variant_did: Option<DefId>,
1838 ctor: Option<(CtorKind, DefId)>,
1839 discr: VariantDiscr,
1840 fields: Vec<FieldDef>,
1844 is_field_list_non_exhaustive: bool,
1847 "VariantDef::new(name = {:?}, variant_did = {:?}, ctor = {:?}, discr = {:?},
1848 fields = {:?}, adt_kind = {:?}, parent_did = {:?})",
1849 name, variant_did, ctor, discr, fields, adt_kind, parent_did,
1852 let mut flags = VariantFlags::NO_VARIANT_FLAGS;
1853 if is_field_list_non_exhaustive {
1854 flags |= VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE;
1858 flags |= VariantFlags::IS_RECOVERED;
1861 VariantDef { def_id: variant_did.unwrap_or(parent_did), ctor, name, discr, fields, flags }
1864 /// Is this field list non-exhaustive?
1866 pub fn is_field_list_non_exhaustive(&self) -> bool {
1867 self.flags.intersects(VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE)
1870 /// Was this variant obtained as part of recovering from a syntactic error?
1872 pub fn is_recovered(&self) -> bool {
1873 self.flags.intersects(VariantFlags::IS_RECOVERED)
1876 /// Computes the `Ident` of this variant by looking up the `Span`
1877 pub fn ident(&self, tcx: TyCtxt<'_>) -> Ident {
1878 Ident::new(self.name, tcx.def_ident_span(self.def_id).unwrap())
1882 pub fn ctor_kind(&self) -> Option<CtorKind> {
1883 self.ctor.map(|(kind, _)| kind)
1887 pub fn ctor_def_id(&self) -> Option<DefId> {
1888 self.ctor.map(|(_, def_id)| def_id)
1892 impl PartialEq for VariantDef {
1894 fn eq(&self, other: &Self) -> bool {
1895 // There should be only one `VariantDef` for each `def_id`, therefore
1896 // it is fine to implement `PartialEq` only based on `def_id`.
1898 // Below, we exhaustively destructure `self` and `other` so that if the
1899 // definition of `VariantDef` changes, a compile-error will be produced,
1900 // reminding us to revisit this assumption.
1902 let Self { def_id: lhs_def_id, ctor: _, name: _, discr: _, fields: _, flags: _ } = &self;
1903 let Self { def_id: rhs_def_id, ctor: _, name: _, discr: _, fields: _, flags: _ } = other;
1904 lhs_def_id == rhs_def_id
1908 impl Eq for VariantDef {}
1910 impl Hash for VariantDef {
1912 fn hash<H: Hasher>(&self, s: &mut H) {
1913 // There should be only one `VariantDef` for each `def_id`, therefore
1914 // it is fine to implement `Hash` only based on `def_id`.
1916 // Below, we exhaustively destructure `self` so that if the definition
1917 // of `VariantDef` changes, a compile-error will be produced, reminding
1918 // us to revisit this assumption.
1920 let Self { def_id, ctor: _, name: _, discr: _, fields: _, flags: _ } = &self;
1925 #[derive(Copy, Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
1926 pub enum VariantDiscr {
1927 /// Explicit value for this variant, i.e., `X = 123`.
1928 /// The `DefId` corresponds to the embedded constant.
1931 /// The previous variant's discriminant plus one.
1932 /// For efficiency reasons, the distance from the
1933 /// last `Explicit` discriminant is being stored,
1934 /// or `0` for the first variant, if it has none.
1938 #[derive(Debug, HashStable, TyEncodable, TyDecodable)]
1939 pub struct FieldDef {
1942 pub vis: Visibility<DefId>,
1945 impl PartialEq for FieldDef {
1947 fn eq(&self, other: &Self) -> bool {
1948 // There should be only one `FieldDef` for each `did`, therefore it is
1949 // fine to implement `PartialEq` only based on `did`.
1951 // Below, we exhaustively destructure `self` so that if the definition
1952 // of `FieldDef` changes, a compile-error will be produced, reminding
1953 // us to revisit this assumption.
1955 let Self { did: lhs_did, name: _, vis: _ } = &self;
1957 let Self { did: rhs_did, name: _, vis: _ } = other;
1963 impl Eq for FieldDef {}
1965 impl Hash for FieldDef {
1967 fn hash<H: Hasher>(&self, s: &mut H) {
1968 // There should be only one `FieldDef` for each `did`, therefore it is
1969 // fine to implement `Hash` only based on `did`.
1971 // Below, we exhaustively destructure `self` so that if the definition
1972 // of `FieldDef` changes, a compile-error will be produced, reminding
1973 // us to revisit this assumption.
1975 let Self { did, name: _, vis: _ } = &self;
1981 impl<'tcx> FieldDef {
1982 /// Returns the type of this field. The resulting type is not normalized. The `subst` is
1983 /// typically obtained via the second field of [`TyKind::Adt`].
1984 pub fn ty(&self, tcx: TyCtxt<'tcx>, subst: SubstsRef<'tcx>) -> Ty<'tcx> {
1985 tcx.bound_type_of(self.did).subst(tcx, subst)
1988 /// Computes the `Ident` of this variant by looking up the `Span`
1989 pub fn ident(&self, tcx: TyCtxt<'_>) -> Ident {
1990 Ident::new(self.name, tcx.def_ident_span(self.did).unwrap())
1994 pub type Attributes<'tcx> = impl Iterator<Item = &'tcx ast::Attribute>;
1995 #[derive(Debug, PartialEq, Eq)]
1996 pub enum ImplOverlapKind {
1997 /// These impls are always allowed to overlap.
1999 /// Whether or not the impl is permitted due to the trait being a `#[marker]` trait
2002 /// These impls are allowed to overlap, but that raises
2003 /// an issue #33140 future-compatibility warning.
2005 /// Some background: in Rust 1.0, the trait-object types `Send + Sync` (today's
2006 /// `dyn Send + Sync`) and `Sync + Send` (now `dyn Sync + Send`) were different.
2008 /// The widely-used version 0.1.0 of the crate `traitobject` had accidentally relied
2009 /// that difference, making what reduces to the following set of impls:
2011 /// ```compile_fail,(E0119)
2013 /// impl Trait for dyn Send + Sync {}
2014 /// impl Trait for dyn Sync + Send {}
2017 /// Obviously, once we made these types be identical, that code causes a coherence
2018 /// error and a fairly big headache for us. However, luckily for us, the trait
2019 /// `Trait` used in this case is basically a marker trait, and therefore having
2020 /// overlapping impls for it is sound.
2022 /// To handle this, we basically regard the trait as a marker trait, with an additional
2023 /// future-compatibility warning. To avoid accidentally "stabilizing" this feature,
2024 /// it has the following restrictions:
2026 /// 1. The trait must indeed be a marker-like trait (i.e., no items), and must be
2028 /// 2. The trait-ref of both impls must be equal.
2029 /// 3. The trait-ref of both impls must be a trait object type consisting only of
2031 /// 4. Neither of the impls can have any where-clauses.
2033 /// Once `traitobject` 0.1.0 is no longer an active concern, this hack can be removed.
2037 impl<'tcx> TyCtxt<'tcx> {
2038 pub fn typeck_body(self, body: hir::BodyId) -> &'tcx TypeckResults<'tcx> {
2039 self.typeck(self.hir().body_owner_def_id(body))
2042 pub fn provided_trait_methods(self, id: DefId) -> impl 'tcx + Iterator<Item = &'tcx AssocItem> {
2043 self.associated_items(id)
2044 .in_definition_order()
2045 .filter(move |item| item.kind == AssocKind::Fn && item.defaultness(self).has_value())
2048 pub fn repr_options_of_def(self, did: DefId) -> ReprOptions {
2049 let mut flags = ReprFlags::empty();
2050 let mut size = None;
2051 let mut max_align: Option<Align> = None;
2052 let mut min_pack: Option<Align> = None;
2054 // Generate a deterministically-derived seed from the item's path hash
2055 // to allow for cross-crate compilation to actually work
2056 let mut field_shuffle_seed = self.def_path_hash(did).0.to_smaller_hash();
2058 // If the user defined a custom seed for layout randomization, xor the item's
2059 // path hash with the user defined seed, this will allowing determinism while
2060 // still allowing users to further randomize layout generation for e.g. fuzzing
2061 if let Some(user_seed) = self.sess.opts.unstable_opts.layout_seed {
2062 field_shuffle_seed ^= user_seed;
2065 for attr in self.get_attrs(did, sym::repr) {
2066 for r in attr::parse_repr_attr(&self.sess, attr) {
2067 flags.insert(match r {
2068 attr::ReprC => ReprFlags::IS_C,
2069 attr::ReprPacked(pack) => {
2070 let pack = Align::from_bytes(pack as u64).unwrap();
2071 min_pack = Some(if let Some(min_pack) = min_pack {
2078 attr::ReprTransparent => ReprFlags::IS_TRANSPARENT,
2079 attr::ReprSimd => ReprFlags::IS_SIMD,
2080 attr::ReprInt(i) => {
2081 size = Some(match i {
2082 attr::IntType::SignedInt(x) => match x {
2083 ast::IntTy::Isize => IntegerType::Pointer(true),
2084 ast::IntTy::I8 => IntegerType::Fixed(Integer::I8, true),
2085 ast::IntTy::I16 => IntegerType::Fixed(Integer::I16, true),
2086 ast::IntTy::I32 => IntegerType::Fixed(Integer::I32, true),
2087 ast::IntTy::I64 => IntegerType::Fixed(Integer::I64, true),
2088 ast::IntTy::I128 => IntegerType::Fixed(Integer::I128, true),
2090 attr::IntType::UnsignedInt(x) => match x {
2091 ast::UintTy::Usize => IntegerType::Pointer(false),
2092 ast::UintTy::U8 => IntegerType::Fixed(Integer::I8, false),
2093 ast::UintTy::U16 => IntegerType::Fixed(Integer::I16, false),
2094 ast::UintTy::U32 => IntegerType::Fixed(Integer::I32, false),
2095 ast::UintTy::U64 => IntegerType::Fixed(Integer::I64, false),
2096 ast::UintTy::U128 => IntegerType::Fixed(Integer::I128, false),
2101 attr::ReprAlign(align) => {
2102 max_align = max_align.max(Some(Align::from_bytes(align as u64).unwrap()));
2109 // If `-Z randomize-layout` was enabled for the type definition then we can
2110 // consider performing layout randomization
2111 if self.sess.opts.unstable_opts.randomize_layout {
2112 flags.insert(ReprFlags::RANDOMIZE_LAYOUT);
2115 // This is here instead of layout because the choice must make it into metadata.
2116 if !self.consider_optimizing(|| format!("Reorder fields of {:?}", self.def_path_str(did))) {
2117 flags.insert(ReprFlags::IS_LINEAR);
2120 ReprOptions { int: size, align: max_align, pack: min_pack, flags, field_shuffle_seed }
2123 /// Look up the name of a definition across crates. This does not look at HIR.
2124 pub fn opt_item_name(self, def_id: DefId) -> Option<Symbol> {
2125 if let Some(cnum) = def_id.as_crate_root() {
2126 Some(self.crate_name(cnum))
2128 let def_key = self.def_key(def_id);
2129 match def_key.disambiguated_data.data {
2130 // The name of a constructor is that of its parent.
2131 rustc_hir::definitions::DefPathData::Ctor => self
2132 .opt_item_name(DefId { krate: def_id.krate, index: def_key.parent.unwrap() }),
2133 // The name of opaque types only exists in HIR.
2134 rustc_hir::definitions::DefPathData::ImplTrait
2135 if let Some(def_id) = def_id.as_local() =>
2136 self.hir().opt_name(self.hir().local_def_id_to_hir_id(def_id)),
2137 _ => def_key.get_opt_name(),
2142 /// Look up the name of a definition across crates. This does not look at HIR.
2144 /// This method will ICE if the corresponding item does not have a name. In these cases, use
2145 /// [`opt_item_name`] instead.
2147 /// [`opt_item_name`]: Self::opt_item_name
2148 pub fn item_name(self, id: DefId) -> Symbol {
2149 self.opt_item_name(id).unwrap_or_else(|| {
2150 bug!("item_name: no name for {:?}", self.def_path(id));
2154 /// Look up the name and span of a definition.
2156 /// See [`item_name`][Self::item_name] for more information.
2157 pub fn opt_item_ident(self, def_id: DefId) -> Option<Ident> {
2158 let def = self.opt_item_name(def_id)?;
2161 .and_then(|id| self.def_ident_span(id))
2162 .unwrap_or(rustc_span::DUMMY_SP);
2163 Some(Ident::new(def, span))
2166 pub fn opt_associated_item(self, def_id: DefId) -> Option<&'tcx AssocItem> {
2167 if let DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy = self.def_kind(def_id) {
2168 Some(self.associated_item(def_id))
2174 pub fn find_field_index(self, ident: Ident, variant: &VariantDef) -> Option<usize> {
2178 .position(|field| self.hygienic_eq(ident, field.ident(self), variant.def_id))
2181 /// Returns `true` if the impls are the same polarity and the trait either
2182 /// has no items or is annotated `#[marker]` and prevents item overrides.
2183 pub fn impls_are_allowed_to_overlap(
2187 ) -> Option<ImplOverlapKind> {
2188 // If either trait impl references an error, they're allowed to overlap,
2189 // as one of them essentially doesn't exist.
2190 if self.impl_trait_ref(def_id1).map_or(false, |tr| tr.references_error())
2191 || self.impl_trait_ref(def_id2).map_or(false, |tr| tr.references_error())
2193 return Some(ImplOverlapKind::Permitted { marker: false });
2196 match (self.impl_polarity(def_id1), self.impl_polarity(def_id2)) {
2197 (ImplPolarity::Reservation, _) | (_, ImplPolarity::Reservation) => {
2198 // `#[rustc_reservation_impl]` impls don't overlap with anything
2200 "impls_are_allowed_to_overlap({:?}, {:?}) = Some(Permitted) (reservations)",
2203 return Some(ImplOverlapKind::Permitted { marker: false });
2205 (ImplPolarity::Positive, ImplPolarity::Negative)
2206 | (ImplPolarity::Negative, ImplPolarity::Positive) => {
2207 // `impl AutoTrait for Type` + `impl !AutoTrait for Type`
2209 "impls_are_allowed_to_overlap({:?}, {:?}) - None (differing polarities)",
2214 (ImplPolarity::Positive, ImplPolarity::Positive)
2215 | (ImplPolarity::Negative, ImplPolarity::Negative) => {}
2218 let is_marker_overlap = {
2219 let is_marker_impl = |def_id: DefId| -> bool {
2220 let trait_ref = self.impl_trait_ref(def_id);
2221 trait_ref.map_or(false, |tr| self.trait_def(tr.def_id).is_marker)
2223 is_marker_impl(def_id1) && is_marker_impl(def_id2)
2226 if is_marker_overlap {
2228 "impls_are_allowed_to_overlap({:?}, {:?}) = Some(Permitted) (marker overlap)",
2231 Some(ImplOverlapKind::Permitted { marker: true })
2233 if let Some(self_ty1) = self.issue33140_self_ty(def_id1) {
2234 if let Some(self_ty2) = self.issue33140_self_ty(def_id2) {
2235 if self_ty1 == self_ty2 {
2237 "impls_are_allowed_to_overlap({:?}, {:?}) - issue #33140 HACK",
2240 return Some(ImplOverlapKind::Issue33140);
2243 "impls_are_allowed_to_overlap({:?}, {:?}) - found {:?} != {:?}",
2244 def_id1, def_id2, self_ty1, self_ty2
2250 debug!("impls_are_allowed_to_overlap({:?}, {:?}) = None", def_id1, def_id2);
2255 /// Returns `ty::VariantDef` if `res` refers to a struct,
2256 /// or variant or their constructors, panics otherwise.
2257 pub fn expect_variant_res(self, res: Res) -> &'tcx VariantDef {
2259 Res::Def(DefKind::Variant, did) => {
2260 let enum_did = self.parent(did);
2261 self.adt_def(enum_did).variant_with_id(did)
2263 Res::Def(DefKind::Struct | DefKind::Union, did) => self.adt_def(did).non_enum_variant(),
2264 Res::Def(DefKind::Ctor(CtorOf::Variant, ..), variant_ctor_did) => {
2265 let variant_did = self.parent(variant_ctor_did);
2266 let enum_did = self.parent(variant_did);
2267 self.adt_def(enum_did).variant_with_ctor_id(variant_ctor_did)
2269 Res::Def(DefKind::Ctor(CtorOf::Struct, ..), ctor_did) => {
2270 let struct_did = self.parent(ctor_did);
2271 self.adt_def(struct_did).non_enum_variant()
2273 _ => bug!("expect_variant_res used with unexpected res {:?}", res),
2277 /// Returns the possibly-auto-generated MIR of a `(DefId, Subst)` pair.
2278 #[instrument(skip(self), level = "debug")]
2279 pub fn instance_mir(self, instance: ty::InstanceDef<'tcx>) -> &'tcx Body<'tcx> {
2281 ty::InstanceDef::Item(def) => {
2282 debug!("calling def_kind on def: {:?}", def);
2283 let def_kind = self.def_kind(def.did);
2284 debug!("returned from def_kind: {:?}", def_kind);
2287 | DefKind::Static(..)
2288 | DefKind::AssocConst
2290 | DefKind::AnonConst
2291 | DefKind::InlineConst => self.mir_for_ctfe_opt_const_arg(def),
2292 // If the caller wants `mir_for_ctfe` of a function they should not be using
2293 // `instance_mir`, so we'll assume const fn also wants the optimized version.
2295 assert_eq!(def.const_param_did, None);
2296 self.optimized_mir(def.did)
2300 ty::InstanceDef::VTableShim(..)
2301 | ty::InstanceDef::ReifyShim(..)
2302 | ty::InstanceDef::Intrinsic(..)
2303 | ty::InstanceDef::FnPtrShim(..)
2304 | ty::InstanceDef::Virtual(..)
2305 | ty::InstanceDef::ClosureOnceShim { .. }
2306 | ty::InstanceDef::DropGlue(..)
2307 | ty::InstanceDef::CloneShim(..) => self.mir_shims(instance),
2311 // FIXME(@lcnr): Remove this function.
2312 pub fn get_attrs_unchecked(self, did: DefId) -> &'tcx [ast::Attribute] {
2313 if let Some(did) = did.as_local() {
2314 self.hir().attrs(self.hir().local_def_id_to_hir_id(did))
2316 self.item_attrs(did)
2320 /// Gets all attributes with the given name.
2321 pub fn get_attrs(self, did: DefId, attr: Symbol) -> ty::Attributes<'tcx> {
2322 let filter_fn = move |a: &&ast::Attribute| a.has_name(attr);
2323 if let Some(did) = did.as_local() {
2324 self.hir().attrs(self.hir().local_def_id_to_hir_id(did)).iter().filter(filter_fn)
2325 } else if cfg!(debug_assertions) && rustc_feature::is_builtin_only_local(attr) {
2326 bug!("tried to access the `only_local` attribute `{}` from an extern crate", attr);
2328 self.item_attrs(did).iter().filter(filter_fn)
2332 pub fn get_attr(self, did: DefId, attr: Symbol) -> Option<&'tcx ast::Attribute> {
2333 if cfg!(debug_assertions) && !rustc_feature::is_valid_for_get_attr(attr) {
2334 bug!("get_attr: unexpected called with DefId `{:?}`, attr `{:?}`", did, attr);
2336 self.get_attrs(did, attr).next()
2340 /// Determines whether an item is annotated with an attribute.
2341 pub fn has_attr(self, did: DefId, attr: Symbol) -> bool {
2342 if cfg!(debug_assertions) && !did.is_local() && rustc_feature::is_builtin_only_local(attr) {
2343 bug!("tried to access the `only_local` attribute `{}` from an extern crate", attr);
2345 self.get_attrs(did, attr).next().is_some()
2349 /// Returns `true` if this is an `auto trait`.
2350 pub fn trait_is_auto(self, trait_def_id: DefId) -> bool {
2351 self.trait_def(trait_def_id).has_auto_impl
2354 pub fn trait_is_coinductive(self, trait_def_id: DefId) -> bool {
2355 self.trait_is_auto(trait_def_id) || self.lang_items().sized_trait() == Some(trait_def_id)
2358 /// Returns layout of a generator. Layout might be unavailable if the
2359 /// generator is tainted by errors.
2360 pub fn generator_layout(self, def_id: DefId) -> Option<&'tcx GeneratorLayout<'tcx>> {
2361 self.optimized_mir(def_id).generator_layout()
2364 /// Given the `DefId` of an impl, returns the `DefId` of the trait it implements.
2365 /// If it implements no trait, returns `None`.
2366 pub fn trait_id_of_impl(self, def_id: DefId) -> Option<DefId> {
2367 self.impl_trait_ref(def_id).map(|tr| tr.def_id)
2370 /// If the given `DefId` describes an item belonging to a trait,
2371 /// returns the `DefId` of the trait that the trait item belongs to;
2372 /// otherwise, returns `None`.
2373 pub fn trait_of_item(self, def_id: DefId) -> Option<DefId> {
2374 if let DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy = self.def_kind(def_id) {
2375 let parent = self.parent(def_id);
2376 if let DefKind::Trait | DefKind::TraitAlias = self.def_kind(parent) {
2377 return Some(parent);
2383 /// If the given `DefId` describes a method belonging to an impl, returns the
2384 /// `DefId` of the impl that the method belongs to; otherwise, returns `None`.
2385 pub fn impl_of_method(self, def_id: DefId) -> Option<DefId> {
2386 if let DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy = self.def_kind(def_id) {
2387 let parent = self.parent(def_id);
2388 if let DefKind::Impl = self.def_kind(parent) {
2389 return Some(parent);
2395 /// If the given `DefId` belongs to a trait that was automatically derived, returns `true`.
2396 pub fn is_builtin_derive(self, def_id: DefId) -> bool {
2397 self.has_attr(def_id, sym::automatically_derived)
2400 /// Looks up the span of `impl_did` if the impl is local; otherwise returns `Err`
2401 /// with the name of the crate containing the impl.
2402 pub fn span_of_impl(self, impl_def_id: DefId) -> Result<Span, Symbol> {
2403 if let Some(impl_def_id) = impl_def_id.as_local() {
2404 Ok(self.def_span(impl_def_id))
2406 Err(self.crate_name(impl_def_id.krate))
2410 /// Hygienically compares a use-site name (`use_name`) for a field or an associated item with
2411 /// its supposed definition name (`def_name`). The method also needs `DefId` of the supposed
2412 /// definition's parent/scope to perform comparison.
2413 pub fn hygienic_eq(self, use_name: Ident, def_name: Ident, def_parent_def_id: DefId) -> bool {
2414 // We could use `Ident::eq` here, but we deliberately don't. The name
2415 // comparison fails frequently, and we want to avoid the expensive
2416 // `normalize_to_macros_2_0()` calls required for the span comparison whenever possible.
2417 use_name.name == def_name.name
2421 .hygienic_eq(def_name.span.ctxt(), self.expn_that_defined(def_parent_def_id))
2424 pub fn adjust_ident(self, mut ident: Ident, scope: DefId) -> Ident {
2425 ident.span.normalize_to_macros_2_0_and_adjust(self.expn_that_defined(scope));
2429 pub fn adjust_ident_and_get_scope(
2434 ) -> (Ident, DefId) {
2437 .normalize_to_macros_2_0_and_adjust(self.expn_that_defined(scope))
2438 .and_then(|actual_expansion| actual_expansion.expn_data().parent_module)
2439 .unwrap_or_else(|| self.parent_module(block).to_def_id());
2443 /// Returns `true` if the debuginfo for `span` should be collapsed to the outermost expansion
2444 /// site. Only applies when `Span` is the result of macro expansion.
2446 /// - If the `collapse_debuginfo` feature is enabled then debuginfo is not collapsed by default
2447 /// and only when a macro definition is annotated with `#[collapse_debuginfo]`.
2448 /// - If `collapse_debuginfo` is not enabled, then debuginfo is collapsed by default.
2450 /// When `-Zdebug-macros` is provided then debuginfo will never be collapsed.
2451 pub fn should_collapse_debuginfo(self, span: Span) -> bool {
2452 !self.sess.opts.unstable_opts.debug_macros
2453 && if self.features().collapse_debuginfo {
2454 span.in_macro_expansion_with_collapse_debuginfo()
2456 // Inlined spans should not be collapsed as that leads to all of the
2457 // inlined code being attributed to the inline callsite.
2458 span.from_expansion() && !span.is_inlined()
2462 pub fn is_object_safe(self, key: DefId) -> bool {
2463 self.object_safety_violations(key).is_empty()
2467 pub fn is_const_fn_raw(self, def_id: DefId) -> bool {
2468 matches!(self.def_kind(def_id), DefKind::Fn | DefKind::AssocFn | DefKind::Ctor(..))
2469 && self.constness(def_id) == hir::Constness::Const
2473 pub fn is_const_default_method(self, def_id: DefId) -> bool {
2474 matches!(self.trait_of_item(def_id), Some(trait_id) if self.has_attr(trait_id, sym::const_trait))
2477 pub fn impl_trait_in_trait_parent(self, mut def_id: DefId) -> DefId {
2478 while let def_kind = self.def_kind(def_id) && def_kind != DefKind::AssocFn {
2479 debug_assert_eq!(def_kind, DefKind::ImplTraitPlaceholder);
2480 def_id = self.parent(def_id);
2486 /// Yields the parent function's `LocalDefId` if `def_id` is an `impl Trait` definition.
2487 pub fn is_impl_trait_defn(tcx: TyCtxt<'_>, def_id: DefId) -> Option<LocalDefId> {
2488 let def_id = def_id.as_local()?;
2489 if let Node::Item(item) = tcx.hir().get_by_def_id(def_id) {
2490 if let hir::ItemKind::OpaqueTy(ref opaque_ty) = item.kind {
2491 return match opaque_ty.origin {
2492 hir::OpaqueTyOrigin::FnReturn(parent) | hir::OpaqueTyOrigin::AsyncFn(parent) => {
2495 hir::OpaqueTyOrigin::TyAlias => None,
2502 pub fn int_ty(ity: ast::IntTy) -> IntTy {
2504 ast::IntTy::Isize => IntTy::Isize,
2505 ast::IntTy::I8 => IntTy::I8,
2506 ast::IntTy::I16 => IntTy::I16,
2507 ast::IntTy::I32 => IntTy::I32,
2508 ast::IntTy::I64 => IntTy::I64,
2509 ast::IntTy::I128 => IntTy::I128,
2513 pub fn uint_ty(uty: ast::UintTy) -> UintTy {
2515 ast::UintTy::Usize => UintTy::Usize,
2516 ast::UintTy::U8 => UintTy::U8,
2517 ast::UintTy::U16 => UintTy::U16,
2518 ast::UintTy::U32 => UintTy::U32,
2519 ast::UintTy::U64 => UintTy::U64,
2520 ast::UintTy::U128 => UintTy::U128,
2524 pub fn float_ty(fty: ast::FloatTy) -> FloatTy {
2526 ast::FloatTy::F32 => FloatTy::F32,
2527 ast::FloatTy::F64 => FloatTy::F64,
2531 pub fn ast_int_ty(ity: IntTy) -> ast::IntTy {
2533 IntTy::Isize => ast::IntTy::Isize,
2534 IntTy::I8 => ast::IntTy::I8,
2535 IntTy::I16 => ast::IntTy::I16,
2536 IntTy::I32 => ast::IntTy::I32,
2537 IntTy::I64 => ast::IntTy::I64,
2538 IntTy::I128 => ast::IntTy::I128,
2542 pub fn ast_uint_ty(uty: UintTy) -> ast::UintTy {
2544 UintTy::Usize => ast::UintTy::Usize,
2545 UintTy::U8 => ast::UintTy::U8,
2546 UintTy::U16 => ast::UintTy::U16,
2547 UintTy::U32 => ast::UintTy::U32,
2548 UintTy::U64 => ast::UintTy::U64,
2549 UintTy::U128 => ast::UintTy::U128,
2553 pub fn provide(providers: &mut ty::query::Providers) {
2554 closure::provide(providers);
2555 context::provide(providers);
2556 erase_regions::provide(providers);
2557 inhabitedness::provide(providers);
2558 util::provide(providers);
2559 print::provide(providers);
2560 super::util::bug::provide(providers);
2561 super::middle::provide(providers);
2562 *providers = ty::query::Providers {
2563 trait_impls_of: trait_def::trait_impls_of_provider,
2564 incoherent_impls: trait_def::incoherent_impls_provider,
2565 const_param_default: consts::const_param_default,
2566 vtable_allocation: vtable::vtable_allocation_provider,
2571 /// A map for the local crate mapping each type to a vector of its
2572 /// inherent impls. This is not meant to be used outside of coherence;
2573 /// rather, you should request the vector for a specific type via
2574 /// `tcx.inherent_impls(def_id)` so as to minimize your dependencies
2575 /// (constructing this map requires touching the entire crate).
2576 #[derive(Clone, Debug, Default, HashStable)]
2577 pub struct CrateInherentImpls {
2578 pub inherent_impls: LocalDefIdMap<Vec<DefId>>,
2579 pub incoherent_impls: FxHashMap<SimplifiedType, Vec<LocalDefId>>,
2582 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, HashStable)]
2583 pub struct SymbolName<'tcx> {
2584 /// `&str` gives a consistent ordering, which ensures reproducible builds.
2585 pub name: &'tcx str,
2588 impl<'tcx> SymbolName<'tcx> {
2589 pub fn new(tcx: TyCtxt<'tcx>, name: &str) -> SymbolName<'tcx> {
2591 name: unsafe { str::from_utf8_unchecked(tcx.arena.alloc_slice(name.as_bytes())) },
2596 impl<'tcx> fmt::Display for SymbolName<'tcx> {
2597 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2598 fmt::Display::fmt(&self.name, fmt)
2602 impl<'tcx> fmt::Debug for SymbolName<'tcx> {
2603 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2604 fmt::Display::fmt(&self.name, fmt)
2608 #[derive(Debug, Default, Copy, Clone)]
2609 pub struct FoundRelationships {
2610 /// This is true if we identified that this Ty (`?T`) is found in a `?T: Foo`
2611 /// obligation, where:
2613 /// * `Foo` is not `Sized`
2614 /// * `(): Foo` may be satisfied
2615 pub self_in_trait: bool,
2616 /// This is true if we identified that this Ty (`?T`) is found in a `<_ as
2617 /// _>::AssocType = ?T`
2621 /// The constituent parts of a type level constant of kind ADT or array.
2622 #[derive(Copy, Clone, Debug, HashStable)]
2623 pub struct DestructuredConst<'tcx> {
2624 pub variant: Option<VariantIdx>,
2625 pub fields: &'tcx [ty::Const<'tcx>],
2628 // Some types are used a lot. Make sure they don't unintentionally get bigger.
2629 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
2632 use rustc_data_structures::static_assert_size;
2633 // tidy-alphabetical-start
2634 static_assert_size!(PredicateKind<'_>, 32);
2635 static_assert_size!(WithCachedTypeInfo<TyKind<'_>>, 56);
2636 // tidy-alphabetical-end