1 //! Defines how the compiler represents types internally.
3 //! Two important entities in this module are:
5 //! - [`rustc_middle::ty::Ty`], used to represent the semantics of a type.
6 //! - [`rustc_middle::ty::TyCtxt`], the central data structure in the compiler.
8 //! For more information, see ["The `ty` module: representing types"] in the rustc-dev-guide.
10 //! ["The `ty` module: representing types"]: https://rustc-dev-guide.rust-lang.org/ty.html
12 pub use self::fold::{FallibleTypeFolder, TypeFoldable, TypeFolder, TypeSuperFoldable};
13 pub use self::visit::{TypeSuperVisitable, TypeVisitable, TypeVisitor};
14 pub use self::AssocItemContainer::*;
15 pub use self::BorrowKind::*;
16 pub use self::IntVarValue::*;
17 pub use self::Variance::*;
18 use crate::error::{OpaqueHiddenTypeMismatch, TypeMismatchReason};
19 use crate::metadata::ModChild;
20 use crate::middle::privacy::EffectiveVisibilities;
21 use crate::mir::{Body, GeneratorLayout};
22 use crate::traits::{self, Reveal};
24 use crate::ty::fast_reject::SimplifiedType;
25 use crate::ty::util::Discr;
29 use hir::OpaqueTyOrigin;
31 use rustc_ast::node_id::NodeMap;
32 use rustc_attr as attr;
33 use rustc_data_structures::fingerprint::Fingerprint;
34 use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap, FxIndexSet};
35 use rustc_data_structures::intern::{Interned, WithStableHash};
36 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
37 use rustc_data_structures::tagged_ptr::CopyTaggedPtr;
39 use rustc_hir::def::{CtorKind, CtorOf, DefKind, LifetimeRes, Res};
40 use rustc_hir::def_id::{CrateNum, DefId, LocalDefId, LocalDefIdMap};
41 use rustc_hir::definitions::Definitions;
43 use rustc_index::vec::IndexVec;
44 use rustc_macros::HashStable;
45 use rustc_query_system::ich::StableHashingContext;
46 use rustc_serialize::{Decodable, Encodable};
47 use rustc_session::cstore::CrateStoreDyn;
48 use rustc_span::hygiene::MacroKind;
49 use rustc_span::symbol::{kw, sym, Ident, Symbol};
50 use rustc_span::{ExpnId, Span};
51 use rustc_target::abi::{Align, Integer, IntegerType, VariantIdx};
52 pub use rustc_target::abi::{ReprFlags, ReprOptions};
57 use std::hash::{Hash, Hasher};
58 use std::marker::PhantomData;
60 use std::num::NonZeroUsize;
61 use std::ops::ControlFlow;
64 pub use crate::ty::diagnostics::*;
65 pub use rustc_type_ir::DynKind::*;
66 pub use rustc_type_ir::InferTy::*;
67 pub use rustc_type_ir::RegionKind::*;
68 pub use rustc_type_ir::TyKind::*;
69 pub use rustc_type_ir::*;
71 pub use self::binding::BindingMode;
72 pub use self::binding::BindingMode::*;
73 pub use self::closure::{
74 is_ancestor_or_same_capture, place_to_string_for_capture, BorrowKind, CaptureInfo,
75 CapturedPlace, ClosureKind, MinCaptureInformationMap, MinCaptureList,
76 RootVariableMinCaptureList, UpvarCapture, UpvarCaptureMap, UpvarId, UpvarListMap, UpvarPath,
79 pub use self::consts::{
80 Const, ConstInt, ConstKind, ConstS, Expr, InferConst, ScalarInt, UnevaluatedConst, ValTree,
82 pub use self::context::{
83 tls, CanonicalUserType, CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations,
84 CtxtInterners, DeducedParamAttrs, FreeRegionInfo, GeneratorDiagnosticData,
85 GeneratorInteriorTypeCause, GlobalCtxt, Lift, OnDiskCache, TyCtxt, TypeckResults, UserType,
86 UserTypeAnnotationIndex,
88 pub use self::instance::{Instance, InstanceDef, ShortInstance};
89 pub use self::list::List;
90 pub use self::parameterized::ParameterizedOverTcx;
91 pub use self::rvalue_scopes::RvalueScopes;
92 pub use self::sty::BoundRegionKind::*;
94 Article, Binder, BoundRegion, BoundRegionKind, BoundTy, BoundTyKind, BoundVar,
95 BoundVariableKind, CanonicalPolyFnSig, ClosureSubsts, ClosureSubstsParts, ConstVid,
96 EarlyBoundRegion, ExistentialPredicate, ExistentialProjection, ExistentialTraitRef, FnSig,
97 FreeRegion, GenSig, GeneratorSubsts, GeneratorSubstsParts, InlineConstSubsts,
98 InlineConstSubstsParts, ParamConst, ParamTy, PolyExistentialPredicate,
99 PolyExistentialProjection, PolyExistentialTraitRef, PolyFnSig, PolyGenSig, PolyTraitRef,
100 ProjectionTy, Region, RegionKind, RegionVid, TraitRef, TyKind, TypeAndMut, UpvarSubsts,
103 pub use self::trait_def::TraitDef;
106 pub mod abstract_const;
115 pub mod inhabitedness;
117 pub mod normalize_erasing_regions;
142 mod structural_impls;
147 pub type RegisteredTools = FxHashSet<Ident>;
149 pub struct ResolverOutputs {
150 pub definitions: Definitions,
151 pub global_ctxt: ResolverGlobalCtxt,
152 pub ast_lowering: ResolverAstLowering,
156 pub struct ResolverGlobalCtxt {
157 pub cstore: Box<CrateStoreDyn>,
158 pub visibilities: FxHashMap<LocalDefId, Visibility>,
159 /// This field is used to decide whether we should make `PRIVATE_IN_PUBLIC` a hard error.
160 pub has_pub_restricted: bool,
161 /// Item with a given `LocalDefId` was defined during macro expansion with ID `ExpnId`.
162 pub expn_that_defined: FxHashMap<LocalDefId, ExpnId>,
163 /// Reference span for definitions.
164 pub source_span: IndexVec<LocalDefId, Span>,
165 pub effective_visibilities: EffectiveVisibilities,
166 pub extern_crate_map: FxHashMap<LocalDefId, CrateNum>,
167 pub maybe_unused_trait_imports: FxIndexSet<LocalDefId>,
168 pub maybe_unused_extern_crates: Vec<(LocalDefId, Span)>,
169 pub reexport_map: FxHashMap<LocalDefId, Vec<ModChild>>,
170 pub glob_map: FxHashMap<LocalDefId, FxHashSet<Symbol>>,
171 /// Extern prelude entries. The value is `true` if the entry was introduced
172 /// via `extern crate` item and not `--extern` option or compiler built-in.
173 pub extern_prelude: FxHashMap<Symbol, bool>,
174 pub main_def: Option<MainDefinition>,
175 pub trait_impls: FxIndexMap<DefId, Vec<LocalDefId>>,
176 /// A list of proc macro LocalDefIds, written out in the order in which
177 /// they are declared in the static array generated by proc_macro_harness.
178 pub proc_macros: Vec<LocalDefId>,
179 /// Mapping from ident span to path span for paths that don't exist as written, but that
180 /// exist under `std`. For example, wrote `str::from_utf8` instead of `std::str::from_utf8`.
181 pub confused_type_with_std_module: FxHashMap<Span, Span>,
182 pub registered_tools: RegisteredTools,
185 /// Resolutions that should only be used for lowering.
186 /// This struct is meant to be consumed by lowering.
188 pub struct ResolverAstLowering {
189 pub legacy_const_generic_args: FxHashMap<DefId, Option<Vec<usize>>>,
191 /// Resolutions for nodes that have a single resolution.
192 pub partial_res_map: NodeMap<hir::def::PartialRes>,
193 /// Resolutions for import nodes, which have multiple resolutions in different namespaces.
194 pub import_res_map: NodeMap<hir::def::PerNS<Option<Res<ast::NodeId>>>>,
195 /// Resolutions for labels (node IDs of their corresponding blocks or loops).
196 pub label_res_map: NodeMap<ast::NodeId>,
197 /// Resolutions for lifetimes.
198 pub lifetimes_res_map: NodeMap<LifetimeRes>,
199 /// Lifetime parameters that lowering will have to introduce.
200 pub extra_lifetime_params_map: NodeMap<Vec<(Ident, ast::NodeId, LifetimeRes)>>,
202 pub next_node_id: ast::NodeId,
204 pub node_id_to_def_id: FxHashMap<ast::NodeId, LocalDefId>,
205 pub def_id_to_node_id: IndexVec<LocalDefId, ast::NodeId>,
207 pub trait_map: NodeMap<Vec<hir::TraitCandidate>>,
208 /// A small map keeping true kinds of built-in macros that appear to be fn-like on
209 /// the surface (`macro` items in libcore), but are actually attributes or derives.
210 pub builtin_macro_kinds: FxHashMap<LocalDefId, MacroKind>,
211 /// List functions and methods for which lifetime elision was successful.
212 pub lifetime_elision_allowed: FxHashSet<ast::NodeId>,
215 #[derive(Clone, Copy, Debug)]
216 pub struct MainDefinition {
217 pub res: Res<ast::NodeId>,
222 impl MainDefinition {
223 pub fn opt_fn_def_id(self) -> Option<DefId> {
224 if let Res::Def(DefKind::Fn, def_id) = self.res { Some(def_id) } else { None }
228 /// The "header" of an impl is everything outside the body: a Self type, a trait
229 /// ref (in the case of a trait impl), and a set of predicates (from the
230 /// bounds / where-clauses).
231 #[derive(Clone, Debug, TypeFoldable, TypeVisitable)]
232 pub struct ImplHeader<'tcx> {
233 pub impl_def_id: DefId,
234 pub self_ty: Ty<'tcx>,
235 pub trait_ref: Option<TraitRef<'tcx>>,
236 pub predicates: Vec<Predicate<'tcx>>,
239 #[derive(Copy, Clone, Debug, TypeFoldable, TypeVisitable)]
240 pub enum ImplSubject<'tcx> {
241 Trait(TraitRef<'tcx>),
245 #[derive(Copy, Clone, PartialEq, Eq, Hash, TyEncodable, TyDecodable, HashStable, Debug)]
246 #[derive(TypeFoldable, TypeVisitable)]
247 pub enum ImplPolarity {
248 /// `impl Trait for Type`
250 /// `impl !Trait for Type`
252 /// `#[rustc_reservation_impl] impl Trait for Type`
254 /// This is a "stability hack", not a real Rust feature.
255 /// See #64631 for details.
260 /// Flips polarity by turning `Positive` into `Negative` and `Negative` into `Positive`.
261 pub fn flip(&self) -> Option<ImplPolarity> {
263 ImplPolarity::Positive => Some(ImplPolarity::Negative),
264 ImplPolarity::Negative => Some(ImplPolarity::Positive),
265 ImplPolarity::Reservation => None,
270 impl fmt::Display for ImplPolarity {
271 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
273 Self::Positive => f.write_str("positive"),
274 Self::Negative => f.write_str("negative"),
275 Self::Reservation => f.write_str("reservation"),
280 #[derive(Clone, Debug, PartialEq, Eq, Copy, Hash, Encodable, Decodable, HashStable)]
281 pub enum Visibility<Id = LocalDefId> {
282 /// Visible everywhere (including in other crates).
284 /// Visible only in the given crate-local module.
288 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable, TyEncodable, TyDecodable)]
289 pub enum BoundConstness {
292 /// `T: ~const Trait`
294 /// Requires resolving to const only when we are in a const context.
298 impl BoundConstness {
299 /// Reduce `self` and `constness` to two possible combined states instead of four.
300 pub fn and(&mut self, constness: hir::Constness) -> hir::Constness {
301 match (constness, self) {
302 (hir::Constness::Const, BoundConstness::ConstIfConst) => hir::Constness::Const,
304 *this = BoundConstness::NotConst;
305 hir::Constness::NotConst
311 impl fmt::Display for BoundConstness {
312 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
314 Self::NotConst => f.write_str("normal"),
315 Self::ConstIfConst => f.write_str("`~const`"),
320 #[derive(Clone, Debug, PartialEq, Eq, Copy, Hash, TyEncodable, TyDecodable, HashStable)]
321 #[derive(TypeFoldable, TypeVisitable)]
322 pub struct ClosureSizeProfileData<'tcx> {
323 /// Tuple containing the types of closure captures before the feature `capture_disjoint_fields`
324 pub before_feature_tys: Ty<'tcx>,
325 /// Tuple containing the types of closure captures after the feature `capture_disjoint_fields`
326 pub after_feature_tys: Ty<'tcx>,
329 pub trait DefIdTree: Copy {
330 fn opt_parent(self, id: DefId) -> Option<DefId>;
334 fn parent(self, id: DefId) -> DefId {
335 match self.opt_parent(id) {
337 // not `unwrap_or_else` to avoid breaking caller tracking
338 None => bug!("{id:?} doesn't have a parent"),
344 fn opt_local_parent(self, id: LocalDefId) -> Option<LocalDefId> {
345 self.opt_parent(id.to_def_id()).map(DefId::expect_local)
350 fn local_parent(self, id: LocalDefId) -> LocalDefId {
351 self.parent(id.to_def_id()).expect_local()
354 fn is_descendant_of(self, mut descendant: DefId, ancestor: DefId) -> bool {
355 if descendant.krate != ancestor.krate {
359 while descendant != ancestor {
360 match self.opt_parent(descendant) {
361 Some(parent) => descendant = parent,
362 None => return false,
369 impl<'tcx> DefIdTree for TyCtxt<'tcx> {
371 fn opt_parent(self, id: DefId) -> Option<DefId> {
372 self.def_key(id).parent.map(|index| DefId { index, ..id })
376 impl<Id> Visibility<Id> {
377 pub fn is_public(self) -> bool {
378 matches!(self, Visibility::Public)
381 pub fn map_id<OutId>(self, f: impl FnOnce(Id) -> OutId) -> Visibility<OutId> {
383 Visibility::Public => Visibility::Public,
384 Visibility::Restricted(id) => Visibility::Restricted(f(id)),
389 impl<Id: Into<DefId>> Visibility<Id> {
390 pub fn to_def_id(self) -> Visibility<DefId> {
391 self.map_id(Into::into)
394 /// Returns `true` if an item with this visibility is accessible from the given module.
395 pub fn is_accessible_from(self, module: impl Into<DefId>, tree: impl DefIdTree) -> bool {
397 // Public items are visible everywhere.
398 Visibility::Public => true,
399 Visibility::Restricted(id) => tree.is_descendant_of(module.into(), id.into()),
403 /// Returns `true` if this visibility is at least as accessible as the given visibility
404 pub fn is_at_least(self, vis: Visibility<impl Into<DefId>>, tree: impl DefIdTree) -> bool {
406 Visibility::Public => self.is_public(),
407 Visibility::Restricted(id) => self.is_accessible_from(id, tree),
412 impl Visibility<DefId> {
413 pub fn expect_local(self) -> Visibility {
414 self.map_id(|id| id.expect_local())
417 /// Returns `true` if this item is visible anywhere in the local crate.
418 pub fn is_visible_locally(self) -> bool {
420 Visibility::Public => true,
421 Visibility::Restricted(def_id) => def_id.is_local(),
426 /// The crate variances map is computed during typeck and contains the
427 /// variance of every item in the local crate. You should not use it
428 /// directly, because to do so will make your pass dependent on the
429 /// HIR of every item in the local crate. Instead, use
430 /// `tcx.variances_of()` to get the variance for a *particular*
432 #[derive(HashStable, Debug)]
433 pub struct CrateVariancesMap<'tcx> {
434 /// For each item with generics, maps to a vector of the variance
435 /// of its generics. If an item has no generics, it will have no
437 pub variances: FxHashMap<DefId, &'tcx [ty::Variance]>,
440 // Contains information needed to resolve types and (in the future) look up
441 // the types of AST nodes.
442 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
443 pub struct CReaderCacheKey {
444 pub cnum: Option<CrateNum>,
448 /// Represents a type.
451 /// - This is a very "dumb" struct (with no derives and no `impls`).
452 /// - Values of this type are always interned and thus unique, and are stored
453 /// as an `Interned<TyS>`.
454 /// - `Ty` (which contains a reference to a `Interned<TyS>`) or `Interned<TyS>`
455 /// should be used everywhere instead of `TyS`. In particular, `Ty` has most
456 /// of the relevant methods.
457 #[derive(PartialEq, Eq, PartialOrd, Ord)]
458 #[allow(rustc::usage_of_ty_tykind)]
459 pub(crate) struct TyS<'tcx> {
460 /// This field shouldn't be used directly and may be removed in the future.
461 /// Use `Ty::kind()` instead.
464 /// This field provides fast access to information that is also contained
467 /// This field shouldn't be used directly and may be removed in the future.
468 /// Use `Ty::flags()` instead.
471 /// This field provides fast access to information that is also contained
474 /// This is a kind of confusing thing: it stores the smallest
477 /// (a) the binder itself captures nothing but
478 /// (b) all the late-bound things within the type are captured
479 /// by some sub-binder.
481 /// So, for a type without any late-bound things, like `u32`, this
482 /// will be *innermost*, because that is the innermost binder that
483 /// captures nothing. But for a type `&'D u32`, where `'D` is a
484 /// late-bound region with De Bruijn index `D`, this would be `D + 1`
485 /// -- the binder itself does not capture `D`, but `D` is captured
486 /// by an inner binder.
488 /// We call this concept an "exclusive" binder `D` because all
489 /// De Bruijn indices within the type are contained within `0..D`
491 outer_exclusive_binder: ty::DebruijnIndex,
494 /// Use this rather than `TyS`, whenever possible.
495 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, HashStable)]
496 #[rustc_diagnostic_item = "Ty"]
497 #[rustc_pass_by_value]
498 pub struct Ty<'tcx>(Interned<'tcx, WithStableHash<TyS<'tcx>>>);
500 impl<'tcx> TyCtxt<'tcx> {
501 /// A "bool" type used in rustc_mir_transform unit tests when we
502 /// have not spun up a TyCtxt.
503 pub const BOOL_TY_FOR_UNIT_TESTING: Ty<'tcx> = Ty(Interned::new_unchecked(&WithStableHash {
506 flags: TypeFlags::empty(),
507 outer_exclusive_binder: DebruijnIndex::from_usize(0),
509 stable_hash: Fingerprint::ZERO,
513 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for TyS<'tcx> {
515 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
519 // The other fields just provide fast access to information that is
520 // also contained in `kind`, so no need to hash them.
523 outer_exclusive_binder: _,
526 kind.hash_stable(hcx, hasher)
530 impl ty::EarlyBoundRegion {
531 /// Does this early bound region have a name? Early bound regions normally
532 /// always have names except when using anonymous lifetimes (`'_`).
533 pub fn has_name(&self) -> bool {
534 self.name != kw::UnderscoreLifetime && self.name != kw::Empty
538 /// Represents a predicate.
540 /// See comments on `TyS`, which apply here too (albeit for
541 /// `PredicateS`/`Predicate` rather than `TyS`/`Ty`).
543 pub(crate) struct PredicateS<'tcx> {
544 kind: Binder<'tcx, PredicateKind<'tcx>>,
546 /// See the comment for the corresponding field of [TyS].
547 outer_exclusive_binder: ty::DebruijnIndex,
550 /// Use this rather than `PredicateS`, whenever possible.
551 #[derive(Clone, Copy, PartialEq, Eq, Hash, HashStable)]
552 #[rustc_pass_by_value]
553 pub struct Predicate<'tcx>(Interned<'tcx, WithStableHash<PredicateS<'tcx>>>);
555 impl<'tcx> Predicate<'tcx> {
556 /// Gets the inner `Binder<'tcx, PredicateKind<'tcx>>`.
558 pub fn kind(self) -> Binder<'tcx, PredicateKind<'tcx>> {
563 pub fn flags(self) -> TypeFlags {
568 pub fn outer_exclusive_binder(self) -> DebruijnIndex {
569 self.0.outer_exclusive_binder
572 /// Flips the polarity of a Predicate.
574 /// Given `T: Trait` predicate it returns `T: !Trait` and given `T: !Trait` returns `T: Trait`.
575 pub fn flip_polarity(self, tcx: TyCtxt<'tcx>) -> Option<Predicate<'tcx>> {
578 .map_bound(|kind| match kind {
579 PredicateKind::Clause(Clause::Trait(TraitPredicate {
583 })) => Some(PredicateKind::Clause(Clause::Trait(TraitPredicate {
586 polarity: polarity.flip()?,
593 Some(tcx.mk_predicate(kind))
596 pub fn without_const(mut self, tcx: TyCtxt<'tcx>) -> Self {
597 if let PredicateKind::Clause(Clause::Trait(TraitPredicate { trait_ref, constness, polarity })) = self.kind().skip_binder()
598 && constness != BoundConstness::NotConst
600 self = tcx.mk_predicate(self.kind().rebind(PredicateKind::Clause(Clause::Trait(TraitPredicate {
602 constness: BoundConstness::NotConst,
609 /// Whether this projection can be soundly normalized.
611 /// Wf predicates must not be normalized, as normalization
612 /// can remove required bounds which would cause us to
613 /// unsoundly accept some programs. See #91068.
615 pub fn allow_normalization(self) -> bool {
616 match self.kind().skip_binder() {
617 PredicateKind::WellFormed(_) => false,
618 PredicateKind::Clause(Clause::Trait(_))
619 | PredicateKind::Clause(Clause::RegionOutlives(_))
620 | PredicateKind::Clause(Clause::TypeOutlives(_))
621 | PredicateKind::Clause(Clause::Projection(_))
622 | PredicateKind::ObjectSafe(_)
623 | PredicateKind::ClosureKind(_, _, _)
624 | PredicateKind::Subtype(_)
625 | PredicateKind::Coerce(_)
626 | PredicateKind::ConstEvaluatable(_)
627 | PredicateKind::ConstEquate(_, _)
628 | PredicateKind::Ambiguous
629 | PredicateKind::TypeWellFormedFromEnv(_) => true,
634 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for PredicateS<'tcx> {
635 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
639 // The other fields just provide fast access to information that is
640 // also contained in `kind`, so no need to hash them.
642 outer_exclusive_binder: _,
645 kind.hash_stable(hcx, hasher);
649 impl rustc_errors::IntoDiagnosticArg for Predicate<'_> {
650 fn into_diagnostic_arg(self) -> rustc_errors::DiagnosticArgValue<'static> {
651 rustc_errors::DiagnosticArgValue::Str(std::borrow::Cow::Owned(self.to_string()))
655 #[derive(Clone, Copy, PartialEq, Eq, Hash, TyEncodable, TyDecodable)]
656 #[derive(HashStable, TypeFoldable, TypeVisitable, Lift)]
657 /// A clause is something that can appear in where bounds or be inferred
658 /// by implied bounds.
659 pub enum Clause<'tcx> {
660 /// Corresponds to `where Foo: Bar<A, B, C>`. `Foo` here would be
661 /// the `Self` type of the trait reference and `A`, `B`, and `C`
662 /// would be the type parameters.
663 Trait(TraitPredicate<'tcx>),
666 RegionOutlives(RegionOutlivesPredicate<'tcx>),
669 TypeOutlives(TypeOutlivesPredicate<'tcx>),
671 /// `where <T as TraitRef>::Name == X`, approximately.
672 /// See the `ProjectionPredicate` struct for details.
673 Projection(ProjectionPredicate<'tcx>),
676 #[derive(Clone, Copy, PartialEq, Eq, Hash, TyEncodable, TyDecodable)]
677 #[derive(HashStable, TypeFoldable, TypeVisitable, Lift)]
678 pub enum PredicateKind<'tcx> {
680 Clause(Clause<'tcx>),
682 /// No syntax: `T` well-formed.
683 WellFormed(GenericArg<'tcx>),
685 /// Trait must be object-safe.
688 /// No direct syntax. May be thought of as `where T: FnFoo<...>`
689 /// for some substitutions `...` and `T` being a closure type.
690 /// Satisfied (or refuted) once we know the closure's kind.
691 ClosureKind(DefId, SubstsRef<'tcx>, ClosureKind),
695 /// This obligation is created most often when we have two
696 /// unresolved type variables and hence don't have enough
697 /// information to process the subtyping obligation yet.
698 Subtype(SubtypePredicate<'tcx>),
700 /// `T1` coerced to `T2`
702 /// Like a subtyping obligation, this is created most often
703 /// when we have two unresolved type variables and hence
704 /// don't have enough information to process the coercion
705 /// obligation yet. At the moment, we actually process coercions
706 /// very much like subtyping and don't handle the full coercion
708 Coerce(CoercePredicate<'tcx>),
710 /// Constant initializer must evaluate successfully.
711 ConstEvaluatable(ty::Const<'tcx>),
713 /// Constants must be equal. The first component is the const that is expected.
714 ConstEquate(Const<'tcx>, Const<'tcx>),
716 /// Represents a type found in the environment that we can use for implied bounds.
718 /// Only used for Chalk.
719 TypeWellFormedFromEnv(Ty<'tcx>),
721 /// A marker predicate that is always ambiguous.
722 /// Used for coherence to mark opaque types as possibly equal to each other but ambiguous.
726 /// The crate outlives map is computed during typeck and contains the
727 /// outlives of every item in the local crate. You should not use it
728 /// directly, because to do so will make your pass dependent on the
729 /// HIR of every item in the local crate. Instead, use
730 /// `tcx.inferred_outlives_of()` to get the outlives for a *particular*
732 #[derive(HashStable, Debug)]
733 pub struct CratePredicatesMap<'tcx> {
734 /// For each struct with outlive bounds, maps to a vector of the
735 /// predicate of its outlive bounds. If an item has no outlives
736 /// bounds, it will have no entry.
737 pub predicates: FxHashMap<DefId, &'tcx [(Clause<'tcx>, Span)]>,
740 impl<'tcx> Predicate<'tcx> {
741 /// Performs a substitution suitable for going from a
742 /// poly-trait-ref to supertraits that must hold if that
743 /// poly-trait-ref holds. This is slightly different from a normal
744 /// substitution in terms of what happens with bound regions. See
745 /// lengthy comment below for details.
746 pub fn subst_supertrait(
749 trait_ref: &ty::PolyTraitRef<'tcx>,
750 ) -> Predicate<'tcx> {
751 // The interaction between HRTB and supertraits is not entirely
752 // obvious. Let me walk you (and myself) through an example.
754 // Let's start with an easy case. Consider two traits:
756 // trait Foo<'a>: Bar<'a,'a> { }
757 // trait Bar<'b,'c> { }
759 // Now, if we have a trait reference `for<'x> T: Foo<'x>`, then
760 // we can deduce that `for<'x> T: Bar<'x,'x>`. Basically, if we
761 // knew that `Foo<'x>` (for any 'x) then we also know that
762 // `Bar<'x,'x>` (for any 'x). This more-or-less falls out from
763 // normal substitution.
765 // In terms of why this is sound, the idea is that whenever there
766 // is an impl of `T:Foo<'a>`, it must show that `T:Bar<'a,'a>`
767 // holds. So if there is an impl of `T:Foo<'a>` that applies to
768 // all `'a`, then we must know that `T:Bar<'a,'a>` holds for all
771 // Another example to be careful of is this:
773 // trait Foo1<'a>: for<'b> Bar1<'a,'b> { }
774 // trait Bar1<'b,'c> { }
776 // Here, if we have `for<'x> T: Foo1<'x>`, then what do we know?
777 // The answer is that we know `for<'x,'b> T: Bar1<'x,'b>`. The
778 // reason is similar to the previous example: any impl of
779 // `T:Foo1<'x>` must show that `for<'b> T: Bar1<'x, 'b>`. So
780 // basically we would want to collapse the bound lifetimes from
781 // the input (`trait_ref`) and the supertraits.
783 // To achieve this in practice is fairly straightforward. Let's
784 // consider the more complicated scenario:
786 // - We start out with `for<'x> T: Foo1<'x>`. In this case, `'x`
787 // has a De Bruijn index of 1. We want to produce `for<'x,'b> T: Bar1<'x,'b>`,
788 // where both `'x` and `'b` would have a DB index of 1.
789 // The substitution from the input trait-ref is therefore going to be
790 // `'a => 'x` (where `'x` has a DB index of 1).
791 // - The supertrait-ref is `for<'b> Bar1<'a,'b>`, where `'a` is an
792 // early-bound parameter and `'b' is a late-bound parameter with a
794 // - If we replace `'a` with `'x` from the input, it too will have
795 // a DB index of 1, and thus we'll have `for<'x,'b> Bar1<'x,'b>`
796 // just as we wanted.
798 // There is only one catch. If we just apply the substitution `'a
799 // => 'x` to `for<'b> Bar1<'a,'b>`, the substitution code will
800 // adjust the DB index because we substituting into a binder (it
801 // tries to be so smart...) resulting in `for<'x> for<'b>
802 // Bar1<'x,'b>` (we have no syntax for this, so use your
803 // imagination). Basically the 'x will have DB index of 2 and 'b
804 // will have DB index of 1. Not quite what we want. So we apply
805 // the substitution to the *contents* of the trait reference,
806 // rather than the trait reference itself (put another way, the
807 // substitution code expects equal binding levels in the values
808 // from the substitution and the value being substituted into, and
809 // this trick achieves that).
811 // Working through the second example:
812 // trait_ref: for<'x> T: Foo1<'^0.0>; substs: [T, '^0.0]
813 // predicate: for<'b> Self: Bar1<'a, '^0.0>; substs: [Self, 'a, '^0.0]
814 // We want to end up with:
815 // for<'x, 'b> T: Bar1<'^0.0, '^0.1>
817 // 1) We must shift all bound vars in predicate by the length
818 // of trait ref's bound vars. So, we would end up with predicate like
819 // Self: Bar1<'a, '^0.1>
820 // 2) We can then apply the trait substs to this, ending up with
821 // T: Bar1<'^0.0, '^0.1>
822 // 3) Finally, to create the final bound vars, we concatenate the bound
823 // vars of the trait ref with those of the predicate:
825 let bound_pred = self.kind();
826 let pred_bound_vars = bound_pred.bound_vars();
827 let trait_bound_vars = trait_ref.bound_vars();
828 // 1) Self: Bar1<'a, '^0.0> -> Self: Bar1<'a, '^0.1>
830 tcx.shift_bound_var_indices(trait_bound_vars.len(), bound_pred.skip_binder());
831 // 2) Self: Bar1<'a, '^0.1> -> T: Bar1<'^0.0, '^0.1>
832 let new = EarlyBinder(shifted_pred).subst(tcx, trait_ref.skip_binder().substs);
833 // 3) ['x] + ['b] -> ['x, 'b]
835 tcx.mk_bound_variable_kinds(trait_bound_vars.iter().chain(pred_bound_vars));
836 tcx.reuse_or_mk_predicate(self, ty::Binder::bind_with_vars(new, bound_vars))
840 #[derive(Clone, Copy, PartialEq, Eq, Hash, TyEncodable, TyDecodable)]
841 #[derive(HashStable, TypeFoldable, TypeVisitable, Lift)]
842 pub struct TraitPredicate<'tcx> {
843 pub trait_ref: TraitRef<'tcx>,
845 pub constness: BoundConstness,
847 /// If polarity is Positive: we are proving that the trait is implemented.
849 /// If polarity is Negative: we are proving that a negative impl of this trait
850 /// exists. (Note that coherence also checks whether negative impls of supertraits
851 /// exist via a series of predicates.)
853 /// If polarity is Reserved: that's a bug.
854 pub polarity: ImplPolarity,
857 pub type PolyTraitPredicate<'tcx> = ty::Binder<'tcx, TraitPredicate<'tcx>>;
859 impl<'tcx> TraitPredicate<'tcx> {
860 pub fn remap_constness(&mut self, param_env: &mut ParamEnv<'tcx>) {
861 *param_env = param_env.with_constness(self.constness.and(param_env.constness()))
864 /// Remap the constness of this predicate before emitting it for diagnostics.
865 pub fn remap_constness_diag(&mut self, param_env: ParamEnv<'tcx>) {
866 // this is different to `remap_constness` that callees want to print this predicate
867 // in case of selection errors. `T: ~const Drop` bounds cannot end up here when the
868 // param_env is not const because it is always satisfied in non-const contexts.
869 if let hir::Constness::NotConst = param_env.constness() {
870 self.constness = ty::BoundConstness::NotConst;
874 pub fn with_self_type(self, tcx: TyCtxt<'tcx>, self_ty: Ty<'tcx>) -> Self {
875 Self { trait_ref: self.trait_ref.with_self_type(tcx, self_ty), ..self }
878 pub fn def_id(self) -> DefId {
879 self.trait_ref.def_id
882 pub fn self_ty(self) -> Ty<'tcx> {
883 self.trait_ref.self_ty()
887 pub fn is_const_if_const(self) -> bool {
888 self.constness == BoundConstness::ConstIfConst
891 pub fn is_constness_satisfied_by(self, constness: hir::Constness) -> bool {
892 match (self.constness, constness) {
893 (BoundConstness::NotConst, _)
894 | (BoundConstness::ConstIfConst, hir::Constness::Const) => true,
895 (BoundConstness::ConstIfConst, hir::Constness::NotConst) => false,
899 pub fn without_const(mut self) -> Self {
900 self.constness = BoundConstness::NotConst;
905 impl<'tcx> PolyTraitPredicate<'tcx> {
906 pub fn def_id(self) -> DefId {
907 // Ok to skip binder since trait `DefId` does not care about regions.
908 self.skip_binder().def_id()
911 pub fn self_ty(self) -> ty::Binder<'tcx, Ty<'tcx>> {
912 self.map_bound(|trait_ref| trait_ref.self_ty())
915 /// Remap the constness of this predicate before emitting it for diagnostics.
916 pub fn remap_constness_diag(&mut self, param_env: ParamEnv<'tcx>) {
917 *self = self.map_bound(|mut p| {
918 p.remap_constness_diag(param_env);
924 pub fn is_const_if_const(self) -> bool {
925 self.skip_binder().is_const_if_const()
930 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, TyEncodable, TyDecodable)]
931 #[derive(HashStable, TypeFoldable, TypeVisitable, Lift)]
932 pub struct OutlivesPredicate<A, B>(pub A, pub B);
933 pub type RegionOutlivesPredicate<'tcx> = OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>;
934 pub type TypeOutlivesPredicate<'tcx> = OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>;
935 pub type PolyRegionOutlivesPredicate<'tcx> = ty::Binder<'tcx, RegionOutlivesPredicate<'tcx>>;
936 pub type PolyTypeOutlivesPredicate<'tcx> = ty::Binder<'tcx, TypeOutlivesPredicate<'tcx>>;
938 /// Encodes that `a` must be a subtype of `b`. The `a_is_expected` flag indicates
939 /// whether the `a` type is the type that we should label as "expected" when
940 /// presenting user diagnostics.
941 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, TyEncodable, TyDecodable)]
942 #[derive(HashStable, TypeFoldable, TypeVisitable, Lift)]
943 pub struct SubtypePredicate<'tcx> {
944 pub a_is_expected: bool,
948 pub type PolySubtypePredicate<'tcx> = ty::Binder<'tcx, SubtypePredicate<'tcx>>;
950 /// Encodes that we have to coerce *from* the `a` type to the `b` type.
951 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, TyEncodable, TyDecodable)]
952 #[derive(HashStable, TypeFoldable, TypeVisitable, Lift)]
953 pub struct CoercePredicate<'tcx> {
957 pub type PolyCoercePredicate<'tcx> = ty::Binder<'tcx, CoercePredicate<'tcx>>;
959 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
960 pub struct Term<'tcx> {
962 marker: PhantomData<(Ty<'tcx>, Const<'tcx>)>,
965 impl Debug for Term<'_> {
966 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
967 let data = if let Some(ty) = self.ty() {
968 format!("Term::Ty({:?})", ty)
969 } else if let Some(ct) = self.ct() {
970 format!("Term::Ct({:?})", ct)
978 impl<'tcx> From<Ty<'tcx>> for Term<'tcx> {
979 fn from(ty: Ty<'tcx>) -> Self {
980 TermKind::Ty(ty).pack()
984 impl<'tcx> From<Const<'tcx>> for Term<'tcx> {
985 fn from(c: Const<'tcx>) -> Self {
986 TermKind::Const(c).pack()
990 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for Term<'tcx> {
991 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
992 self.unpack().hash_stable(hcx, hasher);
996 impl<'tcx> TypeFoldable<'tcx> for Term<'tcx> {
997 fn try_fold_with<F: FallibleTypeFolder<'tcx>>(self, folder: &mut F) -> Result<Self, F::Error> {
998 Ok(self.unpack().try_fold_with(folder)?.pack())
1002 impl<'tcx> TypeVisitable<'tcx> for Term<'tcx> {
1003 fn visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> ControlFlow<V::BreakTy> {
1004 self.unpack().visit_with(visitor)
1008 impl<'tcx, E: TyEncoder<I = TyCtxt<'tcx>>> Encodable<E> for Term<'tcx> {
1009 fn encode(&self, e: &mut E) {
1010 self.unpack().encode(e)
1014 impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> Decodable<D> for Term<'tcx> {
1015 fn decode(d: &mut D) -> Self {
1016 let res: TermKind<'tcx> = Decodable::decode(d);
1021 impl<'tcx> Term<'tcx> {
1023 pub fn unpack(self) -> TermKind<'tcx> {
1024 let ptr = self.ptr.get();
1025 // SAFETY: use of `Interned::new_unchecked` here is ok because these
1026 // pointers were originally created from `Interned` types in `pack()`,
1027 // and this is just going in the other direction.
1029 match ptr & TAG_MASK {
1030 TYPE_TAG => TermKind::Ty(Ty(Interned::new_unchecked(
1031 &*((ptr & !TAG_MASK) as *const WithStableHash<ty::TyS<'tcx>>),
1033 CONST_TAG => TermKind::Const(ty::Const(Interned::new_unchecked(
1034 &*((ptr & !TAG_MASK) as *const ty::ConstS<'tcx>),
1036 _ => core::intrinsics::unreachable(),
1041 pub fn ty(&self) -> Option<Ty<'tcx>> {
1042 if let TermKind::Ty(ty) = self.unpack() { Some(ty) } else { None }
1045 pub fn ct(&self) -> Option<Const<'tcx>> {
1046 if let TermKind::Const(c) = self.unpack() { Some(c) } else { None }
1049 pub fn into_arg(self) -> GenericArg<'tcx> {
1050 match self.unpack() {
1051 TermKind::Ty(ty) => ty.into(),
1052 TermKind::Const(c) => c.into(),
1057 const TAG_MASK: usize = 0b11;
1058 const TYPE_TAG: usize = 0b00;
1059 const CONST_TAG: usize = 0b01;
1061 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, TyEncodable, TyDecodable)]
1062 #[derive(HashStable, TypeFoldable, TypeVisitable)]
1063 pub enum TermKind<'tcx> {
1068 impl<'tcx> TermKind<'tcx> {
1070 fn pack(self) -> Term<'tcx> {
1071 let (tag, ptr) = match self {
1072 TermKind::Ty(ty) => {
1073 // Ensure we can use the tag bits.
1074 assert_eq!(mem::align_of_val(&*ty.0.0) & TAG_MASK, 0);
1075 (TYPE_TAG, ty.0.0 as *const WithStableHash<ty::TyS<'tcx>> as usize)
1077 TermKind::Const(ct) => {
1078 // Ensure we can use the tag bits.
1079 assert_eq!(mem::align_of_val(&*ct.0.0) & TAG_MASK, 0);
1080 (CONST_TAG, ct.0.0 as *const ty::ConstS<'tcx> as usize)
1084 Term { ptr: unsafe { NonZeroUsize::new_unchecked(ptr | tag) }, marker: PhantomData }
1088 /// This kind of predicate has no *direct* correspondent in the
1089 /// syntax, but it roughly corresponds to the syntactic forms:
1091 /// 1. `T: TraitRef<..., Item = Type>`
1092 /// 2. `<T as TraitRef<...>>::Item == Type` (NYI)
1094 /// In particular, form #1 is "desugared" to the combination of a
1095 /// normal trait predicate (`T: TraitRef<...>`) and one of these
1096 /// predicates. Form #2 is a broader form in that it also permits
1097 /// equality between arbitrary types. Processing an instance of
1098 /// Form #2 eventually yields one of these `ProjectionPredicate`
1099 /// instances to normalize the LHS.
1100 #[derive(Copy, Clone, PartialEq, Eq, Hash, TyEncodable, TyDecodable)]
1101 #[derive(HashStable, TypeFoldable, TypeVisitable, Lift)]
1102 pub struct ProjectionPredicate<'tcx> {
1103 pub projection_ty: ProjectionTy<'tcx>,
1104 pub term: Term<'tcx>,
1107 pub type PolyProjectionPredicate<'tcx> = Binder<'tcx, ProjectionPredicate<'tcx>>;
1109 impl<'tcx> PolyProjectionPredicate<'tcx> {
1110 /// Returns the `DefId` of the trait of the associated item being projected.
1112 pub fn trait_def_id(&self, tcx: TyCtxt<'tcx>) -> DefId {
1113 self.skip_binder().projection_ty.trait_def_id(tcx)
1116 /// Get the [PolyTraitRef] required for this projection to be well formed.
1117 /// Note that for generic associated types the predicates of the associated
1118 /// type also need to be checked.
1120 pub fn required_poly_trait_ref(&self, tcx: TyCtxt<'tcx>) -> PolyTraitRef<'tcx> {
1121 // Note: unlike with `TraitRef::to_poly_trait_ref()`,
1122 // `self.0.trait_ref` is permitted to have escaping regions.
1123 // This is because here `self` has a `Binder` and so does our
1124 // return value, so we are preserving the number of binding
1126 self.map_bound(|predicate| predicate.projection_ty.trait_ref(tcx))
1129 pub fn term(&self) -> Binder<'tcx, Term<'tcx>> {
1130 self.map_bound(|predicate| predicate.term)
1133 /// The `DefId` of the `TraitItem` for the associated type.
1135 /// Note that this is not the `DefId` of the `TraitRef` containing this
1136 /// associated type, which is in `tcx.associated_item(projection_def_id()).container`.
1137 pub fn projection_def_id(&self) -> DefId {
1138 // Ok to skip binder since trait `DefId` does not care about regions.
1139 self.skip_binder().projection_ty.item_def_id
1143 pub trait ToPolyTraitRef<'tcx> {
1144 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx>;
1147 impl<'tcx> ToPolyTraitRef<'tcx> for PolyTraitPredicate<'tcx> {
1148 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
1149 self.map_bound_ref(|trait_pred| trait_pred.trait_ref)
1153 pub trait ToPredicate<'tcx, Predicate> {
1154 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate;
1157 impl<'tcx, T> ToPredicate<'tcx, T> for T {
1158 fn to_predicate(self, _tcx: TyCtxt<'tcx>) -> T {
1163 impl<'tcx> ToPredicate<'tcx, Predicate<'tcx>> for Binder<'tcx, PredicateKind<'tcx>> {
1165 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1166 tcx.mk_predicate(self)
1170 impl<'tcx> ToPredicate<'tcx, Predicate<'tcx>> for Clause<'tcx> {
1172 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1173 tcx.mk_predicate(ty::Binder::dummy(ty::PredicateKind::Clause(self)))
1177 impl<'tcx> ToPredicate<'tcx, Predicate<'tcx>> for Binder<'tcx, TraitRef<'tcx>> {
1179 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1180 let pred: PolyTraitPredicate<'tcx> = self.to_predicate(tcx);
1181 pred.to_predicate(tcx)
1185 impl<'tcx> ToPredicate<'tcx, PolyTraitPredicate<'tcx>> for Binder<'tcx, TraitRef<'tcx>> {
1187 fn to_predicate(self, _: TyCtxt<'tcx>) -> PolyTraitPredicate<'tcx> {
1188 self.map_bound(|trait_ref| TraitPredicate {
1190 constness: ty::BoundConstness::NotConst,
1191 polarity: ty::ImplPolarity::Positive,
1196 impl<'tcx> ToPredicate<'tcx, Predicate<'tcx>> for PolyTraitPredicate<'tcx> {
1197 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1198 self.map_bound(|p| PredicateKind::Clause(Clause::Trait(p))).to_predicate(tcx)
1202 impl<'tcx> ToPredicate<'tcx, Predicate<'tcx>> for PolyRegionOutlivesPredicate<'tcx> {
1203 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1204 self.map_bound(|p| PredicateKind::Clause(Clause::RegionOutlives(p))).to_predicate(tcx)
1208 impl<'tcx> ToPredicate<'tcx, Predicate<'tcx>> for PolyTypeOutlivesPredicate<'tcx> {
1209 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1210 self.map_bound(|p| PredicateKind::Clause(Clause::TypeOutlives(p))).to_predicate(tcx)
1214 impl<'tcx> ToPredicate<'tcx, Predicate<'tcx>> for PolyProjectionPredicate<'tcx> {
1215 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1216 self.map_bound(|p| PredicateKind::Clause(Clause::Projection(p))).to_predicate(tcx)
1220 impl<'tcx> Predicate<'tcx> {
1221 pub fn to_opt_poly_trait_pred(self) -> Option<PolyTraitPredicate<'tcx>> {
1222 let predicate = self.kind();
1223 match predicate.skip_binder() {
1224 PredicateKind::Clause(Clause::Trait(t)) => Some(predicate.rebind(t)),
1225 PredicateKind::Clause(Clause::Projection(..))
1226 | PredicateKind::Subtype(..)
1227 | PredicateKind::Coerce(..)
1228 | PredicateKind::Clause(Clause::RegionOutlives(..))
1229 | PredicateKind::WellFormed(..)
1230 | PredicateKind::ObjectSafe(..)
1231 | PredicateKind::ClosureKind(..)
1232 | PredicateKind::Clause(Clause::TypeOutlives(..))
1233 | PredicateKind::ConstEvaluatable(..)
1234 | PredicateKind::ConstEquate(..)
1235 | PredicateKind::Ambiguous
1236 | PredicateKind::TypeWellFormedFromEnv(..) => None,
1240 pub fn to_opt_poly_projection_pred(self) -> Option<PolyProjectionPredicate<'tcx>> {
1241 let predicate = self.kind();
1242 match predicate.skip_binder() {
1243 PredicateKind::Clause(Clause::Projection(t)) => Some(predicate.rebind(t)),
1244 PredicateKind::Clause(Clause::Trait(..))
1245 | PredicateKind::Subtype(..)
1246 | PredicateKind::Coerce(..)
1247 | PredicateKind::Clause(Clause::RegionOutlives(..))
1248 | PredicateKind::WellFormed(..)
1249 | PredicateKind::ObjectSafe(..)
1250 | PredicateKind::ClosureKind(..)
1251 | PredicateKind::Clause(Clause::TypeOutlives(..))
1252 | PredicateKind::ConstEvaluatable(..)
1253 | PredicateKind::ConstEquate(..)
1254 | PredicateKind::Ambiguous
1255 | PredicateKind::TypeWellFormedFromEnv(..) => None,
1259 pub fn to_opt_type_outlives(self) -> Option<PolyTypeOutlivesPredicate<'tcx>> {
1260 let predicate = self.kind();
1261 match predicate.skip_binder() {
1262 PredicateKind::Clause(Clause::TypeOutlives(data)) => Some(predicate.rebind(data)),
1263 PredicateKind::Clause(Clause::Trait(..))
1264 | PredicateKind::Clause(Clause::Projection(..))
1265 | PredicateKind::Subtype(..)
1266 | PredicateKind::Coerce(..)
1267 | PredicateKind::Clause(Clause::RegionOutlives(..))
1268 | PredicateKind::WellFormed(..)
1269 | PredicateKind::ObjectSafe(..)
1270 | PredicateKind::ClosureKind(..)
1271 | PredicateKind::ConstEvaluatable(..)
1272 | PredicateKind::ConstEquate(..)
1273 | PredicateKind::Ambiguous
1274 | PredicateKind::TypeWellFormedFromEnv(..) => None,
1279 /// Represents the bounds declared on a particular set of type
1280 /// parameters. Should eventually be generalized into a flag list of
1281 /// where-clauses. You can obtain an `InstantiatedPredicates` list from a
1282 /// `GenericPredicates` by using the `instantiate` method. Note that this method
1283 /// reflects an important semantic invariant of `InstantiatedPredicates`: while
1284 /// the `GenericPredicates` are expressed in terms of the bound type
1285 /// parameters of the impl/trait/whatever, an `InstantiatedPredicates` instance
1286 /// represented a set of bounds for some particular instantiation,
1287 /// meaning that the generic parameters have been substituted with
1291 /// ```ignore (illustrative)
1292 /// struct Foo<T, U: Bar<T>> { ... }
1294 /// Here, the `GenericPredicates` for `Foo` would contain a list of bounds like
1295 /// `[[], [U:Bar<T>]]`. Now if there were some particular reference
1296 /// like `Foo<isize,usize>`, then the `InstantiatedPredicates` would be `[[],
1297 /// [usize:Bar<isize>]]`.
1298 #[derive(Clone, Debug, TypeFoldable, TypeVisitable)]
1299 pub struct InstantiatedPredicates<'tcx> {
1300 pub predicates: Vec<Predicate<'tcx>>,
1301 pub spans: Vec<Span>,
1304 impl<'tcx> InstantiatedPredicates<'tcx> {
1305 pub fn empty() -> InstantiatedPredicates<'tcx> {
1306 InstantiatedPredicates { predicates: vec![], spans: vec![] }
1309 pub fn is_empty(&self) -> bool {
1310 self.predicates.is_empty()
1314 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable, TyEncodable, TyDecodable, Lift)]
1315 #[derive(TypeFoldable, TypeVisitable)]
1316 pub struct OpaqueTypeKey<'tcx> {
1317 pub def_id: LocalDefId,
1318 pub substs: SubstsRef<'tcx>,
1321 #[derive(Copy, Clone, Debug, TypeFoldable, TypeVisitable, HashStable, TyEncodable, TyDecodable)]
1322 pub struct OpaqueHiddenType<'tcx> {
1323 /// The span of this particular definition of the opaque type. So
1326 /// ```ignore (incomplete snippet)
1327 /// type Foo = impl Baz;
1328 /// fn bar() -> Foo {
1329 /// // ^^^ This is the span we are looking for!
1333 /// In cases where the fn returns `(impl Trait, impl Trait)` or
1334 /// other such combinations, the result is currently
1335 /// over-approximated, but better than nothing.
1338 /// The type variable that represents the value of the opaque type
1339 /// that we require. In other words, after we compile this function,
1340 /// we will be created a constraint like:
1341 /// ```ignore (pseudo-rust)
1344 /// where `?C` is the value of this type variable. =) It may
1345 /// naturally refer to the type and lifetime parameters in scope
1346 /// in this function, though ultimately it should only reference
1347 /// those that are arguments to `Foo` in the constraint above. (In
1348 /// other words, `?C` should not include `'b`, even though it's a
1349 /// lifetime parameter on `foo`.)
1353 impl<'tcx> OpaqueHiddenType<'tcx> {
1354 pub fn report_mismatch(&self, other: &Self, tcx: TyCtxt<'tcx>) {
1355 // Found different concrete types for the opaque type.
1356 let sub_diag = if self.span == other.span {
1357 TypeMismatchReason::ConflictType { span: self.span }
1359 TypeMismatchReason::PreviousUse { span: self.span }
1361 tcx.sess.emit_err(OpaqueHiddenTypeMismatch {
1364 other_span: other.span,
1369 #[instrument(level = "debug", skip(tcx), ret)]
1370 pub fn remap_generic_params_to_declaration_params(
1372 opaque_type_key: OpaqueTypeKey<'tcx>,
1374 // typeck errors have subpar spans for opaque types, so delay error reporting until borrowck.
1375 ignore_errors: bool,
1376 origin: OpaqueTyOrigin,
1378 let OpaqueTypeKey { def_id, substs } = opaque_type_key;
1380 // Use substs to build up a reverse map from regions to their
1381 // identity mappings. This is necessary because of `impl
1382 // Trait` lifetimes are computed by replacing existing
1383 // lifetimes with 'static and remapping only those used in the
1384 // `impl Trait` return type, resulting in the parameters
1386 let id_substs = InternalSubsts::identity_for_item(tcx, def_id.to_def_id());
1389 // This zip may have several times the same lifetime in `substs` paired with a different
1390 // lifetime from `id_substs`. Simply `collect`ing the iterator is the correct behaviour:
1391 // it will pick the last one, which is the one we introduced in the impl-trait desugaring.
1392 let map = substs.iter().zip(id_substs);
1394 let map: FxHashMap<GenericArg<'tcx>, GenericArg<'tcx>> = match origin {
1395 // HACK: The HIR lowering for async fn does not generate
1396 // any `+ Captures<'x>` bounds for the `impl Future<...>`, so all async fns with lifetimes
1397 // would now fail to compile. We should probably just make hir lowering fill this in properly.
1398 OpaqueTyOrigin::AsyncFn(_) => map.collect(),
1399 OpaqueTyOrigin::FnReturn(_) | OpaqueTyOrigin::TyAlias => {
1400 // Opaque types may only use regions that are bound. So for
1402 // type Foo<'a, 'b, 'c> = impl Trait<'a> + 'b;
1404 // we may not use `'c` in the hidden type.
1405 let variances = tcx.variances_of(def_id);
1408 map.filter(|(_, v)| {
1409 let ty::GenericArgKind::Lifetime(lt) = v.unpack() else { return true };
1410 let ty::ReEarlyBound(ebr) = lt.kind() else { bug!() };
1411 variances[ebr.index as usize] == ty::Variance::Invariant
1416 debug!("map = {:#?}", map);
1418 // Convert the type from the function into a type valid outside
1419 // the function, by replacing invalid regions with 'static,
1420 // after producing an error for each of them.
1421 self.fold_with(&mut opaque_types::ReverseMapper::new(tcx, map, self.span, ignore_errors))
1425 /// The "placeholder index" fully defines a placeholder region, type, or const. Placeholders are
1426 /// identified by both a universe, as well as a name residing within that universe. Distinct bound
1427 /// regions/types/consts within the same universe simply have an unknown relationship to one
1429 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
1430 #[derive(HashStable, TyEncodable, TyDecodable)]
1431 pub struct Placeholder<T> {
1432 pub universe: UniverseIndex,
1436 pub type PlaceholderRegion = Placeholder<BoundRegionKind>;
1438 pub type PlaceholderType = Placeholder<BoundVar>;
1440 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable)]
1441 #[derive(TyEncodable, TyDecodable, PartialOrd, Ord)]
1442 pub struct BoundConst<'tcx> {
1447 pub type PlaceholderConst<'tcx> = Placeholder<BoundVar>;
1449 /// A `DefId` which, in case it is a const argument, is potentially bundled with
1450 /// the `DefId` of the generic parameter it instantiates.
1452 /// This is used to avoid calls to `type_of` for const arguments during typeck
1453 /// which cause cycle errors.
1458 /// fn foo<const N: usize>(&self) -> [u8; N] { [0; N] }
1459 /// // ^ const parameter
1463 /// fn foo<const M: u8>(&self) -> usize { 42 }
1464 /// // ^ const parameter
1469 /// let _b = a.foo::<{ 3 + 7 }>();
1470 /// // ^^^^^^^^^ const argument
1474 /// Let's look at the call `a.foo::<{ 3 + 7 }>()` here. We do not know
1475 /// which `foo` is used until we know the type of `a`.
1477 /// We only know the type of `a` once we are inside of `typeck(main)`.
1478 /// We also end up normalizing the type of `_b` during `typeck(main)` which
1479 /// requires us to evaluate the const argument.
1481 /// To evaluate that const argument we need to know its type,
1482 /// which we would get using `type_of(const_arg)`. This requires us to
1483 /// resolve `foo` as it can be either `usize` or `u8` in this example.
1484 /// However, resolving `foo` once again requires `typeck(main)` to get the type of `a`,
1485 /// which results in a cycle.
1487 /// In short we must not call `type_of(const_arg)` during `typeck(main)`.
1489 /// When first creating the `ty::Const` of the const argument inside of `typeck` we have
1490 /// already resolved `foo` so we know which const parameter this argument instantiates.
1491 /// This means that we also know the expected result of `type_of(const_arg)` even if we
1492 /// aren't allowed to call that query: it is equal to `type_of(const_param)` which is
1493 /// trivial to compute.
1495 /// If we now want to use that constant in a place which potentially needs its type
1496 /// we also pass the type of its `const_param`. This is the point of `WithOptConstParam`,
1497 /// except that instead of a `Ty` we bundle the `DefId` of the const parameter.
1498 /// Meaning that we need to use `type_of(const_param_did)` if `const_param_did` is `Some`
1499 /// to get the type of `did`.
1500 #[derive(Copy, Clone, Debug, TypeFoldable, TypeVisitable, Lift, TyEncodable, TyDecodable)]
1501 #[derive(PartialEq, Eq, PartialOrd, Ord)]
1502 #[derive(Hash, HashStable)]
1503 pub struct WithOptConstParam<T> {
1505 /// The `DefId` of the corresponding generic parameter in case `did` is
1506 /// a const argument.
1508 /// Note that even if `did` is a const argument, this may still be `None`.
1509 /// All queries taking `WithOptConstParam` start by calling `tcx.opt_const_param_of(def.did)`
1510 /// to potentially update `param_did` in the case it is `None`.
1511 pub const_param_did: Option<DefId>,
1514 impl<T> WithOptConstParam<T> {
1515 /// Creates a new `WithOptConstParam` setting `const_param_did` to `None`.
1517 pub fn unknown(did: T) -> WithOptConstParam<T> {
1518 WithOptConstParam { did, const_param_did: None }
1522 impl WithOptConstParam<LocalDefId> {
1523 /// Returns `Some((did, param_did))` if `def_id` is a const argument,
1524 /// `None` otherwise.
1526 pub fn try_lookup(did: LocalDefId, tcx: TyCtxt<'_>) -> Option<(LocalDefId, DefId)> {
1527 tcx.opt_const_param_of(did).map(|param_did| (did, param_did))
1530 /// In case `self` is unknown but `self.did` is a const argument, this returns
1531 /// a `WithOptConstParam` with the correct `const_param_did`.
1533 pub fn try_upgrade(self, tcx: TyCtxt<'_>) -> Option<WithOptConstParam<LocalDefId>> {
1534 if self.const_param_did.is_none() {
1535 if let const_param_did @ Some(_) = tcx.opt_const_param_of(self.did) {
1536 return Some(WithOptConstParam { did: self.did, const_param_did });
1543 pub fn to_global(self) -> WithOptConstParam<DefId> {
1544 WithOptConstParam { did: self.did.to_def_id(), const_param_did: self.const_param_did }
1547 pub fn def_id_for_type_of(self) -> DefId {
1548 if let Some(did) = self.const_param_did { did } else { self.did.to_def_id() }
1552 impl WithOptConstParam<DefId> {
1553 pub fn as_local(self) -> Option<WithOptConstParam<LocalDefId>> {
1556 .map(|did| WithOptConstParam { did, const_param_did: self.const_param_did })
1559 pub fn as_const_arg(self) -> Option<(LocalDefId, DefId)> {
1560 if let Some(param_did) = self.const_param_did {
1561 if let Some(did) = self.did.as_local() {
1562 return Some((did, param_did));
1569 pub fn is_local(self) -> bool {
1573 pub fn def_id_for_type_of(self) -> DefId {
1574 self.const_param_did.unwrap_or(self.did)
1578 /// When type checking, we use the `ParamEnv` to track
1579 /// details about the set of where-clauses that are in scope at this
1580 /// particular point.
1581 #[derive(Copy, Clone, Hash, PartialEq, Eq)]
1582 pub struct ParamEnv<'tcx> {
1583 /// This packs both caller bounds and the reveal enum into one pointer.
1585 /// Caller bounds are `Obligation`s that the caller must satisfy. This is
1586 /// basically the set of bounds on the in-scope type parameters, translated
1587 /// into `Obligation`s, and elaborated and normalized.
1589 /// Use the `caller_bounds()` method to access.
1591 /// Typically, this is `Reveal::UserFacing`, but during codegen we
1592 /// want `Reveal::All`.
1594 /// Note: This is packed, use the reveal() method to access it.
1595 packed: CopyTaggedPtr<&'tcx List<Predicate<'tcx>>, ParamTag, true>,
1598 #[derive(Copy, Clone)]
1600 reveal: traits::Reveal,
1601 constness: hir::Constness,
1604 unsafe impl rustc_data_structures::tagged_ptr::Tag for ParamTag {
1605 const BITS: usize = 2;
1607 fn into_usize(self) -> usize {
1609 Self { reveal: traits::Reveal::UserFacing, constness: hir::Constness::NotConst } => 0,
1610 Self { reveal: traits::Reveal::All, constness: hir::Constness::NotConst } => 1,
1611 Self { reveal: traits::Reveal::UserFacing, constness: hir::Constness::Const } => 2,
1612 Self { reveal: traits::Reveal::All, constness: hir::Constness::Const } => 3,
1616 unsafe fn from_usize(ptr: usize) -> Self {
1618 0 => Self { reveal: traits::Reveal::UserFacing, constness: hir::Constness::NotConst },
1619 1 => Self { reveal: traits::Reveal::All, constness: hir::Constness::NotConst },
1620 2 => Self { reveal: traits::Reveal::UserFacing, constness: hir::Constness::Const },
1621 3 => Self { reveal: traits::Reveal::All, constness: hir::Constness::Const },
1622 _ => std::hint::unreachable_unchecked(),
1627 impl<'tcx> fmt::Debug for ParamEnv<'tcx> {
1628 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1629 f.debug_struct("ParamEnv")
1630 .field("caller_bounds", &self.caller_bounds())
1631 .field("reveal", &self.reveal())
1632 .field("constness", &self.constness())
1637 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for ParamEnv<'tcx> {
1638 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
1639 self.caller_bounds().hash_stable(hcx, hasher);
1640 self.reveal().hash_stable(hcx, hasher);
1641 self.constness().hash_stable(hcx, hasher);
1645 impl<'tcx> TypeFoldable<'tcx> for ParamEnv<'tcx> {
1646 fn try_fold_with<F: ty::fold::FallibleTypeFolder<'tcx>>(
1649 ) -> Result<Self, F::Error> {
1651 self.caller_bounds().try_fold_with(folder)?,
1652 self.reveal().try_fold_with(folder)?,
1658 impl<'tcx> TypeVisitable<'tcx> for ParamEnv<'tcx> {
1659 fn visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> ControlFlow<V::BreakTy> {
1660 self.caller_bounds().visit_with(visitor)?;
1661 self.reveal().visit_with(visitor)
1665 impl<'tcx> ParamEnv<'tcx> {
1666 /// Construct a trait environment suitable for contexts where
1667 /// there are no where-clauses in scope. Hidden types (like `impl
1668 /// Trait`) are left hidden, so this is suitable for ordinary
1671 pub fn empty() -> Self {
1672 Self::new(List::empty(), Reveal::UserFacing, hir::Constness::NotConst)
1676 pub fn caller_bounds(self) -> &'tcx List<Predicate<'tcx>> {
1677 self.packed.pointer()
1681 pub fn reveal(self) -> traits::Reveal {
1682 self.packed.tag().reveal
1686 pub fn constness(self) -> hir::Constness {
1687 self.packed.tag().constness
1691 pub fn is_const(self) -> bool {
1692 self.packed.tag().constness == hir::Constness::Const
1695 /// Construct a trait environment with no where-clauses in scope
1696 /// where the values of all `impl Trait` and other hidden types
1697 /// are revealed. This is suitable for monomorphized, post-typeck
1698 /// environments like codegen or doing optimizations.
1700 /// N.B., if you want to have predicates in scope, use `ParamEnv::new`,
1701 /// or invoke `param_env.with_reveal_all()`.
1703 pub fn reveal_all() -> Self {
1704 Self::new(List::empty(), Reveal::All, hir::Constness::NotConst)
1707 /// Construct a trait environment with the given set of predicates.
1710 caller_bounds: &'tcx List<Predicate<'tcx>>,
1712 constness: hir::Constness,
1714 ty::ParamEnv { packed: CopyTaggedPtr::new(caller_bounds, ParamTag { reveal, constness }) }
1717 pub fn with_user_facing(mut self) -> Self {
1718 self.packed.set_tag(ParamTag { reveal: Reveal::UserFacing, ..self.packed.tag() });
1723 pub fn with_constness(mut self, constness: hir::Constness) -> Self {
1724 self.packed.set_tag(ParamTag { constness, ..self.packed.tag() });
1729 pub fn with_const(mut self) -> Self {
1730 self.packed.set_tag(ParamTag { constness: hir::Constness::Const, ..self.packed.tag() });
1735 pub fn without_const(mut self) -> Self {
1736 self.packed.set_tag(ParamTag { constness: hir::Constness::NotConst, ..self.packed.tag() });
1741 pub fn remap_constness_with(&mut self, mut constness: ty::BoundConstness) {
1742 *self = self.with_constness(constness.and(self.constness()))
1745 /// Returns a new parameter environment with the same clauses, but
1746 /// which "reveals" the true results of projections in all cases
1747 /// (even for associated types that are specializable). This is
1748 /// the desired behavior during codegen and certain other special
1749 /// contexts; normally though we want to use `Reveal::UserFacing`,
1750 /// which is the default.
1751 /// All opaque types in the caller_bounds of the `ParamEnv`
1752 /// will be normalized to their underlying types.
1753 /// See PR #65989 and issue #65918 for more details
1754 pub fn with_reveal_all_normalized(self, tcx: TyCtxt<'tcx>) -> Self {
1755 if self.packed.tag().reveal == traits::Reveal::All {
1760 tcx.reveal_opaque_types_in_bounds(self.caller_bounds()),
1766 /// Returns this same environment but with no caller bounds.
1768 pub fn without_caller_bounds(self) -> Self {
1769 Self::new(List::empty(), self.reveal(), self.constness())
1772 /// Creates a suitable environment in which to perform trait
1773 /// queries on the given value. When type-checking, this is simply
1774 /// the pair of the environment plus value. But when reveal is set to
1775 /// All, then if `value` does not reference any type parameters, we will
1776 /// pair it with the empty environment. This improves caching and is generally
1779 /// N.B., we preserve the environment when type-checking because it
1780 /// is possible for the user to have wacky where-clauses like
1781 /// `where Box<u32>: Copy`, which are clearly never
1782 /// satisfiable. We generally want to behave as if they were true,
1783 /// although the surrounding function is never reachable.
1784 pub fn and<T: TypeVisitable<'tcx>>(self, value: T) -> ParamEnvAnd<'tcx, T> {
1785 match self.reveal() {
1786 Reveal::UserFacing => ParamEnvAnd { param_env: self, value },
1789 if value.is_global() {
1790 ParamEnvAnd { param_env: self.without_caller_bounds(), value }
1792 ParamEnvAnd { param_env: self, value }
1799 // FIXME(ecstaticmorse): Audit all occurrences of `without_const().to_predicate(tcx)` to ensure that
1800 // the constness of trait bounds is being propagated correctly.
1801 impl<'tcx> PolyTraitRef<'tcx> {
1803 pub fn with_constness(self, constness: BoundConstness) -> PolyTraitPredicate<'tcx> {
1804 self.map_bound(|trait_ref| ty::TraitPredicate {
1807 polarity: ty::ImplPolarity::Positive,
1812 pub fn without_const(self) -> PolyTraitPredicate<'tcx> {
1813 self.with_constness(BoundConstness::NotConst)
1817 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TypeFoldable, TypeVisitable)]
1818 #[derive(HashStable, Lift)]
1819 pub struct ParamEnvAnd<'tcx, T> {
1820 pub param_env: ParamEnv<'tcx>,
1824 impl<'tcx, T> ParamEnvAnd<'tcx, T> {
1825 pub fn into_parts(self) -> (ParamEnv<'tcx>, T) {
1826 (self.param_env, self.value)
1830 pub fn without_const(mut self) -> Self {
1831 self.param_env = self.param_env.without_const();
1836 #[derive(Copy, Clone, Debug, HashStable, Encodable, Decodable)]
1837 pub struct Destructor {
1838 /// The `DefId` of the destructor method
1840 /// The constness of the destructor method
1841 pub constness: hir::Constness,
1845 #[derive(HashStable, TyEncodable, TyDecodable)]
1846 pub struct VariantFlags: u32 {
1847 const NO_VARIANT_FLAGS = 0;
1848 /// Indicates whether the field list of this variant is `#[non_exhaustive]`.
1849 const IS_FIELD_LIST_NON_EXHAUSTIVE = 1 << 0;
1850 /// Indicates whether this variant was obtained as part of recovering from
1851 /// a syntactic error. May be incomplete or bogus.
1852 const IS_RECOVERED = 1 << 1;
1856 /// Definition of a variant -- a struct's fields or an enum variant.
1857 #[derive(Debug, HashStable, TyEncodable, TyDecodable)]
1858 pub struct VariantDef {
1859 /// `DefId` that identifies the variant itself.
1860 /// If this variant belongs to a struct or union, then this is a copy of its `DefId`.
1862 /// `DefId` that identifies the variant's constructor.
1863 /// If this variant is a struct variant, then this is `None`.
1864 pub ctor: Option<(CtorKind, DefId)>,
1865 /// Variant or struct name.
1867 /// Discriminant of this variant.
1868 pub discr: VariantDiscr,
1869 /// Fields of this variant.
1870 pub fields: Vec<FieldDef>,
1871 /// Flags of the variant (e.g. is field list non-exhaustive)?
1872 flags: VariantFlags,
1876 /// Creates a new `VariantDef`.
1878 /// `variant_did` is the `DefId` that identifies the enum variant (if this `VariantDef`
1879 /// represents an enum variant).
1881 /// `ctor_did` is the `DefId` that identifies the constructor of unit or
1882 /// tuple-variants/structs. If this is a `struct`-variant then this should be `None`.
1884 /// `parent_did` is the `DefId` of the `AdtDef` representing the enum or struct that
1885 /// owns this variant. It is used for checking if a struct has `#[non_exhaustive]` w/out having
1886 /// to go through the redirect of checking the ctor's attributes - but compiling a small crate
1887 /// requires loading the `AdtDef`s for all the structs in the universe (e.g., coherence for any
1888 /// built-in trait), and we do not want to load attributes twice.
1890 /// If someone speeds up attribute loading to not be a performance concern, they can
1891 /// remove this hack and use the constructor `DefId` everywhere.
1894 variant_did: Option<DefId>,
1895 ctor: Option<(CtorKind, DefId)>,
1896 discr: VariantDiscr,
1897 fields: Vec<FieldDef>,
1901 is_field_list_non_exhaustive: bool,
1904 "VariantDef::new(name = {:?}, variant_did = {:?}, ctor = {:?}, discr = {:?},
1905 fields = {:?}, adt_kind = {:?}, parent_did = {:?})",
1906 name, variant_did, ctor, discr, fields, adt_kind, parent_did,
1909 let mut flags = VariantFlags::NO_VARIANT_FLAGS;
1910 if is_field_list_non_exhaustive {
1911 flags |= VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE;
1915 flags |= VariantFlags::IS_RECOVERED;
1918 VariantDef { def_id: variant_did.unwrap_or(parent_did), ctor, name, discr, fields, flags }
1921 /// Is this field list non-exhaustive?
1923 pub fn is_field_list_non_exhaustive(&self) -> bool {
1924 self.flags.intersects(VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE)
1927 /// Was this variant obtained as part of recovering from a syntactic error?
1929 pub fn is_recovered(&self) -> bool {
1930 self.flags.intersects(VariantFlags::IS_RECOVERED)
1933 /// Computes the `Ident` of this variant by looking up the `Span`
1934 pub fn ident(&self, tcx: TyCtxt<'_>) -> Ident {
1935 Ident::new(self.name, tcx.def_ident_span(self.def_id).unwrap())
1939 pub fn ctor_kind(&self) -> Option<CtorKind> {
1940 self.ctor.map(|(kind, _)| kind)
1944 pub fn ctor_def_id(&self) -> Option<DefId> {
1945 self.ctor.map(|(_, def_id)| def_id)
1949 impl PartialEq for VariantDef {
1951 fn eq(&self, other: &Self) -> bool {
1952 // There should be only one `VariantDef` for each `def_id`, therefore
1953 // it is fine to implement `PartialEq` only based on `def_id`.
1955 // Below, we exhaustively destructure `self` and `other` so that if the
1956 // definition of `VariantDef` changes, a compile-error will be produced,
1957 // reminding us to revisit this assumption.
1959 let Self { def_id: lhs_def_id, ctor: _, name: _, discr: _, fields: _, flags: _ } = &self;
1960 let Self { def_id: rhs_def_id, ctor: _, name: _, discr: _, fields: _, flags: _ } = other;
1961 lhs_def_id == rhs_def_id
1965 impl Eq for VariantDef {}
1967 impl Hash for VariantDef {
1969 fn hash<H: Hasher>(&self, s: &mut H) {
1970 // There should be only one `VariantDef` for each `def_id`, therefore
1971 // it is fine to implement `Hash` only based on `def_id`.
1973 // Below, we exhaustively destructure `self` so that if the definition
1974 // of `VariantDef` changes, a compile-error will be produced, reminding
1975 // us to revisit this assumption.
1977 let Self { def_id, ctor: _, name: _, discr: _, fields: _, flags: _ } = &self;
1982 #[derive(Copy, Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
1983 pub enum VariantDiscr {
1984 /// Explicit value for this variant, i.e., `X = 123`.
1985 /// The `DefId` corresponds to the embedded constant.
1988 /// The previous variant's discriminant plus one.
1989 /// For efficiency reasons, the distance from the
1990 /// last `Explicit` discriminant is being stored,
1991 /// or `0` for the first variant, if it has none.
1995 #[derive(Debug, HashStable, TyEncodable, TyDecodable)]
1996 pub struct FieldDef {
1999 pub vis: Visibility<DefId>,
2002 impl PartialEq for FieldDef {
2004 fn eq(&self, other: &Self) -> bool {
2005 // There should be only one `FieldDef` for each `did`, therefore it is
2006 // fine to implement `PartialEq` only based on `did`.
2008 // Below, we exhaustively destructure `self` so that if the definition
2009 // of `FieldDef` changes, a compile-error will be produced, reminding
2010 // us to revisit this assumption.
2012 let Self { did: lhs_did, name: _, vis: _ } = &self;
2014 let Self { did: rhs_did, name: _, vis: _ } = other;
2020 impl Eq for FieldDef {}
2022 impl Hash for FieldDef {
2024 fn hash<H: Hasher>(&self, s: &mut H) {
2025 // There should be only one `FieldDef` for each `did`, therefore it is
2026 // fine to implement `Hash` only based on `did`.
2028 // Below, we exhaustively destructure `self` so that if the definition
2029 // of `FieldDef` changes, a compile-error will be produced, reminding
2030 // us to revisit this assumption.
2032 let Self { did, name: _, vis: _ } = &self;
2038 impl<'tcx> FieldDef {
2039 /// Returns the type of this field. The resulting type is not normalized. The `subst` is
2040 /// typically obtained via the second field of [`TyKind::Adt`].
2041 pub fn ty(&self, tcx: TyCtxt<'tcx>, subst: SubstsRef<'tcx>) -> Ty<'tcx> {
2042 tcx.bound_type_of(self.did).subst(tcx, subst)
2045 /// Computes the `Ident` of this variant by looking up the `Span`
2046 pub fn ident(&self, tcx: TyCtxt<'_>) -> Ident {
2047 Ident::new(self.name, tcx.def_ident_span(self.did).unwrap())
2051 pub type Attributes<'tcx> = impl Iterator<Item = &'tcx ast::Attribute>;
2052 #[derive(Debug, PartialEq, Eq)]
2053 pub enum ImplOverlapKind {
2054 /// These impls are always allowed to overlap.
2056 /// Whether or not the impl is permitted due to the trait being a `#[marker]` trait
2059 /// These impls are allowed to overlap, but that raises
2060 /// an issue #33140 future-compatibility warning.
2062 /// Some background: in Rust 1.0, the trait-object types `Send + Sync` (today's
2063 /// `dyn Send + Sync`) and `Sync + Send` (now `dyn Sync + Send`) were different.
2065 /// The widely-used version 0.1.0 of the crate `traitobject` had accidentally relied
2066 /// that difference, making what reduces to the following set of impls:
2068 /// ```compile_fail,(E0119)
2070 /// impl Trait for dyn Send + Sync {}
2071 /// impl Trait for dyn Sync + Send {}
2074 /// Obviously, once we made these types be identical, that code causes a coherence
2075 /// error and a fairly big headache for us. However, luckily for us, the trait
2076 /// `Trait` used in this case is basically a marker trait, and therefore having
2077 /// overlapping impls for it is sound.
2079 /// To handle this, we basically regard the trait as a marker trait, with an additional
2080 /// future-compatibility warning. To avoid accidentally "stabilizing" this feature,
2081 /// it has the following restrictions:
2083 /// 1. The trait must indeed be a marker-like trait (i.e., no items), and must be
2085 /// 2. The trait-ref of both impls must be equal.
2086 /// 3. The trait-ref of both impls must be a trait object type consisting only of
2088 /// 4. Neither of the impls can have any where-clauses.
2090 /// Once `traitobject` 0.1.0 is no longer an active concern, this hack can be removed.
2094 impl<'tcx> TyCtxt<'tcx> {
2095 pub fn typeck_body(self, body: hir::BodyId) -> &'tcx TypeckResults<'tcx> {
2096 self.typeck(self.hir().body_owner_def_id(body))
2099 pub fn provided_trait_methods(self, id: DefId) -> impl 'tcx + Iterator<Item = &'tcx AssocItem> {
2100 self.associated_items(id)
2101 .in_definition_order()
2102 .filter(move |item| item.kind == AssocKind::Fn && item.defaultness(self).has_value())
2105 pub fn repr_options_of_def(self, did: DefId) -> ReprOptions {
2106 let mut flags = ReprFlags::empty();
2107 let mut size = None;
2108 let mut max_align: Option<Align> = None;
2109 let mut min_pack: Option<Align> = None;
2111 // Generate a deterministically-derived seed from the item's path hash
2112 // to allow for cross-crate compilation to actually work
2113 let mut field_shuffle_seed = self.def_path_hash(did).0.to_smaller_hash();
2115 // If the user defined a custom seed for layout randomization, xor the item's
2116 // path hash with the user defined seed, this will allowing determinism while
2117 // still allowing users to further randomize layout generation for e.g. fuzzing
2118 if let Some(user_seed) = self.sess.opts.unstable_opts.layout_seed {
2119 field_shuffle_seed ^= user_seed;
2122 for attr in self.get_attrs(did, sym::repr) {
2123 for r in attr::parse_repr_attr(&self.sess, attr) {
2124 flags.insert(match r {
2125 attr::ReprC => ReprFlags::IS_C,
2126 attr::ReprPacked(pack) => {
2127 let pack = Align::from_bytes(pack as u64).unwrap();
2128 min_pack = Some(if let Some(min_pack) = min_pack {
2135 attr::ReprTransparent => ReprFlags::IS_TRANSPARENT,
2136 attr::ReprSimd => ReprFlags::IS_SIMD,
2137 attr::ReprInt(i) => {
2138 size = Some(match i {
2139 attr::IntType::SignedInt(x) => match x {
2140 ast::IntTy::Isize => IntegerType::Pointer(true),
2141 ast::IntTy::I8 => IntegerType::Fixed(Integer::I8, true),
2142 ast::IntTy::I16 => IntegerType::Fixed(Integer::I16, true),
2143 ast::IntTy::I32 => IntegerType::Fixed(Integer::I32, true),
2144 ast::IntTy::I64 => IntegerType::Fixed(Integer::I64, true),
2145 ast::IntTy::I128 => IntegerType::Fixed(Integer::I128, true),
2147 attr::IntType::UnsignedInt(x) => match x {
2148 ast::UintTy::Usize => IntegerType::Pointer(false),
2149 ast::UintTy::U8 => IntegerType::Fixed(Integer::I8, false),
2150 ast::UintTy::U16 => IntegerType::Fixed(Integer::I16, false),
2151 ast::UintTy::U32 => IntegerType::Fixed(Integer::I32, false),
2152 ast::UintTy::U64 => IntegerType::Fixed(Integer::I64, false),
2153 ast::UintTy::U128 => IntegerType::Fixed(Integer::I128, false),
2158 attr::ReprAlign(align) => {
2159 max_align = max_align.max(Some(Align::from_bytes(align as u64).unwrap()));
2166 // If `-Z randomize-layout` was enabled for the type definition then we can
2167 // consider performing layout randomization
2168 if self.sess.opts.unstable_opts.randomize_layout {
2169 flags.insert(ReprFlags::RANDOMIZE_LAYOUT);
2172 // This is here instead of layout because the choice must make it into metadata.
2173 if !self.consider_optimizing(|| format!("Reorder fields of {:?}", self.def_path_str(did))) {
2174 flags.insert(ReprFlags::IS_LINEAR);
2177 ReprOptions { int: size, align: max_align, pack: min_pack, flags, field_shuffle_seed }
2180 /// Look up the name of a definition across crates. This does not look at HIR.
2181 pub fn opt_item_name(self, def_id: DefId) -> Option<Symbol> {
2182 if let Some(cnum) = def_id.as_crate_root() {
2183 Some(self.crate_name(cnum))
2185 let def_key = self.def_key(def_id);
2186 match def_key.disambiguated_data.data {
2187 // The name of a constructor is that of its parent.
2188 rustc_hir::definitions::DefPathData::Ctor => self
2189 .opt_item_name(DefId { krate: def_id.krate, index: def_key.parent.unwrap() }),
2190 // The name of opaque types only exists in HIR.
2191 rustc_hir::definitions::DefPathData::ImplTrait
2192 if let Some(def_id) = def_id.as_local() =>
2193 self.hir().opt_name(self.hir().local_def_id_to_hir_id(def_id)),
2194 _ => def_key.get_opt_name(),
2199 /// Look up the name of a definition across crates. This does not look at HIR.
2201 /// This method will ICE if the corresponding item does not have a name. In these cases, use
2202 /// [`opt_item_name`] instead.
2204 /// [`opt_item_name`]: Self::opt_item_name
2205 pub fn item_name(self, id: DefId) -> Symbol {
2206 self.opt_item_name(id).unwrap_or_else(|| {
2207 bug!("item_name: no name for {:?}", self.def_path(id));
2211 /// Look up the name and span of a definition.
2213 /// See [`item_name`][Self::item_name] for more information.
2214 pub fn opt_item_ident(self, def_id: DefId) -> Option<Ident> {
2215 let def = self.opt_item_name(def_id)?;
2218 .and_then(|id| self.def_ident_span(id))
2219 .unwrap_or(rustc_span::DUMMY_SP);
2220 Some(Ident::new(def, span))
2223 pub fn opt_associated_item(self, def_id: DefId) -> Option<&'tcx AssocItem> {
2224 if let DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy = self.def_kind(def_id) {
2225 Some(self.associated_item(def_id))
2231 pub fn field_index(self, hir_id: hir::HirId, typeck_results: &TypeckResults<'_>) -> usize {
2232 typeck_results.field_indices().get(hir_id).cloned().expect("no index for a field")
2235 pub fn find_field_index(self, ident: Ident, variant: &VariantDef) -> Option<usize> {
2239 .position(|field| self.hygienic_eq(ident, field.ident(self), variant.def_id))
2242 /// Returns `true` if the impls are the same polarity and the trait either
2243 /// has no items or is annotated `#[marker]` and prevents item overrides.
2244 pub fn impls_are_allowed_to_overlap(
2248 ) -> Option<ImplOverlapKind> {
2249 // If either trait impl references an error, they're allowed to overlap,
2250 // as one of them essentially doesn't exist.
2251 if self.impl_trait_ref(def_id1).map_or(false, |tr| tr.references_error())
2252 || self.impl_trait_ref(def_id2).map_or(false, |tr| tr.references_error())
2254 return Some(ImplOverlapKind::Permitted { marker: false });
2257 match (self.impl_polarity(def_id1), self.impl_polarity(def_id2)) {
2258 (ImplPolarity::Reservation, _) | (_, ImplPolarity::Reservation) => {
2259 // `#[rustc_reservation_impl]` impls don't overlap with anything
2261 "impls_are_allowed_to_overlap({:?}, {:?}) = Some(Permitted) (reservations)",
2264 return Some(ImplOverlapKind::Permitted { marker: false });
2266 (ImplPolarity::Positive, ImplPolarity::Negative)
2267 | (ImplPolarity::Negative, ImplPolarity::Positive) => {
2268 // `impl AutoTrait for Type` + `impl !AutoTrait for Type`
2270 "impls_are_allowed_to_overlap({:?}, {:?}) - None (differing polarities)",
2275 (ImplPolarity::Positive, ImplPolarity::Positive)
2276 | (ImplPolarity::Negative, ImplPolarity::Negative) => {}
2279 let is_marker_overlap = {
2280 let is_marker_impl = |def_id: DefId| -> bool {
2281 let trait_ref = self.impl_trait_ref(def_id);
2282 trait_ref.map_or(false, |tr| self.trait_def(tr.def_id).is_marker)
2284 is_marker_impl(def_id1) && is_marker_impl(def_id2)
2287 if is_marker_overlap {
2289 "impls_are_allowed_to_overlap({:?}, {:?}) = Some(Permitted) (marker overlap)",
2292 Some(ImplOverlapKind::Permitted { marker: true })
2294 if let Some(self_ty1) = self.issue33140_self_ty(def_id1) {
2295 if let Some(self_ty2) = self.issue33140_self_ty(def_id2) {
2296 if self_ty1 == self_ty2 {
2298 "impls_are_allowed_to_overlap({:?}, {:?}) - issue #33140 HACK",
2301 return Some(ImplOverlapKind::Issue33140);
2304 "impls_are_allowed_to_overlap({:?}, {:?}) - found {:?} != {:?}",
2305 def_id1, def_id2, self_ty1, self_ty2
2311 debug!("impls_are_allowed_to_overlap({:?}, {:?}) = None", def_id1, def_id2);
2316 /// Returns `ty::VariantDef` if `res` refers to a struct,
2317 /// or variant or their constructors, panics otherwise.
2318 pub fn expect_variant_res(self, res: Res) -> &'tcx VariantDef {
2320 Res::Def(DefKind::Variant, did) => {
2321 let enum_did = self.parent(did);
2322 self.adt_def(enum_did).variant_with_id(did)
2324 Res::Def(DefKind::Struct | DefKind::Union, did) => self.adt_def(did).non_enum_variant(),
2325 Res::Def(DefKind::Ctor(CtorOf::Variant, ..), variant_ctor_did) => {
2326 let variant_did = self.parent(variant_ctor_did);
2327 let enum_did = self.parent(variant_did);
2328 self.adt_def(enum_did).variant_with_ctor_id(variant_ctor_did)
2330 Res::Def(DefKind::Ctor(CtorOf::Struct, ..), ctor_did) => {
2331 let struct_did = self.parent(ctor_did);
2332 self.adt_def(struct_did).non_enum_variant()
2334 _ => bug!("expect_variant_res used with unexpected res {:?}", res),
2338 /// Returns the possibly-auto-generated MIR of a `(DefId, Subst)` pair.
2339 #[instrument(skip(self), level = "debug")]
2340 pub fn instance_mir(self, instance: ty::InstanceDef<'tcx>) -> &'tcx Body<'tcx> {
2342 ty::InstanceDef::Item(def) => {
2343 debug!("calling def_kind on def: {:?}", def);
2344 let def_kind = self.def_kind(def.did);
2345 debug!("returned from def_kind: {:?}", def_kind);
2348 | DefKind::Static(..)
2349 | DefKind::AssocConst
2351 | DefKind::AnonConst
2352 | DefKind::InlineConst => self.mir_for_ctfe_opt_const_arg(def),
2353 // If the caller wants `mir_for_ctfe` of a function they should not be using
2354 // `instance_mir`, so we'll assume const fn also wants the optimized version.
2356 assert_eq!(def.const_param_did, None);
2357 self.optimized_mir(def.did)
2361 ty::InstanceDef::VTableShim(..)
2362 | ty::InstanceDef::ReifyShim(..)
2363 | ty::InstanceDef::Intrinsic(..)
2364 | ty::InstanceDef::FnPtrShim(..)
2365 | ty::InstanceDef::Virtual(..)
2366 | ty::InstanceDef::ClosureOnceShim { .. }
2367 | ty::InstanceDef::DropGlue(..)
2368 | ty::InstanceDef::CloneShim(..) => self.mir_shims(instance),
2372 // FIXME(@lcnr): Remove this function.
2373 pub fn get_attrs_unchecked(self, did: DefId) -> &'tcx [ast::Attribute] {
2374 if let Some(did) = did.as_local() {
2375 self.hir().attrs(self.hir().local_def_id_to_hir_id(did))
2377 self.item_attrs(did)
2381 /// Gets all attributes with the given name.
2382 pub fn get_attrs(self, did: DefId, attr: Symbol) -> ty::Attributes<'tcx> {
2383 let filter_fn = move |a: &&ast::Attribute| a.has_name(attr);
2384 if let Some(did) = did.as_local() {
2385 self.hir().attrs(self.hir().local_def_id_to_hir_id(did)).iter().filter(filter_fn)
2386 } else if cfg!(debug_assertions) && rustc_feature::is_builtin_only_local(attr) {
2387 bug!("tried to access the `only_local` attribute `{}` from an extern crate", attr);
2389 self.item_attrs(did).iter().filter(filter_fn)
2393 pub fn get_attr(self, did: DefId, attr: Symbol) -> Option<&'tcx ast::Attribute> {
2394 if cfg!(debug_assertions) && !rustc_feature::is_valid_for_get_attr(attr) {
2395 bug!("get_attr: unexpected called with DefId `{:?}`, attr `{:?}`", did, attr);
2397 self.get_attrs(did, attr).next()
2401 /// Determines whether an item is annotated with an attribute.
2402 pub fn has_attr(self, did: DefId, attr: Symbol) -> bool {
2403 if cfg!(debug_assertions) && !did.is_local() && rustc_feature::is_builtin_only_local(attr) {
2404 bug!("tried to access the `only_local` attribute `{}` from an extern crate", attr);
2406 self.get_attrs(did, attr).next().is_some()
2410 /// Returns `true` if this is an `auto trait`.
2411 pub fn trait_is_auto(self, trait_def_id: DefId) -> bool {
2412 self.trait_def(trait_def_id).has_auto_impl
2415 pub fn trait_is_coinductive(self, trait_def_id: DefId) -> bool {
2416 self.trait_is_auto(trait_def_id) || self.lang_items().sized_trait() == Some(trait_def_id)
2419 /// Returns layout of a generator. Layout might be unavailable if the
2420 /// generator is tainted by errors.
2421 pub fn generator_layout(self, def_id: DefId) -> Option<&'tcx GeneratorLayout<'tcx>> {
2422 self.optimized_mir(def_id).generator_layout()
2425 /// Given the `DefId` of an impl, returns the `DefId` of the trait it implements.
2426 /// If it implements no trait, returns `None`.
2427 pub fn trait_id_of_impl(self, def_id: DefId) -> Option<DefId> {
2428 self.impl_trait_ref(def_id).map(|tr| tr.def_id)
2431 /// If the given `DefId` describes an item belonging to a trait,
2432 /// returns the `DefId` of the trait that the trait item belongs to;
2433 /// otherwise, returns `None`.
2434 pub fn trait_of_item(self, def_id: DefId) -> Option<DefId> {
2435 if let DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy = self.def_kind(def_id) {
2436 let parent = self.parent(def_id);
2437 if let DefKind::Trait | DefKind::TraitAlias = self.def_kind(parent) {
2438 return Some(parent);
2444 /// If the given `DefId` describes a method belonging to an impl, returns the
2445 /// `DefId` of the impl that the method belongs to; otherwise, returns `None`.
2446 pub fn impl_of_method(self, def_id: DefId) -> Option<DefId> {
2447 if let DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy = self.def_kind(def_id) {
2448 let parent = self.parent(def_id);
2449 if let DefKind::Impl = self.def_kind(parent) {
2450 return Some(parent);
2456 /// If the given `DefId` belongs to a trait that was automatically derived, returns `true`.
2457 pub fn is_builtin_derive(self, def_id: DefId) -> bool {
2458 self.has_attr(def_id, sym::automatically_derived)
2461 /// Looks up the span of `impl_did` if the impl is local; otherwise returns `Err`
2462 /// with the name of the crate containing the impl.
2463 pub fn span_of_impl(self, impl_def_id: DefId) -> Result<Span, Symbol> {
2464 if let Some(impl_def_id) = impl_def_id.as_local() {
2465 Ok(self.def_span(impl_def_id))
2467 Err(self.crate_name(impl_def_id.krate))
2471 /// Hygienically compares a use-site name (`use_name`) for a field or an associated item with
2472 /// its supposed definition name (`def_name`). The method also needs `DefId` of the supposed
2473 /// definition's parent/scope to perform comparison.
2474 pub fn hygienic_eq(self, use_name: Ident, def_name: Ident, def_parent_def_id: DefId) -> bool {
2475 // We could use `Ident::eq` here, but we deliberately don't. The name
2476 // comparison fails frequently, and we want to avoid the expensive
2477 // `normalize_to_macros_2_0()` calls required for the span comparison whenever possible.
2478 use_name.name == def_name.name
2482 .hygienic_eq(def_name.span.ctxt(), self.expn_that_defined(def_parent_def_id))
2485 pub fn adjust_ident(self, mut ident: Ident, scope: DefId) -> Ident {
2486 ident.span.normalize_to_macros_2_0_and_adjust(self.expn_that_defined(scope));
2490 pub fn adjust_ident_and_get_scope(
2495 ) -> (Ident, DefId) {
2498 .normalize_to_macros_2_0_and_adjust(self.expn_that_defined(scope))
2499 .and_then(|actual_expansion| actual_expansion.expn_data().parent_module)
2500 .unwrap_or_else(|| self.parent_module(block).to_def_id());
2504 /// Returns `true` if the debuginfo for `span` should be collapsed to the outermost expansion
2505 /// site. Only applies when `Span` is the result of macro expansion.
2507 /// - If the `collapse_debuginfo` feature is enabled then debuginfo is not collapsed by default
2508 /// and only when a macro definition is annotated with `#[collapse_debuginfo]`.
2509 /// - If `collapse_debuginfo` is not enabled, then debuginfo is collapsed by default.
2511 /// When `-Zdebug-macros` is provided then debuginfo will never be collapsed.
2512 pub fn should_collapse_debuginfo(self, span: Span) -> bool {
2513 !self.sess.opts.unstable_opts.debug_macros
2514 && if self.features().collapse_debuginfo {
2515 span.in_macro_expansion_with_collapse_debuginfo()
2517 // Inlined spans should not be collapsed as that leads to all of the
2518 // inlined code being attributed to the inline callsite.
2519 span.from_expansion() && !span.is_inlined()
2523 pub fn is_object_safe(self, key: DefId) -> bool {
2524 self.object_safety_violations(key).is_empty()
2528 pub fn is_const_fn_raw(self, def_id: DefId) -> bool {
2529 matches!(self.def_kind(def_id), DefKind::Fn | DefKind::AssocFn | DefKind::Ctor(..))
2530 && self.constness(def_id) == hir::Constness::Const
2534 pub fn is_const_default_method(self, def_id: DefId) -> bool {
2535 matches!(self.trait_of_item(def_id), Some(trait_id) if self.has_attr(trait_id, sym::const_trait))
2538 pub fn impl_trait_in_trait_parent(self, mut def_id: DefId) -> DefId {
2539 while let def_kind = self.def_kind(def_id) && def_kind != DefKind::AssocFn {
2540 debug_assert_eq!(def_kind, DefKind::ImplTraitPlaceholder);
2541 def_id = self.parent(def_id);
2547 /// Yields the parent function's `LocalDefId` if `def_id` is an `impl Trait` definition.
2548 pub fn is_impl_trait_defn(tcx: TyCtxt<'_>, def_id: DefId) -> Option<LocalDefId> {
2549 let def_id = def_id.as_local()?;
2550 if let Node::Item(item) = tcx.hir().get_by_def_id(def_id) {
2551 if let hir::ItemKind::OpaqueTy(ref opaque_ty) = item.kind {
2552 return match opaque_ty.origin {
2553 hir::OpaqueTyOrigin::FnReturn(parent) | hir::OpaqueTyOrigin::AsyncFn(parent) => {
2556 hir::OpaqueTyOrigin::TyAlias => None,
2563 pub fn int_ty(ity: ast::IntTy) -> IntTy {
2565 ast::IntTy::Isize => IntTy::Isize,
2566 ast::IntTy::I8 => IntTy::I8,
2567 ast::IntTy::I16 => IntTy::I16,
2568 ast::IntTy::I32 => IntTy::I32,
2569 ast::IntTy::I64 => IntTy::I64,
2570 ast::IntTy::I128 => IntTy::I128,
2574 pub fn uint_ty(uty: ast::UintTy) -> UintTy {
2576 ast::UintTy::Usize => UintTy::Usize,
2577 ast::UintTy::U8 => UintTy::U8,
2578 ast::UintTy::U16 => UintTy::U16,
2579 ast::UintTy::U32 => UintTy::U32,
2580 ast::UintTy::U64 => UintTy::U64,
2581 ast::UintTy::U128 => UintTy::U128,
2585 pub fn float_ty(fty: ast::FloatTy) -> FloatTy {
2587 ast::FloatTy::F32 => FloatTy::F32,
2588 ast::FloatTy::F64 => FloatTy::F64,
2592 pub fn ast_int_ty(ity: IntTy) -> ast::IntTy {
2594 IntTy::Isize => ast::IntTy::Isize,
2595 IntTy::I8 => ast::IntTy::I8,
2596 IntTy::I16 => ast::IntTy::I16,
2597 IntTy::I32 => ast::IntTy::I32,
2598 IntTy::I64 => ast::IntTy::I64,
2599 IntTy::I128 => ast::IntTy::I128,
2603 pub fn ast_uint_ty(uty: UintTy) -> ast::UintTy {
2605 UintTy::Usize => ast::UintTy::Usize,
2606 UintTy::U8 => ast::UintTy::U8,
2607 UintTy::U16 => ast::UintTy::U16,
2608 UintTy::U32 => ast::UintTy::U32,
2609 UintTy::U64 => ast::UintTy::U64,
2610 UintTy::U128 => ast::UintTy::U128,
2614 pub fn provide(providers: &mut ty::query::Providers) {
2615 closure::provide(providers);
2616 context::provide(providers);
2617 erase_regions::provide(providers);
2618 inhabitedness::provide(providers);
2619 util::provide(providers);
2620 print::provide(providers);
2621 super::util::bug::provide(providers);
2622 super::middle::provide(providers);
2623 *providers = ty::query::Providers {
2624 trait_impls_of: trait_def::trait_impls_of_provider,
2625 incoherent_impls: trait_def::incoherent_impls_provider,
2626 const_param_default: consts::const_param_default,
2627 vtable_allocation: vtable::vtable_allocation_provider,
2632 /// A map for the local crate mapping each type to a vector of its
2633 /// inherent impls. This is not meant to be used outside of coherence;
2634 /// rather, you should request the vector for a specific type via
2635 /// `tcx.inherent_impls(def_id)` so as to minimize your dependencies
2636 /// (constructing this map requires touching the entire crate).
2637 #[derive(Clone, Debug, Default, HashStable)]
2638 pub struct CrateInherentImpls {
2639 pub inherent_impls: LocalDefIdMap<Vec<DefId>>,
2640 pub incoherent_impls: FxHashMap<SimplifiedType, Vec<LocalDefId>>,
2643 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, HashStable)]
2644 pub struct SymbolName<'tcx> {
2645 /// `&str` gives a consistent ordering, which ensures reproducible builds.
2646 pub name: &'tcx str,
2649 impl<'tcx> SymbolName<'tcx> {
2650 pub fn new(tcx: TyCtxt<'tcx>, name: &str) -> SymbolName<'tcx> {
2652 name: unsafe { str::from_utf8_unchecked(tcx.arena.alloc_slice(name.as_bytes())) },
2657 impl<'tcx> fmt::Display for SymbolName<'tcx> {
2658 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2659 fmt::Display::fmt(&self.name, fmt)
2663 impl<'tcx> fmt::Debug for SymbolName<'tcx> {
2664 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2665 fmt::Display::fmt(&self.name, fmt)
2669 #[derive(Debug, Default, Copy, Clone)]
2670 pub struct FoundRelationships {
2671 /// This is true if we identified that this Ty (`?T`) is found in a `?T: Foo`
2672 /// obligation, where:
2674 /// * `Foo` is not `Sized`
2675 /// * `(): Foo` may be satisfied
2676 pub self_in_trait: bool,
2677 /// This is true if we identified that this Ty (`?T`) is found in a `<_ as
2678 /// _>::AssocType = ?T`
2682 /// The constituent parts of a type level constant of kind ADT or array.
2683 #[derive(Copy, Clone, Debug, HashStable)]
2684 pub struct DestructuredConst<'tcx> {
2685 pub variant: Option<VariantIdx>,
2686 pub fields: &'tcx [ty::Const<'tcx>],
2689 // Some types are used a lot. Make sure they don't unintentionally get bigger.
2690 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
2693 use rustc_data_structures::static_assert_size;
2694 // tidy-alphabetical-start
2695 static_assert_size!(PredicateS<'_>, 48);
2696 static_assert_size!(TyS<'_>, 40);
2697 static_assert_size!(WithStableHash<TyS<'_>>, 56);
2698 // tidy-alphabetical-end