1 // ignore-tidy-filelength
2 pub use self::fold::{TypeFoldable, TypeFolder, TypeVisitor};
3 pub use self::AssocItemContainer::*;
4 pub use self::BorrowKind::*;
5 pub use self::IntVarValue::*;
6 pub use self::Variance::*;
8 use crate::hir::exports::ExportMap;
9 use crate::hir::place::Place as HirPlace;
10 use crate::ich::StableHashingContext;
11 use crate::middle::cstore::CrateStoreDyn;
12 use crate::middle::resolve_lifetime::ObjectLifetimeDefault;
13 use crate::mir::interpret::ErrorHandled;
15 use crate::mir::GeneratorLayout;
16 use crate::traits::{self, Reveal};
18 use crate::ty::subst::{GenericArg, InternalSubsts, Subst, SubstsRef};
19 use crate::ty::util::{Discr, IntTypeExt};
21 use rustc_attr as attr;
22 use rustc_data_structures::captures::Captures;
23 use rustc_data_structures::fingerprint::Fingerprint;
24 use rustc_data_structures::fx::FxHashMap;
25 use rustc_data_structures::fx::FxHashSet;
26 use rustc_data_structures::fx::FxIndexMap;
27 use rustc_data_structures::sorted_map::SortedIndexMultiMap;
28 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
29 use rustc_data_structures::sync::{self, par_iter, ParallelIterator};
30 use rustc_data_structures::tagged_ptr::CopyTaggedPtr;
31 use rustc_errors::ErrorReported;
33 use rustc_hir::def::{CtorKind, CtorOf, DefKind, Namespace, Res};
34 use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, LocalDefId, CRATE_DEF_INDEX};
35 use rustc_hir::lang_items::LangItem;
36 use rustc_hir::{Constness, Node};
37 use rustc_index::vec::{Idx, IndexVec};
38 use rustc_macros::HashStable;
39 use rustc_serialize::{self, Encodable, Encoder};
40 use rustc_session::DataTypeKind;
41 use rustc_span::hygiene::ExpnId;
42 use rustc_span::symbol::{kw, sym, Ident, Symbol};
44 use rustc_target::abi::{Align, VariantIdx};
46 use std::cell::RefCell;
47 use std::cmp::Ordering;
49 use std::hash::{Hash, Hasher};
50 use std::ops::{ControlFlow, Range};
54 pub use self::sty::BoundRegion::*;
55 pub use self::sty::InferTy::*;
56 pub use self::sty::RegionKind;
57 pub use self::sty::RegionKind::*;
58 pub use self::sty::TyKind::*;
59 pub use self::sty::{Binder, BoundTy, BoundTyKind, BoundVar, DebruijnIndex, INNERMOST};
60 pub use self::sty::{BoundRegion, EarlyBoundRegion, FreeRegion, Region};
61 pub use self::sty::{CanonicalPolyFnSig, FnSig, GenSig, PolyFnSig, PolyGenSig};
62 pub use self::sty::{ClosureSubsts, GeneratorSubsts, TypeAndMut, UpvarSubsts};
63 pub use self::sty::{ClosureSubstsParts, GeneratorSubstsParts};
64 pub use self::sty::{ConstVid, FloatVid, IntVid, RegionVid, TyVid};
65 pub use self::sty::{ExistentialPredicate, InferTy, ParamConst, ParamTy, ProjectionTy};
66 pub use self::sty::{ExistentialProjection, PolyExistentialProjection};
67 pub use self::sty::{ExistentialTraitRef, PolyExistentialTraitRef};
68 pub use self::sty::{PolyTraitRef, TraitRef, TyKind};
69 pub use crate::ty::diagnostics::*;
71 pub use self::binding::BindingMode;
72 pub use self::binding::BindingMode::*;
74 pub use self::context::{tls, FreeRegionInfo, TyCtxt};
75 pub use self::context::{
76 CanonicalUserType, CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations,
77 DelaySpanBugEmitted, ResolvedOpaqueTy, UserType, UserTypeAnnotationIndex,
79 pub use self::context::{
80 CtxtInterners, GeneratorInteriorTypeCause, GlobalCtxt, Lift, TypeckResults,
83 pub use self::instance::{Instance, InstanceDef};
85 pub use self::list::List;
87 pub use self::trait_def::TraitDef;
89 pub use self::query::queries;
91 pub use self::consts::{Const, ConstInt, ConstKind, InferConst, ScalarInt};
103 pub mod inhabitedness;
105 pub mod normalize_erasing_regions;
120 mod structural_impls;
125 pub struct ResolverOutputs {
126 pub definitions: rustc_hir::definitions::Definitions,
127 pub cstore: Box<CrateStoreDyn>,
128 pub visibilities: FxHashMap<LocalDefId, Visibility>,
129 pub extern_crate_map: FxHashMap<LocalDefId, CrateNum>,
130 pub maybe_unused_trait_imports: FxHashSet<LocalDefId>,
131 pub maybe_unused_extern_crates: Vec<(LocalDefId, Span)>,
132 pub export_map: ExportMap<LocalDefId>,
133 pub glob_map: FxHashMap<LocalDefId, FxHashSet<Symbol>>,
134 /// Extern prelude entries. The value is `true` if the entry was introduced
135 /// via `extern crate` item and not `--extern` option or compiler built-in.
136 pub extern_prelude: FxHashMap<Symbol, bool>,
139 #[derive(Clone, Copy, PartialEq, Eq, Debug, HashStable, Hash)]
140 pub enum AssocItemContainer {
141 TraitContainer(DefId),
142 ImplContainer(DefId),
145 impl AssocItemContainer {
146 /// Asserts that this is the `DefId` of an associated item declared
147 /// in a trait, and returns the trait `DefId`.
148 pub fn assert_trait(&self) -> DefId {
150 TraitContainer(id) => id,
151 _ => bug!("associated item has wrong container type: {:?}", self),
155 pub fn id(&self) -> DefId {
157 TraitContainer(id) => id,
158 ImplContainer(id) => id,
163 /// The "header" of an impl is everything outside the body: a Self type, a trait
164 /// ref (in the case of a trait impl), and a set of predicates (from the
165 /// bounds / where-clauses).
166 #[derive(Clone, Debug, TypeFoldable)]
167 pub struct ImplHeader<'tcx> {
168 pub impl_def_id: DefId,
169 pub self_ty: Ty<'tcx>,
170 pub trait_ref: Option<TraitRef<'tcx>>,
171 pub predicates: Vec<Predicate<'tcx>>,
174 #[derive(Copy, Clone, PartialEq, TyEncodable, TyDecodable, HashStable)]
175 pub enum ImplPolarity {
176 /// `impl Trait for Type`
178 /// `impl !Trait for Type`
180 /// `#[rustc_reservation_impl] impl Trait for Type`
182 /// This is a "stability hack", not a real Rust feature.
183 /// See #64631 for details.
187 #[derive(Copy, Clone, Debug, PartialEq, HashStable, Eq, Hash)]
188 pub struct AssocItem {
190 #[stable_hasher(project(name))]
194 pub defaultness: hir::Defaultness,
195 pub container: AssocItemContainer,
197 /// Whether this is a method with an explicit self
198 /// as its first parameter, allowing method calls.
199 pub fn_has_self_parameter: bool,
202 #[derive(Copy, Clone, PartialEq, Debug, HashStable, Eq, Hash)]
210 pub fn namespace(&self) -> Namespace {
212 ty::AssocKind::Type => Namespace::TypeNS,
213 ty::AssocKind::Const | ty::AssocKind::Fn => Namespace::ValueNS,
217 pub fn as_def_kind(&self) -> DefKind {
219 AssocKind::Const => DefKind::AssocConst,
220 AssocKind::Fn => DefKind::AssocFn,
221 AssocKind::Type => DefKind::AssocTy,
227 pub fn signature(&self, tcx: TyCtxt<'_>) -> String {
229 ty::AssocKind::Fn => {
230 // We skip the binder here because the binder would deanonymize all
231 // late-bound regions, and we don't want method signatures to show up
232 // `as for<'r> fn(&'r MyType)`. Pretty-printing handles late-bound
233 // regions just fine, showing `fn(&MyType)`.
234 tcx.fn_sig(self.def_id).skip_binder().to_string()
236 ty::AssocKind::Type => format!("type {};", self.ident),
237 ty::AssocKind::Const => {
238 format!("const {}: {:?};", self.ident, tcx.type_of(self.def_id))
244 /// A list of `ty::AssocItem`s in definition order that allows for efficient lookup by name.
246 /// When doing lookup by name, we try to postpone hygienic comparison for as long as possible since
247 /// it is relatively expensive. Instead, items are indexed by `Symbol` and hygienic comparison is
248 /// done only on items with the same name.
249 #[derive(Debug, Clone, PartialEq, HashStable)]
250 pub struct AssociatedItems<'tcx> {
251 items: SortedIndexMultiMap<u32, Symbol, &'tcx ty::AssocItem>,
254 impl<'tcx> AssociatedItems<'tcx> {
255 /// Constructs an `AssociatedItems` map from a series of `ty::AssocItem`s in definition order.
256 pub fn new(items_in_def_order: impl IntoIterator<Item = &'tcx ty::AssocItem>) -> Self {
257 let items = items_in_def_order.into_iter().map(|item| (item.ident.name, item)).collect();
258 AssociatedItems { items }
261 /// Returns a slice of associated items in the order they were defined.
263 /// New code should avoid relying on definition order. If you need a particular associated item
264 /// for a known trait, make that trait a lang item instead of indexing this array.
265 pub fn in_definition_order(&self) -> impl '_ + Iterator<Item = &ty::AssocItem> {
266 self.items.iter().map(|(_, v)| *v)
269 pub fn len(&self) -> usize {
273 /// Returns an iterator over all associated items with the given name, ignoring hygiene.
274 pub fn filter_by_name_unhygienic(
277 ) -> impl '_ + Iterator<Item = &ty::AssocItem> {
278 self.items.get_by_key(&name).copied()
281 /// Returns an iterator over all associated items with the given name.
283 /// Multiple items may have the same name if they are in different `Namespace`s. For example,
284 /// an associated type can have the same name as a method. Use one of the `find_by_name_and_*`
285 /// methods below if you know which item you are looking for.
286 pub fn filter_by_name(
290 parent_def_id: DefId,
291 ) -> impl 'a + Iterator<Item = &'a ty::AssocItem> {
292 self.filter_by_name_unhygienic(ident.name)
293 .filter(move |item| tcx.hygienic_eq(ident, item.ident, parent_def_id))
296 /// Returns the associated item with the given name and `AssocKind`, if one exists.
297 pub fn find_by_name_and_kind(
302 parent_def_id: DefId,
303 ) -> Option<&ty::AssocItem> {
304 self.filter_by_name_unhygienic(ident.name)
305 .filter(|item| item.kind == kind)
306 .find(|item| tcx.hygienic_eq(ident, item.ident, parent_def_id))
309 /// Returns the associated item with the given name in the given `Namespace`, if one exists.
310 pub fn find_by_name_and_namespace(
315 parent_def_id: DefId,
316 ) -> Option<&ty::AssocItem> {
317 self.filter_by_name_unhygienic(ident.name)
318 .filter(|item| item.kind.namespace() == ns)
319 .find(|item| tcx.hygienic_eq(ident, item.ident, parent_def_id))
323 #[derive(Clone, Debug, PartialEq, Eq, Copy, Hash, TyEncodable, TyDecodable, HashStable)]
324 pub enum Visibility {
325 /// Visible everywhere (including in other crates).
327 /// Visible only in the given crate-local module.
329 /// Not visible anywhere in the local crate. This is the visibility of private external items.
333 pub trait DefIdTree: Copy {
334 fn parent(self, id: DefId) -> Option<DefId>;
336 fn is_descendant_of(self, mut descendant: DefId, ancestor: DefId) -> bool {
337 if descendant.krate != ancestor.krate {
341 while descendant != ancestor {
342 match self.parent(descendant) {
343 Some(parent) => descendant = parent,
344 None => return false,
351 impl<'tcx> DefIdTree for TyCtxt<'tcx> {
352 fn parent(self, id: DefId) -> Option<DefId> {
353 self.def_key(id).parent.map(|index| DefId { index, ..id })
358 pub fn from_hir(visibility: &hir::Visibility<'_>, id: hir::HirId, tcx: TyCtxt<'_>) -> Self {
359 match visibility.node {
360 hir::VisibilityKind::Public => Visibility::Public,
361 hir::VisibilityKind::Crate(_) => Visibility::Restricted(DefId::local(CRATE_DEF_INDEX)),
362 hir::VisibilityKind::Restricted { ref path, .. } => match path.res {
363 // If there is no resolution, `resolve` will have already reported an error, so
364 // assume that the visibility is public to avoid reporting more privacy errors.
365 Res::Err => Visibility::Public,
366 def => Visibility::Restricted(def.def_id()),
368 hir::VisibilityKind::Inherited => {
369 Visibility::Restricted(tcx.parent_module(id).to_def_id())
374 /// Returns `true` if an item with this visibility is accessible from the given block.
375 pub fn is_accessible_from<T: DefIdTree>(self, module: DefId, tree: T) -> bool {
376 let restriction = match self {
377 // Public items are visible everywhere.
378 Visibility::Public => return true,
379 // Private items from other crates are visible nowhere.
380 Visibility::Invisible => return false,
381 // Restricted items are visible in an arbitrary local module.
382 Visibility::Restricted(other) if other.krate != module.krate => return false,
383 Visibility::Restricted(module) => module,
386 tree.is_descendant_of(module, restriction)
389 /// Returns `true` if this visibility is at least as accessible as the given visibility
390 pub fn is_at_least<T: DefIdTree>(self, vis: Visibility, tree: T) -> bool {
391 let vis_restriction = match vis {
392 Visibility::Public => return self == Visibility::Public,
393 Visibility::Invisible => return true,
394 Visibility::Restricted(module) => module,
397 self.is_accessible_from(vis_restriction, tree)
400 // Returns `true` if this item is visible anywhere in the local crate.
401 pub fn is_visible_locally(self) -> bool {
403 Visibility::Public => true,
404 Visibility::Restricted(def_id) => def_id.is_local(),
405 Visibility::Invisible => false,
410 #[derive(Copy, Clone, PartialEq, TyDecodable, TyEncodable, HashStable)]
412 Covariant, // T<A> <: T<B> iff A <: B -- e.g., function return type
413 Invariant, // T<A> <: T<B> iff B == A -- e.g., type of mutable cell
414 Contravariant, // T<A> <: T<B> iff B <: A -- e.g., function param type
415 Bivariant, // T<A> <: T<B> -- e.g., unused type parameter
418 /// The crate variances map is computed during typeck and contains the
419 /// variance of every item in the local crate. You should not use it
420 /// directly, because to do so will make your pass dependent on the
421 /// HIR of every item in the local crate. Instead, use
422 /// `tcx.variances_of()` to get the variance for a *particular*
424 #[derive(HashStable)]
425 pub struct CrateVariancesMap<'tcx> {
426 /// For each item with generics, maps to a vector of the variance
427 /// of its generics. If an item has no generics, it will have no
429 pub variances: FxHashMap<DefId, &'tcx [ty::Variance]>,
433 /// `a.xform(b)` combines the variance of a context with the
434 /// variance of a type with the following meaning. If we are in a
435 /// context with variance `a`, and we encounter a type argument in
436 /// a position with variance `b`, then `a.xform(b)` is the new
437 /// variance with which the argument appears.
443 /// Here, the "ambient" variance starts as covariant. `*mut T` is
444 /// invariant with respect to `T`, so the variance in which the
445 /// `Vec<i32>` appears is `Covariant.xform(Invariant)`, which
446 /// yields `Invariant`. Now, the type `Vec<T>` is covariant with
447 /// respect to its type argument `T`, and hence the variance of
448 /// the `i32` here is `Invariant.xform(Covariant)`, which results
449 /// (again) in `Invariant`.
453 /// fn(*const Vec<i32>, *mut Vec<i32)
455 /// The ambient variance is covariant. A `fn` type is
456 /// contravariant with respect to its parameters, so the variance
457 /// within which both pointer types appear is
458 /// `Covariant.xform(Contravariant)`, or `Contravariant`. `*const
459 /// T` is covariant with respect to `T`, so the variance within
460 /// which the first `Vec<i32>` appears is
461 /// `Contravariant.xform(Covariant)` or `Contravariant`. The same
462 /// is true for its `i32` argument. In the `*mut T` case, the
463 /// variance of `Vec<i32>` is `Contravariant.xform(Invariant)`,
464 /// and hence the outermost type is `Invariant` with respect to
465 /// `Vec<i32>` (and its `i32` argument).
467 /// Source: Figure 1 of "Taming the Wildcards:
468 /// Combining Definition- and Use-Site Variance" published in PLDI'11.
469 pub fn xform(self, v: ty::Variance) -> ty::Variance {
471 // Figure 1, column 1.
472 (ty::Covariant, ty::Covariant) => ty::Covariant,
473 (ty::Covariant, ty::Contravariant) => ty::Contravariant,
474 (ty::Covariant, ty::Invariant) => ty::Invariant,
475 (ty::Covariant, ty::Bivariant) => ty::Bivariant,
477 // Figure 1, column 2.
478 (ty::Contravariant, ty::Covariant) => ty::Contravariant,
479 (ty::Contravariant, ty::Contravariant) => ty::Covariant,
480 (ty::Contravariant, ty::Invariant) => ty::Invariant,
481 (ty::Contravariant, ty::Bivariant) => ty::Bivariant,
483 // Figure 1, column 3.
484 (ty::Invariant, _) => ty::Invariant,
486 // Figure 1, column 4.
487 (ty::Bivariant, _) => ty::Bivariant,
492 // Contains information needed to resolve types and (in the future) look up
493 // the types of AST nodes.
494 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
495 pub struct CReaderCacheKey {
501 /// Flags that we track on types. These flags are propagated upwards
502 /// through the type during type construction, so that we can quickly check
503 /// whether the type has various kinds of types in it without recursing
504 /// over the type itself.
505 pub struct TypeFlags: u32 {
506 // Does this have parameters? Used to determine whether substitution is
508 /// Does this have [Param]?
509 const HAS_TY_PARAM = 1 << 0;
510 /// Does this have [ReEarlyBound]?
511 const HAS_RE_PARAM = 1 << 1;
512 /// Does this have [ConstKind::Param]?
513 const HAS_CT_PARAM = 1 << 2;
515 const NEEDS_SUBST = TypeFlags::HAS_TY_PARAM.bits
516 | TypeFlags::HAS_RE_PARAM.bits
517 | TypeFlags::HAS_CT_PARAM.bits;
519 /// Does this have [Infer]?
520 const HAS_TY_INFER = 1 << 3;
521 /// Does this have [ReVar]?
522 const HAS_RE_INFER = 1 << 4;
523 /// Does this have [ConstKind::Infer]?
524 const HAS_CT_INFER = 1 << 5;
526 /// Does this have inference variables? Used to determine whether
527 /// inference is required.
528 const NEEDS_INFER = TypeFlags::HAS_TY_INFER.bits
529 | TypeFlags::HAS_RE_INFER.bits
530 | TypeFlags::HAS_CT_INFER.bits;
532 /// Does this have [Placeholder]?
533 const HAS_TY_PLACEHOLDER = 1 << 6;
534 /// Does this have [RePlaceholder]?
535 const HAS_RE_PLACEHOLDER = 1 << 7;
536 /// Does this have [ConstKind::Placeholder]?
537 const HAS_CT_PLACEHOLDER = 1 << 8;
539 /// `true` if there are "names" of regions and so forth
540 /// that are local to a particular fn/inferctxt
541 const HAS_FREE_LOCAL_REGIONS = 1 << 9;
543 /// `true` if there are "names" of types and regions and so forth
544 /// that are local to a particular fn
545 const HAS_FREE_LOCAL_NAMES = TypeFlags::HAS_TY_PARAM.bits
546 | TypeFlags::HAS_CT_PARAM.bits
547 | TypeFlags::HAS_TY_INFER.bits
548 | TypeFlags::HAS_CT_INFER.bits
549 | TypeFlags::HAS_TY_PLACEHOLDER.bits
550 | TypeFlags::HAS_CT_PLACEHOLDER.bits
551 | TypeFlags::HAS_FREE_LOCAL_REGIONS.bits;
553 /// Does this have [Projection]?
554 const HAS_TY_PROJECTION = 1 << 10;
555 /// Does this have [Opaque]?
556 const HAS_TY_OPAQUE = 1 << 11;
557 /// Does this have [ConstKind::Unevaluated]?
558 const HAS_CT_PROJECTION = 1 << 12;
560 /// Could this type be normalized further?
561 const HAS_PROJECTION = TypeFlags::HAS_TY_PROJECTION.bits
562 | TypeFlags::HAS_TY_OPAQUE.bits
563 | TypeFlags::HAS_CT_PROJECTION.bits;
565 /// Is an error type/const reachable?
566 const HAS_ERROR = 1 << 13;
568 /// Does this have any region that "appears free" in the type?
569 /// Basically anything but [ReLateBound] and [ReErased].
570 const HAS_FREE_REGIONS = 1 << 14;
572 /// Does this have any [ReLateBound] regions? Used to check
573 /// if a global bound is safe to evaluate.
574 const HAS_RE_LATE_BOUND = 1 << 15;
576 /// Does this have any [ReErased] regions?
577 const HAS_RE_ERASED = 1 << 16;
579 /// Does this value have parameters/placeholders/inference variables which could be
580 /// replaced later, in a way that would change the results of `impl` specialization?
581 const STILL_FURTHER_SPECIALIZABLE = 1 << 17;
585 #[allow(rustc::usage_of_ty_tykind)]
586 pub struct TyS<'tcx> {
587 /// This field shouldn't be used directly and may be removed in the future.
588 /// Use `TyS::kind()` instead.
590 /// This field shouldn't be used directly and may be removed in the future.
591 /// Use `TyS::flags()` instead.
594 /// This is a kind of confusing thing: it stores the smallest
597 /// (a) the binder itself captures nothing but
598 /// (b) all the late-bound things within the type are captured
599 /// by some sub-binder.
601 /// So, for a type without any late-bound things, like `u32`, this
602 /// will be *innermost*, because that is the innermost binder that
603 /// captures nothing. But for a type `&'D u32`, where `'D` is a
604 /// late-bound region with De Bruijn index `D`, this would be `D + 1`
605 /// -- the binder itself does not capture `D`, but `D` is captured
606 /// by an inner binder.
608 /// We call this concept an "exclusive" binder `D` because all
609 /// De Bruijn indices within the type are contained within `0..D`
611 outer_exclusive_binder: ty::DebruijnIndex,
614 impl<'tcx> TyS<'tcx> {
615 /// A constructor used only for internal testing.
616 #[allow(rustc::usage_of_ty_tykind)]
617 pub fn make_for_test(
620 outer_exclusive_binder: ty::DebruijnIndex,
622 TyS { kind, flags, outer_exclusive_binder }
626 // `TyS` is used a lot. Make sure it doesn't unintentionally get bigger.
627 #[cfg(target_arch = "x86_64")]
628 static_assert_size!(TyS<'_>, 32);
630 impl<'tcx> Ord for TyS<'tcx> {
631 fn cmp(&self, other: &TyS<'tcx>) -> Ordering {
632 self.kind().cmp(other.kind())
636 impl<'tcx> PartialOrd for TyS<'tcx> {
637 fn partial_cmp(&self, other: &TyS<'tcx>) -> Option<Ordering> {
638 Some(self.kind().cmp(other.kind()))
642 impl<'tcx> PartialEq for TyS<'tcx> {
644 fn eq(&self, other: &TyS<'tcx>) -> bool {
648 impl<'tcx> Eq for TyS<'tcx> {}
650 impl<'tcx> Hash for TyS<'tcx> {
651 fn hash<H: Hasher>(&self, s: &mut H) {
652 (self as *const TyS<'_>).hash(s)
656 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for TyS<'tcx> {
657 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
661 // The other fields just provide fast access to information that is
662 // also contained in `kind`, so no need to hash them.
665 outer_exclusive_binder: _,
668 kind.hash_stable(hcx, hasher);
672 #[rustc_diagnostic_item = "Ty"]
673 pub type Ty<'tcx> = &'tcx TyS<'tcx>;
675 #[derive(Clone, Copy, PartialEq, Eq, Hash, TyEncodable, TyDecodable, HashStable)]
676 pub struct UpvarPath {
677 pub hir_id: hir::HirId,
680 /// Upvars do not get their own `NodeId`. Instead, we use the pair of
681 /// the original var ID (that is, the root variable that is referenced
682 /// by the upvar) and the ID of the closure expression.
683 #[derive(Clone, Copy, PartialEq, Eq, Hash, TyEncodable, TyDecodable, HashStable)]
685 pub var_path: UpvarPath,
686 pub closure_expr_id: LocalDefId,
690 pub fn new(var_hir_id: hir::HirId, closure_def_id: LocalDefId) -> UpvarId {
691 UpvarId { var_path: UpvarPath { hir_id: var_hir_id }, closure_expr_id: closure_def_id }
695 #[derive(Clone, PartialEq, Debug, TyEncodable, TyDecodable, Copy, HashStable)]
696 pub enum BorrowKind {
697 /// Data must be immutable and is aliasable.
700 /// Data must be immutable but not aliasable. This kind of borrow
701 /// cannot currently be expressed by the user and is used only in
702 /// implicit closure bindings. It is needed when the closure
703 /// is borrowing or mutating a mutable referent, e.g.:
706 /// let x: &mut isize = ...;
707 /// let y = || *x += 5;
710 /// If we were to try to translate this closure into a more explicit
711 /// form, we'd encounter an error with the code as written:
714 /// struct Env { x: & &mut isize }
715 /// let x: &mut isize = ...;
716 /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
717 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
720 /// This is then illegal because you cannot mutate a `&mut` found
721 /// in an aliasable location. To solve, you'd have to translate with
722 /// an `&mut` borrow:
725 /// struct Env { x: & &mut isize }
726 /// let x: &mut isize = ...;
727 /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
728 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
731 /// Now the assignment to `**env.x` is legal, but creating a
732 /// mutable pointer to `x` is not because `x` is not mutable. We
733 /// could fix this by declaring `x` as `let mut x`. This is ok in
734 /// user code, if awkward, but extra weird for closures, since the
735 /// borrow is hidden.
737 /// So we introduce a "unique imm" borrow -- the referent is
738 /// immutable, but not aliasable. This solves the problem. For
739 /// simplicity, we don't give users the way to express this
740 /// borrow, it's just used when translating closures.
743 /// Data is mutable and not aliasable.
747 /// Information describing the capture of an upvar. This is computed
748 /// during `typeck`, specifically by `regionck`.
749 #[derive(PartialEq, Clone, Debug, Copy, TyEncodable, TyDecodable, HashStable)]
750 pub enum UpvarCapture<'tcx> {
751 /// Upvar is captured by value. This is always true when the
752 /// closure is labeled `move`, but can also be true in other cases
753 /// depending on inference.
755 /// If the upvar was inferred to be captured by value (e.g. `move`
756 /// was not used), then the `Span` points to a usage that
757 /// required it. There may be more than one such usage
758 /// (e.g. `|| { a; a; }`), in which case we pick an
760 ByValue(Option<Span>),
762 /// Upvar is captured by reference.
763 ByRef(UpvarBorrow<'tcx>),
766 #[derive(PartialEq, Clone, Copy, TyEncodable, TyDecodable, HashStable)]
767 pub struct UpvarBorrow<'tcx> {
768 /// The kind of borrow: by-ref upvars have access to shared
769 /// immutable borrows, which are not part of the normal language
771 pub kind: BorrowKind,
773 /// Region of the resulting reference.
774 pub region: ty::Region<'tcx>,
777 /// Given the closure DefId this map provides a map of root variables to minimum
778 /// set of `CapturedPlace`s that need to be tracked to support all captures of that closure.
779 pub type MinCaptureInformationMap<'tcx> = FxHashMap<DefId, RootVariableMinCaptureList<'tcx>>;
781 /// Part of `MinCaptureInformationMap`; Maps a root variable to the list of `CapturedPlace`.
782 /// Used to track the minimum set of `Place`s that need to be captured to support all
783 /// Places captured by the closure starting at a given root variable.
785 /// This provides a convenient and quick way of checking if a variable being used within
786 /// a closure is a capture of a local variable.
787 pub type RootVariableMinCaptureList<'tcx> = FxIndexMap<hir::HirId, MinCaptureList<'tcx>>;
789 /// Part of `MinCaptureInformationMap`; List of `CapturePlace`s.
790 pub type MinCaptureList<'tcx> = Vec<CapturedPlace<'tcx>>;
792 /// A `Place` and the corresponding `CaptureInfo`.
793 #[derive(PartialEq, Clone, Debug, TyEncodable, TyDecodable, HashStable)]
794 pub struct CapturedPlace<'tcx> {
795 pub place: HirPlace<'tcx>,
796 pub info: CaptureInfo<'tcx>,
799 /// Part of `MinCaptureInformationMap`; describes the capture kind (&, &mut, move)
800 /// for a particular capture as well as identifying the part of the source code
801 /// that triggered this capture to occur.
802 #[derive(PartialEq, Clone, Debug, Copy, TyEncodable, TyDecodable, HashStable)]
803 pub struct CaptureInfo<'tcx> {
804 /// Expr Id pointing to use that resulted in selecting the current capture kind
806 /// If the user doesn't enable feature `capture_disjoint_fields` (RFC 2229) then, it is
807 /// possible that we don't see the use of a particular place resulting in expr_id being
808 /// None. In such case we fallback on uvpars_mentioned for span.
819 /// In this example, if `capture_disjoint_fields` is **not** set, then x will be captured,
820 /// but we won't see it being used during capture analysis, since it's essentially a discard.
821 pub expr_id: Option<hir::HirId>,
823 /// Capture mode that was selected
824 pub capture_kind: UpvarCapture<'tcx>,
827 pub type UpvarListMap = FxHashMap<DefId, FxIndexMap<hir::HirId, UpvarId>>;
828 pub type UpvarCaptureMap<'tcx> = FxHashMap<UpvarId, UpvarCapture<'tcx>>;
830 #[derive(Clone, Copy, PartialEq, Eq)]
831 pub enum IntVarValue {
833 UintType(ast::UintTy),
836 #[derive(Clone, Copy, PartialEq, Eq)]
837 pub struct FloatVarValue(pub ast::FloatTy);
839 impl ty::EarlyBoundRegion {
840 /// Does this early bound region have a name? Early bound regions normally
841 /// always have names except when using anonymous lifetimes (`'_`).
842 pub fn has_name(&self) -> bool {
843 self.name != kw::UnderscoreLifetime
847 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable)]
848 pub enum GenericParamDefKind {
852 object_lifetime_default: ObjectLifetimeDefault,
853 synthetic: Option<hir::SyntheticTyParamKind>,
858 impl GenericParamDefKind {
859 pub fn descr(&self) -> &'static str {
861 GenericParamDefKind::Lifetime => "lifetime",
862 GenericParamDefKind::Type { .. } => "type",
863 GenericParamDefKind::Const => "constant",
868 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable)]
869 pub struct GenericParamDef {
874 /// `pure_wrt_drop`, set by the (unsafe) `#[may_dangle]` attribute
875 /// on generic parameter `'a`/`T`, asserts data behind the parameter
876 /// `'a`/`T` won't be accessed during the parent type's `Drop` impl.
877 pub pure_wrt_drop: bool,
879 pub kind: GenericParamDefKind,
882 impl GenericParamDef {
883 pub fn to_early_bound_region_data(&self) -> ty::EarlyBoundRegion {
884 if let GenericParamDefKind::Lifetime = self.kind {
885 ty::EarlyBoundRegion { def_id: self.def_id, index: self.index, name: self.name }
887 bug!("cannot convert a non-lifetime parameter def to an early bound region")
893 pub struct GenericParamCount {
894 pub lifetimes: usize,
899 /// Information about the formal type/lifetime parameters associated
900 /// with an item or method. Analogous to `hir::Generics`.
902 /// The ordering of parameters is the same as in `Subst` (excluding child generics):
903 /// `Self` (optionally), `Lifetime` params..., `Type` params...
904 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable)]
905 pub struct Generics {
906 pub parent: Option<DefId>,
907 pub parent_count: usize,
908 pub params: Vec<GenericParamDef>,
910 /// Reverse map to the `index` field of each `GenericParamDef`.
911 #[stable_hasher(ignore)]
912 pub param_def_id_to_index: FxHashMap<DefId, u32>,
915 pub has_late_bound_regions: Option<Span>,
918 impl<'tcx> Generics {
919 pub fn count(&self) -> usize {
920 self.parent_count + self.params.len()
923 pub fn own_counts(&self) -> GenericParamCount {
924 // We could cache this as a property of `GenericParamCount`, but
925 // the aim is to refactor this away entirely eventually and the
926 // presence of this method will be a constant reminder.
927 let mut own_counts: GenericParamCount = Default::default();
929 for param in &self.params {
931 GenericParamDefKind::Lifetime => own_counts.lifetimes += 1,
932 GenericParamDefKind::Type { .. } => own_counts.types += 1,
933 GenericParamDefKind::Const => own_counts.consts += 1,
940 pub fn requires_monomorphization(&self, tcx: TyCtxt<'tcx>) -> bool {
941 if self.own_requires_monomorphization() {
945 if let Some(parent_def_id) = self.parent {
946 let parent = tcx.generics_of(parent_def_id);
947 parent.requires_monomorphization(tcx)
953 pub fn own_requires_monomorphization(&self) -> bool {
954 for param in &self.params {
956 GenericParamDefKind::Type { .. } | GenericParamDefKind::Const => return true,
957 GenericParamDefKind::Lifetime => {}
963 /// Returns the `GenericParamDef` with the given index.
964 pub fn param_at(&'tcx self, param_index: usize, tcx: TyCtxt<'tcx>) -> &'tcx GenericParamDef {
965 if let Some(index) = param_index.checked_sub(self.parent_count) {
968 tcx.generics_of(self.parent.expect("parent_count > 0 but no parent?"))
969 .param_at(param_index, tcx)
973 /// Returns the `GenericParamDef` associated with this `EarlyBoundRegion`.
976 param: &EarlyBoundRegion,
978 ) -> &'tcx GenericParamDef {
979 let param = self.param_at(param.index as usize, tcx);
981 GenericParamDefKind::Lifetime => param,
982 _ => bug!("expected lifetime parameter, but found another generic parameter"),
986 /// Returns the `GenericParamDef` associated with this `ParamTy`.
987 pub fn type_param(&'tcx self, param: &ParamTy, tcx: TyCtxt<'tcx>) -> &'tcx GenericParamDef {
988 let param = self.param_at(param.index as usize, tcx);
990 GenericParamDefKind::Type { .. } => param,
991 _ => bug!("expected type parameter, but found another generic parameter"),
995 /// Returns the `GenericParamDef` associated with this `ParamConst`.
996 pub fn const_param(&'tcx self, param: &ParamConst, tcx: TyCtxt<'tcx>) -> &GenericParamDef {
997 let param = self.param_at(param.index as usize, tcx);
999 GenericParamDefKind::Const => param,
1000 _ => bug!("expected const parameter, but found another generic parameter"),
1005 /// Bounds on generics.
1006 #[derive(Copy, Clone, Default, Debug, TyEncodable, TyDecodable, HashStable)]
1007 pub struct GenericPredicates<'tcx> {
1008 pub parent: Option<DefId>,
1009 pub predicates: &'tcx [(Predicate<'tcx>, Span)],
1012 impl<'tcx> GenericPredicates<'tcx> {
1016 substs: SubstsRef<'tcx>,
1017 ) -> InstantiatedPredicates<'tcx> {
1018 let mut instantiated = InstantiatedPredicates::empty();
1019 self.instantiate_into(tcx, &mut instantiated, substs);
1023 pub fn instantiate_own(
1026 substs: SubstsRef<'tcx>,
1027 ) -> InstantiatedPredicates<'tcx> {
1028 InstantiatedPredicates {
1029 predicates: self.predicates.iter().map(|(p, _)| p.subst(tcx, substs)).collect(),
1030 spans: self.predicates.iter().map(|(_, sp)| *sp).collect(),
1034 fn instantiate_into(
1037 instantiated: &mut InstantiatedPredicates<'tcx>,
1038 substs: SubstsRef<'tcx>,
1040 if let Some(def_id) = self.parent {
1041 tcx.predicates_of(def_id).instantiate_into(tcx, instantiated, substs);
1043 instantiated.predicates.extend(self.predicates.iter().map(|(p, _)| p.subst(tcx, substs)));
1044 instantiated.spans.extend(self.predicates.iter().map(|(_, sp)| *sp));
1047 pub fn instantiate_identity(&self, tcx: TyCtxt<'tcx>) -> InstantiatedPredicates<'tcx> {
1048 let mut instantiated = InstantiatedPredicates::empty();
1049 self.instantiate_identity_into(tcx, &mut instantiated);
1053 fn instantiate_identity_into(
1056 instantiated: &mut InstantiatedPredicates<'tcx>,
1058 if let Some(def_id) = self.parent {
1059 tcx.predicates_of(def_id).instantiate_identity_into(tcx, instantiated);
1061 instantiated.predicates.extend(self.predicates.iter().map(|(p, _)| p));
1062 instantiated.spans.extend(self.predicates.iter().map(|(_, s)| s));
1067 crate struct PredicateInner<'tcx> {
1068 kind: PredicateKind<'tcx>,
1070 /// See the comment for the corresponding field of [TyS].
1071 outer_exclusive_binder: ty::DebruijnIndex,
1074 #[cfg(target_arch = "x86_64")]
1075 static_assert_size!(PredicateInner<'_>, 48);
1077 #[derive(Clone, Copy, Lift)]
1078 pub struct Predicate<'tcx> {
1079 inner: &'tcx PredicateInner<'tcx>,
1082 impl<'tcx> PartialEq for Predicate<'tcx> {
1083 fn eq(&self, other: &Self) -> bool {
1084 // `self.kind` is always interned.
1085 ptr::eq(self.inner, other.inner)
1089 impl Hash for Predicate<'_> {
1090 fn hash<H: Hasher>(&self, s: &mut H) {
1091 (self.inner as *const PredicateInner<'_>).hash(s)
1095 impl<'tcx> Eq for Predicate<'tcx> {}
1097 impl<'tcx> Predicate<'tcx> {
1099 pub fn kind(self) -> &'tcx PredicateKind<'tcx> {
1103 /// Returns the inner `PredicateAtom`.
1105 /// The returned atom may contain unbound variables bound to binders skipped in this method.
1106 /// It is safe to reapply binders to the given atom.
1108 /// Note that this method panics in case this predicate has unbound variables.
1109 pub fn skip_binders(self) -> PredicateAtom<'tcx> {
1111 &PredicateKind::ForAll(binder) => binder.skip_binder(),
1112 &PredicateKind::Atom(atom) => {
1113 debug_assert!(!atom.has_escaping_bound_vars());
1119 /// Returns the inner `PredicateAtom`.
1121 /// Note that this method does not check if the predicate has unbound variables.
1123 /// Rebinding the returned atom can causes the previously bound variables
1124 /// to end up at the wrong binding level.
1125 pub fn skip_binders_unchecked(self) -> PredicateAtom<'tcx> {
1127 &PredicateKind::ForAll(binder) => binder.skip_binder(),
1128 &PredicateKind::Atom(atom) => atom,
1132 /// Converts this to a `Binder<PredicateAtom<'tcx>>`. If the value was an
1133 /// `Atom`, then it is not allowed to contain escaping bound vars.
1134 pub fn bound_atom(self) -> Binder<PredicateAtom<'tcx>> {
1136 &PredicateKind::ForAll(binder) => binder,
1137 &PredicateKind::Atom(atom) => {
1138 debug_assert!(!atom.has_escaping_bound_vars());
1144 /// Allows using a `Binder<PredicateAtom<'tcx>>` even if the given predicate previously
1145 /// contained unbound variables by shifting these variables outwards.
1146 pub fn bound_atom_with_opt_escaping(self, tcx: TyCtxt<'tcx>) -> Binder<PredicateAtom<'tcx>> {
1148 &PredicateKind::ForAll(binder) => binder,
1149 &PredicateKind::Atom(atom) => Binder::wrap_nonbinding(tcx, atom),
1154 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for Predicate<'tcx> {
1155 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
1156 let PredicateInner {
1159 // The other fields just provide fast access to information that is
1160 // also contained in `kind`, so no need to hash them.
1162 outer_exclusive_binder: _,
1165 kind.hash_stable(hcx, hasher);
1169 #[derive(Clone, Copy, PartialEq, Eq, Hash, TyEncodable, TyDecodable)]
1170 #[derive(HashStable, TypeFoldable)]
1171 pub enum PredicateKind<'tcx> {
1173 ForAll(Binder<PredicateAtom<'tcx>>),
1174 Atom(PredicateAtom<'tcx>),
1177 #[derive(Clone, Copy, PartialEq, Eq, Hash, TyEncodable, TyDecodable)]
1178 #[derive(HashStable, TypeFoldable)]
1179 pub enum PredicateAtom<'tcx> {
1180 /// Corresponds to `where Foo: Bar<A, B, C>`. `Foo` here would be
1181 /// the `Self` type of the trait reference and `A`, `B`, and `C`
1182 /// would be the type parameters.
1184 /// A trait predicate will have `Constness::Const` if it originates
1185 /// from a bound on a `const fn` without the `?const` opt-out (e.g.,
1186 /// `const fn foobar<Foo: Bar>() {}`).
1187 Trait(TraitPredicate<'tcx>, Constness),
1190 RegionOutlives(RegionOutlivesPredicate<'tcx>),
1193 TypeOutlives(TypeOutlivesPredicate<'tcx>),
1195 /// `where <T as TraitRef>::Name == X`, approximately.
1196 /// See the `ProjectionPredicate` struct for details.
1197 Projection(ProjectionPredicate<'tcx>),
1199 /// No syntax: `T` well-formed.
1200 WellFormed(GenericArg<'tcx>),
1202 /// Trait must be object-safe.
1205 /// No direct syntax. May be thought of as `where T: FnFoo<...>`
1206 /// for some substitutions `...` and `T` being a closure type.
1207 /// Satisfied (or refuted) once we know the closure's kind.
1208 ClosureKind(DefId, SubstsRef<'tcx>, ClosureKind),
1211 Subtype(SubtypePredicate<'tcx>),
1213 /// Constant initializer must evaluate successfully.
1214 ConstEvaluatable(ty::WithOptConstParam<DefId>, SubstsRef<'tcx>),
1216 /// Constants must be equal. The first component is the const that is expected.
1217 ConstEquate(&'tcx Const<'tcx>, &'tcx Const<'tcx>),
1219 /// Represents a type found in the environment that we can use for implied bounds.
1221 /// Only used for Chalk.
1222 TypeWellFormedFromEnv(Ty<'tcx>),
1225 impl<'tcx> PredicateAtom<'tcx> {
1226 /// Wraps `self` with the given qualifier if this predicate has any unbound variables.
1227 pub fn potentially_quantified(
1230 qualifier: impl FnOnce(Binder<PredicateAtom<'tcx>>) -> PredicateKind<'tcx>,
1231 ) -> Predicate<'tcx> {
1232 if self.has_escaping_bound_vars() {
1233 qualifier(Binder::bind(self))
1235 PredicateKind::Atom(self)
1241 /// The crate outlives map is computed during typeck and contains the
1242 /// outlives of every item in the local crate. You should not use it
1243 /// directly, because to do so will make your pass dependent on the
1244 /// HIR of every item in the local crate. Instead, use
1245 /// `tcx.inferred_outlives_of()` to get the outlives for a *particular*
1247 #[derive(HashStable)]
1248 pub struct CratePredicatesMap<'tcx> {
1249 /// For each struct with outlive bounds, maps to a vector of the
1250 /// predicate of its outlive bounds. If an item has no outlives
1251 /// bounds, it will have no entry.
1252 pub predicates: FxHashMap<DefId, &'tcx [(Predicate<'tcx>, Span)]>,
1255 impl<'tcx> Predicate<'tcx> {
1256 /// Performs a substitution suitable for going from a
1257 /// poly-trait-ref to supertraits that must hold if that
1258 /// poly-trait-ref holds. This is slightly different from a normal
1259 /// substitution in terms of what happens with bound regions. See
1260 /// lengthy comment below for details.
1261 pub fn subst_supertrait(
1264 trait_ref: &ty::PolyTraitRef<'tcx>,
1265 ) -> Predicate<'tcx> {
1266 // The interaction between HRTB and supertraits is not entirely
1267 // obvious. Let me walk you (and myself) through an example.
1269 // Let's start with an easy case. Consider two traits:
1271 // trait Foo<'a>: Bar<'a,'a> { }
1272 // trait Bar<'b,'c> { }
1274 // Now, if we have a trait reference `for<'x> T: Foo<'x>`, then
1275 // we can deduce that `for<'x> T: Bar<'x,'x>`. Basically, if we
1276 // knew that `Foo<'x>` (for any 'x) then we also know that
1277 // `Bar<'x,'x>` (for any 'x). This more-or-less falls out from
1278 // normal substitution.
1280 // In terms of why this is sound, the idea is that whenever there
1281 // is an impl of `T:Foo<'a>`, it must show that `T:Bar<'a,'a>`
1282 // holds. So if there is an impl of `T:Foo<'a>` that applies to
1283 // all `'a`, then we must know that `T:Bar<'a,'a>` holds for all
1286 // Another example to be careful of is this:
1288 // trait Foo1<'a>: for<'b> Bar1<'a,'b> { }
1289 // trait Bar1<'b,'c> { }
1291 // Here, if we have `for<'x> T: Foo1<'x>`, then what do we know?
1292 // The answer is that we know `for<'x,'b> T: Bar1<'x,'b>`. The
1293 // reason is similar to the previous example: any impl of
1294 // `T:Foo1<'x>` must show that `for<'b> T: Bar1<'x, 'b>`. So
1295 // basically we would want to collapse the bound lifetimes from
1296 // the input (`trait_ref`) and the supertraits.
1298 // To achieve this in practice is fairly straightforward. Let's
1299 // consider the more complicated scenario:
1301 // - We start out with `for<'x> T: Foo1<'x>`. In this case, `'x`
1302 // has a De Bruijn index of 1. We want to produce `for<'x,'b> T: Bar1<'x,'b>`,
1303 // where both `'x` and `'b` would have a DB index of 1.
1304 // The substitution from the input trait-ref is therefore going to be
1305 // `'a => 'x` (where `'x` has a DB index of 1).
1306 // - The super-trait-ref is `for<'b> Bar1<'a,'b>`, where `'a` is an
1307 // early-bound parameter and `'b' is a late-bound parameter with a
1309 // - If we replace `'a` with `'x` from the input, it too will have
1310 // a DB index of 1, and thus we'll have `for<'x,'b> Bar1<'x,'b>`
1311 // just as we wanted.
1313 // There is only one catch. If we just apply the substitution `'a
1314 // => 'x` to `for<'b> Bar1<'a,'b>`, the substitution code will
1315 // adjust the DB index because we substituting into a binder (it
1316 // tries to be so smart...) resulting in `for<'x> for<'b>
1317 // Bar1<'x,'b>` (we have no syntax for this, so use your
1318 // imagination). Basically the 'x will have DB index of 2 and 'b
1319 // will have DB index of 1. Not quite what we want. So we apply
1320 // the substitution to the *contents* of the trait reference,
1321 // rather than the trait reference itself (put another way, the
1322 // substitution code expects equal binding levels in the values
1323 // from the substitution and the value being substituted into, and
1324 // this trick achieves that).
1325 let substs = trait_ref.skip_binder().substs;
1326 let pred = self.skip_binders();
1327 let new = pred.subst(tcx, substs);
1328 if new != pred { new.potentially_quantified(tcx, PredicateKind::ForAll) } else { self }
1332 #[derive(Clone, Copy, PartialEq, Eq, Hash, TyEncodable, TyDecodable)]
1333 #[derive(HashStable, TypeFoldable)]
1334 pub struct TraitPredicate<'tcx> {
1335 pub trait_ref: TraitRef<'tcx>,
1338 pub type PolyTraitPredicate<'tcx> = ty::Binder<TraitPredicate<'tcx>>;
1340 impl<'tcx> TraitPredicate<'tcx> {
1341 pub fn def_id(self) -> DefId {
1342 self.trait_ref.def_id
1345 pub fn self_ty(self) -> Ty<'tcx> {
1346 self.trait_ref.self_ty()
1350 impl<'tcx> PolyTraitPredicate<'tcx> {
1351 pub fn def_id(self) -> DefId {
1352 // Ok to skip binder since trait `DefId` does not care about regions.
1353 self.skip_binder().def_id()
1357 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, TyEncodable, TyDecodable)]
1358 #[derive(HashStable, TypeFoldable)]
1359 pub struct OutlivesPredicate<A, B>(pub A, pub B); // `A: B`
1360 pub type RegionOutlivesPredicate<'tcx> = OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>;
1361 pub type TypeOutlivesPredicate<'tcx> = OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>;
1362 pub type PolyRegionOutlivesPredicate<'tcx> = ty::Binder<RegionOutlivesPredicate<'tcx>>;
1363 pub type PolyTypeOutlivesPredicate<'tcx> = ty::Binder<TypeOutlivesPredicate<'tcx>>;
1365 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, TyEncodable, TyDecodable)]
1366 #[derive(HashStable, TypeFoldable)]
1367 pub struct SubtypePredicate<'tcx> {
1368 pub a_is_expected: bool,
1372 pub type PolySubtypePredicate<'tcx> = ty::Binder<SubtypePredicate<'tcx>>;
1374 /// This kind of predicate has no *direct* correspondent in the
1375 /// syntax, but it roughly corresponds to the syntactic forms:
1377 /// 1. `T: TraitRef<..., Item = Type>`
1378 /// 2. `<T as TraitRef<...>>::Item == Type` (NYI)
1380 /// In particular, form #1 is "desugared" to the combination of a
1381 /// normal trait predicate (`T: TraitRef<...>`) and one of these
1382 /// predicates. Form #2 is a broader form in that it also permits
1383 /// equality between arbitrary types. Processing an instance of
1384 /// Form #2 eventually yields one of these `ProjectionPredicate`
1385 /// instances to normalize the LHS.
1386 #[derive(Copy, Clone, PartialEq, Eq, Hash, TyEncodable, TyDecodable)]
1387 #[derive(HashStable, TypeFoldable)]
1388 pub struct ProjectionPredicate<'tcx> {
1389 pub projection_ty: ProjectionTy<'tcx>,
1393 pub type PolyProjectionPredicate<'tcx> = Binder<ProjectionPredicate<'tcx>>;
1395 impl<'tcx> PolyProjectionPredicate<'tcx> {
1396 /// Returns the `DefId` of the associated item being projected.
1397 pub fn item_def_id(&self) -> DefId {
1398 self.skip_binder().projection_ty.item_def_id
1402 pub fn to_poly_trait_ref(&self, tcx: TyCtxt<'tcx>) -> PolyTraitRef<'tcx> {
1403 // Note: unlike with `TraitRef::to_poly_trait_ref()`,
1404 // `self.0.trait_ref` is permitted to have escaping regions.
1405 // This is because here `self` has a `Binder` and so does our
1406 // return value, so we are preserving the number of binding
1408 self.map_bound(|predicate| predicate.projection_ty.trait_ref(tcx))
1411 pub fn ty(&self) -> Binder<Ty<'tcx>> {
1412 self.map_bound(|predicate| predicate.ty)
1415 /// The `DefId` of the `TraitItem` for the associated type.
1417 /// Note that this is not the `DefId` of the `TraitRef` containing this
1418 /// associated type, which is in `tcx.associated_item(projection_def_id()).container`.
1419 pub fn projection_def_id(&self) -> DefId {
1420 // Ok to skip binder since trait `DefId` does not care about regions.
1421 self.skip_binder().projection_ty.item_def_id
1425 pub trait ToPolyTraitRef<'tcx> {
1426 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx>;
1429 impl<'tcx> ToPolyTraitRef<'tcx> for TraitRef<'tcx> {
1430 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
1431 ty::Binder::dummy(*self)
1435 impl<'tcx> ToPolyTraitRef<'tcx> for PolyTraitPredicate<'tcx> {
1436 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
1437 self.map_bound_ref(|trait_pred| trait_pred.trait_ref)
1441 pub trait ToPredicate<'tcx> {
1442 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx>;
1445 impl ToPredicate<'tcx> for PredicateKind<'tcx> {
1447 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1448 tcx.mk_predicate(self)
1452 impl ToPredicate<'tcx> for PredicateAtom<'tcx> {
1454 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1455 debug_assert!(!self.has_escaping_bound_vars(), "escaping bound vars for {:?}", self);
1456 tcx.mk_predicate(PredicateKind::Atom(self))
1460 impl<'tcx> ToPredicate<'tcx> for ConstnessAnd<TraitRef<'tcx>> {
1461 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1462 PredicateAtom::Trait(ty::TraitPredicate { trait_ref: self.value }, self.constness)
1467 impl<'tcx> ToPredicate<'tcx> for ConstnessAnd<PolyTraitRef<'tcx>> {
1468 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1470 value: self.value.map_bound(|trait_ref| ty::TraitPredicate { trait_ref }),
1471 constness: self.constness,
1477 impl<'tcx> ToPredicate<'tcx> for ConstnessAnd<PolyTraitPredicate<'tcx>> {
1478 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1479 PredicateAtom::Trait(self.value.skip_binder(), self.constness)
1480 .potentially_quantified(tcx, PredicateKind::ForAll)
1484 impl<'tcx> ToPredicate<'tcx> for PolyRegionOutlivesPredicate<'tcx> {
1485 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1486 PredicateAtom::RegionOutlives(self.skip_binder())
1487 .potentially_quantified(tcx, PredicateKind::ForAll)
1491 impl<'tcx> ToPredicate<'tcx> for PolyTypeOutlivesPredicate<'tcx> {
1492 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1493 PredicateAtom::TypeOutlives(self.skip_binder())
1494 .potentially_quantified(tcx, PredicateKind::ForAll)
1498 impl<'tcx> ToPredicate<'tcx> for PolyProjectionPredicate<'tcx> {
1499 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1500 PredicateAtom::Projection(self.skip_binder())
1501 .potentially_quantified(tcx, PredicateKind::ForAll)
1505 impl<'tcx> Predicate<'tcx> {
1506 pub fn to_opt_poly_trait_ref(self) -> Option<PolyTraitRef<'tcx>> {
1507 match self.skip_binders() {
1508 PredicateAtom::Trait(t, _) => Some(ty::Binder::bind(t.trait_ref)),
1509 PredicateAtom::Projection(..)
1510 | PredicateAtom::Subtype(..)
1511 | PredicateAtom::RegionOutlives(..)
1512 | PredicateAtom::WellFormed(..)
1513 | PredicateAtom::ObjectSafe(..)
1514 | PredicateAtom::ClosureKind(..)
1515 | PredicateAtom::TypeOutlives(..)
1516 | PredicateAtom::ConstEvaluatable(..)
1517 | PredicateAtom::ConstEquate(..)
1518 | PredicateAtom::TypeWellFormedFromEnv(..) => None,
1522 pub fn to_opt_type_outlives(self) -> Option<PolyTypeOutlivesPredicate<'tcx>> {
1523 match self.skip_binders() {
1524 PredicateAtom::TypeOutlives(data) => Some(ty::Binder::bind(data)),
1525 PredicateAtom::Trait(..)
1526 | PredicateAtom::Projection(..)
1527 | PredicateAtom::Subtype(..)
1528 | PredicateAtom::RegionOutlives(..)
1529 | PredicateAtom::WellFormed(..)
1530 | PredicateAtom::ObjectSafe(..)
1531 | PredicateAtom::ClosureKind(..)
1532 | PredicateAtom::ConstEvaluatable(..)
1533 | PredicateAtom::ConstEquate(..)
1534 | PredicateAtom::TypeWellFormedFromEnv(..) => None,
1539 /// Represents the bounds declared on a particular set of type
1540 /// parameters. Should eventually be generalized into a flag list of
1541 /// where-clauses. You can obtain a `InstantiatedPredicates` list from a
1542 /// `GenericPredicates` by using the `instantiate` method. Note that this method
1543 /// reflects an important semantic invariant of `InstantiatedPredicates`: while
1544 /// the `GenericPredicates` are expressed in terms of the bound type
1545 /// parameters of the impl/trait/whatever, an `InstantiatedPredicates` instance
1546 /// represented a set of bounds for some particular instantiation,
1547 /// meaning that the generic parameters have been substituted with
1552 /// struct Foo<T, U: Bar<T>> { ... }
1554 /// Here, the `GenericPredicates` for `Foo` would contain a list of bounds like
1555 /// `[[], [U:Bar<T>]]`. Now if there were some particular reference
1556 /// like `Foo<isize,usize>`, then the `InstantiatedPredicates` would be `[[],
1557 /// [usize:Bar<isize>]]`.
1558 #[derive(Clone, Debug, TypeFoldable)]
1559 pub struct InstantiatedPredicates<'tcx> {
1560 pub predicates: Vec<Predicate<'tcx>>,
1561 pub spans: Vec<Span>,
1564 impl<'tcx> InstantiatedPredicates<'tcx> {
1565 pub fn empty() -> InstantiatedPredicates<'tcx> {
1566 InstantiatedPredicates { predicates: vec![], spans: vec![] }
1569 pub fn is_empty(&self) -> bool {
1570 self.predicates.is_empty()
1574 rustc_index::newtype_index! {
1575 /// "Universes" are used during type- and trait-checking in the
1576 /// presence of `for<..>` binders to control what sets of names are
1577 /// visible. Universes are arranged into a tree: the root universe
1578 /// contains names that are always visible. Each child then adds a new
1579 /// set of names that are visible, in addition to those of its parent.
1580 /// We say that the child universe "extends" the parent universe with
1583 /// To make this more concrete, consider this program:
1587 /// fn bar<T>(x: T) {
1588 /// let y: for<'a> fn(&'a u8, Foo) = ...;
1592 /// The struct name `Foo` is in the root universe U0. But the type
1593 /// parameter `T`, introduced on `bar`, is in an extended universe U1
1594 /// -- i.e., within `bar`, we can name both `T` and `Foo`, but outside
1595 /// of `bar`, we cannot name `T`. Then, within the type of `y`, the
1596 /// region `'a` is in a universe U2 that extends U1, because we can
1597 /// name it inside the fn type but not outside.
1599 /// Universes are used to do type- and trait-checking around these
1600 /// "forall" binders (also called **universal quantification**). The
1601 /// idea is that when, in the body of `bar`, we refer to `T` as a
1602 /// type, we aren't referring to any type in particular, but rather a
1603 /// kind of "fresh" type that is distinct from all other types we have
1604 /// actually declared. This is called a **placeholder** type, and we
1605 /// use universes to talk about this. In other words, a type name in
1606 /// universe 0 always corresponds to some "ground" type that the user
1607 /// declared, but a type name in a non-zero universe is a placeholder
1608 /// type -- an idealized representative of "types in general" that we
1609 /// use for checking generic functions.
1610 pub struct UniverseIndex {
1612 DEBUG_FORMAT = "U{}",
1616 impl UniverseIndex {
1617 pub const ROOT: UniverseIndex = UniverseIndex::from_u32(0);
1619 /// Returns the "next" universe index in order -- this new index
1620 /// is considered to extend all previous universes. This
1621 /// corresponds to entering a `forall` quantifier. So, for
1622 /// example, suppose we have this type in universe `U`:
1625 /// for<'a> fn(&'a u32)
1628 /// Once we "enter" into this `for<'a>` quantifier, we are in a
1629 /// new universe that extends `U` -- in this new universe, we can
1630 /// name the region `'a`, but that region was not nameable from
1631 /// `U` because it was not in scope there.
1632 pub fn next_universe(self) -> UniverseIndex {
1633 UniverseIndex::from_u32(self.private.checked_add(1).unwrap())
1636 /// Returns `true` if `self` can name a name from `other` -- in other words,
1637 /// if the set of names in `self` is a superset of those in
1638 /// `other` (`self >= other`).
1639 pub fn can_name(self, other: UniverseIndex) -> bool {
1640 self.private >= other.private
1643 /// Returns `true` if `self` cannot name some names from `other` -- in other
1644 /// words, if the set of names in `self` is a strict subset of
1645 /// those in `other` (`self < other`).
1646 pub fn cannot_name(self, other: UniverseIndex) -> bool {
1647 self.private < other.private
1651 /// The "placeholder index" fully defines a placeholder region, type, or const. Placeholders are
1652 /// identified by both a universe, as well as a name residing within that universe. Distinct bound
1653 /// regions/types/consts within the same universe simply have an unknown relationship to one
1655 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TyEncodable, TyDecodable, PartialOrd, Ord)]
1656 pub struct Placeholder<T> {
1657 pub universe: UniverseIndex,
1661 impl<'a, T> HashStable<StableHashingContext<'a>> for Placeholder<T>
1663 T: HashStable<StableHashingContext<'a>>,
1665 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
1666 self.universe.hash_stable(hcx, hasher);
1667 self.name.hash_stable(hcx, hasher);
1671 pub type PlaceholderRegion = Placeholder<BoundRegion>;
1673 pub type PlaceholderType = Placeholder<BoundVar>;
1675 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable)]
1676 #[derive(TyEncodable, TyDecodable, PartialOrd, Ord)]
1677 pub struct BoundConst<'tcx> {
1682 pub type PlaceholderConst<'tcx> = Placeholder<BoundConst<'tcx>>;
1684 /// A `DefId` which is potentially bundled with its corresponding generic parameter
1685 /// in case `did` is a const argument.
1687 /// This is used to prevent cycle errors during typeck
1688 /// as `type_of(const_arg)` depends on `typeck(owning_body)`
1689 /// which once again requires the type of its generic arguments.
1691 /// Luckily we only need to deal with const arguments once we
1692 /// know their corresponding parameters. We (ab)use this by
1693 /// calling `type_of(param_did)` for these arguments.
1696 /// #![feature(const_generics)]
1700 /// fn foo<const N: usize>(&self) -> usize { N }
1704 /// fn foo<const N: u8>(&self) -> usize { 42 }
1712 #[derive(Copy, Clone, Debug, TypeFoldable, Lift, TyEncodable, TyDecodable)]
1713 #[derive(PartialEq, Eq, PartialOrd, Ord)]
1714 #[derive(Hash, HashStable)]
1715 pub struct WithOptConstParam<T> {
1717 /// The `DefId` of the corresponding generic parameter in case `did` is
1718 /// a const argument.
1720 /// Note that even if `did` is a const argument, this may still be `None`.
1721 /// All queries taking `WithOptConstParam` start by calling `tcx.opt_const_param_of(def.did)`
1722 /// to potentially update `param_did` in case it `None`.
1723 pub const_param_did: Option<DefId>,
1726 impl<T> WithOptConstParam<T> {
1727 /// Creates a new `WithOptConstParam` setting `const_param_did` to `None`.
1729 pub fn unknown(did: T) -> WithOptConstParam<T> {
1730 WithOptConstParam { did, const_param_did: None }
1734 impl WithOptConstParam<LocalDefId> {
1735 /// Returns `Some((did, param_did))` if `def_id` is a const argument,
1736 /// `None` otherwise.
1738 pub fn try_lookup(did: LocalDefId, tcx: TyCtxt<'_>) -> Option<(LocalDefId, DefId)> {
1739 tcx.opt_const_param_of(did).map(|param_did| (did, param_did))
1742 /// In case `self` is unknown but `self.did` is a const argument, this returns
1743 /// a `WithOptConstParam` with the correct `const_param_did`.
1745 pub fn try_upgrade(self, tcx: TyCtxt<'_>) -> Option<WithOptConstParam<LocalDefId>> {
1746 if self.const_param_did.is_none() {
1747 if let const_param_did @ Some(_) = tcx.opt_const_param_of(self.did) {
1748 return Some(WithOptConstParam { did: self.did, const_param_did });
1755 pub fn to_global(self) -> WithOptConstParam<DefId> {
1756 WithOptConstParam { did: self.did.to_def_id(), const_param_did: self.const_param_did }
1759 pub fn def_id_for_type_of(self) -> DefId {
1760 if let Some(did) = self.const_param_did { did } else { self.did.to_def_id() }
1764 impl WithOptConstParam<DefId> {
1765 pub fn as_local(self) -> Option<WithOptConstParam<LocalDefId>> {
1768 .map(|did| WithOptConstParam { did, const_param_did: self.const_param_did })
1771 pub fn as_const_arg(self) -> Option<(LocalDefId, DefId)> {
1772 if let Some(param_did) = self.const_param_did {
1773 if let Some(did) = self.did.as_local() {
1774 return Some((did, param_did));
1781 pub fn expect_local(self) -> WithOptConstParam<LocalDefId> {
1782 self.as_local().unwrap()
1785 pub fn is_local(self) -> bool {
1789 pub fn def_id_for_type_of(self) -> DefId {
1790 self.const_param_did.unwrap_or(self.did)
1794 /// When type checking, we use the `ParamEnv` to track
1795 /// details about the set of where-clauses that are in scope at this
1796 /// particular point.
1797 #[derive(Copy, Clone, Hash, PartialEq, Eq)]
1798 pub struct ParamEnv<'tcx> {
1799 /// This packs both caller bounds and the reveal enum into one pointer.
1801 /// Caller bounds are `Obligation`s that the caller must satisfy. This is
1802 /// basically the set of bounds on the in-scope type parameters, translated
1803 /// into `Obligation`s, and elaborated and normalized.
1805 /// Use the `caller_bounds()` method to access.
1807 /// Typically, this is `Reveal::UserFacing`, but during codegen we
1808 /// want `Reveal::All`.
1810 /// Note: This is packed, use the reveal() method to access it.
1811 packed: CopyTaggedPtr<&'tcx List<Predicate<'tcx>>, traits::Reveal, true>,
1814 unsafe impl rustc_data_structures::tagged_ptr::Tag for traits::Reveal {
1815 const BITS: usize = 1;
1816 fn into_usize(self) -> usize {
1818 traits::Reveal::UserFacing => 0,
1819 traits::Reveal::All => 1,
1822 unsafe fn from_usize(ptr: usize) -> Self {
1824 0 => traits::Reveal::UserFacing,
1825 1 => traits::Reveal::All,
1826 _ => std::hint::unreachable_unchecked(),
1831 impl<'tcx> fmt::Debug for ParamEnv<'tcx> {
1832 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1833 f.debug_struct("ParamEnv")
1834 .field("caller_bounds", &self.caller_bounds())
1835 .field("reveal", &self.reveal())
1840 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for ParamEnv<'tcx> {
1841 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
1842 self.caller_bounds().hash_stable(hcx, hasher);
1843 self.reveal().hash_stable(hcx, hasher);
1847 impl<'tcx> TypeFoldable<'tcx> for ParamEnv<'tcx> {
1848 fn super_fold_with<F: ty::fold::TypeFolder<'tcx>>(self, folder: &mut F) -> Self {
1849 ParamEnv::new(self.caller_bounds().fold_with(folder), self.reveal().fold_with(folder))
1852 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> ControlFlow<()> {
1853 self.caller_bounds().visit_with(visitor)?;
1854 self.reveal().visit_with(visitor)
1858 impl<'tcx> ParamEnv<'tcx> {
1859 /// Construct a trait environment suitable for contexts where
1860 /// there are no where-clauses in scope. Hidden types (like `impl
1861 /// Trait`) are left hidden, so this is suitable for ordinary
1864 pub fn empty() -> Self {
1865 Self::new(List::empty(), Reveal::UserFacing)
1869 pub fn caller_bounds(self) -> &'tcx List<Predicate<'tcx>> {
1870 self.packed.pointer()
1874 pub fn reveal(self) -> traits::Reveal {
1878 /// Construct a trait environment with no where-clauses in scope
1879 /// where the values of all `impl Trait` and other hidden types
1880 /// are revealed. This is suitable for monomorphized, post-typeck
1881 /// environments like codegen or doing optimizations.
1883 /// N.B., if you want to have predicates in scope, use `ParamEnv::new`,
1884 /// or invoke `param_env.with_reveal_all()`.
1886 pub fn reveal_all() -> Self {
1887 Self::new(List::empty(), Reveal::All)
1890 /// Construct a trait environment with the given set of predicates.
1892 pub fn new(caller_bounds: &'tcx List<Predicate<'tcx>>, reveal: Reveal) -> Self {
1893 ty::ParamEnv { packed: CopyTaggedPtr::new(caller_bounds, reveal) }
1896 pub fn with_user_facing(mut self) -> Self {
1897 self.packed.set_tag(Reveal::UserFacing);
1901 /// Returns a new parameter environment with the same clauses, but
1902 /// which "reveals" the true results of projections in all cases
1903 /// (even for associated types that are specializable). This is
1904 /// the desired behavior during codegen and certain other special
1905 /// contexts; normally though we want to use `Reveal::UserFacing`,
1906 /// which is the default.
1907 /// All opaque types in the caller_bounds of the `ParamEnv`
1908 /// will be normalized to their underlying types.
1909 /// See PR #65989 and issue #65918 for more details
1910 pub fn with_reveal_all_normalized(self, tcx: TyCtxt<'tcx>) -> Self {
1911 if self.packed.tag() == traits::Reveal::All {
1915 ParamEnv::new(tcx.normalize_opaque_types(self.caller_bounds()), Reveal::All)
1918 /// Returns this same environment but with no caller bounds.
1919 pub fn without_caller_bounds(self) -> Self {
1920 Self::new(List::empty(), self.reveal())
1923 /// Creates a suitable environment in which to perform trait
1924 /// queries on the given value. When type-checking, this is simply
1925 /// the pair of the environment plus value. But when reveal is set to
1926 /// All, then if `value` does not reference any type parameters, we will
1927 /// pair it with the empty environment. This improves caching and is generally
1930 /// N.B., we preserve the environment when type-checking because it
1931 /// is possible for the user to have wacky where-clauses like
1932 /// `where Box<u32>: Copy`, which are clearly never
1933 /// satisfiable. We generally want to behave as if they were true,
1934 /// although the surrounding function is never reachable.
1935 pub fn and<T: TypeFoldable<'tcx>>(self, value: T) -> ParamEnvAnd<'tcx, T> {
1936 match self.reveal() {
1937 Reveal::UserFacing => ParamEnvAnd { param_env: self, value },
1940 if value.is_global() {
1941 ParamEnvAnd { param_env: self.without_caller_bounds(), value }
1943 ParamEnvAnd { param_env: self, value }
1950 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1951 pub struct ConstnessAnd<T> {
1952 pub constness: Constness,
1956 // FIXME(ecstaticmorse): Audit all occurrences of `without_const().to_predicate(tcx)` to ensure that
1957 // the constness of trait bounds is being propagated correctly.
1958 pub trait WithConstness: Sized {
1960 fn with_constness(self, constness: Constness) -> ConstnessAnd<Self> {
1961 ConstnessAnd { constness, value: self }
1965 fn with_const(self) -> ConstnessAnd<Self> {
1966 self.with_constness(Constness::Const)
1970 fn without_const(self) -> ConstnessAnd<Self> {
1971 self.with_constness(Constness::NotConst)
1975 impl<T> WithConstness for T {}
1977 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TypeFoldable)]
1978 pub struct ParamEnvAnd<'tcx, T> {
1979 pub param_env: ParamEnv<'tcx>,
1983 impl<'tcx, T> ParamEnvAnd<'tcx, T> {
1984 pub fn into_parts(self) -> (ParamEnv<'tcx>, T) {
1985 (self.param_env, self.value)
1989 impl<'a, 'tcx, T> HashStable<StableHashingContext<'a>> for ParamEnvAnd<'tcx, T>
1991 T: HashStable<StableHashingContext<'a>>,
1993 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
1994 let ParamEnvAnd { ref param_env, ref value } = *self;
1996 param_env.hash_stable(hcx, hasher);
1997 value.hash_stable(hcx, hasher);
2001 #[derive(Copy, Clone, Debug, HashStable)]
2002 pub struct Destructor {
2003 /// The `DefId` of the destructor method
2008 #[derive(HashStable)]
2009 pub struct AdtFlags: u32 {
2010 const NO_ADT_FLAGS = 0;
2011 /// Indicates whether the ADT is an enum.
2012 const IS_ENUM = 1 << 0;
2013 /// Indicates whether the ADT is a union.
2014 const IS_UNION = 1 << 1;
2015 /// Indicates whether the ADT is a struct.
2016 const IS_STRUCT = 1 << 2;
2017 /// Indicates whether the ADT is a struct and has a constructor.
2018 const HAS_CTOR = 1 << 3;
2019 /// Indicates whether the type is `PhantomData`.
2020 const IS_PHANTOM_DATA = 1 << 4;
2021 /// Indicates whether the type has a `#[fundamental]` attribute.
2022 const IS_FUNDAMENTAL = 1 << 5;
2023 /// Indicates whether the type is `Box`.
2024 const IS_BOX = 1 << 6;
2025 /// Indicates whether the type is `ManuallyDrop`.
2026 const IS_MANUALLY_DROP = 1 << 7;
2027 /// Indicates whether the variant list of this ADT is `#[non_exhaustive]`.
2028 /// (i.e., this flag is never set unless this ADT is an enum).
2029 const IS_VARIANT_LIST_NON_EXHAUSTIVE = 1 << 8;
2034 #[derive(HashStable)]
2035 pub struct VariantFlags: u32 {
2036 const NO_VARIANT_FLAGS = 0;
2037 /// Indicates whether the field list of this variant is `#[non_exhaustive]`.
2038 const IS_FIELD_LIST_NON_EXHAUSTIVE = 1 << 0;
2039 /// Indicates whether this variant was obtained as part of recovering from
2040 /// a syntactic error. May be incomplete or bogus.
2041 const IS_RECOVERED = 1 << 1;
2045 /// Definition of a variant -- a struct's fields or a enum variant.
2046 #[derive(Debug, HashStable)]
2047 pub struct VariantDef {
2048 /// `DefId` that identifies the variant itself.
2049 /// If this variant belongs to a struct or union, then this is a copy of its `DefId`.
2051 /// `DefId` that identifies the variant's constructor.
2052 /// If this variant is a struct variant, then this is `None`.
2053 pub ctor_def_id: Option<DefId>,
2054 /// Variant or struct name.
2055 #[stable_hasher(project(name))]
2057 /// Discriminant of this variant.
2058 pub discr: VariantDiscr,
2059 /// Fields of this variant.
2060 pub fields: Vec<FieldDef>,
2061 /// Type of constructor of variant.
2062 pub ctor_kind: CtorKind,
2063 /// Flags of the variant (e.g. is field list non-exhaustive)?
2064 flags: VariantFlags,
2068 /// Creates a new `VariantDef`.
2070 /// `variant_did` is the `DefId` that identifies the enum variant (if this `VariantDef`
2071 /// represents an enum variant).
2073 /// `ctor_did` is the `DefId` that identifies the constructor of unit or
2074 /// tuple-variants/structs. If this is a `struct`-variant then this should be `None`.
2076 /// `parent_did` is the `DefId` of the `AdtDef` representing the enum or struct that
2077 /// owns this variant. It is used for checking if a struct has `#[non_exhaustive]` w/out having
2078 /// to go through the redirect of checking the ctor's attributes - but compiling a small crate
2079 /// requires loading the `AdtDef`s for all the structs in the universe (e.g., coherence for any
2080 /// built-in trait), and we do not want to load attributes twice.
2082 /// If someone speeds up attribute loading to not be a performance concern, they can
2083 /// remove this hack and use the constructor `DefId` everywhere.
2086 variant_did: Option<DefId>,
2087 ctor_def_id: Option<DefId>,
2088 discr: VariantDiscr,
2089 fields: Vec<FieldDef>,
2090 ctor_kind: CtorKind,
2094 is_field_list_non_exhaustive: bool,
2097 "VariantDef::new(ident = {:?}, variant_did = {:?}, ctor_def_id = {:?}, discr = {:?},
2098 fields = {:?}, ctor_kind = {:?}, adt_kind = {:?}, parent_did = {:?})",
2099 ident, variant_did, ctor_def_id, discr, fields, ctor_kind, adt_kind, parent_did,
2102 let mut flags = VariantFlags::NO_VARIANT_FLAGS;
2103 if is_field_list_non_exhaustive {
2104 flags |= VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE;
2108 flags |= VariantFlags::IS_RECOVERED;
2112 def_id: variant_did.unwrap_or(parent_did),
2122 /// Is this field list non-exhaustive?
2124 pub fn is_field_list_non_exhaustive(&self) -> bool {
2125 self.flags.intersects(VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE)
2128 /// Was this variant obtained as part of recovering from a syntactic error?
2130 pub fn is_recovered(&self) -> bool {
2131 self.flags.intersects(VariantFlags::IS_RECOVERED)
2135 #[derive(Copy, Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
2136 pub enum VariantDiscr {
2137 /// Explicit value for this variant, i.e., `X = 123`.
2138 /// The `DefId` corresponds to the embedded constant.
2141 /// The previous variant's discriminant plus one.
2142 /// For efficiency reasons, the distance from the
2143 /// last `Explicit` discriminant is being stored,
2144 /// or `0` for the first variant, if it has none.
2148 #[derive(Debug, HashStable)]
2149 pub struct FieldDef {
2151 #[stable_hasher(project(name))]
2153 pub vis: Visibility,
2156 /// The definition of a user-defined type, e.g., a `struct`, `enum`, or `union`.
2158 /// These are all interned (by `alloc_adt_def`) into the global arena.
2160 /// The initialism *ADT* stands for an [*algebraic data type (ADT)*][adt].
2161 /// This is slightly wrong because `union`s are not ADTs.
2162 /// Moreover, Rust only allows recursive data types through indirection.
2164 /// [adt]: https://en.wikipedia.org/wiki/Algebraic_data_type
2166 /// The `DefId` of the struct, enum or union item.
2168 /// Variants of the ADT. If this is a struct or union, then there will be a single variant.
2169 pub variants: IndexVec<VariantIdx, VariantDef>,
2170 /// Flags of the ADT (e.g., is this a struct? is this non-exhaustive?).
2172 /// Repr options provided by the user.
2173 pub repr: ReprOptions,
2176 impl PartialOrd for AdtDef {
2177 fn partial_cmp(&self, other: &AdtDef) -> Option<Ordering> {
2178 Some(self.cmp(&other))
2182 /// There should be only one AdtDef for each `did`, therefore
2183 /// it is fine to implement `Ord` only based on `did`.
2184 impl Ord for AdtDef {
2185 fn cmp(&self, other: &AdtDef) -> Ordering {
2186 self.did.cmp(&other.did)
2190 impl PartialEq for AdtDef {
2191 // `AdtDef`s are always interned, and this is part of `TyS` equality.
2193 fn eq(&self, other: &Self) -> bool {
2194 ptr::eq(self, other)
2198 impl Eq for AdtDef {}
2200 impl Hash for AdtDef {
2202 fn hash<H: Hasher>(&self, s: &mut H) {
2203 (self as *const AdtDef).hash(s)
2207 impl<S: Encoder> Encodable<S> for AdtDef {
2208 fn encode(&self, s: &mut S) -> Result<(), S::Error> {
2213 impl<'a> HashStable<StableHashingContext<'a>> for AdtDef {
2214 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
2216 static CACHE: RefCell<FxHashMap<usize, Fingerprint>> = Default::default();
2219 let hash: Fingerprint = CACHE.with(|cache| {
2220 let addr = self as *const AdtDef as usize;
2221 *cache.borrow_mut().entry(addr).or_insert_with(|| {
2222 let ty::AdtDef { did, ref variants, ref flags, ref repr } = *self;
2224 let mut hasher = StableHasher::new();
2225 did.hash_stable(hcx, &mut hasher);
2226 variants.hash_stable(hcx, &mut hasher);
2227 flags.hash_stable(hcx, &mut hasher);
2228 repr.hash_stable(hcx, &mut hasher);
2234 hash.hash_stable(hcx, hasher);
2238 #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
2245 impl Into<DataTypeKind> for AdtKind {
2246 fn into(self) -> DataTypeKind {
2248 AdtKind::Struct => DataTypeKind::Struct,
2249 AdtKind::Union => DataTypeKind::Union,
2250 AdtKind::Enum => DataTypeKind::Enum,
2256 #[derive(TyEncodable, TyDecodable, Default, HashStable)]
2257 pub struct ReprFlags: u8 {
2258 const IS_C = 1 << 0;
2259 const IS_SIMD = 1 << 1;
2260 const IS_TRANSPARENT = 1 << 2;
2261 // Internal only for now. If true, don't reorder fields.
2262 const IS_LINEAR = 1 << 3;
2263 // If true, don't expose any niche to type's context.
2264 const HIDE_NICHE = 1 << 4;
2265 // Any of these flags being set prevent field reordering optimisation.
2266 const IS_UNOPTIMISABLE = ReprFlags::IS_C.bits |
2267 ReprFlags::IS_SIMD.bits |
2268 ReprFlags::IS_LINEAR.bits;
2272 /// Represents the repr options provided by the user,
2273 #[derive(Copy, Clone, Debug, Eq, PartialEq, TyEncodable, TyDecodable, Default, HashStable)]
2274 pub struct ReprOptions {
2275 pub int: Option<attr::IntType>,
2276 pub align: Option<Align>,
2277 pub pack: Option<Align>,
2278 pub flags: ReprFlags,
2282 pub fn new(tcx: TyCtxt<'_>, did: DefId) -> ReprOptions {
2283 let mut flags = ReprFlags::empty();
2284 let mut size = None;
2285 let mut max_align: Option<Align> = None;
2286 let mut min_pack: Option<Align> = None;
2287 for attr in tcx.get_attrs(did).iter() {
2288 for r in attr::find_repr_attrs(&tcx.sess, attr) {
2289 flags.insert(match r {
2290 attr::ReprC => ReprFlags::IS_C,
2291 attr::ReprPacked(pack) => {
2292 let pack = Align::from_bytes(pack as u64).unwrap();
2293 min_pack = Some(if let Some(min_pack) = min_pack {
2300 attr::ReprTransparent => ReprFlags::IS_TRANSPARENT,
2301 attr::ReprNoNiche => ReprFlags::HIDE_NICHE,
2302 attr::ReprSimd => ReprFlags::IS_SIMD,
2303 attr::ReprInt(i) => {
2307 attr::ReprAlign(align) => {
2308 max_align = max_align.max(Some(Align::from_bytes(align as u64).unwrap()));
2315 // This is here instead of layout because the choice must make it into metadata.
2316 if !tcx.consider_optimizing(|| format!("Reorder fields of {:?}", tcx.def_path_str(did))) {
2317 flags.insert(ReprFlags::IS_LINEAR);
2319 ReprOptions { int: size, align: max_align, pack: min_pack, flags }
2323 pub fn simd(&self) -> bool {
2324 self.flags.contains(ReprFlags::IS_SIMD)
2327 pub fn c(&self) -> bool {
2328 self.flags.contains(ReprFlags::IS_C)
2331 pub fn packed(&self) -> bool {
2335 pub fn transparent(&self) -> bool {
2336 self.flags.contains(ReprFlags::IS_TRANSPARENT)
2339 pub fn linear(&self) -> bool {
2340 self.flags.contains(ReprFlags::IS_LINEAR)
2343 pub fn hide_niche(&self) -> bool {
2344 self.flags.contains(ReprFlags::HIDE_NICHE)
2347 /// Returns the discriminant type, given these `repr` options.
2348 /// This must only be called on enums!
2349 pub fn discr_type(&self) -> attr::IntType {
2350 self.int.unwrap_or(attr::SignedInt(ast::IntTy::Isize))
2353 /// Returns `true` if this `#[repr()]` should inhabit "smart enum
2354 /// layout" optimizations, such as representing `Foo<&T>` as a
2356 pub fn inhibit_enum_layout_opt(&self) -> bool {
2357 self.c() || self.int.is_some()
2360 /// Returns `true` if this `#[repr()]` should inhibit struct field reordering
2361 /// optimizations, such as with `repr(C)`, `repr(packed(1))`, or `repr(<int>)`.
2362 pub fn inhibit_struct_field_reordering_opt(&self) -> bool {
2363 if let Some(pack) = self.pack {
2364 if pack.bytes() == 1 {
2368 self.flags.intersects(ReprFlags::IS_UNOPTIMISABLE) || self.int.is_some()
2371 /// Returns `true` if this `#[repr()]` should inhibit union ABI optimisations.
2372 pub fn inhibit_union_abi_opt(&self) -> bool {
2378 /// Creates a new `AdtDef`.
2383 variants: IndexVec<VariantIdx, VariantDef>,
2386 debug!("AdtDef::new({:?}, {:?}, {:?}, {:?})", did, kind, variants, repr);
2387 let mut flags = AdtFlags::NO_ADT_FLAGS;
2389 if kind == AdtKind::Enum && tcx.has_attr(did, sym::non_exhaustive) {
2390 debug!("found non-exhaustive variant list for {:?}", did);
2391 flags = flags | AdtFlags::IS_VARIANT_LIST_NON_EXHAUSTIVE;
2394 flags |= match kind {
2395 AdtKind::Enum => AdtFlags::IS_ENUM,
2396 AdtKind::Union => AdtFlags::IS_UNION,
2397 AdtKind::Struct => AdtFlags::IS_STRUCT,
2400 if kind == AdtKind::Struct && variants[VariantIdx::new(0)].ctor_def_id.is_some() {
2401 flags |= AdtFlags::HAS_CTOR;
2404 let attrs = tcx.get_attrs(did);
2405 if tcx.sess.contains_name(&attrs, sym::fundamental) {
2406 flags |= AdtFlags::IS_FUNDAMENTAL;
2408 if Some(did) == tcx.lang_items().phantom_data() {
2409 flags |= AdtFlags::IS_PHANTOM_DATA;
2411 if Some(did) == tcx.lang_items().owned_box() {
2412 flags |= AdtFlags::IS_BOX;
2414 if Some(did) == tcx.lang_items().manually_drop() {
2415 flags |= AdtFlags::IS_MANUALLY_DROP;
2418 AdtDef { did, variants, flags, repr }
2421 /// Returns `true` if this is a struct.
2423 pub fn is_struct(&self) -> bool {
2424 self.flags.contains(AdtFlags::IS_STRUCT)
2427 /// Returns `true` if this is a union.
2429 pub fn is_union(&self) -> bool {
2430 self.flags.contains(AdtFlags::IS_UNION)
2433 /// Returns `true` if this is a enum.
2435 pub fn is_enum(&self) -> bool {
2436 self.flags.contains(AdtFlags::IS_ENUM)
2439 /// Returns `true` if the variant list of this ADT is `#[non_exhaustive]`.
2441 pub fn is_variant_list_non_exhaustive(&self) -> bool {
2442 self.flags.contains(AdtFlags::IS_VARIANT_LIST_NON_EXHAUSTIVE)
2445 /// Returns the kind of the ADT.
2447 pub fn adt_kind(&self) -> AdtKind {
2450 } else if self.is_union() {
2457 /// Returns a description of this abstract data type.
2458 pub fn descr(&self) -> &'static str {
2459 match self.adt_kind() {
2460 AdtKind::Struct => "struct",
2461 AdtKind::Union => "union",
2462 AdtKind::Enum => "enum",
2466 /// Returns a description of a variant of this abstract data type.
2468 pub fn variant_descr(&self) -> &'static str {
2469 match self.adt_kind() {
2470 AdtKind::Struct => "struct",
2471 AdtKind::Union => "union",
2472 AdtKind::Enum => "variant",
2476 /// If this function returns `true`, it implies that `is_struct` must return `true`.
2478 pub fn has_ctor(&self) -> bool {
2479 self.flags.contains(AdtFlags::HAS_CTOR)
2482 /// Returns `true` if this type is `#[fundamental]` for the purposes
2483 /// of coherence checking.
2485 pub fn is_fundamental(&self) -> bool {
2486 self.flags.contains(AdtFlags::IS_FUNDAMENTAL)
2489 /// Returns `true` if this is `PhantomData<T>`.
2491 pub fn is_phantom_data(&self) -> bool {
2492 self.flags.contains(AdtFlags::IS_PHANTOM_DATA)
2495 /// Returns `true` if this is Box<T>.
2497 pub fn is_box(&self) -> bool {
2498 self.flags.contains(AdtFlags::IS_BOX)
2501 /// Returns `true` if this is `ManuallyDrop<T>`.
2503 pub fn is_manually_drop(&self) -> bool {
2504 self.flags.contains(AdtFlags::IS_MANUALLY_DROP)
2507 /// Returns `true` if this type has a destructor.
2508 pub fn has_dtor(&self, tcx: TyCtxt<'tcx>) -> bool {
2509 self.destructor(tcx).is_some()
2512 /// Asserts this is a struct or union and returns its unique variant.
2513 pub fn non_enum_variant(&self) -> &VariantDef {
2514 assert!(self.is_struct() || self.is_union());
2515 &self.variants[VariantIdx::new(0)]
2519 pub fn predicates(&self, tcx: TyCtxt<'tcx>) -> GenericPredicates<'tcx> {
2520 tcx.predicates_of(self.did)
2523 /// Returns an iterator over all fields contained
2526 pub fn all_fields(&self) -> impl Iterator<Item = &FieldDef> + Clone {
2527 self.variants.iter().flat_map(|v| v.fields.iter())
2530 /// Whether the ADT lacks fields. Note that this includes uninhabited enums,
2531 /// e.g., `enum Void {}` is considered payload free as well.
2532 pub fn is_payloadfree(&self) -> bool {
2533 self.variants.iter().all(|v| v.fields.is_empty())
2536 /// Return a `VariantDef` given a variant id.
2537 pub fn variant_with_id(&self, vid: DefId) -> &VariantDef {
2538 self.variants.iter().find(|v| v.def_id == vid).expect("variant_with_id: unknown variant")
2541 /// Return a `VariantDef` given a constructor id.
2542 pub fn variant_with_ctor_id(&self, cid: DefId) -> &VariantDef {
2545 .find(|v| v.ctor_def_id == Some(cid))
2546 .expect("variant_with_ctor_id: unknown variant")
2549 /// Return the index of `VariantDef` given a variant id.
2550 pub fn variant_index_with_id(&self, vid: DefId) -> VariantIdx {
2553 .find(|(_, v)| v.def_id == vid)
2554 .expect("variant_index_with_id: unknown variant")
2558 /// Return the index of `VariantDef` given a constructor id.
2559 pub fn variant_index_with_ctor_id(&self, cid: DefId) -> VariantIdx {
2562 .find(|(_, v)| v.ctor_def_id == Some(cid))
2563 .expect("variant_index_with_ctor_id: unknown variant")
2567 pub fn variant_of_res(&self, res: Res) -> &VariantDef {
2569 Res::Def(DefKind::Variant, vid) => self.variant_with_id(vid),
2570 Res::Def(DefKind::Ctor(..), cid) => self.variant_with_ctor_id(cid),
2571 Res::Def(DefKind::Struct, _)
2572 | Res::Def(DefKind::Union, _)
2573 | Res::Def(DefKind::TyAlias, _)
2574 | Res::Def(DefKind::AssocTy, _)
2576 | Res::SelfCtor(..) => self.non_enum_variant(),
2577 _ => bug!("unexpected res {:?} in variant_of_res", res),
2582 pub fn eval_explicit_discr(&self, tcx: TyCtxt<'tcx>, expr_did: DefId) -> Option<Discr<'tcx>> {
2583 assert!(self.is_enum());
2584 let param_env = tcx.param_env(expr_did);
2585 let repr_type = self.repr.discr_type();
2586 match tcx.const_eval_poly(expr_did) {
2588 let ty = repr_type.to_ty(tcx);
2589 if let Some(b) = val.try_to_bits_for_ty(tcx, param_env, ty) {
2590 trace!("discriminants: {} ({:?})", b, repr_type);
2591 Some(Discr { val: b, ty })
2593 info!("invalid enum discriminant: {:#?}", val);
2594 crate::mir::interpret::struct_error(
2595 tcx.at(tcx.def_span(expr_did)),
2596 "constant evaluation of enum discriminant resulted in non-integer",
2603 let msg = match err {
2604 ErrorHandled::Reported(ErrorReported) | ErrorHandled::Linted => {
2605 "enum discriminant evaluation failed"
2607 ErrorHandled::TooGeneric => "enum discriminant depends on generics",
2609 tcx.sess.delay_span_bug(tcx.def_span(expr_did), msg);
2616 pub fn discriminants(
2619 ) -> impl Iterator<Item = (VariantIdx, Discr<'tcx>)> + Captures<'tcx> {
2620 assert!(self.is_enum());
2621 let repr_type = self.repr.discr_type();
2622 let initial = repr_type.initial_discriminant(tcx);
2623 let mut prev_discr = None::<Discr<'tcx>>;
2624 self.variants.iter_enumerated().map(move |(i, v)| {
2625 let mut discr = prev_discr.map_or(initial, |d| d.wrap_incr(tcx));
2626 if let VariantDiscr::Explicit(expr_did) = v.discr {
2627 if let Some(new_discr) = self.eval_explicit_discr(tcx, expr_did) {
2631 prev_discr = Some(discr);
2638 pub fn variant_range(&self) -> Range<VariantIdx> {
2639 VariantIdx::new(0)..VariantIdx::new(self.variants.len())
2642 /// Computes the discriminant value used by a specific variant.
2643 /// Unlike `discriminants`, this is (amortized) constant-time,
2644 /// only doing at most one query for evaluating an explicit
2645 /// discriminant (the last one before the requested variant),
2646 /// assuming there are no constant-evaluation errors there.
2648 pub fn discriminant_for_variant(
2651 variant_index: VariantIdx,
2653 assert!(self.is_enum());
2654 let (val, offset) = self.discriminant_def_for_variant(variant_index);
2655 let explicit_value = val
2656 .and_then(|expr_did| self.eval_explicit_discr(tcx, expr_did))
2657 .unwrap_or_else(|| self.repr.discr_type().initial_discriminant(tcx));
2658 explicit_value.checked_add(tcx, offset as u128).0
2661 /// Yields a `DefId` for the discriminant and an offset to add to it
2662 /// Alternatively, if there is no explicit discriminant, returns the
2663 /// inferred discriminant directly.
2664 pub fn discriminant_def_for_variant(&self, variant_index: VariantIdx) -> (Option<DefId>, u32) {
2665 assert!(!self.variants.is_empty());
2666 let mut explicit_index = variant_index.as_u32();
2669 match self.variants[VariantIdx::from_u32(explicit_index)].discr {
2670 ty::VariantDiscr::Relative(0) => {
2674 ty::VariantDiscr::Relative(distance) => {
2675 explicit_index -= distance;
2677 ty::VariantDiscr::Explicit(did) => {
2678 expr_did = Some(did);
2683 (expr_did, variant_index.as_u32() - explicit_index)
2686 pub fn destructor(&self, tcx: TyCtxt<'tcx>) -> Option<Destructor> {
2687 tcx.adt_destructor(self.did)
2690 /// Returns a list of types such that `Self: Sized` if and only
2691 /// if that type is `Sized`, or `TyErr` if this type is recursive.
2693 /// Oddly enough, checking that the sized-constraint is `Sized` is
2694 /// actually more expressive than checking all members:
2695 /// the `Sized` trait is inductive, so an associated type that references
2696 /// `Self` would prevent its containing ADT from being `Sized`.
2698 /// Due to normalization being eager, this applies even if
2699 /// the associated type is behind a pointer (e.g., issue #31299).
2700 pub fn sized_constraint(&self, tcx: TyCtxt<'tcx>) -> &'tcx [Ty<'tcx>] {
2701 tcx.adt_sized_constraint(self.did).0
2705 impl<'tcx> FieldDef {
2706 /// Returns the type of this field. The `subst` is typically obtained
2707 /// via the second field of `TyKind::AdtDef`.
2708 pub fn ty(&self, tcx: TyCtxt<'tcx>, subst: SubstsRef<'tcx>) -> Ty<'tcx> {
2709 tcx.type_of(self.did).subst(tcx, subst)
2713 /// Represents the various closure traits in the language. This
2714 /// will determine the type of the environment (`self`, in the
2715 /// desugaring) argument that the closure expects.
2717 /// You can get the environment type of a closure using
2718 /// `tcx.closure_env_ty()`.
2719 #[derive(Clone, Copy, PartialOrd, Ord, PartialEq, Eq, Hash, Debug, TyEncodable, TyDecodable)]
2720 #[derive(HashStable)]
2721 pub enum ClosureKind {
2722 // Warning: Ordering is significant here! The ordering is chosen
2723 // because the trait Fn is a subtrait of FnMut and so in turn, and
2724 // hence we order it so that Fn < FnMut < FnOnce.
2730 impl<'tcx> ClosureKind {
2731 // This is the initial value used when doing upvar inference.
2732 pub const LATTICE_BOTTOM: ClosureKind = ClosureKind::Fn;
2734 pub fn trait_did(&self, tcx: TyCtxt<'tcx>) -> DefId {
2736 ClosureKind::Fn => tcx.require_lang_item(LangItem::Fn, None),
2737 ClosureKind::FnMut => tcx.require_lang_item(LangItem::FnMut, None),
2738 ClosureKind::FnOnce => tcx.require_lang_item(LangItem::FnOnce, None),
2742 /// Returns `true` if a type that impls this closure kind
2743 /// must also implement `other`.
2744 pub fn extends(self, other: ty::ClosureKind) -> bool {
2747 (ClosureKind::Fn, ClosureKind::Fn)
2748 | (ClosureKind::Fn, ClosureKind::FnMut)
2749 | (ClosureKind::Fn, ClosureKind::FnOnce)
2750 | (ClosureKind::FnMut, ClosureKind::FnMut)
2751 | (ClosureKind::FnMut, ClosureKind::FnOnce)
2752 | (ClosureKind::FnOnce, ClosureKind::FnOnce)
2756 /// Returns the representative scalar type for this closure kind.
2757 /// See `TyS::to_opt_closure_kind` for more details.
2758 pub fn to_ty(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
2760 ty::ClosureKind::Fn => tcx.types.i8,
2761 ty::ClosureKind::FnMut => tcx.types.i16,
2762 ty::ClosureKind::FnOnce => tcx.types.i32,
2768 pub fn from_mutbl(m: hir::Mutability) -> BorrowKind {
2770 hir::Mutability::Mut => MutBorrow,
2771 hir::Mutability::Not => ImmBorrow,
2775 /// Returns a mutability `m` such that an `&m T` pointer could be used to obtain this borrow
2776 /// kind. Because borrow kinds are richer than mutabilities, we sometimes have to pick a
2777 /// mutability that is stronger than necessary so that it at least *would permit* the borrow in
2779 pub fn to_mutbl_lossy(self) -> hir::Mutability {
2781 MutBorrow => hir::Mutability::Mut,
2782 ImmBorrow => hir::Mutability::Not,
2784 // We have no type corresponding to a unique imm borrow, so
2785 // use `&mut`. It gives all the capabilities of an `&uniq`
2786 // and hence is a safe "over approximation".
2787 UniqueImmBorrow => hir::Mutability::Mut,
2791 pub fn to_user_str(&self) -> &'static str {
2793 MutBorrow => "mutable",
2794 ImmBorrow => "immutable",
2795 UniqueImmBorrow => "uniquely immutable",
2800 pub type Attributes<'tcx> = &'tcx [ast::Attribute];
2802 #[derive(Debug, PartialEq, Eq)]
2803 pub enum ImplOverlapKind {
2804 /// These impls are always allowed to overlap.
2806 /// Whether or not the impl is permitted due to the trait being a `#[marker]` trait
2809 /// These impls are allowed to overlap, but that raises
2810 /// an issue #33140 future-compatibility warning.
2812 /// Some background: in Rust 1.0, the trait-object types `Send + Sync` (today's
2813 /// `dyn Send + Sync`) and `Sync + Send` (now `dyn Sync + Send`) were different.
2815 /// The widely-used version 0.1.0 of the crate `traitobject` had accidentally relied
2816 /// that difference, making what reduces to the following set of impls:
2820 /// impl Trait for dyn Send + Sync {}
2821 /// impl Trait for dyn Sync + Send {}
2824 /// Obviously, once we made these types be identical, that code causes a coherence
2825 /// error and a fairly big headache for us. However, luckily for us, the trait
2826 /// `Trait` used in this case is basically a marker trait, and therefore having
2827 /// overlapping impls for it is sound.
2829 /// To handle this, we basically regard the trait as a marker trait, with an additional
2830 /// future-compatibility warning. To avoid accidentally "stabilizing" this feature,
2831 /// it has the following restrictions:
2833 /// 1. The trait must indeed be a marker-like trait (i.e., no items), and must be
2835 /// 2. The trait-ref of both impls must be equal.
2836 /// 3. The trait-ref of both impls must be a trait object type consisting only of
2838 /// 4. Neither of the impls can have any where-clauses.
2840 /// Once `traitobject` 0.1.0 is no longer an active concern, this hack can be removed.
2844 impl<'tcx> TyCtxt<'tcx> {
2845 pub fn typeck_body(self, body: hir::BodyId) -> &'tcx TypeckResults<'tcx> {
2846 self.typeck(self.hir().body_owner_def_id(body))
2849 /// Returns an iterator of the `DefId`s for all body-owners in this
2850 /// crate. If you would prefer to iterate over the bodies
2851 /// themselves, you can do `self.hir().krate().body_ids.iter()`.
2852 pub fn body_owners(self) -> impl Iterator<Item = LocalDefId> + Captures<'tcx> + 'tcx {
2857 .map(move |&body_id| self.hir().body_owner_def_id(body_id))
2860 pub fn par_body_owners<F: Fn(LocalDefId) + sync::Sync + sync::Send>(self, f: F) {
2861 par_iter(&self.hir().krate().body_ids)
2862 .for_each(|&body_id| f(self.hir().body_owner_def_id(body_id)));
2865 pub fn provided_trait_methods(self, id: DefId) -> impl 'tcx + Iterator<Item = &'tcx AssocItem> {
2866 self.associated_items(id)
2867 .in_definition_order()
2868 .filter(|item| item.kind == AssocKind::Fn && item.defaultness.has_value())
2871 fn item_name_from_hir(self, def_id: DefId) -> Option<Ident> {
2872 self.hir().get_if_local(def_id).and_then(|node| node.ident())
2875 fn item_name_from_def_id(self, def_id: DefId) -> Option<Symbol> {
2876 if def_id.index == CRATE_DEF_INDEX {
2877 Some(self.original_crate_name(def_id.krate))
2879 let def_key = self.def_key(def_id);
2880 match def_key.disambiguated_data.data {
2881 // The name of a constructor is that of its parent.
2882 rustc_hir::definitions::DefPathData::Ctor => self.item_name_from_def_id(DefId {
2883 krate: def_id.krate,
2884 index: def_key.parent.unwrap(),
2886 _ => def_key.disambiguated_data.data.get_opt_name(),
2891 /// Look up the name of an item across crates. This does not look at HIR.
2893 /// When possible, this function should be used for cross-crate lookups over
2894 /// [`opt_item_name`] to avoid invalidating the incremental cache. If you
2895 /// need to handle items without a name, or HIR items that will not be
2896 /// serialized cross-crate, or if you need the span of the item, use
2897 /// [`opt_item_name`] instead.
2899 /// [`opt_item_name`]: Self::opt_item_name
2900 pub fn item_name(self, id: DefId) -> Symbol {
2901 // Look at cross-crate items first to avoid invalidating the incremental cache
2902 // unless we have to.
2903 self.item_name_from_def_id(id).unwrap_or_else(|| {
2904 bug!("item_name: no name for {:?}", self.def_path(id));
2908 /// Look up the name and span of an item or [`Node`].
2910 /// See [`item_name`][Self::item_name] for more information.
2911 pub fn opt_item_name(self, def_id: DefId) -> Option<Ident> {
2912 // Look at the HIR first so the span will be correct if this is a local item.
2913 self.item_name_from_hir(def_id)
2914 .or_else(|| self.item_name_from_def_id(def_id).map(Ident::with_dummy_span))
2917 pub fn opt_associated_item(self, def_id: DefId) -> Option<&'tcx AssocItem> {
2918 let is_associated_item = if let Some(def_id) = def_id.as_local() {
2920 self.hir().get(self.hir().local_def_id_to_hir_id(def_id)),
2921 Node::TraitItem(_) | Node::ImplItem(_)
2925 self.def_kind(def_id),
2926 DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy
2930 is_associated_item.then(|| self.associated_item(def_id))
2933 pub fn field_index(self, hir_id: hir::HirId, typeck_results: &TypeckResults<'_>) -> usize {
2934 typeck_results.field_indices().get(hir_id).cloned().expect("no index for a field")
2937 pub fn find_field_index(self, ident: Ident, variant: &VariantDef) -> Option<usize> {
2938 variant.fields.iter().position(|field| self.hygienic_eq(ident, field.ident, variant.def_id))
2941 /// Returns `true` if the impls are the same polarity and the trait either
2942 /// has no items or is annotated `#[marker]` and prevents item overrides.
2943 pub fn impls_are_allowed_to_overlap(
2947 ) -> Option<ImplOverlapKind> {
2948 // If either trait impl references an error, they're allowed to overlap,
2949 // as one of them essentially doesn't exist.
2950 if self.impl_trait_ref(def_id1).map_or(false, |tr| tr.references_error())
2951 || self.impl_trait_ref(def_id2).map_or(false, |tr| tr.references_error())
2953 return Some(ImplOverlapKind::Permitted { marker: false });
2956 match (self.impl_polarity(def_id1), self.impl_polarity(def_id2)) {
2957 (ImplPolarity::Reservation, _) | (_, ImplPolarity::Reservation) => {
2958 // `#[rustc_reservation_impl]` impls don't overlap with anything
2960 "impls_are_allowed_to_overlap({:?}, {:?}) = Some(Permitted) (reservations)",
2963 return Some(ImplOverlapKind::Permitted { marker: false });
2965 (ImplPolarity::Positive, ImplPolarity::Negative)
2966 | (ImplPolarity::Negative, ImplPolarity::Positive) => {
2967 // `impl AutoTrait for Type` + `impl !AutoTrait for Type`
2969 "impls_are_allowed_to_overlap({:?}, {:?}) - None (differing polarities)",
2974 (ImplPolarity::Positive, ImplPolarity::Positive)
2975 | (ImplPolarity::Negative, ImplPolarity::Negative) => {}
2978 let is_marker_overlap = {
2979 let is_marker_impl = |def_id: DefId| -> bool {
2980 let trait_ref = self.impl_trait_ref(def_id);
2981 trait_ref.map_or(false, |tr| self.trait_def(tr.def_id).is_marker)
2983 is_marker_impl(def_id1) && is_marker_impl(def_id2)
2986 if is_marker_overlap {
2988 "impls_are_allowed_to_overlap({:?}, {:?}) = Some(Permitted) (marker overlap)",
2991 Some(ImplOverlapKind::Permitted { marker: true })
2993 if let Some(self_ty1) = self.issue33140_self_ty(def_id1) {
2994 if let Some(self_ty2) = self.issue33140_self_ty(def_id2) {
2995 if self_ty1 == self_ty2 {
2997 "impls_are_allowed_to_overlap({:?}, {:?}) - issue #33140 HACK",
3000 return Some(ImplOverlapKind::Issue33140);
3003 "impls_are_allowed_to_overlap({:?}, {:?}) - found {:?} != {:?}",
3004 def_id1, def_id2, self_ty1, self_ty2
3010 debug!("impls_are_allowed_to_overlap({:?}, {:?}) = None", def_id1, def_id2);
3015 /// Returns `ty::VariantDef` if `res` refers to a struct,
3016 /// or variant or their constructors, panics otherwise.
3017 pub fn expect_variant_res(self, res: Res) -> &'tcx VariantDef {
3019 Res::Def(DefKind::Variant, did) => {
3020 let enum_did = self.parent(did).unwrap();
3021 self.adt_def(enum_did).variant_with_id(did)
3023 Res::Def(DefKind::Struct | DefKind::Union, did) => self.adt_def(did).non_enum_variant(),
3024 Res::Def(DefKind::Ctor(CtorOf::Variant, ..), variant_ctor_did) => {
3025 let variant_did = self.parent(variant_ctor_did).unwrap();
3026 let enum_did = self.parent(variant_did).unwrap();
3027 self.adt_def(enum_did).variant_with_ctor_id(variant_ctor_did)
3029 Res::Def(DefKind::Ctor(CtorOf::Struct, ..), ctor_did) => {
3030 let struct_did = self.parent(ctor_did).expect("struct ctor has no parent");
3031 self.adt_def(struct_did).non_enum_variant()
3033 _ => bug!("expect_variant_res used with unexpected res {:?}", res),
3037 /// Returns the possibly-auto-generated MIR of a `(DefId, Subst)` pair.
3038 pub fn instance_mir(self, instance: ty::InstanceDef<'tcx>) -> &'tcx Body<'tcx> {
3040 ty::InstanceDef::Item(def) => self.optimized_mir_opt_const_arg(def),
3041 ty::InstanceDef::VtableShim(..)
3042 | ty::InstanceDef::ReifyShim(..)
3043 | ty::InstanceDef::Intrinsic(..)
3044 | ty::InstanceDef::FnPtrShim(..)
3045 | ty::InstanceDef::Virtual(..)
3046 | ty::InstanceDef::ClosureOnceShim { .. }
3047 | ty::InstanceDef::DropGlue(..)
3048 | ty::InstanceDef::CloneShim(..) => self.mir_shims(instance),
3052 /// Gets the attributes of a definition.
3053 pub fn get_attrs(self, did: DefId) -> Attributes<'tcx> {
3054 if let Some(did) = did.as_local() {
3055 self.hir().attrs(self.hir().local_def_id_to_hir_id(did))
3057 self.item_attrs(did)
3061 /// Determines whether an item is annotated with an attribute.
3062 pub fn has_attr(self, did: DefId, attr: Symbol) -> bool {
3063 self.sess.contains_name(&self.get_attrs(did), attr)
3066 /// Returns `true` if this is an `auto trait`.
3067 pub fn trait_is_auto(self, trait_def_id: DefId) -> bool {
3068 self.trait_def(trait_def_id).has_auto_impl
3071 pub fn generator_layout(self, def_id: DefId) -> &'tcx GeneratorLayout<'tcx> {
3072 self.optimized_mir(def_id).generator_layout.as_ref().unwrap()
3075 /// Given the `DefId` of an impl, returns the `DefId` of the trait it implements.
3076 /// If it implements no trait, returns `None`.
3077 pub fn trait_id_of_impl(self, def_id: DefId) -> Option<DefId> {
3078 self.impl_trait_ref(def_id).map(|tr| tr.def_id)
3081 /// If the given defid describes a method belonging to an impl, returns the
3082 /// `DefId` of the impl that the method belongs to; otherwise, returns `None`.
3083 pub fn impl_of_method(self, def_id: DefId) -> Option<DefId> {
3084 self.opt_associated_item(def_id).and_then(|trait_item| match trait_item.container {
3085 TraitContainer(_) => None,
3086 ImplContainer(def_id) => Some(def_id),
3090 /// Looks up the span of `impl_did` if the impl is local; otherwise returns `Err`
3091 /// with the name of the crate containing the impl.
3092 pub fn span_of_impl(self, impl_did: DefId) -> Result<Span, Symbol> {
3093 if let Some(impl_did) = impl_did.as_local() {
3094 let hir_id = self.hir().local_def_id_to_hir_id(impl_did);
3095 Ok(self.hir().span(hir_id))
3097 Err(self.crate_name(impl_did.krate))
3101 /// Hygienically compares a use-site name (`use_name`) for a field or an associated item with
3102 /// its supposed definition name (`def_name`). The method also needs `DefId` of the supposed
3103 /// definition's parent/scope to perform comparison.
3104 pub fn hygienic_eq(self, use_name: Ident, def_name: Ident, def_parent_def_id: DefId) -> bool {
3105 // We could use `Ident::eq` here, but we deliberately don't. The name
3106 // comparison fails frequently, and we want to avoid the expensive
3107 // `normalize_to_macros_2_0()` calls required for the span comparison whenever possible.
3108 use_name.name == def_name.name
3112 .hygienic_eq(def_name.span.ctxt(), self.expansion_that_defined(def_parent_def_id))
3115 pub fn expansion_that_defined(self, scope: DefId) -> ExpnId {
3116 match scope.as_local() {
3117 // Parsing and expansion aren't incremental, so we don't
3118 // need to go through a query for the same-crate case.
3119 Some(scope) => self.hir().definitions().expansion_that_defined(scope),
3120 None => self.expn_that_defined(scope),
3124 pub fn adjust_ident(self, mut ident: Ident, scope: DefId) -> Ident {
3125 ident.span.normalize_to_macros_2_0_and_adjust(self.expansion_that_defined(scope));
3129 pub fn adjust_ident_and_get_scope(
3134 ) -> (Ident, DefId) {
3136 match ident.span.normalize_to_macros_2_0_and_adjust(self.expansion_that_defined(scope))
3138 Some(actual_expansion) => {
3139 self.hir().definitions().parent_module_of_macro_def(actual_expansion)
3141 None => self.parent_module(block).to_def_id(),
3146 pub fn is_object_safe(self, key: DefId) -> bool {
3147 self.object_safety_violations(key).is_empty()
3151 #[derive(Clone, HashStable)]
3152 pub struct AdtSizedConstraint<'tcx>(pub &'tcx [Ty<'tcx>]);
3154 /// Yields the parent function's `DefId` if `def_id` is an `impl Trait` definition.
3155 pub fn is_impl_trait_defn(tcx: TyCtxt<'_>, def_id: DefId) -> Option<DefId> {
3156 if let Some(def_id) = def_id.as_local() {
3157 if let Node::Item(item) = tcx.hir().get(tcx.hir().local_def_id_to_hir_id(def_id)) {
3158 if let hir::ItemKind::OpaqueTy(ref opaque_ty) = item.kind {
3159 return opaque_ty.impl_trait_fn;
3166 pub fn provide(providers: &mut ty::query::Providers) {
3167 context::provide(providers);
3168 erase_regions::provide(providers);
3169 layout::provide(providers);
3170 util::provide(providers);
3171 print::provide(providers);
3172 super::util::bug::provide(providers);
3173 *providers = ty::query::Providers {
3174 trait_impls_of: trait_def::trait_impls_of_provider,
3175 all_local_trait_impls: trait_def::all_local_trait_impls,
3180 /// A map for the local crate mapping each type to a vector of its
3181 /// inherent impls. This is not meant to be used outside of coherence;
3182 /// rather, you should request the vector for a specific type via
3183 /// `tcx.inherent_impls(def_id)` so as to minimize your dependencies
3184 /// (constructing this map requires touching the entire crate).
3185 #[derive(Clone, Debug, Default, HashStable)]
3186 pub struct CrateInherentImpls {
3187 pub inherent_impls: DefIdMap<Vec<DefId>>,
3190 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, HashStable)]
3191 pub struct SymbolName<'tcx> {
3192 /// `&str` gives a consistent ordering, which ensures reproducible builds.
3193 pub name: &'tcx str,
3196 impl<'tcx> SymbolName<'tcx> {
3197 pub fn new(tcx: TyCtxt<'tcx>, name: &str) -> SymbolName<'tcx> {
3199 name: unsafe { str::from_utf8_unchecked(tcx.arena.alloc_slice(name.as_bytes())) },
3204 impl<'tcx> fmt::Display for SymbolName<'tcx> {
3205 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
3206 fmt::Display::fmt(&self.name, fmt)
3210 impl<'tcx> fmt::Debug for SymbolName<'tcx> {
3211 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
3212 fmt::Display::fmt(&self.name, fmt)