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};
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::{Constness, Node};
44 use rustc_macros::HashStable;
45 use rustc_span::hygiene::ExpnId;
46 use rustc_span::symbol::{kw, Ident, Symbol};
48 use rustc_target::abi::Align;
50 use std::cmp::Ordering;
51 use std::hash::{Hash, Hasher};
52 use std::ops::ControlFlow;
53 use std::{fmt, ptr, str};
55 pub use crate::ty::diagnostics::*;
56 pub use rustc_type_ir::InferTy::*;
57 pub use rustc_type_ir::*;
59 pub use self::binding::BindingMode;
60 pub use self::binding::BindingMode::*;
61 pub use self::consts::{Const, ConstInt, ConstKind, InferConst, ScalarInt};
62 pub use self::context::{
63 tls, CanonicalUserType, CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations,
64 CtxtInterners, DelaySpanBugEmitted, FreeRegionInfo, GeneratorInteriorTypeCause, GlobalCtxt,
65 Lift, ResolvedOpaqueTy, TyCtxt, TypeckResults, UserType, UserTypeAnnotationIndex,
67 pub use self::instance::{Instance, InstanceDef};
68 pub use self::list::List;
69 pub use self::sty::BoundRegionKind::*;
70 pub use self::sty::RegionKind::*;
71 pub use self::sty::TyKind::*;
73 Binder, BoundRegion, BoundRegionKind, BoundTy, BoundTyKind, BoundVar, CanonicalPolyFnSig,
74 ClosureSubsts, ClosureSubstsParts, ConstVid, EarlyBoundRegion, ExistentialPredicate,
75 ExistentialProjection, ExistentialTraitRef, FnSig, FreeRegion, GenSig, GeneratorSubsts,
76 GeneratorSubstsParts, ParamConst, ParamTy, PolyExistentialProjection, PolyExistentialTraitRef,
77 PolyFnSig, PolyGenSig, PolyTraitRef, ProjectionTy, Region, RegionKind, RegionVid, TraitRef,
78 TyKind, TypeAndMut, UpvarSubsts,
80 pub use self::trait_def::TraitDef;
91 pub mod inhabitedness;
93 pub mod normalize_erasing_regions;
113 mod structural_impls;
118 pub struct ResolverOutputs {
119 pub definitions: rustc_hir::definitions::Definitions,
120 pub cstore: Box<CrateStoreDyn>,
121 pub visibilities: FxHashMap<LocalDefId, Visibility>,
122 pub extern_crate_map: FxHashMap<LocalDefId, CrateNum>,
123 pub maybe_unused_trait_imports: FxHashSet<LocalDefId>,
124 pub maybe_unused_extern_crates: Vec<(LocalDefId, Span)>,
125 pub export_map: ExportMap<LocalDefId>,
126 pub glob_map: FxHashMap<LocalDefId, FxHashSet<Symbol>>,
127 /// Extern prelude entries. The value is `true` if the entry was introduced
128 /// via `extern crate` item and not `--extern` option or compiler built-in.
129 pub extern_prelude: FxHashMap<Symbol, bool>,
132 /// The "header" of an impl is everything outside the body: a Self type, a trait
133 /// ref (in the case of a trait impl), and a set of predicates (from the
134 /// bounds / where-clauses).
135 #[derive(Clone, Debug, TypeFoldable)]
136 pub struct ImplHeader<'tcx> {
137 pub impl_def_id: DefId,
138 pub self_ty: Ty<'tcx>,
139 pub trait_ref: Option<TraitRef<'tcx>>,
140 pub predicates: Vec<Predicate<'tcx>>,
143 #[derive(Copy, Clone, PartialEq, TyEncodable, TyDecodable, HashStable, Debug)]
144 pub enum ImplPolarity {
145 /// `impl Trait for Type`
147 /// `impl !Trait for Type`
149 /// `#[rustc_reservation_impl] impl Trait for Type`
151 /// This is a "stability hack", not a real Rust feature.
152 /// See #64631 for details.
156 #[derive(Clone, Debug, PartialEq, Eq, Copy, Hash, TyEncodable, TyDecodable, HashStable)]
157 pub enum Visibility {
158 /// Visible everywhere (including in other crates).
160 /// Visible only in the given crate-local module.
162 /// Not visible anywhere in the local crate. This is the visibility of private external items.
166 pub trait DefIdTree: Copy {
167 fn parent(self, id: DefId) -> Option<DefId>;
169 fn is_descendant_of(self, mut descendant: DefId, ancestor: DefId) -> bool {
170 if descendant.krate != ancestor.krate {
174 while descendant != ancestor {
175 match self.parent(descendant) {
176 Some(parent) => descendant = parent,
177 None => return false,
184 impl<'tcx> DefIdTree for TyCtxt<'tcx> {
185 fn parent(self, id: DefId) -> Option<DefId> {
186 self.def_key(id).parent.map(|index| DefId { index, ..id })
191 pub fn from_hir(visibility: &hir::Visibility<'_>, id: hir::HirId, tcx: TyCtxt<'_>) -> Self {
192 match visibility.node {
193 hir::VisibilityKind::Public => Visibility::Public,
194 hir::VisibilityKind::Crate(_) => Visibility::Restricted(DefId::local(CRATE_DEF_INDEX)),
195 hir::VisibilityKind::Restricted { ref path, .. } => match path.res {
196 // If there is no resolution, `resolve` will have already reported an error, so
197 // assume that the visibility is public to avoid reporting more privacy errors.
198 Res::Err => Visibility::Public,
199 def => Visibility::Restricted(def.def_id()),
201 hir::VisibilityKind::Inherited => {
202 Visibility::Restricted(tcx.parent_module(id).to_def_id())
207 /// Returns `true` if an item with this visibility is accessible from the given block.
208 pub fn is_accessible_from<T: DefIdTree>(self, module: DefId, tree: T) -> bool {
209 let restriction = match self {
210 // Public items are visible everywhere.
211 Visibility::Public => return true,
212 // Private items from other crates are visible nowhere.
213 Visibility::Invisible => return false,
214 // Restricted items are visible in an arbitrary local module.
215 Visibility::Restricted(other) if other.krate != module.krate => return false,
216 Visibility::Restricted(module) => module,
219 tree.is_descendant_of(module, restriction)
222 /// Returns `true` if this visibility is at least as accessible as the given visibility
223 pub fn is_at_least<T: DefIdTree>(self, vis: Visibility, tree: T) -> bool {
224 let vis_restriction = match vis {
225 Visibility::Public => return self == Visibility::Public,
226 Visibility::Invisible => return true,
227 Visibility::Restricted(module) => module,
230 self.is_accessible_from(vis_restriction, tree)
233 // Returns `true` if this item is visible anywhere in the local crate.
234 pub fn is_visible_locally(self) -> bool {
236 Visibility::Public => true,
237 Visibility::Restricted(def_id) => def_id.is_local(),
238 Visibility::Invisible => false,
243 /// The crate variances map is computed during typeck and contains the
244 /// variance of every item in the local crate. You should not use it
245 /// directly, because to do so will make your pass dependent on the
246 /// HIR of every item in the local crate. Instead, use
247 /// `tcx.variances_of()` to get the variance for a *particular*
249 #[derive(HashStable, Debug)]
250 pub struct CrateVariancesMap<'tcx> {
251 /// For each item with generics, maps to a vector of the variance
252 /// of its generics. If an item has no generics, it will have no
254 pub variances: FxHashMap<DefId, &'tcx [ty::Variance]>,
257 // Contains information needed to resolve types and (in the future) look up
258 // the types of AST nodes.
259 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
260 pub struct CReaderCacheKey {
265 #[allow(rustc::usage_of_ty_tykind)]
266 pub struct TyS<'tcx> {
267 /// This field shouldn't be used directly and may be removed in the future.
268 /// Use `TyS::kind()` instead.
270 /// This field shouldn't be used directly and may be removed in the future.
271 /// Use `TyS::flags()` instead.
274 /// This is a kind of confusing thing: it stores the smallest
277 /// (a) the binder itself captures nothing but
278 /// (b) all the late-bound things within the type are captured
279 /// by some sub-binder.
281 /// So, for a type without any late-bound things, like `u32`, this
282 /// will be *innermost*, because that is the innermost binder that
283 /// captures nothing. But for a type `&'D u32`, where `'D` is a
284 /// late-bound region with De Bruijn index `D`, this would be `D + 1`
285 /// -- the binder itself does not capture `D`, but `D` is captured
286 /// by an inner binder.
288 /// We call this concept an "exclusive" binder `D` because all
289 /// De Bruijn indices within the type are contained within `0..D`
291 outer_exclusive_binder: ty::DebruijnIndex,
294 impl<'tcx> TyS<'tcx> {
295 /// A constructor used only for internal testing.
296 #[allow(rustc::usage_of_ty_tykind)]
297 pub fn make_for_test(
300 outer_exclusive_binder: ty::DebruijnIndex,
302 TyS { kind, flags, outer_exclusive_binder }
306 // `TyS` is used a lot. Make sure it doesn't unintentionally get bigger.
307 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
308 static_assert_size!(TyS<'_>, 32);
310 impl<'tcx> Ord for TyS<'tcx> {
311 fn cmp(&self, other: &TyS<'tcx>) -> Ordering {
312 self.kind().cmp(other.kind())
316 impl<'tcx> PartialOrd for TyS<'tcx> {
317 fn partial_cmp(&self, other: &TyS<'tcx>) -> Option<Ordering> {
318 Some(self.kind().cmp(other.kind()))
322 impl<'tcx> PartialEq for TyS<'tcx> {
324 fn eq(&self, other: &TyS<'tcx>) -> bool {
328 impl<'tcx> Eq for TyS<'tcx> {}
330 impl<'tcx> Hash for TyS<'tcx> {
331 fn hash<H: Hasher>(&self, s: &mut H) {
332 (self as *const TyS<'_>).hash(s)
336 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for TyS<'tcx> {
337 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
341 // The other fields just provide fast access to information that is
342 // also contained in `kind`, so no need to hash them.
345 outer_exclusive_binder: _,
348 kind.hash_stable(hcx, hasher);
352 #[rustc_diagnostic_item = "Ty"]
353 pub type Ty<'tcx> = &'tcx TyS<'tcx>;
355 #[derive(Clone, PartialEq, Debug, TyEncodable, TyDecodable, TypeFoldable, Copy, HashStable)]
356 pub enum BorrowKind {
357 /// Data must be immutable and is aliasable.
360 /// Data must be immutable but not aliasable. This kind of borrow
361 /// cannot currently be expressed by the user and is used only in
362 /// implicit closure bindings. It is needed when the closure
363 /// is borrowing or mutating a mutable referent, e.g.:
366 /// let x: &mut isize = ...;
367 /// let y = || *x += 5;
370 /// If we were to try to translate this closure into a more explicit
371 /// form, we'd encounter an error with the code as written:
374 /// struct Env { x: & &mut isize }
375 /// let x: &mut isize = ...;
376 /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
377 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
380 /// This is then illegal because you cannot mutate a `&mut` found
381 /// in an aliasable location. To solve, you'd have to translate with
382 /// an `&mut` borrow:
385 /// struct Env { x: & &mut isize }
386 /// let x: &mut isize = ...;
387 /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
388 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
391 /// Now the assignment to `**env.x` is legal, but creating a
392 /// mutable pointer to `x` is not because `x` is not mutable. We
393 /// could fix this by declaring `x` as `let mut x`. This is ok in
394 /// user code, if awkward, but extra weird for closures, since the
395 /// borrow is hidden.
397 /// So we introduce a "unique imm" borrow -- the referent is
398 /// immutable, but not aliasable. This solves the problem. For
399 /// simplicity, we don't give users the way to express this
400 /// borrow, it's just used when translating closures.
403 /// Data is mutable and not aliasable.
407 pub fn place_to_string_for_capture(tcx: TyCtxt<'tcx>, place: &HirPlace<'tcx>) -> String {
408 let name = match place.base {
409 HirPlaceBase::Upvar(upvar_id) => tcx.hir().name(upvar_id.var_path.hir_id).to_string(),
410 _ => bug!("Capture_information should only contain upvars"),
412 let mut curr_string = name;
414 for (i, proj) in place.projections.iter().enumerate() {
416 HirProjectionKind::Deref => {
417 curr_string = format!("*{}", curr_string);
419 HirProjectionKind::Field(idx, variant) => match place.ty_before_projection(i).kind() {
420 ty::Adt(def, ..) => {
421 curr_string = format!(
424 def.variants[variant].fields[idx as usize].ident.name.as_str()
428 curr_string = format!("{}.{}", curr_string, idx);
432 "Field projection applied to a type other than Adt or Tuple: {:?}.",
433 place.ty_before_projection(i).kind()
437 proj => bug!("{:?} unexpected because it isn't captured", proj),
441 curr_string.to_string()
444 /// Part of `MinCaptureInformationMap`; describes the capture kind (&, &mut, move)
445 /// for a particular capture as well as identifying the part of the source code
446 /// that triggered this capture to occur.
447 #[derive(PartialEq, Clone, Debug, Copy, TyEncodable, TyDecodable, TypeFoldable, HashStable)]
448 pub struct CaptureInfo<'tcx> {
449 /// Expr Id pointing to use that resulted in selecting the current capture kind
453 /// let mut t = (0,1);
456 /// println!("{}",t); // L1
460 /// `capture_kind_expr_id` will point to the use on L2 and `path_expr_id` will point to the
463 /// If the user doesn't enable feature `capture_disjoint_fields` (RFC 2229) then, it is
464 /// possible that we don't see the use of a particular place resulting in capture_kind_expr_id being
465 /// None. In such case we fallback on uvpars_mentioned for span.
476 /// In this example, if `capture_disjoint_fields` is **not** set, then x will be captured,
477 /// but we won't see it being used during capture analysis, since it's essentially a discard.
478 pub capture_kind_expr_id: Option<hir::HirId>,
479 /// Expr Id pointing to use that resulted the corresponding place being captured
481 /// See `capture_kind_expr_id` for example.
483 pub path_expr_id: Option<hir::HirId>,
485 /// Capture mode that was selected
486 pub capture_kind: UpvarCapture<'tcx>,
489 impl ty::EarlyBoundRegion {
490 /// Does this early bound region have a name? Early bound regions normally
491 /// always have names except when using anonymous lifetimes (`'_`).
492 pub fn has_name(&self) -> bool {
493 self.name != kw::UnderscoreLifetime
498 crate struct PredicateInner<'tcx> {
499 kind: Binder<PredicateKind<'tcx>>,
501 /// See the comment for the corresponding field of [TyS].
502 outer_exclusive_binder: ty::DebruijnIndex,
505 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
506 static_assert_size!(PredicateInner<'_>, 40);
508 #[derive(Clone, Copy, Lift)]
509 pub struct Predicate<'tcx> {
510 inner: &'tcx PredicateInner<'tcx>,
513 impl<'tcx> PartialEq for Predicate<'tcx> {
514 fn eq(&self, other: &Self) -> bool {
515 // `self.kind` is always interned.
516 ptr::eq(self.inner, other.inner)
520 impl Hash for Predicate<'_> {
521 fn hash<H: Hasher>(&self, s: &mut H) {
522 (self.inner as *const PredicateInner<'_>).hash(s)
526 impl<'tcx> Eq for Predicate<'tcx> {}
528 impl<'tcx> Predicate<'tcx> {
529 /// Gets the inner `Binder<PredicateKind<'tcx>>`.
531 pub fn kind(self) -> Binder<PredicateKind<'tcx>> {
536 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for Predicate<'tcx> {
537 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
541 // The other fields just provide fast access to information that is
542 // also contained in `kind`, so no need to hash them.
544 outer_exclusive_binder: _,
547 kind.hash_stable(hcx, hasher);
551 #[derive(Clone, Copy, PartialEq, Eq, Hash, TyEncodable, TyDecodable)]
552 #[derive(HashStable, TypeFoldable)]
553 pub enum PredicateKind<'tcx> {
554 /// Corresponds to `where Foo: Bar<A, B, C>`. `Foo` here would be
555 /// the `Self` type of the trait reference and `A`, `B`, and `C`
556 /// would be the type parameters.
558 /// A trait predicate will have `Constness::Const` if it originates
559 /// from a bound on a `const fn` without the `?const` opt-out (e.g.,
560 /// `const fn foobar<Foo: Bar>() {}`).
561 Trait(TraitPredicate<'tcx>, Constness),
564 RegionOutlives(RegionOutlivesPredicate<'tcx>),
567 TypeOutlives(TypeOutlivesPredicate<'tcx>),
569 /// `where <T as TraitRef>::Name == X`, approximately.
570 /// See the `ProjectionPredicate` struct for details.
571 Projection(ProjectionPredicate<'tcx>),
573 /// No syntax: `T` well-formed.
574 WellFormed(GenericArg<'tcx>),
576 /// Trait must be object-safe.
579 /// No direct syntax. May be thought of as `where T: FnFoo<...>`
580 /// for some substitutions `...` and `T` being a closure type.
581 /// Satisfied (or refuted) once we know the closure's kind.
582 ClosureKind(DefId, SubstsRef<'tcx>, ClosureKind),
585 Subtype(SubtypePredicate<'tcx>),
587 /// Constant initializer must evaluate successfully.
588 ConstEvaluatable(ty::WithOptConstParam<DefId>, SubstsRef<'tcx>),
590 /// Constants must be equal. The first component is the const that is expected.
591 ConstEquate(&'tcx Const<'tcx>, &'tcx Const<'tcx>),
593 /// Represents a type found in the environment that we can use for implied bounds.
595 /// Only used for Chalk.
596 TypeWellFormedFromEnv(Ty<'tcx>),
599 /// The crate outlives map is computed during typeck and contains the
600 /// outlives of every item in the local crate. You should not use it
601 /// directly, because to do so will make your pass dependent on the
602 /// HIR of every item in the local crate. Instead, use
603 /// `tcx.inferred_outlives_of()` to get the outlives for a *particular*
605 #[derive(HashStable, Debug)]
606 pub struct CratePredicatesMap<'tcx> {
607 /// For each struct with outlive bounds, maps to a vector of the
608 /// predicate of its outlive bounds. If an item has no outlives
609 /// bounds, it will have no entry.
610 pub predicates: FxHashMap<DefId, &'tcx [(Predicate<'tcx>, Span)]>,
613 impl<'tcx> Predicate<'tcx> {
614 /// Performs a substitution suitable for going from a
615 /// poly-trait-ref to supertraits that must hold if that
616 /// poly-trait-ref holds. This is slightly different from a normal
617 /// substitution in terms of what happens with bound regions. See
618 /// lengthy comment below for details.
619 pub fn subst_supertrait(
622 trait_ref: &ty::PolyTraitRef<'tcx>,
623 ) -> Predicate<'tcx> {
624 // The interaction between HRTB and supertraits is not entirely
625 // obvious. Let me walk you (and myself) through an example.
627 // Let's start with an easy case. Consider two traits:
629 // trait Foo<'a>: Bar<'a,'a> { }
630 // trait Bar<'b,'c> { }
632 // Now, if we have a trait reference `for<'x> T: Foo<'x>`, then
633 // we can deduce that `for<'x> T: Bar<'x,'x>`. Basically, if we
634 // knew that `Foo<'x>` (for any 'x) then we also know that
635 // `Bar<'x,'x>` (for any 'x). This more-or-less falls out from
636 // normal substitution.
638 // In terms of why this is sound, the idea is that whenever there
639 // is an impl of `T:Foo<'a>`, it must show that `T:Bar<'a,'a>`
640 // holds. So if there is an impl of `T:Foo<'a>` that applies to
641 // all `'a`, then we must know that `T:Bar<'a,'a>` holds for all
644 // Another example to be careful of is this:
646 // trait Foo1<'a>: for<'b> Bar1<'a,'b> { }
647 // trait Bar1<'b,'c> { }
649 // Here, if we have `for<'x> T: Foo1<'x>`, then what do we know?
650 // The answer is that we know `for<'x,'b> T: Bar1<'x,'b>`. The
651 // reason is similar to the previous example: any impl of
652 // `T:Foo1<'x>` must show that `for<'b> T: Bar1<'x, 'b>`. So
653 // basically we would want to collapse the bound lifetimes from
654 // the input (`trait_ref`) and the supertraits.
656 // To achieve this in practice is fairly straightforward. Let's
657 // consider the more complicated scenario:
659 // - We start out with `for<'x> T: Foo1<'x>`. In this case, `'x`
660 // has a De Bruijn index of 1. We want to produce `for<'x,'b> T: Bar1<'x,'b>`,
661 // where both `'x` and `'b` would have a DB index of 1.
662 // The substitution from the input trait-ref is therefore going to be
663 // `'a => 'x` (where `'x` has a DB index of 1).
664 // - The super-trait-ref is `for<'b> Bar1<'a,'b>`, where `'a` is an
665 // early-bound parameter and `'b' is a late-bound parameter with a
667 // - If we replace `'a` with `'x` from the input, it too will have
668 // a DB index of 1, and thus we'll have `for<'x,'b> Bar1<'x,'b>`
669 // just as we wanted.
671 // There is only one catch. If we just apply the substitution `'a
672 // => 'x` to `for<'b> Bar1<'a,'b>`, the substitution code will
673 // adjust the DB index because we substituting into a binder (it
674 // tries to be so smart...) resulting in `for<'x> for<'b>
675 // Bar1<'x,'b>` (we have no syntax for this, so use your
676 // imagination). Basically the 'x will have DB index of 2 and 'b
677 // will have DB index of 1. Not quite what we want. So we apply
678 // the substitution to the *contents* of the trait reference,
679 // rather than the trait reference itself (put another way, the
680 // substitution code expects equal binding levels in the values
681 // from the substitution and the value being substituted into, and
682 // this trick achieves that).
683 let substs = trait_ref.skip_binder().substs;
684 let pred = self.kind().skip_binder();
685 let new = pred.subst(tcx, substs);
686 tcx.reuse_or_mk_predicate(self, ty::Binder::bind(new))
690 #[derive(Clone, Copy, PartialEq, Eq, Hash, TyEncodable, TyDecodable)]
691 #[derive(HashStable, TypeFoldable)]
692 pub struct TraitPredicate<'tcx> {
693 pub trait_ref: TraitRef<'tcx>,
696 pub type PolyTraitPredicate<'tcx> = ty::Binder<TraitPredicate<'tcx>>;
698 impl<'tcx> TraitPredicate<'tcx> {
699 pub fn def_id(self) -> DefId {
700 self.trait_ref.def_id
703 pub fn self_ty(self) -> Ty<'tcx> {
704 self.trait_ref.self_ty()
708 impl<'tcx> PolyTraitPredicate<'tcx> {
709 pub fn def_id(self) -> DefId {
710 // Ok to skip binder since trait `DefId` does not care about regions.
711 self.skip_binder().def_id()
714 pub fn self_ty(self) -> ty::Binder<Ty<'tcx>> {
715 self.map_bound(|trait_ref| trait_ref.self_ty())
719 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, TyEncodable, TyDecodable)]
720 #[derive(HashStable, TypeFoldable)]
721 pub struct OutlivesPredicate<A, B>(pub A, pub B); // `A: B`
722 pub type RegionOutlivesPredicate<'tcx> = OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>;
723 pub type TypeOutlivesPredicate<'tcx> = OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>;
724 pub type PolyRegionOutlivesPredicate<'tcx> = ty::Binder<RegionOutlivesPredicate<'tcx>>;
725 pub type PolyTypeOutlivesPredicate<'tcx> = ty::Binder<TypeOutlivesPredicate<'tcx>>;
727 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, TyEncodable, TyDecodable)]
728 #[derive(HashStable, TypeFoldable)]
729 pub struct SubtypePredicate<'tcx> {
730 pub a_is_expected: bool,
734 pub type PolySubtypePredicate<'tcx> = ty::Binder<SubtypePredicate<'tcx>>;
736 /// This kind of predicate has no *direct* correspondent in the
737 /// syntax, but it roughly corresponds to the syntactic forms:
739 /// 1. `T: TraitRef<..., Item = Type>`
740 /// 2. `<T as TraitRef<...>>::Item == Type` (NYI)
742 /// In particular, form #1 is "desugared" to the combination of a
743 /// normal trait predicate (`T: TraitRef<...>`) and one of these
744 /// predicates. Form #2 is a broader form in that it also permits
745 /// equality between arbitrary types. Processing an instance of
746 /// Form #2 eventually yields one of these `ProjectionPredicate`
747 /// instances to normalize the LHS.
748 #[derive(Copy, Clone, PartialEq, Eq, Hash, TyEncodable, TyDecodable)]
749 #[derive(HashStable, TypeFoldable)]
750 pub struct ProjectionPredicate<'tcx> {
751 pub projection_ty: ProjectionTy<'tcx>,
755 pub type PolyProjectionPredicate<'tcx> = Binder<ProjectionPredicate<'tcx>>;
757 impl<'tcx> PolyProjectionPredicate<'tcx> {
758 /// Returns the `DefId` of the associated item being projected.
759 pub fn item_def_id(&self) -> DefId {
760 self.skip_binder().projection_ty.item_def_id
763 /// Returns the `DefId` of the trait of the associated item being projected.
765 pub fn trait_def_id(&self, tcx: TyCtxt<'tcx>) -> DefId {
766 self.skip_binder().projection_ty.trait_def_id(tcx)
770 pub fn projection_self_ty(&self) -> Binder<Ty<'tcx>> {
771 self.map_bound(|predicate| predicate.projection_ty.self_ty())
774 /// Get the [PolyTraitRef] required for this projection to be well formed.
775 /// Note that for generic associated types the predicates of the associated
776 /// type also need to be checked.
778 pub fn required_poly_trait_ref(&self, tcx: TyCtxt<'tcx>) -> PolyTraitRef<'tcx> {
779 // Note: unlike with `TraitRef::to_poly_trait_ref()`,
780 // `self.0.trait_ref` is permitted to have escaping regions.
781 // This is because here `self` has a `Binder` and so does our
782 // return value, so we are preserving the number of binding
784 self.map_bound(|predicate| predicate.projection_ty.trait_ref(tcx))
787 pub fn ty(&self) -> Binder<Ty<'tcx>> {
788 self.map_bound(|predicate| predicate.ty)
791 /// The `DefId` of the `TraitItem` for the associated type.
793 /// Note that this is not the `DefId` of the `TraitRef` containing this
794 /// associated type, which is in `tcx.associated_item(projection_def_id()).container`.
795 pub fn projection_def_id(&self) -> DefId {
796 // Ok to skip binder since trait `DefId` does not care about regions.
797 self.skip_binder().projection_ty.item_def_id
801 pub trait ToPolyTraitRef<'tcx> {
802 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx>;
805 impl<'tcx> ToPolyTraitRef<'tcx> for TraitRef<'tcx> {
806 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
807 ty::Binder::dummy(*self)
811 impl<'tcx> ToPolyTraitRef<'tcx> for PolyTraitPredicate<'tcx> {
812 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
813 self.map_bound_ref(|trait_pred| trait_pred.trait_ref)
817 pub trait ToPredicate<'tcx> {
818 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx>;
821 impl ToPredicate<'tcx> for Binder<PredicateKind<'tcx>> {
823 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
824 tcx.mk_predicate(self)
828 impl ToPredicate<'tcx> for PredicateKind<'tcx> {
830 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
831 tcx.mk_predicate(Binder::dummy(self))
835 impl<'tcx> ToPredicate<'tcx> for ConstnessAnd<TraitRef<'tcx>> {
836 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
837 PredicateKind::Trait(ty::TraitPredicate { trait_ref: self.value }, self.constness)
842 impl<'tcx> ToPredicate<'tcx> for ConstnessAnd<PolyTraitRef<'tcx>> {
843 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
845 value: self.value.map_bound(|trait_ref| ty::TraitPredicate { trait_ref }),
846 constness: self.constness,
852 impl<'tcx> ToPredicate<'tcx> for ConstnessAnd<PolyTraitPredicate<'tcx>> {
853 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
854 self.value.map_bound(|value| PredicateKind::Trait(value, self.constness)).to_predicate(tcx)
858 impl<'tcx> ToPredicate<'tcx> for PolyRegionOutlivesPredicate<'tcx> {
859 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
860 self.map_bound(PredicateKind::RegionOutlives).to_predicate(tcx)
864 impl<'tcx> ToPredicate<'tcx> for PolyTypeOutlivesPredicate<'tcx> {
865 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
866 self.map_bound(PredicateKind::TypeOutlives).to_predicate(tcx)
870 impl<'tcx> ToPredicate<'tcx> for PolyProjectionPredicate<'tcx> {
871 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
872 self.map_bound(PredicateKind::Projection).to_predicate(tcx)
876 impl<'tcx> Predicate<'tcx> {
877 pub fn to_opt_poly_trait_ref(self) -> Option<ConstnessAnd<PolyTraitRef<'tcx>>> {
878 let predicate = self.kind();
879 match predicate.skip_binder() {
880 PredicateKind::Trait(t, constness) => {
881 Some(ConstnessAnd { constness, value: predicate.rebind(t.trait_ref) })
883 PredicateKind::Projection(..)
884 | PredicateKind::Subtype(..)
885 | PredicateKind::RegionOutlives(..)
886 | PredicateKind::WellFormed(..)
887 | PredicateKind::ObjectSafe(..)
888 | PredicateKind::ClosureKind(..)
889 | PredicateKind::TypeOutlives(..)
890 | PredicateKind::ConstEvaluatable(..)
891 | PredicateKind::ConstEquate(..)
892 | PredicateKind::TypeWellFormedFromEnv(..) => None,
896 pub fn to_opt_type_outlives(self) -> Option<PolyTypeOutlivesPredicate<'tcx>> {
897 let predicate = self.kind();
898 match predicate.skip_binder() {
899 PredicateKind::TypeOutlives(data) => Some(predicate.rebind(data)),
900 PredicateKind::Trait(..)
901 | PredicateKind::Projection(..)
902 | PredicateKind::Subtype(..)
903 | PredicateKind::RegionOutlives(..)
904 | PredicateKind::WellFormed(..)
905 | PredicateKind::ObjectSafe(..)
906 | PredicateKind::ClosureKind(..)
907 | PredicateKind::ConstEvaluatable(..)
908 | PredicateKind::ConstEquate(..)
909 | PredicateKind::TypeWellFormedFromEnv(..) => None,
914 /// Represents the bounds declared on a particular set of type
915 /// parameters. Should eventually be generalized into a flag list of
916 /// where-clauses. You can obtain a `InstantiatedPredicates` list from a
917 /// `GenericPredicates` by using the `instantiate` method. Note that this method
918 /// reflects an important semantic invariant of `InstantiatedPredicates`: while
919 /// the `GenericPredicates` are expressed in terms of the bound type
920 /// parameters of the impl/trait/whatever, an `InstantiatedPredicates` instance
921 /// represented a set of bounds for some particular instantiation,
922 /// meaning that the generic parameters have been substituted with
927 /// struct Foo<T, U: Bar<T>> { ... }
929 /// Here, the `GenericPredicates` for `Foo` would contain a list of bounds like
930 /// `[[], [U:Bar<T>]]`. Now if there were some particular reference
931 /// like `Foo<isize,usize>`, then the `InstantiatedPredicates` would be `[[],
932 /// [usize:Bar<isize>]]`.
933 #[derive(Clone, Debug, TypeFoldable)]
934 pub struct InstantiatedPredicates<'tcx> {
935 pub predicates: Vec<Predicate<'tcx>>,
936 pub spans: Vec<Span>,
939 impl<'tcx> InstantiatedPredicates<'tcx> {
940 pub fn empty() -> InstantiatedPredicates<'tcx> {
941 InstantiatedPredicates { predicates: vec![], spans: vec![] }
944 pub fn is_empty(&self) -> bool {
945 self.predicates.is_empty()
949 rustc_index::newtype_index! {
950 /// "Universes" are used during type- and trait-checking in the
951 /// presence of `for<..>` binders to control what sets of names are
952 /// visible. Universes are arranged into a tree: the root universe
953 /// contains names that are always visible. Each child then adds a new
954 /// set of names that are visible, in addition to those of its parent.
955 /// We say that the child universe "extends" the parent universe with
958 /// To make this more concrete, consider this program:
962 /// fn bar<T>(x: T) {
963 /// let y: for<'a> fn(&'a u8, Foo) = ...;
967 /// The struct name `Foo` is in the root universe U0. But the type
968 /// parameter `T`, introduced on `bar`, is in an extended universe U1
969 /// -- i.e., within `bar`, we can name both `T` and `Foo`, but outside
970 /// of `bar`, we cannot name `T`. Then, within the type of `y`, the
971 /// region `'a` is in a universe U2 that extends U1, because we can
972 /// name it inside the fn type but not outside.
974 /// Universes are used to do type- and trait-checking around these
975 /// "forall" binders (also called **universal quantification**). The
976 /// idea is that when, in the body of `bar`, we refer to `T` as a
977 /// type, we aren't referring to any type in particular, but rather a
978 /// kind of "fresh" type that is distinct from all other types we have
979 /// actually declared. This is called a **placeholder** type, and we
980 /// use universes to talk about this. In other words, a type name in
981 /// universe 0 always corresponds to some "ground" type that the user
982 /// declared, but a type name in a non-zero universe is a placeholder
983 /// type -- an idealized representative of "types in general" that we
984 /// use for checking generic functions.
985 pub struct UniverseIndex {
987 DEBUG_FORMAT = "U{}",
992 pub const ROOT: UniverseIndex = UniverseIndex::from_u32(0);
994 /// Returns the "next" universe index in order -- this new index
995 /// is considered to extend all previous universes. This
996 /// corresponds to entering a `forall` quantifier. So, for
997 /// example, suppose we have this type in universe `U`:
1000 /// for<'a> fn(&'a u32)
1003 /// Once we "enter" into this `for<'a>` quantifier, we are in a
1004 /// new universe that extends `U` -- in this new universe, we can
1005 /// name the region `'a`, but that region was not nameable from
1006 /// `U` because it was not in scope there.
1007 pub fn next_universe(self) -> UniverseIndex {
1008 UniverseIndex::from_u32(self.private.checked_add(1).unwrap())
1011 /// Returns `true` if `self` can name a name from `other` -- in other words,
1012 /// if the set of names in `self` is a superset of those in
1013 /// `other` (`self >= other`).
1014 pub fn can_name(self, other: UniverseIndex) -> bool {
1015 self.private >= other.private
1018 /// Returns `true` if `self` cannot name some names from `other` -- in other
1019 /// words, if the set of names in `self` is a strict subset of
1020 /// those in `other` (`self < other`).
1021 pub fn cannot_name(self, other: UniverseIndex) -> bool {
1022 self.private < other.private
1026 /// The "placeholder index" fully defines a placeholder region, type, or const. Placeholders are
1027 /// identified by both a universe, as well as a name residing within that universe. Distinct bound
1028 /// regions/types/consts within the same universe simply have an unknown relationship to one
1030 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TyEncodable, TyDecodable, PartialOrd, Ord)]
1031 pub struct Placeholder<T> {
1032 pub universe: UniverseIndex,
1036 impl<'a, T> HashStable<StableHashingContext<'a>> for Placeholder<T>
1038 T: HashStable<StableHashingContext<'a>>,
1040 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
1041 self.universe.hash_stable(hcx, hasher);
1042 self.name.hash_stable(hcx, hasher);
1046 pub type PlaceholderRegion = Placeholder<BoundRegionKind>;
1048 pub type PlaceholderType = Placeholder<BoundVar>;
1050 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable)]
1051 #[derive(TyEncodable, TyDecodable, PartialOrd, Ord)]
1052 pub struct BoundConst<'tcx> {
1057 pub type PlaceholderConst<'tcx> = Placeholder<BoundConst<'tcx>>;
1059 /// A `DefId` which, in case it is a const argument, is potentially bundled with
1060 /// the `DefId` of the generic parameter it instantiates.
1062 /// This is used to avoid calls to `type_of` for const arguments during typeck
1063 /// which cause cycle errors.
1068 /// fn foo<const N: usize>(&self) -> [u8; N] { [0; N] }
1069 /// // ^ const parameter
1073 /// fn foo<const M: u8>(&self) -> usize { 42 }
1074 /// // ^ const parameter
1079 /// let _b = a.foo::<{ 3 + 7 }>();
1080 /// // ^^^^^^^^^ const argument
1084 /// Let's look at the call `a.foo::<{ 3 + 7 }>()` here. We do not know
1085 /// which `foo` is used until we know the type of `a`.
1087 /// We only know the type of `a` once we are inside of `typeck(main)`.
1088 /// We also end up normalizing the type of `_b` during `typeck(main)` which
1089 /// requires us to evaluate the const argument.
1091 /// To evaluate that const argument we need to know its type,
1092 /// which we would get using `type_of(const_arg)`. This requires us to
1093 /// resolve `foo` as it can be either `usize` or `u8` in this example.
1094 /// However, resolving `foo` once again requires `typeck(main)` to get the type of `a`,
1095 /// which results in a cycle.
1097 /// In short we must not call `type_of(const_arg)` during `typeck(main)`.
1099 /// When first creating the `ty::Const` of the const argument inside of `typeck` we have
1100 /// already resolved `foo` so we know which const parameter this argument instantiates.
1101 /// This means that we also know the expected result of `type_of(const_arg)` even if we
1102 /// aren't allowed to call that query: it is equal to `type_of(const_param)` which is
1103 /// trivial to compute.
1105 /// If we now want to use that constant in a place which potentionally needs its type
1106 /// we also pass the type of its `const_param`. This is the point of `WithOptConstParam`,
1107 /// except that instead of a `Ty` we bundle the `DefId` of the const parameter.
1108 /// Meaning that we need to use `type_of(const_param_did)` if `const_param_did` is `Some`
1109 /// to get the type of `did`.
1110 #[derive(Copy, Clone, Debug, TypeFoldable, Lift, TyEncodable, TyDecodable)]
1111 #[derive(PartialEq, Eq, PartialOrd, Ord)]
1112 #[derive(Hash, HashStable)]
1113 pub struct WithOptConstParam<T> {
1115 /// The `DefId` of the corresponding generic parameter in case `did` is
1116 /// a const argument.
1118 /// Note that even if `did` is a const argument, this may still be `None`.
1119 /// All queries taking `WithOptConstParam` start by calling `tcx.opt_const_param_of(def.did)`
1120 /// to potentially update `param_did` in the case it is `None`.
1121 pub const_param_did: Option<DefId>,
1124 impl<T> WithOptConstParam<T> {
1125 /// Creates a new `WithOptConstParam` setting `const_param_did` to `None`.
1127 pub fn unknown(did: T) -> WithOptConstParam<T> {
1128 WithOptConstParam { did, const_param_did: None }
1132 impl WithOptConstParam<LocalDefId> {
1133 /// Returns `Some((did, param_did))` if `def_id` is a const argument,
1134 /// `None` otherwise.
1136 pub fn try_lookup(did: LocalDefId, tcx: TyCtxt<'_>) -> Option<(LocalDefId, DefId)> {
1137 tcx.opt_const_param_of(did).map(|param_did| (did, param_did))
1140 /// In case `self` is unknown but `self.did` is a const argument, this returns
1141 /// a `WithOptConstParam` with the correct `const_param_did`.
1143 pub fn try_upgrade(self, tcx: TyCtxt<'_>) -> Option<WithOptConstParam<LocalDefId>> {
1144 if self.const_param_did.is_none() {
1145 if let const_param_did @ Some(_) = tcx.opt_const_param_of(self.did) {
1146 return Some(WithOptConstParam { did: self.did, const_param_did });
1153 pub fn to_global(self) -> WithOptConstParam<DefId> {
1154 WithOptConstParam { did: self.did.to_def_id(), const_param_did: self.const_param_did }
1157 pub fn def_id_for_type_of(self) -> DefId {
1158 if let Some(did) = self.const_param_did { did } else { self.did.to_def_id() }
1162 impl WithOptConstParam<DefId> {
1163 pub fn as_local(self) -> Option<WithOptConstParam<LocalDefId>> {
1166 .map(|did| WithOptConstParam { did, const_param_did: self.const_param_did })
1169 pub fn as_const_arg(self) -> Option<(LocalDefId, DefId)> {
1170 if let Some(param_did) = self.const_param_did {
1171 if let Some(did) = self.did.as_local() {
1172 return Some((did, param_did));
1179 pub fn expect_local(self) -> WithOptConstParam<LocalDefId> {
1180 self.as_local().unwrap()
1183 pub fn is_local(self) -> bool {
1187 pub fn def_id_for_type_of(self) -> DefId {
1188 self.const_param_did.unwrap_or(self.did)
1192 /// When type checking, we use the `ParamEnv` to track
1193 /// details about the set of where-clauses that are in scope at this
1194 /// particular point.
1195 #[derive(Copy, Clone, Hash, PartialEq, Eq)]
1196 pub struct ParamEnv<'tcx> {
1197 /// This packs both caller bounds and the reveal enum into one pointer.
1199 /// Caller bounds are `Obligation`s that the caller must satisfy. This is
1200 /// basically the set of bounds on the in-scope type parameters, translated
1201 /// into `Obligation`s, and elaborated and normalized.
1203 /// Use the `caller_bounds()` method to access.
1205 /// Typically, this is `Reveal::UserFacing`, but during codegen we
1206 /// want `Reveal::All`.
1208 /// Note: This is packed, use the reveal() method to access it.
1209 packed: CopyTaggedPtr<&'tcx List<Predicate<'tcx>>, traits::Reveal, true>,
1212 unsafe impl rustc_data_structures::tagged_ptr::Tag for traits::Reveal {
1213 const BITS: usize = 1;
1214 fn into_usize(self) -> usize {
1216 traits::Reveal::UserFacing => 0,
1217 traits::Reveal::All => 1,
1220 unsafe fn from_usize(ptr: usize) -> Self {
1222 0 => traits::Reveal::UserFacing,
1223 1 => traits::Reveal::All,
1224 _ => std::hint::unreachable_unchecked(),
1229 impl<'tcx> fmt::Debug for ParamEnv<'tcx> {
1230 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1231 f.debug_struct("ParamEnv")
1232 .field("caller_bounds", &self.caller_bounds())
1233 .field("reveal", &self.reveal())
1238 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for ParamEnv<'tcx> {
1239 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
1240 self.caller_bounds().hash_stable(hcx, hasher);
1241 self.reveal().hash_stable(hcx, hasher);
1245 impl<'tcx> TypeFoldable<'tcx> for ParamEnv<'tcx> {
1246 fn super_fold_with<F: ty::fold::TypeFolder<'tcx>>(self, folder: &mut F) -> Self {
1247 ParamEnv::new(self.caller_bounds().fold_with(folder), self.reveal().fold_with(folder))
1250 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> ControlFlow<V::BreakTy> {
1251 self.caller_bounds().visit_with(visitor)?;
1252 self.reveal().visit_with(visitor)
1256 impl<'tcx> ParamEnv<'tcx> {
1257 /// Construct a trait environment suitable for contexts where
1258 /// there are no where-clauses in scope. Hidden types (like `impl
1259 /// Trait`) are left hidden, so this is suitable for ordinary
1262 pub fn empty() -> Self {
1263 Self::new(List::empty(), Reveal::UserFacing)
1267 pub fn caller_bounds(self) -> &'tcx List<Predicate<'tcx>> {
1268 self.packed.pointer()
1272 pub fn reveal(self) -> traits::Reveal {
1276 /// Construct a trait environment with no where-clauses in scope
1277 /// where the values of all `impl Trait` and other hidden types
1278 /// are revealed. This is suitable for monomorphized, post-typeck
1279 /// environments like codegen or doing optimizations.
1281 /// N.B., if you want to have predicates in scope, use `ParamEnv::new`,
1282 /// or invoke `param_env.with_reveal_all()`.
1284 pub fn reveal_all() -> Self {
1285 Self::new(List::empty(), Reveal::All)
1288 /// Construct a trait environment with the given set of predicates.
1290 pub fn new(caller_bounds: &'tcx List<Predicate<'tcx>>, reveal: Reveal) -> Self {
1291 ty::ParamEnv { packed: CopyTaggedPtr::new(caller_bounds, reveal) }
1294 pub fn with_user_facing(mut self) -> Self {
1295 self.packed.set_tag(Reveal::UserFacing);
1299 /// Returns a new parameter environment with the same clauses, but
1300 /// which "reveals" the true results of projections in all cases
1301 /// (even for associated types that are specializable). This is
1302 /// the desired behavior during codegen and certain other special
1303 /// contexts; normally though we want to use `Reveal::UserFacing`,
1304 /// which is the default.
1305 /// All opaque types in the caller_bounds of the `ParamEnv`
1306 /// will be normalized to their underlying types.
1307 /// See PR #65989 and issue #65918 for more details
1308 pub fn with_reveal_all_normalized(self, tcx: TyCtxt<'tcx>) -> Self {
1309 if self.packed.tag() == traits::Reveal::All {
1313 ParamEnv::new(tcx.normalize_opaque_types(self.caller_bounds()), Reveal::All)
1316 /// Returns this same environment but with no caller bounds.
1317 pub fn without_caller_bounds(self) -> Self {
1318 Self::new(List::empty(), self.reveal())
1321 /// Creates a suitable environment in which to perform trait
1322 /// queries on the given value. When type-checking, this is simply
1323 /// the pair of the environment plus value. But when reveal is set to
1324 /// All, then if `value` does not reference any type parameters, we will
1325 /// pair it with the empty environment. This improves caching and is generally
1328 /// N.B., we preserve the environment when type-checking because it
1329 /// is possible for the user to have wacky where-clauses like
1330 /// `where Box<u32>: Copy`, which are clearly never
1331 /// satisfiable. We generally want to behave as if they were true,
1332 /// although the surrounding function is never reachable.
1333 pub fn and<T: TypeFoldable<'tcx>>(self, value: T) -> ParamEnvAnd<'tcx, T> {
1334 match self.reveal() {
1335 Reveal::UserFacing => ParamEnvAnd { param_env: self, value },
1338 if value.is_global() {
1339 ParamEnvAnd { param_env: self.without_caller_bounds(), value }
1341 ParamEnvAnd { param_env: self, value }
1348 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TypeFoldable)]
1349 pub struct ConstnessAnd<T> {
1350 pub constness: Constness,
1354 // FIXME(ecstaticmorse): Audit all occurrences of `without_const().to_predicate(tcx)` to ensure that
1355 // the constness of trait bounds is being propagated correctly.
1356 pub trait WithConstness: Sized {
1358 fn with_constness(self, constness: Constness) -> ConstnessAnd<Self> {
1359 ConstnessAnd { constness, value: self }
1363 fn with_const(self) -> ConstnessAnd<Self> {
1364 self.with_constness(Constness::Const)
1368 fn without_const(self) -> ConstnessAnd<Self> {
1369 self.with_constness(Constness::NotConst)
1373 impl<T> WithConstness for T {}
1375 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TypeFoldable)]
1376 pub struct ParamEnvAnd<'tcx, T> {
1377 pub param_env: ParamEnv<'tcx>,
1381 impl<'tcx, T> ParamEnvAnd<'tcx, T> {
1382 pub fn into_parts(self) -> (ParamEnv<'tcx>, T) {
1383 (self.param_env, self.value)
1387 impl<'a, 'tcx, T> HashStable<StableHashingContext<'a>> for ParamEnvAnd<'tcx, T>
1389 T: HashStable<StableHashingContext<'a>>,
1391 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
1392 let ParamEnvAnd { ref param_env, ref value } = *self;
1394 param_env.hash_stable(hcx, hasher);
1395 value.hash_stable(hcx, hasher);
1399 #[derive(Copy, Clone, Debug, HashStable)]
1400 pub struct Destructor {
1401 /// The `DefId` of the destructor method
1406 #[derive(HashStable)]
1407 pub struct VariantFlags: u32 {
1408 const NO_VARIANT_FLAGS = 0;
1409 /// Indicates whether the field list of this variant is `#[non_exhaustive]`.
1410 const IS_FIELD_LIST_NON_EXHAUSTIVE = 1 << 0;
1411 /// Indicates whether this variant was obtained as part of recovering from
1412 /// a syntactic error. May be incomplete or bogus.
1413 const IS_RECOVERED = 1 << 1;
1417 /// Definition of a variant -- a struct's fields or a enum variant.
1418 #[derive(Debug, HashStable)]
1419 pub struct VariantDef {
1420 /// `DefId` that identifies the variant itself.
1421 /// If this variant belongs to a struct or union, then this is a copy of its `DefId`.
1423 /// `DefId` that identifies the variant's constructor.
1424 /// If this variant is a struct variant, then this is `None`.
1425 pub ctor_def_id: Option<DefId>,
1426 /// Variant or struct name.
1427 #[stable_hasher(project(name))]
1429 /// Discriminant of this variant.
1430 pub discr: VariantDiscr,
1431 /// Fields of this variant.
1432 pub fields: Vec<FieldDef>,
1433 /// Type of constructor of variant.
1434 pub ctor_kind: CtorKind,
1435 /// Flags of the variant (e.g. is field list non-exhaustive)?
1436 flags: VariantFlags,
1440 /// Creates a new `VariantDef`.
1442 /// `variant_did` is the `DefId` that identifies the enum variant (if this `VariantDef`
1443 /// represents an enum variant).
1445 /// `ctor_did` is the `DefId` that identifies the constructor of unit or
1446 /// tuple-variants/structs. If this is a `struct`-variant then this should be `None`.
1448 /// `parent_did` is the `DefId` of the `AdtDef` representing the enum or struct that
1449 /// owns this variant. It is used for checking if a struct has `#[non_exhaustive]` w/out having
1450 /// to go through the redirect of checking the ctor's attributes - but compiling a small crate
1451 /// requires loading the `AdtDef`s for all the structs in the universe (e.g., coherence for any
1452 /// built-in trait), and we do not want to load attributes twice.
1454 /// If someone speeds up attribute loading to not be a performance concern, they can
1455 /// remove this hack and use the constructor `DefId` everywhere.
1458 variant_did: Option<DefId>,
1459 ctor_def_id: Option<DefId>,
1460 discr: VariantDiscr,
1461 fields: Vec<FieldDef>,
1462 ctor_kind: CtorKind,
1466 is_field_list_non_exhaustive: bool,
1469 "VariantDef::new(ident = {:?}, variant_did = {:?}, ctor_def_id = {:?}, discr = {:?},
1470 fields = {:?}, ctor_kind = {:?}, adt_kind = {:?}, parent_did = {:?})",
1471 ident, variant_did, ctor_def_id, discr, fields, ctor_kind, adt_kind, parent_did,
1474 let mut flags = VariantFlags::NO_VARIANT_FLAGS;
1475 if is_field_list_non_exhaustive {
1476 flags |= VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE;
1480 flags |= VariantFlags::IS_RECOVERED;
1484 def_id: variant_did.unwrap_or(parent_did),
1494 /// Is this field list non-exhaustive?
1496 pub fn is_field_list_non_exhaustive(&self) -> bool {
1497 self.flags.intersects(VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE)
1500 /// Was this variant obtained as part of recovering from a syntactic error?
1502 pub fn is_recovered(&self) -> bool {
1503 self.flags.intersects(VariantFlags::IS_RECOVERED)
1507 #[derive(Copy, Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
1508 pub enum VariantDiscr {
1509 /// Explicit value for this variant, i.e., `X = 123`.
1510 /// The `DefId` corresponds to the embedded constant.
1513 /// The previous variant's discriminant plus one.
1514 /// For efficiency reasons, the distance from the
1515 /// last `Explicit` discriminant is being stored,
1516 /// or `0` for the first variant, if it has none.
1520 #[derive(Debug, HashStable)]
1521 pub struct FieldDef {
1523 #[stable_hasher(project(name))]
1525 pub vis: Visibility,
1529 #[derive(TyEncodable, TyDecodable, Default, HashStable)]
1530 pub struct ReprFlags: u8 {
1531 const IS_C = 1 << 0;
1532 const IS_SIMD = 1 << 1;
1533 const IS_TRANSPARENT = 1 << 2;
1534 // Internal only for now. If true, don't reorder fields.
1535 const IS_LINEAR = 1 << 3;
1536 // If true, don't expose any niche to type's context.
1537 const HIDE_NICHE = 1 << 4;
1538 // Any of these flags being set prevent field reordering optimisation.
1539 const IS_UNOPTIMISABLE = ReprFlags::IS_C.bits |
1540 ReprFlags::IS_SIMD.bits |
1541 ReprFlags::IS_LINEAR.bits;
1545 /// Represents the repr options provided by the user,
1546 #[derive(Copy, Clone, Debug, Eq, PartialEq, TyEncodable, TyDecodable, Default, HashStable)]
1547 pub struct ReprOptions {
1548 pub int: Option<attr::IntType>,
1549 pub align: Option<Align>,
1550 pub pack: Option<Align>,
1551 pub flags: ReprFlags,
1555 pub fn new(tcx: TyCtxt<'_>, did: DefId) -> ReprOptions {
1556 let mut flags = ReprFlags::empty();
1557 let mut size = None;
1558 let mut max_align: Option<Align> = None;
1559 let mut min_pack: Option<Align> = None;
1560 for attr in tcx.get_attrs(did).iter() {
1561 for r in attr::find_repr_attrs(&tcx.sess, attr) {
1562 flags.insert(match r {
1563 attr::ReprC => ReprFlags::IS_C,
1564 attr::ReprPacked(pack) => {
1565 let pack = Align::from_bytes(pack as u64).unwrap();
1566 min_pack = Some(if let Some(min_pack) = min_pack {
1573 attr::ReprTransparent => ReprFlags::IS_TRANSPARENT,
1574 attr::ReprNoNiche => ReprFlags::HIDE_NICHE,
1575 attr::ReprSimd => ReprFlags::IS_SIMD,
1576 attr::ReprInt(i) => {
1580 attr::ReprAlign(align) => {
1581 max_align = max_align.max(Some(Align::from_bytes(align as u64).unwrap()));
1588 // This is here instead of layout because the choice must make it into metadata.
1589 if !tcx.consider_optimizing(|| format!("Reorder fields of {:?}", tcx.def_path_str(did))) {
1590 flags.insert(ReprFlags::IS_LINEAR);
1592 ReprOptions { int: size, align: max_align, pack: min_pack, flags }
1596 pub fn simd(&self) -> bool {
1597 self.flags.contains(ReprFlags::IS_SIMD)
1600 pub fn c(&self) -> bool {
1601 self.flags.contains(ReprFlags::IS_C)
1604 pub fn packed(&self) -> bool {
1608 pub fn transparent(&self) -> bool {
1609 self.flags.contains(ReprFlags::IS_TRANSPARENT)
1612 pub fn linear(&self) -> bool {
1613 self.flags.contains(ReprFlags::IS_LINEAR)
1616 pub fn hide_niche(&self) -> bool {
1617 self.flags.contains(ReprFlags::HIDE_NICHE)
1620 /// Returns the discriminant type, given these `repr` options.
1621 /// This must only be called on enums!
1622 pub fn discr_type(&self) -> attr::IntType {
1623 self.int.unwrap_or(attr::SignedInt(ast::IntTy::Isize))
1626 /// Returns `true` if this `#[repr()]` should inhabit "smart enum
1627 /// layout" optimizations, such as representing `Foo<&T>` as a
1629 pub fn inhibit_enum_layout_opt(&self) -> bool {
1630 self.c() || self.int.is_some()
1633 /// Returns `true` if this `#[repr()]` should inhibit struct field reordering
1634 /// optimizations, such as with `repr(C)`, `repr(packed(1))`, or `repr(<int>)`.
1635 pub fn inhibit_struct_field_reordering_opt(&self) -> bool {
1636 if let Some(pack) = self.pack {
1637 if pack.bytes() == 1 {
1641 self.flags.intersects(ReprFlags::IS_UNOPTIMISABLE) || self.int.is_some()
1644 /// Returns `true` if this `#[repr()]` should inhibit union ABI optimisations.
1645 pub fn inhibit_union_abi_opt(&self) -> bool {
1650 impl<'tcx> FieldDef {
1651 /// Returns the type of this field. The `subst` is typically obtained
1652 /// via the second field of `TyKind::AdtDef`.
1653 pub fn ty(&self, tcx: TyCtxt<'tcx>, subst: SubstsRef<'tcx>) -> Ty<'tcx> {
1654 tcx.type_of(self.did).subst(tcx, subst)
1659 pub fn from_mutbl(m: hir::Mutability) -> BorrowKind {
1661 hir::Mutability::Mut => MutBorrow,
1662 hir::Mutability::Not => ImmBorrow,
1666 /// Returns a mutability `m` such that an `&m T` pointer could be used to obtain this borrow
1667 /// kind. Because borrow kinds are richer than mutabilities, we sometimes have to pick a
1668 /// mutability that is stronger than necessary so that it at least *would permit* the borrow in
1670 pub fn to_mutbl_lossy(self) -> hir::Mutability {
1672 MutBorrow => hir::Mutability::Mut,
1673 ImmBorrow => hir::Mutability::Not,
1675 // We have no type corresponding to a unique imm borrow, so
1676 // use `&mut`. It gives all the capabilities of an `&uniq`
1677 // and hence is a safe "over approximation".
1678 UniqueImmBorrow => hir::Mutability::Mut,
1682 pub fn to_user_str(&self) -> &'static str {
1684 MutBorrow => "mutable",
1685 ImmBorrow => "immutable",
1686 UniqueImmBorrow => "uniquely immutable",
1691 pub type Attributes<'tcx> = &'tcx [ast::Attribute];
1693 #[derive(Debug, PartialEq, Eq)]
1694 pub enum ImplOverlapKind {
1695 /// These impls are always allowed to overlap.
1697 /// Whether or not the impl is permitted due to the trait being a `#[marker]` trait
1700 /// These impls are allowed to overlap, but that raises
1701 /// an issue #33140 future-compatibility warning.
1703 /// Some background: in Rust 1.0, the trait-object types `Send + Sync` (today's
1704 /// `dyn Send + Sync`) and `Sync + Send` (now `dyn Sync + Send`) were different.
1706 /// The widely-used version 0.1.0 of the crate `traitobject` had accidentally relied
1707 /// that difference, making what reduces to the following set of impls:
1711 /// impl Trait for dyn Send + Sync {}
1712 /// impl Trait for dyn Sync + Send {}
1715 /// Obviously, once we made these types be identical, that code causes a coherence
1716 /// error and a fairly big headache for us. However, luckily for us, the trait
1717 /// `Trait` used in this case is basically a marker trait, and therefore having
1718 /// overlapping impls for it is sound.
1720 /// To handle this, we basically regard the trait as a marker trait, with an additional
1721 /// future-compatibility warning. To avoid accidentally "stabilizing" this feature,
1722 /// it has the following restrictions:
1724 /// 1. The trait must indeed be a marker-like trait (i.e., no items), and must be
1726 /// 2. The trait-ref of both impls must be equal.
1727 /// 3. The trait-ref of both impls must be a trait object type consisting only of
1729 /// 4. Neither of the impls can have any where-clauses.
1731 /// Once `traitobject` 0.1.0 is no longer an active concern, this hack can be removed.
1735 impl<'tcx> TyCtxt<'tcx> {
1736 pub fn typeck_body(self, body: hir::BodyId) -> &'tcx TypeckResults<'tcx> {
1737 self.typeck(self.hir().body_owner_def_id(body))
1740 /// Returns an iterator of the `DefId`s for all body-owners in this
1741 /// crate. If you would prefer to iterate over the bodies
1742 /// themselves, you can do `self.hir().krate().body_ids.iter()`.
1743 pub fn body_owners(self) -> impl Iterator<Item = LocalDefId> + Captures<'tcx> + 'tcx {
1748 .map(move |&body_id| self.hir().body_owner_def_id(body_id))
1751 pub fn par_body_owners<F: Fn(LocalDefId) + sync::Sync + sync::Send>(self, f: F) {
1752 par_iter(&self.hir().krate().body_ids)
1753 .for_each(|&body_id| f(self.hir().body_owner_def_id(body_id)));
1756 pub fn provided_trait_methods(self, id: DefId) -> impl 'tcx + Iterator<Item = &'tcx AssocItem> {
1757 self.associated_items(id)
1758 .in_definition_order()
1759 .filter(|item| item.kind == AssocKind::Fn && item.defaultness.has_value())
1762 fn item_name_from_hir(self, def_id: DefId) -> Option<Ident> {
1763 self.hir().get_if_local(def_id).and_then(|node| node.ident())
1766 fn item_name_from_def_id(self, def_id: DefId) -> Option<Symbol> {
1767 if def_id.index == CRATE_DEF_INDEX {
1768 Some(self.original_crate_name(def_id.krate))
1770 let def_key = self.def_key(def_id);
1771 match def_key.disambiguated_data.data {
1772 // The name of a constructor is that of its parent.
1773 rustc_hir::definitions::DefPathData::Ctor => self.item_name_from_def_id(DefId {
1774 krate: def_id.krate,
1775 index: def_key.parent.unwrap(),
1777 _ => def_key.disambiguated_data.data.get_opt_name(),
1782 /// Look up the name of an item across crates. This does not look at HIR.
1784 /// When possible, this function should be used for cross-crate lookups over
1785 /// [`opt_item_name`] to avoid invalidating the incremental cache. If you
1786 /// need to handle items without a name, or HIR items that will not be
1787 /// serialized cross-crate, or if you need the span of the item, use
1788 /// [`opt_item_name`] instead.
1790 /// [`opt_item_name`]: Self::opt_item_name
1791 pub fn item_name(self, id: DefId) -> Symbol {
1792 // Look at cross-crate items first to avoid invalidating the incremental cache
1793 // unless we have to.
1794 self.item_name_from_def_id(id).unwrap_or_else(|| {
1795 bug!("item_name: no name for {:?}", self.def_path(id));
1799 /// Look up the name and span of an item or [`Node`].
1801 /// See [`item_name`][Self::item_name] for more information.
1802 pub fn opt_item_name(self, def_id: DefId) -> Option<Ident> {
1803 // Look at the HIR first so the span will be correct if this is a local item.
1804 self.item_name_from_hir(def_id)
1805 .or_else(|| self.item_name_from_def_id(def_id).map(Ident::with_dummy_span))
1808 pub fn opt_associated_item(self, def_id: DefId) -> Option<&'tcx AssocItem> {
1809 if let DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy = self.def_kind(def_id) {
1810 Some(self.associated_item(def_id))
1816 pub fn field_index(self, hir_id: hir::HirId, typeck_results: &TypeckResults<'_>) -> usize {
1817 typeck_results.field_indices().get(hir_id).cloned().expect("no index for a field")
1820 pub fn find_field_index(self, ident: Ident, variant: &VariantDef) -> Option<usize> {
1821 variant.fields.iter().position(|field| self.hygienic_eq(ident, field.ident, variant.def_id))
1824 /// Returns `true` if the impls are the same polarity and the trait either
1825 /// has no items or is annotated `#[marker]` and prevents item overrides.
1826 pub fn impls_are_allowed_to_overlap(
1830 ) -> Option<ImplOverlapKind> {
1831 // If either trait impl references an error, they're allowed to overlap,
1832 // as one of them essentially doesn't exist.
1833 if self.impl_trait_ref(def_id1).map_or(false, |tr| tr.references_error())
1834 || self.impl_trait_ref(def_id2).map_or(false, |tr| tr.references_error())
1836 return Some(ImplOverlapKind::Permitted { marker: false });
1839 match (self.impl_polarity(def_id1), self.impl_polarity(def_id2)) {
1840 (ImplPolarity::Reservation, _) | (_, ImplPolarity::Reservation) => {
1841 // `#[rustc_reservation_impl]` impls don't overlap with anything
1843 "impls_are_allowed_to_overlap({:?}, {:?}) = Some(Permitted) (reservations)",
1846 return Some(ImplOverlapKind::Permitted { marker: false });
1848 (ImplPolarity::Positive, ImplPolarity::Negative)
1849 | (ImplPolarity::Negative, ImplPolarity::Positive) => {
1850 // `impl AutoTrait for Type` + `impl !AutoTrait for Type`
1852 "impls_are_allowed_to_overlap({:?}, {:?}) - None (differing polarities)",
1857 (ImplPolarity::Positive, ImplPolarity::Positive)
1858 | (ImplPolarity::Negative, ImplPolarity::Negative) => {}
1861 let is_marker_overlap = {
1862 let is_marker_impl = |def_id: DefId| -> bool {
1863 let trait_ref = self.impl_trait_ref(def_id);
1864 trait_ref.map_or(false, |tr| self.trait_def(tr.def_id).is_marker)
1866 is_marker_impl(def_id1) && is_marker_impl(def_id2)
1869 if is_marker_overlap {
1871 "impls_are_allowed_to_overlap({:?}, {:?}) = Some(Permitted) (marker overlap)",
1874 Some(ImplOverlapKind::Permitted { marker: true })
1876 if let Some(self_ty1) = self.issue33140_self_ty(def_id1) {
1877 if let Some(self_ty2) = self.issue33140_self_ty(def_id2) {
1878 if self_ty1 == self_ty2 {
1880 "impls_are_allowed_to_overlap({:?}, {:?}) - issue #33140 HACK",
1883 return Some(ImplOverlapKind::Issue33140);
1886 "impls_are_allowed_to_overlap({:?}, {:?}) - found {:?} != {:?}",
1887 def_id1, def_id2, self_ty1, self_ty2
1893 debug!("impls_are_allowed_to_overlap({:?}, {:?}) = None", def_id1, def_id2);
1898 /// Returns `ty::VariantDef` if `res` refers to a struct,
1899 /// or variant or their constructors, panics otherwise.
1900 pub fn expect_variant_res(self, res: Res) -> &'tcx VariantDef {
1902 Res::Def(DefKind::Variant, did) => {
1903 let enum_did = self.parent(did).unwrap();
1904 self.adt_def(enum_did).variant_with_id(did)
1906 Res::Def(DefKind::Struct | DefKind::Union, did) => self.adt_def(did).non_enum_variant(),
1907 Res::Def(DefKind::Ctor(CtorOf::Variant, ..), variant_ctor_did) => {
1908 let variant_did = self.parent(variant_ctor_did).unwrap();
1909 let enum_did = self.parent(variant_did).unwrap();
1910 self.adt_def(enum_did).variant_with_ctor_id(variant_ctor_did)
1912 Res::Def(DefKind::Ctor(CtorOf::Struct, ..), ctor_did) => {
1913 let struct_did = self.parent(ctor_did).expect("struct ctor has no parent");
1914 self.adt_def(struct_did).non_enum_variant()
1916 _ => bug!("expect_variant_res used with unexpected res {:?}", res),
1920 /// Returns the possibly-auto-generated MIR of a `(DefId, Subst)` pair.
1921 pub fn instance_mir(self, instance: ty::InstanceDef<'tcx>) -> &'tcx Body<'tcx> {
1923 ty::InstanceDef::Item(def) => match self.def_kind(def.did) {
1926 | DefKind::AssocConst
1928 | DefKind::AnonConst => self.mir_for_ctfe_opt_const_arg(def),
1929 // If the caller wants `mir_for_ctfe` of a function they should not be using
1930 // `instance_mir`, so we'll assume const fn also wants the optimized version.
1932 assert_eq!(def.const_param_did, None);
1933 self.optimized_mir(def.did)
1936 ty::InstanceDef::VtableShim(..)
1937 | ty::InstanceDef::ReifyShim(..)
1938 | ty::InstanceDef::Intrinsic(..)
1939 | ty::InstanceDef::FnPtrShim(..)
1940 | ty::InstanceDef::Virtual(..)
1941 | ty::InstanceDef::ClosureOnceShim { .. }
1942 | ty::InstanceDef::DropGlue(..)
1943 | ty::InstanceDef::CloneShim(..) => self.mir_shims(instance),
1947 /// Gets the attributes of a definition.
1948 pub fn get_attrs(self, did: DefId) -> Attributes<'tcx> {
1949 if let Some(did) = did.as_local() {
1950 self.hir().attrs(self.hir().local_def_id_to_hir_id(did))
1952 self.item_attrs(did)
1956 /// Determines whether an item is annotated with an attribute.
1957 pub fn has_attr(self, did: DefId, attr: Symbol) -> bool {
1958 self.sess.contains_name(&self.get_attrs(did), attr)
1961 /// Returns `true` if this is an `auto trait`.
1962 pub fn trait_is_auto(self, trait_def_id: DefId) -> bool {
1963 self.trait_def(trait_def_id).has_auto_impl
1966 /// Returns layout of a generator. Layout might be unavailable if the
1967 /// generator is tainted by errors.
1968 pub fn generator_layout(self, def_id: DefId) -> Option<&'tcx GeneratorLayout<'tcx>> {
1969 self.optimized_mir(def_id).generator_layout()
1972 /// Given the `DefId` of an impl, returns the `DefId` of the trait it implements.
1973 /// If it implements no trait, returns `None`.
1974 pub fn trait_id_of_impl(self, def_id: DefId) -> Option<DefId> {
1975 self.impl_trait_ref(def_id).map(|tr| tr.def_id)
1978 /// If the given defid describes a method belonging to an impl, returns the
1979 /// `DefId` of the impl that the method belongs to; otherwise, returns `None`.
1980 pub fn impl_of_method(self, def_id: DefId) -> Option<DefId> {
1981 self.opt_associated_item(def_id).and_then(|trait_item| match trait_item.container {
1982 TraitContainer(_) => None,
1983 ImplContainer(def_id) => Some(def_id),
1987 /// Looks up the span of `impl_did` if the impl is local; otherwise returns `Err`
1988 /// with the name of the crate containing the impl.
1989 pub fn span_of_impl(self, impl_did: DefId) -> Result<Span, Symbol> {
1990 if let Some(impl_did) = impl_did.as_local() {
1991 let hir_id = self.hir().local_def_id_to_hir_id(impl_did);
1992 Ok(self.hir().span(hir_id))
1994 Err(self.crate_name(impl_did.krate))
1998 /// Hygienically compares a use-site name (`use_name`) for a field or an associated item with
1999 /// its supposed definition name (`def_name`). The method also needs `DefId` of the supposed
2000 /// definition's parent/scope to perform comparison.
2001 pub fn hygienic_eq(self, use_name: Ident, def_name: Ident, def_parent_def_id: DefId) -> bool {
2002 // We could use `Ident::eq` here, but we deliberately don't. The name
2003 // comparison fails frequently, and we want to avoid the expensive
2004 // `normalize_to_macros_2_0()` calls required for the span comparison whenever possible.
2005 use_name.name == def_name.name
2009 .hygienic_eq(def_name.span.ctxt(), self.expansion_that_defined(def_parent_def_id))
2012 pub fn expansion_that_defined(self, scope: DefId) -> ExpnId {
2013 match scope.as_local() {
2014 // Parsing and expansion aren't incremental, so we don't
2015 // need to go through a query for the same-crate case.
2016 Some(scope) => self.hir().definitions().expansion_that_defined(scope),
2017 None => self.expn_that_defined(scope),
2021 pub fn adjust_ident(self, mut ident: Ident, scope: DefId) -> Ident {
2022 ident.span.normalize_to_macros_2_0_and_adjust(self.expansion_that_defined(scope));
2026 pub fn adjust_ident_and_get_scope(
2031 ) -> (Ident, DefId) {
2033 match ident.span.normalize_to_macros_2_0_and_adjust(self.expansion_that_defined(scope))
2035 Some(actual_expansion) => {
2036 self.hir().definitions().parent_module_of_macro_def(actual_expansion)
2038 None => self.parent_module(block).to_def_id(),
2043 pub fn is_object_safe(self, key: DefId) -> bool {
2044 self.object_safety_violations(key).is_empty()
2048 /// Yields the parent function's `DefId` if `def_id` is an `impl Trait` definition.
2049 pub fn is_impl_trait_defn(tcx: TyCtxt<'_>, def_id: DefId) -> Option<DefId> {
2050 if let Some(def_id) = def_id.as_local() {
2051 if let Node::Item(item) = tcx.hir().get(tcx.hir().local_def_id_to_hir_id(def_id)) {
2052 if let hir::ItemKind::OpaqueTy(ref opaque_ty) = item.kind {
2053 return opaque_ty.impl_trait_fn;
2060 pub fn int_ty(ity: ast::IntTy) -> IntTy {
2062 ast::IntTy::Isize => IntTy::Isize,
2063 ast::IntTy::I8 => IntTy::I8,
2064 ast::IntTy::I16 => IntTy::I16,
2065 ast::IntTy::I32 => IntTy::I32,
2066 ast::IntTy::I64 => IntTy::I64,
2067 ast::IntTy::I128 => IntTy::I128,
2071 pub fn uint_ty(uty: ast::UintTy) -> UintTy {
2073 ast::UintTy::Usize => UintTy::Usize,
2074 ast::UintTy::U8 => UintTy::U8,
2075 ast::UintTy::U16 => UintTy::U16,
2076 ast::UintTy::U32 => UintTy::U32,
2077 ast::UintTy::U64 => UintTy::U64,
2078 ast::UintTy::U128 => UintTy::U128,
2082 pub fn float_ty(fty: ast::FloatTy) -> FloatTy {
2084 ast::FloatTy::F32 => FloatTy::F32,
2085 ast::FloatTy::F64 => FloatTy::F64,
2089 pub fn ast_int_ty(ity: IntTy) -> ast::IntTy {
2091 IntTy::Isize => ast::IntTy::Isize,
2092 IntTy::I8 => ast::IntTy::I8,
2093 IntTy::I16 => ast::IntTy::I16,
2094 IntTy::I32 => ast::IntTy::I32,
2095 IntTy::I64 => ast::IntTy::I64,
2096 IntTy::I128 => ast::IntTy::I128,
2100 pub fn ast_uint_ty(uty: UintTy) -> ast::UintTy {
2102 UintTy::Usize => ast::UintTy::Usize,
2103 UintTy::U8 => ast::UintTy::U8,
2104 UintTy::U16 => ast::UintTy::U16,
2105 UintTy::U32 => ast::UintTy::U32,
2106 UintTy::U64 => ast::UintTy::U64,
2107 UintTy::U128 => ast::UintTy::U128,
2111 pub fn provide(providers: &mut ty::query::Providers) {
2112 context::provide(providers);
2113 erase_regions::provide(providers);
2114 layout::provide(providers);
2115 util::provide(providers);
2116 print::provide(providers);
2117 super::util::bug::provide(providers);
2118 *providers = ty::query::Providers {
2119 trait_impls_of: trait_def::trait_impls_of_provider,
2120 all_local_trait_impls: trait_def::all_local_trait_impls,
2121 type_uninhabited_from: inhabitedness::type_uninhabited_from,
2126 /// A map for the local crate mapping each type to a vector of its
2127 /// inherent impls. This is not meant to be used outside of coherence;
2128 /// rather, you should request the vector for a specific type via
2129 /// `tcx.inherent_impls(def_id)` so as to minimize your dependencies
2130 /// (constructing this map requires touching the entire crate).
2131 #[derive(Clone, Debug, Default, HashStable)]
2132 pub struct CrateInherentImpls {
2133 pub inherent_impls: DefIdMap<Vec<DefId>>,
2136 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, HashStable)]
2137 pub struct SymbolName<'tcx> {
2138 /// `&str` gives a consistent ordering, which ensures reproducible builds.
2139 pub name: &'tcx str,
2142 impl<'tcx> SymbolName<'tcx> {
2143 pub fn new(tcx: TyCtxt<'tcx>, name: &str) -> SymbolName<'tcx> {
2145 name: unsafe { str::from_utf8_unchecked(tcx.arena.alloc_slice(name.as_bytes())) },
2150 impl<'tcx> fmt::Display for SymbolName<'tcx> {
2151 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2152 fmt::Display::fmt(&self.name, fmt)
2156 impl<'tcx> fmt::Debug for SymbolName<'tcx> {
2157 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2158 fmt::Display::fmt(&self.name, fmt)