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 ructc-dev-guide.
10 //! ["The `ty` module: representing types"]: https://rustc-dev-guide.rust-lang.org/ty.html
12 pub use self::fold::{TypeFoldable, TypeFolder, TypeVisitor};
13 pub use self::AssocItemContainer::*;
14 pub use self::BorrowKind::*;
15 pub use self::IntVarValue::*;
16 pub use self::Variance::*;
22 use crate::hir::exports::ExportMap;
23 use crate::hir::place::{
24 Place as HirPlace, PlaceBase as HirPlaceBase, ProjectionKind as HirProjectionKind,
26 use crate::ich::StableHashingContext;
27 use crate::middle::cstore::CrateStoreDyn;
28 use crate::mir::{Body, GeneratorLayout};
29 use crate::traits::{self, Reveal};
31 use crate::ty::subst::{GenericArg, InternalSubsts, Subst, SubstsRef};
32 use crate::ty::util::Discr;
34 use rustc_attr as attr;
35 use rustc_data_structures::captures::Captures;
36 use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap};
37 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
38 use rustc_data_structures::sync::{self, par_iter, ParallelIterator};
39 use rustc_data_structures::tagged_ptr::CopyTaggedPtr;
41 use rustc_hir::def::{CtorKind, CtorOf, DefKind, Res};
42 use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, LocalDefId, CRATE_DEF_INDEX};
43 use rustc_hir::lang_items::LangItem;
44 use rustc_hir::{Constness, Node};
45 use rustc_macros::HashStable;
46 use rustc_span::hygiene::ExpnId;
47 use rustc_span::symbol::{kw, Ident, Symbol};
49 use rustc_target::abi::Align;
51 use std::cmp::Ordering;
52 use std::hash::{Hash, Hasher};
53 use std::ops::ControlFlow;
54 use std::{fmt, ptr, str};
56 pub use crate::ty::diagnostics::*;
57 pub use rustc_type_ir::InferTy::*;
58 pub use rustc_type_ir::*;
60 pub use self::binding::BindingMode;
61 pub use self::binding::BindingMode::*;
62 pub use self::consts::{Const, ConstInt, ConstKind, InferConst, ScalarInt};
63 pub use self::context::{
64 tls, CanonicalUserType, CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations,
65 CtxtInterners, DelaySpanBugEmitted, FreeRegionInfo, GeneratorInteriorTypeCause, GlobalCtxt,
66 Lift, ResolvedOpaqueTy, TyCtxt, TypeckResults, UserType, UserTypeAnnotationIndex,
68 pub use self::instance::{Instance, InstanceDef};
69 pub use self::list::List;
70 pub use self::sty::BoundRegionKind::*;
71 pub use self::sty::RegionKind::*;
72 pub use self::sty::TyKind::*;
74 Binder, BoundRegion, BoundRegionKind, BoundTy, BoundTyKind, BoundVar, CanonicalPolyFnSig,
75 ClosureSubsts, ClosureSubstsParts, ConstVid, EarlyBoundRegion, ExistentialPredicate,
76 ExistentialProjection, ExistentialTraitRef, FnSig, FreeRegion, GenSig, GeneratorSubsts,
77 GeneratorSubstsParts, ParamConst, ParamTy, PolyExistentialProjection, PolyExistentialTraitRef,
78 PolyFnSig, PolyGenSig, PolyTraitRef, ProjectionTy, Region, RegionKind, RegionVid, TraitRef,
79 TyKind, TypeAndMut, UpvarSubsts,
81 pub use self::trait_def::TraitDef;
92 pub mod inhabitedness;
94 pub mod normalize_erasing_regions;
113 mod structural_impls;
119 pub struct ResolverOutputs {
120 pub definitions: rustc_hir::definitions::Definitions,
121 pub cstore: Box<CrateStoreDyn>,
122 pub visibilities: FxHashMap<LocalDefId, Visibility>,
123 pub extern_crate_map: FxHashMap<LocalDefId, CrateNum>,
124 pub maybe_unused_trait_imports: FxHashSet<LocalDefId>,
125 pub maybe_unused_extern_crates: Vec<(LocalDefId, Span)>,
126 pub export_map: ExportMap<LocalDefId>,
127 pub glob_map: FxHashMap<LocalDefId, FxHashSet<Symbol>>,
128 /// Extern prelude entries. The value is `true` if the entry was introduced
129 /// via `extern crate` item and not `--extern` option or compiler built-in.
130 pub extern_prelude: FxHashMap<Symbol, bool>,
133 /// The "header" of an impl is everything outside the body: a Self type, a trait
134 /// ref (in the case of a trait impl), and a set of predicates (from the
135 /// bounds / where-clauses).
136 #[derive(Clone, Debug, TypeFoldable)]
137 pub struct ImplHeader<'tcx> {
138 pub impl_def_id: DefId,
139 pub self_ty: Ty<'tcx>,
140 pub trait_ref: Option<TraitRef<'tcx>>,
141 pub predicates: Vec<Predicate<'tcx>>,
144 #[derive(Copy, Clone, PartialEq, TyEncodable, TyDecodable, HashStable, Debug)]
145 pub enum ImplPolarity {
146 /// `impl Trait for Type`
148 /// `impl !Trait for Type`
150 /// `#[rustc_reservation_impl] impl Trait for Type`
152 /// This is a "stability hack", not a real Rust feature.
153 /// See #64631 for details.
157 #[derive(Clone, Debug, PartialEq, Eq, Copy, Hash, TyEncodable, TyDecodable, HashStable)]
158 pub enum Visibility {
159 /// Visible everywhere (including in other crates).
161 /// Visible only in the given crate-local module.
163 /// Not visible anywhere in the local crate. This is the visibility of private external items.
167 pub trait DefIdTree: Copy {
168 fn parent(self, id: DefId) -> Option<DefId>;
170 fn is_descendant_of(self, mut descendant: DefId, ancestor: DefId) -> bool {
171 if descendant.krate != ancestor.krate {
175 while descendant != ancestor {
176 match self.parent(descendant) {
177 Some(parent) => descendant = parent,
178 None => return false,
185 impl<'tcx> DefIdTree for TyCtxt<'tcx> {
186 fn parent(self, id: DefId) -> Option<DefId> {
187 self.def_key(id).parent.map(|index| DefId { index, ..id })
192 pub fn from_hir(visibility: &hir::Visibility<'_>, id: hir::HirId, tcx: TyCtxt<'_>) -> Self {
193 match visibility.node {
194 hir::VisibilityKind::Public => Visibility::Public,
195 hir::VisibilityKind::Crate(_) => Visibility::Restricted(DefId::local(CRATE_DEF_INDEX)),
196 hir::VisibilityKind::Restricted { ref path, .. } => match path.res {
197 // If there is no resolution, `resolve` will have already reported an error, so
198 // assume that the visibility is public to avoid reporting more privacy errors.
199 Res::Err => Visibility::Public,
200 def => Visibility::Restricted(def.def_id()),
202 hir::VisibilityKind::Inherited => {
203 Visibility::Restricted(tcx.parent_module(id).to_def_id())
208 /// Returns `true` if an item with this visibility is accessible from the given block.
209 pub fn is_accessible_from<T: DefIdTree>(self, module: DefId, tree: T) -> bool {
210 let restriction = match self {
211 // Public items are visible everywhere.
212 Visibility::Public => return true,
213 // Private items from other crates are visible nowhere.
214 Visibility::Invisible => return false,
215 // Restricted items are visible in an arbitrary local module.
216 Visibility::Restricted(other) if other.krate != module.krate => return false,
217 Visibility::Restricted(module) => module,
220 tree.is_descendant_of(module, restriction)
223 /// Returns `true` if this visibility is at least as accessible as the given visibility
224 pub fn is_at_least<T: DefIdTree>(self, vis: Visibility, tree: T) -> bool {
225 let vis_restriction = match vis {
226 Visibility::Public => return self == Visibility::Public,
227 Visibility::Invisible => return true,
228 Visibility::Restricted(module) => module,
231 self.is_accessible_from(vis_restriction, tree)
234 // Returns `true` if this item is visible anywhere in the local crate.
235 pub fn is_visible_locally(self) -> bool {
237 Visibility::Public => true,
238 Visibility::Restricted(def_id) => def_id.is_local(),
239 Visibility::Invisible => false,
244 /// The crate variances map is computed during typeck and contains the
245 /// variance of every item in the local crate. You should not use it
246 /// directly, because to do so will make your pass dependent on the
247 /// HIR of every item in the local crate. Instead, use
248 /// `tcx.variances_of()` to get the variance for a *particular*
250 #[derive(HashStable, Debug)]
251 pub struct CrateVariancesMap<'tcx> {
252 /// For each item with generics, maps to a vector of the variance
253 /// of its generics. If an item has no generics, it will have no
255 pub variances: FxHashMap<DefId, &'tcx [ty::Variance]>,
258 // Contains information needed to resolve types and (in the future) look up
259 // the types of AST nodes.
260 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
261 pub struct CReaderCacheKey {
266 #[allow(rustc::usage_of_ty_tykind)]
267 pub struct TyS<'tcx> {
268 /// This field shouldn't be used directly and may be removed in the future.
269 /// Use `TyS::kind()` instead.
271 /// This field shouldn't be used directly and may be removed in the future.
272 /// Use `TyS::flags()` instead.
275 /// This is a kind of confusing thing: it stores the smallest
278 /// (a) the binder itself captures nothing but
279 /// (b) all the late-bound things within the type are captured
280 /// by some sub-binder.
282 /// So, for a type without any late-bound things, like `u32`, this
283 /// will be *innermost*, because that is the innermost binder that
284 /// captures nothing. But for a type `&'D u32`, where `'D` is a
285 /// late-bound region with De Bruijn index `D`, this would be `D + 1`
286 /// -- the binder itself does not capture `D`, but `D` is captured
287 /// by an inner binder.
289 /// We call this concept an "exclusive" binder `D` because all
290 /// De Bruijn indices within the type are contained within `0..D`
292 outer_exclusive_binder: ty::DebruijnIndex,
295 impl<'tcx> TyS<'tcx> {
296 /// A constructor used only for internal testing.
297 #[allow(rustc::usage_of_ty_tykind)]
298 pub fn make_for_test(
301 outer_exclusive_binder: ty::DebruijnIndex,
303 TyS { kind, flags, outer_exclusive_binder }
307 // `TyS` is used a lot. Make sure it doesn't unintentionally get bigger.
308 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
309 static_assert_size!(TyS<'_>, 32);
311 impl<'tcx> Ord for TyS<'tcx> {
312 fn cmp(&self, other: &TyS<'tcx>) -> Ordering {
313 self.kind().cmp(other.kind())
317 impl<'tcx> PartialOrd for TyS<'tcx> {
318 fn partial_cmp(&self, other: &TyS<'tcx>) -> Option<Ordering> {
319 Some(self.kind().cmp(other.kind()))
323 impl<'tcx> PartialEq for TyS<'tcx> {
325 fn eq(&self, other: &TyS<'tcx>) -> bool {
329 impl<'tcx> Eq for TyS<'tcx> {}
331 impl<'tcx> Hash for TyS<'tcx> {
332 fn hash<H: Hasher>(&self, s: &mut H) {
333 (self as *const TyS<'_>).hash(s)
337 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for TyS<'tcx> {
338 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
342 // The other fields just provide fast access to information that is
343 // also contained in `kind`, so no need to hash them.
346 outer_exclusive_binder: _,
349 kind.hash_stable(hcx, hasher);
353 #[rustc_diagnostic_item = "Ty"]
354 pub type Ty<'tcx> = &'tcx TyS<'tcx>;
356 #[derive(Clone, PartialEq, Debug, TyEncodable, TyDecodable, TypeFoldable, Copy, HashStable)]
357 pub enum BorrowKind {
358 /// Data must be immutable and is aliasable.
361 /// Data must be immutable but not aliasable. This kind of borrow
362 /// cannot currently be expressed by the user and is used only in
363 /// implicit closure bindings. It is needed when the closure
364 /// is borrowing or mutating a mutable referent, e.g.:
367 /// let x: &mut isize = ...;
368 /// let y = || *x += 5;
371 /// If we were to try to translate this closure into a more explicit
372 /// form, we'd encounter an error with the code as written:
375 /// struct Env { x: & &mut isize }
376 /// let x: &mut isize = ...;
377 /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
378 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
381 /// This is then illegal because you cannot mutate a `&mut` found
382 /// in an aliasable location. To solve, you'd have to translate with
383 /// an `&mut` borrow:
386 /// struct Env { x: & &mut isize }
387 /// let x: &mut isize = ...;
388 /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
389 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
392 /// Now the assignment to `**env.x` is legal, but creating a
393 /// mutable pointer to `x` is not because `x` is not mutable. We
394 /// could fix this by declaring `x` as `let mut x`. This is ok in
395 /// user code, if awkward, but extra weird for closures, since the
396 /// borrow is hidden.
398 /// So we introduce a "unique imm" borrow -- the referent is
399 /// immutable, but not aliasable. This solves the problem. For
400 /// simplicity, we don't give users the way to express this
401 /// borrow, it's just used when translating closures.
404 /// Data is mutable and not aliasable.
408 /// Given the closure DefId this map provides a map of root variables to minimum
409 /// set of `CapturedPlace`s that need to be tracked to support all captures of that closure.
410 pub type MinCaptureInformationMap<'tcx> = FxHashMap<DefId, RootVariableMinCaptureList<'tcx>>;
412 /// Part of `MinCaptureInformationMap`; Maps a root variable to the list of `CapturedPlace`.
413 /// Used to track the minimum set of `Place`s that need to be captured to support all
414 /// Places captured by the closure starting at a given root variable.
416 /// This provides a convenient and quick way of checking if a variable being used within
417 /// a closure is a capture of a local variable.
418 pub type RootVariableMinCaptureList<'tcx> = FxIndexMap<hir::HirId, MinCaptureList<'tcx>>;
420 /// Part of `MinCaptureInformationMap`; List of `CapturePlace`s.
421 pub type MinCaptureList<'tcx> = Vec<CapturedPlace<'tcx>>;
423 /// A composite describing a `Place` that is captured by a closure.
424 #[derive(PartialEq, Clone, Debug, TyEncodable, TyDecodable, TypeFoldable, HashStable)]
425 pub struct CapturedPlace<'tcx> {
426 /// The `Place` that is captured.
427 pub place: HirPlace<'tcx>,
429 /// `CaptureKind` and expression(s) that resulted in such capture of `place`.
430 pub info: CaptureInfo<'tcx>,
432 /// Represents if `place` can be mutated or not.
433 pub mutability: hir::Mutability,
436 impl CapturedPlace<'tcx> {
437 /// Returns the hir-id of the root variable for the captured place.
438 /// e.g., if `a.b.c` was captured, would return the hir-id for `a`.
439 pub fn get_root_variable(&self) -> hir::HirId {
440 match self.place.base {
441 HirPlaceBase::Upvar(upvar_id) => upvar_id.var_path.hir_id,
442 base => bug!("Expected upvar, found={:?}", base),
447 pub fn place_to_string_for_capture(tcx: TyCtxt<'tcx>, place: &HirPlace<'tcx>) -> String {
448 let name = match place.base {
449 HirPlaceBase::Upvar(upvar_id) => tcx.hir().name(upvar_id.var_path.hir_id).to_string(),
450 _ => bug!("Capture_information should only contain upvars"),
452 let mut curr_string = name;
454 for (i, proj) in place.projections.iter().enumerate() {
456 HirProjectionKind::Deref => {
457 curr_string = format!("*{}", curr_string);
459 HirProjectionKind::Field(idx, variant) => match place.ty_before_projection(i).kind() {
460 ty::Adt(def, ..) => {
461 curr_string = format!(
464 def.variants[variant].fields[idx as usize].ident.name.as_str()
468 curr_string = format!("{}.{}", curr_string, idx);
472 "Field projection applied to a type other than Adt or Tuple: {:?}.",
473 place.ty_before_projection(i).kind()
477 proj => bug!("{:?} unexpected because it isn't captured", proj),
481 curr_string.to_string()
484 /// Part of `MinCaptureInformationMap`; describes the capture kind (&, &mut, move)
485 /// for a particular capture as well as identifying the part of the source code
486 /// that triggered this capture to occur.
487 #[derive(PartialEq, Clone, Debug, Copy, TyEncodable, TyDecodable, TypeFoldable, HashStable)]
488 pub struct CaptureInfo<'tcx> {
489 /// Expr Id pointing to use that resulted in selecting the current capture kind
493 /// let mut t = (0,1);
496 /// println!("{}",t); // L1
500 /// `capture_kind_expr_id` will point to the use on L2 and `path_expr_id` will point to the
503 /// If the user doesn't enable feature `capture_disjoint_fields` (RFC 2229) then, it is
504 /// possible that we don't see the use of a particular place resulting in capture_kind_expr_id being
505 /// None. In such case we fallback on uvpars_mentioned for span.
516 /// In this example, if `capture_disjoint_fields` is **not** set, then x will be captured,
517 /// but we won't see it being used during capture analysis, since it's essentially a discard.
518 pub capture_kind_expr_id: Option<hir::HirId>,
519 /// Expr Id pointing to use that resulted the corresponding place being captured
521 /// See `capture_kind_expr_id` for example.
523 pub path_expr_id: Option<hir::HirId>,
525 /// Capture mode that was selected
526 pub capture_kind: UpvarCapture<'tcx>,
529 impl ty::EarlyBoundRegion {
530 /// Does this early bound region have a name? Early bound regions normally
531 /// always have names except when using anonymous lifetimes (`'_`).
532 pub fn has_name(&self) -> bool {
533 self.name != kw::UnderscoreLifetime
538 crate struct PredicateInner<'tcx> {
539 kind: Binder<PredicateKind<'tcx>>,
541 /// See the comment for the corresponding field of [TyS].
542 outer_exclusive_binder: ty::DebruijnIndex,
545 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
546 static_assert_size!(PredicateInner<'_>, 40);
548 #[derive(Clone, Copy, Lift)]
549 pub struct Predicate<'tcx> {
550 inner: &'tcx PredicateInner<'tcx>,
553 impl<'tcx> PartialEq for Predicate<'tcx> {
554 fn eq(&self, other: &Self) -> bool {
555 // `self.kind` is always interned.
556 ptr::eq(self.inner, other.inner)
560 impl Hash for Predicate<'_> {
561 fn hash<H: Hasher>(&self, s: &mut H) {
562 (self.inner as *const PredicateInner<'_>).hash(s)
566 impl<'tcx> Eq for Predicate<'tcx> {}
568 impl<'tcx> Predicate<'tcx> {
569 /// Gets the inner `Binder<PredicateKind<'tcx>>`.
571 pub fn kind(self) -> Binder<PredicateKind<'tcx>> {
576 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for Predicate<'tcx> {
577 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
581 // The other fields just provide fast access to information that is
582 // also contained in `kind`, so no need to hash them.
584 outer_exclusive_binder: _,
587 kind.hash_stable(hcx, hasher);
591 #[derive(Clone, Copy, PartialEq, Eq, Hash, TyEncodable, TyDecodable)]
592 #[derive(HashStable, TypeFoldable)]
593 pub enum PredicateKind<'tcx> {
594 /// Corresponds to `where Foo: Bar<A, B, C>`. `Foo` here would be
595 /// the `Self` type of the trait reference and `A`, `B`, and `C`
596 /// would be the type parameters.
598 /// A trait predicate will have `Constness::Const` if it originates
599 /// from a bound on a `const fn` without the `?const` opt-out (e.g.,
600 /// `const fn foobar<Foo: Bar>() {}`).
601 Trait(TraitPredicate<'tcx>, Constness),
604 RegionOutlives(RegionOutlivesPredicate<'tcx>),
607 TypeOutlives(TypeOutlivesPredicate<'tcx>),
609 /// `where <T as TraitRef>::Name == X`, approximately.
610 /// See the `ProjectionPredicate` struct for details.
611 Projection(ProjectionPredicate<'tcx>),
613 /// No syntax: `T` well-formed.
614 WellFormed(GenericArg<'tcx>),
616 /// Trait must be object-safe.
619 /// No direct syntax. May be thought of as `where T: FnFoo<...>`
620 /// for some substitutions `...` and `T` being a closure type.
621 /// Satisfied (or refuted) once we know the closure's kind.
622 ClosureKind(DefId, SubstsRef<'tcx>, ClosureKind),
625 Subtype(SubtypePredicate<'tcx>),
627 /// Constant initializer must evaluate successfully.
628 ConstEvaluatable(ty::WithOptConstParam<DefId>, SubstsRef<'tcx>),
630 /// Constants must be equal. The first component is the const that is expected.
631 ConstEquate(&'tcx Const<'tcx>, &'tcx Const<'tcx>),
633 /// Represents a type found in the environment that we can use for implied bounds.
635 /// Only used for Chalk.
636 TypeWellFormedFromEnv(Ty<'tcx>),
639 /// The crate outlives map is computed during typeck and contains the
640 /// outlives of every item in the local crate. You should not use it
641 /// directly, because to do so will make your pass dependent on the
642 /// HIR of every item in the local crate. Instead, use
643 /// `tcx.inferred_outlives_of()` to get the outlives for a *particular*
645 #[derive(HashStable, Debug)]
646 pub struct CratePredicatesMap<'tcx> {
647 /// For each struct with outlive bounds, maps to a vector of the
648 /// predicate of its outlive bounds. If an item has no outlives
649 /// bounds, it will have no entry.
650 pub predicates: FxHashMap<DefId, &'tcx [(Predicate<'tcx>, Span)]>,
653 impl<'tcx> Predicate<'tcx> {
654 /// Performs a substitution suitable for going from a
655 /// poly-trait-ref to supertraits that must hold if that
656 /// poly-trait-ref holds. This is slightly different from a normal
657 /// substitution in terms of what happens with bound regions. See
658 /// lengthy comment below for details.
659 pub fn subst_supertrait(
662 trait_ref: &ty::PolyTraitRef<'tcx>,
663 ) -> Predicate<'tcx> {
664 // The interaction between HRTB and supertraits is not entirely
665 // obvious. Let me walk you (and myself) through an example.
667 // Let's start with an easy case. Consider two traits:
669 // trait Foo<'a>: Bar<'a,'a> { }
670 // trait Bar<'b,'c> { }
672 // Now, if we have a trait reference `for<'x> T: Foo<'x>`, then
673 // we can deduce that `for<'x> T: Bar<'x,'x>`. Basically, if we
674 // knew that `Foo<'x>` (for any 'x) then we also know that
675 // `Bar<'x,'x>` (for any 'x). This more-or-less falls out from
676 // normal substitution.
678 // In terms of why this is sound, the idea is that whenever there
679 // is an impl of `T:Foo<'a>`, it must show that `T:Bar<'a,'a>`
680 // holds. So if there is an impl of `T:Foo<'a>` that applies to
681 // all `'a`, then we must know that `T:Bar<'a,'a>` holds for all
684 // Another example to be careful of is this:
686 // trait Foo1<'a>: for<'b> Bar1<'a,'b> { }
687 // trait Bar1<'b,'c> { }
689 // Here, if we have `for<'x> T: Foo1<'x>`, then what do we know?
690 // The answer is that we know `for<'x,'b> T: Bar1<'x,'b>`. The
691 // reason is similar to the previous example: any impl of
692 // `T:Foo1<'x>` must show that `for<'b> T: Bar1<'x, 'b>`. So
693 // basically we would want to collapse the bound lifetimes from
694 // the input (`trait_ref`) and the supertraits.
696 // To achieve this in practice is fairly straightforward. Let's
697 // consider the more complicated scenario:
699 // - We start out with `for<'x> T: Foo1<'x>`. In this case, `'x`
700 // has a De Bruijn index of 1. We want to produce `for<'x,'b> T: Bar1<'x,'b>`,
701 // where both `'x` and `'b` would have a DB index of 1.
702 // The substitution from the input trait-ref is therefore going to be
703 // `'a => 'x` (where `'x` has a DB index of 1).
704 // - The super-trait-ref is `for<'b> Bar1<'a,'b>`, where `'a` is an
705 // early-bound parameter and `'b' is a late-bound parameter with a
707 // - If we replace `'a` with `'x` from the input, it too will have
708 // a DB index of 1, and thus we'll have `for<'x,'b> Bar1<'x,'b>`
709 // just as we wanted.
711 // There is only one catch. If we just apply the substitution `'a
712 // => 'x` to `for<'b> Bar1<'a,'b>`, the substitution code will
713 // adjust the DB index because we substituting into a binder (it
714 // tries to be so smart...) resulting in `for<'x> for<'b>
715 // Bar1<'x,'b>` (we have no syntax for this, so use your
716 // imagination). Basically the 'x will have DB index of 2 and 'b
717 // will have DB index of 1. Not quite what we want. So we apply
718 // the substitution to the *contents* of the trait reference,
719 // rather than the trait reference itself (put another way, the
720 // substitution code expects equal binding levels in the values
721 // from the substitution and the value being substituted into, and
722 // this trick achieves that).
723 let substs = trait_ref.skip_binder().substs;
724 let pred = self.kind().skip_binder();
725 let new = pred.subst(tcx, substs);
726 tcx.reuse_or_mk_predicate(self, ty::Binder::bind(new))
730 #[derive(Clone, Copy, PartialEq, Eq, Hash, TyEncodable, TyDecodable)]
731 #[derive(HashStable, TypeFoldable)]
732 pub struct TraitPredicate<'tcx> {
733 pub trait_ref: TraitRef<'tcx>,
736 pub type PolyTraitPredicate<'tcx> = ty::Binder<TraitPredicate<'tcx>>;
738 impl<'tcx> TraitPredicate<'tcx> {
739 pub fn def_id(self) -> DefId {
740 self.trait_ref.def_id
743 pub fn self_ty(self) -> Ty<'tcx> {
744 self.trait_ref.self_ty()
748 impl<'tcx> PolyTraitPredicate<'tcx> {
749 pub fn def_id(self) -> DefId {
750 // Ok to skip binder since trait `DefId` does not care about regions.
751 self.skip_binder().def_id()
754 pub fn self_ty(self) -> ty::Binder<Ty<'tcx>> {
755 self.map_bound(|trait_ref| trait_ref.self_ty())
759 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, TyEncodable, TyDecodable)]
760 #[derive(HashStable, TypeFoldable)]
761 pub struct OutlivesPredicate<A, B>(pub A, pub B); // `A: B`
762 pub type RegionOutlivesPredicate<'tcx> = OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>;
763 pub type TypeOutlivesPredicate<'tcx> = OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>;
764 pub type PolyRegionOutlivesPredicate<'tcx> = ty::Binder<RegionOutlivesPredicate<'tcx>>;
765 pub type PolyTypeOutlivesPredicate<'tcx> = ty::Binder<TypeOutlivesPredicate<'tcx>>;
767 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, TyEncodable, TyDecodable)]
768 #[derive(HashStable, TypeFoldable)]
769 pub struct SubtypePredicate<'tcx> {
770 pub a_is_expected: bool,
774 pub type PolySubtypePredicate<'tcx> = ty::Binder<SubtypePredicate<'tcx>>;
776 /// This kind of predicate has no *direct* correspondent in the
777 /// syntax, but it roughly corresponds to the syntactic forms:
779 /// 1. `T: TraitRef<..., Item = Type>`
780 /// 2. `<T as TraitRef<...>>::Item == Type` (NYI)
782 /// In particular, form #1 is "desugared" to the combination of a
783 /// normal trait predicate (`T: TraitRef<...>`) and one of these
784 /// predicates. Form #2 is a broader form in that it also permits
785 /// equality between arbitrary types. Processing an instance of
786 /// Form #2 eventually yields one of these `ProjectionPredicate`
787 /// instances to normalize the LHS.
788 #[derive(Copy, Clone, PartialEq, Eq, Hash, TyEncodable, TyDecodable)]
789 #[derive(HashStable, TypeFoldable)]
790 pub struct ProjectionPredicate<'tcx> {
791 pub projection_ty: ProjectionTy<'tcx>,
795 pub type PolyProjectionPredicate<'tcx> = Binder<ProjectionPredicate<'tcx>>;
797 impl<'tcx> PolyProjectionPredicate<'tcx> {
798 /// Returns the `DefId` of the associated item being projected.
799 pub fn item_def_id(&self) -> DefId {
800 self.skip_binder().projection_ty.item_def_id
803 /// Returns the `DefId` of the trait of the associated item being projected.
805 pub fn trait_def_id(&self, tcx: TyCtxt<'tcx>) -> DefId {
806 self.skip_binder().projection_ty.trait_def_id(tcx)
810 pub fn projection_self_ty(&self) -> Binder<Ty<'tcx>> {
811 self.map_bound(|predicate| predicate.projection_ty.self_ty())
814 /// Get the [PolyTraitRef] required for this projection to be well formed.
815 /// Note that for generic associated types the predicates of the associated
816 /// type also need to be checked.
818 pub fn required_poly_trait_ref(&self, tcx: TyCtxt<'tcx>) -> PolyTraitRef<'tcx> {
819 // Note: unlike with `TraitRef::to_poly_trait_ref()`,
820 // `self.0.trait_ref` is permitted to have escaping regions.
821 // This is because here `self` has a `Binder` and so does our
822 // return value, so we are preserving the number of binding
824 self.map_bound(|predicate| predicate.projection_ty.trait_ref(tcx))
827 pub fn ty(&self) -> Binder<Ty<'tcx>> {
828 self.map_bound(|predicate| predicate.ty)
831 /// The `DefId` of the `TraitItem` for the associated type.
833 /// Note that this is not the `DefId` of the `TraitRef` containing this
834 /// associated type, which is in `tcx.associated_item(projection_def_id()).container`.
835 pub fn projection_def_id(&self) -> DefId {
836 // Ok to skip binder since trait `DefId` does not care about regions.
837 self.skip_binder().projection_ty.item_def_id
841 pub trait ToPolyTraitRef<'tcx> {
842 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx>;
845 impl<'tcx> ToPolyTraitRef<'tcx> for TraitRef<'tcx> {
846 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
847 ty::Binder::dummy(*self)
851 impl<'tcx> ToPolyTraitRef<'tcx> for PolyTraitPredicate<'tcx> {
852 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
853 self.map_bound_ref(|trait_pred| trait_pred.trait_ref)
857 pub trait ToPredicate<'tcx> {
858 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx>;
861 impl ToPredicate<'tcx> for Binder<PredicateKind<'tcx>> {
863 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
864 tcx.mk_predicate(self)
868 impl ToPredicate<'tcx> for PredicateKind<'tcx> {
870 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
871 tcx.mk_predicate(Binder::dummy(self))
875 impl<'tcx> ToPredicate<'tcx> for ConstnessAnd<TraitRef<'tcx>> {
876 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
877 PredicateKind::Trait(ty::TraitPredicate { trait_ref: self.value }, self.constness)
882 impl<'tcx> ToPredicate<'tcx> for ConstnessAnd<PolyTraitRef<'tcx>> {
883 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
885 value: self.value.map_bound(|trait_ref| ty::TraitPredicate { trait_ref }),
886 constness: self.constness,
892 impl<'tcx> ToPredicate<'tcx> for ConstnessAnd<PolyTraitPredicate<'tcx>> {
893 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
894 self.value.map_bound(|value| PredicateKind::Trait(value, self.constness)).to_predicate(tcx)
898 impl<'tcx> ToPredicate<'tcx> for PolyRegionOutlivesPredicate<'tcx> {
899 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
900 self.map_bound(PredicateKind::RegionOutlives).to_predicate(tcx)
904 impl<'tcx> ToPredicate<'tcx> for PolyTypeOutlivesPredicate<'tcx> {
905 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
906 self.map_bound(PredicateKind::TypeOutlives).to_predicate(tcx)
910 impl<'tcx> ToPredicate<'tcx> for PolyProjectionPredicate<'tcx> {
911 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
912 self.map_bound(PredicateKind::Projection).to_predicate(tcx)
916 impl<'tcx> Predicate<'tcx> {
917 pub fn to_opt_poly_trait_ref(self) -> Option<ConstnessAnd<PolyTraitRef<'tcx>>> {
918 let predicate = self.kind();
919 match predicate.skip_binder() {
920 PredicateKind::Trait(t, constness) => {
921 Some(ConstnessAnd { constness, value: predicate.rebind(t.trait_ref) })
923 PredicateKind::Projection(..)
924 | PredicateKind::Subtype(..)
925 | PredicateKind::RegionOutlives(..)
926 | PredicateKind::WellFormed(..)
927 | PredicateKind::ObjectSafe(..)
928 | PredicateKind::ClosureKind(..)
929 | PredicateKind::TypeOutlives(..)
930 | PredicateKind::ConstEvaluatable(..)
931 | PredicateKind::ConstEquate(..)
932 | PredicateKind::TypeWellFormedFromEnv(..) => None,
936 pub fn to_opt_type_outlives(self) -> Option<PolyTypeOutlivesPredicate<'tcx>> {
937 let predicate = self.kind();
938 match predicate.skip_binder() {
939 PredicateKind::TypeOutlives(data) => Some(predicate.rebind(data)),
940 PredicateKind::Trait(..)
941 | PredicateKind::Projection(..)
942 | PredicateKind::Subtype(..)
943 | PredicateKind::RegionOutlives(..)
944 | PredicateKind::WellFormed(..)
945 | PredicateKind::ObjectSafe(..)
946 | PredicateKind::ClosureKind(..)
947 | PredicateKind::ConstEvaluatable(..)
948 | PredicateKind::ConstEquate(..)
949 | PredicateKind::TypeWellFormedFromEnv(..) => None,
954 /// Represents the bounds declared on a particular set of type
955 /// parameters. Should eventually be generalized into a flag list of
956 /// where-clauses. You can obtain a `InstantiatedPredicates` list from a
957 /// `GenericPredicates` by using the `instantiate` method. Note that this method
958 /// reflects an important semantic invariant of `InstantiatedPredicates`: while
959 /// the `GenericPredicates` are expressed in terms of the bound type
960 /// parameters of the impl/trait/whatever, an `InstantiatedPredicates` instance
961 /// represented a set of bounds for some particular instantiation,
962 /// meaning that the generic parameters have been substituted with
967 /// struct Foo<T, U: Bar<T>> { ... }
969 /// Here, the `GenericPredicates` for `Foo` would contain a list of bounds like
970 /// `[[], [U:Bar<T>]]`. Now if there were some particular reference
971 /// like `Foo<isize,usize>`, then the `InstantiatedPredicates` would be `[[],
972 /// [usize:Bar<isize>]]`.
973 #[derive(Clone, Debug, TypeFoldable)]
974 pub struct InstantiatedPredicates<'tcx> {
975 pub predicates: Vec<Predicate<'tcx>>,
976 pub spans: Vec<Span>,
979 impl<'tcx> InstantiatedPredicates<'tcx> {
980 pub fn empty() -> InstantiatedPredicates<'tcx> {
981 InstantiatedPredicates { predicates: vec![], spans: vec![] }
984 pub fn is_empty(&self) -> bool {
985 self.predicates.is_empty()
989 rustc_index::newtype_index! {
990 /// "Universes" are used during type- and trait-checking in the
991 /// presence of `for<..>` binders to control what sets of names are
992 /// visible. Universes are arranged into a tree: the root universe
993 /// contains names that are always visible. Each child then adds a new
994 /// set of names that are visible, in addition to those of its parent.
995 /// We say that the child universe "extends" the parent universe with
998 /// To make this more concrete, consider this program:
1002 /// fn bar<T>(x: T) {
1003 /// let y: for<'a> fn(&'a u8, Foo) = ...;
1007 /// The struct name `Foo` is in the root universe U0. But the type
1008 /// parameter `T`, introduced on `bar`, is in an extended universe U1
1009 /// -- i.e., within `bar`, we can name both `T` and `Foo`, but outside
1010 /// of `bar`, we cannot name `T`. Then, within the type of `y`, the
1011 /// region `'a` is in a universe U2 that extends U1, because we can
1012 /// name it inside the fn type but not outside.
1014 /// Universes are used to do type- and trait-checking around these
1015 /// "forall" binders (also called **universal quantification**). The
1016 /// idea is that when, in the body of `bar`, we refer to `T` as a
1017 /// type, we aren't referring to any type in particular, but rather a
1018 /// kind of "fresh" type that is distinct from all other types we have
1019 /// actually declared. This is called a **placeholder** type, and we
1020 /// use universes to talk about this. In other words, a type name in
1021 /// universe 0 always corresponds to some "ground" type that the user
1022 /// declared, but a type name in a non-zero universe is a placeholder
1023 /// type -- an idealized representative of "types in general" that we
1024 /// use for checking generic functions.
1025 pub struct UniverseIndex {
1027 DEBUG_FORMAT = "U{}",
1031 impl UniverseIndex {
1032 pub const ROOT: UniverseIndex = UniverseIndex::from_u32(0);
1034 /// Returns the "next" universe index in order -- this new index
1035 /// is considered to extend all previous universes. This
1036 /// corresponds to entering a `forall` quantifier. So, for
1037 /// example, suppose we have this type in universe `U`:
1040 /// for<'a> fn(&'a u32)
1043 /// Once we "enter" into this `for<'a>` quantifier, we are in a
1044 /// new universe that extends `U` -- in this new universe, we can
1045 /// name the region `'a`, but that region was not nameable from
1046 /// `U` because it was not in scope there.
1047 pub fn next_universe(self) -> UniverseIndex {
1048 UniverseIndex::from_u32(self.private.checked_add(1).unwrap())
1051 /// Returns `true` if `self` can name a name from `other` -- in other words,
1052 /// if the set of names in `self` is a superset of those in
1053 /// `other` (`self >= other`).
1054 pub fn can_name(self, other: UniverseIndex) -> bool {
1055 self.private >= other.private
1058 /// Returns `true` if `self` cannot name some names from `other` -- in other
1059 /// words, if the set of names in `self` is a strict subset of
1060 /// those in `other` (`self < other`).
1061 pub fn cannot_name(self, other: UniverseIndex) -> bool {
1062 self.private < other.private
1066 /// The "placeholder index" fully defines a placeholder region, type, or const. Placeholders are
1067 /// identified by both a universe, as well as a name residing within that universe. Distinct bound
1068 /// regions/types/consts within the same universe simply have an unknown relationship to one
1070 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TyEncodable, TyDecodable, PartialOrd, Ord)]
1071 pub struct Placeholder<T> {
1072 pub universe: UniverseIndex,
1076 impl<'a, T> HashStable<StableHashingContext<'a>> for Placeholder<T>
1078 T: HashStable<StableHashingContext<'a>>,
1080 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
1081 self.universe.hash_stable(hcx, hasher);
1082 self.name.hash_stable(hcx, hasher);
1086 pub type PlaceholderRegion = Placeholder<BoundRegionKind>;
1088 pub type PlaceholderType = Placeholder<BoundVar>;
1090 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable)]
1091 #[derive(TyEncodable, TyDecodable, PartialOrd, Ord)]
1092 pub struct BoundConst<'tcx> {
1097 pub type PlaceholderConst<'tcx> = Placeholder<BoundConst<'tcx>>;
1099 /// A `DefId` which, in case it is a const argument, is potentially bundled with
1100 /// the `DefId` of the generic parameter it instantiates.
1102 /// This is used to avoid calls to `type_of` for const arguments during typeck
1103 /// which cause cycle errors.
1108 /// fn foo<const N: usize>(&self) -> [u8; N] { [0; N] }
1109 /// // ^ const parameter
1113 /// fn foo<const M: u8>(&self) -> usize { 42 }
1114 /// // ^ const parameter
1119 /// let _b = a.foo::<{ 3 + 7 }>();
1120 /// // ^^^^^^^^^ const argument
1124 /// Let's look at the call `a.foo::<{ 3 + 7 }>()` here. We do not know
1125 /// which `foo` is used until we know the type of `a`.
1127 /// We only know the type of `a` once we are inside of `typeck(main)`.
1128 /// We also end up normalizing the type of `_b` during `typeck(main)` which
1129 /// requires us to evaluate the const argument.
1131 /// To evaluate that const argument we need to know its type,
1132 /// which we would get using `type_of(const_arg)`. This requires us to
1133 /// resolve `foo` as it can be either `usize` or `u8` in this example.
1134 /// However, resolving `foo` once again requires `typeck(main)` to get the type of `a`,
1135 /// which results in a cycle.
1137 /// In short we must not call `type_of(const_arg)` during `typeck(main)`.
1139 /// When first creating the `ty::Const` of the const argument inside of `typeck` we have
1140 /// already resolved `foo` so we know which const parameter this argument instantiates.
1141 /// This means that we also know the expected result of `type_of(const_arg)` even if we
1142 /// aren't allowed to call that query: it is equal to `type_of(const_param)` which is
1143 /// trivial to compute.
1145 /// If we now want to use that constant in a place which potentionally needs its type
1146 /// we also pass the type of its `const_param`. This is the point of `WithOptConstParam`,
1147 /// except that instead of a `Ty` we bundle the `DefId` of the const parameter.
1148 /// Meaning that we need to use `type_of(const_param_did)` if `const_param_did` is `Some`
1149 /// to get the type of `did`.
1150 #[derive(Copy, Clone, Debug, TypeFoldable, Lift, TyEncodable, TyDecodable)]
1151 #[derive(PartialEq, Eq, PartialOrd, Ord)]
1152 #[derive(Hash, HashStable)]
1153 pub struct WithOptConstParam<T> {
1155 /// The `DefId` of the corresponding generic parameter in case `did` is
1156 /// a const argument.
1158 /// Note that even if `did` is a const argument, this may still be `None`.
1159 /// All queries taking `WithOptConstParam` start by calling `tcx.opt_const_param_of(def.did)`
1160 /// to potentially update `param_did` in the case it is `None`.
1161 pub const_param_did: Option<DefId>,
1164 impl<T> WithOptConstParam<T> {
1165 /// Creates a new `WithOptConstParam` setting `const_param_did` to `None`.
1167 pub fn unknown(did: T) -> WithOptConstParam<T> {
1168 WithOptConstParam { did, const_param_did: None }
1172 impl WithOptConstParam<LocalDefId> {
1173 /// Returns `Some((did, param_did))` if `def_id` is a const argument,
1174 /// `None` otherwise.
1176 pub fn try_lookup(did: LocalDefId, tcx: TyCtxt<'_>) -> Option<(LocalDefId, DefId)> {
1177 tcx.opt_const_param_of(did).map(|param_did| (did, param_did))
1180 /// In case `self` is unknown but `self.did` is a const argument, this returns
1181 /// a `WithOptConstParam` with the correct `const_param_did`.
1183 pub fn try_upgrade(self, tcx: TyCtxt<'_>) -> Option<WithOptConstParam<LocalDefId>> {
1184 if self.const_param_did.is_none() {
1185 if let const_param_did @ Some(_) = tcx.opt_const_param_of(self.did) {
1186 return Some(WithOptConstParam { did: self.did, const_param_did });
1193 pub fn to_global(self) -> WithOptConstParam<DefId> {
1194 WithOptConstParam { did: self.did.to_def_id(), const_param_did: self.const_param_did }
1197 pub fn def_id_for_type_of(self) -> DefId {
1198 if let Some(did) = self.const_param_did { did } else { self.did.to_def_id() }
1202 impl WithOptConstParam<DefId> {
1203 pub fn as_local(self) -> Option<WithOptConstParam<LocalDefId>> {
1206 .map(|did| WithOptConstParam { did, const_param_did: self.const_param_did })
1209 pub fn as_const_arg(self) -> Option<(LocalDefId, DefId)> {
1210 if let Some(param_did) = self.const_param_did {
1211 if let Some(did) = self.did.as_local() {
1212 return Some((did, param_did));
1219 pub fn expect_local(self) -> WithOptConstParam<LocalDefId> {
1220 self.as_local().unwrap()
1223 pub fn is_local(self) -> bool {
1227 pub fn def_id_for_type_of(self) -> DefId {
1228 self.const_param_did.unwrap_or(self.did)
1232 /// When type checking, we use the `ParamEnv` to track
1233 /// details about the set of where-clauses that are in scope at this
1234 /// particular point.
1235 #[derive(Copy, Clone, Hash, PartialEq, Eq)]
1236 pub struct ParamEnv<'tcx> {
1237 /// This packs both caller bounds and the reveal enum into one pointer.
1239 /// Caller bounds are `Obligation`s that the caller must satisfy. This is
1240 /// basically the set of bounds on the in-scope type parameters, translated
1241 /// into `Obligation`s, and elaborated and normalized.
1243 /// Use the `caller_bounds()` method to access.
1245 /// Typically, this is `Reveal::UserFacing`, but during codegen we
1246 /// want `Reveal::All`.
1248 /// Note: This is packed, use the reveal() method to access it.
1249 packed: CopyTaggedPtr<&'tcx List<Predicate<'tcx>>, traits::Reveal, true>,
1252 unsafe impl rustc_data_structures::tagged_ptr::Tag for traits::Reveal {
1253 const BITS: usize = 1;
1254 fn into_usize(self) -> usize {
1256 traits::Reveal::UserFacing => 0,
1257 traits::Reveal::All => 1,
1260 unsafe fn from_usize(ptr: usize) -> Self {
1262 0 => traits::Reveal::UserFacing,
1263 1 => traits::Reveal::All,
1264 _ => std::hint::unreachable_unchecked(),
1269 impl<'tcx> fmt::Debug for ParamEnv<'tcx> {
1270 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1271 f.debug_struct("ParamEnv")
1272 .field("caller_bounds", &self.caller_bounds())
1273 .field("reveal", &self.reveal())
1278 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for ParamEnv<'tcx> {
1279 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
1280 self.caller_bounds().hash_stable(hcx, hasher);
1281 self.reveal().hash_stable(hcx, hasher);
1285 impl<'tcx> TypeFoldable<'tcx> for ParamEnv<'tcx> {
1286 fn super_fold_with<F: ty::fold::TypeFolder<'tcx>>(self, folder: &mut F) -> Self {
1287 ParamEnv::new(self.caller_bounds().fold_with(folder), self.reveal().fold_with(folder))
1290 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> ControlFlow<V::BreakTy> {
1291 self.caller_bounds().visit_with(visitor)?;
1292 self.reveal().visit_with(visitor)
1296 impl<'tcx> ParamEnv<'tcx> {
1297 /// Construct a trait environment suitable for contexts where
1298 /// there are no where-clauses in scope. Hidden types (like `impl
1299 /// Trait`) are left hidden, so this is suitable for ordinary
1302 pub fn empty() -> Self {
1303 Self::new(List::empty(), Reveal::UserFacing)
1307 pub fn caller_bounds(self) -> &'tcx List<Predicate<'tcx>> {
1308 self.packed.pointer()
1312 pub fn reveal(self) -> traits::Reveal {
1316 /// Construct a trait environment with no where-clauses in scope
1317 /// where the values of all `impl Trait` and other hidden types
1318 /// are revealed. This is suitable for monomorphized, post-typeck
1319 /// environments like codegen or doing optimizations.
1321 /// N.B., if you want to have predicates in scope, use `ParamEnv::new`,
1322 /// or invoke `param_env.with_reveal_all()`.
1324 pub fn reveal_all() -> Self {
1325 Self::new(List::empty(), Reveal::All)
1328 /// Construct a trait environment with the given set of predicates.
1330 pub fn new(caller_bounds: &'tcx List<Predicate<'tcx>>, reveal: Reveal) -> Self {
1331 ty::ParamEnv { packed: CopyTaggedPtr::new(caller_bounds, reveal) }
1334 pub fn with_user_facing(mut self) -> Self {
1335 self.packed.set_tag(Reveal::UserFacing);
1339 /// Returns a new parameter environment with the same clauses, but
1340 /// which "reveals" the true results of projections in all cases
1341 /// (even for associated types that are specializable). This is
1342 /// the desired behavior during codegen and certain other special
1343 /// contexts; normally though we want to use `Reveal::UserFacing`,
1344 /// which is the default.
1345 /// All opaque types in the caller_bounds of the `ParamEnv`
1346 /// will be normalized to their underlying types.
1347 /// See PR #65989 and issue #65918 for more details
1348 pub fn with_reveal_all_normalized(self, tcx: TyCtxt<'tcx>) -> Self {
1349 if self.packed.tag() == traits::Reveal::All {
1353 ParamEnv::new(tcx.normalize_opaque_types(self.caller_bounds()), Reveal::All)
1356 /// Returns this same environment but with no caller bounds.
1357 pub fn without_caller_bounds(self) -> Self {
1358 Self::new(List::empty(), self.reveal())
1361 /// Creates a suitable environment in which to perform trait
1362 /// queries on the given value. When type-checking, this is simply
1363 /// the pair of the environment plus value. But when reveal is set to
1364 /// All, then if `value` does not reference any type parameters, we will
1365 /// pair it with the empty environment. This improves caching and is generally
1368 /// N.B., we preserve the environment when type-checking because it
1369 /// is possible for the user to have wacky where-clauses like
1370 /// `where Box<u32>: Copy`, which are clearly never
1371 /// satisfiable. We generally want to behave as if they were true,
1372 /// although the surrounding function is never reachable.
1373 pub fn and<T: TypeFoldable<'tcx>>(self, value: T) -> ParamEnvAnd<'tcx, T> {
1374 match self.reveal() {
1375 Reveal::UserFacing => ParamEnvAnd { param_env: self, value },
1378 if value.is_global() {
1379 ParamEnvAnd { param_env: self.without_caller_bounds(), value }
1381 ParamEnvAnd { param_env: self, value }
1388 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TypeFoldable)]
1389 pub struct ConstnessAnd<T> {
1390 pub constness: Constness,
1394 // FIXME(ecstaticmorse): Audit all occurrences of `without_const().to_predicate(tcx)` to ensure that
1395 // the constness of trait bounds is being propagated correctly.
1396 pub trait WithConstness: Sized {
1398 fn with_constness(self, constness: Constness) -> ConstnessAnd<Self> {
1399 ConstnessAnd { constness, value: self }
1403 fn with_const(self) -> ConstnessAnd<Self> {
1404 self.with_constness(Constness::Const)
1408 fn without_const(self) -> ConstnessAnd<Self> {
1409 self.with_constness(Constness::NotConst)
1413 impl<T> WithConstness for T {}
1415 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TypeFoldable)]
1416 pub struct ParamEnvAnd<'tcx, T> {
1417 pub param_env: ParamEnv<'tcx>,
1421 impl<'tcx, T> ParamEnvAnd<'tcx, T> {
1422 pub fn into_parts(self) -> (ParamEnv<'tcx>, T) {
1423 (self.param_env, self.value)
1427 impl<'a, 'tcx, T> HashStable<StableHashingContext<'a>> for ParamEnvAnd<'tcx, T>
1429 T: HashStable<StableHashingContext<'a>>,
1431 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
1432 let ParamEnvAnd { ref param_env, ref value } = *self;
1434 param_env.hash_stable(hcx, hasher);
1435 value.hash_stable(hcx, hasher);
1439 #[derive(Copy, Clone, Debug, HashStable)]
1440 pub struct Destructor {
1441 /// The `DefId` of the destructor method
1446 #[derive(HashStable)]
1447 pub struct VariantFlags: u32 {
1448 const NO_VARIANT_FLAGS = 0;
1449 /// Indicates whether the field list of this variant is `#[non_exhaustive]`.
1450 const IS_FIELD_LIST_NON_EXHAUSTIVE = 1 << 0;
1451 /// Indicates whether this variant was obtained as part of recovering from
1452 /// a syntactic error. May be incomplete or bogus.
1453 const IS_RECOVERED = 1 << 1;
1457 /// Definition of a variant -- a struct's fields or a enum variant.
1458 #[derive(Debug, HashStable)]
1459 pub struct VariantDef {
1460 /// `DefId` that identifies the variant itself.
1461 /// If this variant belongs to a struct or union, then this is a copy of its `DefId`.
1463 /// `DefId` that identifies the variant's constructor.
1464 /// If this variant is a struct variant, then this is `None`.
1465 pub ctor_def_id: Option<DefId>,
1466 /// Variant or struct name.
1467 #[stable_hasher(project(name))]
1469 /// Discriminant of this variant.
1470 pub discr: VariantDiscr,
1471 /// Fields of this variant.
1472 pub fields: Vec<FieldDef>,
1473 /// Type of constructor of variant.
1474 pub ctor_kind: CtorKind,
1475 /// Flags of the variant (e.g. is field list non-exhaustive)?
1476 flags: VariantFlags,
1480 /// Creates a new `VariantDef`.
1482 /// `variant_did` is the `DefId` that identifies the enum variant (if this `VariantDef`
1483 /// represents an enum variant).
1485 /// `ctor_did` is the `DefId` that identifies the constructor of unit or
1486 /// tuple-variants/structs. If this is a `struct`-variant then this should be `None`.
1488 /// `parent_did` is the `DefId` of the `AdtDef` representing the enum or struct that
1489 /// owns this variant. It is used for checking if a struct has `#[non_exhaustive]` w/out having
1490 /// to go through the redirect of checking the ctor's attributes - but compiling a small crate
1491 /// requires loading the `AdtDef`s for all the structs in the universe (e.g., coherence for any
1492 /// built-in trait), and we do not want to load attributes twice.
1494 /// If someone speeds up attribute loading to not be a performance concern, they can
1495 /// remove this hack and use the constructor `DefId` everywhere.
1498 variant_did: Option<DefId>,
1499 ctor_def_id: Option<DefId>,
1500 discr: VariantDiscr,
1501 fields: Vec<FieldDef>,
1502 ctor_kind: CtorKind,
1506 is_field_list_non_exhaustive: bool,
1509 "VariantDef::new(ident = {:?}, variant_did = {:?}, ctor_def_id = {:?}, discr = {:?},
1510 fields = {:?}, ctor_kind = {:?}, adt_kind = {:?}, parent_did = {:?})",
1511 ident, variant_did, ctor_def_id, discr, fields, ctor_kind, adt_kind, parent_did,
1514 let mut flags = VariantFlags::NO_VARIANT_FLAGS;
1515 if is_field_list_non_exhaustive {
1516 flags |= VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE;
1520 flags |= VariantFlags::IS_RECOVERED;
1524 def_id: variant_did.unwrap_or(parent_did),
1534 /// Is this field list non-exhaustive?
1536 pub fn is_field_list_non_exhaustive(&self) -> bool {
1537 self.flags.intersects(VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE)
1540 /// Was this variant obtained as part of recovering from a syntactic error?
1542 pub fn is_recovered(&self) -> bool {
1543 self.flags.intersects(VariantFlags::IS_RECOVERED)
1547 #[derive(Copy, Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
1548 pub enum VariantDiscr {
1549 /// Explicit value for this variant, i.e., `X = 123`.
1550 /// The `DefId` corresponds to the embedded constant.
1553 /// The previous variant's discriminant plus one.
1554 /// For efficiency reasons, the distance from the
1555 /// last `Explicit` discriminant is being stored,
1556 /// or `0` for the first variant, if it has none.
1560 #[derive(Debug, HashStable)]
1561 pub struct FieldDef {
1563 #[stable_hasher(project(name))]
1565 pub vis: Visibility,
1569 #[derive(TyEncodable, TyDecodable, Default, HashStable)]
1570 pub struct ReprFlags: u8 {
1571 const IS_C = 1 << 0;
1572 const IS_SIMD = 1 << 1;
1573 const IS_TRANSPARENT = 1 << 2;
1574 // Internal only for now. If true, don't reorder fields.
1575 const IS_LINEAR = 1 << 3;
1576 // If true, don't expose any niche to type's context.
1577 const HIDE_NICHE = 1 << 4;
1578 // Any of these flags being set prevent field reordering optimisation.
1579 const IS_UNOPTIMISABLE = ReprFlags::IS_C.bits |
1580 ReprFlags::IS_SIMD.bits |
1581 ReprFlags::IS_LINEAR.bits;
1585 /// Represents the repr options provided by the user,
1586 #[derive(Copy, Clone, Debug, Eq, PartialEq, TyEncodable, TyDecodable, Default, HashStable)]
1587 pub struct ReprOptions {
1588 pub int: Option<attr::IntType>,
1589 pub align: Option<Align>,
1590 pub pack: Option<Align>,
1591 pub flags: ReprFlags,
1595 pub fn new(tcx: TyCtxt<'_>, did: DefId) -> ReprOptions {
1596 let mut flags = ReprFlags::empty();
1597 let mut size = None;
1598 let mut max_align: Option<Align> = None;
1599 let mut min_pack: Option<Align> = None;
1600 for attr in tcx.get_attrs(did).iter() {
1601 for r in attr::find_repr_attrs(&tcx.sess, attr) {
1602 flags.insert(match r {
1603 attr::ReprC => ReprFlags::IS_C,
1604 attr::ReprPacked(pack) => {
1605 let pack = Align::from_bytes(pack as u64).unwrap();
1606 min_pack = Some(if let Some(min_pack) = min_pack {
1613 attr::ReprTransparent => ReprFlags::IS_TRANSPARENT,
1614 attr::ReprNoNiche => ReprFlags::HIDE_NICHE,
1615 attr::ReprSimd => ReprFlags::IS_SIMD,
1616 attr::ReprInt(i) => {
1620 attr::ReprAlign(align) => {
1621 max_align = max_align.max(Some(Align::from_bytes(align as u64).unwrap()));
1628 // This is here instead of layout because the choice must make it into metadata.
1629 if !tcx.consider_optimizing(|| format!("Reorder fields of {:?}", tcx.def_path_str(did))) {
1630 flags.insert(ReprFlags::IS_LINEAR);
1632 ReprOptions { int: size, align: max_align, pack: min_pack, flags }
1636 pub fn simd(&self) -> bool {
1637 self.flags.contains(ReprFlags::IS_SIMD)
1640 pub fn c(&self) -> bool {
1641 self.flags.contains(ReprFlags::IS_C)
1644 pub fn packed(&self) -> bool {
1648 pub fn transparent(&self) -> bool {
1649 self.flags.contains(ReprFlags::IS_TRANSPARENT)
1652 pub fn linear(&self) -> bool {
1653 self.flags.contains(ReprFlags::IS_LINEAR)
1656 pub fn hide_niche(&self) -> bool {
1657 self.flags.contains(ReprFlags::HIDE_NICHE)
1660 /// Returns the discriminant type, given these `repr` options.
1661 /// This must only be called on enums!
1662 pub fn discr_type(&self) -> attr::IntType {
1663 self.int.unwrap_or(attr::SignedInt(ast::IntTy::Isize))
1666 /// Returns `true` if this `#[repr()]` should inhabit "smart enum
1667 /// layout" optimizations, such as representing `Foo<&T>` as a
1669 pub fn inhibit_enum_layout_opt(&self) -> bool {
1670 self.c() || self.int.is_some()
1673 /// Returns `true` if this `#[repr()]` should inhibit struct field reordering
1674 /// optimizations, such as with `repr(C)`, `repr(packed(1))`, or `repr(<int>)`.
1675 pub fn inhibit_struct_field_reordering_opt(&self) -> bool {
1676 if let Some(pack) = self.pack {
1677 if pack.bytes() == 1 {
1681 self.flags.intersects(ReprFlags::IS_UNOPTIMISABLE) || self.int.is_some()
1684 /// Returns `true` if this `#[repr()]` should inhibit union ABI optimisations.
1685 pub fn inhibit_union_abi_opt(&self) -> bool {
1690 impl<'tcx> FieldDef {
1691 /// Returns the type of this field. The `subst` is typically obtained
1692 /// via the second field of `TyKind::AdtDef`.
1693 pub fn ty(&self, tcx: TyCtxt<'tcx>, subst: SubstsRef<'tcx>) -> Ty<'tcx> {
1694 tcx.type_of(self.did).subst(tcx, subst)
1698 /// Represents the various closure traits in the language. This
1699 /// will determine the type of the environment (`self`, in the
1700 /// desugaring) argument that the closure expects.
1702 /// You can get the environment type of a closure using
1703 /// `tcx.closure_env_ty()`.
1704 #[derive(Clone, Copy, PartialOrd, Ord, PartialEq, Eq, Hash, Debug, TyEncodable, TyDecodable)]
1705 #[derive(HashStable)]
1706 pub enum ClosureKind {
1707 // Warning: Ordering is significant here! The ordering is chosen
1708 // because the trait Fn is a subtrait of FnMut and so in turn, and
1709 // hence we order it so that Fn < FnMut < FnOnce.
1715 impl<'tcx> ClosureKind {
1716 // This is the initial value used when doing upvar inference.
1717 pub const LATTICE_BOTTOM: ClosureKind = ClosureKind::Fn;
1719 pub fn trait_did(&self, tcx: TyCtxt<'tcx>) -> DefId {
1721 ClosureKind::Fn => tcx.require_lang_item(LangItem::Fn, None),
1722 ClosureKind::FnMut => tcx.require_lang_item(LangItem::FnMut, None),
1723 ClosureKind::FnOnce => tcx.require_lang_item(LangItem::FnOnce, None),
1727 /// Returns `true` if a type that impls this closure kind
1728 /// must also implement `other`.
1729 pub fn extends(self, other: ty::ClosureKind) -> bool {
1732 (ClosureKind::Fn, ClosureKind::Fn)
1733 | (ClosureKind::Fn, ClosureKind::FnMut)
1734 | (ClosureKind::Fn, ClosureKind::FnOnce)
1735 | (ClosureKind::FnMut, ClosureKind::FnMut)
1736 | (ClosureKind::FnMut, ClosureKind::FnOnce)
1737 | (ClosureKind::FnOnce, ClosureKind::FnOnce)
1741 /// Returns the representative scalar type for this closure kind.
1742 /// See `TyS::to_opt_closure_kind` for more details.
1743 pub fn to_ty(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
1745 ty::ClosureKind::Fn => tcx.types.i8,
1746 ty::ClosureKind::FnMut => tcx.types.i16,
1747 ty::ClosureKind::FnOnce => tcx.types.i32,
1753 pub fn from_mutbl(m: hir::Mutability) -> BorrowKind {
1755 hir::Mutability::Mut => MutBorrow,
1756 hir::Mutability::Not => ImmBorrow,
1760 /// Returns a mutability `m` such that an `&m T` pointer could be used to obtain this borrow
1761 /// kind. Because borrow kinds are richer than mutabilities, we sometimes have to pick a
1762 /// mutability that is stronger than necessary so that it at least *would permit* the borrow in
1764 pub fn to_mutbl_lossy(self) -> hir::Mutability {
1766 MutBorrow => hir::Mutability::Mut,
1767 ImmBorrow => hir::Mutability::Not,
1769 // We have no type corresponding to a unique imm borrow, so
1770 // use `&mut`. It gives all the capabilities of an `&uniq`
1771 // and hence is a safe "over approximation".
1772 UniqueImmBorrow => hir::Mutability::Mut,
1776 pub fn to_user_str(&self) -> &'static str {
1778 MutBorrow => "mutable",
1779 ImmBorrow => "immutable",
1780 UniqueImmBorrow => "uniquely immutable",
1785 pub type Attributes<'tcx> = &'tcx [ast::Attribute];
1787 #[derive(Debug, PartialEq, Eq)]
1788 pub enum ImplOverlapKind {
1789 /// These impls are always allowed to overlap.
1791 /// Whether or not the impl is permitted due to the trait being a `#[marker]` trait
1794 /// These impls are allowed to overlap, but that raises
1795 /// an issue #33140 future-compatibility warning.
1797 /// Some background: in Rust 1.0, the trait-object types `Send + Sync` (today's
1798 /// `dyn Send + Sync`) and `Sync + Send` (now `dyn Sync + Send`) were different.
1800 /// The widely-used version 0.1.0 of the crate `traitobject` had accidentally relied
1801 /// that difference, making what reduces to the following set of impls:
1805 /// impl Trait for dyn Send + Sync {}
1806 /// impl Trait for dyn Sync + Send {}
1809 /// Obviously, once we made these types be identical, that code causes a coherence
1810 /// error and a fairly big headache for us. However, luckily for us, the trait
1811 /// `Trait` used in this case is basically a marker trait, and therefore having
1812 /// overlapping impls for it is sound.
1814 /// To handle this, we basically regard the trait as a marker trait, with an additional
1815 /// future-compatibility warning. To avoid accidentally "stabilizing" this feature,
1816 /// it has the following restrictions:
1818 /// 1. The trait must indeed be a marker-like trait (i.e., no items), and must be
1820 /// 2. The trait-ref of both impls must be equal.
1821 /// 3. The trait-ref of both impls must be a trait object type consisting only of
1823 /// 4. Neither of the impls can have any where-clauses.
1825 /// Once `traitobject` 0.1.0 is no longer an active concern, this hack can be removed.
1829 impl<'tcx> TyCtxt<'tcx> {
1830 pub fn typeck_body(self, body: hir::BodyId) -> &'tcx TypeckResults<'tcx> {
1831 self.typeck(self.hir().body_owner_def_id(body))
1834 /// Returns an iterator of the `DefId`s for all body-owners in this
1835 /// crate. If you would prefer to iterate over the bodies
1836 /// themselves, you can do `self.hir().krate().body_ids.iter()`.
1837 pub fn body_owners(self) -> impl Iterator<Item = LocalDefId> + Captures<'tcx> + 'tcx {
1842 .map(move |&body_id| self.hir().body_owner_def_id(body_id))
1845 pub fn par_body_owners<F: Fn(LocalDefId) + sync::Sync + sync::Send>(self, f: F) {
1846 par_iter(&self.hir().krate().body_ids)
1847 .for_each(|&body_id| f(self.hir().body_owner_def_id(body_id)));
1850 pub fn provided_trait_methods(self, id: DefId) -> impl 'tcx + Iterator<Item = &'tcx AssocItem> {
1851 self.associated_items(id)
1852 .in_definition_order()
1853 .filter(|item| item.kind == AssocKind::Fn && item.defaultness.has_value())
1856 fn item_name_from_hir(self, def_id: DefId) -> Option<Ident> {
1857 self.hir().get_if_local(def_id).and_then(|node| node.ident())
1860 fn item_name_from_def_id(self, def_id: DefId) -> Option<Symbol> {
1861 if def_id.index == CRATE_DEF_INDEX {
1862 Some(self.original_crate_name(def_id.krate))
1864 let def_key = self.def_key(def_id);
1865 match def_key.disambiguated_data.data {
1866 // The name of a constructor is that of its parent.
1867 rustc_hir::definitions::DefPathData::Ctor => self.item_name_from_def_id(DefId {
1868 krate: def_id.krate,
1869 index: def_key.parent.unwrap(),
1871 _ => def_key.disambiguated_data.data.get_opt_name(),
1876 /// Look up the name of an item across crates. This does not look at HIR.
1878 /// When possible, this function should be used for cross-crate lookups over
1879 /// [`opt_item_name`] to avoid invalidating the incremental cache. If you
1880 /// need to handle items without a name, or HIR items that will not be
1881 /// serialized cross-crate, or if you need the span of the item, use
1882 /// [`opt_item_name`] instead.
1884 /// [`opt_item_name`]: Self::opt_item_name
1885 pub fn item_name(self, id: DefId) -> Symbol {
1886 // Look at cross-crate items first to avoid invalidating the incremental cache
1887 // unless we have to.
1888 self.item_name_from_def_id(id).unwrap_or_else(|| {
1889 bug!("item_name: no name for {:?}", self.def_path(id));
1893 /// Look up the name and span of an item or [`Node`].
1895 /// See [`item_name`][Self::item_name] for more information.
1896 pub fn opt_item_name(self, def_id: DefId) -> Option<Ident> {
1897 // Look at the HIR first so the span will be correct if this is a local item.
1898 self.item_name_from_hir(def_id)
1899 .or_else(|| self.item_name_from_def_id(def_id).map(Ident::with_dummy_span))
1902 pub fn opt_associated_item(self, def_id: DefId) -> Option<&'tcx AssocItem> {
1903 if let DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy = self.def_kind(def_id) {
1904 Some(self.associated_item(def_id))
1910 pub fn field_index(self, hir_id: hir::HirId, typeck_results: &TypeckResults<'_>) -> usize {
1911 typeck_results.field_indices().get(hir_id).cloned().expect("no index for a field")
1914 pub fn find_field_index(self, ident: Ident, variant: &VariantDef) -> Option<usize> {
1915 variant.fields.iter().position(|field| self.hygienic_eq(ident, field.ident, variant.def_id))
1918 /// Returns `true` if the impls are the same polarity and the trait either
1919 /// has no items or is annotated `#[marker]` and prevents item overrides.
1920 pub fn impls_are_allowed_to_overlap(
1924 ) -> Option<ImplOverlapKind> {
1925 // If either trait impl references an error, they're allowed to overlap,
1926 // as one of them essentially doesn't exist.
1927 if self.impl_trait_ref(def_id1).map_or(false, |tr| tr.references_error())
1928 || self.impl_trait_ref(def_id2).map_or(false, |tr| tr.references_error())
1930 return Some(ImplOverlapKind::Permitted { marker: false });
1933 match (self.impl_polarity(def_id1), self.impl_polarity(def_id2)) {
1934 (ImplPolarity::Reservation, _) | (_, ImplPolarity::Reservation) => {
1935 // `#[rustc_reservation_impl]` impls don't overlap with anything
1937 "impls_are_allowed_to_overlap({:?}, {:?}) = Some(Permitted) (reservations)",
1940 return Some(ImplOverlapKind::Permitted { marker: false });
1942 (ImplPolarity::Positive, ImplPolarity::Negative)
1943 | (ImplPolarity::Negative, ImplPolarity::Positive) => {
1944 // `impl AutoTrait for Type` + `impl !AutoTrait for Type`
1946 "impls_are_allowed_to_overlap({:?}, {:?}) - None (differing polarities)",
1951 (ImplPolarity::Positive, ImplPolarity::Positive)
1952 | (ImplPolarity::Negative, ImplPolarity::Negative) => {}
1955 let is_marker_overlap = {
1956 let is_marker_impl = |def_id: DefId| -> bool {
1957 let trait_ref = self.impl_trait_ref(def_id);
1958 trait_ref.map_or(false, |tr| self.trait_def(tr.def_id).is_marker)
1960 is_marker_impl(def_id1) && is_marker_impl(def_id2)
1963 if is_marker_overlap {
1965 "impls_are_allowed_to_overlap({:?}, {:?}) = Some(Permitted) (marker overlap)",
1968 Some(ImplOverlapKind::Permitted { marker: true })
1970 if let Some(self_ty1) = self.issue33140_self_ty(def_id1) {
1971 if let Some(self_ty2) = self.issue33140_self_ty(def_id2) {
1972 if self_ty1 == self_ty2 {
1974 "impls_are_allowed_to_overlap({:?}, {:?}) - issue #33140 HACK",
1977 return Some(ImplOverlapKind::Issue33140);
1980 "impls_are_allowed_to_overlap({:?}, {:?}) - found {:?} != {:?}",
1981 def_id1, def_id2, self_ty1, self_ty2
1987 debug!("impls_are_allowed_to_overlap({:?}, {:?}) = None", def_id1, def_id2);
1992 /// Returns `ty::VariantDef` if `res` refers to a struct,
1993 /// or variant or their constructors, panics otherwise.
1994 pub fn expect_variant_res(self, res: Res) -> &'tcx VariantDef {
1996 Res::Def(DefKind::Variant, did) => {
1997 let enum_did = self.parent(did).unwrap();
1998 self.adt_def(enum_did).variant_with_id(did)
2000 Res::Def(DefKind::Struct | DefKind::Union, did) => self.adt_def(did).non_enum_variant(),
2001 Res::Def(DefKind::Ctor(CtorOf::Variant, ..), variant_ctor_did) => {
2002 let variant_did = self.parent(variant_ctor_did).unwrap();
2003 let enum_did = self.parent(variant_did).unwrap();
2004 self.adt_def(enum_did).variant_with_ctor_id(variant_ctor_did)
2006 Res::Def(DefKind::Ctor(CtorOf::Struct, ..), ctor_did) => {
2007 let struct_did = self.parent(ctor_did).expect("struct ctor has no parent");
2008 self.adt_def(struct_did).non_enum_variant()
2010 _ => bug!("expect_variant_res used with unexpected res {:?}", res),
2014 /// Returns the possibly-auto-generated MIR of a `(DefId, Subst)` pair.
2015 pub fn instance_mir(self, instance: ty::InstanceDef<'tcx>) -> &'tcx Body<'tcx> {
2017 ty::InstanceDef::Item(def) => match self.def_kind(def.did) {
2020 | DefKind::AssocConst
2022 | DefKind::AnonConst => self.mir_for_ctfe_opt_const_arg(def),
2023 // If the caller wants `mir_for_ctfe` of a function they should not be using
2024 // `instance_mir`, so we'll assume const fn also wants the optimized version.
2026 assert_eq!(def.const_param_did, None);
2027 self.optimized_mir(def.did)
2030 ty::InstanceDef::VtableShim(..)
2031 | ty::InstanceDef::ReifyShim(..)
2032 | ty::InstanceDef::Intrinsic(..)
2033 | ty::InstanceDef::FnPtrShim(..)
2034 | ty::InstanceDef::Virtual(..)
2035 | ty::InstanceDef::ClosureOnceShim { .. }
2036 | ty::InstanceDef::DropGlue(..)
2037 | ty::InstanceDef::CloneShim(..) => self.mir_shims(instance),
2041 /// Gets the attributes of a definition.
2042 pub fn get_attrs(self, did: DefId) -> Attributes<'tcx> {
2043 if let Some(did) = did.as_local() {
2044 self.hir().attrs(self.hir().local_def_id_to_hir_id(did))
2046 self.item_attrs(did)
2050 /// Determines whether an item is annotated with an attribute.
2051 pub fn has_attr(self, did: DefId, attr: Symbol) -> bool {
2052 self.sess.contains_name(&self.get_attrs(did), attr)
2055 /// Returns `true` if this is an `auto trait`.
2056 pub fn trait_is_auto(self, trait_def_id: DefId) -> bool {
2057 self.trait_def(trait_def_id).has_auto_impl
2060 /// Returns layout of a generator. Layout might be unavailable if the
2061 /// generator is tainted by errors.
2062 pub fn generator_layout(self, def_id: DefId) -> Option<&'tcx GeneratorLayout<'tcx>> {
2063 self.optimized_mir(def_id).generator_layout()
2066 /// Given the `DefId` of an impl, returns the `DefId` of the trait it implements.
2067 /// If it implements no trait, returns `None`.
2068 pub fn trait_id_of_impl(self, def_id: DefId) -> Option<DefId> {
2069 self.impl_trait_ref(def_id).map(|tr| tr.def_id)
2072 /// If the given defid describes a method belonging to an impl, returns the
2073 /// `DefId` of the impl that the method belongs to; otherwise, returns `None`.
2074 pub fn impl_of_method(self, def_id: DefId) -> Option<DefId> {
2075 self.opt_associated_item(def_id).and_then(|trait_item| match trait_item.container {
2076 TraitContainer(_) => None,
2077 ImplContainer(def_id) => Some(def_id),
2081 /// Looks up the span of `impl_did` if the impl is local; otherwise returns `Err`
2082 /// with the name of the crate containing the impl.
2083 pub fn span_of_impl(self, impl_did: DefId) -> Result<Span, Symbol> {
2084 if let Some(impl_did) = impl_did.as_local() {
2085 let hir_id = self.hir().local_def_id_to_hir_id(impl_did);
2086 Ok(self.hir().span(hir_id))
2088 Err(self.crate_name(impl_did.krate))
2092 /// Hygienically compares a use-site name (`use_name`) for a field or an associated item with
2093 /// its supposed definition name (`def_name`). The method also needs `DefId` of the supposed
2094 /// definition's parent/scope to perform comparison.
2095 pub fn hygienic_eq(self, use_name: Ident, def_name: Ident, def_parent_def_id: DefId) -> bool {
2096 // We could use `Ident::eq` here, but we deliberately don't. The name
2097 // comparison fails frequently, and we want to avoid the expensive
2098 // `normalize_to_macros_2_0()` calls required for the span comparison whenever possible.
2099 use_name.name == def_name.name
2103 .hygienic_eq(def_name.span.ctxt(), self.expansion_that_defined(def_parent_def_id))
2106 pub fn expansion_that_defined(self, scope: DefId) -> ExpnId {
2107 match scope.as_local() {
2108 // Parsing and expansion aren't incremental, so we don't
2109 // need to go through a query for the same-crate case.
2110 Some(scope) => self.hir().definitions().expansion_that_defined(scope),
2111 None => self.expn_that_defined(scope),
2115 pub fn adjust_ident(self, mut ident: Ident, scope: DefId) -> Ident {
2116 ident.span.normalize_to_macros_2_0_and_adjust(self.expansion_that_defined(scope));
2120 pub fn adjust_ident_and_get_scope(
2125 ) -> (Ident, DefId) {
2127 match ident.span.normalize_to_macros_2_0_and_adjust(self.expansion_that_defined(scope))
2129 Some(actual_expansion) => {
2130 self.hir().definitions().parent_module_of_macro_def(actual_expansion)
2132 None => self.parent_module(block).to_def_id(),
2137 pub fn is_object_safe(self, key: DefId) -> bool {
2138 self.object_safety_violations(key).is_empty()
2142 /// Yields the parent function's `DefId` if `def_id` is an `impl Trait` definition.
2143 pub fn is_impl_trait_defn(tcx: TyCtxt<'_>, def_id: DefId) -> Option<DefId> {
2144 if let Some(def_id) = def_id.as_local() {
2145 if let Node::Item(item) = tcx.hir().get(tcx.hir().local_def_id_to_hir_id(def_id)) {
2146 if let hir::ItemKind::OpaqueTy(ref opaque_ty) = item.kind {
2147 return opaque_ty.impl_trait_fn;
2154 pub fn int_ty(ity: ast::IntTy) -> IntTy {
2156 ast::IntTy::Isize => IntTy::Isize,
2157 ast::IntTy::I8 => IntTy::I8,
2158 ast::IntTy::I16 => IntTy::I16,
2159 ast::IntTy::I32 => IntTy::I32,
2160 ast::IntTy::I64 => IntTy::I64,
2161 ast::IntTy::I128 => IntTy::I128,
2165 pub fn uint_ty(uty: ast::UintTy) -> UintTy {
2167 ast::UintTy::Usize => UintTy::Usize,
2168 ast::UintTy::U8 => UintTy::U8,
2169 ast::UintTy::U16 => UintTy::U16,
2170 ast::UintTy::U32 => UintTy::U32,
2171 ast::UintTy::U64 => UintTy::U64,
2172 ast::UintTy::U128 => UintTy::U128,
2176 pub fn float_ty(fty: ast::FloatTy) -> FloatTy {
2178 ast::FloatTy::F32 => FloatTy::F32,
2179 ast::FloatTy::F64 => FloatTy::F64,
2183 pub fn ast_int_ty(ity: IntTy) -> ast::IntTy {
2185 IntTy::Isize => ast::IntTy::Isize,
2186 IntTy::I8 => ast::IntTy::I8,
2187 IntTy::I16 => ast::IntTy::I16,
2188 IntTy::I32 => ast::IntTy::I32,
2189 IntTy::I64 => ast::IntTy::I64,
2190 IntTy::I128 => ast::IntTy::I128,
2194 pub fn ast_uint_ty(uty: UintTy) -> ast::UintTy {
2196 UintTy::Usize => ast::UintTy::Usize,
2197 UintTy::U8 => ast::UintTy::U8,
2198 UintTy::U16 => ast::UintTy::U16,
2199 UintTy::U32 => ast::UintTy::U32,
2200 UintTy::U64 => ast::UintTy::U64,
2201 UintTy::U128 => ast::UintTy::U128,
2205 pub fn provide(providers: &mut ty::query::Providers) {
2206 context::provide(providers);
2207 erase_regions::provide(providers);
2208 layout::provide(providers);
2209 util::provide(providers);
2210 print::provide(providers);
2211 super::util::bug::provide(providers);
2212 *providers = ty::query::Providers {
2213 trait_impls_of: trait_def::trait_impls_of_provider,
2214 all_local_trait_impls: trait_def::all_local_trait_impls,
2215 type_uninhabited_from: inhabitedness::type_uninhabited_from,
2220 /// A map for the local crate mapping each type to a vector of its
2221 /// inherent impls. This is not meant to be used outside of coherence;
2222 /// rather, you should request the vector for a specific type via
2223 /// `tcx.inherent_impls(def_id)` so as to minimize your dependencies
2224 /// (constructing this map requires touching the entire crate).
2225 #[derive(Clone, Debug, Default, HashStable)]
2226 pub struct CrateInherentImpls {
2227 pub inherent_impls: DefIdMap<Vec<DefId>>,
2230 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, HashStable)]
2231 pub struct SymbolName<'tcx> {
2232 /// `&str` gives a consistent ordering, which ensures reproducible builds.
2233 pub name: &'tcx str,
2236 impl<'tcx> SymbolName<'tcx> {
2237 pub fn new(tcx: TyCtxt<'tcx>, name: &str) -> SymbolName<'tcx> {
2239 name: unsafe { str::from_utf8_unchecked(tcx.arena.alloc_slice(name.as_bytes())) },
2244 impl<'tcx> fmt::Display for SymbolName<'tcx> {
2245 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2246 fmt::Display::fmt(&self.name, fmt)
2250 impl<'tcx> fmt::Debug for SymbolName<'tcx> {
2251 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2252 fmt::Display::fmt(&self.name, fmt)