1 // ignore-tidy-filelength
2 pub use self::fold::{TypeFoldable, 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::ich::StableHashingContext;
10 use crate::infer::canonical::Canonical;
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_errors::ErrorReported;
32 use rustc_hir::def::{CtorKind, CtorOf, DefKind, Namespace, Res};
33 use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, LocalDefId, CRATE_DEF_INDEX};
34 use rustc_hir::lang_items::{FnMutTraitLangItem, FnOnceTraitLangItem, FnTraitLangItem};
35 use rustc_hir::{Constness, Node};
36 use rustc_index::vec::{Idx, IndexVec};
37 use rustc_macros::HashStable;
38 use rustc_serialize::{self, Encodable, Encoder};
39 use rustc_session::DataTypeKind;
40 use rustc_span::hygiene::ExpnId;
41 use rustc_span::symbol::{kw, sym, Ident, Symbol};
43 use rustc_target::abi::{Align, VariantIdx};
45 use std::cell::RefCell;
46 use std::cmp::Ordering;
48 use std::hash::{Hash, Hasher};
49 use std::marker::PhantomData;
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::{ConstVid, FloatVid, IntVid, RegionVid, TyVid};
64 pub use self::sty::{ExistentialPredicate, InferTy, ParamConst, ParamTy, ProjectionTy};
65 pub use self::sty::{ExistentialProjection, PolyExistentialProjection};
66 pub use self::sty::{ExistentialTraitRef, PolyExistentialTraitRef};
67 pub use self::sty::{PolyTraitRef, TraitRef, TyKind};
68 pub use crate::ty::diagnostics::*;
70 pub use self::binding::BindingMode;
71 pub use self::binding::BindingMode::*;
73 pub use self::context::{tls, FreeRegionInfo, TyCtxt};
74 pub use self::context::{
75 CanonicalUserType, CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations, ResolvedOpaqueTy,
76 UserType, UserTypeAnnotationIndex,
78 pub use self::context::{
79 CtxtInterners, GeneratorInteriorTypeCause, GlobalCtxt, Lift, TypeckResults,
82 pub use self::instance::{Instance, InstanceDef};
84 pub use self::list::List;
86 pub use self::trait_def::TraitDef;
88 pub use self::query::queries;
90 pub use self::consts::{Const, ConstInt, ConstKind, InferConst};
103 pub mod inhabitedness;
105 pub mod normalize_erasing_regions;
121 mod structural_impls;
126 pub struct ResolverOutputs {
127 pub definitions: rustc_hir::definitions::Definitions,
128 pub cstore: Box<CrateStoreDyn>,
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, RustcEncodable, RustcDecodable, 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 /// Returns an iterator over all associated items with the given name, ignoring hygiene.
270 pub fn filter_by_name_unhygienic(
273 ) -> impl '_ + Iterator<Item = &ty::AssocItem> {
274 self.items.get_by_key(&name).copied()
277 /// Returns an iterator over all associated items with the given name.
279 /// Multiple items may have the same name if they are in different `Namespace`s. For example,
280 /// an associated type can have the same name as a method. Use one of the `find_by_name_and_*`
281 /// methods below if you know which item you are looking for.
282 pub fn filter_by_name(
286 parent_def_id: DefId,
287 ) -> impl 'a + Iterator<Item = &'a ty::AssocItem> {
288 self.filter_by_name_unhygienic(ident.name)
289 .filter(move |item| tcx.hygienic_eq(ident, item.ident, parent_def_id))
292 /// Returns the associated item with the given name and `AssocKind`, if one exists.
293 pub fn find_by_name_and_kind(
298 parent_def_id: DefId,
299 ) -> Option<&ty::AssocItem> {
300 self.filter_by_name_unhygienic(ident.name)
301 .filter(|item| item.kind == kind)
302 .find(|item| tcx.hygienic_eq(ident, item.ident, parent_def_id))
305 /// Returns the associated item with the given name in the given `Namespace`, if one exists.
306 pub fn find_by_name_and_namespace(
311 parent_def_id: DefId,
312 ) -> Option<&ty::AssocItem> {
313 self.filter_by_name_unhygienic(ident.name)
314 .filter(|item| item.kind.namespace() == ns)
315 .find(|item| tcx.hygienic_eq(ident, item.ident, parent_def_id))
319 #[derive(Clone, Debug, PartialEq, Eq, Copy, RustcEncodable, RustcDecodable, HashStable, Hash)]
320 pub enum Visibility {
321 /// Visible everywhere (including in other crates).
323 /// Visible only in the given crate-local module.
325 /// Not visible anywhere in the local crate. This is the visibility of private external items.
329 pub trait DefIdTree: Copy {
330 fn parent(self, id: DefId) -> Option<DefId>;
332 fn is_descendant_of(self, mut descendant: DefId, ancestor: DefId) -> bool {
333 if descendant.krate != ancestor.krate {
337 while descendant != ancestor {
338 match self.parent(descendant) {
339 Some(parent) => descendant = parent,
340 None => return false,
347 impl<'tcx> DefIdTree for TyCtxt<'tcx> {
348 fn parent(self, id: DefId) -> Option<DefId> {
349 self.def_key(id).parent.map(|index| DefId { index, ..id })
354 pub fn from_hir(visibility: &hir::Visibility<'_>, id: hir::HirId, tcx: TyCtxt<'_>) -> Self {
355 match visibility.node {
356 hir::VisibilityKind::Public => Visibility::Public,
357 hir::VisibilityKind::Crate(_) => Visibility::Restricted(DefId::local(CRATE_DEF_INDEX)),
358 hir::VisibilityKind::Restricted { ref path, .. } => match path.res {
359 // If there is no resolution, `resolve` will have already reported an error, so
360 // assume that the visibility is public to avoid reporting more privacy errors.
361 Res::Err => Visibility::Public,
362 def => Visibility::Restricted(def.def_id()),
364 hir::VisibilityKind::Inherited => {
365 Visibility::Restricted(tcx.parent_module(id).to_def_id())
370 /// Returns `true` if an item with this visibility is accessible from the given block.
371 pub fn is_accessible_from<T: DefIdTree>(self, module: DefId, tree: T) -> bool {
372 let restriction = match self {
373 // Public items are visible everywhere.
374 Visibility::Public => return true,
375 // Private items from other crates are visible nowhere.
376 Visibility::Invisible => return false,
377 // Restricted items are visible in an arbitrary local module.
378 Visibility::Restricted(other) if other.krate != module.krate => return false,
379 Visibility::Restricted(module) => module,
382 tree.is_descendant_of(module, restriction)
385 /// Returns `true` if this visibility is at least as accessible as the given visibility
386 pub fn is_at_least<T: DefIdTree>(self, vis: Visibility, tree: T) -> bool {
387 let vis_restriction = match vis {
388 Visibility::Public => return self == Visibility::Public,
389 Visibility::Invisible => return true,
390 Visibility::Restricted(module) => module,
393 self.is_accessible_from(vis_restriction, tree)
396 // Returns `true` if this item is visible anywhere in the local crate.
397 pub fn is_visible_locally(self) -> bool {
399 Visibility::Public => true,
400 Visibility::Restricted(def_id) => def_id.is_local(),
401 Visibility::Invisible => false,
406 #[derive(Copy, Clone, PartialEq, RustcDecodable, RustcEncodable, HashStable)]
408 Covariant, // T<A> <: T<B> iff A <: B -- e.g., function return type
409 Invariant, // T<A> <: T<B> iff B == A -- e.g., type of mutable cell
410 Contravariant, // T<A> <: T<B> iff B <: A -- e.g., function param type
411 Bivariant, // T<A> <: T<B> -- e.g., unused type parameter
414 /// The crate variances map is computed during typeck and contains the
415 /// variance of every item in the local crate. You should not use it
416 /// directly, because to do so will make your pass dependent on the
417 /// HIR of every item in the local crate. Instead, use
418 /// `tcx.variances_of()` to get the variance for a *particular*
420 #[derive(HashStable)]
421 pub struct CrateVariancesMap<'tcx> {
422 /// For each item with generics, maps to a vector of the variance
423 /// of its generics. If an item has no generics, it will have no
425 pub variances: FxHashMap<DefId, &'tcx [ty::Variance]>,
429 /// `a.xform(b)` combines the variance of a context with the
430 /// variance of a type with the following meaning. If we are in a
431 /// context with variance `a`, and we encounter a type argument in
432 /// a position with variance `b`, then `a.xform(b)` is the new
433 /// variance with which the argument appears.
439 /// Here, the "ambient" variance starts as covariant. `*mut T` is
440 /// invariant with respect to `T`, so the variance in which the
441 /// `Vec<i32>` appears is `Covariant.xform(Invariant)`, which
442 /// yields `Invariant`. Now, the type `Vec<T>` is covariant with
443 /// respect to its type argument `T`, and hence the variance of
444 /// the `i32` here is `Invariant.xform(Covariant)`, which results
445 /// (again) in `Invariant`.
449 /// fn(*const Vec<i32>, *mut Vec<i32)
451 /// The ambient variance is covariant. A `fn` type is
452 /// contravariant with respect to its parameters, so the variance
453 /// within which both pointer types appear is
454 /// `Covariant.xform(Contravariant)`, or `Contravariant`. `*const
455 /// T` is covariant with respect to `T`, so the variance within
456 /// which the first `Vec<i32>` appears is
457 /// `Contravariant.xform(Covariant)` or `Contravariant`. The same
458 /// is true for its `i32` argument. In the `*mut T` case, the
459 /// variance of `Vec<i32>` is `Contravariant.xform(Invariant)`,
460 /// and hence the outermost type is `Invariant` with respect to
461 /// `Vec<i32>` (and its `i32` argument).
463 /// Source: Figure 1 of "Taming the Wildcards:
464 /// Combining Definition- and Use-Site Variance" published in PLDI'11.
465 pub fn xform(self, v: ty::Variance) -> ty::Variance {
467 // Figure 1, column 1.
468 (ty::Covariant, ty::Covariant) => ty::Covariant,
469 (ty::Covariant, ty::Contravariant) => ty::Contravariant,
470 (ty::Covariant, ty::Invariant) => ty::Invariant,
471 (ty::Covariant, ty::Bivariant) => ty::Bivariant,
473 // Figure 1, column 2.
474 (ty::Contravariant, ty::Covariant) => ty::Contravariant,
475 (ty::Contravariant, ty::Contravariant) => ty::Covariant,
476 (ty::Contravariant, ty::Invariant) => ty::Invariant,
477 (ty::Contravariant, ty::Bivariant) => ty::Bivariant,
479 // Figure 1, column 3.
480 (ty::Invariant, _) => ty::Invariant,
482 // Figure 1, column 4.
483 (ty::Bivariant, _) => ty::Bivariant,
488 // Contains information needed to resolve types and (in the future) look up
489 // the types of AST nodes.
490 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
491 pub struct CReaderCacheKey {
497 /// Flags that we track on types. These flags are propagated upwards
498 /// through the type during type construction, so that we can quickly check
499 /// whether the type has various kinds of types in it without recursing
500 /// over the type itself.
501 pub struct TypeFlags: u32 {
502 // Does this have parameters? Used to determine whether substitution is
504 /// Does this have [Param]?
505 const HAS_TY_PARAM = 1 << 0;
506 /// Does this have [ReEarlyBound]?
507 const HAS_RE_PARAM = 1 << 1;
508 /// Does this have [ConstKind::Param]?
509 const HAS_CT_PARAM = 1 << 2;
511 const NEEDS_SUBST = TypeFlags::HAS_TY_PARAM.bits
512 | TypeFlags::HAS_RE_PARAM.bits
513 | TypeFlags::HAS_CT_PARAM.bits;
515 /// Does this have [Infer]?
516 const HAS_TY_INFER = 1 << 3;
517 /// Does this have [ReVar]?
518 const HAS_RE_INFER = 1 << 4;
519 /// Does this have [ConstKind::Infer]?
520 const HAS_CT_INFER = 1 << 5;
522 /// Does this have inference variables? Used to determine whether
523 /// inference is required.
524 const NEEDS_INFER = TypeFlags::HAS_TY_INFER.bits
525 | TypeFlags::HAS_RE_INFER.bits
526 | TypeFlags::HAS_CT_INFER.bits;
528 /// Does this have [Placeholder]?
529 const HAS_TY_PLACEHOLDER = 1 << 6;
530 /// Does this have [RePlaceholder]?
531 const HAS_RE_PLACEHOLDER = 1 << 7;
532 /// Does this have [ConstKind::Placeholder]?
533 const HAS_CT_PLACEHOLDER = 1 << 8;
535 /// `true` if there are "names" of regions and so forth
536 /// that are local to a particular fn/inferctxt
537 const HAS_FREE_LOCAL_REGIONS = 1 << 9;
539 /// `true` if there are "names" of types and regions and so forth
540 /// that are local to a particular fn
541 const HAS_FREE_LOCAL_NAMES = TypeFlags::HAS_TY_PARAM.bits
542 | TypeFlags::HAS_CT_PARAM.bits
543 | TypeFlags::HAS_TY_INFER.bits
544 | TypeFlags::HAS_CT_INFER.bits
545 | TypeFlags::HAS_TY_PLACEHOLDER.bits
546 | TypeFlags::HAS_CT_PLACEHOLDER.bits
547 | TypeFlags::HAS_FREE_LOCAL_REGIONS.bits;
549 /// Does this have [Projection]?
550 const HAS_TY_PROJECTION = 1 << 10;
551 /// Does this have [Opaque]?
552 const HAS_TY_OPAQUE = 1 << 11;
553 /// Does this have [ConstKind::Unevaluated]?
554 const HAS_CT_PROJECTION = 1 << 12;
556 /// Could this type be normalized further?
557 const HAS_PROJECTION = TypeFlags::HAS_TY_PROJECTION.bits
558 | TypeFlags::HAS_TY_OPAQUE.bits
559 | TypeFlags::HAS_CT_PROJECTION.bits;
561 /// Is an error type/const reachable?
562 const HAS_ERROR = 1 << 13;
564 /// Does this have any region that "appears free" in the type?
565 /// Basically anything but [ReLateBound] and [ReErased].
566 const HAS_FREE_REGIONS = 1 << 14;
568 /// Does this have any [ReLateBound] regions? Used to check
569 /// if a global bound is safe to evaluate.
570 const HAS_RE_LATE_BOUND = 1 << 15;
572 /// Does this have any [ReErased] regions?
573 const HAS_RE_ERASED = 1 << 16;
575 /// Does this value have parameters/placeholders/inference variables which could be
576 /// replaced later, in a way that would change the results of `impl` specialization?
577 const STILL_FURTHER_SPECIALIZABLE = 1 << 17;
581 #[allow(rustc::usage_of_ty_tykind)]
582 pub struct TyS<'tcx> {
583 pub kind: TyKind<'tcx>,
584 pub flags: TypeFlags,
586 /// This is a kind of confusing thing: it stores the smallest
589 /// (a) the binder itself captures nothing but
590 /// (b) all the late-bound things within the type are captured
591 /// by some sub-binder.
593 /// So, for a type without any late-bound things, like `u32`, this
594 /// will be *innermost*, because that is the innermost binder that
595 /// captures nothing. But for a type `&'D u32`, where `'D` is a
596 /// late-bound region with De Bruijn index `D`, this would be `D + 1`
597 /// -- the binder itself does not capture `D`, but `D` is captured
598 /// by an inner binder.
600 /// We call this concept an "exclusive" binder `D` because all
601 /// De Bruijn indices within the type are contained within `0..D`
603 outer_exclusive_binder: ty::DebruijnIndex,
606 // `TyS` is used a lot. Make sure it doesn't unintentionally get bigger.
607 #[cfg(target_arch = "x86_64")]
608 static_assert_size!(TyS<'_>, 32);
610 impl<'tcx> Ord for TyS<'tcx> {
611 fn cmp(&self, other: &TyS<'tcx>) -> Ordering {
612 self.kind.cmp(&other.kind)
616 impl<'tcx> PartialOrd for TyS<'tcx> {
617 fn partial_cmp(&self, other: &TyS<'tcx>) -> Option<Ordering> {
618 Some(self.kind.cmp(&other.kind))
622 impl<'tcx> PartialEq for TyS<'tcx> {
624 fn eq(&self, other: &TyS<'tcx>) -> bool {
628 impl<'tcx> Eq for TyS<'tcx> {}
630 impl<'tcx> Hash for TyS<'tcx> {
631 fn hash<H: Hasher>(&self, s: &mut H) {
632 (self as *const TyS<'_>).hash(s)
636 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for TyS<'tcx> {
637 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
641 // The other fields just provide fast access to information that is
642 // also contained in `kind`, so no need to hash them.
645 outer_exclusive_binder: _,
648 kind.hash_stable(hcx, hasher);
652 #[rustc_diagnostic_item = "Ty"]
653 pub type Ty<'tcx> = &'tcx TyS<'tcx>;
655 impl<'tcx> rustc_serialize::UseSpecializedEncodable for Ty<'tcx> {}
656 impl<'tcx> rustc_serialize::UseSpecializedDecodable for Ty<'tcx> {}
657 impl<'tcx> rustc_serialize::UseSpecializedDecodable for &'tcx List<Ty<'tcx>> {}
659 pub type CanonicalTy<'tcx> = Canonical<'tcx, Ty<'tcx>>;
661 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
662 pub struct UpvarPath {
663 pub hir_id: hir::HirId,
666 /// Upvars do not get their own `NodeId`. Instead, we use the pair of
667 /// the original var ID (that is, the root variable that is referenced
668 /// by the upvar) and the ID of the closure expression.
669 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
671 pub var_path: UpvarPath,
672 pub closure_expr_id: LocalDefId,
675 #[derive(Clone, PartialEq, Debug, RustcEncodable, RustcDecodable, Copy, HashStable)]
676 pub enum BorrowKind {
677 /// Data must be immutable and is aliasable.
680 /// Data must be immutable but not aliasable. This kind of borrow
681 /// cannot currently be expressed by the user and is used only in
682 /// implicit closure bindings. It is needed when the closure
683 /// is borrowing or mutating a mutable referent, e.g.:
685 /// let x: &mut isize = ...;
686 /// let y = || *x += 5;
688 /// If we were to try to translate this closure into a more explicit
689 /// form, we'd encounter an error with the code as written:
691 /// struct Env { x: & &mut isize }
692 /// let x: &mut isize = ...;
693 /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
694 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
696 /// This is then illegal because you cannot mutate a `&mut` found
697 /// in an aliasable location. To solve, you'd have to translate with
698 /// an `&mut` borrow:
700 /// struct Env { x: & &mut isize }
701 /// let x: &mut isize = ...;
702 /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
703 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
705 /// Now the assignment to `**env.x` is legal, but creating a
706 /// mutable pointer to `x` is not because `x` is not mutable. We
707 /// could fix this by declaring `x` as `let mut x`. This is ok in
708 /// user code, if awkward, but extra weird for closures, since the
709 /// borrow is hidden.
711 /// So we introduce a "unique imm" borrow -- the referent is
712 /// immutable, but not aliasable. This solves the problem. For
713 /// simplicity, we don't give users the way to express this
714 /// borrow, it's just used when translating closures.
717 /// Data is mutable and not aliasable.
721 /// Information describing the capture of an upvar. This is computed
722 /// during `typeck`, specifically by `regionck`.
723 #[derive(PartialEq, Clone, Debug, Copy, RustcEncodable, RustcDecodable, HashStable)]
724 pub enum UpvarCapture<'tcx> {
725 /// Upvar is captured by value. This is always true when the
726 /// closure is labeled `move`, but can also be true in other cases
727 /// depending on inference.
730 /// Upvar is captured by reference.
731 ByRef(UpvarBorrow<'tcx>),
734 #[derive(PartialEq, Clone, Copy, RustcEncodable, RustcDecodable, HashStable)]
735 pub struct UpvarBorrow<'tcx> {
736 /// The kind of borrow: by-ref upvars have access to shared
737 /// immutable borrows, which are not part of the normal language
739 pub kind: BorrowKind,
741 /// Region of the resulting reference.
742 pub region: ty::Region<'tcx>,
745 pub type UpvarListMap = FxHashMap<DefId, FxIndexMap<hir::HirId, UpvarId>>;
746 pub type UpvarCaptureMap<'tcx> = FxHashMap<UpvarId, UpvarCapture<'tcx>>;
748 #[derive(Clone, Copy, PartialEq, Eq)]
749 pub enum IntVarValue {
751 UintType(ast::UintTy),
754 #[derive(Clone, Copy, PartialEq, Eq)]
755 pub struct FloatVarValue(pub ast::FloatTy);
757 impl ty::EarlyBoundRegion {
758 pub fn to_bound_region(&self) -> ty::BoundRegion {
759 ty::BoundRegion::BrNamed(self.def_id, self.name)
762 /// Does this early bound region have a name? Early bound regions normally
763 /// always have names except when using anonymous lifetimes (`'_`).
764 pub fn has_name(&self) -> bool {
765 self.name != kw::UnderscoreLifetime
769 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
770 pub enum GenericParamDefKind {
774 object_lifetime_default: ObjectLifetimeDefault,
775 synthetic: Option<hir::SyntheticTyParamKind>,
780 impl GenericParamDefKind {
781 pub fn descr(&self) -> &'static str {
783 GenericParamDefKind::Lifetime => "lifetime",
784 GenericParamDefKind::Type { .. } => "type",
785 GenericParamDefKind::Const => "constant",
790 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
791 pub struct GenericParamDef {
796 /// `pure_wrt_drop`, set by the (unsafe) `#[may_dangle]` attribute
797 /// on generic parameter `'a`/`T`, asserts data behind the parameter
798 /// `'a`/`T` won't be accessed during the parent type's `Drop` impl.
799 pub pure_wrt_drop: bool,
801 pub kind: GenericParamDefKind,
804 impl GenericParamDef {
805 pub fn to_early_bound_region_data(&self) -> ty::EarlyBoundRegion {
806 if let GenericParamDefKind::Lifetime = self.kind {
807 ty::EarlyBoundRegion { def_id: self.def_id, index: self.index, name: self.name }
809 bug!("cannot convert a non-lifetime parameter def to an early bound region")
813 pub fn to_bound_region(&self) -> ty::BoundRegion {
814 if let GenericParamDefKind::Lifetime = self.kind {
815 self.to_early_bound_region_data().to_bound_region()
817 bug!("cannot convert a non-lifetime parameter def to an early bound region")
823 pub struct GenericParamCount {
824 pub lifetimes: usize,
829 /// Information about the formal type/lifetime parameters associated
830 /// with an item or method. Analogous to `hir::Generics`.
832 /// The ordering of parameters is the same as in `Subst` (excluding child generics):
833 /// `Self` (optionally), `Lifetime` params..., `Type` params...
834 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
835 pub struct Generics {
836 pub parent: Option<DefId>,
837 pub parent_count: usize,
838 pub params: Vec<GenericParamDef>,
840 /// Reverse map to the `index` field of each `GenericParamDef`.
841 #[stable_hasher(ignore)]
842 pub param_def_id_to_index: FxHashMap<DefId, u32>,
845 pub has_late_bound_regions: Option<Span>,
848 impl<'tcx> Generics {
849 pub fn count(&self) -> usize {
850 self.parent_count + self.params.len()
853 pub fn own_counts(&self) -> GenericParamCount {
854 // We could cache this as a property of `GenericParamCount`, but
855 // the aim is to refactor this away entirely eventually and the
856 // presence of this method will be a constant reminder.
857 let mut own_counts: GenericParamCount = Default::default();
859 for param in &self.params {
861 GenericParamDefKind::Lifetime => own_counts.lifetimes += 1,
862 GenericParamDefKind::Type { .. } => own_counts.types += 1,
863 GenericParamDefKind::Const => own_counts.consts += 1,
870 pub fn requires_monomorphization(&self, tcx: TyCtxt<'tcx>) -> bool {
871 if self.own_requires_monomorphization() {
875 if let Some(parent_def_id) = self.parent {
876 let parent = tcx.generics_of(parent_def_id);
877 parent.requires_monomorphization(tcx)
883 pub fn own_requires_monomorphization(&self) -> bool {
884 for param in &self.params {
886 GenericParamDefKind::Type { .. } | GenericParamDefKind::Const => return true,
887 GenericParamDefKind::Lifetime => {}
893 /// Returns the `GenericParamDef` with the given index.
894 pub fn param_at(&'tcx self, param_index: usize, tcx: TyCtxt<'tcx>) -> &'tcx GenericParamDef {
895 if let Some(index) = param_index.checked_sub(self.parent_count) {
898 tcx.generics_of(self.parent.expect("parent_count > 0 but no parent?"))
899 .param_at(param_index, tcx)
903 /// Returns the `GenericParamDef` associated with this `EarlyBoundRegion`.
906 param: &EarlyBoundRegion,
908 ) -> &'tcx GenericParamDef {
909 let param = self.param_at(param.index as usize, tcx);
911 GenericParamDefKind::Lifetime => param,
912 _ => bug!("expected lifetime parameter, but found another generic parameter"),
916 /// Returns the `GenericParamDef` associated with this `ParamTy`.
917 pub fn type_param(&'tcx self, param: &ParamTy, tcx: TyCtxt<'tcx>) -> &'tcx GenericParamDef {
918 let param = self.param_at(param.index as usize, tcx);
920 GenericParamDefKind::Type { .. } => param,
921 _ => bug!("expected type parameter, but found another generic parameter"),
925 /// Returns the `GenericParamDef` associated with this `ParamConst`.
926 pub fn const_param(&'tcx self, param: &ParamConst, tcx: TyCtxt<'tcx>) -> &GenericParamDef {
927 let param = self.param_at(param.index as usize, tcx);
929 GenericParamDefKind::Const => param,
930 _ => bug!("expected const parameter, but found another generic parameter"),
935 /// Bounds on generics.
936 #[derive(Copy, Clone, Default, Debug, RustcEncodable, RustcDecodable, HashStable)]
937 pub struct GenericPredicates<'tcx> {
938 pub parent: Option<DefId>,
939 pub predicates: &'tcx [(Predicate<'tcx>, Span)],
942 impl<'tcx> GenericPredicates<'tcx> {
946 substs: SubstsRef<'tcx>,
947 ) -> InstantiatedPredicates<'tcx> {
948 let mut instantiated = InstantiatedPredicates::empty();
949 self.instantiate_into(tcx, &mut instantiated, substs);
953 pub fn instantiate_own(
956 substs: SubstsRef<'tcx>,
957 ) -> InstantiatedPredicates<'tcx> {
958 InstantiatedPredicates {
959 predicates: self.predicates.iter().map(|(p, _)| p.subst(tcx, substs)).collect(),
960 spans: self.predicates.iter().map(|(_, sp)| *sp).collect(),
967 instantiated: &mut InstantiatedPredicates<'tcx>,
968 substs: SubstsRef<'tcx>,
970 if let Some(def_id) = self.parent {
971 tcx.predicates_of(def_id).instantiate_into(tcx, instantiated, substs);
973 instantiated.predicates.extend(self.predicates.iter().map(|(p, _)| p.subst(tcx, substs)));
974 instantiated.spans.extend(self.predicates.iter().map(|(_, sp)| *sp));
977 pub fn instantiate_identity(&self, tcx: TyCtxt<'tcx>) -> InstantiatedPredicates<'tcx> {
978 let mut instantiated = InstantiatedPredicates::empty();
979 self.instantiate_identity_into(tcx, &mut instantiated);
983 fn instantiate_identity_into(
986 instantiated: &mut InstantiatedPredicates<'tcx>,
988 if let Some(def_id) = self.parent {
989 tcx.predicates_of(def_id).instantiate_identity_into(tcx, instantiated);
991 instantiated.predicates.extend(self.predicates.iter().map(|(p, _)| p));
992 instantiated.spans.extend(self.predicates.iter().map(|(_, s)| s));
995 pub fn instantiate_supertrait(
998 poly_trait_ref: &ty::PolyTraitRef<'tcx>,
999 ) -> InstantiatedPredicates<'tcx> {
1000 assert_eq!(self.parent, None);
1001 InstantiatedPredicates {
1005 .map(|(pred, _)| pred.subst_supertrait(tcx, poly_trait_ref))
1007 spans: self.predicates.iter().map(|(_, sp)| *sp).collect(),
1013 crate struct PredicateInner<'tcx> {
1014 kind: PredicateKind<'tcx>,
1016 /// See the comment for the corresponding field of [TyS].
1017 outer_exclusive_binder: ty::DebruijnIndex,
1020 #[cfg(target_arch = "x86_64")]
1021 static_assert_size!(PredicateInner<'_>, 48);
1023 #[derive(Clone, Copy, Lift)]
1024 pub struct Predicate<'tcx> {
1025 inner: &'tcx PredicateInner<'tcx>,
1028 impl rustc_serialize::UseSpecializedEncodable for Predicate<'_> {}
1029 impl rustc_serialize::UseSpecializedDecodable for Predicate<'_> {}
1031 impl<'tcx> PartialEq for Predicate<'tcx> {
1032 fn eq(&self, other: &Self) -> bool {
1033 // `self.kind` is always interned.
1034 ptr::eq(self.inner, other.inner)
1038 impl Hash for Predicate<'_> {
1039 fn hash<H: Hasher>(&self, s: &mut H) {
1040 (self.inner as *const PredicateInner<'_>).hash(s)
1044 impl<'tcx> Eq for Predicate<'tcx> {}
1046 impl<'tcx> Predicate<'tcx> {
1048 pub fn kind(self) -> &'tcx PredicateKind<'tcx> {
1052 /// Returns the inner `PredicateAtom`.
1054 /// Note that this method panics in case this predicate has unbound variables.
1055 pub fn skip_binders(self) -> PredicateAtom<'tcx> {
1057 &PredicateKind::ForAll(binder) => binder.skip_binder().skip_binders(),
1058 &ty::PredicateKind::Atom(atom) => atom,
1062 /// Returns the inner `PredicateAtom`.
1064 /// Note that this method does not check if predicate has unbound variables,
1065 /// rebinding the returned atom potentially causes the previously bound variables
1066 /// to end up at the wrong binding level.
1067 pub fn skip_binders_unchecked(self) -> PredicateAtom<'tcx> {
1069 &PredicateKind::ForAll(binder) => binder.skip_binder().skip_binders(),
1070 &ty::PredicateKind::Atom(atom) => atom,
1074 pub fn bound_atom(self, tcx: TyCtxt<'tcx>) -> Binder<PredicateAtom<'tcx>> {
1076 &PredicateKind::ForAll(binder) => binder.map_bound(|inner| match inner.kind() {
1077 ty::PredicateKind::ForAll(_) => bug!("unexpect forall"),
1078 &ty::PredicateKind::Atom(atom) => atom,
1080 &ty::PredicateKind::Atom(atom) => Binder::wrap_nonbinding(tcx, atom),
1084 /// Wraps `self` with the given qualifier if this predicate has any unbound variables.
1085 pub fn potentially_quantified(
1088 qualifier: impl FnOnce(Binder<Predicate<'tcx>>) -> PredicateKind<'tcx>,
1089 ) -> Predicate<'tcx> {
1090 if self.has_escaping_bound_vars() {
1091 qualifier(Binder::bind(self)).to_predicate(tcx)
1098 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for Predicate<'tcx> {
1099 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
1100 let PredicateInner {
1103 // The other fields just provide fast access to information that is
1104 // also contained in `kind`, so no need to hash them.
1106 outer_exclusive_binder: _,
1109 kind.hash_stable(hcx, hasher);
1113 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1114 #[derive(HashStable, TypeFoldable)]
1115 pub enum PredicateKind<'tcx> {
1117 ForAll(Binder<Predicate<'tcx>>),
1119 Atom(PredicateAtom<'tcx>),
1122 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1123 #[derive(HashStable, TypeFoldable)]
1124 pub enum PredicateAtom<'tcx> {
1125 /// Corresponds to `where Foo: Bar<A, B, C>`. `Foo` here would be
1126 /// the `Self` type of the trait reference and `A`, `B`, and `C`
1127 /// would be the type parameters.
1129 /// A trait predicate will have `Constness::Const` if it originates
1130 /// from a bound on a `const fn` without the `?const` opt-out (e.g.,
1131 /// `const fn foobar<Foo: Bar>() {}`).
1132 Trait(TraitPredicate<'tcx>, Constness),
1135 RegionOutlives(RegionOutlivesPredicate<'tcx>),
1138 TypeOutlives(TypeOutlivesPredicate<'tcx>),
1140 /// `where <T as TraitRef>::Name == X`, approximately.
1141 /// See the `ProjectionPredicate` struct for details.
1142 Projection(ProjectionPredicate<'tcx>),
1144 /// No syntax: `T` well-formed.
1145 WellFormed(GenericArg<'tcx>),
1147 /// Trait must be object-safe.
1150 /// No direct syntax. May be thought of as `where T: FnFoo<...>`
1151 /// for some substitutions `...` and `T` being a closure type.
1152 /// Satisfied (or refuted) once we know the closure's kind.
1153 ClosureKind(DefId, SubstsRef<'tcx>, ClosureKind),
1156 Subtype(SubtypePredicate<'tcx>),
1158 /// Constant initializer must evaluate successfully.
1159 ConstEvaluatable(ty::WithOptConstParam<DefId>, SubstsRef<'tcx>),
1161 /// Constants must be equal. The first component is the const that is expected.
1162 ConstEquate(&'tcx Const<'tcx>, &'tcx Const<'tcx>),
1165 /// The crate outlives map is computed during typeck and contains the
1166 /// outlives of every item in the local crate. You should not use it
1167 /// directly, because to do so will make your pass dependent on the
1168 /// HIR of every item in the local crate. Instead, use
1169 /// `tcx.inferred_outlives_of()` to get the outlives for a *particular*
1171 #[derive(HashStable)]
1172 pub struct CratePredicatesMap<'tcx> {
1173 /// For each struct with outlive bounds, maps to a vector of the
1174 /// predicate of its outlive bounds. If an item has no outlives
1175 /// bounds, it will have no entry.
1176 pub predicates: FxHashMap<DefId, &'tcx [(ty::Predicate<'tcx>, Span)]>,
1179 impl<'tcx> Predicate<'tcx> {
1180 /// Performs a substitution suitable for going from a
1181 /// poly-trait-ref to supertraits that must hold if that
1182 /// poly-trait-ref holds. This is slightly different from a normal
1183 /// substitution in terms of what happens with bound regions. See
1184 /// lengthy comment below for details.
1185 pub fn subst_supertrait(
1188 trait_ref: &ty::PolyTraitRef<'tcx>,
1189 ) -> ty::Predicate<'tcx> {
1190 // The interaction between HRTB and supertraits is not entirely
1191 // obvious. Let me walk you (and myself) through an example.
1193 // Let's start with an easy case. Consider two traits:
1195 // trait Foo<'a>: Bar<'a,'a> { }
1196 // trait Bar<'b,'c> { }
1198 // Now, if we have a trait reference `for<'x> T: Foo<'x>`, then
1199 // we can deduce that `for<'x> T: Bar<'x,'x>`. Basically, if we
1200 // knew that `Foo<'x>` (for any 'x) then we also know that
1201 // `Bar<'x,'x>` (for any 'x). This more-or-less falls out from
1202 // normal substitution.
1204 // In terms of why this is sound, the idea is that whenever there
1205 // is an impl of `T:Foo<'a>`, it must show that `T:Bar<'a,'a>`
1206 // holds. So if there is an impl of `T:Foo<'a>` that applies to
1207 // all `'a`, then we must know that `T:Bar<'a,'a>` holds for all
1210 // Another example to be careful of is this:
1212 // trait Foo1<'a>: for<'b> Bar1<'a,'b> { }
1213 // trait Bar1<'b,'c> { }
1215 // Here, if we have `for<'x> T: Foo1<'x>`, then what do we know?
1216 // The answer is that we know `for<'x,'b> T: Bar1<'x,'b>`. The
1217 // reason is similar to the previous example: any impl of
1218 // `T:Foo1<'x>` must show that `for<'b> T: Bar1<'x, 'b>`. So
1219 // basically we would want to collapse the bound lifetimes from
1220 // the input (`trait_ref`) and the supertraits.
1222 // To achieve this in practice is fairly straightforward. Let's
1223 // consider the more complicated scenario:
1225 // - We start out with `for<'x> T: Foo1<'x>`. In this case, `'x`
1226 // has a De Bruijn index of 1. We want to produce `for<'x,'b> T: Bar1<'x,'b>`,
1227 // where both `'x` and `'b` would have a DB index of 1.
1228 // The substitution from the input trait-ref is therefore going to be
1229 // `'a => 'x` (where `'x` has a DB index of 1).
1230 // - The super-trait-ref is `for<'b> Bar1<'a,'b>`, where `'a` is an
1231 // early-bound parameter and `'b' is a late-bound parameter with a
1233 // - If we replace `'a` with `'x` from the input, it too will have
1234 // a DB index of 1, and thus we'll have `for<'x,'b> Bar1<'x,'b>`
1235 // just as we wanted.
1237 // There is only one catch. If we just apply the substitution `'a
1238 // => 'x` to `for<'b> Bar1<'a,'b>`, the substitution code will
1239 // adjust the DB index because we substituting into a binder (it
1240 // tries to be so smart...) resulting in `for<'x> for<'b>
1241 // Bar1<'x,'b>` (we have no syntax for this, so use your
1242 // imagination). Basically the 'x will have DB index of 2 and 'b
1243 // will have DB index of 1. Not quite what we want. So we apply
1244 // the substitution to the *contents* of the trait reference,
1245 // rather than the trait reference itself (put another way, the
1246 // substitution code expects equal binding levels in the values
1247 // from the substitution and the value being substituted into, and
1248 // this trick achieves that).
1249 let substs = trait_ref.skip_binder().substs;
1250 let pred = self.skip_binders();
1251 let new = pred.subst(tcx, substs);
1253 new.to_predicate(tcx).potentially_quantified(tcx, PredicateKind::ForAll)
1260 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1261 #[derive(HashStable, TypeFoldable)]
1262 pub struct TraitPredicate<'tcx> {
1263 pub trait_ref: TraitRef<'tcx>,
1266 pub type PolyTraitPredicate<'tcx> = ty::Binder<TraitPredicate<'tcx>>;
1268 impl<'tcx> TraitPredicate<'tcx> {
1269 pub fn def_id(self) -> DefId {
1270 self.trait_ref.def_id
1273 pub fn self_ty(self) -> Ty<'tcx> {
1274 self.trait_ref.self_ty()
1278 impl<'tcx> PolyTraitPredicate<'tcx> {
1279 pub fn def_id(self) -> DefId {
1280 // Ok to skip binder since trait `DefId` does not care about regions.
1281 self.skip_binder().def_id()
1285 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, RustcEncodable, RustcDecodable)]
1286 #[derive(HashStable, TypeFoldable)]
1287 pub struct OutlivesPredicate<A, B>(pub A, pub B); // `A: B`
1288 pub type PolyOutlivesPredicate<A, B> = ty::Binder<OutlivesPredicate<A, B>>;
1289 pub type RegionOutlivesPredicate<'tcx> = OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>;
1290 pub type TypeOutlivesPredicate<'tcx> = OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>;
1291 pub type PolyRegionOutlivesPredicate<'tcx> = ty::Binder<RegionOutlivesPredicate<'tcx>>;
1292 pub type PolyTypeOutlivesPredicate<'tcx> = ty::Binder<TypeOutlivesPredicate<'tcx>>;
1294 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
1295 #[derive(HashStable, TypeFoldable)]
1296 pub struct SubtypePredicate<'tcx> {
1297 pub a_is_expected: bool,
1301 pub type PolySubtypePredicate<'tcx> = ty::Binder<SubtypePredicate<'tcx>>;
1303 /// This kind of predicate has no *direct* correspondent in the
1304 /// syntax, but it roughly corresponds to the syntactic forms:
1306 /// 1. `T: TraitRef<..., Item = Type>`
1307 /// 2. `<T as TraitRef<...>>::Item == Type` (NYI)
1309 /// In particular, form #1 is "desugared" to the combination of a
1310 /// normal trait predicate (`T: TraitRef<...>`) and one of these
1311 /// predicates. Form #2 is a broader form in that it also permits
1312 /// equality between arbitrary types. Processing an instance of
1313 /// Form #2 eventually yields one of these `ProjectionPredicate`
1314 /// instances to normalize the LHS.
1315 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1316 #[derive(HashStable, TypeFoldable)]
1317 pub struct ProjectionPredicate<'tcx> {
1318 pub projection_ty: ProjectionTy<'tcx>,
1322 pub type PolyProjectionPredicate<'tcx> = Binder<ProjectionPredicate<'tcx>>;
1324 impl<'tcx> PolyProjectionPredicate<'tcx> {
1325 /// Returns the `DefId` of the associated item being projected.
1326 pub fn item_def_id(&self) -> DefId {
1327 self.skip_binder().projection_ty.item_def_id
1331 pub fn to_poly_trait_ref(&self, tcx: TyCtxt<'tcx>) -> PolyTraitRef<'tcx> {
1332 // Note: unlike with `TraitRef::to_poly_trait_ref()`,
1333 // `self.0.trait_ref` is permitted to have escaping regions.
1334 // This is because here `self` has a `Binder` and so does our
1335 // return value, so we are preserving the number of binding
1337 self.map_bound(|predicate| predicate.projection_ty.trait_ref(tcx))
1340 pub fn ty(&self) -> Binder<Ty<'tcx>> {
1341 self.map_bound(|predicate| predicate.ty)
1344 /// The `DefId` of the `TraitItem` for the associated type.
1346 /// Note that this is not the `DefId` of the `TraitRef` containing this
1347 /// associated type, which is in `tcx.associated_item(projection_def_id()).container`.
1348 pub fn projection_def_id(&self) -> DefId {
1349 // Ok to skip binder since trait `DefId` does not care about regions.
1350 self.skip_binder().projection_ty.item_def_id
1354 pub trait ToPolyTraitRef<'tcx> {
1355 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx>;
1358 impl<'tcx> ToPolyTraitRef<'tcx> for TraitRef<'tcx> {
1359 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
1360 ty::Binder::dummy(*self)
1364 impl<'tcx> ToPolyTraitRef<'tcx> for PolyTraitPredicate<'tcx> {
1365 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
1366 self.map_bound_ref(|trait_pred| trait_pred.trait_ref)
1370 pub trait ToPredicate<'tcx> {
1371 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx>;
1374 impl ToPredicate<'tcx> for PredicateKind<'tcx> {
1376 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1377 tcx.mk_predicate(self)
1381 impl ToPredicate<'tcx> for PredicateAtom<'tcx> {
1383 fn to_predicate(&self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1384 tcx.mk_predicate(ty::PredicateKind::Atom(*self))
1388 impl<'tcx> ToPredicate<'tcx> for ConstnessAnd<TraitRef<'tcx>> {
1389 fn to_predicate(&self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1390 ty::PredicateAtom::Trait(ty::TraitPredicate { trait_ref: self.value }, self.constness)
1395 impl<'tcx> ToPredicate<'tcx> for ConstnessAnd<PolyTraitRef<'tcx>> {
1396 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1398 value: self.value.map_bound(|trait_ref| ty::TraitPredicate { trait_ref }),
1399 constness: self.constness,
1405 impl<'tcx> ToPredicate<'tcx> for ConstnessAnd<PolyTraitPredicate<'tcx>> {
1406 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1407 if let Some(pred) = self.value.no_bound_vars() {
1408 ty::PredicateAtom::Trait(pred, self.constness).to_predicate(tcx)
1410 ty::PredicateKind::ForAll(
1411 self.value.map_bound(|pred| {
1412 ty::PredicateAtom::Trait(pred, self.constness).to_predicate(tcx)
1420 impl<'tcx> ToPredicate<'tcx> for PolyRegionOutlivesPredicate<'tcx> {
1421 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1422 if let Some(outlives) = self.no_bound_vars() {
1423 PredicateAtom::RegionOutlives(outlives).to_predicate(tcx)
1425 ty::PredicateKind::ForAll(
1426 self.map_bound(|outlives| {
1427 PredicateAtom::RegionOutlives(outlives).to_predicate(tcx)
1435 impl<'tcx> ToPredicate<'tcx> for PolyTypeOutlivesPredicate<'tcx> {
1436 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1437 if let Some(outlives) = self.no_bound_vars() {
1438 PredicateAtom::TypeOutlives(outlives).to_predicate(tcx)
1440 ty::PredicateKind::ForAll(
1441 self.map_bound(|outlives| PredicateAtom::TypeOutlives(outlives).to_predicate(tcx)),
1448 impl<'tcx> ToPredicate<'tcx> for PolyProjectionPredicate<'tcx> {
1449 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1450 if let Some(proj) = self.no_bound_vars() {
1451 PredicateAtom::Projection(proj).to_predicate(tcx)
1453 ty::PredicateKind::ForAll(
1454 self.map_bound(|proj| PredicateAtom::Projection(proj).to_predicate(tcx)),
1461 impl<'tcx> Predicate<'tcx> {
1462 pub fn to_opt_poly_trait_ref(self) -> Option<PolyTraitRef<'tcx>> {
1463 match self.skip_binders() {
1464 PredicateAtom::Trait(t, _) => Some(ty::Binder::bind(t.trait_ref)),
1465 PredicateAtom::Projection(..)
1466 | PredicateAtom::Subtype(..)
1467 | PredicateAtom::RegionOutlives(..)
1468 | PredicateAtom::WellFormed(..)
1469 | PredicateAtom::ObjectSafe(..)
1470 | PredicateAtom::ClosureKind(..)
1471 | PredicateAtom::TypeOutlives(..)
1472 | PredicateAtom::ConstEvaluatable(..)
1473 | PredicateAtom::ConstEquate(..) => None,
1477 pub fn to_opt_type_outlives(self) -> Option<PolyTypeOutlivesPredicate<'tcx>> {
1478 match self.skip_binders() {
1479 PredicateAtom::TypeOutlives(data) => Some(ty::Binder::bind(data)),
1480 PredicateAtom::Trait(..)
1481 | PredicateAtom::Projection(..)
1482 | PredicateAtom::Subtype(..)
1483 | PredicateAtom::RegionOutlives(..)
1484 | PredicateAtom::WellFormed(..)
1485 | PredicateAtom::ObjectSafe(..)
1486 | PredicateAtom::ClosureKind(..)
1487 | PredicateAtom::ConstEvaluatable(..)
1488 | PredicateAtom::ConstEquate(..) => None,
1493 /// Represents the bounds declared on a particular set of type
1494 /// parameters. Should eventually be generalized into a flag list of
1495 /// where-clauses. You can obtain a `InstantiatedPredicates` list from a
1496 /// `GenericPredicates` by using the `instantiate` method. Note that this method
1497 /// reflects an important semantic invariant of `InstantiatedPredicates`: while
1498 /// the `GenericPredicates` are expressed in terms of the bound type
1499 /// parameters of the impl/trait/whatever, an `InstantiatedPredicates` instance
1500 /// represented a set of bounds for some particular instantiation,
1501 /// meaning that the generic parameters have been substituted with
1506 /// struct Foo<T, U: Bar<T>> { ... }
1508 /// Here, the `GenericPredicates` for `Foo` would contain a list of bounds like
1509 /// `[[], [U:Bar<T>]]`. Now if there were some particular reference
1510 /// like `Foo<isize,usize>`, then the `InstantiatedPredicates` would be `[[],
1511 /// [usize:Bar<isize>]]`.
1512 #[derive(Clone, Debug, TypeFoldable)]
1513 pub struct InstantiatedPredicates<'tcx> {
1514 pub predicates: Vec<Predicate<'tcx>>,
1515 pub spans: Vec<Span>,
1518 impl<'tcx> InstantiatedPredicates<'tcx> {
1519 pub fn empty() -> InstantiatedPredicates<'tcx> {
1520 InstantiatedPredicates { predicates: vec![], spans: vec![] }
1523 pub fn is_empty(&self) -> bool {
1524 self.predicates.is_empty()
1528 rustc_index::newtype_index! {
1529 /// "Universes" are used during type- and trait-checking in the
1530 /// presence of `for<..>` binders to control what sets of names are
1531 /// visible. Universes are arranged into a tree: the root universe
1532 /// contains names that are always visible. Each child then adds a new
1533 /// set of names that are visible, in addition to those of its parent.
1534 /// We say that the child universe "extends" the parent universe with
1537 /// To make this more concrete, consider this program:
1541 /// fn bar<T>(x: T) {
1542 /// let y: for<'a> fn(&'a u8, Foo) = ...;
1546 /// The struct name `Foo` is in the root universe U0. But the type
1547 /// parameter `T`, introduced on `bar`, is in an extended universe U1
1548 /// -- i.e., within `bar`, we can name both `T` and `Foo`, but outside
1549 /// of `bar`, we cannot name `T`. Then, within the type of `y`, the
1550 /// region `'a` is in a universe U2 that extends U1, because we can
1551 /// name it inside the fn type but not outside.
1553 /// Universes are used to do type- and trait-checking around these
1554 /// "forall" binders (also called **universal quantification**). The
1555 /// idea is that when, in the body of `bar`, we refer to `T` as a
1556 /// type, we aren't referring to any type in particular, but rather a
1557 /// kind of "fresh" type that is distinct from all other types we have
1558 /// actually declared. This is called a **placeholder** type, and we
1559 /// use universes to talk about this. In other words, a type name in
1560 /// universe 0 always corresponds to some "ground" type that the user
1561 /// declared, but a type name in a non-zero universe is a placeholder
1562 /// type -- an idealized representative of "types in general" that we
1563 /// use for checking generic functions.
1564 pub struct UniverseIndex {
1566 DEBUG_FORMAT = "U{}",
1570 impl UniverseIndex {
1571 pub const ROOT: UniverseIndex = UniverseIndex::from_u32(0);
1573 /// Returns the "next" universe index in order -- this new index
1574 /// is considered to extend all previous universes. This
1575 /// corresponds to entering a `forall` quantifier. So, for
1576 /// example, suppose we have this type in universe `U`:
1579 /// for<'a> fn(&'a u32)
1582 /// Once we "enter" into this `for<'a>` quantifier, we are in a
1583 /// new universe that extends `U` -- in this new universe, we can
1584 /// name the region `'a`, but that region was not nameable from
1585 /// `U` because it was not in scope there.
1586 pub fn next_universe(self) -> UniverseIndex {
1587 UniverseIndex::from_u32(self.private.checked_add(1).unwrap())
1590 /// Returns `true` if `self` can name a name from `other` -- in other words,
1591 /// if the set of names in `self` is a superset of those in
1592 /// `other` (`self >= other`).
1593 pub fn can_name(self, other: UniverseIndex) -> bool {
1594 self.private >= other.private
1597 /// Returns `true` if `self` cannot name some names from `other` -- in other
1598 /// words, if the set of names in `self` is a strict subset of
1599 /// those in `other` (`self < other`).
1600 pub fn cannot_name(self, other: UniverseIndex) -> bool {
1601 self.private < other.private
1605 /// The "placeholder index" fully defines a placeholder region.
1606 /// Placeholder regions are identified by both a **universe** as well
1607 /// as a "bound-region" within that universe. The `bound_region` is
1608 /// basically a name -- distinct bound regions within the same
1609 /// universe are just two regions with an unknown relationship to one
1611 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, PartialOrd, Ord)]
1612 pub struct Placeholder<T> {
1613 pub universe: UniverseIndex,
1617 impl<'a, T> HashStable<StableHashingContext<'a>> for Placeholder<T>
1619 T: HashStable<StableHashingContext<'a>>,
1621 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
1622 self.universe.hash_stable(hcx, hasher);
1623 self.name.hash_stable(hcx, hasher);
1627 pub type PlaceholderRegion = Placeholder<BoundRegion>;
1629 pub type PlaceholderType = Placeholder<BoundVar>;
1631 pub type PlaceholderConst = Placeholder<BoundVar>;
1633 /// A `DefId` which is potentially bundled with its corresponding generic parameter
1634 /// in case `did` is a const argument.
1636 /// This is used to prevent cycle errors during typeck
1637 /// as `type_of(const_arg)` depends on `typeck(owning_body)`
1638 /// which once again requires the type of its generic arguments.
1640 /// Luckily we only need to deal with const arguments once we
1641 /// know their corresponding parameters. We (ab)use this by
1642 /// calling `type_of(param_did)` for these arguments.
1645 /// #![feature(const_generics)]
1649 /// fn foo<const N: usize>(&self) -> usize { N }
1653 /// fn foo<const N: u8>(&self) -> usize { 42 }
1661 #[derive(Copy, Clone, Debug, TypeFoldable, Lift, RustcEncodable, RustcDecodable)]
1662 #[derive(PartialEq, Eq, PartialOrd, Ord)]
1663 #[derive(Hash, HashStable)]
1664 pub struct WithOptConstParam<T> {
1666 /// The `DefId` of the corresponding generic paramter in case `did` is
1667 /// a const argument.
1669 /// Note that even if `did` is a const argument, this may still be `None`.
1670 /// All queries taking `WithOptConstParam` start by calling `tcx.opt_const_param_of(def.did)`
1671 /// to potentially update `param_did` in case it `None`.
1672 pub const_param_did: Option<DefId>,
1675 impl<T> WithOptConstParam<T> {
1676 /// Creates a new `WithOptConstParam` setting `const_param_did` to `None`.
1678 pub fn unknown(did: T) -> WithOptConstParam<T> {
1679 WithOptConstParam { did, const_param_did: None }
1683 impl WithOptConstParam<LocalDefId> {
1684 /// Returns `Some((did, param_did))` if `def_id` is a const argument,
1685 /// `None` otherwise.
1687 pub fn try_lookup(did: LocalDefId, tcx: TyCtxt<'_>) -> Option<(LocalDefId, DefId)> {
1688 tcx.opt_const_param_of(did).map(|param_did| (did, param_did))
1691 /// In case `self` is unknown but `self.did` is a const argument, this returns
1692 /// a `WithOptConstParam` with the correct `const_param_did`.
1694 pub fn try_upgrade(self, tcx: TyCtxt<'_>) -> Option<WithOptConstParam<LocalDefId>> {
1695 if self.const_param_did.is_none() {
1696 if let const_param_did @ Some(_) = tcx.opt_const_param_of(self.did) {
1697 return Some(WithOptConstParam { did: self.did, const_param_did });
1704 pub fn to_global(self) -> WithOptConstParam<DefId> {
1705 WithOptConstParam { did: self.did.to_def_id(), const_param_did: self.const_param_did }
1708 pub fn def_id_for_type_of(self) -> DefId {
1709 if let Some(did) = self.const_param_did { did } else { self.did.to_def_id() }
1713 impl WithOptConstParam<DefId> {
1714 pub fn as_local(self) -> Option<WithOptConstParam<LocalDefId>> {
1717 .map(|did| WithOptConstParam { did, const_param_did: self.const_param_did })
1720 pub fn as_const_arg(self) -> Option<(LocalDefId, DefId)> {
1721 if let Some(param_did) = self.const_param_did {
1722 if let Some(did) = self.did.as_local() {
1723 return Some((did, param_did));
1730 pub fn expect_local(self) -> WithOptConstParam<LocalDefId> {
1731 self.as_local().unwrap()
1734 pub fn is_local(self) -> bool {
1738 pub fn def_id_for_type_of(self) -> DefId {
1739 self.const_param_did.unwrap_or(self.did)
1743 /// When type checking, we use the `ParamEnv` to track
1744 /// details about the set of where-clauses that are in scope at this
1745 /// particular point.
1746 #[derive(Copy, Clone)]
1747 pub struct ParamEnv<'tcx> {
1748 // We pack the caller_bounds List pointer and a Reveal enum into this usize.
1749 // Specifically, the low bit represents Reveal, with 0 meaning `UserFacing`
1750 // and 1 meaning `All`. The rest is the pointer.
1752 // This relies on the List<ty::Predicate<'tcx>> type having at least 2-byte
1753 // alignment. Lists start with a usize and are repr(C) so this should be
1754 // fine; there is a debug_assert in the constructor as well.
1756 // Note that the choice of 0 for UserFacing is intentional -- since it is the
1757 // first variant in Reveal this means that joining the pointer is a simple `or`.
1760 /// `Obligation`s that the caller must satisfy. This is basically
1761 /// the set of bounds on the in-scope type parameters, translated
1762 /// into `Obligation`s, and elaborated and normalized.
1764 /// Note: This is packed into the `packed_data` usize above, use the
1765 /// `caller_bounds()` method to access it.
1766 caller_bounds: PhantomData<&'tcx List<ty::Predicate<'tcx>>>,
1768 /// Typically, this is `Reveal::UserFacing`, but during codegen we
1769 /// want `Reveal::All`.
1771 /// Note: This is packed into the caller_bounds usize above, use the reveal()
1772 /// method to access it.
1773 reveal: PhantomData<traits::Reveal>,
1775 /// If this `ParamEnv` comes from a call to `tcx.param_env(def_id)`,
1776 /// register that `def_id` (useful for transitioning to the chalk trait
1778 pub def_id: Option<DefId>,
1781 impl<'tcx> fmt::Debug for ParamEnv<'tcx> {
1782 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1783 f.debug_struct("ParamEnv")
1784 .field("caller_bounds", &self.caller_bounds())
1785 .field("reveal", &self.reveal())
1786 .field("def_id", &self.def_id)
1791 impl<'tcx> Hash for ParamEnv<'tcx> {
1792 fn hash<H: Hasher>(&self, state: &mut H) {
1793 // List hashes as the raw pointer, so we can skip splitting into the
1794 // pointer and the enum.
1795 self.packed_data.hash(state);
1796 self.def_id.hash(state);
1800 impl<'tcx> PartialEq for ParamEnv<'tcx> {
1801 fn eq(&self, other: &Self) -> bool {
1802 self.caller_bounds() == other.caller_bounds()
1803 && self.reveal() == other.reveal()
1804 && self.def_id == other.def_id
1807 impl<'tcx> Eq for ParamEnv<'tcx> {}
1809 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for ParamEnv<'tcx> {
1810 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
1811 self.caller_bounds().hash_stable(hcx, hasher);
1812 self.reveal().hash_stable(hcx, hasher);
1813 self.def_id.hash_stable(hcx, hasher);
1817 impl<'tcx> TypeFoldable<'tcx> for ParamEnv<'tcx> {
1818 fn super_fold_with<F: ty::fold::TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
1820 self.caller_bounds().fold_with(folder),
1821 self.reveal().fold_with(folder),
1822 self.def_id.fold_with(folder),
1826 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1827 self.caller_bounds().visit_with(visitor)
1828 || self.reveal().visit_with(visitor)
1829 || self.def_id.visit_with(visitor)
1833 impl<'tcx> ParamEnv<'tcx> {
1834 /// Construct a trait environment suitable for contexts where
1835 /// there are no where-clauses in scope. Hidden types (like `impl
1836 /// Trait`) are left hidden, so this is suitable for ordinary
1839 pub fn empty() -> Self {
1840 Self::new(List::empty(), Reveal::UserFacing, None)
1844 pub fn caller_bounds(self) -> &'tcx List<ty::Predicate<'tcx>> {
1845 // mask out bottom bit
1846 unsafe { &*((self.packed_data & (!1)) as *const _) }
1850 pub fn reveal(self) -> traits::Reveal {
1851 if self.packed_data & 1 == 0 { traits::Reveal::UserFacing } else { traits::Reveal::All }
1854 /// Construct a trait environment with no where-clauses in scope
1855 /// where the values of all `impl Trait` and other hidden types
1856 /// are revealed. This is suitable for monomorphized, post-typeck
1857 /// environments like codegen or doing optimizations.
1859 /// N.B., if you want to have predicates in scope, use `ParamEnv::new`,
1860 /// or invoke `param_env.with_reveal_all()`.
1862 pub fn reveal_all() -> Self {
1863 Self::new(List::empty(), Reveal::All, None)
1866 /// Construct a trait environment with the given set of predicates.
1869 caller_bounds: &'tcx List<ty::Predicate<'tcx>>,
1871 def_id: Option<DefId>,
1873 let packed_data = caller_bounds as *const _ as usize;
1874 // Check that we can pack the reveal data into the pointer.
1875 debug_assert!(packed_data & 1 == 0);
1877 packed_data: packed_data
1879 Reveal::UserFacing => 0,
1882 caller_bounds: PhantomData,
1883 reveal: PhantomData,
1888 pub fn with_user_facing(mut self) -> Self {
1890 self.packed_data &= !1;
1894 /// Returns a new parameter environment with the same clauses, but
1895 /// which "reveals" the true results of projections in all cases
1896 /// (even for associated types that are specializable). This is
1897 /// the desired behavior during codegen and certain other special
1898 /// contexts; normally though we want to use `Reveal::UserFacing`,
1899 /// which is the default.
1900 pub fn with_reveal_all(mut self) -> Self {
1901 self.packed_data |= 1;
1905 /// Returns this same environment but with no caller bounds.
1906 pub fn without_caller_bounds(self) -> Self {
1907 Self::new(List::empty(), self.reveal(), self.def_id)
1910 /// Creates a suitable environment in which to perform trait
1911 /// queries on the given value. When type-checking, this is simply
1912 /// the pair of the environment plus value. But when reveal is set to
1913 /// All, then if `value` does not reference any type parameters, we will
1914 /// pair it with the empty environment. This improves caching and is generally
1917 /// N.B., we preserve the environment when type-checking because it
1918 /// is possible for the user to have wacky where-clauses like
1919 /// `where Box<u32>: Copy`, which are clearly never
1920 /// satisfiable. We generally want to behave as if they were true,
1921 /// although the surrounding function is never reachable.
1922 pub fn and<T: TypeFoldable<'tcx>>(self, value: T) -> ParamEnvAnd<'tcx, T> {
1923 match self.reveal() {
1924 Reveal::UserFacing => ParamEnvAnd { param_env: self, value },
1927 if value.is_global() {
1928 ParamEnvAnd { param_env: self.without_caller_bounds(), value }
1930 ParamEnvAnd { param_env: self, value }
1937 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1938 pub struct ConstnessAnd<T> {
1939 pub constness: Constness,
1943 // FIXME(ecstaticmorse): Audit all occurrences of `without_const().to_predicate(tcx)` to ensure that
1944 // the constness of trait bounds is being propagated correctly.
1945 pub trait WithConstness: Sized {
1947 fn with_constness(self, constness: Constness) -> ConstnessAnd<Self> {
1948 ConstnessAnd { constness, value: self }
1952 fn with_const(self) -> ConstnessAnd<Self> {
1953 self.with_constness(Constness::Const)
1957 fn without_const(self) -> ConstnessAnd<Self> {
1958 self.with_constness(Constness::NotConst)
1962 impl<T> WithConstness for T {}
1964 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TypeFoldable)]
1965 pub struct ParamEnvAnd<'tcx, T> {
1966 pub param_env: ParamEnv<'tcx>,
1970 impl<'tcx, T> ParamEnvAnd<'tcx, T> {
1971 pub fn into_parts(self) -> (ParamEnv<'tcx>, T) {
1972 (self.param_env, self.value)
1976 impl<'a, 'tcx, T> HashStable<StableHashingContext<'a>> for ParamEnvAnd<'tcx, T>
1978 T: HashStable<StableHashingContext<'a>>,
1980 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
1981 let ParamEnvAnd { ref param_env, ref value } = *self;
1983 param_env.hash_stable(hcx, hasher);
1984 value.hash_stable(hcx, hasher);
1988 #[derive(Copy, Clone, Debug, HashStable)]
1989 pub struct Destructor {
1990 /// The `DefId` of the destructor method
1995 #[derive(HashStable)]
1996 pub struct AdtFlags: u32 {
1997 const NO_ADT_FLAGS = 0;
1998 /// Indicates whether the ADT is an enum.
1999 const IS_ENUM = 1 << 0;
2000 /// Indicates whether the ADT is a union.
2001 const IS_UNION = 1 << 1;
2002 /// Indicates whether the ADT is a struct.
2003 const IS_STRUCT = 1 << 2;
2004 /// Indicates whether the ADT is a struct and has a constructor.
2005 const HAS_CTOR = 1 << 3;
2006 /// Indicates whether the type is `PhantomData`.
2007 const IS_PHANTOM_DATA = 1 << 4;
2008 /// Indicates whether the type has a `#[fundamental]` attribute.
2009 const IS_FUNDAMENTAL = 1 << 5;
2010 /// Indicates whether the type is `Box`.
2011 const IS_BOX = 1 << 6;
2012 /// Indicates whether the type is `ManuallyDrop`.
2013 const IS_MANUALLY_DROP = 1 << 7;
2014 /// Indicates whether the variant list of this ADT is `#[non_exhaustive]`.
2015 /// (i.e., this flag is never set unless this ADT is an enum).
2016 const IS_VARIANT_LIST_NON_EXHAUSTIVE = 1 << 8;
2021 #[derive(HashStable)]
2022 pub struct VariantFlags: u32 {
2023 const NO_VARIANT_FLAGS = 0;
2024 /// Indicates whether the field list of this variant is `#[non_exhaustive]`.
2025 const IS_FIELD_LIST_NON_EXHAUSTIVE = 1 << 0;
2029 /// Definition of a variant -- a struct's fields or a enum variant.
2030 #[derive(Debug, HashStable)]
2031 pub struct VariantDef {
2032 /// `DefId` that identifies the variant itself.
2033 /// If this variant belongs to a struct or union, then this is a copy of its `DefId`.
2035 /// `DefId` that identifies the variant's constructor.
2036 /// If this variant is a struct variant, then this is `None`.
2037 pub ctor_def_id: Option<DefId>,
2038 /// Variant or struct name.
2039 #[stable_hasher(project(name))]
2041 /// Discriminant of this variant.
2042 pub discr: VariantDiscr,
2043 /// Fields of this variant.
2044 pub fields: Vec<FieldDef>,
2045 /// Type of constructor of variant.
2046 pub ctor_kind: CtorKind,
2047 /// Flags of the variant (e.g. is field list non-exhaustive)?
2048 flags: VariantFlags,
2049 /// Variant is obtained as part of recovering from a syntactic error.
2050 /// May be incomplete or bogus.
2051 pub recovered: bool,
2054 impl<'tcx> VariantDef {
2055 /// Creates a new `VariantDef`.
2057 /// `variant_did` is the `DefId` that identifies the enum variant (if this `VariantDef`
2058 /// represents an enum variant).
2060 /// `ctor_did` is the `DefId` that identifies the constructor of unit or
2061 /// tuple-variants/structs. If this is a `struct`-variant then this should be `None`.
2063 /// `parent_did` is the `DefId` of the `AdtDef` representing the enum or struct that
2064 /// owns this variant. It is used for checking if a struct has `#[non_exhaustive]` w/out having
2065 /// to go through the redirect of checking the ctor's attributes - but compiling a small crate
2066 /// requires loading the `AdtDef`s for all the structs in the universe (e.g., coherence for any
2067 /// built-in trait), and we do not want to load attributes twice.
2069 /// If someone speeds up attribute loading to not be a performance concern, they can
2070 /// remove this hack and use the constructor `DefId` everywhere.
2074 variant_did: Option<DefId>,
2075 ctor_def_id: Option<DefId>,
2076 discr: VariantDiscr,
2077 fields: Vec<FieldDef>,
2078 ctor_kind: CtorKind,
2084 "VariantDef::new(ident = {:?}, variant_did = {:?}, ctor_def_id = {:?}, discr = {:?},
2085 fields = {:?}, ctor_kind = {:?}, adt_kind = {:?}, parent_did = {:?})",
2086 ident, variant_did, ctor_def_id, discr, fields, ctor_kind, adt_kind, parent_did,
2089 let mut flags = VariantFlags::NO_VARIANT_FLAGS;
2090 if adt_kind == AdtKind::Struct && tcx.has_attr(parent_did, sym::non_exhaustive) {
2091 debug!("found non-exhaustive field list for {:?}", parent_did);
2092 flags = flags | VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE;
2093 } else if let Some(variant_did) = variant_did {
2094 if tcx.has_attr(variant_did, sym::non_exhaustive) {
2095 debug!("found non-exhaustive field list for {:?}", variant_did);
2096 flags = flags | VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE;
2101 def_id: variant_did.unwrap_or(parent_did),
2112 /// Is this field list non-exhaustive?
2114 pub fn is_field_list_non_exhaustive(&self) -> bool {
2115 self.flags.intersects(VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE)
2118 /// `repr(transparent)` structs can have a single non-ZST field, this function returns that
2120 pub fn transparent_newtype_field(&self, tcx: TyCtxt<'tcx>) -> Option<&FieldDef> {
2121 for field in &self.fields {
2122 let field_ty = field.ty(tcx, InternalSubsts::identity_for_item(tcx, self.def_id));
2123 if !field_ty.is_zst(tcx, self.def_id) {
2132 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2133 pub enum VariantDiscr {
2134 /// Explicit value for this variant, i.e., `X = 123`.
2135 /// The `DefId` corresponds to the embedded constant.
2138 /// The previous variant's discriminant plus one.
2139 /// For efficiency reasons, the distance from the
2140 /// last `Explicit` discriminant is being stored,
2141 /// or `0` for the first variant, if it has none.
2145 #[derive(Debug, HashStable)]
2146 pub struct FieldDef {
2148 #[stable_hasher(project(name))]
2150 pub vis: Visibility,
2153 /// The definition of a user-defined type, e.g., a `struct`, `enum`, or `union`.
2155 /// These are all interned (by `alloc_adt_def`) into the global arena.
2157 /// The initialism *ADT* stands for an [*algebraic data type (ADT)*][adt].
2158 /// This is slightly wrong because `union`s are not ADTs.
2159 /// Moreover, Rust only allows recursive data types through indirection.
2161 /// [adt]: https://en.wikipedia.org/wiki/Algebraic_data_type
2163 /// The `DefId` of the struct, enum or union item.
2165 /// Variants of the ADT. If this is a struct or union, then there will be a single variant.
2166 pub variants: IndexVec<VariantIdx, VariantDef>,
2167 /// Flags of the ADT (e.g., is this a struct? is this non-exhaustive?).
2169 /// Repr options provided by the user.
2170 pub repr: ReprOptions,
2173 impl PartialOrd for AdtDef {
2174 fn partial_cmp(&self, other: &AdtDef) -> Option<Ordering> {
2175 Some(self.cmp(&other))
2179 /// There should be only one AdtDef for each `did`, therefore
2180 /// it is fine to implement `Ord` only based on `did`.
2181 impl Ord for AdtDef {
2182 fn cmp(&self, other: &AdtDef) -> Ordering {
2183 self.did.cmp(&other.did)
2187 impl PartialEq for AdtDef {
2188 // `AdtDef`s are always interned, and this is part of `TyS` equality.
2190 fn eq(&self, other: &Self) -> bool {
2191 ptr::eq(self, other)
2195 impl Eq for AdtDef {}
2197 impl Hash for AdtDef {
2199 fn hash<H: Hasher>(&self, s: &mut H) {
2200 (self as *const AdtDef).hash(s)
2204 impl<'tcx> rustc_serialize::UseSpecializedEncodable for &'tcx AdtDef {
2205 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
2210 impl<'tcx> rustc_serialize::UseSpecializedDecodable for &'tcx AdtDef {}
2212 impl<'a> HashStable<StableHashingContext<'a>> for AdtDef {
2213 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
2215 static CACHE: RefCell<FxHashMap<usize, Fingerprint>> = Default::default();
2218 let hash: Fingerprint = CACHE.with(|cache| {
2219 let addr = self as *const AdtDef as usize;
2220 *cache.borrow_mut().entry(addr).or_insert_with(|| {
2221 let ty::AdtDef { did, ref variants, ref flags, ref repr } = *self;
2223 let mut hasher = StableHasher::new();
2224 did.hash_stable(hcx, &mut hasher);
2225 variants.hash_stable(hcx, &mut hasher);
2226 flags.hash_stable(hcx, &mut hasher);
2227 repr.hash_stable(hcx, &mut hasher);
2233 hash.hash_stable(hcx, hasher);
2237 #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
2244 impl Into<DataTypeKind> for AdtKind {
2245 fn into(self) -> DataTypeKind {
2247 AdtKind::Struct => DataTypeKind::Struct,
2248 AdtKind::Union => DataTypeKind::Union,
2249 AdtKind::Enum => DataTypeKind::Enum,
2255 #[derive(RustcEncodable, RustcDecodable, Default, HashStable)]
2256 pub struct ReprFlags: u8 {
2257 const IS_C = 1 << 0;
2258 const IS_SIMD = 1 << 1;
2259 const IS_TRANSPARENT = 1 << 2;
2260 // Internal only for now. If true, don't reorder fields.
2261 const IS_LINEAR = 1 << 3;
2262 // If true, don't expose any niche to type's context.
2263 const HIDE_NICHE = 1 << 4;
2264 // Any of these flags being set prevent field reordering optimisation.
2265 const IS_UNOPTIMISABLE = ReprFlags::IS_C.bits |
2266 ReprFlags::IS_SIMD.bits |
2267 ReprFlags::IS_LINEAR.bits;
2271 /// Represents the repr options provided by the user,
2272 #[derive(Copy, Clone, Debug, Eq, PartialEq, RustcEncodable, RustcDecodable, Default, HashStable)]
2273 pub struct ReprOptions {
2274 pub int: Option<attr::IntType>,
2275 pub align: Option<Align>,
2276 pub pack: Option<Align>,
2277 pub flags: ReprFlags,
2281 pub fn new(tcx: TyCtxt<'_>, did: DefId) -> ReprOptions {
2282 let mut flags = ReprFlags::empty();
2283 let mut size = None;
2284 let mut max_align: Option<Align> = None;
2285 let mut min_pack: Option<Align> = None;
2286 for attr in tcx.get_attrs(did).iter() {
2287 for r in attr::find_repr_attrs(&tcx.sess.parse_sess, attr) {
2288 flags.insert(match r {
2289 attr::ReprC => ReprFlags::IS_C,
2290 attr::ReprPacked(pack) => {
2291 let pack = Align::from_bytes(pack as u64).unwrap();
2292 min_pack = Some(if let Some(min_pack) = min_pack {
2299 attr::ReprTransparent => ReprFlags::IS_TRANSPARENT,
2300 attr::ReprNoNiche => ReprFlags::HIDE_NICHE,
2301 attr::ReprSimd => ReprFlags::IS_SIMD,
2302 attr::ReprInt(i) => {
2306 attr::ReprAlign(align) => {
2307 max_align = max_align.max(Some(Align::from_bytes(align as u64).unwrap()));
2314 // This is here instead of layout because the choice must make it into metadata.
2315 if !tcx.consider_optimizing(|| format!("Reorder fields of {:?}", tcx.def_path_str(did))) {
2316 flags.insert(ReprFlags::IS_LINEAR);
2318 ReprOptions { int: size, align: max_align, pack: min_pack, flags }
2322 pub fn simd(&self) -> bool {
2323 self.flags.contains(ReprFlags::IS_SIMD)
2326 pub fn c(&self) -> bool {
2327 self.flags.contains(ReprFlags::IS_C)
2330 pub fn packed(&self) -> bool {
2334 pub fn transparent(&self) -> bool {
2335 self.flags.contains(ReprFlags::IS_TRANSPARENT)
2338 pub fn linear(&self) -> bool {
2339 self.flags.contains(ReprFlags::IS_LINEAR)
2342 pub fn hide_niche(&self) -> bool {
2343 self.flags.contains(ReprFlags::HIDE_NICHE)
2346 /// Returns the discriminant type, given these `repr` options.
2347 /// This must only be called on enums!
2348 pub fn discr_type(&self) -> attr::IntType {
2349 self.int.unwrap_or(attr::SignedInt(ast::IntTy::Isize))
2352 /// Returns `true` if this `#[repr()]` should inhabit "smart enum
2353 /// layout" optimizations, such as representing `Foo<&T>` as a
2355 pub fn inhibit_enum_layout_opt(&self) -> bool {
2356 self.c() || self.int.is_some()
2359 /// Returns `true` if this `#[repr()]` should inhibit struct field reordering
2360 /// optimizations, such as with `repr(C)`, `repr(packed(1))`, or `repr(<int>)`.
2361 pub fn inhibit_struct_field_reordering_opt(&self) -> bool {
2362 if let Some(pack) = self.pack {
2363 if pack.bytes() == 1 {
2367 self.flags.intersects(ReprFlags::IS_UNOPTIMISABLE) || self.int.is_some()
2370 /// Returns `true` if this `#[repr()]` should inhibit union ABI optimisations.
2371 pub fn inhibit_union_abi_opt(&self) -> bool {
2377 /// Creates a new `AdtDef`.
2382 variants: IndexVec<VariantIdx, VariantDef>,
2385 debug!("AdtDef::new({:?}, {:?}, {:?}, {:?})", did, kind, variants, repr);
2386 let mut flags = AdtFlags::NO_ADT_FLAGS;
2388 if kind == AdtKind::Enum && tcx.has_attr(did, sym::non_exhaustive) {
2389 debug!("found non-exhaustive variant list for {:?}", did);
2390 flags = flags | AdtFlags::IS_VARIANT_LIST_NON_EXHAUSTIVE;
2393 flags |= match kind {
2394 AdtKind::Enum => AdtFlags::IS_ENUM,
2395 AdtKind::Union => AdtFlags::IS_UNION,
2396 AdtKind::Struct => AdtFlags::IS_STRUCT,
2399 if kind == AdtKind::Struct && variants[VariantIdx::new(0)].ctor_def_id.is_some() {
2400 flags |= AdtFlags::HAS_CTOR;
2403 let attrs = tcx.get_attrs(did);
2404 if attr::contains_name(&attrs, sym::fundamental) {
2405 flags |= AdtFlags::IS_FUNDAMENTAL;
2407 if Some(did) == tcx.lang_items().phantom_data() {
2408 flags |= AdtFlags::IS_PHANTOM_DATA;
2410 if Some(did) == tcx.lang_items().owned_box() {
2411 flags |= AdtFlags::IS_BOX;
2413 if Some(did) == tcx.lang_items().manually_drop() {
2414 flags |= AdtFlags::IS_MANUALLY_DROP;
2417 AdtDef { did, variants, flags, repr }
2420 /// Returns `true` if this is a struct.
2422 pub fn is_struct(&self) -> bool {
2423 self.flags.contains(AdtFlags::IS_STRUCT)
2426 /// Returns `true` if this is a union.
2428 pub fn is_union(&self) -> bool {
2429 self.flags.contains(AdtFlags::IS_UNION)
2432 /// Returns `true` if this is a enum.
2434 pub fn is_enum(&self) -> bool {
2435 self.flags.contains(AdtFlags::IS_ENUM)
2438 /// Returns `true` if the variant list of this ADT is `#[non_exhaustive]`.
2440 pub fn is_variant_list_non_exhaustive(&self) -> bool {
2441 self.flags.contains(AdtFlags::IS_VARIANT_LIST_NON_EXHAUSTIVE)
2444 /// Returns the kind of the ADT.
2446 pub fn adt_kind(&self) -> AdtKind {
2449 } else if self.is_union() {
2456 /// Returns a description of this abstract data type.
2457 pub fn descr(&self) -> &'static str {
2458 match self.adt_kind() {
2459 AdtKind::Struct => "struct",
2460 AdtKind::Union => "union",
2461 AdtKind::Enum => "enum",
2465 /// Returns a description of a variant of this abstract data type.
2467 pub fn variant_descr(&self) -> &'static str {
2468 match self.adt_kind() {
2469 AdtKind::Struct => "struct",
2470 AdtKind::Union => "union",
2471 AdtKind::Enum => "variant",
2475 /// If this function returns `true`, it implies that `is_struct` must return `true`.
2477 pub fn has_ctor(&self) -> bool {
2478 self.flags.contains(AdtFlags::HAS_CTOR)
2481 /// Returns `true` if this type is `#[fundamental]` for the purposes
2482 /// of coherence checking.
2484 pub fn is_fundamental(&self) -> bool {
2485 self.flags.contains(AdtFlags::IS_FUNDAMENTAL)
2488 /// Returns `true` if this is `PhantomData<T>`.
2490 pub fn is_phantom_data(&self) -> bool {
2491 self.flags.contains(AdtFlags::IS_PHANTOM_DATA)
2494 /// Returns `true` if this is Box<T>.
2496 pub fn is_box(&self) -> bool {
2497 self.flags.contains(AdtFlags::IS_BOX)
2500 /// Returns `true` if this is `ManuallyDrop<T>`.
2502 pub fn is_manually_drop(&self) -> bool {
2503 self.flags.contains(AdtFlags::IS_MANUALLY_DROP)
2506 /// Returns `true` if this type has a destructor.
2507 pub fn has_dtor(&self, tcx: TyCtxt<'tcx>) -> bool {
2508 self.destructor(tcx).is_some()
2511 /// Asserts this is a struct or union and returns its unique variant.
2512 pub fn non_enum_variant(&self) -> &VariantDef {
2513 assert!(self.is_struct() || self.is_union());
2514 &self.variants[VariantIdx::new(0)]
2518 pub fn predicates(&self, tcx: TyCtxt<'tcx>) -> GenericPredicates<'tcx> {
2519 tcx.predicates_of(self.did)
2522 /// Returns an iterator over all fields contained
2525 pub fn all_fields(&self) -> impl Iterator<Item = &FieldDef> + Clone {
2526 self.variants.iter().flat_map(|v| v.fields.iter())
2529 pub fn is_payloadfree(&self) -> bool {
2530 !self.variants.is_empty() && self.variants.iter().all(|v| v.fields.is_empty())
2533 /// Return a `VariantDef` given a variant id.
2534 pub fn variant_with_id(&self, vid: DefId) -> &VariantDef {
2535 self.variants.iter().find(|v| v.def_id == vid).expect("variant_with_id: unknown variant")
2538 /// Return a `VariantDef` given a constructor id.
2539 pub fn variant_with_ctor_id(&self, cid: DefId) -> &VariantDef {
2542 .find(|v| v.ctor_def_id == Some(cid))
2543 .expect("variant_with_ctor_id: unknown variant")
2546 /// Return the index of `VariantDef` given a variant id.
2547 pub fn variant_index_with_id(&self, vid: DefId) -> VariantIdx {
2550 .find(|(_, v)| v.def_id == vid)
2551 .expect("variant_index_with_id: unknown variant")
2555 /// Return the index of `VariantDef` given a constructor id.
2556 pub fn variant_index_with_ctor_id(&self, cid: DefId) -> VariantIdx {
2559 .find(|(_, v)| v.ctor_def_id == Some(cid))
2560 .expect("variant_index_with_ctor_id: unknown variant")
2564 pub fn variant_of_res(&self, res: Res) -> &VariantDef {
2566 Res::Def(DefKind::Variant, vid) => self.variant_with_id(vid),
2567 Res::Def(DefKind::Ctor(..), cid) => self.variant_with_ctor_id(cid),
2568 Res::Def(DefKind::Struct, _)
2569 | Res::Def(DefKind::Union, _)
2570 | Res::Def(DefKind::TyAlias, _)
2571 | Res::Def(DefKind::AssocTy, _)
2573 | Res::SelfCtor(..) => self.non_enum_variant(),
2574 _ => bug!("unexpected res {:?} in variant_of_res", res),
2579 pub fn eval_explicit_discr(&self, tcx: TyCtxt<'tcx>, expr_did: DefId) -> Option<Discr<'tcx>> {
2580 assert!(self.is_enum());
2581 let param_env = tcx.param_env(expr_did);
2582 let repr_type = self.repr.discr_type();
2583 match tcx.const_eval_poly(expr_did) {
2585 let ty = repr_type.to_ty(tcx);
2586 if let Some(b) = val.try_to_bits_for_ty(tcx, param_env, ty) {
2587 trace!("discriminants: {} ({:?})", b, repr_type);
2588 Some(Discr { val: b, ty })
2590 info!("invalid enum discriminant: {:#?}", val);
2591 crate::mir::interpret::struct_error(
2592 tcx.at(tcx.def_span(expr_did)),
2593 "constant evaluation of enum discriminant resulted in non-integer",
2600 let msg = match err {
2601 ErrorHandled::Reported(ErrorReported) | ErrorHandled::Linted => {
2602 "enum discriminant evaluation failed"
2604 ErrorHandled::TooGeneric => "enum discriminant depends on generics",
2606 tcx.sess.delay_span_bug(tcx.def_span(expr_did), msg);
2613 pub fn discriminants(
2616 ) -> impl Iterator<Item = (VariantIdx, Discr<'tcx>)> + Captures<'tcx> {
2617 assert!(self.is_enum());
2618 let repr_type = self.repr.discr_type();
2619 let initial = repr_type.initial_discriminant(tcx);
2620 let mut prev_discr = None::<Discr<'tcx>>;
2621 self.variants.iter_enumerated().map(move |(i, v)| {
2622 let mut discr = prev_discr.map_or(initial, |d| d.wrap_incr(tcx));
2623 if let VariantDiscr::Explicit(expr_did) = v.discr {
2624 if let Some(new_discr) = self.eval_explicit_discr(tcx, expr_did) {
2628 prev_discr = Some(discr);
2635 pub fn variant_range(&self) -> Range<VariantIdx> {
2636 VariantIdx::new(0)..VariantIdx::new(self.variants.len())
2639 /// Computes the discriminant value used by a specific variant.
2640 /// Unlike `discriminants`, this is (amortized) constant-time,
2641 /// only doing at most one query for evaluating an explicit
2642 /// discriminant (the last one before the requested variant),
2643 /// assuming there are no constant-evaluation errors there.
2645 pub fn discriminant_for_variant(
2648 variant_index: VariantIdx,
2650 assert!(self.is_enum());
2651 let (val, offset) = self.discriminant_def_for_variant(variant_index);
2652 let explicit_value = val
2653 .and_then(|expr_did| self.eval_explicit_discr(tcx, expr_did))
2654 .unwrap_or_else(|| self.repr.discr_type().initial_discriminant(tcx));
2655 explicit_value.checked_add(tcx, offset as u128).0
2658 /// Yields a `DefId` for the discriminant and an offset to add to it
2659 /// Alternatively, if there is no explicit discriminant, returns the
2660 /// inferred discriminant directly.
2661 pub fn discriminant_def_for_variant(&self, variant_index: VariantIdx) -> (Option<DefId>, u32) {
2662 assert!(!self.variants.is_empty());
2663 let mut explicit_index = variant_index.as_u32();
2666 match self.variants[VariantIdx::from_u32(explicit_index)].discr {
2667 ty::VariantDiscr::Relative(0) => {
2671 ty::VariantDiscr::Relative(distance) => {
2672 explicit_index -= distance;
2674 ty::VariantDiscr::Explicit(did) => {
2675 expr_did = Some(did);
2680 (expr_did, variant_index.as_u32() - explicit_index)
2683 pub fn destructor(&self, tcx: TyCtxt<'tcx>) -> Option<Destructor> {
2684 tcx.adt_destructor(self.did)
2687 /// Returns a list of types such that `Self: Sized` if and only
2688 /// if that type is `Sized`, or `TyErr` if this type is recursive.
2690 /// Oddly enough, checking that the sized-constraint is `Sized` is
2691 /// actually more expressive than checking all members:
2692 /// the `Sized` trait is inductive, so an associated type that references
2693 /// `Self` would prevent its containing ADT from being `Sized`.
2695 /// Due to normalization being eager, this applies even if
2696 /// the associated type is behind a pointer (e.g., issue #31299).
2697 pub fn sized_constraint(&self, tcx: TyCtxt<'tcx>) -> &'tcx [Ty<'tcx>] {
2698 tcx.adt_sized_constraint(self.did).0
2702 impl<'tcx> FieldDef {
2703 /// Returns the type of this field. The `subst` is typically obtained
2704 /// via the second field of `TyKind::AdtDef`.
2705 pub fn ty(&self, tcx: TyCtxt<'tcx>, subst: SubstsRef<'tcx>) -> Ty<'tcx> {
2706 tcx.type_of(self.did).subst(tcx, subst)
2710 /// Represents the various closure traits in the language. This
2711 /// will determine the type of the environment (`self`, in the
2712 /// desugaring) argument that the closure expects.
2714 /// You can get the environment type of a closure using
2715 /// `tcx.closure_env_ty()`.
2716 #[derive(Clone, Copy, PartialOrd, Ord, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
2717 #[derive(HashStable)]
2718 pub enum ClosureKind {
2719 // Warning: Ordering is significant here! The ordering is chosen
2720 // because the trait Fn is a subtrait of FnMut and so in turn, and
2721 // hence we order it so that Fn < FnMut < FnOnce.
2727 impl<'tcx> ClosureKind {
2728 // This is the initial value used when doing upvar inference.
2729 pub const LATTICE_BOTTOM: ClosureKind = ClosureKind::Fn;
2731 pub fn trait_did(&self, tcx: TyCtxt<'tcx>) -> DefId {
2733 ClosureKind::Fn => tcx.require_lang_item(FnTraitLangItem, None),
2734 ClosureKind::FnMut => tcx.require_lang_item(FnMutTraitLangItem, None),
2735 ClosureKind::FnOnce => tcx.require_lang_item(FnOnceTraitLangItem, None),
2739 /// Returns `true` if this a type that impls this closure kind
2740 /// must also implement `other`.
2741 pub fn extends(self, other: ty::ClosureKind) -> bool {
2742 match (self, other) {
2743 (ClosureKind::Fn, ClosureKind::Fn) => true,
2744 (ClosureKind::Fn, ClosureKind::FnMut) => true,
2745 (ClosureKind::Fn, ClosureKind::FnOnce) => true,
2746 (ClosureKind::FnMut, ClosureKind::FnMut) => true,
2747 (ClosureKind::FnMut, ClosureKind::FnOnce) => true,
2748 (ClosureKind::FnOnce, ClosureKind::FnOnce) => true,
2753 /// Returns the representative scalar type for this closure kind.
2754 /// See `TyS::to_opt_closure_kind` for more details.
2755 pub fn to_ty(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
2757 ty::ClosureKind::Fn => tcx.types.i8,
2758 ty::ClosureKind::FnMut => tcx.types.i16,
2759 ty::ClosureKind::FnOnce => tcx.types.i32,
2765 pub fn from_mutbl(m: hir::Mutability) -> BorrowKind {
2767 hir::Mutability::Mut => MutBorrow,
2768 hir::Mutability::Not => ImmBorrow,
2772 /// Returns a mutability `m` such that an `&m T` pointer could be used to obtain this borrow
2773 /// kind. Because borrow kinds are richer than mutabilities, we sometimes have to pick a
2774 /// mutability that is stronger than necessary so that it at least *would permit* the borrow in
2776 pub fn to_mutbl_lossy(self) -> hir::Mutability {
2778 MutBorrow => hir::Mutability::Mut,
2779 ImmBorrow => hir::Mutability::Not,
2781 // We have no type corresponding to a unique imm borrow, so
2782 // use `&mut`. It gives all the capabilities of an `&uniq`
2783 // and hence is a safe "over approximation".
2784 UniqueImmBorrow => hir::Mutability::Mut,
2788 pub fn to_user_str(&self) -> &'static str {
2790 MutBorrow => "mutable",
2791 ImmBorrow => "immutable",
2792 UniqueImmBorrow => "uniquely immutable",
2797 pub type Attributes<'tcx> = &'tcx [ast::Attribute];
2799 #[derive(Debug, PartialEq, Eq)]
2800 pub enum ImplOverlapKind {
2801 /// These impls are always allowed to overlap.
2803 /// Whether or not the impl is permitted due to the trait being a `#[marker]` trait
2806 /// These impls are allowed to overlap, but that raises
2807 /// an issue #33140 future-compatibility warning.
2809 /// Some background: in Rust 1.0, the trait-object types `Send + Sync` (today's
2810 /// `dyn Send + Sync`) and `Sync + Send` (now `dyn Sync + Send`) were different.
2812 /// The widely-used version 0.1.0 of the crate `traitobject` had accidentally relied
2813 /// that difference, making what reduces to the following set of impls:
2817 /// impl Trait for dyn Send + Sync {}
2818 /// impl Trait for dyn Sync + Send {}
2821 /// Obviously, once we made these types be identical, that code causes a coherence
2822 /// error and a fairly big headache for us. However, luckily for us, the trait
2823 /// `Trait` used in this case is basically a marker trait, and therefore having
2824 /// overlapping impls for it is sound.
2826 /// To handle this, we basically regard the trait as a marker trait, with an additional
2827 /// future-compatibility warning. To avoid accidentally "stabilizing" this feature,
2828 /// it has the following restrictions:
2830 /// 1. The trait must indeed be a marker-like trait (i.e., no items), and must be
2832 /// 2. The trait-ref of both impls must be equal.
2833 /// 3. The trait-ref of both impls must be a trait object type consisting only of
2835 /// 4. Neither of the impls can have any where-clauses.
2837 /// Once `traitobject` 0.1.0 is no longer an active concern, this hack can be removed.
2841 impl<'tcx> TyCtxt<'tcx> {
2842 pub fn typeck_body(self, body: hir::BodyId) -> &'tcx TypeckResults<'tcx> {
2843 self.typeck(self.hir().body_owner_def_id(body))
2846 /// Returns an iterator of the `DefId`s for all body-owners in this
2847 /// crate. If you would prefer to iterate over the bodies
2848 /// themselves, you can do `self.hir().krate().body_ids.iter()`.
2849 pub fn body_owners(self) -> impl Iterator<Item = LocalDefId> + Captures<'tcx> + 'tcx {
2854 .map(move |&body_id| self.hir().body_owner_def_id(body_id))
2857 pub fn par_body_owners<F: Fn(LocalDefId) + sync::Sync + sync::Send>(self, f: F) {
2858 par_iter(&self.hir().krate().body_ids)
2859 .for_each(|&body_id| f(self.hir().body_owner_def_id(body_id)));
2862 pub fn provided_trait_methods(self, id: DefId) -> impl 'tcx + Iterator<Item = &'tcx AssocItem> {
2863 self.associated_items(id)
2864 .in_definition_order()
2865 .filter(|item| item.kind == AssocKind::Fn && item.defaultness.has_value())
2868 pub fn opt_item_name(self, def_id: DefId) -> Option<Ident> {
2871 .and_then(|def_id| self.hir().get(self.hir().as_local_hir_id(def_id)).ident())
2874 pub fn opt_associated_item(self, def_id: DefId) -> Option<&'tcx AssocItem> {
2875 let is_associated_item = if let Some(def_id) = def_id.as_local() {
2876 match self.hir().get(self.hir().as_local_hir_id(def_id)) {
2877 Node::TraitItem(_) | Node::ImplItem(_) => true,
2881 match self.def_kind(def_id) {
2882 DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy => true,
2887 is_associated_item.then(|| self.associated_item(def_id))
2890 pub fn field_index(self, hir_id: hir::HirId, typeck_results: &TypeckResults<'_>) -> usize {
2891 typeck_results.field_indices().get(hir_id).cloned().expect("no index for a field")
2894 pub fn find_field_index(self, ident: Ident, variant: &VariantDef) -> Option<usize> {
2895 variant.fields.iter().position(|field| self.hygienic_eq(ident, field.ident, variant.def_id))
2898 /// Returns `true` if the impls are the same polarity and the trait either
2899 /// has no items or is annotated `#[marker]` and prevents item overrides.
2900 pub fn impls_are_allowed_to_overlap(
2904 ) -> Option<ImplOverlapKind> {
2905 // If either trait impl references an error, they're allowed to overlap,
2906 // as one of them essentially doesn't exist.
2907 if self.impl_trait_ref(def_id1).map_or(false, |tr| tr.references_error())
2908 || self.impl_trait_ref(def_id2).map_or(false, |tr| tr.references_error())
2910 return Some(ImplOverlapKind::Permitted { marker: false });
2913 match (self.impl_polarity(def_id1), self.impl_polarity(def_id2)) {
2914 (ImplPolarity::Reservation, _) | (_, ImplPolarity::Reservation) => {
2915 // `#[rustc_reservation_impl]` impls don't overlap with anything
2917 "impls_are_allowed_to_overlap({:?}, {:?}) = Some(Permitted) (reservations)",
2920 return Some(ImplOverlapKind::Permitted { marker: false });
2922 (ImplPolarity::Positive, ImplPolarity::Negative)
2923 | (ImplPolarity::Negative, ImplPolarity::Positive) => {
2924 // `impl AutoTrait for Type` + `impl !AutoTrait for Type`
2926 "impls_are_allowed_to_overlap({:?}, {:?}) - None (differing polarities)",
2931 (ImplPolarity::Positive, ImplPolarity::Positive)
2932 | (ImplPolarity::Negative, ImplPolarity::Negative) => {}
2935 let is_marker_overlap = {
2936 let is_marker_impl = |def_id: DefId| -> bool {
2937 let trait_ref = self.impl_trait_ref(def_id);
2938 trait_ref.map_or(false, |tr| self.trait_def(tr.def_id).is_marker)
2940 is_marker_impl(def_id1) && is_marker_impl(def_id2)
2943 if is_marker_overlap {
2945 "impls_are_allowed_to_overlap({:?}, {:?}) = Some(Permitted) (marker overlap)",
2948 Some(ImplOverlapKind::Permitted { marker: true })
2950 if let Some(self_ty1) = self.issue33140_self_ty(def_id1) {
2951 if let Some(self_ty2) = self.issue33140_self_ty(def_id2) {
2952 if self_ty1 == self_ty2 {
2954 "impls_are_allowed_to_overlap({:?}, {:?}) - issue #33140 HACK",
2957 return Some(ImplOverlapKind::Issue33140);
2960 "impls_are_allowed_to_overlap({:?}, {:?}) - found {:?} != {:?}",
2961 def_id1, def_id2, self_ty1, self_ty2
2967 debug!("impls_are_allowed_to_overlap({:?}, {:?}) = None", def_id1, def_id2);
2972 /// Returns `ty::VariantDef` if `res` refers to a struct,
2973 /// or variant or their constructors, panics otherwise.
2974 pub fn expect_variant_res(self, res: Res) -> &'tcx VariantDef {
2976 Res::Def(DefKind::Variant, did) => {
2977 let enum_did = self.parent(did).unwrap();
2978 self.adt_def(enum_did).variant_with_id(did)
2980 Res::Def(DefKind::Struct | DefKind::Union, did) => self.adt_def(did).non_enum_variant(),
2981 Res::Def(DefKind::Ctor(CtorOf::Variant, ..), variant_ctor_did) => {
2982 let variant_did = self.parent(variant_ctor_did).unwrap();
2983 let enum_did = self.parent(variant_did).unwrap();
2984 self.adt_def(enum_did).variant_with_ctor_id(variant_ctor_did)
2986 Res::Def(DefKind::Ctor(CtorOf::Struct, ..), ctor_did) => {
2987 let struct_did = self.parent(ctor_did).expect("struct ctor has no parent");
2988 self.adt_def(struct_did).non_enum_variant()
2990 _ => bug!("expect_variant_res used with unexpected res {:?}", res),
2994 pub fn item_name(self, id: DefId) -> Symbol {
2995 if id.index == CRATE_DEF_INDEX {
2996 self.original_crate_name(id.krate)
2998 let def_key = self.def_key(id);
2999 match def_key.disambiguated_data.data {
3000 // The name of a constructor is that of its parent.
3001 rustc_hir::definitions::DefPathData::Ctor => {
3002 self.item_name(DefId { krate: id.krate, index: def_key.parent.unwrap() })
3004 _ => def_key.disambiguated_data.data.get_opt_name().unwrap_or_else(|| {
3005 bug!("item_name: no name for {:?}", self.def_path(id));
3011 /// Returns the possibly-auto-generated MIR of a `(DefId, Subst)` pair.
3012 pub fn instance_mir(self, instance: ty::InstanceDef<'tcx>) -> &'tcx Body<'tcx> {
3014 ty::InstanceDef::Item(def) => {
3015 if let Some((did, param_did)) = def.as_const_arg() {
3016 self.optimized_mir_of_const_arg((did, param_did))
3018 self.optimized_mir(def.did)
3021 ty::InstanceDef::VtableShim(..)
3022 | ty::InstanceDef::ReifyShim(..)
3023 | ty::InstanceDef::Intrinsic(..)
3024 | ty::InstanceDef::FnPtrShim(..)
3025 | ty::InstanceDef::Virtual(..)
3026 | ty::InstanceDef::ClosureOnceShim { .. }
3027 | ty::InstanceDef::DropGlue(..)
3028 | ty::InstanceDef::CloneShim(..) => self.mir_shims(instance),
3032 /// Gets the attributes of a definition.
3033 pub fn get_attrs(self, did: DefId) -> Attributes<'tcx> {
3034 if let Some(did) = did.as_local() {
3035 self.hir().attrs(self.hir().as_local_hir_id(did))
3037 self.item_attrs(did)
3041 /// Determines whether an item is annotated with an attribute.
3042 pub fn has_attr(self, did: DefId, attr: Symbol) -> bool {
3043 attr::contains_name(&self.get_attrs(did), attr)
3046 /// Returns `true` if this is an `auto trait`.
3047 pub fn trait_is_auto(self, trait_def_id: DefId) -> bool {
3048 self.trait_def(trait_def_id).has_auto_impl
3051 pub fn generator_layout(self, def_id: DefId) -> &'tcx GeneratorLayout<'tcx> {
3052 self.optimized_mir(def_id).generator_layout.as_ref().unwrap()
3055 /// Given the `DefId` of an impl, returns the `DefId` of the trait it implements.
3056 /// If it implements no trait, returns `None`.
3057 pub fn trait_id_of_impl(self, def_id: DefId) -> Option<DefId> {
3058 self.impl_trait_ref(def_id).map(|tr| tr.def_id)
3061 /// If the given defid describes a method belonging to an impl, returns the
3062 /// `DefId` of the impl that the method belongs to; otherwise, returns `None`.
3063 pub fn impl_of_method(self, def_id: DefId) -> Option<DefId> {
3064 self.opt_associated_item(def_id).and_then(|trait_item| match trait_item.container {
3065 TraitContainer(_) => None,
3066 ImplContainer(def_id) => Some(def_id),
3070 /// Looks up the span of `impl_did` if the impl is local; otherwise returns `Err`
3071 /// with the name of the crate containing the impl.
3072 pub fn span_of_impl(self, impl_did: DefId) -> Result<Span, Symbol> {
3073 if let Some(impl_did) = impl_did.as_local() {
3074 let hir_id = self.hir().as_local_hir_id(impl_did);
3075 Ok(self.hir().span(hir_id))
3077 Err(self.crate_name(impl_did.krate))
3081 /// Hygienically compares a use-site name (`use_name`) for a field or an associated item with
3082 /// its supposed definition name (`def_name`). The method also needs `DefId` of the supposed
3083 /// definition's parent/scope to perform comparison.
3084 pub fn hygienic_eq(self, use_name: Ident, def_name: Ident, def_parent_def_id: DefId) -> bool {
3085 // We could use `Ident::eq` here, but we deliberately don't. The name
3086 // comparison fails frequently, and we want to avoid the expensive
3087 // `normalize_to_macros_2_0()` calls required for the span comparison whenever possible.
3088 use_name.name == def_name.name
3092 .hygienic_eq(def_name.span.ctxt(), self.expansion_that_defined(def_parent_def_id))
3095 fn expansion_that_defined(self, scope: DefId) -> ExpnId {
3096 match scope.as_local() {
3097 Some(scope) => self.hir().definitions().expansion_that_defined(scope),
3098 None => ExpnId::root(),
3102 pub fn adjust_ident(self, mut ident: Ident, scope: DefId) -> Ident {
3103 ident.span.normalize_to_macros_2_0_and_adjust(self.expansion_that_defined(scope));
3107 pub fn adjust_ident_and_get_scope(
3112 ) -> (Ident, DefId) {
3114 match ident.span.normalize_to_macros_2_0_and_adjust(self.expansion_that_defined(scope))
3116 Some(actual_expansion) => {
3117 self.hir().definitions().parent_module_of_macro_def(actual_expansion)
3119 None => self.parent_module(block).to_def_id(),
3124 pub fn is_object_safe(self, key: DefId) -> bool {
3125 self.object_safety_violations(key).is_empty()
3129 #[derive(Clone, HashStable)]
3130 pub struct AdtSizedConstraint<'tcx>(pub &'tcx [Ty<'tcx>]);
3132 /// Yields the parent function's `DefId` if `def_id` is an `impl Trait` definition.
3133 pub fn is_impl_trait_defn(tcx: TyCtxt<'_>, def_id: DefId) -> Option<DefId> {
3134 if let Some(def_id) = def_id.as_local() {
3135 if let Node::Item(item) = tcx.hir().get(tcx.hir().as_local_hir_id(def_id)) {
3136 if let hir::ItemKind::OpaqueTy(ref opaque_ty) = item.kind {
3137 return opaque_ty.impl_trait_fn;
3144 pub fn provide(providers: &mut ty::query::Providers) {
3145 context::provide(providers);
3146 erase_regions::provide(providers);
3147 layout::provide(providers);
3148 super::util::bug::provide(providers);
3149 *providers = ty::query::Providers {
3150 trait_impls_of: trait_def::trait_impls_of_provider,
3151 all_local_trait_impls: trait_def::all_local_trait_impls,
3156 /// A map for the local crate mapping each type to a vector of its
3157 /// inherent impls. This is not meant to be used outside of coherence;
3158 /// rather, you should request the vector for a specific type via
3159 /// `tcx.inherent_impls(def_id)` so as to minimize your dependencies
3160 /// (constructing this map requires touching the entire crate).
3161 #[derive(Clone, Debug, Default, HashStable)]
3162 pub struct CrateInherentImpls {
3163 pub inherent_impls: DefIdMap<Vec<DefId>>,
3166 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, HashStable)]
3167 pub struct SymbolName<'tcx> {
3168 /// `&str` gives a consistent ordering, which ensures reproducible builds.
3169 pub name: &'tcx str,
3172 impl<'tcx> SymbolName<'tcx> {
3173 pub fn new(tcx: TyCtxt<'tcx>, name: &str) -> SymbolName<'tcx> {
3175 name: unsafe { str::from_utf8_unchecked(tcx.arena.alloc_slice(name.as_bytes())) },
3180 impl<'tcx> fmt::Display for SymbolName<'tcx> {
3181 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
3182 fmt::Display::fmt(&self.name, fmt)
3186 impl<'tcx> fmt::Debug for SymbolName<'tcx> {
3187 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
3188 fmt::Display::fmt(&self.name, fmt)
3192 impl<'tcx> rustc_serialize::UseSpecializedEncodable for SymbolName<'tcx> {
3193 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
3194 s.emit_str(self.name)
3198 // The decoding takes place in `decode_symbol_name()`.
3199 impl<'tcx> rustc_serialize::UseSpecializedDecodable for SymbolName<'tcx> {}