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::ich::StableHashingContext;
24 use crate::middle::cstore::CrateStoreDyn;
25 use crate::mir::{Body, GeneratorLayout};
26 use crate::traits::{self, Reveal};
28 use crate::ty::subst::{GenericArg, InternalSubsts, Subst, SubstsRef};
29 use crate::ty::util::Discr;
31 use rustc_attr as attr;
32 use rustc_data_structures::captures::Captures;
33 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
34 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
35 use rustc_data_structures::sync::{self, par_iter, ParallelIterator};
36 use rustc_data_structures::tagged_ptr::CopyTaggedPtr;
38 use rustc_hir::def::{CtorKind, CtorOf, DefKind, Res};
39 use rustc_hir::def_id::{CrateNum, DefId, LocalDefId, LocalDefIdMap, CRATE_DEF_INDEX};
40 use rustc_hir::{Constness, Node};
41 use rustc_macros::HashStable;
42 use rustc_span::hygiene::ExpnId;
43 use rustc_span::symbol::{kw, Ident, Symbol};
45 use rustc_target::abi::Align;
47 use std::cmp::Ordering;
48 use std::hash::{Hash, Hasher};
49 use std::ops::ControlFlow;
50 use std::{fmt, ptr, str};
52 pub use crate::ty::diagnostics::*;
53 pub use rustc_type_ir::InferTy::*;
54 pub use rustc_type_ir::*;
56 pub use self::binding::BindingMode;
57 pub use self::binding::BindingMode::*;
58 pub use self::consts::{Const, ConstInt, ConstKind, InferConst, ScalarInt, Unevaluated, ValTree};
59 pub use self::context::{
60 tls, CanonicalUserType, CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations,
61 CtxtInterners, DelaySpanBugEmitted, FreeRegionInfo, GeneratorInteriorTypeCause, GlobalCtxt,
62 Lift, ResolvedOpaqueTy, TyCtxt, TypeckResults, UserType, UserTypeAnnotationIndex,
64 pub use self::instance::{Instance, InstanceDef};
65 pub use self::list::List;
66 pub use self::sty::BoundRegionKind::*;
67 pub use self::sty::RegionKind::*;
68 pub use self::sty::TyKind::*;
70 Binder, BoundRegion, BoundRegionKind, BoundTy, BoundTyKind, BoundVar, BoundVariableKind,
71 CanonicalPolyFnSig, ClosureSubsts, ClosureSubstsParts, ConstVid, EarlyBoundRegion,
72 ExistentialPredicate, ExistentialProjection, ExistentialTraitRef, FnSig, FreeRegion, GenSig,
73 GeneratorSubsts, GeneratorSubstsParts, ParamConst, ParamTy, PolyExistentialProjection,
74 PolyExistentialTraitRef, PolyFnSig, PolyGenSig, PolyTraitRef, ProjectionTy, Region, RegionKind,
75 RegionVid, TraitRef, TyKind, TypeAndMut, UpvarSubsts,
77 pub use self::trait_def::TraitDef;
88 pub mod inhabitedness;
90 pub mod normalize_erasing_regions;
110 mod structural_impls;
115 pub struct ResolverOutputs {
116 pub definitions: rustc_hir::definitions::Definitions,
117 pub cstore: Box<CrateStoreDyn>,
118 pub visibilities: FxHashMap<LocalDefId, Visibility>,
119 pub extern_crate_map: FxHashMap<LocalDefId, CrateNum>,
120 pub maybe_unused_trait_imports: FxHashSet<LocalDefId>,
121 pub maybe_unused_extern_crates: Vec<(LocalDefId, Span)>,
122 pub export_map: ExportMap<LocalDefId>,
123 pub glob_map: FxHashMap<LocalDefId, FxHashSet<Symbol>>,
124 /// Extern prelude entries. The value is `true` if the entry was introduced
125 /// via `extern crate` item and not `--extern` option or compiler built-in.
126 pub extern_prelude: FxHashMap<Symbol, bool>,
127 pub main_def: Option<MainDefinition>,
130 #[derive(Clone, Copy)]
131 pub struct MainDefinition {
132 pub res: Res<ast::NodeId>,
137 impl MainDefinition {
138 pub fn opt_fn_def_id(self) -> Option<DefId> {
139 if let Res::Def(DefKind::Fn, def_id) = self.res { Some(def_id) } else { None }
143 /// The "header" of an impl is everything outside the body: a Self type, a trait
144 /// ref (in the case of a trait impl), and a set of predicates (from the
145 /// bounds / where-clauses).
146 #[derive(Clone, Debug, TypeFoldable)]
147 pub struct ImplHeader<'tcx> {
148 pub impl_def_id: DefId,
149 pub self_ty: Ty<'tcx>,
150 pub trait_ref: Option<TraitRef<'tcx>>,
151 pub predicates: Vec<Predicate<'tcx>>,
154 #[derive(Copy, Clone, PartialEq, TyEncodable, TyDecodable, HashStable, Debug)]
155 pub enum ImplPolarity {
156 /// `impl Trait for Type`
158 /// `impl !Trait for Type`
160 /// `#[rustc_reservation_impl] impl Trait for Type`
162 /// This is a "stability hack", not a real Rust feature.
163 /// See #64631 for details.
167 #[derive(Clone, Debug, PartialEq, Eq, Copy, Hash, TyEncodable, TyDecodable, HashStable)]
168 pub enum Visibility {
169 /// Visible everywhere (including in other crates).
171 /// Visible only in the given crate-local module.
173 /// Not visible anywhere in the local crate. This is the visibility of private external items.
177 pub trait DefIdTree: Copy {
178 fn parent(self, id: DefId) -> Option<DefId>;
180 fn is_descendant_of(self, mut descendant: DefId, ancestor: DefId) -> bool {
181 if descendant.krate != ancestor.krate {
185 while descendant != ancestor {
186 match self.parent(descendant) {
187 Some(parent) => descendant = parent,
188 None => return false,
195 impl<'tcx> DefIdTree for TyCtxt<'tcx> {
196 fn parent(self, id: DefId) -> Option<DefId> {
197 self.def_key(id).parent.map(|index| DefId { index, ..id })
202 pub fn from_hir(visibility: &hir::Visibility<'_>, id: hir::HirId, tcx: TyCtxt<'_>) -> Self {
203 match visibility.node {
204 hir::VisibilityKind::Public => Visibility::Public,
205 hir::VisibilityKind::Crate(_) => Visibility::Restricted(DefId::local(CRATE_DEF_INDEX)),
206 hir::VisibilityKind::Restricted { ref path, .. } => match path.res {
207 // If there is no resolution, `resolve` will have already reported an error, so
208 // assume that the visibility is public to avoid reporting more privacy errors.
209 Res::Err => Visibility::Public,
210 def => Visibility::Restricted(def.def_id()),
212 hir::VisibilityKind::Inherited => {
213 Visibility::Restricted(tcx.parent_module(id).to_def_id())
218 /// Returns `true` if an item with this visibility is accessible from the given block.
219 pub fn is_accessible_from<T: DefIdTree>(self, module: DefId, tree: T) -> bool {
220 let restriction = match self {
221 // Public items are visible everywhere.
222 Visibility::Public => return true,
223 // Private items from other crates are visible nowhere.
224 Visibility::Invisible => return false,
225 // Restricted items are visible in an arbitrary local module.
226 Visibility::Restricted(other) if other.krate != module.krate => return false,
227 Visibility::Restricted(module) => module,
230 tree.is_descendant_of(module, restriction)
233 /// Returns `true` if this visibility is at least as accessible as the given visibility
234 pub fn is_at_least<T: DefIdTree>(self, vis: Visibility, tree: T) -> bool {
235 let vis_restriction = match vis {
236 Visibility::Public => return self == Visibility::Public,
237 Visibility::Invisible => return true,
238 Visibility::Restricted(module) => module,
241 self.is_accessible_from(vis_restriction, tree)
244 // Returns `true` if this item is visible anywhere in the local crate.
245 pub fn is_visible_locally(self) -> bool {
247 Visibility::Public => true,
248 Visibility::Restricted(def_id) => def_id.is_local(),
249 Visibility::Invisible => false,
254 /// The crate variances map is computed during typeck and contains the
255 /// variance of every item in the local crate. You should not use it
256 /// directly, because to do so will make your pass dependent on the
257 /// HIR of every item in the local crate. Instead, use
258 /// `tcx.variances_of()` to get the variance for a *particular*
260 #[derive(HashStable, Debug)]
261 pub struct CrateVariancesMap<'tcx> {
262 /// For each item with generics, maps to a vector of the variance
263 /// of its generics. If an item has no generics, it will have no
265 pub variances: FxHashMap<DefId, &'tcx [ty::Variance]>,
268 // Contains information needed to resolve types and (in the future) look up
269 // the types of AST nodes.
270 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
271 pub struct CReaderCacheKey {
272 pub cnum: Option<CrateNum>,
276 #[allow(rustc::usage_of_ty_tykind)]
277 pub struct TyS<'tcx> {
278 /// This field shouldn't be used directly and may be removed in the future.
279 /// Use `TyS::kind()` instead.
281 /// This field shouldn't be used directly and may be removed in the future.
282 /// Use `TyS::flags()` instead.
285 /// This is a kind of confusing thing: it stores the smallest
288 /// (a) the binder itself captures nothing but
289 /// (b) all the late-bound things within the type are captured
290 /// by some sub-binder.
292 /// So, for a type without any late-bound things, like `u32`, this
293 /// will be *innermost*, because that is the innermost binder that
294 /// captures nothing. But for a type `&'D u32`, where `'D` is a
295 /// late-bound region with De Bruijn index `D`, this would be `D + 1`
296 /// -- the binder itself does not capture `D`, but `D` is captured
297 /// by an inner binder.
299 /// We call this concept an "exclusive" binder `D` because all
300 /// De Bruijn indices within the type are contained within `0..D`
302 outer_exclusive_binder: ty::DebruijnIndex,
305 impl<'tcx> TyS<'tcx> {
306 /// A constructor used only for internal testing.
307 #[allow(rustc::usage_of_ty_tykind)]
308 pub fn make_for_test(
311 outer_exclusive_binder: ty::DebruijnIndex,
313 TyS { kind, flags, outer_exclusive_binder }
317 // `TyS` is used a lot. Make sure it doesn't unintentionally get bigger.
318 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
319 static_assert_size!(TyS<'_>, 40);
321 impl<'tcx> Ord for TyS<'tcx> {
322 fn cmp(&self, other: &TyS<'tcx>) -> Ordering {
323 self.kind().cmp(other.kind())
327 impl<'tcx> PartialOrd for TyS<'tcx> {
328 fn partial_cmp(&self, other: &TyS<'tcx>) -> Option<Ordering> {
329 Some(self.kind().cmp(other.kind()))
333 impl<'tcx> PartialEq for TyS<'tcx> {
335 fn eq(&self, other: &TyS<'tcx>) -> bool {
339 impl<'tcx> Eq for TyS<'tcx> {}
341 impl<'tcx> Hash for TyS<'tcx> {
342 fn hash<H: Hasher>(&self, s: &mut H) {
343 (self as *const TyS<'_>).hash(s)
347 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for TyS<'tcx> {
348 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
352 // The other fields just provide fast access to information that is
353 // also contained in `kind`, so no need to hash them.
356 outer_exclusive_binder: _,
359 kind.hash_stable(hcx, hasher);
363 #[rustc_diagnostic_item = "Ty"]
364 pub type Ty<'tcx> = &'tcx TyS<'tcx>;
366 impl ty::EarlyBoundRegion {
367 /// Does this early bound region have a name? Early bound regions normally
368 /// always have names except when using anonymous lifetimes (`'_`).
369 pub fn has_name(&self) -> bool {
370 self.name != kw::UnderscoreLifetime
375 crate struct PredicateInner<'tcx> {
376 kind: Binder<'tcx, PredicateKind<'tcx>>,
378 /// See the comment for the corresponding field of [TyS].
379 outer_exclusive_binder: ty::DebruijnIndex,
382 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
383 static_assert_size!(PredicateInner<'_>, 48);
385 #[derive(Clone, Copy, Lift)]
386 pub struct Predicate<'tcx> {
387 inner: &'tcx PredicateInner<'tcx>,
390 impl<'tcx> PartialEq for Predicate<'tcx> {
391 fn eq(&self, other: &Self) -> bool {
392 // `self.kind` is always interned.
393 ptr::eq(self.inner, other.inner)
397 impl Hash for Predicate<'_> {
398 fn hash<H: Hasher>(&self, s: &mut H) {
399 (self.inner as *const PredicateInner<'_>).hash(s)
403 impl<'tcx> Eq for Predicate<'tcx> {}
405 impl<'tcx> Predicate<'tcx> {
406 /// Gets the inner `Binder<'tcx, PredicateKind<'tcx>>`.
408 pub fn kind(self) -> Binder<'tcx, PredicateKind<'tcx>> {
413 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for Predicate<'tcx> {
414 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
418 // The other fields just provide fast access to information that is
419 // also contained in `kind`, so no need to hash them.
421 outer_exclusive_binder: _,
424 kind.hash_stable(hcx, hasher);
428 #[derive(Clone, Copy, PartialEq, Eq, Hash, TyEncodable, TyDecodable)]
429 #[derive(HashStable, TypeFoldable)]
430 pub enum PredicateKind<'tcx> {
431 /// Corresponds to `where Foo: Bar<A, B, C>`. `Foo` here would be
432 /// the `Self` type of the trait reference and `A`, `B`, and `C`
433 /// would be the type parameters.
435 /// A trait predicate will have `Constness::Const` if it originates
436 /// from a bound on a `const fn` without the `?const` opt-out (e.g.,
437 /// `const fn foobar<Foo: Bar>() {}`).
438 Trait(TraitPredicate<'tcx>, Constness),
441 RegionOutlives(RegionOutlivesPredicate<'tcx>),
444 TypeOutlives(TypeOutlivesPredicate<'tcx>),
446 /// `where <T as TraitRef>::Name == X`, approximately.
447 /// See the `ProjectionPredicate` struct for details.
448 Projection(ProjectionPredicate<'tcx>),
450 /// No syntax: `T` well-formed.
451 WellFormed(GenericArg<'tcx>),
453 /// Trait must be object-safe.
456 /// No direct syntax. May be thought of as `where T: FnFoo<...>`
457 /// for some substitutions `...` and `T` being a closure type.
458 /// Satisfied (or refuted) once we know the closure's kind.
459 ClosureKind(DefId, SubstsRef<'tcx>, ClosureKind),
462 Subtype(SubtypePredicate<'tcx>),
464 /// Constant initializer must evaluate successfully.
465 ConstEvaluatable(ty::WithOptConstParam<DefId>, SubstsRef<'tcx>),
467 /// Constants must be equal. The first component is the const that is expected.
468 ConstEquate(&'tcx Const<'tcx>, &'tcx Const<'tcx>),
470 /// Represents a type found in the environment that we can use for implied bounds.
472 /// Only used for Chalk.
473 TypeWellFormedFromEnv(Ty<'tcx>),
476 /// The crate outlives map is computed during typeck and contains the
477 /// outlives of every item in the local crate. You should not use it
478 /// directly, because to do so will make your pass dependent on the
479 /// HIR of every item in the local crate. Instead, use
480 /// `tcx.inferred_outlives_of()` to get the outlives for a *particular*
482 #[derive(HashStable, Debug)]
483 pub struct CratePredicatesMap<'tcx> {
484 /// For each struct with outlive bounds, maps to a vector of the
485 /// predicate of its outlive bounds. If an item has no outlives
486 /// bounds, it will have no entry.
487 pub predicates: FxHashMap<DefId, &'tcx [(Predicate<'tcx>, Span)]>,
490 impl<'tcx> Predicate<'tcx> {
491 /// Performs a substitution suitable for going from a
492 /// poly-trait-ref to supertraits that must hold if that
493 /// poly-trait-ref holds. This is slightly different from a normal
494 /// substitution in terms of what happens with bound regions. See
495 /// lengthy comment below for details.
496 pub fn subst_supertrait(
499 trait_ref: &ty::PolyTraitRef<'tcx>,
500 ) -> Predicate<'tcx> {
501 // The interaction between HRTB and supertraits is not entirely
502 // obvious. Let me walk you (and myself) through an example.
504 // Let's start with an easy case. Consider two traits:
506 // trait Foo<'a>: Bar<'a,'a> { }
507 // trait Bar<'b,'c> { }
509 // Now, if we have a trait reference `for<'x> T: Foo<'x>`, then
510 // we can deduce that `for<'x> T: Bar<'x,'x>`. Basically, if we
511 // knew that `Foo<'x>` (for any 'x) then we also know that
512 // `Bar<'x,'x>` (for any 'x). This more-or-less falls out from
513 // normal substitution.
515 // In terms of why this is sound, the idea is that whenever there
516 // is an impl of `T:Foo<'a>`, it must show that `T:Bar<'a,'a>`
517 // holds. So if there is an impl of `T:Foo<'a>` that applies to
518 // all `'a`, then we must know that `T:Bar<'a,'a>` holds for all
521 // Another example to be careful of is this:
523 // trait Foo1<'a>: for<'b> Bar1<'a,'b> { }
524 // trait Bar1<'b,'c> { }
526 // Here, if we have `for<'x> T: Foo1<'x>`, then what do we know?
527 // The answer is that we know `for<'x,'b> T: Bar1<'x,'b>`. The
528 // reason is similar to the previous example: any impl of
529 // `T:Foo1<'x>` must show that `for<'b> T: Bar1<'x, 'b>`. So
530 // basically we would want to collapse the bound lifetimes from
531 // the input (`trait_ref`) and the supertraits.
533 // To achieve this in practice is fairly straightforward. Let's
534 // consider the more complicated scenario:
536 // - We start out with `for<'x> T: Foo1<'x>`. In this case, `'x`
537 // has a De Bruijn index of 1. We want to produce `for<'x,'b> T: Bar1<'x,'b>`,
538 // where both `'x` and `'b` would have a DB index of 1.
539 // The substitution from the input trait-ref is therefore going to be
540 // `'a => 'x` (where `'x` has a DB index of 1).
541 // - The super-trait-ref is `for<'b> Bar1<'a,'b>`, where `'a` is an
542 // early-bound parameter and `'b' is a late-bound parameter with a
544 // - If we replace `'a` with `'x` from the input, it too will have
545 // a DB index of 1, and thus we'll have `for<'x,'b> Bar1<'x,'b>`
546 // just as we wanted.
548 // There is only one catch. If we just apply the substitution `'a
549 // => 'x` to `for<'b> Bar1<'a,'b>`, the substitution code will
550 // adjust the DB index because we substituting into a binder (it
551 // tries to be so smart...) resulting in `for<'x> for<'b>
552 // Bar1<'x,'b>` (we have no syntax for this, so use your
553 // imagination). Basically the 'x will have DB index of 2 and 'b
554 // will have DB index of 1. Not quite what we want. So we apply
555 // the substitution to the *contents* of the trait reference,
556 // rather than the trait reference itself (put another way, the
557 // substitution code expects equal binding levels in the values
558 // from the substitution and the value being substituted into, and
559 // this trick achieves that).
561 // Working through the second example:
562 // trait_ref: for<'x> T: Foo1<'^0.0>; substs: [T, '^0.0]
563 // predicate: for<'b> Self: Bar1<'a, '^0.0>; substs: [Self, 'a, '^0.0]
564 // We want to end up with:
565 // for<'x, 'b> T: Bar1<'^0.0, '^0.1>
567 // 1) We must shift all bound vars in predicate by the length
568 // of trait ref's bound vars. So, we would end up with predicate like
569 // Self: Bar1<'a, '^0.1>
570 // 2) We can then apply the trait substs to this, ending up with
571 // T: Bar1<'^0.0, '^0.1>
572 // 3) Finally, to create the final bound vars, we concatenate the bound
573 // vars of the trait ref with those of the predicate:
575 let bound_pred = self.kind();
576 let pred_bound_vars = bound_pred.bound_vars();
577 let trait_bound_vars = trait_ref.bound_vars();
578 // 1) Self: Bar1<'a, '^0.0> -> Self: Bar1<'a, '^0.1>
580 tcx.shift_bound_var_indices(trait_bound_vars.len(), bound_pred.skip_binder());
581 // 2) Self: Bar1<'a, '^0.1> -> T: Bar1<'^0.0, '^0.1>
582 let new = shifted_pred.subst(tcx, trait_ref.skip_binder().substs);
583 // 3) ['x] + ['b] -> ['x, 'b]
585 tcx.mk_bound_variable_kinds(trait_bound_vars.iter().chain(pred_bound_vars));
586 tcx.reuse_or_mk_predicate(self, ty::Binder::bind_with_vars(new, bound_vars))
590 #[derive(Clone, Copy, PartialEq, Eq, Hash, TyEncodable, TyDecodable)]
591 #[derive(HashStable, TypeFoldable)]
592 pub struct TraitPredicate<'tcx> {
593 pub trait_ref: TraitRef<'tcx>,
596 pub type PolyTraitPredicate<'tcx> = ty::Binder<'tcx, TraitPredicate<'tcx>>;
598 impl<'tcx> TraitPredicate<'tcx> {
599 pub fn def_id(self) -> DefId {
600 self.trait_ref.def_id
603 pub fn self_ty(self) -> Ty<'tcx> {
604 self.trait_ref.self_ty()
608 impl<'tcx> PolyTraitPredicate<'tcx> {
609 pub fn def_id(self) -> DefId {
610 // Ok to skip binder since trait `DefId` does not care about regions.
611 self.skip_binder().def_id()
614 pub fn self_ty(self) -> ty::Binder<'tcx, Ty<'tcx>> {
615 self.map_bound(|trait_ref| trait_ref.self_ty())
619 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, TyEncodable, TyDecodable)]
620 #[derive(HashStable, TypeFoldable)]
621 pub struct OutlivesPredicate<A, B>(pub A, pub B); // `A: B`
622 pub type RegionOutlivesPredicate<'tcx> = OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>;
623 pub type TypeOutlivesPredicate<'tcx> = OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>;
624 pub type PolyRegionOutlivesPredicate<'tcx> = ty::Binder<'tcx, RegionOutlivesPredicate<'tcx>>;
625 pub type PolyTypeOutlivesPredicate<'tcx> = ty::Binder<'tcx, TypeOutlivesPredicate<'tcx>>;
627 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, TyEncodable, TyDecodable)]
628 #[derive(HashStable, TypeFoldable)]
629 pub struct SubtypePredicate<'tcx> {
630 pub a_is_expected: bool,
634 pub type PolySubtypePredicate<'tcx> = ty::Binder<'tcx, SubtypePredicate<'tcx>>;
636 /// This kind of predicate has no *direct* correspondent in the
637 /// syntax, but it roughly corresponds to the syntactic forms:
639 /// 1. `T: TraitRef<..., Item = Type>`
640 /// 2. `<T as TraitRef<...>>::Item == Type` (NYI)
642 /// In particular, form #1 is "desugared" to the combination of a
643 /// normal trait predicate (`T: TraitRef<...>`) and one of these
644 /// predicates. Form #2 is a broader form in that it also permits
645 /// equality between arbitrary types. Processing an instance of
646 /// Form #2 eventually yields one of these `ProjectionPredicate`
647 /// instances to normalize the LHS.
648 #[derive(Copy, Clone, PartialEq, Eq, Hash, TyEncodable, TyDecodable)]
649 #[derive(HashStable, TypeFoldable)]
650 pub struct ProjectionPredicate<'tcx> {
651 pub projection_ty: ProjectionTy<'tcx>,
655 pub type PolyProjectionPredicate<'tcx> = Binder<'tcx, ProjectionPredicate<'tcx>>;
657 impl<'tcx> PolyProjectionPredicate<'tcx> {
658 /// Returns the `DefId` of the trait of the associated item being projected.
660 pub fn trait_def_id(&self, tcx: TyCtxt<'tcx>) -> DefId {
661 self.skip_binder().projection_ty.trait_def_id(tcx)
664 /// Get the [PolyTraitRef] required for this projection to be well formed.
665 /// Note that for generic associated types the predicates of the associated
666 /// type also need to be checked.
668 pub fn required_poly_trait_ref(&self, tcx: TyCtxt<'tcx>) -> PolyTraitRef<'tcx> {
669 // Note: unlike with `TraitRef::to_poly_trait_ref()`,
670 // `self.0.trait_ref` is permitted to have escaping regions.
671 // This is because here `self` has a `Binder` and so does our
672 // return value, so we are preserving the number of binding
674 self.map_bound(|predicate| predicate.projection_ty.trait_ref(tcx))
677 pub fn ty(&self) -> Binder<'tcx, Ty<'tcx>> {
678 self.map_bound(|predicate| predicate.ty)
681 /// The `DefId` of the `TraitItem` for the associated type.
683 /// Note that this is not the `DefId` of the `TraitRef` containing this
684 /// associated type, which is in `tcx.associated_item(projection_def_id()).container`.
685 pub fn projection_def_id(&self) -> DefId {
686 // Ok to skip binder since trait `DefId` does not care about regions.
687 self.skip_binder().projection_ty.item_def_id
691 pub trait ToPolyTraitRef<'tcx> {
692 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx>;
695 impl<'tcx> ToPolyTraitRef<'tcx> for TraitRef<'tcx> {
696 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
697 ty::Binder::dummy(*self)
701 impl<'tcx> ToPolyTraitRef<'tcx> for PolyTraitPredicate<'tcx> {
702 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
703 self.map_bound_ref(|trait_pred| trait_pred.trait_ref)
707 pub trait ToPredicate<'tcx> {
708 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx>;
711 impl ToPredicate<'tcx> for Binder<'tcx, PredicateKind<'tcx>> {
713 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
714 tcx.mk_predicate(self)
718 impl ToPredicate<'tcx> for PredicateKind<'tcx> {
720 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
721 tcx.mk_predicate(Binder::dummy(self))
725 impl<'tcx> ToPredicate<'tcx> for ConstnessAnd<TraitRef<'tcx>> {
726 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
727 PredicateKind::Trait(ty::TraitPredicate { trait_ref: self.value }, self.constness)
732 impl<'tcx> ToPredicate<'tcx> for ConstnessAnd<PolyTraitRef<'tcx>> {
733 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
735 .map_bound(|trait_ref| {
736 PredicateKind::Trait(ty::TraitPredicate { trait_ref }, self.constness)
742 impl<'tcx> ToPredicate<'tcx> for ConstnessAnd<PolyTraitPredicate<'tcx>> {
743 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
744 self.value.map_bound(|value| PredicateKind::Trait(value, self.constness)).to_predicate(tcx)
748 impl<'tcx> ToPredicate<'tcx> for PolyRegionOutlivesPredicate<'tcx> {
749 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
750 self.map_bound(PredicateKind::RegionOutlives).to_predicate(tcx)
754 impl<'tcx> ToPredicate<'tcx> for PolyTypeOutlivesPredicate<'tcx> {
755 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
756 self.map_bound(PredicateKind::TypeOutlives).to_predicate(tcx)
760 impl<'tcx> ToPredicate<'tcx> for PolyProjectionPredicate<'tcx> {
761 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
762 self.map_bound(PredicateKind::Projection).to_predicate(tcx)
766 impl<'tcx> Predicate<'tcx> {
767 pub fn to_opt_poly_trait_ref(self) -> Option<ConstnessAnd<PolyTraitRef<'tcx>>> {
768 let predicate = self.kind();
769 match predicate.skip_binder() {
770 PredicateKind::Trait(t, constness) => {
771 Some(ConstnessAnd { constness, value: predicate.rebind(t.trait_ref) })
773 PredicateKind::Projection(..)
774 | PredicateKind::Subtype(..)
775 | PredicateKind::RegionOutlives(..)
776 | PredicateKind::WellFormed(..)
777 | PredicateKind::ObjectSafe(..)
778 | PredicateKind::ClosureKind(..)
779 | PredicateKind::TypeOutlives(..)
780 | PredicateKind::ConstEvaluatable(..)
781 | PredicateKind::ConstEquate(..)
782 | PredicateKind::TypeWellFormedFromEnv(..) => None,
786 pub fn to_opt_type_outlives(self) -> Option<PolyTypeOutlivesPredicate<'tcx>> {
787 let predicate = self.kind();
788 match predicate.skip_binder() {
789 PredicateKind::TypeOutlives(data) => Some(predicate.rebind(data)),
790 PredicateKind::Trait(..)
791 | PredicateKind::Projection(..)
792 | PredicateKind::Subtype(..)
793 | PredicateKind::RegionOutlives(..)
794 | PredicateKind::WellFormed(..)
795 | PredicateKind::ObjectSafe(..)
796 | PredicateKind::ClosureKind(..)
797 | PredicateKind::ConstEvaluatable(..)
798 | PredicateKind::ConstEquate(..)
799 | PredicateKind::TypeWellFormedFromEnv(..) => None,
804 /// Represents the bounds declared on a particular set of type
805 /// parameters. Should eventually be generalized into a flag list of
806 /// where-clauses. You can obtain a `InstantiatedPredicates` list from a
807 /// `GenericPredicates` by using the `instantiate` method. Note that this method
808 /// reflects an important semantic invariant of `InstantiatedPredicates`: while
809 /// the `GenericPredicates` are expressed in terms of the bound type
810 /// parameters of the impl/trait/whatever, an `InstantiatedPredicates` instance
811 /// represented a set of bounds for some particular instantiation,
812 /// meaning that the generic parameters have been substituted with
817 /// struct Foo<T, U: Bar<T>> { ... }
819 /// Here, the `GenericPredicates` for `Foo` would contain a list of bounds like
820 /// `[[], [U:Bar<T>]]`. Now if there were some particular reference
821 /// like `Foo<isize,usize>`, then the `InstantiatedPredicates` would be `[[],
822 /// [usize:Bar<isize>]]`.
823 #[derive(Clone, Debug, TypeFoldable)]
824 pub struct InstantiatedPredicates<'tcx> {
825 pub predicates: Vec<Predicate<'tcx>>,
826 pub spans: Vec<Span>,
829 impl<'tcx> InstantiatedPredicates<'tcx> {
830 pub fn empty() -> InstantiatedPredicates<'tcx> {
831 InstantiatedPredicates { predicates: vec![], spans: vec![] }
834 pub fn is_empty(&self) -> bool {
835 self.predicates.is_empty()
839 rustc_index::newtype_index! {
840 /// "Universes" are used during type- and trait-checking in the
841 /// presence of `for<..>` binders to control what sets of names are
842 /// visible. Universes are arranged into a tree: the root universe
843 /// contains names that are always visible. Each child then adds a new
844 /// set of names that are visible, in addition to those of its parent.
845 /// We say that the child universe "extends" the parent universe with
848 /// To make this more concrete, consider this program:
852 /// fn bar<T>(x: T) {
853 /// let y: for<'a> fn(&'a u8, Foo) = ...;
857 /// The struct name `Foo` is in the root universe U0. But the type
858 /// parameter `T`, introduced on `bar`, is in an extended universe U1
859 /// -- i.e., within `bar`, we can name both `T` and `Foo`, but outside
860 /// of `bar`, we cannot name `T`. Then, within the type of `y`, the
861 /// region `'a` is in a universe U2 that extends U1, because we can
862 /// name it inside the fn type but not outside.
864 /// Universes are used to do type- and trait-checking around these
865 /// "forall" binders (also called **universal quantification**). The
866 /// idea is that when, in the body of `bar`, we refer to `T` as a
867 /// type, we aren't referring to any type in particular, but rather a
868 /// kind of "fresh" type that is distinct from all other types we have
869 /// actually declared. This is called a **placeholder** type, and we
870 /// use universes to talk about this. In other words, a type name in
871 /// universe 0 always corresponds to some "ground" type that the user
872 /// declared, but a type name in a non-zero universe is a placeholder
873 /// type -- an idealized representative of "types in general" that we
874 /// use for checking generic functions.
875 pub struct UniverseIndex {
877 DEBUG_FORMAT = "U{}",
882 pub const ROOT: UniverseIndex = UniverseIndex::from_u32(0);
884 /// Returns the "next" universe index in order -- this new index
885 /// is considered to extend all previous universes. This
886 /// corresponds to entering a `forall` quantifier. So, for
887 /// example, suppose we have this type in universe `U`:
890 /// for<'a> fn(&'a u32)
893 /// Once we "enter" into this `for<'a>` quantifier, we are in a
894 /// new universe that extends `U` -- in this new universe, we can
895 /// name the region `'a`, but that region was not nameable from
896 /// `U` because it was not in scope there.
897 pub fn next_universe(self) -> UniverseIndex {
898 UniverseIndex::from_u32(self.private.checked_add(1).unwrap())
901 /// Returns `true` if `self` can name a name from `other` -- in other words,
902 /// if the set of names in `self` is a superset of those in
903 /// `other` (`self >= other`).
904 pub fn can_name(self, other: UniverseIndex) -> bool {
905 self.private >= other.private
908 /// Returns `true` if `self` cannot name some names from `other` -- in other
909 /// words, if the set of names in `self` is a strict subset of
910 /// those in `other` (`self < other`).
911 pub fn cannot_name(self, other: UniverseIndex) -> bool {
912 self.private < other.private
916 /// The "placeholder index" fully defines a placeholder region, type, or const. Placeholders are
917 /// identified by both a universe, as well as a name residing within that universe. Distinct bound
918 /// regions/types/consts within the same universe simply have an unknown relationship to one
920 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TyEncodable, TyDecodable, PartialOrd, Ord)]
921 pub struct Placeholder<T> {
922 pub universe: UniverseIndex,
926 impl<'a, T> HashStable<StableHashingContext<'a>> for Placeholder<T>
928 T: HashStable<StableHashingContext<'a>>,
930 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
931 self.universe.hash_stable(hcx, hasher);
932 self.name.hash_stable(hcx, hasher);
936 pub type PlaceholderRegion = Placeholder<BoundRegionKind>;
938 pub type PlaceholderType = Placeholder<BoundVar>;
940 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable)]
941 #[derive(TyEncodable, TyDecodable, PartialOrd, Ord)]
942 pub struct BoundConst<'tcx> {
947 pub type PlaceholderConst<'tcx> = Placeholder<BoundConst<'tcx>>;
949 /// A `DefId` which, in case it is a const argument, is potentially bundled with
950 /// the `DefId` of the generic parameter it instantiates.
952 /// This is used to avoid calls to `type_of` for const arguments during typeck
953 /// which cause cycle errors.
958 /// fn foo<const N: usize>(&self) -> [u8; N] { [0; N] }
959 /// // ^ const parameter
963 /// fn foo<const M: u8>(&self) -> usize { 42 }
964 /// // ^ const parameter
969 /// let _b = a.foo::<{ 3 + 7 }>();
970 /// // ^^^^^^^^^ const argument
974 /// Let's look at the call `a.foo::<{ 3 + 7 }>()` here. We do not know
975 /// which `foo` is used until we know the type of `a`.
977 /// We only know the type of `a` once we are inside of `typeck(main)`.
978 /// We also end up normalizing the type of `_b` during `typeck(main)` which
979 /// requires us to evaluate the const argument.
981 /// To evaluate that const argument we need to know its type,
982 /// which we would get using `type_of(const_arg)`. This requires us to
983 /// resolve `foo` as it can be either `usize` or `u8` in this example.
984 /// However, resolving `foo` once again requires `typeck(main)` to get the type of `a`,
985 /// which results in a cycle.
987 /// In short we must not call `type_of(const_arg)` during `typeck(main)`.
989 /// When first creating the `ty::Const` of the const argument inside of `typeck` we have
990 /// already resolved `foo` so we know which const parameter this argument instantiates.
991 /// This means that we also know the expected result of `type_of(const_arg)` even if we
992 /// aren't allowed to call that query: it is equal to `type_of(const_param)` which is
993 /// trivial to compute.
995 /// If we now want to use that constant in a place which potentionally needs its type
996 /// we also pass the type of its `const_param`. This is the point of `WithOptConstParam`,
997 /// except that instead of a `Ty` we bundle the `DefId` of the const parameter.
998 /// Meaning that we need to use `type_of(const_param_did)` if `const_param_did` is `Some`
999 /// to get the type of `did`.
1000 #[derive(Copy, Clone, Debug, TypeFoldable, Lift, TyEncodable, TyDecodable)]
1001 #[derive(PartialEq, Eq, PartialOrd, Ord)]
1002 #[derive(Hash, HashStable)]
1003 pub struct WithOptConstParam<T> {
1005 /// The `DefId` of the corresponding generic parameter in case `did` is
1006 /// a const argument.
1008 /// Note that even if `did` is a const argument, this may still be `None`.
1009 /// All queries taking `WithOptConstParam` start by calling `tcx.opt_const_param_of(def.did)`
1010 /// to potentially update `param_did` in the case it is `None`.
1011 pub const_param_did: Option<DefId>,
1014 impl<T> WithOptConstParam<T> {
1015 /// Creates a new `WithOptConstParam` setting `const_param_did` to `None`.
1017 pub fn unknown(did: T) -> WithOptConstParam<T> {
1018 WithOptConstParam { did, const_param_did: None }
1022 impl WithOptConstParam<LocalDefId> {
1023 /// Returns `Some((did, param_did))` if `def_id` is a const argument,
1024 /// `None` otherwise.
1026 pub fn try_lookup(did: LocalDefId, tcx: TyCtxt<'_>) -> Option<(LocalDefId, DefId)> {
1027 tcx.opt_const_param_of(did).map(|param_did| (did, param_did))
1030 /// In case `self` is unknown but `self.did` is a const argument, this returns
1031 /// a `WithOptConstParam` with the correct `const_param_did`.
1033 pub fn try_upgrade(self, tcx: TyCtxt<'_>) -> Option<WithOptConstParam<LocalDefId>> {
1034 if self.const_param_did.is_none() {
1035 if let const_param_did @ Some(_) = tcx.opt_const_param_of(self.did) {
1036 return Some(WithOptConstParam { did: self.did, const_param_did });
1043 pub fn to_global(self) -> WithOptConstParam<DefId> {
1044 WithOptConstParam { did: self.did.to_def_id(), const_param_did: self.const_param_did }
1047 pub fn def_id_for_type_of(self) -> DefId {
1048 if let Some(did) = self.const_param_did { did } else { self.did.to_def_id() }
1052 impl WithOptConstParam<DefId> {
1053 pub fn as_local(self) -> Option<WithOptConstParam<LocalDefId>> {
1056 .map(|did| WithOptConstParam { did, const_param_did: self.const_param_did })
1059 pub fn as_const_arg(self) -> Option<(LocalDefId, DefId)> {
1060 if let Some(param_did) = self.const_param_did {
1061 if let Some(did) = self.did.as_local() {
1062 return Some((did, param_did));
1069 pub fn is_local(self) -> bool {
1073 pub fn def_id_for_type_of(self) -> DefId {
1074 self.const_param_did.unwrap_or(self.did)
1078 /// When type checking, we use the `ParamEnv` to track
1079 /// details about the set of where-clauses that are in scope at this
1080 /// particular point.
1081 #[derive(Copy, Clone, Hash, PartialEq, Eq)]
1082 pub struct ParamEnv<'tcx> {
1083 /// This packs both caller bounds and the reveal enum into one pointer.
1085 /// Caller bounds are `Obligation`s that the caller must satisfy. This is
1086 /// basically the set of bounds on the in-scope type parameters, translated
1087 /// into `Obligation`s, and elaborated and normalized.
1089 /// Use the `caller_bounds()` method to access.
1091 /// Typically, this is `Reveal::UserFacing`, but during codegen we
1092 /// want `Reveal::All`.
1094 /// Note: This is packed, use the reveal() method to access it.
1095 packed: CopyTaggedPtr<&'tcx List<Predicate<'tcx>>, traits::Reveal, true>,
1098 unsafe impl rustc_data_structures::tagged_ptr::Tag for traits::Reveal {
1099 const BITS: usize = 1;
1101 fn into_usize(self) -> usize {
1103 traits::Reveal::UserFacing => 0,
1104 traits::Reveal::All => 1,
1108 unsafe fn from_usize(ptr: usize) -> Self {
1110 0 => traits::Reveal::UserFacing,
1111 1 => traits::Reveal::All,
1112 _ => std::hint::unreachable_unchecked(),
1117 impl<'tcx> fmt::Debug for ParamEnv<'tcx> {
1118 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1119 f.debug_struct("ParamEnv")
1120 .field("caller_bounds", &self.caller_bounds())
1121 .field("reveal", &self.reveal())
1126 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for ParamEnv<'tcx> {
1127 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
1128 self.caller_bounds().hash_stable(hcx, hasher);
1129 self.reveal().hash_stable(hcx, hasher);
1133 impl<'tcx> TypeFoldable<'tcx> for ParamEnv<'tcx> {
1134 fn super_fold_with<F: ty::fold::TypeFolder<'tcx>>(self, folder: &mut F) -> Self {
1135 ParamEnv::new(self.caller_bounds().fold_with(folder), self.reveal().fold_with(folder))
1138 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> ControlFlow<V::BreakTy> {
1139 self.caller_bounds().visit_with(visitor)?;
1140 self.reveal().visit_with(visitor)
1144 impl<'tcx> ParamEnv<'tcx> {
1145 /// Construct a trait environment suitable for contexts where
1146 /// there are no where-clauses in scope. Hidden types (like `impl
1147 /// Trait`) are left hidden, so this is suitable for ordinary
1150 pub fn empty() -> Self {
1151 Self::new(List::empty(), Reveal::UserFacing)
1155 pub fn caller_bounds(self) -> &'tcx List<Predicate<'tcx>> {
1156 self.packed.pointer()
1160 pub fn reveal(self) -> traits::Reveal {
1164 /// Construct a trait environment with no where-clauses in scope
1165 /// where the values of all `impl Trait` and other hidden types
1166 /// are revealed. This is suitable for monomorphized, post-typeck
1167 /// environments like codegen or doing optimizations.
1169 /// N.B., if you want to have predicates in scope, use `ParamEnv::new`,
1170 /// or invoke `param_env.with_reveal_all()`.
1172 pub fn reveal_all() -> Self {
1173 Self::new(List::empty(), Reveal::All)
1176 /// Construct a trait environment with the given set of predicates.
1178 pub fn new(caller_bounds: &'tcx List<Predicate<'tcx>>, reveal: Reveal) -> Self {
1179 ty::ParamEnv { packed: CopyTaggedPtr::new(caller_bounds, reveal) }
1182 pub fn with_user_facing(mut self) -> Self {
1183 self.packed.set_tag(Reveal::UserFacing);
1187 /// Returns a new parameter environment with the same clauses, but
1188 /// which "reveals" the true results of projections in all cases
1189 /// (even for associated types that are specializable). This is
1190 /// the desired behavior during codegen and certain other special
1191 /// contexts; normally though we want to use `Reveal::UserFacing`,
1192 /// which is the default.
1193 /// All opaque types in the caller_bounds of the `ParamEnv`
1194 /// will be normalized to their underlying types.
1195 /// See PR #65989 and issue #65918 for more details
1196 pub fn with_reveal_all_normalized(self, tcx: TyCtxt<'tcx>) -> Self {
1197 if self.packed.tag() == traits::Reveal::All {
1201 ParamEnv::new(tcx.normalize_opaque_types(self.caller_bounds()), Reveal::All)
1204 /// Returns this same environment but with no caller bounds.
1206 pub fn without_caller_bounds(self) -> Self {
1207 Self::new(List::empty(), self.reveal())
1210 /// Creates a suitable environment in which to perform trait
1211 /// queries on the given value. When type-checking, this is simply
1212 /// the pair of the environment plus value. But when reveal is set to
1213 /// All, then if `value` does not reference any type parameters, we will
1214 /// pair it with the empty environment. This improves caching and is generally
1217 /// N.B., we preserve the environment when type-checking because it
1218 /// is possible for the user to have wacky where-clauses like
1219 /// `where Box<u32>: Copy`, which are clearly never
1220 /// satisfiable. We generally want to behave as if they were true,
1221 /// although the surrounding function is never reachable.
1222 pub fn and<T: TypeFoldable<'tcx>>(self, value: T) -> ParamEnvAnd<'tcx, T> {
1223 match self.reveal() {
1224 Reveal::UserFacing => ParamEnvAnd { param_env: self, value },
1227 if value.is_global() {
1228 ParamEnvAnd { param_env: self.without_caller_bounds(), value }
1230 ParamEnvAnd { param_env: self, value }
1237 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TypeFoldable)]
1238 pub struct ConstnessAnd<T> {
1239 pub constness: Constness,
1243 // FIXME(ecstaticmorse): Audit all occurrences of `without_const().to_predicate(tcx)` to ensure that
1244 // the constness of trait bounds is being propagated correctly.
1245 pub trait WithConstness: Sized {
1247 fn with_constness(self, constness: Constness) -> ConstnessAnd<Self> {
1248 ConstnessAnd { constness, value: self }
1252 fn with_const(self) -> ConstnessAnd<Self> {
1253 self.with_constness(Constness::Const)
1257 fn without_const(self) -> ConstnessAnd<Self> {
1258 self.with_constness(Constness::NotConst)
1262 impl<T> WithConstness for T {}
1264 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TypeFoldable)]
1265 pub struct ParamEnvAnd<'tcx, T> {
1266 pub param_env: ParamEnv<'tcx>,
1270 impl<'tcx, T> ParamEnvAnd<'tcx, T> {
1271 pub fn into_parts(self) -> (ParamEnv<'tcx>, T) {
1272 (self.param_env, self.value)
1276 impl<'a, 'tcx, T> HashStable<StableHashingContext<'a>> for ParamEnvAnd<'tcx, T>
1278 T: HashStable<StableHashingContext<'a>>,
1280 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
1281 let ParamEnvAnd { ref param_env, ref value } = *self;
1283 param_env.hash_stable(hcx, hasher);
1284 value.hash_stable(hcx, hasher);
1288 #[derive(Copy, Clone, Debug, HashStable)]
1289 pub struct Destructor {
1290 /// The `DefId` of the destructor method
1295 #[derive(HashStable)]
1296 pub struct VariantFlags: u32 {
1297 const NO_VARIANT_FLAGS = 0;
1298 /// Indicates whether the field list of this variant is `#[non_exhaustive]`.
1299 const IS_FIELD_LIST_NON_EXHAUSTIVE = 1 << 0;
1300 /// Indicates whether this variant was obtained as part of recovering from
1301 /// a syntactic error. May be incomplete or bogus.
1302 const IS_RECOVERED = 1 << 1;
1306 /// Definition of a variant -- a struct's fields or a enum variant.
1307 #[derive(Debug, HashStable)]
1308 pub struct VariantDef {
1309 /// `DefId` that identifies the variant itself.
1310 /// If this variant belongs to a struct or union, then this is a copy of its `DefId`.
1312 /// `DefId` that identifies the variant's constructor.
1313 /// If this variant is a struct variant, then this is `None`.
1314 pub ctor_def_id: Option<DefId>,
1315 /// Variant or struct name.
1316 #[stable_hasher(project(name))]
1318 /// Discriminant of this variant.
1319 pub discr: VariantDiscr,
1320 /// Fields of this variant.
1321 pub fields: Vec<FieldDef>,
1322 /// Type of constructor of variant.
1323 pub ctor_kind: CtorKind,
1324 /// Flags of the variant (e.g. is field list non-exhaustive)?
1325 flags: VariantFlags,
1329 /// Creates a new `VariantDef`.
1331 /// `variant_did` is the `DefId` that identifies the enum variant (if this `VariantDef`
1332 /// represents an enum variant).
1334 /// `ctor_did` is the `DefId` that identifies the constructor of unit or
1335 /// tuple-variants/structs. If this is a `struct`-variant then this should be `None`.
1337 /// `parent_did` is the `DefId` of the `AdtDef` representing the enum or struct that
1338 /// owns this variant. It is used for checking if a struct has `#[non_exhaustive]` w/out having
1339 /// to go through the redirect of checking the ctor's attributes - but compiling a small crate
1340 /// requires loading the `AdtDef`s for all the structs in the universe (e.g., coherence for any
1341 /// built-in trait), and we do not want to load attributes twice.
1343 /// If someone speeds up attribute loading to not be a performance concern, they can
1344 /// remove this hack and use the constructor `DefId` everywhere.
1347 variant_did: Option<DefId>,
1348 ctor_def_id: Option<DefId>,
1349 discr: VariantDiscr,
1350 fields: Vec<FieldDef>,
1351 ctor_kind: CtorKind,
1355 is_field_list_non_exhaustive: bool,
1358 "VariantDef::new(ident = {:?}, variant_did = {:?}, ctor_def_id = {:?}, discr = {:?},
1359 fields = {:?}, ctor_kind = {:?}, adt_kind = {:?}, parent_did = {:?})",
1360 ident, variant_did, ctor_def_id, discr, fields, ctor_kind, adt_kind, parent_did,
1363 let mut flags = VariantFlags::NO_VARIANT_FLAGS;
1364 if is_field_list_non_exhaustive {
1365 flags |= VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE;
1369 flags |= VariantFlags::IS_RECOVERED;
1373 def_id: variant_did.unwrap_or(parent_did),
1383 /// Is this field list non-exhaustive?
1385 pub fn is_field_list_non_exhaustive(&self) -> bool {
1386 self.flags.intersects(VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE)
1389 /// Was this variant obtained as part of recovering from a syntactic error?
1391 pub fn is_recovered(&self) -> bool {
1392 self.flags.intersects(VariantFlags::IS_RECOVERED)
1396 #[derive(Copy, Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
1397 pub enum VariantDiscr {
1398 /// Explicit value for this variant, i.e., `X = 123`.
1399 /// The `DefId` corresponds to the embedded constant.
1402 /// The previous variant's discriminant plus one.
1403 /// For efficiency reasons, the distance from the
1404 /// last `Explicit` discriminant is being stored,
1405 /// or `0` for the first variant, if it has none.
1409 #[derive(Debug, HashStable)]
1410 pub struct FieldDef {
1412 #[stable_hasher(project(name))]
1414 pub vis: Visibility,
1418 #[derive(TyEncodable, TyDecodable, Default, HashStable)]
1419 pub struct ReprFlags: u8 {
1420 const IS_C = 1 << 0;
1421 const IS_SIMD = 1 << 1;
1422 const IS_TRANSPARENT = 1 << 2;
1423 // Internal only for now. If true, don't reorder fields.
1424 const IS_LINEAR = 1 << 3;
1425 // If true, don't expose any niche to type's context.
1426 const HIDE_NICHE = 1 << 4;
1427 // Any of these flags being set prevent field reordering optimisation.
1428 const IS_UNOPTIMISABLE = ReprFlags::IS_C.bits |
1429 ReprFlags::IS_SIMD.bits |
1430 ReprFlags::IS_LINEAR.bits;
1434 /// Represents the repr options provided by the user,
1435 #[derive(Copy, Clone, Debug, Eq, PartialEq, TyEncodable, TyDecodable, Default, HashStable)]
1436 pub struct ReprOptions {
1437 pub int: Option<attr::IntType>,
1438 pub align: Option<Align>,
1439 pub pack: Option<Align>,
1440 pub flags: ReprFlags,
1444 pub fn new(tcx: TyCtxt<'_>, did: DefId) -> ReprOptions {
1445 let mut flags = ReprFlags::empty();
1446 let mut size = None;
1447 let mut max_align: Option<Align> = None;
1448 let mut min_pack: Option<Align> = None;
1449 for attr in tcx.get_attrs(did).iter() {
1450 for r in attr::find_repr_attrs(&tcx.sess, attr) {
1451 flags.insert(match r {
1452 attr::ReprC => ReprFlags::IS_C,
1453 attr::ReprPacked(pack) => {
1454 let pack = Align::from_bytes(pack as u64).unwrap();
1455 min_pack = Some(if let Some(min_pack) = min_pack {
1462 attr::ReprTransparent => ReprFlags::IS_TRANSPARENT,
1463 attr::ReprNoNiche => ReprFlags::HIDE_NICHE,
1464 attr::ReprSimd => ReprFlags::IS_SIMD,
1465 attr::ReprInt(i) => {
1469 attr::ReprAlign(align) => {
1470 max_align = max_align.max(Some(Align::from_bytes(align as u64).unwrap()));
1477 // This is here instead of layout because the choice must make it into metadata.
1478 if !tcx.consider_optimizing(|| format!("Reorder fields of {:?}", tcx.def_path_str(did))) {
1479 flags.insert(ReprFlags::IS_LINEAR);
1481 ReprOptions { int: size, align: max_align, pack: min_pack, flags }
1485 pub fn simd(&self) -> bool {
1486 self.flags.contains(ReprFlags::IS_SIMD)
1489 pub fn c(&self) -> bool {
1490 self.flags.contains(ReprFlags::IS_C)
1493 pub fn packed(&self) -> bool {
1497 pub fn transparent(&self) -> bool {
1498 self.flags.contains(ReprFlags::IS_TRANSPARENT)
1501 pub fn linear(&self) -> bool {
1502 self.flags.contains(ReprFlags::IS_LINEAR)
1505 pub fn hide_niche(&self) -> bool {
1506 self.flags.contains(ReprFlags::HIDE_NICHE)
1509 /// Returns the discriminant type, given these `repr` options.
1510 /// This must only be called on enums!
1511 pub fn discr_type(&self) -> attr::IntType {
1512 self.int.unwrap_or(attr::SignedInt(ast::IntTy::Isize))
1515 /// Returns `true` if this `#[repr()]` should inhabit "smart enum
1516 /// layout" optimizations, such as representing `Foo<&T>` as a
1518 pub fn inhibit_enum_layout_opt(&self) -> bool {
1519 self.c() || self.int.is_some()
1522 /// Returns `true` if this `#[repr()]` should inhibit struct field reordering
1523 /// optimizations, such as with `repr(C)`, `repr(packed(1))`, or `repr(<int>)`.
1524 pub fn inhibit_struct_field_reordering_opt(&self) -> bool {
1525 if let Some(pack) = self.pack {
1526 if pack.bytes() == 1 {
1530 self.flags.intersects(ReprFlags::IS_UNOPTIMISABLE) || self.int.is_some()
1533 /// Returns `true` if this `#[repr()]` should inhibit union ABI optimisations.
1534 pub fn inhibit_union_abi_opt(&self) -> bool {
1539 impl<'tcx> FieldDef {
1540 /// Returns the type of this field. The `subst` is typically obtained
1541 /// via the second field of `TyKind::AdtDef`.
1542 pub fn ty(&self, tcx: TyCtxt<'tcx>, subst: SubstsRef<'tcx>) -> Ty<'tcx> {
1543 tcx.type_of(self.did).subst(tcx, subst)
1547 pub type Attributes<'tcx> = &'tcx [ast::Attribute];
1549 #[derive(Debug, PartialEq, Eq)]
1550 pub enum ImplOverlapKind {
1551 /// These impls are always allowed to overlap.
1553 /// Whether or not the impl is permitted due to the trait being a `#[marker]` trait
1556 /// These impls are allowed to overlap, but that raises
1557 /// an issue #33140 future-compatibility warning.
1559 /// Some background: in Rust 1.0, the trait-object types `Send + Sync` (today's
1560 /// `dyn Send + Sync`) and `Sync + Send` (now `dyn Sync + Send`) were different.
1562 /// The widely-used version 0.1.0 of the crate `traitobject` had accidentally relied
1563 /// that difference, making what reduces to the following set of impls:
1567 /// impl Trait for dyn Send + Sync {}
1568 /// impl Trait for dyn Sync + Send {}
1571 /// Obviously, once we made these types be identical, that code causes a coherence
1572 /// error and a fairly big headache for us. However, luckily for us, the trait
1573 /// `Trait` used in this case is basically a marker trait, and therefore having
1574 /// overlapping impls for it is sound.
1576 /// To handle this, we basically regard the trait as a marker trait, with an additional
1577 /// future-compatibility warning. To avoid accidentally "stabilizing" this feature,
1578 /// it has the following restrictions:
1580 /// 1. The trait must indeed be a marker-like trait (i.e., no items), and must be
1582 /// 2. The trait-ref of both impls must be equal.
1583 /// 3. The trait-ref of both impls must be a trait object type consisting only of
1585 /// 4. Neither of the impls can have any where-clauses.
1587 /// Once `traitobject` 0.1.0 is no longer an active concern, this hack can be removed.
1591 impl<'tcx> TyCtxt<'tcx> {
1592 pub fn typeck_body(self, body: hir::BodyId) -> &'tcx TypeckResults<'tcx> {
1593 self.typeck(self.hir().body_owner_def_id(body))
1596 /// Returns an iterator of the `DefId`s for all body-owners in this
1597 /// crate. If you would prefer to iterate over the bodies
1598 /// themselves, you can do `self.hir().krate().body_ids.iter()`.
1599 pub fn body_owners(self) -> impl Iterator<Item = LocalDefId> + Captures<'tcx> + 'tcx {
1604 .map(move |&body_id| self.hir().body_owner_def_id(body_id))
1607 pub fn par_body_owners<F: Fn(LocalDefId) + sync::Sync + sync::Send>(self, f: F) {
1608 par_iter(&self.hir().krate().body_ids)
1609 .for_each(|&body_id| f(self.hir().body_owner_def_id(body_id)));
1612 pub fn provided_trait_methods(self, id: DefId) -> impl 'tcx + Iterator<Item = &'tcx AssocItem> {
1613 self.associated_items(id)
1614 .in_definition_order()
1615 .filter(|item| item.kind == AssocKind::Fn && item.defaultness.has_value())
1618 fn item_name_from_hir(self, def_id: DefId) -> Option<Ident> {
1619 self.hir().get_if_local(def_id).and_then(|node| node.ident())
1622 fn item_name_from_def_id(self, def_id: DefId) -> Option<Symbol> {
1623 if def_id.index == CRATE_DEF_INDEX {
1624 Some(self.crate_name(def_id.krate))
1626 let def_key = self.def_key(def_id);
1627 match def_key.disambiguated_data.data {
1628 // The name of a constructor is that of its parent.
1629 rustc_hir::definitions::DefPathData::Ctor => self.item_name_from_def_id(DefId {
1630 krate: def_id.krate,
1631 index: def_key.parent.unwrap(),
1633 _ => def_key.disambiguated_data.data.get_opt_name(),
1638 /// Look up the name of an item across crates. This does not look at HIR.
1640 /// When possible, this function should be used for cross-crate lookups over
1641 /// [`opt_item_name`] to avoid invalidating the incremental cache. If you
1642 /// need to handle items without a name, or HIR items that will not be
1643 /// serialized cross-crate, or if you need the span of the item, use
1644 /// [`opt_item_name`] instead.
1646 /// [`opt_item_name`]: Self::opt_item_name
1647 pub fn item_name(self, id: DefId) -> Symbol {
1648 // Look at cross-crate items first to avoid invalidating the incremental cache
1649 // unless we have to.
1650 self.item_name_from_def_id(id).unwrap_or_else(|| {
1651 bug!("item_name: no name for {:?}", self.def_path(id));
1655 /// Look up the name and span of an item or [`Node`].
1657 /// See [`item_name`][Self::item_name] for more information.
1658 pub fn opt_item_name(self, def_id: DefId) -> Option<Ident> {
1659 // Look at the HIR first so the span will be correct if this is a local item.
1660 self.item_name_from_hir(def_id)
1661 .or_else(|| self.item_name_from_def_id(def_id).map(Ident::with_dummy_span))
1664 pub fn opt_associated_item(self, def_id: DefId) -> Option<&'tcx AssocItem> {
1665 if let DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy = self.def_kind(def_id) {
1666 Some(self.associated_item(def_id))
1672 pub fn field_index(self, hir_id: hir::HirId, typeck_results: &TypeckResults<'_>) -> usize {
1673 typeck_results.field_indices().get(hir_id).cloned().expect("no index for a field")
1676 pub fn find_field_index(self, ident: Ident, variant: &VariantDef) -> Option<usize> {
1677 variant.fields.iter().position(|field| self.hygienic_eq(ident, field.ident, variant.def_id))
1680 /// Returns `true` if the impls are the same polarity and the trait either
1681 /// has no items or is annotated `#[marker]` and prevents item overrides.
1682 pub fn impls_are_allowed_to_overlap(
1686 ) -> Option<ImplOverlapKind> {
1687 // If either trait impl references an error, they're allowed to overlap,
1688 // as one of them essentially doesn't exist.
1689 if self.impl_trait_ref(def_id1).map_or(false, |tr| tr.references_error())
1690 || self.impl_trait_ref(def_id2).map_or(false, |tr| tr.references_error())
1692 return Some(ImplOverlapKind::Permitted { marker: false });
1695 match (self.impl_polarity(def_id1), self.impl_polarity(def_id2)) {
1696 (ImplPolarity::Reservation, _) | (_, ImplPolarity::Reservation) => {
1697 // `#[rustc_reservation_impl]` impls don't overlap with anything
1699 "impls_are_allowed_to_overlap({:?}, {:?}) = Some(Permitted) (reservations)",
1702 return Some(ImplOverlapKind::Permitted { marker: false });
1704 (ImplPolarity::Positive, ImplPolarity::Negative)
1705 | (ImplPolarity::Negative, ImplPolarity::Positive) => {
1706 // `impl AutoTrait for Type` + `impl !AutoTrait for Type`
1708 "impls_are_allowed_to_overlap({:?}, {:?}) - None (differing polarities)",
1713 (ImplPolarity::Positive, ImplPolarity::Positive)
1714 | (ImplPolarity::Negative, ImplPolarity::Negative) => {}
1717 let is_marker_overlap = {
1718 let is_marker_impl = |def_id: DefId| -> bool {
1719 let trait_ref = self.impl_trait_ref(def_id);
1720 trait_ref.map_or(false, |tr| self.trait_def(tr.def_id).is_marker)
1722 is_marker_impl(def_id1) && is_marker_impl(def_id2)
1725 if is_marker_overlap {
1727 "impls_are_allowed_to_overlap({:?}, {:?}) = Some(Permitted) (marker overlap)",
1730 Some(ImplOverlapKind::Permitted { marker: true })
1732 if let Some(self_ty1) = self.issue33140_self_ty(def_id1) {
1733 if let Some(self_ty2) = self.issue33140_self_ty(def_id2) {
1734 if self_ty1 == self_ty2 {
1736 "impls_are_allowed_to_overlap({:?}, {:?}) - issue #33140 HACK",
1739 return Some(ImplOverlapKind::Issue33140);
1742 "impls_are_allowed_to_overlap({:?}, {:?}) - found {:?} != {:?}",
1743 def_id1, def_id2, self_ty1, self_ty2
1749 debug!("impls_are_allowed_to_overlap({:?}, {:?}) = None", def_id1, def_id2);
1754 /// Returns `ty::VariantDef` if `res` refers to a struct,
1755 /// or variant or their constructors, panics otherwise.
1756 pub fn expect_variant_res(self, res: Res) -> &'tcx VariantDef {
1758 Res::Def(DefKind::Variant, did) => {
1759 let enum_did = self.parent(did).unwrap();
1760 self.adt_def(enum_did).variant_with_id(did)
1762 Res::Def(DefKind::Struct | DefKind::Union, did) => self.adt_def(did).non_enum_variant(),
1763 Res::Def(DefKind::Ctor(CtorOf::Variant, ..), variant_ctor_did) => {
1764 let variant_did = self.parent(variant_ctor_did).unwrap();
1765 let enum_did = self.parent(variant_did).unwrap();
1766 self.adt_def(enum_did).variant_with_ctor_id(variant_ctor_did)
1768 Res::Def(DefKind::Ctor(CtorOf::Struct, ..), ctor_did) => {
1769 let struct_did = self.parent(ctor_did).expect("struct ctor has no parent");
1770 self.adt_def(struct_did).non_enum_variant()
1772 _ => bug!("expect_variant_res used with unexpected res {:?}", res),
1776 /// Returns the possibly-auto-generated MIR of a `(DefId, Subst)` pair.
1777 pub fn instance_mir(self, instance: ty::InstanceDef<'tcx>) -> &'tcx Body<'tcx> {
1779 ty::InstanceDef::Item(def) => match self.def_kind(def.did) {
1782 | DefKind::AssocConst
1784 | DefKind::AnonConst => self.mir_for_ctfe_opt_const_arg(def),
1785 // If the caller wants `mir_for_ctfe` of a function they should not be using
1786 // `instance_mir`, so we'll assume const fn also wants the optimized version.
1788 assert_eq!(def.const_param_did, None);
1789 self.optimized_mir(def.did)
1792 ty::InstanceDef::VtableShim(..)
1793 | ty::InstanceDef::ReifyShim(..)
1794 | ty::InstanceDef::Intrinsic(..)
1795 | ty::InstanceDef::FnPtrShim(..)
1796 | ty::InstanceDef::Virtual(..)
1797 | ty::InstanceDef::ClosureOnceShim { .. }
1798 | ty::InstanceDef::DropGlue(..)
1799 | ty::InstanceDef::CloneShim(..) => self.mir_shims(instance),
1803 /// Gets the attributes of a definition.
1804 pub fn get_attrs(self, did: DefId) -> Attributes<'tcx> {
1805 if let Some(did) = did.as_local() {
1806 self.hir().attrs(self.hir().local_def_id_to_hir_id(did))
1808 self.item_attrs(did)
1812 /// Determines whether an item is annotated with an attribute.
1813 pub fn has_attr(self, did: DefId, attr: Symbol) -> bool {
1814 self.sess.contains_name(&self.get_attrs(did), attr)
1817 /// Returns `true` if this is an `auto trait`.
1818 pub fn trait_is_auto(self, trait_def_id: DefId) -> bool {
1819 self.trait_def(trait_def_id).has_auto_impl
1822 /// Returns layout of a generator. Layout might be unavailable if the
1823 /// generator is tainted by errors.
1824 pub fn generator_layout(self, def_id: DefId) -> Option<&'tcx GeneratorLayout<'tcx>> {
1825 self.optimized_mir(def_id).generator_layout()
1828 /// Given the `DefId` of an impl, returns the `DefId` of the trait it implements.
1829 /// If it implements no trait, returns `None`.
1830 pub fn trait_id_of_impl(self, def_id: DefId) -> Option<DefId> {
1831 self.impl_trait_ref(def_id).map(|tr| tr.def_id)
1834 /// If the given defid describes a method belonging to an impl, returns the
1835 /// `DefId` of the impl that the method belongs to; otherwise, returns `None`.
1836 pub fn impl_of_method(self, def_id: DefId) -> Option<DefId> {
1837 self.opt_associated_item(def_id).and_then(|trait_item| match trait_item.container {
1838 TraitContainer(_) => None,
1839 ImplContainer(def_id) => Some(def_id),
1843 /// Looks up the span of `impl_did` if the impl is local; otherwise returns `Err`
1844 /// with the name of the crate containing the impl.
1845 pub fn span_of_impl(self, impl_did: DefId) -> Result<Span, Symbol> {
1846 if let Some(impl_did) = impl_did.as_local() {
1847 let hir_id = self.hir().local_def_id_to_hir_id(impl_did);
1848 Ok(self.hir().span(hir_id))
1850 Err(self.crate_name(impl_did.krate))
1854 /// Hygienically compares a use-site name (`use_name`) for a field or an associated item with
1855 /// its supposed definition name (`def_name`). The method also needs `DefId` of the supposed
1856 /// definition's parent/scope to perform comparison.
1857 pub fn hygienic_eq(self, use_name: Ident, def_name: Ident, def_parent_def_id: DefId) -> bool {
1858 // We could use `Ident::eq` here, but we deliberately don't. The name
1859 // comparison fails frequently, and we want to avoid the expensive
1860 // `normalize_to_macros_2_0()` calls required for the span comparison whenever possible.
1861 use_name.name == def_name.name
1865 .hygienic_eq(def_name.span.ctxt(), self.expansion_that_defined(def_parent_def_id))
1868 pub fn expansion_that_defined(self, scope: DefId) -> ExpnId {
1869 match scope.as_local() {
1870 // Parsing and expansion aren't incremental, so we don't
1871 // need to go through a query for the same-crate case.
1872 Some(scope) => self.hir().definitions().expansion_that_defined(scope),
1873 None => self.expn_that_defined(scope),
1877 pub fn adjust_ident(self, mut ident: Ident, scope: DefId) -> Ident {
1878 ident.span.normalize_to_macros_2_0_and_adjust(self.expansion_that_defined(scope));
1882 pub fn adjust_ident_and_get_scope(
1887 ) -> (Ident, DefId) {
1889 match ident.span.normalize_to_macros_2_0_and_adjust(self.expansion_that_defined(scope))
1891 Some(actual_expansion) => {
1892 self.hir().definitions().parent_module_of_macro_def(actual_expansion)
1894 None => self.parent_module(block).to_def_id(),
1899 pub fn is_object_safe(self, key: DefId) -> bool {
1900 self.object_safety_violations(key).is_empty()
1904 /// Yields the parent function's `DefId` if `def_id` is an `impl Trait` definition.
1905 pub fn is_impl_trait_defn(tcx: TyCtxt<'_>, def_id: DefId) -> Option<DefId> {
1906 if let Some(def_id) = def_id.as_local() {
1907 if let Node::Item(item) = tcx.hir().get(tcx.hir().local_def_id_to_hir_id(def_id)) {
1908 if let hir::ItemKind::OpaqueTy(ref opaque_ty) = item.kind {
1909 return opaque_ty.impl_trait_fn;
1916 pub fn int_ty(ity: ast::IntTy) -> IntTy {
1918 ast::IntTy::Isize => IntTy::Isize,
1919 ast::IntTy::I8 => IntTy::I8,
1920 ast::IntTy::I16 => IntTy::I16,
1921 ast::IntTy::I32 => IntTy::I32,
1922 ast::IntTy::I64 => IntTy::I64,
1923 ast::IntTy::I128 => IntTy::I128,
1927 pub fn uint_ty(uty: ast::UintTy) -> UintTy {
1929 ast::UintTy::Usize => UintTy::Usize,
1930 ast::UintTy::U8 => UintTy::U8,
1931 ast::UintTy::U16 => UintTy::U16,
1932 ast::UintTy::U32 => UintTy::U32,
1933 ast::UintTy::U64 => UintTy::U64,
1934 ast::UintTy::U128 => UintTy::U128,
1938 pub fn float_ty(fty: ast::FloatTy) -> FloatTy {
1940 ast::FloatTy::F32 => FloatTy::F32,
1941 ast::FloatTy::F64 => FloatTy::F64,
1945 pub fn ast_int_ty(ity: IntTy) -> ast::IntTy {
1947 IntTy::Isize => ast::IntTy::Isize,
1948 IntTy::I8 => ast::IntTy::I8,
1949 IntTy::I16 => ast::IntTy::I16,
1950 IntTy::I32 => ast::IntTy::I32,
1951 IntTy::I64 => ast::IntTy::I64,
1952 IntTy::I128 => ast::IntTy::I128,
1956 pub fn ast_uint_ty(uty: UintTy) -> ast::UintTy {
1958 UintTy::Usize => ast::UintTy::Usize,
1959 UintTy::U8 => ast::UintTy::U8,
1960 UintTy::U16 => ast::UintTy::U16,
1961 UintTy::U32 => ast::UintTy::U32,
1962 UintTy::U64 => ast::UintTy::U64,
1963 UintTy::U128 => ast::UintTy::U128,
1967 pub fn provide(providers: &mut ty::query::Providers) {
1968 context::provide(providers);
1969 erase_regions::provide(providers);
1970 layout::provide(providers);
1971 util::provide(providers);
1972 print::provide(providers);
1973 super::util::bug::provide(providers);
1974 *providers = ty::query::Providers {
1975 trait_impls_of: trait_def::trait_impls_of_provider,
1976 type_uninhabited_from: inhabitedness::type_uninhabited_from,
1977 const_param_default: consts::const_param_default,
1982 /// A map for the local crate mapping each type to a vector of its
1983 /// inherent impls. This is not meant to be used outside of coherence;
1984 /// rather, you should request the vector for a specific type via
1985 /// `tcx.inherent_impls(def_id)` so as to minimize your dependencies
1986 /// (constructing this map requires touching the entire crate).
1987 #[derive(Clone, Debug, Default, HashStable)]
1988 pub struct CrateInherentImpls {
1989 pub inherent_impls: LocalDefIdMap<Vec<DefId>>,
1992 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, HashStable)]
1993 pub struct SymbolName<'tcx> {
1994 /// `&str` gives a consistent ordering, which ensures reproducible builds.
1995 pub name: &'tcx str,
1998 impl<'tcx> SymbolName<'tcx> {
1999 pub fn new(tcx: TyCtxt<'tcx>, name: &str) -> SymbolName<'tcx> {
2001 name: unsafe { str::from_utf8_unchecked(tcx.arena.alloc_slice(name.as_bytes())) },
2006 impl<'tcx> fmt::Display for SymbolName<'tcx> {
2007 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2008 fmt::Display::fmt(&self.name, fmt)
2012 impl<'tcx> fmt::Debug for SymbolName<'tcx> {
2013 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2014 fmt::Display::fmt(&self.name, fmt)