1 // ignore-tidy-filelength
3 pub use self::fold::{TypeFoldable, TypeVisitor};
4 pub use self::AssocItemContainer::*;
5 pub use self::BorrowKind::*;
6 pub use self::IntVarValue::*;
7 pub use self::Variance::*;
9 use crate::arena::Arena;
10 use crate::hir::exports::ExportMap;
11 use crate::hir::map as hir_map;
13 use crate::ich::Fingerprint;
14 use crate::ich::StableHashingContext;
15 use crate::infer::canonical::Canonical;
16 use crate::middle::cstore::CrateStoreDyn;
17 use crate::middle::lang_items::{FnMutTraitLangItem, FnOnceTraitLangItem, FnTraitLangItem};
18 use crate::middle::resolve_lifetime::ObjectLifetimeDefault;
19 use crate::mir::interpret::ErrorHandled;
20 use crate::mir::GeneratorLayout;
21 use crate::mir::ReadOnlyBodyAndCache;
22 use crate::session::DataTypeKind;
23 use crate::traits::{self, Reveal};
25 use crate::ty::layout::VariantIdx;
26 use crate::ty::subst::{InternalSubsts, Subst, SubstsRef};
27 use crate::ty::util::{Discr, IntTypeExt};
28 use crate::ty::walk::TypeWalker;
29 use rustc_ast::ast::{self, Ident, Name};
30 use rustc_ast::node_id::{NodeId, NodeMap, NodeSet};
31 use rustc_attr as attr;
32 use rustc_data_structures::captures::Captures;
33 use rustc_data_structures::fx::FxHashMap;
34 use rustc_data_structures::fx::FxIndexMap;
35 use rustc_data_structures::sorted_map::SortedIndexMultiMap;
36 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
37 use rustc_data_structures::sync::{self, par_iter, Lrc, ParallelIterator};
39 use rustc_hir::def::{CtorKind, CtorOf, DefKind, Namespace, Res};
40 use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, LocalDefId, CRATE_DEF_INDEX, LOCAL_CRATE};
41 use rustc_hir::{Constness, GlobMap, Node, TraitMap};
42 use rustc_index::vec::{Idx, IndexVec};
43 use rustc_macros::HashStable;
44 use rustc_serialize::{self, Encodable, Encoder};
45 use rustc_span::hygiene::ExpnId;
46 use rustc_span::symbol::{kw, sym, Symbol};
48 use rustc_target::abi::Align;
50 use std::cell::RefCell;
51 use std::cmp::{self, Ordering};
53 use std::hash::{Hash, Hasher};
59 pub use self::sty::BoundRegion::*;
60 pub use self::sty::InferTy::*;
61 pub use self::sty::RegionKind;
62 pub use self::sty::RegionKind::*;
63 pub use self::sty::TyKind::*;
64 pub use self::sty::{Binder, BoundTy, BoundTyKind, BoundVar, DebruijnIndex, INNERMOST};
65 pub use self::sty::{BoundRegion, EarlyBoundRegion, FreeRegion, Region};
66 pub use self::sty::{CanonicalPolyFnSig, FnSig, GenSig, PolyFnSig, PolyGenSig};
67 pub use self::sty::{ClosureSubsts, GeneratorSubsts, TypeAndMut, UpvarSubsts};
68 pub use self::sty::{Const, ConstKind, ExistentialProjection, PolyExistentialProjection};
69 pub use self::sty::{ConstVid, FloatVid, IntVid, RegionVid, TyVid};
70 pub use self::sty::{ExistentialPredicate, InferConst, InferTy, ParamConst, ParamTy, ProjectionTy};
71 pub use self::sty::{ExistentialTraitRef, PolyExistentialTraitRef};
72 pub use self::sty::{PolyTraitRef, TraitRef, TyKind};
73 pub use crate::ty::diagnostics::*;
75 pub use self::binding::BindingMode;
76 pub use self::binding::BindingMode::*;
78 pub use self::context::{keep_local, tls, FreeRegionInfo, TyCtxt};
79 pub use self::context::{
80 CanonicalUserType, CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations, ResolvedOpaqueTy,
81 UserType, UserTypeAnnotationIndex,
83 pub use self::context::{
84 CtxtInterners, GeneratorInteriorTypeCause, GlobalCtxt, Lift, TypeckTables,
87 pub use self::instance::RESOLVE_INSTANCE;
88 pub use self::instance::{Instance, InstanceDef};
90 pub use self::trait_def::TraitDef;
92 pub use self::query::queries;
105 pub mod free_region_map;
106 pub mod inhabitedness;
108 pub mod normalize_erasing_regions;
122 mod structural_impls;
127 pub struct ResolverOutputs {
128 pub definitions: hir_map::Definitions,
129 pub cstore: Box<CrateStoreDyn>,
130 pub extern_crate_map: NodeMap<CrateNum>,
131 pub trait_map: TraitMap<NodeId>,
132 pub maybe_unused_trait_imports: NodeSet,
133 pub maybe_unused_extern_crates: Vec<(NodeId, Span)>,
134 pub export_map: ExportMap<NodeId>,
135 pub glob_map: GlobMap,
136 /// Extern prelude entries. The value is `true` if the entry was introduced
137 /// via `extern crate` item and not `--extern` option or compiler built-in.
138 pub extern_prelude: FxHashMap<Name, bool>,
141 #[derive(Clone, Copy, PartialEq, Eq, Debug, HashStable)]
142 pub enum AssocItemContainer {
143 TraitContainer(DefId),
144 ImplContainer(DefId),
147 impl AssocItemContainer {
148 /// Asserts that this is the `DefId` of an associated item declared
149 /// in a trait, and returns the trait `DefId`.
150 pub fn assert_trait(&self) -> DefId {
152 TraitContainer(id) => id,
153 _ => bug!("associated item has wrong container type: {:?}", self),
157 pub fn id(&self) -> DefId {
159 TraitContainer(id) => id,
160 ImplContainer(id) => id,
165 /// The "header" of an impl is everything outside the body: a Self type, a trait
166 /// ref (in the case of a trait impl), and a set of predicates (from the
167 /// bounds / where-clauses).
168 #[derive(Clone, Debug, TypeFoldable)]
169 pub struct ImplHeader<'tcx> {
170 pub impl_def_id: DefId,
171 pub self_ty: Ty<'tcx>,
172 pub trait_ref: Option<TraitRef<'tcx>>,
173 pub predicates: Vec<Predicate<'tcx>>,
176 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable)]
177 pub enum ImplPolarity {
178 /// `impl Trait for Type`
180 /// `impl !Trait for Type`
182 /// `#[rustc_reservation_impl] impl Trait for Type`
184 /// This is a "stability hack", not a real Rust feature.
185 /// See #64631 for details.
189 #[derive(Copy, Clone, Debug, PartialEq, HashStable)]
190 pub struct AssocItem {
192 #[stable_hasher(project(name))]
196 pub defaultness: hir::Defaultness,
197 pub container: AssocItemContainer,
199 /// Whether this is a method with an explicit self
200 /// as its first argument, allowing method calls.
201 pub method_has_self_argument: bool,
204 #[derive(Copy, Clone, PartialEq, Debug, HashStable)]
213 pub fn suggestion_descr(&self) -> &'static str {
215 ty::AssocKind::Method => "method call",
216 ty::AssocKind::Type | ty::AssocKind::OpaqueTy => "associated type",
217 ty::AssocKind::Const => "associated constant",
221 pub fn namespace(&self) -> Namespace {
223 ty::AssocKind::OpaqueTy | ty::AssocKind::Type => Namespace::TypeNS,
224 ty::AssocKind::Const | ty::AssocKind::Method => Namespace::ValueNS,
230 pub fn def_kind(&self) -> DefKind {
232 AssocKind::Const => DefKind::AssocConst,
233 AssocKind::Method => DefKind::Method,
234 AssocKind::Type => DefKind::AssocTy,
235 AssocKind::OpaqueTy => DefKind::AssocOpaqueTy,
239 /// Tests whether the associated item admits a non-trivial implementation
241 pub fn relevant_for_never(&self) -> bool {
243 AssocKind::OpaqueTy | AssocKind::Const | AssocKind::Type => true,
244 // FIXME(canndrew): Be more thorough here, check if any argument is uninhabited.
245 AssocKind::Method => !self.method_has_self_argument,
249 pub fn signature(&self, tcx: TyCtxt<'_>) -> String {
251 ty::AssocKind::Method => {
252 // We skip the binder here because the binder would deanonymize all
253 // late-bound regions, and we don't want method signatures to show up
254 // `as for<'r> fn(&'r MyType)`. Pretty-printing handles late-bound
255 // regions just fine, showing `fn(&MyType)`.
256 tcx.fn_sig(self.def_id).skip_binder().to_string()
258 ty::AssocKind::Type => format!("type {};", self.ident),
259 // FIXME(type_alias_impl_trait): we should print bounds here too.
260 ty::AssocKind::OpaqueTy => format!("type {};", self.ident),
261 ty::AssocKind::Const => {
262 format!("const {}: {:?};", self.ident, tcx.type_of(self.def_id))
268 /// A list of `ty::AssocItem`s in definition order that allows for efficient lookup by name.
270 /// When doing lookup by name, we try to postpone hygienic comparison for as long as possible since
271 /// it is relatively expensive. Instead, items are indexed by `Symbol` and hygienic comparison is
272 /// done only on items with the same name.
273 #[derive(Debug, Clone, PartialEq, HashStable)]
274 pub struct AssociatedItems {
275 items: SortedIndexMultiMap<u32, Symbol, ty::AssocItem>,
278 impl AssociatedItems {
279 /// Constructs an `AssociatedItems` map from a series of `ty::AssocItem`s in definition order.
280 pub fn new(items_in_def_order: impl IntoIterator<Item = ty::AssocItem>) -> Self {
281 let items = items_in_def_order.into_iter().map(|item| (item.ident.name, item)).collect();
282 AssociatedItems { items }
285 /// Returns a slice of associated items in the order they were defined.
287 /// New code should avoid relying on definition order. If you need a particular associated item
288 /// for a known trait, make that trait a lang item instead of indexing this array.
289 pub fn in_definition_order(&self) -> impl '_ + Iterator<Item = &ty::AssocItem> {
290 self.items.iter().map(|(_, v)| v)
293 /// Returns an iterator over all associated items with the given name, ignoring hygiene.
294 pub fn filter_by_name_unhygienic(
297 ) -> impl '_ + Iterator<Item = &ty::AssocItem> {
298 self.items.get_by_key(&name)
301 /// Returns an iterator over all associated items with the given name.
303 /// Multiple items may have the same name if they are in different `Namespace`s. For example,
304 /// an associated type can have the same name as a method. Use one of the `find_by_name_and_*`
305 /// methods below if you know which item you are looking for.
306 pub fn filter_by_name(
310 parent_def_id: DefId,
311 ) -> impl 'a + Iterator<Item = &'a ty::AssocItem> {
312 self.filter_by_name_unhygienic(ident.name)
313 .filter(move |item| tcx.hygienic_eq(ident, item.ident, parent_def_id))
316 /// Returns the associated item with the given name and `AssocKind`, if one exists.
317 pub fn find_by_name_and_kind(
322 parent_def_id: DefId,
323 ) -> Option<&ty::AssocItem> {
324 self.filter_by_name_unhygienic(ident.name)
325 .filter(|item| item.kind == kind)
326 .find(|item| tcx.hygienic_eq(ident, item.ident, parent_def_id))
329 /// Returns the associated item with the given name in the given `Namespace`, if one exists.
330 pub fn find_by_name_and_namespace(
335 parent_def_id: DefId,
336 ) -> Option<&ty::AssocItem> {
337 self.filter_by_name_unhygienic(ident.name)
338 .filter(|item| item.kind.namespace() == ns)
339 .find(|item| tcx.hygienic_eq(ident, item.ident, parent_def_id))
343 #[derive(Clone, Debug, PartialEq, Eq, Copy, RustcEncodable, RustcDecodable, HashStable)]
344 pub enum Visibility {
345 /// Visible everywhere (including in other crates).
347 /// Visible only in the given crate-local module.
349 /// Not visible anywhere in the local crate. This is the visibility of private external items.
353 pub trait DefIdTree: Copy {
354 fn parent(self, id: DefId) -> Option<DefId>;
356 fn is_descendant_of(self, mut descendant: DefId, ancestor: DefId) -> bool {
357 if descendant.krate != ancestor.krate {
361 while descendant != ancestor {
362 match self.parent(descendant) {
363 Some(parent) => descendant = parent,
364 None => return false,
371 impl<'tcx> DefIdTree for TyCtxt<'tcx> {
372 fn parent(self, id: DefId) -> Option<DefId> {
373 self.def_key(id).parent.map(|index| DefId { index, ..id })
378 pub fn from_hir(visibility: &hir::Visibility<'_>, id: hir::HirId, tcx: TyCtxt<'_>) -> Self {
379 match visibility.node {
380 hir::VisibilityKind::Public => Visibility::Public,
381 hir::VisibilityKind::Crate(_) => Visibility::Restricted(DefId::local(CRATE_DEF_INDEX)),
382 hir::VisibilityKind::Restricted { ref path, .. } => match path.res {
383 // If there is no resolution, `resolve` will have already reported an error, so
384 // assume that the visibility is public to avoid reporting more privacy errors.
385 Res::Err => Visibility::Public,
386 def => Visibility::Restricted(def.def_id()),
388 hir::VisibilityKind::Inherited => Visibility::Restricted(tcx.parent_module(id)),
392 /// Returns `true` if an item with this visibility is accessible from the given block.
393 pub fn is_accessible_from<T: DefIdTree>(self, module: DefId, tree: T) -> bool {
394 let restriction = match self {
395 // Public items are visible everywhere.
396 Visibility::Public => return true,
397 // Private items from other crates are visible nowhere.
398 Visibility::Invisible => return false,
399 // Restricted items are visible in an arbitrary local module.
400 Visibility::Restricted(other) if other.krate != module.krate => return false,
401 Visibility::Restricted(module) => module,
404 tree.is_descendant_of(module, restriction)
407 /// Returns `true` if this visibility is at least as accessible as the given visibility
408 pub fn is_at_least<T: DefIdTree>(self, vis: Visibility, tree: T) -> bool {
409 let vis_restriction = match vis {
410 Visibility::Public => return self == Visibility::Public,
411 Visibility::Invisible => return true,
412 Visibility::Restricted(module) => module,
415 self.is_accessible_from(vis_restriction, tree)
418 // Returns `true` if this item is visible anywhere in the local crate.
419 pub fn is_visible_locally(self) -> bool {
421 Visibility::Public => true,
422 Visibility::Restricted(def_id) => def_id.is_local(),
423 Visibility::Invisible => false,
428 #[derive(Copy, Clone, PartialEq, RustcDecodable, RustcEncodable, HashStable)]
430 Covariant, // T<A> <: T<B> iff A <: B -- e.g., function return type
431 Invariant, // T<A> <: T<B> iff B == A -- e.g., type of mutable cell
432 Contravariant, // T<A> <: T<B> iff B <: A -- e.g., function param type
433 Bivariant, // T<A> <: T<B> -- e.g., unused type parameter
436 /// The crate variances map is computed during typeck and contains the
437 /// variance of every item in the local crate. You should not use it
438 /// directly, because to do so will make your pass dependent on the
439 /// HIR of every item in the local crate. Instead, use
440 /// `tcx.variances_of()` to get the variance for a *particular*
442 #[derive(HashStable)]
443 pub struct CrateVariancesMap<'tcx> {
444 /// For each item with generics, maps to a vector of the variance
445 /// of its generics. If an item has no generics, it will have no
447 pub variances: FxHashMap<DefId, &'tcx [ty::Variance]>,
451 /// `a.xform(b)` combines the variance of a context with the
452 /// variance of a type with the following meaning. If we are in a
453 /// context with variance `a`, and we encounter a type argument in
454 /// a position with variance `b`, then `a.xform(b)` is the new
455 /// variance with which the argument appears.
461 /// Here, the "ambient" variance starts as covariant. `*mut T` is
462 /// invariant with respect to `T`, so the variance in which the
463 /// `Vec<i32>` appears is `Covariant.xform(Invariant)`, which
464 /// yields `Invariant`. Now, the type `Vec<T>` is covariant with
465 /// respect to its type argument `T`, and hence the variance of
466 /// the `i32` here is `Invariant.xform(Covariant)`, which results
467 /// (again) in `Invariant`.
471 /// fn(*const Vec<i32>, *mut Vec<i32)
473 /// The ambient variance is covariant. A `fn` type is
474 /// contravariant with respect to its parameters, so the variance
475 /// within which both pointer types appear is
476 /// `Covariant.xform(Contravariant)`, or `Contravariant`. `*const
477 /// T` is covariant with respect to `T`, so the variance within
478 /// which the first `Vec<i32>` appears is
479 /// `Contravariant.xform(Covariant)` or `Contravariant`. The same
480 /// is true for its `i32` argument. In the `*mut T` case, the
481 /// variance of `Vec<i32>` is `Contravariant.xform(Invariant)`,
482 /// and hence the outermost type is `Invariant` with respect to
483 /// `Vec<i32>` (and its `i32` argument).
485 /// Source: Figure 1 of "Taming the Wildcards:
486 /// Combining Definition- and Use-Site Variance" published in PLDI'11.
487 pub fn xform(self, v: ty::Variance) -> ty::Variance {
489 // Figure 1, column 1.
490 (ty::Covariant, ty::Covariant) => ty::Covariant,
491 (ty::Covariant, ty::Contravariant) => ty::Contravariant,
492 (ty::Covariant, ty::Invariant) => ty::Invariant,
493 (ty::Covariant, ty::Bivariant) => ty::Bivariant,
495 // Figure 1, column 2.
496 (ty::Contravariant, ty::Covariant) => ty::Contravariant,
497 (ty::Contravariant, ty::Contravariant) => ty::Covariant,
498 (ty::Contravariant, ty::Invariant) => ty::Invariant,
499 (ty::Contravariant, ty::Bivariant) => ty::Bivariant,
501 // Figure 1, column 3.
502 (ty::Invariant, _) => ty::Invariant,
504 // Figure 1, column 4.
505 (ty::Bivariant, _) => ty::Bivariant,
510 // Contains information needed to resolve types and (in the future) look up
511 // the types of AST nodes.
512 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
513 pub struct CReaderCacheKey {
519 /// Flags that we track on types. These flags are propagated upwards
520 /// through the type during type construction, so that we can quickly check
521 /// whether the type has various kinds of types in it without recursing
522 /// over the type itself.
523 pub struct TypeFlags: u32 {
524 // Does this have parameters? Used to determine whether substitution is
526 /// Does this have [Param]?
527 const HAS_TY_PARAM = 1 << 0;
528 /// Does this have [ReEarlyBound]?
529 const HAS_RE_PARAM = 1 << 1;
530 /// Does this have [ConstKind::Param]?
531 const HAS_CT_PARAM = 1 << 2;
533 const NEEDS_SUBST = TypeFlags::HAS_TY_PARAM.bits
534 | TypeFlags::HAS_RE_PARAM.bits
535 | TypeFlags::HAS_CT_PARAM.bits;
537 /// Does this have [Infer]?
538 const HAS_TY_INFER = 1 << 3;
539 /// Does this have [ReVar]?
540 const HAS_RE_INFER = 1 << 4;
541 /// Does this have [ConstKind::Infer]?
542 const HAS_CT_INFER = 1 << 5;
544 /// Does this have inference variables? Used to determine whether
545 /// inference is required.
546 const NEEDS_INFER = TypeFlags::HAS_TY_INFER.bits
547 | TypeFlags::HAS_RE_INFER.bits
548 | TypeFlags::HAS_CT_INFER.bits;
550 /// Does this have [Placeholder]?
551 const HAS_TY_PLACEHOLDER = 1 << 6;
552 /// Does this have [RePlaceholder]?
553 const HAS_RE_PLACEHOLDER = 1 << 7;
554 /// Does this have [ConstKind::Placeholder]?
555 const HAS_CT_PLACEHOLDER = 1 << 8;
557 /// `true` if there are "names" of types and regions and so forth
558 /// that are local to a particular fn
559 const HAS_FREE_LOCAL_NAMES = TypeFlags::HAS_TY_PARAM.bits
560 | TypeFlags::HAS_RE_PARAM.bits
561 | TypeFlags::HAS_CT_PARAM.bits
562 | TypeFlags::HAS_TY_INFER.bits
563 | TypeFlags::HAS_RE_INFER.bits
564 | TypeFlags::HAS_CT_INFER.bits
565 | TypeFlags::HAS_TY_PLACEHOLDER.bits
566 | TypeFlags::HAS_RE_PLACEHOLDER.bits
567 | TypeFlags::HAS_CT_PLACEHOLDER.bits;
569 /// Does this have [Projection] or [UnnormalizedProjection]?
570 const HAS_TY_PROJECTION = 1 << 9;
571 /// Does this have [Opaque]?
572 const HAS_TY_OPAQUE = 1 << 10;
573 /// Does this have [ConstKind::Unevaluated]?
574 const HAS_CT_PROJECTION = 1 << 11;
576 /// Could this type be normalized further?
577 const HAS_PROJECTION = TypeFlags::HAS_TY_PROJECTION.bits
578 | TypeFlags::HAS_TY_OPAQUE.bits
579 | TypeFlags::HAS_CT_PROJECTION.bits;
581 /// Present if the type belongs in a local type context.
582 /// Set for placeholders and inference variables that are not "Fresh".
583 const KEEP_IN_LOCAL_TCX = 1 << 12;
585 /// Is an error type reachable?
586 const HAS_TY_ERR = 1 << 13;
588 /// Does this have any region that "appears free" in the type?
589 /// Basically anything but [ReLateBound] and [ReErased].
590 const HAS_FREE_REGIONS = 1 << 14;
592 /// Does this have any [ReLateBound] regions? Used to check
593 /// if a global bound is safe to evaluate.
594 const HAS_RE_LATE_BOUND = 1 << 15;
596 /// Does this have any [ReErased] regions?
597 const HAS_RE_ERASED = 1 << 16;
599 /// Flags representing the nominal content of a type,
600 /// computed by FlagsComputation. If you add a new nominal
601 /// flag, it should be added here too.
602 const NOMINAL_FLAGS = TypeFlags::HAS_TY_PARAM.bits
603 | TypeFlags::HAS_RE_PARAM.bits
604 | TypeFlags::HAS_CT_PARAM.bits
605 | TypeFlags::HAS_TY_INFER.bits
606 | TypeFlags::HAS_RE_INFER.bits
607 | TypeFlags::HAS_CT_INFER.bits
608 | TypeFlags::HAS_TY_PLACEHOLDER.bits
609 | TypeFlags::HAS_RE_PLACEHOLDER.bits
610 | TypeFlags::HAS_CT_PLACEHOLDER.bits
611 | TypeFlags::HAS_TY_PROJECTION.bits
612 | TypeFlags::HAS_TY_OPAQUE.bits
613 | TypeFlags::HAS_CT_PROJECTION.bits
614 | TypeFlags::KEEP_IN_LOCAL_TCX.bits
615 | TypeFlags::HAS_TY_ERR.bits
616 | TypeFlags::HAS_FREE_REGIONS.bits
617 | TypeFlags::HAS_RE_LATE_BOUND.bits
618 | TypeFlags::HAS_RE_ERASED.bits;
622 #[allow(rustc::usage_of_ty_tykind)]
623 pub struct TyS<'tcx> {
624 pub kind: TyKind<'tcx>,
625 pub flags: TypeFlags,
627 /// This is a kind of confusing thing: it stores the smallest
630 /// (a) the binder itself captures nothing but
631 /// (b) all the late-bound things within the type are captured
632 /// by some sub-binder.
634 /// So, for a type without any late-bound things, like `u32`, this
635 /// will be *innermost*, because that is the innermost binder that
636 /// captures nothing. But for a type `&'D u32`, where `'D` is a
637 /// late-bound region with De Bruijn index `D`, this would be `D + 1`
638 /// -- the binder itself does not capture `D`, but `D` is captured
639 /// by an inner binder.
641 /// We call this concept an "exclusive" binder `D` because all
642 /// De Bruijn indices within the type are contained within `0..D`
644 outer_exclusive_binder: ty::DebruijnIndex,
647 // `TyS` is used a lot. Make sure it doesn't unintentionally get bigger.
648 #[cfg(target_arch = "x86_64")]
649 static_assert_size!(TyS<'_>, 32);
651 impl<'tcx> Ord for TyS<'tcx> {
652 fn cmp(&self, other: &TyS<'tcx>) -> Ordering {
653 self.kind.cmp(&other.kind)
657 impl<'tcx> PartialOrd for TyS<'tcx> {
658 fn partial_cmp(&self, other: &TyS<'tcx>) -> Option<Ordering> {
659 Some(self.kind.cmp(&other.kind))
663 impl<'tcx> PartialEq for TyS<'tcx> {
665 fn eq(&self, other: &TyS<'tcx>) -> bool {
669 impl<'tcx> Eq for TyS<'tcx> {}
671 impl<'tcx> Hash for TyS<'tcx> {
672 fn hash<H: Hasher>(&self, s: &mut H) {
673 (self as *const TyS<'_>).hash(s)
677 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for ty::TyS<'tcx> {
678 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
682 // The other fields just provide fast access to information that is
683 // also contained in `kind`, so no need to hash them.
686 outer_exclusive_binder: _,
689 kind.hash_stable(hcx, hasher);
693 #[rustc_diagnostic_item = "Ty"]
694 pub type Ty<'tcx> = &'tcx TyS<'tcx>;
696 impl<'tcx> rustc_serialize::UseSpecializedEncodable for Ty<'tcx> {}
697 impl<'tcx> rustc_serialize::UseSpecializedDecodable for Ty<'tcx> {}
699 pub type CanonicalTy<'tcx> = Canonical<'tcx, Ty<'tcx>>;
702 /// A dummy type used to force `List` to be unsized while not requiring references to it be wide
704 type OpaqueListContents;
707 /// A wrapper for slices with the additional invariant
708 /// that the slice is interned and no other slice with
709 /// the same contents can exist in the same context.
710 /// This means we can use pointer for both
711 /// equality comparisons and hashing.
712 /// Note: `Slice` was already taken by the `Ty`.
717 opaque: OpaqueListContents,
720 unsafe impl<T: Sync> Sync for List<T> {}
722 impl<T: Copy> List<T> {
724 fn from_arena<'tcx>(arena: &'tcx Arena<'tcx>, slice: &[T]) -> &'tcx List<T> {
725 assert!(!mem::needs_drop::<T>());
726 assert!(mem::size_of::<T>() != 0);
727 assert!(!slice.is_empty());
729 // Align up the size of the len (usize) field
730 let align = mem::align_of::<T>();
731 let align_mask = align - 1;
732 let offset = mem::size_of::<usize>();
733 let offset = (offset + align_mask) & !align_mask;
735 let size = offset + slice.len() * mem::size_of::<T>();
739 .alloc_raw(size, cmp::max(mem::align_of::<T>(), mem::align_of::<usize>()));
741 let result = &mut *(mem.as_mut_ptr() as *mut List<T>);
743 result.len = slice.len();
745 // Write the elements
746 let arena_slice = slice::from_raw_parts_mut(result.data.as_mut_ptr(), result.len);
747 arena_slice.copy_from_slice(slice);
754 impl<T: fmt::Debug> fmt::Debug for List<T> {
755 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
760 impl<T: Encodable> Encodable for List<T> {
762 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
767 impl<T> Ord for List<T>
771 fn cmp(&self, other: &List<T>) -> Ordering {
772 if self == other { Ordering::Equal } else { <[T] as Ord>::cmp(&**self, &**other) }
776 impl<T> PartialOrd for List<T>
780 fn partial_cmp(&self, other: &List<T>) -> Option<Ordering> {
782 Some(Ordering::Equal)
784 <[T] as PartialOrd>::partial_cmp(&**self, &**other)
789 impl<T: PartialEq> PartialEq for List<T> {
791 fn eq(&self, other: &List<T>) -> bool {
795 impl<T: Eq> Eq for List<T> {}
797 impl<T> Hash for List<T> {
799 fn hash<H: Hasher>(&self, s: &mut H) {
800 (self as *const List<T>).hash(s)
804 impl<T> Deref for List<T> {
807 fn deref(&self) -> &[T] {
812 impl<T> AsRef<[T]> for List<T> {
814 fn as_ref(&self) -> &[T] {
815 unsafe { slice::from_raw_parts(self.data.as_ptr(), self.len) }
819 impl<'a, T> IntoIterator for &'a List<T> {
821 type IntoIter = <&'a [T] as IntoIterator>::IntoIter;
823 fn into_iter(self) -> Self::IntoIter {
828 impl<'tcx> rustc_serialize::UseSpecializedDecodable for &'tcx List<Ty<'tcx>> {}
832 pub fn empty<'a>() -> &'a List<T> {
833 #[repr(align(64), C)]
834 struct EmptySlice([u8; 64]);
835 static EMPTY_SLICE: EmptySlice = EmptySlice([0; 64]);
836 assert!(mem::align_of::<T>() <= 64);
837 unsafe { &*(&EMPTY_SLICE as *const _ as *const List<T>) }
841 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
842 pub struct UpvarPath {
843 pub hir_id: hir::HirId,
846 /// Upvars do not get their own `NodeId`. Instead, we use the pair of
847 /// the original var ID (that is, the root variable that is referenced
848 /// by the upvar) and the ID of the closure expression.
849 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
851 pub var_path: UpvarPath,
852 pub closure_expr_id: LocalDefId,
855 #[derive(Clone, PartialEq, Debug, RustcEncodable, RustcDecodable, Copy, HashStable)]
856 pub enum BorrowKind {
857 /// Data must be immutable and is aliasable.
860 /// Data must be immutable but not aliasable. This kind of borrow
861 /// cannot currently be expressed by the user and is used only in
862 /// implicit closure bindings. It is needed when the closure
863 /// is borrowing or mutating a mutable referent, e.g.:
865 /// let x: &mut isize = ...;
866 /// let y = || *x += 5;
868 /// If we were to try to translate this closure into a more explicit
869 /// form, we'd encounter an error with the code as written:
871 /// struct Env { x: & &mut isize }
872 /// let x: &mut isize = ...;
873 /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
874 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
876 /// This is then illegal because you cannot mutate a `&mut` found
877 /// in an aliasable location. To solve, you'd have to translate with
878 /// an `&mut` borrow:
880 /// struct Env { x: & &mut isize }
881 /// let x: &mut isize = ...;
882 /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
883 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
885 /// Now the assignment to `**env.x` is legal, but creating a
886 /// mutable pointer to `x` is not because `x` is not mutable. We
887 /// could fix this by declaring `x` as `let mut x`. This is ok in
888 /// user code, if awkward, but extra weird for closures, since the
889 /// borrow is hidden.
891 /// So we introduce a "unique imm" borrow -- the referent is
892 /// immutable, but not aliasable. This solves the problem. For
893 /// simplicity, we don't give users the way to express this
894 /// borrow, it's just used when translating closures.
897 /// Data is mutable and not aliasable.
901 /// Information describing the capture of an upvar. This is computed
902 /// during `typeck`, specifically by `regionck`.
903 #[derive(PartialEq, Clone, Debug, Copy, RustcEncodable, RustcDecodable, HashStable)]
904 pub enum UpvarCapture<'tcx> {
905 /// Upvar is captured by value. This is always true when the
906 /// closure is labeled `move`, but can also be true in other cases
907 /// depending on inference.
910 /// Upvar is captured by reference.
911 ByRef(UpvarBorrow<'tcx>),
914 #[derive(PartialEq, Clone, Copy, RustcEncodable, RustcDecodable, HashStable)]
915 pub struct UpvarBorrow<'tcx> {
916 /// The kind of borrow: by-ref upvars have access to shared
917 /// immutable borrows, which are not part of the normal language
919 pub kind: BorrowKind,
921 /// Region of the resulting reference.
922 pub region: ty::Region<'tcx>,
925 pub type UpvarListMap = FxHashMap<DefId, FxIndexMap<hir::HirId, UpvarId>>;
926 pub type UpvarCaptureMap<'tcx> = FxHashMap<UpvarId, UpvarCapture<'tcx>>;
928 #[derive(Clone, Copy, PartialEq, Eq)]
929 pub enum IntVarValue {
931 UintType(ast::UintTy),
934 #[derive(Clone, Copy, PartialEq, Eq)]
935 pub struct FloatVarValue(pub ast::FloatTy);
937 impl ty::EarlyBoundRegion {
938 pub fn to_bound_region(&self) -> ty::BoundRegion {
939 ty::BoundRegion::BrNamed(self.def_id, self.name)
942 /// Does this early bound region have a name? Early bound regions normally
943 /// always have names except when using anonymous lifetimes (`'_`).
944 pub fn has_name(&self) -> bool {
945 self.name != kw::UnderscoreLifetime
949 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
950 pub enum GenericParamDefKind {
954 object_lifetime_default: ObjectLifetimeDefault,
955 synthetic: Option<hir::SyntheticTyParamKind>,
960 impl GenericParamDefKind {
961 pub fn descr(&self) -> &'static str {
963 GenericParamDefKind::Lifetime => "lifetime",
964 GenericParamDefKind::Type { .. } => "type",
965 GenericParamDefKind::Const => "constant",
970 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
971 pub struct GenericParamDef {
976 /// `pure_wrt_drop`, set by the (unsafe) `#[may_dangle]` attribute
977 /// on generic parameter `'a`/`T`, asserts data behind the parameter
978 /// `'a`/`T` won't be accessed during the parent type's `Drop` impl.
979 pub pure_wrt_drop: bool,
981 pub kind: GenericParamDefKind,
984 impl GenericParamDef {
985 pub fn to_early_bound_region_data(&self) -> ty::EarlyBoundRegion {
986 if let GenericParamDefKind::Lifetime = self.kind {
987 ty::EarlyBoundRegion { def_id: self.def_id, index: self.index, name: self.name }
989 bug!("cannot convert a non-lifetime parameter def to an early bound region")
993 pub fn to_bound_region(&self) -> ty::BoundRegion {
994 if let GenericParamDefKind::Lifetime = self.kind {
995 self.to_early_bound_region_data().to_bound_region()
997 bug!("cannot convert a non-lifetime parameter def to an early bound region")
1003 pub struct GenericParamCount {
1004 pub lifetimes: usize,
1009 /// Information about the formal type/lifetime parameters associated
1010 /// with an item or method. Analogous to `hir::Generics`.
1012 /// The ordering of parameters is the same as in `Subst` (excluding child generics):
1013 /// `Self` (optionally), `Lifetime` params..., `Type` params...
1014 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
1015 pub struct Generics {
1016 pub parent: Option<DefId>,
1017 pub parent_count: usize,
1018 pub params: Vec<GenericParamDef>,
1020 /// Reverse map to the `index` field of each `GenericParamDef`.
1021 #[stable_hasher(ignore)]
1022 pub param_def_id_to_index: FxHashMap<DefId, u32>,
1025 pub has_late_bound_regions: Option<Span>,
1028 impl<'tcx> Generics {
1029 pub fn count(&self) -> usize {
1030 self.parent_count + self.params.len()
1033 pub fn own_counts(&self) -> GenericParamCount {
1034 // We could cache this as a property of `GenericParamCount`, but
1035 // the aim is to refactor this away entirely eventually and the
1036 // presence of this method will be a constant reminder.
1037 let mut own_counts: GenericParamCount = Default::default();
1039 for param in &self.params {
1041 GenericParamDefKind::Lifetime => own_counts.lifetimes += 1,
1042 GenericParamDefKind::Type { .. } => own_counts.types += 1,
1043 GenericParamDefKind::Const => own_counts.consts += 1,
1050 pub fn requires_monomorphization(&self, tcx: TyCtxt<'tcx>) -> bool {
1051 if self.own_requires_monomorphization() {
1055 if let Some(parent_def_id) = self.parent {
1056 let parent = tcx.generics_of(parent_def_id);
1057 parent.requires_monomorphization(tcx)
1063 pub fn own_requires_monomorphization(&self) -> bool {
1064 for param in &self.params {
1066 GenericParamDefKind::Type { .. } | GenericParamDefKind::Const => return true,
1067 GenericParamDefKind::Lifetime => {}
1073 pub fn region_param(
1075 param: &EarlyBoundRegion,
1077 ) -> &'tcx GenericParamDef {
1078 if let Some(index) = param.index.checked_sub(self.parent_count as u32) {
1079 let param = &self.params[index as usize];
1081 GenericParamDefKind::Lifetime => param,
1082 _ => bug!("expected lifetime parameter, but found another generic parameter"),
1085 tcx.generics_of(self.parent.expect("parent_count > 0 but no parent?"))
1086 .region_param(param, tcx)
1090 /// Returns the `GenericParamDef` associated with this `ParamTy`.
1091 pub fn type_param(&'tcx self, param: &ParamTy, tcx: TyCtxt<'tcx>) -> &'tcx GenericParamDef {
1092 if let Some(index) = param.index.checked_sub(self.parent_count as u32) {
1093 let param = &self.params[index as usize];
1095 GenericParamDefKind::Type { .. } => param,
1096 _ => bug!("expected type parameter, but found another generic parameter"),
1099 tcx.generics_of(self.parent.expect("parent_count > 0 but no parent?"))
1100 .type_param(param, tcx)
1104 /// Returns the `ConstParameterDef` associated with this `ParamConst`.
1105 pub fn const_param(&'tcx self, param: &ParamConst, tcx: TyCtxt<'tcx>) -> &GenericParamDef {
1106 if let Some(index) = param.index.checked_sub(self.parent_count as u32) {
1107 let param = &self.params[index as usize];
1109 GenericParamDefKind::Const => param,
1110 _ => bug!("expected const parameter, but found another generic parameter"),
1113 tcx.generics_of(self.parent.expect("parent_count>0 but no parent?"))
1114 .const_param(param, tcx)
1119 /// Bounds on generics.
1120 #[derive(Copy, Clone, Default, Debug, RustcEncodable, RustcDecodable, HashStable)]
1121 pub struct GenericPredicates<'tcx> {
1122 pub parent: Option<DefId>,
1123 pub predicates: &'tcx [(Predicate<'tcx>, Span)],
1126 impl<'tcx> GenericPredicates<'tcx> {
1130 substs: SubstsRef<'tcx>,
1131 ) -> InstantiatedPredicates<'tcx> {
1132 let mut instantiated = InstantiatedPredicates::empty();
1133 self.instantiate_into(tcx, &mut instantiated, substs);
1137 pub fn instantiate_own(
1140 substs: SubstsRef<'tcx>,
1141 ) -> InstantiatedPredicates<'tcx> {
1142 InstantiatedPredicates {
1143 predicates: self.predicates.iter().map(|(p, _)| p.subst(tcx, substs)).collect(),
1144 spans: self.predicates.iter().map(|(_, sp)| *sp).collect(),
1148 fn instantiate_into(
1151 instantiated: &mut InstantiatedPredicates<'tcx>,
1152 substs: SubstsRef<'tcx>,
1154 if let Some(def_id) = self.parent {
1155 tcx.predicates_of(def_id).instantiate_into(tcx, instantiated, substs);
1157 instantiated.predicates.extend(self.predicates.iter().map(|(p, _)| p.subst(tcx, substs)));
1158 instantiated.spans.extend(self.predicates.iter().map(|(_, sp)| *sp));
1161 pub fn instantiate_identity(&self, tcx: TyCtxt<'tcx>) -> InstantiatedPredicates<'tcx> {
1162 let mut instantiated = InstantiatedPredicates::empty();
1163 self.instantiate_identity_into(tcx, &mut instantiated);
1167 fn instantiate_identity_into(
1170 instantiated: &mut InstantiatedPredicates<'tcx>,
1172 if let Some(def_id) = self.parent {
1173 tcx.predicates_of(def_id).instantiate_identity_into(tcx, instantiated);
1175 instantiated.predicates.extend(self.predicates.iter().map(|(p, _)| p));
1176 instantiated.spans.extend(self.predicates.iter().map(|(_, s)| s));
1179 pub fn instantiate_supertrait(
1182 poly_trait_ref: &ty::PolyTraitRef<'tcx>,
1183 ) -> InstantiatedPredicates<'tcx> {
1184 assert_eq!(self.parent, None);
1185 InstantiatedPredicates {
1189 .map(|(pred, _)| pred.subst_supertrait(tcx, poly_trait_ref))
1191 spans: self.predicates.iter().map(|(_, sp)| *sp).collect(),
1196 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1197 #[derive(HashStable, TypeFoldable)]
1198 pub enum Predicate<'tcx> {
1199 /// Corresponds to `where Foo: Bar<A, B, C>`. `Foo` here would be
1200 /// the `Self` type of the trait reference and `A`, `B`, and `C`
1201 /// would be the type parameters.
1203 /// A trait predicate will have `Constness::Const` if it originates
1204 /// from a bound on a `const fn` without the `?const` opt-out (e.g.,
1205 /// `const fn foobar<Foo: Bar>() {}`).
1206 Trait(PolyTraitPredicate<'tcx>, Constness),
1209 RegionOutlives(PolyRegionOutlivesPredicate<'tcx>),
1212 TypeOutlives(PolyTypeOutlivesPredicate<'tcx>),
1214 /// `where <T as TraitRef>::Name == X`, approximately.
1215 /// See the `ProjectionPredicate` struct for details.
1216 Projection(PolyProjectionPredicate<'tcx>),
1218 /// No syntax: `T` well-formed.
1219 WellFormed(Ty<'tcx>),
1221 /// Trait must be object-safe.
1224 /// No direct syntax. May be thought of as `where T: FnFoo<...>`
1225 /// for some substitutions `...` and `T` being a closure type.
1226 /// Satisfied (or refuted) once we know the closure's kind.
1227 ClosureKind(DefId, SubstsRef<'tcx>, ClosureKind),
1230 Subtype(PolySubtypePredicate<'tcx>),
1232 /// Constant initializer must evaluate successfully.
1233 ConstEvaluatable(DefId, SubstsRef<'tcx>),
1236 /// The crate outlives map is computed during typeck and contains the
1237 /// outlives of every item in the local crate. You should not use it
1238 /// directly, because to do so will make your pass dependent on the
1239 /// HIR of every item in the local crate. Instead, use
1240 /// `tcx.inferred_outlives_of()` to get the outlives for a *particular*
1242 #[derive(HashStable)]
1243 pub struct CratePredicatesMap<'tcx> {
1244 /// For each struct with outlive bounds, maps to a vector of the
1245 /// predicate of its outlive bounds. If an item has no outlives
1246 /// bounds, it will have no entry.
1247 pub predicates: FxHashMap<DefId, &'tcx [(ty::Predicate<'tcx>, Span)]>,
1250 impl<'tcx> AsRef<Predicate<'tcx>> for Predicate<'tcx> {
1251 fn as_ref(&self) -> &Predicate<'tcx> {
1256 impl<'tcx> Predicate<'tcx> {
1257 /// Performs a substitution suitable for going from a
1258 /// poly-trait-ref to supertraits that must hold if that
1259 /// poly-trait-ref holds. This is slightly different from a normal
1260 /// substitution in terms of what happens with bound regions. See
1261 /// lengthy comment below for details.
1262 pub fn subst_supertrait(
1265 trait_ref: &ty::PolyTraitRef<'tcx>,
1266 ) -> ty::Predicate<'tcx> {
1267 // The interaction between HRTB and supertraits is not entirely
1268 // obvious. Let me walk you (and myself) through an example.
1270 // Let's start with an easy case. Consider two traits:
1272 // trait Foo<'a>: Bar<'a,'a> { }
1273 // trait Bar<'b,'c> { }
1275 // Now, if we have a trait reference `for<'x> T: Foo<'x>`, then
1276 // we can deduce that `for<'x> T: Bar<'x,'x>`. Basically, if we
1277 // knew that `Foo<'x>` (for any 'x) then we also know that
1278 // `Bar<'x,'x>` (for any 'x). This more-or-less falls out from
1279 // normal substitution.
1281 // In terms of why this is sound, the idea is that whenever there
1282 // is an impl of `T:Foo<'a>`, it must show that `T:Bar<'a,'a>`
1283 // holds. So if there is an impl of `T:Foo<'a>` that applies to
1284 // all `'a`, then we must know that `T:Bar<'a,'a>` holds for all
1287 // Another example to be careful of is this:
1289 // trait Foo1<'a>: for<'b> Bar1<'a,'b> { }
1290 // trait Bar1<'b,'c> { }
1292 // Here, if we have `for<'x> T: Foo1<'x>`, then what do we know?
1293 // The answer is that we know `for<'x,'b> T: Bar1<'x,'b>`. The
1294 // reason is similar to the previous example: any impl of
1295 // `T:Foo1<'x>` must show that `for<'b> T: Bar1<'x, 'b>`. So
1296 // basically we would want to collapse the bound lifetimes from
1297 // the input (`trait_ref`) and the supertraits.
1299 // To achieve this in practice is fairly straightforward. Let's
1300 // consider the more complicated scenario:
1302 // - We start out with `for<'x> T: Foo1<'x>`. In this case, `'x`
1303 // has a De Bruijn index of 1. We want to produce `for<'x,'b> T: Bar1<'x,'b>`,
1304 // where both `'x` and `'b` would have a DB index of 1.
1305 // The substitution from the input trait-ref is therefore going to be
1306 // `'a => 'x` (where `'x` has a DB index of 1).
1307 // - The super-trait-ref is `for<'b> Bar1<'a,'b>`, where `'a` is an
1308 // early-bound parameter and `'b' is a late-bound parameter with a
1310 // - If we replace `'a` with `'x` from the input, it too will have
1311 // a DB index of 1, and thus we'll have `for<'x,'b> Bar1<'x,'b>`
1312 // just as we wanted.
1314 // There is only one catch. If we just apply the substitution `'a
1315 // => 'x` to `for<'b> Bar1<'a,'b>`, the substitution code will
1316 // adjust the DB index because we substituting into a binder (it
1317 // tries to be so smart...) resulting in `for<'x> for<'b>
1318 // Bar1<'x,'b>` (we have no syntax for this, so use your
1319 // imagination). Basically the 'x will have DB index of 2 and 'b
1320 // will have DB index of 1. Not quite what we want. So we apply
1321 // the substitution to the *contents* of the trait reference,
1322 // rather than the trait reference itself (put another way, the
1323 // substitution code expects equal binding levels in the values
1324 // from the substitution and the value being substituted into, and
1325 // this trick achieves that).
1327 let substs = &trait_ref.skip_binder().substs;
1329 Predicate::Trait(ref binder, constness) => {
1330 Predicate::Trait(binder.map_bound(|data| data.subst(tcx, substs)), constness)
1332 Predicate::Subtype(ref binder) => {
1333 Predicate::Subtype(binder.map_bound(|data| data.subst(tcx, substs)))
1335 Predicate::RegionOutlives(ref binder) => {
1336 Predicate::RegionOutlives(binder.map_bound(|data| data.subst(tcx, substs)))
1338 Predicate::TypeOutlives(ref binder) => {
1339 Predicate::TypeOutlives(binder.map_bound(|data| data.subst(tcx, substs)))
1341 Predicate::Projection(ref binder) => {
1342 Predicate::Projection(binder.map_bound(|data| data.subst(tcx, substs)))
1344 Predicate::WellFormed(data) => Predicate::WellFormed(data.subst(tcx, substs)),
1345 Predicate::ObjectSafe(trait_def_id) => Predicate::ObjectSafe(trait_def_id),
1346 Predicate::ClosureKind(closure_def_id, closure_substs, kind) => {
1347 Predicate::ClosureKind(closure_def_id, closure_substs.subst(tcx, substs), kind)
1349 Predicate::ConstEvaluatable(def_id, const_substs) => {
1350 Predicate::ConstEvaluatable(def_id, const_substs.subst(tcx, substs))
1356 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1357 #[derive(HashStable, TypeFoldable)]
1358 pub struct TraitPredicate<'tcx> {
1359 pub trait_ref: TraitRef<'tcx>,
1362 pub type PolyTraitPredicate<'tcx> = ty::Binder<TraitPredicate<'tcx>>;
1364 impl<'tcx> TraitPredicate<'tcx> {
1365 pub fn def_id(&self) -> DefId {
1366 self.trait_ref.def_id
1369 pub fn input_types<'a>(&'a self) -> impl DoubleEndedIterator<Item = Ty<'tcx>> + 'a {
1370 self.trait_ref.input_types()
1373 pub fn self_ty(&self) -> Ty<'tcx> {
1374 self.trait_ref.self_ty()
1378 impl<'tcx> PolyTraitPredicate<'tcx> {
1379 pub fn def_id(&self) -> DefId {
1380 // Ok to skip binder since trait `DefId` does not care about regions.
1381 self.skip_binder().def_id()
1385 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, RustcEncodable, RustcDecodable)]
1386 #[derive(HashStable, TypeFoldable)]
1387 pub struct OutlivesPredicate<A, B>(pub A, pub B); // `A: B`
1388 pub type PolyOutlivesPredicate<A, B> = ty::Binder<OutlivesPredicate<A, B>>;
1389 pub type RegionOutlivesPredicate<'tcx> = OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>;
1390 pub type TypeOutlivesPredicate<'tcx> = OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>;
1391 pub type PolyRegionOutlivesPredicate<'tcx> = ty::Binder<RegionOutlivesPredicate<'tcx>>;
1392 pub type PolyTypeOutlivesPredicate<'tcx> = ty::Binder<TypeOutlivesPredicate<'tcx>>;
1394 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
1395 #[derive(HashStable, TypeFoldable)]
1396 pub struct SubtypePredicate<'tcx> {
1397 pub a_is_expected: bool,
1401 pub type PolySubtypePredicate<'tcx> = ty::Binder<SubtypePredicate<'tcx>>;
1403 /// This kind of predicate has no *direct* correspondent in the
1404 /// syntax, but it roughly corresponds to the syntactic forms:
1406 /// 1. `T: TraitRef<..., Item = Type>`
1407 /// 2. `<T as TraitRef<...>>::Item == Type` (NYI)
1409 /// In particular, form #1 is "desugared" to the combination of a
1410 /// normal trait predicate (`T: TraitRef<...>`) and one of these
1411 /// predicates. Form #2 is a broader form in that it also permits
1412 /// equality between arbitrary types. Processing an instance of
1413 /// Form #2 eventually yields one of these `ProjectionPredicate`
1414 /// instances to normalize the LHS.
1415 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1416 #[derive(HashStable, TypeFoldable)]
1417 pub struct ProjectionPredicate<'tcx> {
1418 pub projection_ty: ProjectionTy<'tcx>,
1422 pub type PolyProjectionPredicate<'tcx> = Binder<ProjectionPredicate<'tcx>>;
1424 impl<'tcx> PolyProjectionPredicate<'tcx> {
1425 /// Returns the `DefId` of the associated item being projected.
1426 pub fn item_def_id(&self) -> DefId {
1427 self.skip_binder().projection_ty.item_def_id
1431 pub fn to_poly_trait_ref(&self, tcx: TyCtxt<'tcx>) -> PolyTraitRef<'tcx> {
1432 // Note: unlike with `TraitRef::to_poly_trait_ref()`,
1433 // `self.0.trait_ref` is permitted to have escaping regions.
1434 // This is because here `self` has a `Binder` and so does our
1435 // return value, so we are preserving the number of binding
1437 self.map_bound(|predicate| predicate.projection_ty.trait_ref(tcx))
1440 pub fn ty(&self) -> Binder<Ty<'tcx>> {
1441 self.map_bound(|predicate| predicate.ty)
1444 /// The `DefId` of the `TraitItem` for the associated type.
1446 /// Note that this is not the `DefId` of the `TraitRef` containing this
1447 /// associated type, which is in `tcx.associated_item(projection_def_id()).container`.
1448 pub fn projection_def_id(&self) -> DefId {
1449 // Ok to skip binder since trait `DefId` does not care about regions.
1450 self.skip_binder().projection_ty.item_def_id
1454 pub trait ToPolyTraitRef<'tcx> {
1455 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx>;
1458 impl<'tcx> ToPolyTraitRef<'tcx> for TraitRef<'tcx> {
1459 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
1460 ty::Binder::dummy(*self)
1464 impl<'tcx> ToPolyTraitRef<'tcx> for PolyTraitPredicate<'tcx> {
1465 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
1466 self.map_bound_ref(|trait_pred| trait_pred.trait_ref)
1470 pub trait ToPredicate<'tcx> {
1471 fn to_predicate(&self) -> Predicate<'tcx>;
1474 impl<'tcx> ToPredicate<'tcx> for ConstnessAnd<TraitRef<'tcx>> {
1475 fn to_predicate(&self) -> Predicate<'tcx> {
1476 ty::Predicate::Trait(
1477 ty::Binder::dummy(ty::TraitPredicate { trait_ref: self.value }),
1483 impl<'tcx> ToPredicate<'tcx> for ConstnessAnd<&TraitRef<'tcx>> {
1484 fn to_predicate(&self) -> Predicate<'tcx> {
1485 ty::Predicate::Trait(
1486 ty::Binder::dummy(ty::TraitPredicate { trait_ref: *self.value }),
1492 impl<'tcx> ToPredicate<'tcx> for ConstnessAnd<PolyTraitRef<'tcx>> {
1493 fn to_predicate(&self) -> Predicate<'tcx> {
1494 ty::Predicate::Trait(self.value.to_poly_trait_predicate(), self.constness)
1498 impl<'tcx> ToPredicate<'tcx> for ConstnessAnd<&PolyTraitRef<'tcx>> {
1499 fn to_predicate(&self) -> Predicate<'tcx> {
1500 ty::Predicate::Trait(self.value.to_poly_trait_predicate(), self.constness)
1504 impl<'tcx> ToPredicate<'tcx> for PolyRegionOutlivesPredicate<'tcx> {
1505 fn to_predicate(&self) -> Predicate<'tcx> {
1506 Predicate::RegionOutlives(*self)
1510 impl<'tcx> ToPredicate<'tcx> for PolyTypeOutlivesPredicate<'tcx> {
1511 fn to_predicate(&self) -> Predicate<'tcx> {
1512 Predicate::TypeOutlives(*self)
1516 impl<'tcx> ToPredicate<'tcx> for PolyProjectionPredicate<'tcx> {
1517 fn to_predicate(&self) -> Predicate<'tcx> {
1518 Predicate::Projection(*self)
1522 // A custom iterator used by `Predicate::walk_tys`.
1523 enum WalkTysIter<'tcx, I, J, K>
1525 I: Iterator<Item = Ty<'tcx>>,
1526 J: Iterator<Item = Ty<'tcx>>,
1527 K: Iterator<Item = Ty<'tcx>>,
1531 Two(Ty<'tcx>, Ty<'tcx>),
1537 impl<'tcx, I, J, K> Iterator for WalkTysIter<'tcx, I, J, K>
1539 I: Iterator<Item = Ty<'tcx>>,
1540 J: Iterator<Item = Ty<'tcx>>,
1541 K: Iterator<Item = Ty<'tcx>>,
1543 type Item = Ty<'tcx>;
1545 fn next(&mut self) -> Option<Ty<'tcx>> {
1547 WalkTysIter::None => None,
1548 WalkTysIter::One(item) => {
1549 *self = WalkTysIter::None;
1552 WalkTysIter::Two(item1, item2) => {
1553 *self = WalkTysIter::One(item2);
1556 WalkTysIter::Types(ref mut iter) => iter.next(),
1557 WalkTysIter::InputTypes(ref mut iter) => iter.next(),
1558 WalkTysIter::ProjectionTypes(ref mut iter) => iter.next(),
1563 impl<'tcx> Predicate<'tcx> {
1564 /// Iterates over the types in this predicate. Note that in all
1565 /// cases this is skipping over a binder, so late-bound regions
1566 /// with depth 0 are bound by the predicate.
1567 pub fn walk_tys(&'a self) -> impl Iterator<Item = Ty<'tcx>> + 'a {
1569 ty::Predicate::Trait(ref data, _) => {
1570 WalkTysIter::InputTypes(data.skip_binder().input_types())
1572 ty::Predicate::Subtype(binder) => {
1573 let SubtypePredicate { a, b, a_is_expected: _ } = binder.skip_binder();
1574 WalkTysIter::Two(a, b)
1576 ty::Predicate::TypeOutlives(binder) => WalkTysIter::One(binder.skip_binder().0),
1577 ty::Predicate::RegionOutlives(..) => WalkTysIter::None,
1578 ty::Predicate::Projection(ref data) => {
1579 let inner = data.skip_binder();
1580 WalkTysIter::ProjectionTypes(
1581 inner.projection_ty.substs.types().chain(Some(inner.ty)),
1584 ty::Predicate::WellFormed(data) => WalkTysIter::One(data),
1585 ty::Predicate::ObjectSafe(_trait_def_id) => WalkTysIter::None,
1586 ty::Predicate::ClosureKind(_closure_def_id, closure_substs, _kind) => {
1587 WalkTysIter::Types(closure_substs.types())
1589 ty::Predicate::ConstEvaluatable(_, substs) => WalkTysIter::Types(substs.types()),
1593 pub fn to_opt_poly_trait_ref(&self) -> Option<PolyTraitRef<'tcx>> {
1595 Predicate::Trait(ref t, _) => Some(t.to_poly_trait_ref()),
1596 Predicate::Projection(..)
1597 | Predicate::Subtype(..)
1598 | Predicate::RegionOutlives(..)
1599 | Predicate::WellFormed(..)
1600 | Predicate::ObjectSafe(..)
1601 | Predicate::ClosureKind(..)
1602 | Predicate::TypeOutlives(..)
1603 | Predicate::ConstEvaluatable(..) => None,
1607 pub fn to_opt_type_outlives(&self) -> Option<PolyTypeOutlivesPredicate<'tcx>> {
1609 Predicate::TypeOutlives(data) => Some(data),
1610 Predicate::Trait(..)
1611 | Predicate::Projection(..)
1612 | Predicate::Subtype(..)
1613 | Predicate::RegionOutlives(..)
1614 | Predicate::WellFormed(..)
1615 | Predicate::ObjectSafe(..)
1616 | Predicate::ClosureKind(..)
1617 | Predicate::ConstEvaluatable(..) => None,
1622 /// Represents the bounds declared on a particular set of type
1623 /// parameters. Should eventually be generalized into a flag list of
1624 /// where-clauses. You can obtain a `InstantiatedPredicates` list from a
1625 /// `GenericPredicates` by using the `instantiate` method. Note that this method
1626 /// reflects an important semantic invariant of `InstantiatedPredicates`: while
1627 /// the `GenericPredicates` are expressed in terms of the bound type
1628 /// parameters of the impl/trait/whatever, an `InstantiatedPredicates` instance
1629 /// represented a set of bounds for some particular instantiation,
1630 /// meaning that the generic parameters have been substituted with
1635 /// struct Foo<T, U: Bar<T>> { ... }
1637 /// Here, the `GenericPredicates` for `Foo` would contain a list of bounds like
1638 /// `[[], [U:Bar<T>]]`. Now if there were some particular reference
1639 /// like `Foo<isize,usize>`, then the `InstantiatedPredicates` would be `[[],
1640 /// [usize:Bar<isize>]]`.
1641 #[derive(Clone, Debug, TypeFoldable)]
1642 pub struct InstantiatedPredicates<'tcx> {
1643 pub predicates: Vec<Predicate<'tcx>>,
1644 pub spans: Vec<Span>,
1647 impl<'tcx> InstantiatedPredicates<'tcx> {
1648 pub fn empty() -> InstantiatedPredicates<'tcx> {
1649 InstantiatedPredicates { predicates: vec![], spans: vec![] }
1652 pub fn is_empty(&self) -> bool {
1653 self.predicates.is_empty()
1657 rustc_index::newtype_index! {
1658 /// "Universes" are used during type- and trait-checking in the
1659 /// presence of `for<..>` binders to control what sets of names are
1660 /// visible. Universes are arranged into a tree: the root universe
1661 /// contains names that are always visible. Each child then adds a new
1662 /// set of names that are visible, in addition to those of its parent.
1663 /// We say that the child universe "extends" the parent universe with
1666 /// To make this more concrete, consider this program:
1670 /// fn bar<T>(x: T) {
1671 /// let y: for<'a> fn(&'a u8, Foo) = ...;
1675 /// The struct name `Foo` is in the root universe U0. But the type
1676 /// parameter `T`, introduced on `bar`, is in an extended universe U1
1677 /// -- i.e., within `bar`, we can name both `T` and `Foo`, but outside
1678 /// of `bar`, we cannot name `T`. Then, within the type of `y`, the
1679 /// region `'a` is in a universe U2 that extends U1, because we can
1680 /// name it inside the fn type but not outside.
1682 /// Universes are used to do type- and trait-checking around these
1683 /// "forall" binders (also called **universal quantification**). The
1684 /// idea is that when, in the body of `bar`, we refer to `T` as a
1685 /// type, we aren't referring to any type in particular, but rather a
1686 /// kind of "fresh" type that is distinct from all other types we have
1687 /// actually declared. This is called a **placeholder** type, and we
1688 /// use universes to talk about this. In other words, a type name in
1689 /// universe 0 always corresponds to some "ground" type that the user
1690 /// declared, but a type name in a non-zero universe is a placeholder
1691 /// type -- an idealized representative of "types in general" that we
1692 /// use for checking generic functions.
1693 pub struct UniverseIndex {
1695 DEBUG_FORMAT = "U{}",
1699 impl UniverseIndex {
1700 pub const ROOT: UniverseIndex = UniverseIndex::from_u32_const(0);
1702 /// Returns the "next" universe index in order -- this new index
1703 /// is considered to extend all previous universes. This
1704 /// corresponds to entering a `forall` quantifier. So, for
1705 /// example, suppose we have this type in universe `U`:
1708 /// for<'a> fn(&'a u32)
1711 /// Once we "enter" into this `for<'a>` quantifier, we are in a
1712 /// new universe that extends `U` -- in this new universe, we can
1713 /// name the region `'a`, but that region was not nameable from
1714 /// `U` because it was not in scope there.
1715 pub fn next_universe(self) -> UniverseIndex {
1716 UniverseIndex::from_u32(self.private.checked_add(1).unwrap())
1719 /// Returns `true` if `self` can name a name from `other` -- in other words,
1720 /// if the set of names in `self` is a superset of those in
1721 /// `other` (`self >= other`).
1722 pub fn can_name(self, other: UniverseIndex) -> bool {
1723 self.private >= other.private
1726 /// Returns `true` if `self` cannot name some names from `other` -- in other
1727 /// words, if the set of names in `self` is a strict subset of
1728 /// those in `other` (`self < other`).
1729 pub fn cannot_name(self, other: UniverseIndex) -> bool {
1730 self.private < other.private
1734 /// The "placeholder index" fully defines a placeholder region.
1735 /// Placeholder regions are identified by both a **universe** as well
1736 /// as a "bound-region" within that universe. The `bound_region` is
1737 /// basically a name -- distinct bound regions within the same
1738 /// universe are just two regions with an unknown relationship to one
1740 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, PartialOrd, Ord)]
1741 pub struct Placeholder<T> {
1742 pub universe: UniverseIndex,
1746 impl<'a, T> HashStable<StableHashingContext<'a>> for Placeholder<T>
1748 T: HashStable<StableHashingContext<'a>>,
1750 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
1751 self.universe.hash_stable(hcx, hasher);
1752 self.name.hash_stable(hcx, hasher);
1756 pub type PlaceholderRegion = Placeholder<BoundRegion>;
1758 pub type PlaceholderType = Placeholder<BoundVar>;
1760 pub type PlaceholderConst = Placeholder<BoundVar>;
1762 /// When type checking, we use the `ParamEnv` to track
1763 /// details about the set of where-clauses that are in scope at this
1764 /// particular point.
1765 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable, TypeFoldable)]
1766 pub struct ParamEnv<'tcx> {
1767 /// `Obligation`s that the caller must satisfy. This is basically
1768 /// the set of bounds on the in-scope type parameters, translated
1769 /// into `Obligation`s, and elaborated and normalized.
1770 pub caller_bounds: &'tcx List<ty::Predicate<'tcx>>,
1772 /// Typically, this is `Reveal::UserFacing`, but during codegen we
1773 /// want `Reveal::All` -- note that this is always paired with an
1774 /// empty environment. To get that, use `ParamEnv::reveal()`.
1775 pub reveal: traits::Reveal,
1777 /// If this `ParamEnv` comes from a call to `tcx.param_env(def_id)`,
1778 /// register that `def_id` (useful for transitioning to the chalk trait
1780 pub def_id: Option<DefId>,
1783 impl<'tcx> ParamEnv<'tcx> {
1784 /// Construct a trait environment suitable for contexts where
1785 /// there are no where-clauses in scope. Hidden types (like `impl
1786 /// Trait`) are left hidden, so this is suitable for ordinary
1789 pub fn empty() -> Self {
1790 Self::new(List::empty(), Reveal::UserFacing, None)
1793 /// Construct a trait environment with no where-clauses in scope
1794 /// where the values of all `impl Trait` and other hidden types
1795 /// are revealed. This is suitable for monomorphized, post-typeck
1796 /// environments like codegen or doing optimizations.
1798 /// N.B., if you want to have predicates in scope, use `ParamEnv::new`,
1799 /// or invoke `param_env.with_reveal_all()`.
1801 pub fn reveal_all() -> Self {
1802 Self::new(List::empty(), Reveal::All, None)
1805 /// Construct a trait environment with the given set of predicates.
1808 caller_bounds: &'tcx List<ty::Predicate<'tcx>>,
1810 def_id: Option<DefId>,
1812 ty::ParamEnv { caller_bounds, reveal, def_id }
1815 /// Returns a new parameter environment with the same clauses, but
1816 /// which "reveals" the true results of projections in all cases
1817 /// (even for associated types that are specializable). This is
1818 /// the desired behavior during codegen and certain other special
1819 /// contexts; normally though we want to use `Reveal::UserFacing`,
1820 /// which is the default.
1821 pub fn with_reveal_all(self) -> Self {
1822 ty::ParamEnv { reveal: Reveal::All, ..self }
1825 /// Returns this same environment but with no caller bounds.
1826 pub fn without_caller_bounds(self) -> Self {
1827 ty::ParamEnv { caller_bounds: List::empty(), ..self }
1830 /// Creates a suitable environment in which to perform trait
1831 /// queries on the given value. When type-checking, this is simply
1832 /// the pair of the environment plus value. But when reveal is set to
1833 /// All, then if `value` does not reference any type parameters, we will
1834 /// pair it with the empty environment. This improves caching and is generally
1837 /// N.B., we preserve the environment when type-checking because it
1838 /// is possible for the user to have wacky where-clauses like
1839 /// `where Box<u32>: Copy`, which are clearly never
1840 /// satisfiable. We generally want to behave as if they were true,
1841 /// although the surrounding function is never reachable.
1842 pub fn and<T: TypeFoldable<'tcx>>(self, value: T) -> ParamEnvAnd<'tcx, T> {
1844 Reveal::UserFacing => ParamEnvAnd { param_env: self, value },
1847 if value.is_global() {
1848 ParamEnvAnd { param_env: self.without_caller_bounds(), value }
1850 ParamEnvAnd { param_env: self, value }
1857 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1858 pub struct ConstnessAnd<T> {
1859 pub constness: Constness,
1863 // FIXME(ecstaticmorse): Audit all occurrences of `without_const().to_predicate()` to ensure that
1864 // the constness of trait bounds is being propagated correctly.
1865 pub trait WithConstness: Sized {
1867 fn with_constness(self, constness: Constness) -> ConstnessAnd<Self> {
1868 ConstnessAnd { constness, value: self }
1872 fn with_const(self) -> ConstnessAnd<Self> {
1873 self.with_constness(Constness::Const)
1877 fn without_const(self) -> ConstnessAnd<Self> {
1878 self.with_constness(Constness::NotConst)
1882 impl<T> WithConstness for T {}
1884 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TypeFoldable)]
1885 pub struct ParamEnvAnd<'tcx, T> {
1886 pub param_env: ParamEnv<'tcx>,
1890 impl<'tcx, T> ParamEnvAnd<'tcx, T> {
1891 pub fn into_parts(self) -> (ParamEnv<'tcx>, T) {
1892 (self.param_env, self.value)
1896 impl<'a, 'tcx, T> HashStable<StableHashingContext<'a>> for ParamEnvAnd<'tcx, T>
1898 T: HashStable<StableHashingContext<'a>>,
1900 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
1901 let ParamEnvAnd { ref param_env, ref value } = *self;
1903 param_env.hash_stable(hcx, hasher);
1904 value.hash_stable(hcx, hasher);
1908 #[derive(Copy, Clone, Debug, HashStable)]
1909 pub struct Destructor {
1910 /// The `DefId` of the destructor method
1915 #[derive(HashStable)]
1916 pub struct AdtFlags: u32 {
1917 const NO_ADT_FLAGS = 0;
1918 /// Indicates whether the ADT is an enum.
1919 const IS_ENUM = 1 << 0;
1920 /// Indicates whether the ADT is a union.
1921 const IS_UNION = 1 << 1;
1922 /// Indicates whether the ADT is a struct.
1923 const IS_STRUCT = 1 << 2;
1924 /// Indicates whether the ADT is a struct and has a constructor.
1925 const HAS_CTOR = 1 << 3;
1926 /// Indicates whether the type is `PhantomData`.
1927 const IS_PHANTOM_DATA = 1 << 4;
1928 /// Indicates whether the type has a `#[fundamental]` attribute.
1929 const IS_FUNDAMENTAL = 1 << 5;
1930 /// Indicates whether the type is `Box`.
1931 const IS_BOX = 1 << 6;
1932 /// Indicates whether the type is `ManuallyDrop`.
1933 const IS_MANUALLY_DROP = 1 << 7;
1934 // FIXME(matthewjasper) replace these with diagnostic items
1935 /// Indicates whether the type is an `Arc`.
1936 const IS_ARC = 1 << 8;
1937 /// Indicates whether the type is an `Rc`.
1938 const IS_RC = 1 << 9;
1939 /// Indicates whether the variant list of this ADT is `#[non_exhaustive]`.
1940 /// (i.e., this flag is never set unless this ADT is an enum).
1941 const IS_VARIANT_LIST_NON_EXHAUSTIVE = 1 << 10;
1946 #[derive(HashStable)]
1947 pub struct VariantFlags: u32 {
1948 const NO_VARIANT_FLAGS = 0;
1949 /// Indicates whether the field list of this variant is `#[non_exhaustive]`.
1950 const IS_FIELD_LIST_NON_EXHAUSTIVE = 1 << 0;
1954 /// Definition of a variant -- a struct's fields or a enum variant.
1955 #[derive(Debug, HashStable)]
1956 pub struct VariantDef {
1957 /// `DefId` that identifies the variant itself.
1958 /// If this variant belongs to a struct or union, then this is a copy of its `DefId`.
1960 /// `DefId` that identifies the variant's constructor.
1961 /// If this variant is a struct variant, then this is `None`.
1962 pub ctor_def_id: Option<DefId>,
1963 /// Variant or struct name.
1964 #[stable_hasher(project(name))]
1966 /// Discriminant of this variant.
1967 pub discr: VariantDiscr,
1968 /// Fields of this variant.
1969 pub fields: Vec<FieldDef>,
1970 /// Type of constructor of variant.
1971 pub ctor_kind: CtorKind,
1972 /// Flags of the variant (e.g. is field list non-exhaustive)?
1973 flags: VariantFlags,
1974 /// Variant is obtained as part of recovering from a syntactic error.
1975 /// May be incomplete or bogus.
1976 pub recovered: bool,
1979 impl<'tcx> VariantDef {
1980 /// Creates a new `VariantDef`.
1982 /// `variant_did` is the `DefId` that identifies the enum variant (if this `VariantDef`
1983 /// represents an enum variant).
1985 /// `ctor_did` is the `DefId` that identifies the constructor of unit or
1986 /// tuple-variants/structs. If this is a `struct`-variant then this should be `None`.
1988 /// `parent_did` is the `DefId` of the `AdtDef` representing the enum or struct that
1989 /// owns this variant. It is used for checking if a struct has `#[non_exhaustive]` w/out having
1990 /// to go through the redirect of checking the ctor's attributes - but compiling a small crate
1991 /// requires loading the `AdtDef`s for all the structs in the universe (e.g., coherence for any
1992 /// built-in trait), and we do not want to load attributes twice.
1994 /// If someone speeds up attribute loading to not be a performance concern, they can
1995 /// remove this hack and use the constructor `DefId` everywhere.
1999 variant_did: Option<DefId>,
2000 ctor_def_id: Option<DefId>,
2001 discr: VariantDiscr,
2002 fields: Vec<FieldDef>,
2003 ctor_kind: CtorKind,
2009 "VariantDef::new(ident = {:?}, variant_did = {:?}, ctor_def_id = {:?}, discr = {:?},
2010 fields = {:?}, ctor_kind = {:?}, adt_kind = {:?}, parent_did = {:?})",
2011 ident, variant_did, ctor_def_id, discr, fields, ctor_kind, adt_kind, parent_did,
2014 let mut flags = VariantFlags::NO_VARIANT_FLAGS;
2015 if adt_kind == AdtKind::Struct && tcx.has_attr(parent_did, sym::non_exhaustive) {
2016 debug!("found non-exhaustive field list for {:?}", parent_did);
2017 flags = flags | VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE;
2018 } else if let Some(variant_did) = variant_did {
2019 if tcx.has_attr(variant_did, sym::non_exhaustive) {
2020 debug!("found non-exhaustive field list for {:?}", variant_did);
2021 flags = flags | VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE;
2026 def_id: variant_did.unwrap_or(parent_did),
2037 /// Is this field list non-exhaustive?
2039 pub fn is_field_list_non_exhaustive(&self) -> bool {
2040 self.flags.intersects(VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE)
2044 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2045 pub enum VariantDiscr {
2046 /// Explicit value for this variant, i.e., `X = 123`.
2047 /// The `DefId` corresponds to the embedded constant.
2050 /// The previous variant's discriminant plus one.
2051 /// For efficiency reasons, the distance from the
2052 /// last `Explicit` discriminant is being stored,
2053 /// or `0` for the first variant, if it has none.
2057 #[derive(Debug, HashStable)]
2058 pub struct FieldDef {
2060 #[stable_hasher(project(name))]
2062 pub vis: Visibility,
2065 /// The definition of a user-defined type, e.g., a `struct`, `enum`, or `union`.
2067 /// These are all interned (by `intern_adt_def`) into the `adt_defs` table.
2069 /// The initialism *ADT* stands for an [*algebraic data type (ADT)*][adt].
2070 /// This is slightly wrong because `union`s are not ADTs.
2071 /// Moreover, Rust only allows recursive data types through indirection.
2073 /// [adt]: https://en.wikipedia.org/wiki/Algebraic_data_type
2075 /// The `DefId` of the struct, enum or union item.
2077 /// Variants of the ADT. If this is a struct or union, then there will be a single variant.
2078 pub variants: IndexVec<self::layout::VariantIdx, VariantDef>,
2079 /// Flags of the ADT (e.g., is this a struct? is this non-exhaustive?).
2081 /// Repr options provided by the user.
2082 pub repr: ReprOptions,
2085 impl PartialOrd for AdtDef {
2086 fn partial_cmp(&self, other: &AdtDef) -> Option<Ordering> {
2087 Some(self.cmp(&other))
2091 /// There should be only one AdtDef for each `did`, therefore
2092 /// it is fine to implement `Ord` only based on `did`.
2093 impl Ord for AdtDef {
2094 fn cmp(&self, other: &AdtDef) -> Ordering {
2095 self.did.cmp(&other.did)
2099 impl PartialEq for AdtDef {
2100 // `AdtDef`s are always interned, and this is part of `TyS` equality.
2102 fn eq(&self, other: &Self) -> bool {
2103 ptr::eq(self, other)
2107 impl Eq for AdtDef {}
2109 impl Hash for AdtDef {
2111 fn hash<H: Hasher>(&self, s: &mut H) {
2112 (self as *const AdtDef).hash(s)
2116 impl<'tcx> rustc_serialize::UseSpecializedEncodable for &'tcx AdtDef {
2117 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
2122 impl<'tcx> rustc_serialize::UseSpecializedDecodable for &'tcx AdtDef {}
2124 impl<'a> HashStable<StableHashingContext<'a>> for AdtDef {
2125 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
2127 static CACHE: RefCell<FxHashMap<usize, Fingerprint>> = Default::default();
2130 let hash: Fingerprint = CACHE.with(|cache| {
2131 let addr = self as *const AdtDef as usize;
2132 *cache.borrow_mut().entry(addr).or_insert_with(|| {
2133 let ty::AdtDef { did, ref variants, ref flags, ref repr } = *self;
2135 let mut hasher = StableHasher::new();
2136 did.hash_stable(hcx, &mut hasher);
2137 variants.hash_stable(hcx, &mut hasher);
2138 flags.hash_stable(hcx, &mut hasher);
2139 repr.hash_stable(hcx, &mut hasher);
2145 hash.hash_stable(hcx, hasher);
2149 #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
2156 impl Into<DataTypeKind> for AdtKind {
2157 fn into(self) -> DataTypeKind {
2159 AdtKind::Struct => DataTypeKind::Struct,
2160 AdtKind::Union => DataTypeKind::Union,
2161 AdtKind::Enum => DataTypeKind::Enum,
2167 #[derive(RustcEncodable, RustcDecodable, Default, HashStable)]
2168 pub struct ReprFlags: u8 {
2169 const IS_C = 1 << 0;
2170 const IS_SIMD = 1 << 1;
2171 const IS_TRANSPARENT = 1 << 2;
2172 // Internal only for now. If true, don't reorder fields.
2173 const IS_LINEAR = 1 << 3;
2174 // If true, don't expose any niche to type's context.
2175 const HIDE_NICHE = 1 << 4;
2176 // Any of these flags being set prevent field reordering optimisation.
2177 const IS_UNOPTIMISABLE = ReprFlags::IS_C.bits |
2178 ReprFlags::IS_SIMD.bits |
2179 ReprFlags::IS_LINEAR.bits;
2183 /// Represents the repr options provided by the user,
2184 #[derive(Copy, Clone, Debug, Eq, PartialEq, RustcEncodable, RustcDecodable, Default, HashStable)]
2185 pub struct ReprOptions {
2186 pub int: Option<attr::IntType>,
2187 pub align: Option<Align>,
2188 pub pack: Option<Align>,
2189 pub flags: ReprFlags,
2193 pub fn new(tcx: TyCtxt<'_>, did: DefId) -> ReprOptions {
2194 let mut flags = ReprFlags::empty();
2195 let mut size = None;
2196 let mut max_align: Option<Align> = None;
2197 let mut min_pack: Option<Align> = None;
2198 for attr in tcx.get_attrs(did).iter() {
2199 for r in attr::find_repr_attrs(&tcx.sess.parse_sess, attr) {
2200 flags.insert(match r {
2201 attr::ReprC => ReprFlags::IS_C,
2202 attr::ReprPacked(pack) => {
2203 let pack = Align::from_bytes(pack as u64).unwrap();
2204 min_pack = Some(if let Some(min_pack) = min_pack {
2211 attr::ReprTransparent => ReprFlags::IS_TRANSPARENT,
2212 attr::ReprNoNiche => ReprFlags::HIDE_NICHE,
2213 attr::ReprSimd => ReprFlags::IS_SIMD,
2214 attr::ReprInt(i) => {
2218 attr::ReprAlign(align) => {
2219 max_align = max_align.max(Some(Align::from_bytes(align as u64).unwrap()));
2226 // This is here instead of layout because the choice must make it into metadata.
2227 if !tcx.consider_optimizing(|| format!("Reorder fields of {:?}", tcx.def_path_str(did))) {
2228 flags.insert(ReprFlags::IS_LINEAR);
2230 ReprOptions { int: size, align: max_align, pack: min_pack, flags }
2234 pub fn simd(&self) -> bool {
2235 self.flags.contains(ReprFlags::IS_SIMD)
2238 pub fn c(&self) -> bool {
2239 self.flags.contains(ReprFlags::IS_C)
2242 pub fn packed(&self) -> bool {
2246 pub fn transparent(&self) -> bool {
2247 self.flags.contains(ReprFlags::IS_TRANSPARENT)
2250 pub fn linear(&self) -> bool {
2251 self.flags.contains(ReprFlags::IS_LINEAR)
2254 pub fn hide_niche(&self) -> bool {
2255 self.flags.contains(ReprFlags::HIDE_NICHE)
2258 pub fn discr_type(&self) -> attr::IntType {
2259 self.int.unwrap_or(attr::SignedInt(ast::IntTy::Isize))
2262 /// Returns `true` if this `#[repr()]` should inhabit "smart enum
2263 /// layout" optimizations, such as representing `Foo<&T>` as a
2265 pub fn inhibit_enum_layout_opt(&self) -> bool {
2266 self.c() || self.int.is_some()
2269 /// Returns `true` if this `#[repr()]` should inhibit struct field reordering
2270 /// optimizations, such as with `repr(C)`, `repr(packed(1))`, or `repr(<int>)`.
2271 pub fn inhibit_struct_field_reordering_opt(&self) -> bool {
2272 if let Some(pack) = self.pack {
2273 if pack.bytes() == 1 {
2277 self.flags.intersects(ReprFlags::IS_UNOPTIMISABLE) || self.int.is_some()
2280 /// Returns `true` if this `#[repr()]` should inhibit union ABI optimisations.
2281 pub fn inhibit_union_abi_opt(&self) -> bool {
2287 /// Creates a new `AdtDef`.
2292 variants: IndexVec<VariantIdx, VariantDef>,
2295 debug!("AdtDef::new({:?}, {:?}, {:?}, {:?})", did, kind, variants, repr);
2296 let mut flags = AdtFlags::NO_ADT_FLAGS;
2298 if kind == AdtKind::Enum && tcx.has_attr(did, sym::non_exhaustive) {
2299 debug!("found non-exhaustive variant list for {:?}", did);
2300 flags = flags | AdtFlags::IS_VARIANT_LIST_NON_EXHAUSTIVE;
2303 flags |= match kind {
2304 AdtKind::Enum => AdtFlags::IS_ENUM,
2305 AdtKind::Union => AdtFlags::IS_UNION,
2306 AdtKind::Struct => AdtFlags::IS_STRUCT,
2309 if kind == AdtKind::Struct && variants[VariantIdx::new(0)].ctor_def_id.is_some() {
2310 flags |= AdtFlags::HAS_CTOR;
2313 let attrs = tcx.get_attrs(did);
2314 if attr::contains_name(&attrs, sym::fundamental) {
2315 flags |= AdtFlags::IS_FUNDAMENTAL;
2317 if Some(did) == tcx.lang_items().phantom_data() {
2318 flags |= AdtFlags::IS_PHANTOM_DATA;
2320 if Some(did) == tcx.lang_items().owned_box() {
2321 flags |= AdtFlags::IS_BOX;
2323 if Some(did) == tcx.lang_items().manually_drop() {
2324 flags |= AdtFlags::IS_MANUALLY_DROP;
2326 if Some(did) == tcx.lang_items().arc() {
2327 flags |= AdtFlags::IS_ARC;
2329 if Some(did) == tcx.lang_items().rc() {
2330 flags |= AdtFlags::IS_RC;
2333 AdtDef { did, variants, flags, repr }
2336 /// Returns `true` if this is a struct.
2338 pub fn is_struct(&self) -> bool {
2339 self.flags.contains(AdtFlags::IS_STRUCT)
2342 /// Returns `true` if this is a union.
2344 pub fn is_union(&self) -> bool {
2345 self.flags.contains(AdtFlags::IS_UNION)
2348 /// Returns `true` if this is a enum.
2350 pub fn is_enum(&self) -> bool {
2351 self.flags.contains(AdtFlags::IS_ENUM)
2354 /// Returns `true` if the variant list of this ADT is `#[non_exhaustive]`.
2356 pub fn is_variant_list_non_exhaustive(&self) -> bool {
2357 self.flags.contains(AdtFlags::IS_VARIANT_LIST_NON_EXHAUSTIVE)
2360 /// Returns the kind of the ADT.
2362 pub fn adt_kind(&self) -> AdtKind {
2365 } else if self.is_union() {
2372 /// Returns a description of this abstract data type.
2373 pub fn descr(&self) -> &'static str {
2374 match self.adt_kind() {
2375 AdtKind::Struct => "struct",
2376 AdtKind::Union => "union",
2377 AdtKind::Enum => "enum",
2381 /// Returns a description of a variant of this abstract data type.
2383 pub fn variant_descr(&self) -> &'static str {
2384 match self.adt_kind() {
2385 AdtKind::Struct => "struct",
2386 AdtKind::Union => "union",
2387 AdtKind::Enum => "variant",
2391 /// If this function returns `true`, it implies that `is_struct` must return `true`.
2393 pub fn has_ctor(&self) -> bool {
2394 self.flags.contains(AdtFlags::HAS_CTOR)
2397 /// Returns `true` if this type is `#[fundamental]` for the purposes
2398 /// of coherence checking.
2400 pub fn is_fundamental(&self) -> bool {
2401 self.flags.contains(AdtFlags::IS_FUNDAMENTAL)
2404 /// Returns `true` if this is `PhantomData<T>`.
2406 pub fn is_phantom_data(&self) -> bool {
2407 self.flags.contains(AdtFlags::IS_PHANTOM_DATA)
2410 /// Returns `true` if this is `Arc<T>`.
2411 pub fn is_arc(&self) -> bool {
2412 self.flags.contains(AdtFlags::IS_ARC)
2415 /// Returns `true` if this is `Rc<T>`.
2416 pub fn is_rc(&self) -> bool {
2417 self.flags.contains(AdtFlags::IS_RC)
2420 /// Returns `true` if this is Box<T>.
2422 pub fn is_box(&self) -> bool {
2423 self.flags.contains(AdtFlags::IS_BOX)
2426 /// Returns `true` if this is `ManuallyDrop<T>`.
2428 pub fn is_manually_drop(&self) -> bool {
2429 self.flags.contains(AdtFlags::IS_MANUALLY_DROP)
2432 /// Returns `true` if this type has a destructor.
2433 pub fn has_dtor(&self, tcx: TyCtxt<'tcx>) -> bool {
2434 self.destructor(tcx).is_some()
2437 /// Asserts this is a struct or union and returns its unique variant.
2438 pub fn non_enum_variant(&self) -> &VariantDef {
2439 assert!(self.is_struct() || self.is_union());
2440 &self.variants[VariantIdx::new(0)]
2444 pub fn predicates(&self, tcx: TyCtxt<'tcx>) -> GenericPredicates<'tcx> {
2445 tcx.predicates_of(self.did)
2448 /// Returns an iterator over all fields contained
2451 pub fn all_fields(&self) -> impl Iterator<Item = &FieldDef> + Clone {
2452 self.variants.iter().flat_map(|v| v.fields.iter())
2455 pub fn is_payloadfree(&self) -> bool {
2456 !self.variants.is_empty() && self.variants.iter().all(|v| v.fields.is_empty())
2459 /// Return a `VariantDef` given a variant id.
2460 pub fn variant_with_id(&self, vid: DefId) -> &VariantDef {
2461 self.variants.iter().find(|v| v.def_id == vid).expect("variant_with_id: unknown variant")
2464 /// Return a `VariantDef` given a constructor id.
2465 pub fn variant_with_ctor_id(&self, cid: DefId) -> &VariantDef {
2468 .find(|v| v.ctor_def_id == Some(cid))
2469 .expect("variant_with_ctor_id: unknown variant")
2472 /// Return the index of `VariantDef` given a variant id.
2473 pub fn variant_index_with_id(&self, vid: DefId) -> VariantIdx {
2476 .find(|(_, v)| v.def_id == vid)
2477 .expect("variant_index_with_id: unknown variant")
2481 /// Return the index of `VariantDef` given a constructor id.
2482 pub fn variant_index_with_ctor_id(&self, cid: DefId) -> VariantIdx {
2485 .find(|(_, v)| v.ctor_def_id == Some(cid))
2486 .expect("variant_index_with_ctor_id: unknown variant")
2490 pub fn variant_of_res(&self, res: Res) -> &VariantDef {
2492 Res::Def(DefKind::Variant, vid) => self.variant_with_id(vid),
2493 Res::Def(DefKind::Ctor(..), cid) => self.variant_with_ctor_id(cid),
2494 Res::Def(DefKind::Struct, _)
2495 | Res::Def(DefKind::Union, _)
2496 | Res::Def(DefKind::TyAlias, _)
2497 | Res::Def(DefKind::AssocTy, _)
2499 | Res::SelfCtor(..) => self.non_enum_variant(),
2500 _ => bug!("unexpected res {:?} in variant_of_res", res),
2505 pub fn eval_explicit_discr(&self, tcx: TyCtxt<'tcx>, expr_did: DefId) -> Option<Discr<'tcx>> {
2506 let param_env = tcx.param_env(expr_did);
2507 let repr_type = self.repr.discr_type();
2508 match tcx.const_eval_poly(expr_did) {
2510 let ty = repr_type.to_ty(tcx);
2511 if let Some(b) = val.try_to_bits_for_ty(tcx, param_env, ty) {
2512 trace!("discriminants: {} ({:?})", b, repr_type);
2513 Some(Discr { val: b, ty })
2515 info!("invalid enum discriminant: {:#?}", val);
2516 crate::mir::interpret::struct_error(
2517 tcx.at(tcx.def_span(expr_did)),
2518 "constant evaluation of enum discriminant resulted in non-integer",
2524 Err(ErrorHandled::Reported) => {
2525 if !expr_did.is_local() {
2527 tcx.def_span(expr_did),
2528 "variant discriminant evaluation succeeded \
2529 in its crate but failed locally"
2534 Err(ErrorHandled::TooGeneric) => {
2535 span_bug!(tcx.def_span(expr_did), "enum discriminant depends on generic arguments",)
2541 pub fn discriminants(
2544 ) -> impl Iterator<Item = (VariantIdx, Discr<'tcx>)> + Captures<'tcx> {
2545 let repr_type = self.repr.discr_type();
2546 let initial = repr_type.initial_discriminant(tcx);
2547 let mut prev_discr = None::<Discr<'tcx>>;
2548 self.variants.iter_enumerated().map(move |(i, v)| {
2549 let mut discr = prev_discr.map_or(initial, |d| d.wrap_incr(tcx));
2550 if let VariantDiscr::Explicit(expr_did) = v.discr {
2551 if let Some(new_discr) = self.eval_explicit_discr(tcx, expr_did) {
2555 prev_discr = Some(discr);
2562 pub fn variant_range(&self) -> Range<VariantIdx> {
2563 VariantIdx::new(0)..VariantIdx::new(self.variants.len())
2566 /// Computes the discriminant value used by a specific variant.
2567 /// Unlike `discriminants`, this is (amortized) constant-time,
2568 /// only doing at most one query for evaluating an explicit
2569 /// discriminant (the last one before the requested variant),
2570 /// assuming there are no constant-evaluation errors there.
2572 pub fn discriminant_for_variant(
2575 variant_index: VariantIdx,
2577 let (val, offset) = self.discriminant_def_for_variant(variant_index);
2578 let explicit_value = val
2579 .and_then(|expr_did| self.eval_explicit_discr(tcx, expr_did))
2580 .unwrap_or_else(|| self.repr.discr_type().initial_discriminant(tcx));
2581 explicit_value.checked_add(tcx, offset as u128).0
2584 /// Yields a `DefId` for the discriminant and an offset to add to it
2585 /// Alternatively, if there is no explicit discriminant, returns the
2586 /// inferred discriminant directly.
2587 pub fn discriminant_def_for_variant(&self, variant_index: VariantIdx) -> (Option<DefId>, u32) {
2588 let mut explicit_index = variant_index.as_u32();
2591 match self.variants[VariantIdx::from_u32(explicit_index)].discr {
2592 ty::VariantDiscr::Relative(0) => {
2596 ty::VariantDiscr::Relative(distance) => {
2597 explicit_index -= distance;
2599 ty::VariantDiscr::Explicit(did) => {
2600 expr_did = Some(did);
2605 (expr_did, variant_index.as_u32() - explicit_index)
2608 pub fn destructor(&self, tcx: TyCtxt<'tcx>) -> Option<Destructor> {
2609 tcx.adt_destructor(self.did)
2612 /// Returns a list of types such that `Self: Sized` if and only
2613 /// if that type is `Sized`, or `TyErr` if this type is recursive.
2615 /// Oddly enough, checking that the sized-constraint is `Sized` is
2616 /// actually more expressive than checking all members:
2617 /// the `Sized` trait is inductive, so an associated type that references
2618 /// `Self` would prevent its containing ADT from being `Sized`.
2620 /// Due to normalization being eager, this applies even if
2621 /// the associated type is behind a pointer (e.g., issue #31299).
2622 pub fn sized_constraint(&self, tcx: TyCtxt<'tcx>) -> &'tcx [Ty<'tcx>] {
2623 tcx.adt_sized_constraint(self.did).0
2627 impl<'tcx> FieldDef {
2628 /// Returns the type of this field. The `subst` is typically obtained
2629 /// via the second field of `TyKind::AdtDef`.
2630 pub fn ty(&self, tcx: TyCtxt<'tcx>, subst: SubstsRef<'tcx>) -> Ty<'tcx> {
2631 tcx.type_of(self.did).subst(tcx, subst)
2635 /// Represents the various closure traits in the language. This
2636 /// will determine the type of the environment (`self`, in the
2637 /// desugaring) argument that the closure expects.
2639 /// You can get the environment type of a closure using
2640 /// `tcx.closure_env_ty()`.
2654 pub enum ClosureKind {
2655 // Warning: Ordering is significant here! The ordering is chosen
2656 // because the trait Fn is a subtrait of FnMut and so in turn, and
2657 // hence we order it so that Fn < FnMut < FnOnce.
2663 impl<'tcx> ClosureKind {
2664 // This is the initial value used when doing upvar inference.
2665 pub const LATTICE_BOTTOM: ClosureKind = ClosureKind::Fn;
2667 pub fn trait_did(&self, tcx: TyCtxt<'tcx>) -> DefId {
2669 ClosureKind::Fn => tcx.require_lang_item(FnTraitLangItem, None),
2670 ClosureKind::FnMut => tcx.require_lang_item(FnMutTraitLangItem, None),
2671 ClosureKind::FnOnce => tcx.require_lang_item(FnOnceTraitLangItem, None),
2675 /// Returns `true` if this a type that impls this closure kind
2676 /// must also implement `other`.
2677 pub fn extends(self, other: ty::ClosureKind) -> bool {
2678 match (self, other) {
2679 (ClosureKind::Fn, ClosureKind::Fn) => true,
2680 (ClosureKind::Fn, ClosureKind::FnMut) => true,
2681 (ClosureKind::Fn, ClosureKind::FnOnce) => true,
2682 (ClosureKind::FnMut, ClosureKind::FnMut) => true,
2683 (ClosureKind::FnMut, ClosureKind::FnOnce) => true,
2684 (ClosureKind::FnOnce, ClosureKind::FnOnce) => true,
2689 /// Returns the representative scalar type for this closure kind.
2690 /// See `TyS::to_opt_closure_kind` for more details.
2691 pub fn to_ty(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
2693 ty::ClosureKind::Fn => tcx.types.i8,
2694 ty::ClosureKind::FnMut => tcx.types.i16,
2695 ty::ClosureKind::FnOnce => tcx.types.i32,
2700 impl<'tcx> TyS<'tcx> {
2701 /// Iterator that walks `self` and any types reachable from
2702 /// `self`, in depth-first order. Note that just walks the types
2703 /// that appear in `self`, it does not descend into the fields of
2704 /// structs or variants. For example:
2707 /// isize => { isize }
2708 /// Foo<Bar<isize>> => { Foo<Bar<isize>>, Bar<isize>, isize }
2709 /// [isize] => { [isize], isize }
2711 pub fn walk(&'tcx self) -> TypeWalker<'tcx> {
2712 TypeWalker::new(self)
2715 /// Iterator that walks the immediate children of `self`. Hence
2716 /// `Foo<Bar<i32>, u32>` yields the sequence `[Bar<i32>, u32]`
2717 /// (but not `i32`, like `walk`).
2718 pub fn walk_shallow(&'tcx self) -> smallvec::IntoIter<walk::TypeWalkerArray<'tcx>> {
2719 walk::walk_shallow(self)
2722 /// Walks `ty` and any types appearing within `ty`, invoking the
2723 /// callback `f` on each type. If the callback returns `false`, then the
2724 /// children of the current type are ignored.
2726 /// Note: prefer `ty.walk()` where possible.
2727 pub fn maybe_walk<F>(&'tcx self, mut f: F)
2729 F: FnMut(Ty<'tcx>) -> bool,
2731 let mut walker = self.walk();
2732 while let Some(ty) = walker.next() {
2734 walker.skip_current_subtree();
2741 pub fn from_mutbl(m: hir::Mutability) -> BorrowKind {
2743 hir::Mutability::Mut => MutBorrow,
2744 hir::Mutability::Not => ImmBorrow,
2748 /// Returns a mutability `m` such that an `&m T` pointer could be used to obtain this borrow
2749 /// kind. Because borrow kinds are richer than mutabilities, we sometimes have to pick a
2750 /// mutability that is stronger than necessary so that it at least *would permit* the borrow in
2752 pub fn to_mutbl_lossy(self) -> hir::Mutability {
2754 MutBorrow => hir::Mutability::Mut,
2755 ImmBorrow => hir::Mutability::Not,
2757 // We have no type corresponding to a unique imm borrow, so
2758 // use `&mut`. It gives all the capabilities of an `&uniq`
2759 // and hence is a safe "over approximation".
2760 UniqueImmBorrow => hir::Mutability::Mut,
2764 pub fn to_user_str(&self) -> &'static str {
2766 MutBorrow => "mutable",
2767 ImmBorrow => "immutable",
2768 UniqueImmBorrow => "uniquely immutable",
2773 #[derive(Debug, Clone)]
2774 pub enum Attributes<'tcx> {
2775 Owned(Lrc<[ast::Attribute]>),
2776 Borrowed(&'tcx [ast::Attribute]),
2779 impl<'tcx> ::std::ops::Deref for Attributes<'tcx> {
2780 type Target = [ast::Attribute];
2782 fn deref(&self) -> &[ast::Attribute] {
2784 &Attributes::Owned(ref data) => &data,
2785 &Attributes::Borrowed(data) => data,
2790 #[derive(Debug, PartialEq, Eq)]
2791 pub enum ImplOverlapKind {
2792 /// These impls are always allowed to overlap.
2794 /// Whether or not the impl is permitted due to the trait being a `#[marker]` trait
2797 /// These impls are allowed to overlap, but that raises
2798 /// an issue #33140 future-compatibility warning.
2800 /// Some background: in Rust 1.0, the trait-object types `Send + Sync` (today's
2801 /// `dyn Send + Sync`) and `Sync + Send` (now `dyn Sync + Send`) were different.
2803 /// The widely-used version 0.1.0 of the crate `traitobject` had accidentally relied
2804 /// that difference, making what reduces to the following set of impls:
2808 /// impl Trait for dyn Send + Sync {}
2809 /// impl Trait for dyn Sync + Send {}
2812 /// Obviously, once we made these types be identical, that code causes a coherence
2813 /// error and a fairly big headache for us. However, luckily for us, the trait
2814 /// `Trait` used in this case is basically a marker trait, and therefore having
2815 /// overlapping impls for it is sound.
2817 /// To handle this, we basically regard the trait as a marker trait, with an additional
2818 /// future-compatibility warning. To avoid accidentally "stabilizing" this feature,
2819 /// it has the following restrictions:
2821 /// 1. The trait must indeed be a marker-like trait (i.e., no items), and must be
2823 /// 2. The trait-ref of both impls must be equal.
2824 /// 3. The trait-ref of both impls must be a trait object type consisting only of
2826 /// 4. Neither of the impls can have any where-clauses.
2828 /// Once `traitobject` 0.1.0 is no longer an active concern, this hack can be removed.
2832 impl<'tcx> TyCtxt<'tcx> {
2833 pub fn body_tables(self, body: hir::BodyId) -> &'tcx TypeckTables<'tcx> {
2834 self.typeck_tables_of(self.hir().body_owner_def_id(body))
2837 /// Returns an iterator of the `DefId`s for all body-owners in this
2838 /// crate. If you would prefer to iterate over the bodies
2839 /// themselves, you can do `self.hir().krate().body_ids.iter()`.
2840 pub fn body_owners(self) -> impl Iterator<Item = DefId> + Captures<'tcx> + 'tcx {
2845 .map(move |&body_id| self.hir().body_owner_def_id(body_id))
2848 pub fn par_body_owners<F: Fn(DefId) + sync::Sync + sync::Send>(self, f: F) {
2849 par_iter(&self.hir().krate().body_ids)
2850 .for_each(|&body_id| f(self.hir().body_owner_def_id(body_id)));
2853 pub fn provided_trait_methods(self, id: DefId) -> impl 'tcx + Iterator<Item = &'tcx AssocItem> {
2854 self.associated_items(id)
2855 .in_definition_order()
2856 .filter(|item| item.kind == AssocKind::Method && item.defaultness.has_value())
2859 pub fn trait_relevant_for_never(self, did: DefId) -> bool {
2860 self.associated_items(did).in_definition_order().any(|item| item.relevant_for_never())
2863 pub fn opt_item_name(self, def_id: DefId) -> Option<Ident> {
2864 self.hir().as_local_hir_id(def_id).and_then(|hir_id| self.hir().get(hir_id).ident())
2867 pub fn opt_associated_item(self, def_id: DefId) -> Option<AssocItem> {
2868 let is_associated_item = if let Some(hir_id) = self.hir().as_local_hir_id(def_id) {
2869 match self.hir().get(hir_id) {
2870 Node::TraitItem(_) | Node::ImplItem(_) => true,
2874 match self.def_kind(def_id).expect("no def for `DefId`") {
2875 DefKind::AssocConst | DefKind::Method | DefKind::AssocTy => true,
2880 is_associated_item.then(|| self.associated_item(def_id))
2883 pub fn field_index(self, hir_id: hir::HirId, tables: &TypeckTables<'_>) -> usize {
2884 tables.field_indices().get(hir_id).cloned().expect("no index for a field")
2887 pub fn find_field_index(self, ident: Ident, variant: &VariantDef) -> Option<usize> {
2888 variant.fields.iter().position(|field| self.hygienic_eq(ident, field.ident, variant.def_id))
2891 /// Returns `true` if the impls are the same polarity and the trait either
2892 /// has no items or is annotated #[marker] and prevents item overrides.
2893 pub fn impls_are_allowed_to_overlap(
2897 ) -> Option<ImplOverlapKind> {
2898 // If either trait impl references an error, they're allowed to overlap,
2899 // as one of them essentially doesn't exist.
2900 if self.impl_trait_ref(def_id1).map_or(false, |tr| tr.references_error())
2901 || self.impl_trait_ref(def_id2).map_or(false, |tr| tr.references_error())
2903 return Some(ImplOverlapKind::Permitted { marker: false });
2906 match (self.impl_polarity(def_id1), self.impl_polarity(def_id2)) {
2907 (ImplPolarity::Reservation, _) | (_, ImplPolarity::Reservation) => {
2908 // `#[rustc_reservation_impl]` impls don't overlap with anything
2910 "impls_are_allowed_to_overlap({:?}, {:?}) = Some(Permitted) (reservations)",
2913 return Some(ImplOverlapKind::Permitted { marker: false });
2915 (ImplPolarity::Positive, ImplPolarity::Negative)
2916 | (ImplPolarity::Negative, ImplPolarity::Positive) => {
2917 // `impl AutoTrait for Type` + `impl !AutoTrait for Type`
2919 "impls_are_allowed_to_overlap({:?}, {:?}) - None (differing polarities)",
2924 (ImplPolarity::Positive, ImplPolarity::Positive)
2925 | (ImplPolarity::Negative, ImplPolarity::Negative) => {}
2928 let is_marker_overlap = {
2929 let is_marker_impl = |def_id: DefId| -> bool {
2930 let trait_ref = self.impl_trait_ref(def_id);
2931 trait_ref.map_or(false, |tr| self.trait_def(tr.def_id).is_marker)
2933 is_marker_impl(def_id1) && is_marker_impl(def_id2)
2936 if is_marker_overlap {
2938 "impls_are_allowed_to_overlap({:?}, {:?}) = Some(Permitted) (marker overlap)",
2941 Some(ImplOverlapKind::Permitted { marker: true })
2943 if let Some(self_ty1) = self.issue33140_self_ty(def_id1) {
2944 if let Some(self_ty2) = self.issue33140_self_ty(def_id2) {
2945 if self_ty1 == self_ty2 {
2947 "impls_are_allowed_to_overlap({:?}, {:?}) - issue #33140 HACK",
2950 return Some(ImplOverlapKind::Issue33140);
2953 "impls_are_allowed_to_overlap({:?}, {:?}) - found {:?} != {:?}",
2954 def_id1, def_id2, self_ty1, self_ty2
2960 debug!("impls_are_allowed_to_overlap({:?}, {:?}) = None", def_id1, def_id2);
2965 /// Returns `ty::VariantDef` if `res` refers to a struct,
2966 /// or variant or their constructors, panics otherwise.
2967 pub fn expect_variant_res(self, res: Res) -> &'tcx VariantDef {
2969 Res::Def(DefKind::Variant, did) => {
2970 let enum_did = self.parent(did).unwrap();
2971 self.adt_def(enum_did).variant_with_id(did)
2973 Res::Def(DefKind::Struct, did) | Res::Def(DefKind::Union, did) => {
2974 self.adt_def(did).non_enum_variant()
2976 Res::Def(DefKind::Ctor(CtorOf::Variant, ..), variant_ctor_did) => {
2977 let variant_did = self.parent(variant_ctor_did).unwrap();
2978 let enum_did = self.parent(variant_did).unwrap();
2979 self.adt_def(enum_did).variant_with_ctor_id(variant_ctor_did)
2981 Res::Def(DefKind::Ctor(CtorOf::Struct, ..), ctor_did) => {
2982 let struct_did = self.parent(ctor_did).expect("struct ctor has no parent");
2983 self.adt_def(struct_did).non_enum_variant()
2985 _ => bug!("expect_variant_res used with unexpected res {:?}", res),
2989 pub fn item_name(self, id: DefId) -> Symbol {
2990 if id.index == CRATE_DEF_INDEX {
2991 self.original_crate_name(id.krate)
2993 let def_key = self.def_key(id);
2994 match def_key.disambiguated_data.data {
2995 // The name of a constructor is that of its parent.
2996 hir_map::DefPathData::Ctor => {
2997 self.item_name(DefId { krate: id.krate, index: def_key.parent.unwrap() })
2999 _ => def_key.disambiguated_data.data.get_opt_name().unwrap_or_else(|| {
3000 bug!("item_name: no name for {:?}", self.def_path(id));
3006 /// Returns the possibly-auto-generated MIR of a `(DefId, Subst)` pair.
3007 pub fn instance_mir(self, instance: ty::InstanceDef<'tcx>) -> ReadOnlyBodyAndCache<'tcx, 'tcx> {
3009 ty::InstanceDef::Item(did) => self.optimized_mir(did).unwrap_read_only(),
3010 ty::InstanceDef::VtableShim(..)
3011 | ty::InstanceDef::ReifyShim(..)
3012 | ty::InstanceDef::Intrinsic(..)
3013 | ty::InstanceDef::FnPtrShim(..)
3014 | ty::InstanceDef::Virtual(..)
3015 | ty::InstanceDef::ClosureOnceShim { .. }
3016 | ty::InstanceDef::DropGlue(..)
3017 | ty::InstanceDef::CloneShim(..) => self.mir_shims(instance).unwrap_read_only(),
3021 /// Gets the attributes of a definition.
3022 pub fn get_attrs(self, did: DefId) -> Attributes<'tcx> {
3023 if let Some(id) = self.hir().as_local_hir_id(did) {
3024 Attributes::Borrowed(self.hir().attrs(id))
3026 Attributes::Owned(self.item_attrs(did))
3030 /// Determines whether an item is annotated with an attribute.
3031 pub fn has_attr(self, did: DefId, attr: Symbol) -> bool {
3032 attr::contains_name(&self.get_attrs(did), attr)
3035 /// Returns `true` if this is an `auto trait`.
3036 pub fn trait_is_auto(self, trait_def_id: DefId) -> bool {
3037 self.trait_def(trait_def_id).has_auto_impl
3040 pub fn generator_layout(self, def_id: DefId) -> &'tcx GeneratorLayout<'tcx> {
3041 self.optimized_mir(def_id).generator_layout.as_ref().unwrap()
3044 /// Given the `DefId` of an impl, returns the `DefId` of the trait it implements.
3045 /// If it implements no trait, returns `None`.
3046 pub fn trait_id_of_impl(self, def_id: DefId) -> Option<DefId> {
3047 self.impl_trait_ref(def_id).map(|tr| tr.def_id)
3050 /// If the given defid describes a method belonging to an impl, returns the
3051 /// `DefId` of the impl that the method belongs to; otherwise, returns `None`.
3052 pub fn impl_of_method(self, def_id: DefId) -> Option<DefId> {
3053 let item = if def_id.krate != LOCAL_CRATE {
3054 if let Some(DefKind::Method) = self.def_kind(def_id) {
3055 Some(self.associated_item(def_id))
3060 self.opt_associated_item(def_id)
3063 item.and_then(|trait_item| match trait_item.container {
3064 TraitContainer(_) => None,
3065 ImplContainer(def_id) => Some(def_id),
3069 /// Looks up the span of `impl_did` if the impl is local; otherwise returns `Err`
3070 /// with the name of the crate containing the impl.
3071 pub fn span_of_impl(self, impl_did: DefId) -> Result<Span, Symbol> {
3072 if impl_did.is_local() {
3073 let hir_id = self.hir().as_local_hir_id(impl_did).unwrap();
3074 Ok(self.hir().span(hir_id))
3076 Err(self.crate_name(impl_did.krate))
3080 /// Hygienically compares a use-site name (`use_name`) for a field or an associated item with
3081 /// its supposed definition name (`def_name`). The method also needs `DefId` of the supposed
3082 /// definition's parent/scope to perform comparison.
3083 pub fn hygienic_eq(self, use_name: Ident, def_name: Ident, def_parent_def_id: DefId) -> bool {
3084 // We could use `Ident::eq` here, but we deliberately don't. The name
3085 // comparison fails frequently, and we want to avoid the expensive
3086 // `modern()` calls required for the span comparison whenever possible.
3087 use_name.name == def_name.name
3091 .hygienic_eq(def_name.span.ctxt(), self.expansion_that_defined(def_parent_def_id))
3094 fn expansion_that_defined(self, scope: DefId) -> ExpnId {
3096 LOCAL_CRATE => self.hir().definitions().expansion_that_defined(scope.index),
3097 _ => ExpnId::root(),
3101 pub fn adjust_ident(self, mut ident: Ident, scope: DefId) -> Ident {
3102 ident.span.modernize_and_adjust(self.expansion_that_defined(scope));
3106 pub fn adjust_ident_and_get_scope(
3111 ) -> (Ident, DefId) {
3112 let scope = match ident.span.modernize_and_adjust(self.expansion_that_defined(scope)) {
3113 Some(actual_expansion) => {
3114 self.hir().definitions().parent_module_of_macro_def(actual_expansion)
3116 None => self.parent_module(block),
3121 pub fn is_object_safe(self, key: DefId) -> bool {
3122 self.object_safety_violations(key).is_empty()
3126 #[derive(Clone, HashStable)]
3127 pub struct AdtSizedConstraint<'tcx>(pub &'tcx [Ty<'tcx>]);
3129 /// Yields the parent function's `DefId` if `def_id` is an `impl Trait` definition.
3130 pub fn is_impl_trait_defn(tcx: TyCtxt<'_>, def_id: DefId) -> Option<DefId> {
3131 if let Some(hir_id) = tcx.hir().as_local_hir_id(def_id) {
3132 if let Node::Item(item) = tcx.hir().get(hir_id) {
3133 if let hir::ItemKind::OpaqueTy(ref opaque_ty) = item.kind {
3134 return opaque_ty.impl_trait_fn;
3141 pub fn provide(providers: &mut ty::query::Providers<'_>) {
3142 context::provide(providers);
3143 erase_regions::provide(providers);
3144 layout::provide(providers);
3146 ty::query::Providers { trait_impls_of: trait_def::trait_impls_of_provider, ..*providers };
3149 /// A map for the local crate mapping each type to a vector of its
3150 /// inherent impls. This is not meant to be used outside of coherence;
3151 /// rather, you should request the vector for a specific type via
3152 /// `tcx.inherent_impls(def_id)` so as to minimize your dependencies
3153 /// (constructing this map requires touching the entire crate).
3154 #[derive(Clone, Debug, Default, HashStable)]
3155 pub struct CrateInherentImpls {
3156 pub inherent_impls: DefIdMap<Vec<DefId>>,
3159 #[derive(Clone, Copy, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
3160 pub struct SymbolName {
3161 // FIXME: we don't rely on interning or equality here - better have
3162 // this be a `&'tcx str`.
3167 pub fn new(name: &str) -> SymbolName {
3168 SymbolName { name: Symbol::intern(name) }
3172 impl PartialOrd for SymbolName {
3173 fn partial_cmp(&self, other: &SymbolName) -> Option<Ordering> {
3174 self.name.as_str().partial_cmp(&other.name.as_str())
3178 /// Ordering must use the chars to ensure reproducible builds.
3179 impl Ord for SymbolName {
3180 fn cmp(&self, other: &SymbolName) -> Ordering {
3181 self.name.as_str().cmp(&other.name.as_str())
3185 impl fmt::Display for SymbolName {
3186 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
3187 fmt::Display::fmt(&self.name, fmt)
3191 impl fmt::Debug for SymbolName {
3192 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
3193 fmt::Display::fmt(&self.name, fmt)