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::ich::StableHashingContext;
12 use crate::infer::canonical::Canonical;
13 use crate::middle::cstore::CrateStoreDyn;
14 use crate::middle::resolve_lifetime::ObjectLifetimeDefault;
15 use crate::mir::interpret::ErrorHandled;
16 use crate::mir::GeneratorLayout;
17 use crate::mir::ReadOnlyBodyAndCache;
18 use crate::traits::{self, Reveal};
20 use crate::ty::subst::{InternalSubsts, Subst, SubstsRef};
21 use crate::ty::util::{Discr, IntTypeExt};
22 use crate::ty::walk::TypeWalker;
23 use rustc_ast::ast::{self, Ident, Name};
24 use rustc_ast::node_id::{NodeId, NodeMap, NodeSet};
25 use rustc_attr as attr;
26 use rustc_data_structures::captures::Captures;
27 use rustc_data_structures::fingerprint::Fingerprint;
28 use rustc_data_structures::fx::FxHashMap;
29 use rustc_data_structures::fx::FxIndexMap;
30 use rustc_data_structures::sorted_map::SortedIndexMultiMap;
31 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
32 use rustc_data_structures::sync::{self, par_iter, Lrc, ParallelIterator};
34 use rustc_hir::def::{CtorKind, CtorOf, DefKind, Namespace, Res};
35 use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, LocalDefId, CRATE_DEF_INDEX};
36 use rustc_hir::lang_items::{FnMutTraitLangItem, FnOnceTraitLangItem, FnTraitLangItem};
37 use rustc_hir::{Constness, GlobMap, Node, TraitMap};
38 use rustc_index::vec::{Idx, IndexVec};
39 use rustc_macros::HashStable;
40 use rustc_serialize::{self, Encodable, Encoder};
41 use rustc_session::DataTypeKind;
42 use rustc_span::hygiene::ExpnId;
43 use rustc_span::symbol::{kw, sym, Symbol};
45 use rustc_target::abi::{Align, VariantIdx};
47 use std::cell::RefCell;
48 use std::cmp::{self, Ordering};
50 use std::hash::{Hash, Hasher};
56 pub use self::sty::BoundRegion::*;
57 pub use self::sty::InferTy::*;
58 pub use self::sty::RegionKind;
59 pub use self::sty::RegionKind::*;
60 pub use self::sty::TyKind::*;
61 pub use self::sty::{Binder, BoundTy, BoundTyKind, BoundVar, DebruijnIndex, INNERMOST};
62 pub use self::sty::{BoundRegion, EarlyBoundRegion, FreeRegion, Region};
63 pub use self::sty::{CanonicalPolyFnSig, FnSig, GenSig, PolyFnSig, PolyGenSig};
64 pub use self::sty::{ClosureSubsts, GeneratorSubsts, TypeAndMut, UpvarSubsts};
65 pub use self::sty::{Const, ConstKind, ExistentialProjection, PolyExistentialProjection};
66 pub use self::sty::{ConstVid, FloatVid, IntVid, RegionVid, TyVid};
67 pub use self::sty::{ExistentialPredicate, InferConst, InferTy, ParamConst, ParamTy, ProjectionTy};
68 pub use self::sty::{ExistentialTraitRef, PolyExistentialTraitRef};
69 pub use self::sty::{PolyTraitRef, TraitRef, TyKind};
70 pub use crate::ty::diagnostics::*;
72 pub use self::binding::BindingMode;
73 pub use self::binding::BindingMode::*;
75 pub use self::context::{keep_local, tls, FreeRegionInfo, TyCtxt};
76 pub use self::context::{
77 CanonicalUserType, CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations, ResolvedOpaqueTy,
78 UserType, UserTypeAnnotationIndex,
80 pub use self::context::{
81 CtxtInterners, GeneratorInteriorTypeCause, GlobalCtxt, Lift, TypeckTables,
84 pub use self::instance::RESOLVE_INSTANCE;
85 pub use self::instance::{Instance, InstanceDef};
87 pub use self::trait_def::TraitDef;
89 pub use self::query::queries;
102 pub mod free_region_map;
103 pub mod inhabitedness;
105 pub mod normalize_erasing_regions;
119 mod structural_impls;
124 pub struct ResolverOutputs {
125 pub definitions: rustc_hir::definitions::Definitions,
126 pub cstore: Box<CrateStoreDyn>,
127 pub extern_crate_map: NodeMap<CrateNum>,
128 pub trait_map: TraitMap<NodeId>,
129 pub maybe_unused_trait_imports: NodeSet,
130 pub maybe_unused_extern_crates: Vec<(NodeId, Span)>,
131 pub export_map: ExportMap<NodeId>,
132 pub glob_map: GlobMap,
133 /// Extern prelude entries. The value is `true` if the entry was introduced
134 /// via `extern crate` item and not `--extern` option or compiler built-in.
135 pub extern_prelude: FxHashMap<Name, bool>,
138 #[derive(Clone, Copy, PartialEq, Eq, Debug, HashStable)]
139 pub enum AssocItemContainer {
140 TraitContainer(DefId),
141 ImplContainer(DefId),
144 impl AssocItemContainer {
145 /// Asserts that this is the `DefId` of an associated item declared
146 /// in a trait, and returns the trait `DefId`.
147 pub fn assert_trait(&self) -> DefId {
149 TraitContainer(id) => id,
150 _ => bug!("associated item has wrong container type: {:?}", self),
154 pub fn id(&self) -> DefId {
156 TraitContainer(id) => id,
157 ImplContainer(id) => id,
162 /// The "header" of an impl is everything outside the body: a Self type, a trait
163 /// ref (in the case of a trait impl), and a set of predicates (from the
164 /// bounds / where-clauses).
165 #[derive(Clone, Debug, TypeFoldable)]
166 pub struct ImplHeader<'tcx> {
167 pub impl_def_id: DefId,
168 pub self_ty: Ty<'tcx>,
169 pub trait_ref: Option<TraitRef<'tcx>>,
170 pub predicates: Vec<Predicate<'tcx>>,
173 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable)]
174 pub enum ImplPolarity {
175 /// `impl Trait for Type`
177 /// `impl !Trait for Type`
179 /// `#[rustc_reservation_impl] impl Trait for Type`
181 /// This is a "stability hack", not a real Rust feature.
182 /// See #64631 for details.
186 #[derive(Copy, Clone, Debug, PartialEq, HashStable)]
187 pub struct AssocItem {
189 #[stable_hasher(project(name))]
193 pub defaultness: hir::Defaultness,
194 pub container: AssocItemContainer,
196 /// Whether this is a method with an explicit self
197 /// as its first argument, allowing method calls.
198 pub method_has_self_argument: bool,
201 #[derive(Copy, Clone, PartialEq, Debug, HashStable)]
210 pub fn suggestion_descr(&self) -> &'static str {
212 ty::AssocKind::Method => "method call",
213 ty::AssocKind::Type | ty::AssocKind::OpaqueTy => "associated type",
214 ty::AssocKind::Const => "associated constant",
218 pub fn namespace(&self) -> Namespace {
220 ty::AssocKind::OpaqueTy | ty::AssocKind::Type => Namespace::TypeNS,
221 ty::AssocKind::Const | ty::AssocKind::Method => Namespace::ValueNS,
227 pub fn def_kind(&self) -> DefKind {
229 AssocKind::Const => DefKind::AssocConst,
230 AssocKind::Method => DefKind::AssocFn,
231 AssocKind::Type => DefKind::AssocTy,
232 AssocKind::OpaqueTy => DefKind::AssocOpaqueTy,
236 /// Tests whether the associated item admits a non-trivial implementation
238 pub fn relevant_for_never(&self) -> bool {
240 AssocKind::OpaqueTy | AssocKind::Const | AssocKind::Type => true,
241 // FIXME(canndrew): Be more thorough here, check if any argument is uninhabited.
242 AssocKind::Method => !self.method_has_self_argument,
246 pub fn signature(&self, tcx: TyCtxt<'_>) -> String {
248 ty::AssocKind::Method => {
249 // We skip the binder here because the binder would deanonymize all
250 // late-bound regions, and we don't want method signatures to show up
251 // `as for<'r> fn(&'r MyType)`. Pretty-printing handles late-bound
252 // regions just fine, showing `fn(&MyType)`.
253 tcx.fn_sig(self.def_id).skip_binder().to_string()
255 ty::AssocKind::Type => format!("type {};", self.ident),
256 // FIXME(type_alias_impl_trait): we should print bounds here too.
257 ty::AssocKind::OpaqueTy => format!("type {};", self.ident),
258 ty::AssocKind::Const => {
259 format!("const {}: {:?};", self.ident, tcx.type_of(self.def_id))
265 /// A list of `ty::AssocItem`s in definition order that allows for efficient lookup by name.
267 /// When doing lookup by name, we try to postpone hygienic comparison for as long as possible since
268 /// it is relatively expensive. Instead, items are indexed by `Symbol` and hygienic comparison is
269 /// done only on items with the same name.
270 #[derive(Debug, Clone, PartialEq, HashStable)]
271 pub struct AssociatedItems {
272 items: SortedIndexMultiMap<u32, Symbol, ty::AssocItem>,
275 impl AssociatedItems {
276 /// Constructs an `AssociatedItems` map from a series of `ty::AssocItem`s in definition order.
277 pub fn new(items_in_def_order: impl IntoIterator<Item = ty::AssocItem>) -> Self {
278 let items = items_in_def_order.into_iter().map(|item| (item.ident.name, item)).collect();
279 AssociatedItems { items }
282 /// Returns a slice of associated items in the order they were defined.
284 /// New code should avoid relying on definition order. If you need a particular associated item
285 /// for a known trait, make that trait a lang item instead of indexing this array.
286 pub fn in_definition_order(&self) -> impl '_ + Iterator<Item = &ty::AssocItem> {
287 self.items.iter().map(|(_, v)| v)
290 /// Returns an iterator over all associated items with the given name, ignoring hygiene.
291 pub fn filter_by_name_unhygienic(
294 ) -> impl '_ + Iterator<Item = &ty::AssocItem> {
295 self.items.get_by_key(&name)
298 /// Returns an iterator over all associated items with the given name.
300 /// Multiple items may have the same name if they are in different `Namespace`s. For example,
301 /// an associated type can have the same name as a method. Use one of the `find_by_name_and_*`
302 /// methods below if you know which item you are looking for.
303 pub fn filter_by_name(
307 parent_def_id: DefId,
308 ) -> impl 'a + Iterator<Item = &'a ty::AssocItem> {
309 self.filter_by_name_unhygienic(ident.name)
310 .filter(move |item| tcx.hygienic_eq(ident, item.ident, parent_def_id))
313 /// Returns the associated item with the given name and `AssocKind`, if one exists.
314 pub fn find_by_name_and_kind(
319 parent_def_id: DefId,
320 ) -> Option<&ty::AssocItem> {
321 self.filter_by_name_unhygienic(ident.name)
322 .filter(|item| item.kind == kind)
323 .find(|item| tcx.hygienic_eq(ident, item.ident, parent_def_id))
326 /// Returns the associated item with the given name in the given `Namespace`, if one exists.
327 pub fn find_by_name_and_namespace(
332 parent_def_id: DefId,
333 ) -> Option<&ty::AssocItem> {
334 self.filter_by_name_unhygienic(ident.name)
335 .filter(|item| item.kind.namespace() == ns)
336 .find(|item| tcx.hygienic_eq(ident, item.ident, parent_def_id))
340 #[derive(Clone, Debug, PartialEq, Eq, Copy, RustcEncodable, RustcDecodable, HashStable)]
341 pub enum Visibility {
342 /// Visible everywhere (including in other crates).
344 /// Visible only in the given crate-local module.
346 /// Not visible anywhere in the local crate. This is the visibility of private external items.
350 pub trait DefIdTree: Copy {
351 fn parent(self, id: DefId) -> Option<DefId>;
353 fn is_descendant_of(self, mut descendant: DefId, ancestor: DefId) -> bool {
354 if descendant.krate != ancestor.krate {
358 while descendant != ancestor {
359 match self.parent(descendant) {
360 Some(parent) => descendant = parent,
361 None => return false,
368 impl<'tcx> DefIdTree for TyCtxt<'tcx> {
369 fn parent(self, id: DefId) -> Option<DefId> {
370 self.def_key(id).parent.map(|index| DefId { index, ..id })
375 pub fn from_hir(visibility: &hir::Visibility<'_>, id: hir::HirId, tcx: TyCtxt<'_>) -> Self {
376 match visibility.node {
377 hir::VisibilityKind::Public => Visibility::Public,
378 hir::VisibilityKind::Crate(_) => Visibility::Restricted(DefId::local(CRATE_DEF_INDEX)),
379 hir::VisibilityKind::Restricted { ref path, .. } => match path.res {
380 // If there is no resolution, `resolve` will have already reported an error, so
381 // assume that the visibility is public to avoid reporting more privacy errors.
382 Res::Err => Visibility::Public,
383 def => Visibility::Restricted(def.def_id()),
385 hir::VisibilityKind::Inherited => {
386 Visibility::Restricted(tcx.parent_module(id).to_def_id())
391 /// Returns `true` if an item with this visibility is accessible from the given block.
392 pub fn is_accessible_from<T: DefIdTree>(self, module: DefId, tree: T) -> bool {
393 let restriction = match self {
394 // Public items are visible everywhere.
395 Visibility::Public => return true,
396 // Private items from other crates are visible nowhere.
397 Visibility::Invisible => return false,
398 // Restricted items are visible in an arbitrary local module.
399 Visibility::Restricted(other) if other.krate != module.krate => return false,
400 Visibility::Restricted(module) => module,
403 tree.is_descendant_of(module, restriction)
406 /// Returns `true` if this visibility is at least as accessible as the given visibility
407 pub fn is_at_least<T: DefIdTree>(self, vis: Visibility, tree: T) -> bool {
408 let vis_restriction = match vis {
409 Visibility::Public => return self == Visibility::Public,
410 Visibility::Invisible => return true,
411 Visibility::Restricted(module) => module,
414 self.is_accessible_from(vis_restriction, tree)
417 // Returns `true` if this item is visible anywhere in the local crate.
418 pub fn is_visible_locally(self) -> bool {
420 Visibility::Public => true,
421 Visibility::Restricted(def_id) => def_id.is_local(),
422 Visibility::Invisible => false,
427 #[derive(Copy, Clone, PartialEq, RustcDecodable, RustcEncodable, HashStable)]
429 Covariant, // T<A> <: T<B> iff A <: B -- e.g., function return type
430 Invariant, // T<A> <: T<B> iff B == A -- e.g., type of mutable cell
431 Contravariant, // T<A> <: T<B> iff B <: A -- e.g., function param type
432 Bivariant, // T<A> <: T<B> -- e.g., unused type parameter
435 /// The crate variances map is computed during typeck and contains the
436 /// variance of every item in the local crate. You should not use it
437 /// directly, because to do so will make your pass dependent on the
438 /// HIR of every item in the local crate. Instead, use
439 /// `tcx.variances_of()` to get the variance for a *particular*
441 #[derive(HashStable)]
442 pub struct CrateVariancesMap<'tcx> {
443 /// For each item with generics, maps to a vector of the variance
444 /// of its generics. If an item has no generics, it will have no
446 pub variances: FxHashMap<DefId, &'tcx [ty::Variance]>,
450 /// `a.xform(b)` combines the variance of a context with the
451 /// variance of a type with the following meaning. If we are in a
452 /// context with variance `a`, and we encounter a type argument in
453 /// a position with variance `b`, then `a.xform(b)` is the new
454 /// variance with which the argument appears.
460 /// Here, the "ambient" variance starts as covariant. `*mut T` is
461 /// invariant with respect to `T`, so the variance in which the
462 /// `Vec<i32>` appears is `Covariant.xform(Invariant)`, which
463 /// yields `Invariant`. Now, the type `Vec<T>` is covariant with
464 /// respect to its type argument `T`, and hence the variance of
465 /// the `i32` here is `Invariant.xform(Covariant)`, which results
466 /// (again) in `Invariant`.
470 /// fn(*const Vec<i32>, *mut Vec<i32)
472 /// The ambient variance is covariant. A `fn` type is
473 /// contravariant with respect to its parameters, so the variance
474 /// within which both pointer types appear is
475 /// `Covariant.xform(Contravariant)`, or `Contravariant`. `*const
476 /// T` is covariant with respect to `T`, so the variance within
477 /// which the first `Vec<i32>` appears is
478 /// `Contravariant.xform(Covariant)` or `Contravariant`. The same
479 /// is true for its `i32` argument. In the `*mut T` case, the
480 /// variance of `Vec<i32>` is `Contravariant.xform(Invariant)`,
481 /// and hence the outermost type is `Invariant` with respect to
482 /// `Vec<i32>` (and its `i32` argument).
484 /// Source: Figure 1 of "Taming the Wildcards:
485 /// Combining Definition- and Use-Site Variance" published in PLDI'11.
486 pub fn xform(self, v: ty::Variance) -> ty::Variance {
488 // Figure 1, column 1.
489 (ty::Covariant, ty::Covariant) => ty::Covariant,
490 (ty::Covariant, ty::Contravariant) => ty::Contravariant,
491 (ty::Covariant, ty::Invariant) => ty::Invariant,
492 (ty::Covariant, ty::Bivariant) => ty::Bivariant,
494 // Figure 1, column 2.
495 (ty::Contravariant, ty::Covariant) => ty::Contravariant,
496 (ty::Contravariant, ty::Contravariant) => ty::Covariant,
497 (ty::Contravariant, ty::Invariant) => ty::Invariant,
498 (ty::Contravariant, ty::Bivariant) => ty::Bivariant,
500 // Figure 1, column 3.
501 (ty::Invariant, _) => ty::Invariant,
503 // Figure 1, column 4.
504 (ty::Bivariant, _) => ty::Bivariant,
509 // Contains information needed to resolve types and (in the future) look up
510 // the types of AST nodes.
511 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
512 pub struct CReaderCacheKey {
518 /// Flags that we track on types. These flags are propagated upwards
519 /// through the type during type construction, so that we can quickly check
520 /// whether the type has various kinds of types in it without recursing
521 /// over the type itself.
522 pub struct TypeFlags: u32 {
523 // Does this have parameters? Used to determine whether substitution is
525 /// Does this have [Param]?
526 const HAS_TY_PARAM = 1 << 0;
527 /// Does this have [ReEarlyBound]?
528 const HAS_RE_PARAM = 1 << 1;
529 /// Does this have [ConstKind::Param]?
530 const HAS_CT_PARAM = 1 << 2;
532 const NEEDS_SUBST = TypeFlags::HAS_TY_PARAM.bits
533 | TypeFlags::HAS_RE_PARAM.bits
534 | TypeFlags::HAS_CT_PARAM.bits;
536 /// Does this have [Infer]?
537 const HAS_TY_INFER = 1 << 3;
538 /// Does this have [ReVar]?
539 const HAS_RE_INFER = 1 << 4;
540 /// Does this have [ConstKind::Infer]?
541 const HAS_CT_INFER = 1 << 5;
543 /// Does this have inference variables? Used to determine whether
544 /// inference is required.
545 const NEEDS_INFER = TypeFlags::HAS_TY_INFER.bits
546 | TypeFlags::HAS_RE_INFER.bits
547 | TypeFlags::HAS_CT_INFER.bits;
549 /// Does this have [Placeholder]?
550 const HAS_TY_PLACEHOLDER = 1 << 6;
551 /// Does this have [RePlaceholder]?
552 const HAS_RE_PLACEHOLDER = 1 << 7;
553 /// Does this have [ConstKind::Placeholder]?
554 const HAS_CT_PLACEHOLDER = 1 << 8;
556 /// `true` if there are "names" of regions and so forth
557 /// that are local to a particular fn/inferctxt
558 const HAS_FREE_LOCAL_REGIONS = 1 << 9;
560 /// `true` if there are "names" of types and regions and so forth
561 /// that are local to a particular fn
562 const HAS_FREE_LOCAL_NAMES = TypeFlags::HAS_TY_PARAM.bits
563 | TypeFlags::HAS_CT_PARAM.bits
564 | TypeFlags::HAS_TY_INFER.bits
565 | TypeFlags::HAS_CT_INFER.bits
566 | TypeFlags::HAS_TY_PLACEHOLDER.bits
567 | TypeFlags::HAS_CT_PLACEHOLDER.bits
568 | TypeFlags::HAS_FREE_LOCAL_REGIONS.bits;
570 /// Does this have [Projection] or [UnnormalizedProjection]?
571 const HAS_TY_PROJECTION = 1 << 10;
572 /// Does this have [Opaque]?
573 const HAS_TY_OPAQUE = 1 << 11;
574 /// Does this have [ConstKind::Unevaluated]?
575 const HAS_CT_PROJECTION = 1 << 12;
577 /// Could this type be normalized further?
578 const HAS_PROJECTION = TypeFlags::HAS_TY_PROJECTION.bits
579 | TypeFlags::HAS_TY_OPAQUE.bits
580 | TypeFlags::HAS_CT_PROJECTION.bits;
582 /// Present if the type belongs in a local type context.
583 /// Set for placeholders and inference variables that are not "Fresh".
584 const KEEP_IN_LOCAL_TCX = 1 << 13;
586 /// Is an error type reachable?
587 const HAS_TY_ERR = 1 << 14;
589 /// Does this have any region that "appears free" in the type?
590 /// Basically anything but [ReLateBound] and [ReErased].
591 const HAS_FREE_REGIONS = 1 << 15;
593 /// Does this have any [ReLateBound] regions? Used to check
594 /// if a global bound is safe to evaluate.
595 const HAS_RE_LATE_BOUND = 1 << 16;
597 /// Does this have any [ReErased] regions?
598 const HAS_RE_ERASED = 1 << 17;
600 /// Does this value have parameters/placeholders/inference variables which could be
601 /// replaced later, in a way that would change the results of `impl` specialization?
602 const STILL_FURTHER_SPECIALIZABLE = 1 << 18;
604 /// Flags representing the nominal content of a type,
605 /// computed by FlagsComputation. If you add a new nominal
606 /// flag, it should be added here too.
607 const NOMINAL_FLAGS = TypeFlags::HAS_TY_PARAM.bits
608 | TypeFlags::HAS_RE_PARAM.bits
609 | TypeFlags::HAS_CT_PARAM.bits
610 | TypeFlags::HAS_TY_INFER.bits
611 | TypeFlags::HAS_RE_INFER.bits
612 | TypeFlags::HAS_CT_INFER.bits
613 | TypeFlags::HAS_TY_PLACEHOLDER.bits
614 | TypeFlags::HAS_RE_PLACEHOLDER.bits
615 | TypeFlags::HAS_CT_PLACEHOLDER.bits
616 | TypeFlags::HAS_FREE_LOCAL_REGIONS.bits
617 | TypeFlags::HAS_TY_PROJECTION.bits
618 | TypeFlags::HAS_TY_OPAQUE.bits
619 | TypeFlags::HAS_CT_PROJECTION.bits
620 | TypeFlags::KEEP_IN_LOCAL_TCX.bits
621 | TypeFlags::HAS_TY_ERR.bits
622 | TypeFlags::HAS_FREE_REGIONS.bits
623 | TypeFlags::HAS_RE_LATE_BOUND.bits
624 | TypeFlags::HAS_RE_ERASED.bits
625 | TypeFlags::STILL_FURTHER_SPECIALIZABLE.bits;
629 #[allow(rustc::usage_of_ty_tykind)]
630 pub struct TyS<'tcx> {
631 pub kind: TyKind<'tcx>,
632 pub flags: TypeFlags,
634 /// This is a kind of confusing thing: it stores the smallest
637 /// (a) the binder itself captures nothing but
638 /// (b) all the late-bound things within the type are captured
639 /// by some sub-binder.
641 /// So, for a type without any late-bound things, like `u32`, this
642 /// will be *innermost*, because that is the innermost binder that
643 /// captures nothing. But for a type `&'D u32`, where `'D` is a
644 /// late-bound region with De Bruijn index `D`, this would be `D + 1`
645 /// -- the binder itself does not capture `D`, but `D` is captured
646 /// by an inner binder.
648 /// We call this concept an "exclusive" binder `D` because all
649 /// De Bruijn indices within the type are contained within `0..D`
651 outer_exclusive_binder: ty::DebruijnIndex,
654 // `TyS` is used a lot. Make sure it doesn't unintentionally get bigger.
655 #[cfg(target_arch = "x86_64")]
656 static_assert_size!(TyS<'_>, 32);
658 impl<'tcx> Ord for TyS<'tcx> {
659 fn cmp(&self, other: &TyS<'tcx>) -> Ordering {
660 self.kind.cmp(&other.kind)
664 impl<'tcx> PartialOrd for TyS<'tcx> {
665 fn partial_cmp(&self, other: &TyS<'tcx>) -> Option<Ordering> {
666 Some(self.kind.cmp(&other.kind))
670 impl<'tcx> PartialEq for TyS<'tcx> {
672 fn eq(&self, other: &TyS<'tcx>) -> bool {
676 impl<'tcx> Eq for TyS<'tcx> {}
678 impl<'tcx> Hash for TyS<'tcx> {
679 fn hash<H: Hasher>(&self, s: &mut H) {
680 (self as *const TyS<'_>).hash(s)
684 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for ty::TyS<'tcx> {
685 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
689 // The other fields just provide fast access to information that is
690 // also contained in `kind`, so no need to hash them.
693 outer_exclusive_binder: _,
696 kind.hash_stable(hcx, hasher);
700 #[rustc_diagnostic_item = "Ty"]
701 pub type Ty<'tcx> = &'tcx TyS<'tcx>;
703 impl<'tcx> rustc_serialize::UseSpecializedEncodable for Ty<'tcx> {}
704 impl<'tcx> rustc_serialize::UseSpecializedDecodable for Ty<'tcx> {}
706 pub type CanonicalTy<'tcx> = Canonical<'tcx, Ty<'tcx>>;
709 /// A dummy type used to force `List` to be unsized while not requiring references to it be wide
711 type OpaqueListContents;
714 /// A wrapper for slices with the additional invariant
715 /// that the slice is interned and no other slice with
716 /// the same contents can exist in the same context.
717 /// This means we can use pointer for both
718 /// equality comparisons and hashing.
719 /// Note: `Slice` was already taken by the `Ty`.
724 opaque: OpaqueListContents,
727 unsafe impl<T: Sync> Sync for List<T> {}
729 impl<T: Copy> List<T> {
731 fn from_arena<'tcx>(arena: &'tcx Arena<'tcx>, slice: &[T]) -> &'tcx List<T> {
732 assert!(!mem::needs_drop::<T>());
733 assert!(mem::size_of::<T>() != 0);
734 assert!(!slice.is_empty());
736 // Align up the size of the len (usize) field
737 let align = mem::align_of::<T>();
738 let align_mask = align - 1;
739 let offset = mem::size_of::<usize>();
740 let offset = (offset + align_mask) & !align_mask;
742 let size = offset + slice.len() * mem::size_of::<T>();
746 .alloc_raw(size, cmp::max(mem::align_of::<T>(), mem::align_of::<usize>()));
748 let result = &mut *(mem.as_mut_ptr() as *mut List<T>);
750 result.len = slice.len();
752 // Write the elements
753 let arena_slice = slice::from_raw_parts_mut(result.data.as_mut_ptr(), result.len);
754 arena_slice.copy_from_slice(slice);
761 impl<T: fmt::Debug> fmt::Debug for List<T> {
762 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
767 impl<T: Encodable> Encodable for List<T> {
769 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
774 impl<T> Ord for List<T>
778 fn cmp(&self, other: &List<T>) -> Ordering {
779 if self == other { Ordering::Equal } else { <[T] as Ord>::cmp(&**self, &**other) }
783 impl<T> PartialOrd for List<T>
787 fn partial_cmp(&self, other: &List<T>) -> Option<Ordering> {
789 Some(Ordering::Equal)
791 <[T] as PartialOrd>::partial_cmp(&**self, &**other)
796 impl<T: PartialEq> PartialEq for List<T> {
798 fn eq(&self, other: &List<T>) -> bool {
802 impl<T: Eq> Eq for List<T> {}
804 impl<T> Hash for List<T> {
806 fn hash<H: Hasher>(&self, s: &mut H) {
807 (self as *const List<T>).hash(s)
811 impl<T> Deref for List<T> {
814 fn deref(&self) -> &[T] {
819 impl<T> AsRef<[T]> for List<T> {
821 fn as_ref(&self) -> &[T] {
822 unsafe { slice::from_raw_parts(self.data.as_ptr(), self.len) }
826 impl<'a, T> IntoIterator for &'a List<T> {
828 type IntoIter = <&'a [T] as IntoIterator>::IntoIter;
830 fn into_iter(self) -> Self::IntoIter {
835 impl<'tcx> rustc_serialize::UseSpecializedDecodable for &'tcx List<Ty<'tcx>> {}
839 pub fn empty<'a>() -> &'a List<T> {
840 #[repr(align(64), C)]
841 struct EmptySlice([u8; 64]);
842 static EMPTY_SLICE: EmptySlice = EmptySlice([0; 64]);
843 assert!(mem::align_of::<T>() <= 64);
844 unsafe { &*(&EMPTY_SLICE as *const _ as *const List<T>) }
848 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
849 pub struct UpvarPath {
850 pub hir_id: hir::HirId,
853 /// Upvars do not get their own `NodeId`. Instead, we use the pair of
854 /// the original var ID (that is, the root variable that is referenced
855 /// by the upvar) and the ID of the closure expression.
856 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
858 pub var_path: UpvarPath,
859 pub closure_expr_id: LocalDefId,
862 #[derive(Clone, PartialEq, Debug, RustcEncodable, RustcDecodable, Copy, HashStable)]
863 pub enum BorrowKind {
864 /// Data must be immutable and is aliasable.
867 /// Data must be immutable but not aliasable. This kind of borrow
868 /// cannot currently be expressed by the user and is used only in
869 /// implicit closure bindings. It is needed when the closure
870 /// is borrowing or mutating a mutable referent, e.g.:
872 /// let x: &mut isize = ...;
873 /// let y = || *x += 5;
875 /// If we were to try to translate this closure into a more explicit
876 /// form, we'd encounter an error with the code as written:
878 /// struct Env { x: & &mut isize }
879 /// let x: &mut isize = ...;
880 /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
881 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
883 /// This is then illegal because you cannot mutate a `&mut` found
884 /// in an aliasable location. To solve, you'd have to translate with
885 /// an `&mut` borrow:
887 /// struct Env { x: & &mut isize }
888 /// let x: &mut isize = ...;
889 /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
890 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
892 /// Now the assignment to `**env.x` is legal, but creating a
893 /// mutable pointer to `x` is not because `x` is not mutable. We
894 /// could fix this by declaring `x` as `let mut x`. This is ok in
895 /// user code, if awkward, but extra weird for closures, since the
896 /// borrow is hidden.
898 /// So we introduce a "unique imm" borrow -- the referent is
899 /// immutable, but not aliasable. This solves the problem. For
900 /// simplicity, we don't give users the way to express this
901 /// borrow, it's just used when translating closures.
904 /// Data is mutable and not aliasable.
908 /// Information describing the capture of an upvar. This is computed
909 /// during `typeck`, specifically by `regionck`.
910 #[derive(PartialEq, Clone, Debug, Copy, RustcEncodable, RustcDecodable, HashStable)]
911 pub enum UpvarCapture<'tcx> {
912 /// Upvar is captured by value. This is always true when the
913 /// closure is labeled `move`, but can also be true in other cases
914 /// depending on inference.
917 /// Upvar is captured by reference.
918 ByRef(UpvarBorrow<'tcx>),
921 #[derive(PartialEq, Clone, Copy, RustcEncodable, RustcDecodable, HashStable)]
922 pub struct UpvarBorrow<'tcx> {
923 /// The kind of borrow: by-ref upvars have access to shared
924 /// immutable borrows, which are not part of the normal language
926 pub kind: BorrowKind,
928 /// Region of the resulting reference.
929 pub region: ty::Region<'tcx>,
932 pub type UpvarListMap = FxHashMap<DefId, FxIndexMap<hir::HirId, UpvarId>>;
933 pub type UpvarCaptureMap<'tcx> = FxHashMap<UpvarId, UpvarCapture<'tcx>>;
935 #[derive(Clone, Copy, PartialEq, Eq)]
936 pub enum IntVarValue {
938 UintType(ast::UintTy),
941 #[derive(Clone, Copy, PartialEq, Eq)]
942 pub struct FloatVarValue(pub ast::FloatTy);
944 impl ty::EarlyBoundRegion {
945 pub fn to_bound_region(&self) -> ty::BoundRegion {
946 ty::BoundRegion::BrNamed(self.def_id, self.name)
949 /// Does this early bound region have a name? Early bound regions normally
950 /// always have names except when using anonymous lifetimes (`'_`).
951 pub fn has_name(&self) -> bool {
952 self.name != kw::UnderscoreLifetime
956 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
957 pub enum GenericParamDefKind {
961 object_lifetime_default: ObjectLifetimeDefault,
962 synthetic: Option<hir::SyntheticTyParamKind>,
967 impl GenericParamDefKind {
968 pub fn descr(&self) -> &'static str {
970 GenericParamDefKind::Lifetime => "lifetime",
971 GenericParamDefKind::Type { .. } => "type",
972 GenericParamDefKind::Const => "constant",
977 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
978 pub struct GenericParamDef {
983 /// `pure_wrt_drop`, set by the (unsafe) `#[may_dangle]` attribute
984 /// on generic parameter `'a`/`T`, asserts data behind the parameter
985 /// `'a`/`T` won't be accessed during the parent type's `Drop` impl.
986 pub pure_wrt_drop: bool,
988 pub kind: GenericParamDefKind,
991 impl GenericParamDef {
992 pub fn to_early_bound_region_data(&self) -> ty::EarlyBoundRegion {
993 if let GenericParamDefKind::Lifetime = self.kind {
994 ty::EarlyBoundRegion { def_id: self.def_id, index: self.index, name: self.name }
996 bug!("cannot convert a non-lifetime parameter def to an early bound region")
1000 pub fn to_bound_region(&self) -> ty::BoundRegion {
1001 if let GenericParamDefKind::Lifetime = self.kind {
1002 self.to_early_bound_region_data().to_bound_region()
1004 bug!("cannot convert a non-lifetime parameter def to an early bound region")
1010 pub struct GenericParamCount {
1011 pub lifetimes: usize,
1016 /// Information about the formal type/lifetime parameters associated
1017 /// with an item or method. Analogous to `hir::Generics`.
1019 /// The ordering of parameters is the same as in `Subst` (excluding child generics):
1020 /// `Self` (optionally), `Lifetime` params..., `Type` params...
1021 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
1022 pub struct Generics {
1023 pub parent: Option<DefId>,
1024 pub parent_count: usize,
1025 pub params: Vec<GenericParamDef>,
1027 /// Reverse map to the `index` field of each `GenericParamDef`.
1028 #[stable_hasher(ignore)]
1029 pub param_def_id_to_index: FxHashMap<DefId, u32>,
1032 pub has_late_bound_regions: Option<Span>,
1035 impl<'tcx> Generics {
1036 pub fn count(&self) -> usize {
1037 self.parent_count + self.params.len()
1040 pub fn own_counts(&self) -> GenericParamCount {
1041 // We could cache this as a property of `GenericParamCount`, but
1042 // the aim is to refactor this away entirely eventually and the
1043 // presence of this method will be a constant reminder.
1044 let mut own_counts: GenericParamCount = Default::default();
1046 for param in &self.params {
1048 GenericParamDefKind::Lifetime => own_counts.lifetimes += 1,
1049 GenericParamDefKind::Type { .. } => own_counts.types += 1,
1050 GenericParamDefKind::Const => own_counts.consts += 1,
1057 pub fn requires_monomorphization(&self, tcx: TyCtxt<'tcx>) -> bool {
1058 if self.own_requires_monomorphization() {
1062 if let Some(parent_def_id) = self.parent {
1063 let parent = tcx.generics_of(parent_def_id);
1064 parent.requires_monomorphization(tcx)
1070 pub fn own_requires_monomorphization(&self) -> bool {
1071 for param in &self.params {
1073 GenericParamDefKind::Type { .. } | GenericParamDefKind::Const => return true,
1074 GenericParamDefKind::Lifetime => {}
1080 pub fn param_at(&'tcx self, param_index: usize, tcx: TyCtxt<'tcx>) -> &'tcx GenericParamDef {
1081 if let Some(index) = param_index.checked_sub(self.parent_count) {
1084 tcx.generics_of(self.parent.expect("parent_count > 0 but no parent?"))
1085 .param_at(param_index, tcx)
1089 pub fn region_param(
1091 param: &EarlyBoundRegion,
1093 ) -> &'tcx GenericParamDef {
1094 let param = self.param_at(param.index as usize, tcx);
1096 GenericParamDefKind::Lifetime => param,
1097 _ => bug!("expected lifetime parameter, but found another generic parameter"),
1101 /// Returns the `GenericParamDef` associated with this `ParamTy`.
1102 pub fn type_param(&'tcx self, param: &ParamTy, tcx: TyCtxt<'tcx>) -> &'tcx GenericParamDef {
1103 let param = self.param_at(param.index as usize, tcx);
1105 GenericParamDefKind::Type { .. } => param,
1106 _ => bug!("expected type parameter, but found another generic parameter"),
1110 /// Returns the `ConstParameterDef` associated with this `ParamConst`.
1111 pub fn const_param(&'tcx self, param: &ParamConst, tcx: TyCtxt<'tcx>) -> &GenericParamDef {
1112 let param = self.param_at(param.index as usize, tcx);
1114 GenericParamDefKind::Const => param,
1115 _ => bug!("expected const parameter, but found another generic parameter"),
1120 /// Bounds on generics.
1121 #[derive(Copy, Clone, Default, Debug, RustcEncodable, RustcDecodable, HashStable)]
1122 pub struct GenericPredicates<'tcx> {
1123 pub parent: Option<DefId>,
1124 pub predicates: &'tcx [(Predicate<'tcx>, Span)],
1127 impl<'tcx> GenericPredicates<'tcx> {
1131 substs: SubstsRef<'tcx>,
1132 ) -> InstantiatedPredicates<'tcx> {
1133 let mut instantiated = InstantiatedPredicates::empty();
1134 self.instantiate_into(tcx, &mut instantiated, substs);
1138 pub fn instantiate_own(
1141 substs: SubstsRef<'tcx>,
1142 ) -> InstantiatedPredicates<'tcx> {
1143 InstantiatedPredicates {
1144 predicates: self.predicates.iter().map(|(p, _)| p.subst(tcx, substs)).collect(),
1145 spans: self.predicates.iter().map(|(_, sp)| *sp).collect(),
1149 fn instantiate_into(
1152 instantiated: &mut InstantiatedPredicates<'tcx>,
1153 substs: SubstsRef<'tcx>,
1155 if let Some(def_id) = self.parent {
1156 tcx.predicates_of(def_id).instantiate_into(tcx, instantiated, substs);
1158 instantiated.predicates.extend(self.predicates.iter().map(|(p, _)| p.subst(tcx, substs)));
1159 instantiated.spans.extend(self.predicates.iter().map(|(_, sp)| *sp));
1162 pub fn instantiate_identity(&self, tcx: TyCtxt<'tcx>) -> InstantiatedPredicates<'tcx> {
1163 let mut instantiated = InstantiatedPredicates::empty();
1164 self.instantiate_identity_into(tcx, &mut instantiated);
1168 fn instantiate_identity_into(
1171 instantiated: &mut InstantiatedPredicates<'tcx>,
1173 if let Some(def_id) = self.parent {
1174 tcx.predicates_of(def_id).instantiate_identity_into(tcx, instantiated);
1176 instantiated.predicates.extend(self.predicates.iter().map(|(p, _)| p));
1177 instantiated.spans.extend(self.predicates.iter().map(|(_, s)| s));
1180 pub fn instantiate_supertrait(
1183 poly_trait_ref: &ty::PolyTraitRef<'tcx>,
1184 ) -> InstantiatedPredicates<'tcx> {
1185 assert_eq!(self.parent, None);
1186 InstantiatedPredicates {
1190 .map(|(pred, _)| pred.subst_supertrait(tcx, poly_trait_ref))
1192 spans: self.predicates.iter().map(|(_, sp)| *sp).collect(),
1197 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1198 #[derive(HashStable, TypeFoldable)]
1199 pub enum Predicate<'tcx> {
1200 /// Corresponds to `where Foo: Bar<A, B, C>`. `Foo` here would be
1201 /// the `Self` type of the trait reference and `A`, `B`, and `C`
1202 /// would be the type parameters.
1204 /// A trait predicate will have `Constness::Const` if it originates
1205 /// from a bound on a `const fn` without the `?const` opt-out (e.g.,
1206 /// `const fn foobar<Foo: Bar>() {}`).
1207 Trait(PolyTraitPredicate<'tcx>, Constness),
1210 RegionOutlives(PolyRegionOutlivesPredicate<'tcx>),
1213 TypeOutlives(PolyTypeOutlivesPredicate<'tcx>),
1215 /// `where <T as TraitRef>::Name == X`, approximately.
1216 /// See the `ProjectionPredicate` struct for details.
1217 Projection(PolyProjectionPredicate<'tcx>),
1219 /// No syntax: `T` well-formed.
1220 WellFormed(Ty<'tcx>),
1222 /// Trait must be object-safe.
1225 /// No direct syntax. May be thought of as `where T: FnFoo<...>`
1226 /// for some substitutions `...` and `T` being a closure type.
1227 /// Satisfied (or refuted) once we know the closure's kind.
1228 ClosureKind(DefId, SubstsRef<'tcx>, ClosureKind),
1231 Subtype(PolySubtypePredicate<'tcx>),
1233 /// Constant initializer must evaluate successfully.
1234 ConstEvaluatable(DefId, SubstsRef<'tcx>),
1237 /// The crate outlives map is computed during typeck and contains the
1238 /// outlives of every item in the local crate. You should not use it
1239 /// directly, because to do so will make your pass dependent on the
1240 /// HIR of every item in the local crate. Instead, use
1241 /// `tcx.inferred_outlives_of()` to get the outlives for a *particular*
1243 #[derive(HashStable)]
1244 pub struct CratePredicatesMap<'tcx> {
1245 /// For each struct with outlive bounds, maps to a vector of the
1246 /// predicate of its outlive bounds. If an item has no outlives
1247 /// bounds, it will have no entry.
1248 pub predicates: FxHashMap<DefId, &'tcx [(ty::Predicate<'tcx>, Span)]>,
1251 impl<'tcx> AsRef<Predicate<'tcx>> for Predicate<'tcx> {
1252 fn as_ref(&self) -> &Predicate<'tcx> {
1257 impl<'tcx> Predicate<'tcx> {
1258 /// Performs a substitution suitable for going from a
1259 /// poly-trait-ref to supertraits that must hold if that
1260 /// poly-trait-ref holds. This is slightly different from a normal
1261 /// substitution in terms of what happens with bound regions. See
1262 /// lengthy comment below for details.
1263 pub fn subst_supertrait(
1266 trait_ref: &ty::PolyTraitRef<'tcx>,
1267 ) -> ty::Predicate<'tcx> {
1268 // The interaction between HRTB and supertraits is not entirely
1269 // obvious. Let me walk you (and myself) through an example.
1271 // Let's start with an easy case. Consider two traits:
1273 // trait Foo<'a>: Bar<'a,'a> { }
1274 // trait Bar<'b,'c> { }
1276 // Now, if we have a trait reference `for<'x> T: Foo<'x>`, then
1277 // we can deduce that `for<'x> T: Bar<'x,'x>`. Basically, if we
1278 // knew that `Foo<'x>` (for any 'x) then we also know that
1279 // `Bar<'x,'x>` (for any 'x). This more-or-less falls out from
1280 // normal substitution.
1282 // In terms of why this is sound, the idea is that whenever there
1283 // is an impl of `T:Foo<'a>`, it must show that `T:Bar<'a,'a>`
1284 // holds. So if there is an impl of `T:Foo<'a>` that applies to
1285 // all `'a`, then we must know that `T:Bar<'a,'a>` holds for all
1288 // Another example to be careful of is this:
1290 // trait Foo1<'a>: for<'b> Bar1<'a,'b> { }
1291 // trait Bar1<'b,'c> { }
1293 // Here, if we have `for<'x> T: Foo1<'x>`, then what do we know?
1294 // The answer is that we know `for<'x,'b> T: Bar1<'x,'b>`. The
1295 // reason is similar to the previous example: any impl of
1296 // `T:Foo1<'x>` must show that `for<'b> T: Bar1<'x, 'b>`. So
1297 // basically we would want to collapse the bound lifetimes from
1298 // the input (`trait_ref`) and the supertraits.
1300 // To achieve this in practice is fairly straightforward. Let's
1301 // consider the more complicated scenario:
1303 // - We start out with `for<'x> T: Foo1<'x>`. In this case, `'x`
1304 // has a De Bruijn index of 1. We want to produce `for<'x,'b> T: Bar1<'x,'b>`,
1305 // where both `'x` and `'b` would have a DB index of 1.
1306 // The substitution from the input trait-ref is therefore going to be
1307 // `'a => 'x` (where `'x` has a DB index of 1).
1308 // - The super-trait-ref is `for<'b> Bar1<'a,'b>`, where `'a` is an
1309 // early-bound parameter and `'b' is a late-bound parameter with a
1311 // - If we replace `'a` with `'x` from the input, it too will have
1312 // a DB index of 1, and thus we'll have `for<'x,'b> Bar1<'x,'b>`
1313 // just as we wanted.
1315 // There is only one catch. If we just apply the substitution `'a
1316 // => 'x` to `for<'b> Bar1<'a,'b>`, the substitution code will
1317 // adjust the DB index because we substituting into a binder (it
1318 // tries to be so smart...) resulting in `for<'x> for<'b>
1319 // Bar1<'x,'b>` (we have no syntax for this, so use your
1320 // imagination). Basically the 'x will have DB index of 2 and 'b
1321 // will have DB index of 1. Not quite what we want. So we apply
1322 // the substitution to the *contents* of the trait reference,
1323 // rather than the trait reference itself (put another way, the
1324 // substitution code expects equal binding levels in the values
1325 // from the substitution and the value being substituted into, and
1326 // this trick achieves that).
1328 let substs = &trait_ref.skip_binder().substs;
1330 Predicate::Trait(ref binder, constness) => {
1331 Predicate::Trait(binder.map_bound(|data| data.subst(tcx, substs)), constness)
1333 Predicate::Subtype(ref binder) => {
1334 Predicate::Subtype(binder.map_bound(|data| data.subst(tcx, substs)))
1336 Predicate::RegionOutlives(ref binder) => {
1337 Predicate::RegionOutlives(binder.map_bound(|data| data.subst(tcx, substs)))
1339 Predicate::TypeOutlives(ref binder) => {
1340 Predicate::TypeOutlives(binder.map_bound(|data| data.subst(tcx, substs)))
1342 Predicate::Projection(ref binder) => {
1343 Predicate::Projection(binder.map_bound(|data| data.subst(tcx, substs)))
1345 Predicate::WellFormed(data) => Predicate::WellFormed(data.subst(tcx, substs)),
1346 Predicate::ObjectSafe(trait_def_id) => Predicate::ObjectSafe(trait_def_id),
1347 Predicate::ClosureKind(closure_def_id, closure_substs, kind) => {
1348 Predicate::ClosureKind(closure_def_id, closure_substs.subst(tcx, substs), kind)
1350 Predicate::ConstEvaluatable(def_id, const_substs) => {
1351 Predicate::ConstEvaluatable(def_id, const_substs.subst(tcx, substs))
1357 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1358 #[derive(HashStable, TypeFoldable)]
1359 pub struct TraitPredicate<'tcx> {
1360 pub trait_ref: TraitRef<'tcx>,
1363 pub type PolyTraitPredicate<'tcx> = ty::Binder<TraitPredicate<'tcx>>;
1365 impl<'tcx> TraitPredicate<'tcx> {
1366 pub fn def_id(&self) -> DefId {
1367 self.trait_ref.def_id
1370 pub fn input_types<'a>(&'a self) -> impl DoubleEndedIterator<Item = Ty<'tcx>> + 'a {
1371 self.trait_ref.input_types()
1374 pub fn self_ty(&self) -> Ty<'tcx> {
1375 self.trait_ref.self_ty()
1379 impl<'tcx> PolyTraitPredicate<'tcx> {
1380 pub fn def_id(&self) -> DefId {
1381 // Ok to skip binder since trait `DefId` does not care about regions.
1382 self.skip_binder().def_id()
1386 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, RustcEncodable, RustcDecodable)]
1387 #[derive(HashStable, TypeFoldable)]
1388 pub struct OutlivesPredicate<A, B>(pub A, pub B); // `A: B`
1389 pub type PolyOutlivesPredicate<A, B> = ty::Binder<OutlivesPredicate<A, B>>;
1390 pub type RegionOutlivesPredicate<'tcx> = OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>;
1391 pub type TypeOutlivesPredicate<'tcx> = OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>;
1392 pub type PolyRegionOutlivesPredicate<'tcx> = ty::Binder<RegionOutlivesPredicate<'tcx>>;
1393 pub type PolyTypeOutlivesPredicate<'tcx> = ty::Binder<TypeOutlivesPredicate<'tcx>>;
1395 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
1396 #[derive(HashStable, TypeFoldable)]
1397 pub struct SubtypePredicate<'tcx> {
1398 pub a_is_expected: bool,
1402 pub type PolySubtypePredicate<'tcx> = ty::Binder<SubtypePredicate<'tcx>>;
1404 /// This kind of predicate has no *direct* correspondent in the
1405 /// syntax, but it roughly corresponds to the syntactic forms:
1407 /// 1. `T: TraitRef<..., Item = Type>`
1408 /// 2. `<T as TraitRef<...>>::Item == Type` (NYI)
1410 /// In particular, form #1 is "desugared" to the combination of a
1411 /// normal trait predicate (`T: TraitRef<...>`) and one of these
1412 /// predicates. Form #2 is a broader form in that it also permits
1413 /// equality between arbitrary types. Processing an instance of
1414 /// Form #2 eventually yields one of these `ProjectionPredicate`
1415 /// instances to normalize the LHS.
1416 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1417 #[derive(HashStable, TypeFoldable)]
1418 pub struct ProjectionPredicate<'tcx> {
1419 pub projection_ty: ProjectionTy<'tcx>,
1423 pub type PolyProjectionPredicate<'tcx> = Binder<ProjectionPredicate<'tcx>>;
1425 impl<'tcx> PolyProjectionPredicate<'tcx> {
1426 /// Returns the `DefId` of the associated item being projected.
1427 pub fn item_def_id(&self) -> DefId {
1428 self.skip_binder().projection_ty.item_def_id
1432 pub fn to_poly_trait_ref(&self, tcx: TyCtxt<'tcx>) -> PolyTraitRef<'tcx> {
1433 // Note: unlike with `TraitRef::to_poly_trait_ref()`,
1434 // `self.0.trait_ref` is permitted to have escaping regions.
1435 // This is because here `self` has a `Binder` and so does our
1436 // return value, so we are preserving the number of binding
1438 self.map_bound(|predicate| predicate.projection_ty.trait_ref(tcx))
1441 pub fn ty(&self) -> Binder<Ty<'tcx>> {
1442 self.map_bound(|predicate| predicate.ty)
1445 /// The `DefId` of the `TraitItem` for the associated type.
1447 /// Note that this is not the `DefId` of the `TraitRef` containing this
1448 /// associated type, which is in `tcx.associated_item(projection_def_id()).container`.
1449 pub fn projection_def_id(&self) -> DefId {
1450 // Ok to skip binder since trait `DefId` does not care about regions.
1451 self.skip_binder().projection_ty.item_def_id
1455 pub trait ToPolyTraitRef<'tcx> {
1456 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx>;
1459 impl<'tcx> ToPolyTraitRef<'tcx> for TraitRef<'tcx> {
1460 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
1461 ty::Binder::dummy(*self)
1465 impl<'tcx> ToPolyTraitRef<'tcx> for PolyTraitPredicate<'tcx> {
1466 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
1467 self.map_bound_ref(|trait_pred| trait_pred.trait_ref)
1471 pub trait ToPredicate<'tcx> {
1472 fn to_predicate(&self) -> Predicate<'tcx>;
1475 impl<'tcx> ToPredicate<'tcx> for ConstnessAnd<TraitRef<'tcx>> {
1476 fn to_predicate(&self) -> Predicate<'tcx> {
1477 ty::Predicate::Trait(
1478 ty::Binder::dummy(ty::TraitPredicate { trait_ref: self.value }),
1484 impl<'tcx> ToPredicate<'tcx> for ConstnessAnd<&TraitRef<'tcx>> {
1485 fn to_predicate(&self) -> Predicate<'tcx> {
1486 ty::Predicate::Trait(
1487 ty::Binder::dummy(ty::TraitPredicate { trait_ref: *self.value }),
1493 impl<'tcx> ToPredicate<'tcx> for ConstnessAnd<PolyTraitRef<'tcx>> {
1494 fn to_predicate(&self) -> Predicate<'tcx> {
1495 ty::Predicate::Trait(self.value.to_poly_trait_predicate(), self.constness)
1499 impl<'tcx> ToPredicate<'tcx> for ConstnessAnd<&PolyTraitRef<'tcx>> {
1500 fn to_predicate(&self) -> Predicate<'tcx> {
1501 ty::Predicate::Trait(self.value.to_poly_trait_predicate(), self.constness)
1505 impl<'tcx> ToPredicate<'tcx> for PolyRegionOutlivesPredicate<'tcx> {
1506 fn to_predicate(&self) -> Predicate<'tcx> {
1507 Predicate::RegionOutlives(*self)
1511 impl<'tcx> ToPredicate<'tcx> for PolyTypeOutlivesPredicate<'tcx> {
1512 fn to_predicate(&self) -> Predicate<'tcx> {
1513 Predicate::TypeOutlives(*self)
1517 impl<'tcx> ToPredicate<'tcx> for PolyProjectionPredicate<'tcx> {
1518 fn to_predicate(&self) -> Predicate<'tcx> {
1519 Predicate::Projection(*self)
1523 // A custom iterator used by `Predicate::walk_tys`.
1524 enum WalkTysIter<'tcx, I, J, K>
1526 I: Iterator<Item = Ty<'tcx>>,
1527 J: Iterator<Item = Ty<'tcx>>,
1528 K: Iterator<Item = Ty<'tcx>>,
1532 Two(Ty<'tcx>, Ty<'tcx>),
1538 impl<'tcx, I, J, K> Iterator for WalkTysIter<'tcx, I, J, K>
1540 I: Iterator<Item = Ty<'tcx>>,
1541 J: Iterator<Item = Ty<'tcx>>,
1542 K: Iterator<Item = Ty<'tcx>>,
1544 type Item = Ty<'tcx>;
1546 fn next(&mut self) -> Option<Ty<'tcx>> {
1548 WalkTysIter::None => None,
1549 WalkTysIter::One(item) => {
1550 *self = WalkTysIter::None;
1553 WalkTysIter::Two(item1, item2) => {
1554 *self = WalkTysIter::One(item2);
1557 WalkTysIter::Types(ref mut iter) => iter.next(),
1558 WalkTysIter::InputTypes(ref mut iter) => iter.next(),
1559 WalkTysIter::ProjectionTypes(ref mut iter) => iter.next(),
1564 impl<'tcx> Predicate<'tcx> {
1565 /// Iterates over the types in this predicate. Note that in all
1566 /// cases this is skipping over a binder, so late-bound regions
1567 /// with depth 0 are bound by the predicate.
1568 pub fn walk_tys(&'a self) -> impl Iterator<Item = Ty<'tcx>> + 'a {
1570 ty::Predicate::Trait(ref data, _) => {
1571 WalkTysIter::InputTypes(data.skip_binder().input_types())
1573 ty::Predicate::Subtype(binder) => {
1574 let SubtypePredicate { a, b, a_is_expected: _ } = binder.skip_binder();
1575 WalkTysIter::Two(a, b)
1577 ty::Predicate::TypeOutlives(binder) => WalkTysIter::One(binder.skip_binder().0),
1578 ty::Predicate::RegionOutlives(..) => WalkTysIter::None,
1579 ty::Predicate::Projection(ref data) => {
1580 let inner = data.skip_binder();
1581 WalkTysIter::ProjectionTypes(
1582 inner.projection_ty.substs.types().chain(Some(inner.ty)),
1585 ty::Predicate::WellFormed(data) => WalkTysIter::One(data),
1586 ty::Predicate::ObjectSafe(_trait_def_id) => WalkTysIter::None,
1587 ty::Predicate::ClosureKind(_closure_def_id, closure_substs, _kind) => {
1588 WalkTysIter::Types(closure_substs.types())
1590 ty::Predicate::ConstEvaluatable(_, substs) => WalkTysIter::Types(substs.types()),
1594 pub fn to_opt_poly_trait_ref(&self) -> Option<PolyTraitRef<'tcx>> {
1596 Predicate::Trait(ref t, _) => Some(t.to_poly_trait_ref()),
1597 Predicate::Projection(..)
1598 | Predicate::Subtype(..)
1599 | Predicate::RegionOutlives(..)
1600 | Predicate::WellFormed(..)
1601 | Predicate::ObjectSafe(..)
1602 | Predicate::ClosureKind(..)
1603 | Predicate::TypeOutlives(..)
1604 | Predicate::ConstEvaluatable(..) => None,
1608 pub fn to_opt_type_outlives(&self) -> Option<PolyTypeOutlivesPredicate<'tcx>> {
1610 Predicate::TypeOutlives(data) => Some(data),
1611 Predicate::Trait(..)
1612 | Predicate::Projection(..)
1613 | Predicate::Subtype(..)
1614 | Predicate::RegionOutlives(..)
1615 | Predicate::WellFormed(..)
1616 | Predicate::ObjectSafe(..)
1617 | Predicate::ClosureKind(..)
1618 | Predicate::ConstEvaluatable(..) => None,
1623 /// Represents the bounds declared on a particular set of type
1624 /// parameters. Should eventually be generalized into a flag list of
1625 /// where-clauses. You can obtain a `InstantiatedPredicates` list from a
1626 /// `GenericPredicates` by using the `instantiate` method. Note that this method
1627 /// reflects an important semantic invariant of `InstantiatedPredicates`: while
1628 /// the `GenericPredicates` are expressed in terms of the bound type
1629 /// parameters of the impl/trait/whatever, an `InstantiatedPredicates` instance
1630 /// represented a set of bounds for some particular instantiation,
1631 /// meaning that the generic parameters have been substituted with
1636 /// struct Foo<T, U: Bar<T>> { ... }
1638 /// Here, the `GenericPredicates` for `Foo` would contain a list of bounds like
1639 /// `[[], [U:Bar<T>]]`. Now if there were some particular reference
1640 /// like `Foo<isize,usize>`, then the `InstantiatedPredicates` would be `[[],
1641 /// [usize:Bar<isize>]]`.
1642 #[derive(Clone, Debug, TypeFoldable)]
1643 pub struct InstantiatedPredicates<'tcx> {
1644 pub predicates: Vec<Predicate<'tcx>>,
1645 pub spans: Vec<Span>,
1648 impl<'tcx> InstantiatedPredicates<'tcx> {
1649 pub fn empty() -> InstantiatedPredicates<'tcx> {
1650 InstantiatedPredicates { predicates: vec![], spans: vec![] }
1653 pub fn is_empty(&self) -> bool {
1654 self.predicates.is_empty()
1658 rustc_index::newtype_index! {
1659 /// "Universes" are used during type- and trait-checking in the
1660 /// presence of `for<..>` binders to control what sets of names are
1661 /// visible. Universes are arranged into a tree: the root universe
1662 /// contains names that are always visible. Each child then adds a new
1663 /// set of names that are visible, in addition to those of its parent.
1664 /// We say that the child universe "extends" the parent universe with
1667 /// To make this more concrete, consider this program:
1671 /// fn bar<T>(x: T) {
1672 /// let y: for<'a> fn(&'a u8, Foo) = ...;
1676 /// The struct name `Foo` is in the root universe U0. But the type
1677 /// parameter `T`, introduced on `bar`, is in an extended universe U1
1678 /// -- i.e., within `bar`, we can name both `T` and `Foo`, but outside
1679 /// of `bar`, we cannot name `T`. Then, within the type of `y`, the
1680 /// region `'a` is in a universe U2 that extends U1, because we can
1681 /// name it inside the fn type but not outside.
1683 /// Universes are used to do type- and trait-checking around these
1684 /// "forall" binders (also called **universal quantification**). The
1685 /// idea is that when, in the body of `bar`, we refer to `T` as a
1686 /// type, we aren't referring to any type in particular, but rather a
1687 /// kind of "fresh" type that is distinct from all other types we have
1688 /// actually declared. This is called a **placeholder** type, and we
1689 /// use universes to talk about this. In other words, a type name in
1690 /// universe 0 always corresponds to some "ground" type that the user
1691 /// declared, but a type name in a non-zero universe is a placeholder
1692 /// type -- an idealized representative of "types in general" that we
1693 /// use for checking generic functions.
1694 pub struct UniverseIndex {
1696 DEBUG_FORMAT = "U{}",
1700 impl UniverseIndex {
1701 pub const ROOT: UniverseIndex = UniverseIndex::from_u32(0);
1703 /// Returns the "next" universe index in order -- this new index
1704 /// is considered to extend all previous universes. This
1705 /// corresponds to entering a `forall` quantifier. So, for
1706 /// example, suppose we have this type in universe `U`:
1709 /// for<'a> fn(&'a u32)
1712 /// Once we "enter" into this `for<'a>` quantifier, we are in a
1713 /// new universe that extends `U` -- in this new universe, we can
1714 /// name the region `'a`, but that region was not nameable from
1715 /// `U` because it was not in scope there.
1716 pub fn next_universe(self) -> UniverseIndex {
1717 UniverseIndex::from_u32(self.private.checked_add(1).unwrap())
1720 /// Returns `true` if `self` can name a name from `other` -- in other words,
1721 /// if the set of names in `self` is a superset of those in
1722 /// `other` (`self >= other`).
1723 pub fn can_name(self, other: UniverseIndex) -> bool {
1724 self.private >= other.private
1727 /// Returns `true` if `self` cannot name some names from `other` -- in other
1728 /// words, if the set of names in `self` is a strict subset of
1729 /// those in `other` (`self < other`).
1730 pub fn cannot_name(self, other: UniverseIndex) -> bool {
1731 self.private < other.private
1735 /// The "placeholder index" fully defines a placeholder region.
1736 /// Placeholder regions are identified by both a **universe** as well
1737 /// as a "bound-region" within that universe. The `bound_region` is
1738 /// basically a name -- distinct bound regions within the same
1739 /// universe are just two regions with an unknown relationship to one
1741 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, PartialOrd, Ord)]
1742 pub struct Placeholder<T> {
1743 pub universe: UniverseIndex,
1747 impl<'a, T> HashStable<StableHashingContext<'a>> for Placeholder<T>
1749 T: HashStable<StableHashingContext<'a>>,
1751 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
1752 self.universe.hash_stable(hcx, hasher);
1753 self.name.hash_stable(hcx, hasher);
1757 pub type PlaceholderRegion = Placeholder<BoundRegion>;
1759 pub type PlaceholderType = Placeholder<BoundVar>;
1761 pub type PlaceholderConst = Placeholder<BoundVar>;
1763 /// When type checking, we use the `ParamEnv` to track
1764 /// details about the set of where-clauses that are in scope at this
1765 /// particular point.
1766 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable, TypeFoldable)]
1767 pub struct ParamEnv<'tcx> {
1768 /// `Obligation`s that the caller must satisfy. This is basically
1769 /// the set of bounds on the in-scope type parameters, translated
1770 /// into `Obligation`s, and elaborated and normalized.
1771 pub caller_bounds: &'tcx List<ty::Predicate<'tcx>>,
1773 /// Typically, this is `Reveal::UserFacing`, but during codegen we
1774 /// want `Reveal::All` -- note that this is always paired with an
1775 /// empty environment. To get that, use `ParamEnv::reveal()`.
1776 pub reveal: traits::Reveal,
1778 /// If this `ParamEnv` comes from a call to `tcx.param_env(def_id)`,
1779 /// register that `def_id` (useful for transitioning to the chalk trait
1781 pub def_id: Option<DefId>,
1784 impl<'tcx> ParamEnv<'tcx> {
1785 /// Construct a trait environment suitable for contexts where
1786 /// there are no where-clauses in scope. Hidden types (like `impl
1787 /// Trait`) are left hidden, so this is suitable for ordinary
1790 pub fn empty() -> Self {
1791 Self::new(List::empty(), Reveal::UserFacing, None)
1794 /// Construct a trait environment with no where-clauses in scope
1795 /// where the values of all `impl Trait` and other hidden types
1796 /// are revealed. This is suitable for monomorphized, post-typeck
1797 /// environments like codegen or doing optimizations.
1799 /// N.B., if you want to have predicates in scope, use `ParamEnv::new`,
1800 /// or invoke `param_env.with_reveal_all()`.
1802 pub fn reveal_all() -> Self {
1803 Self::new(List::empty(), Reveal::All, None)
1806 /// Construct a trait environment with the given set of predicates.
1809 caller_bounds: &'tcx List<ty::Predicate<'tcx>>,
1811 def_id: Option<DefId>,
1813 ty::ParamEnv { caller_bounds, reveal, def_id }
1816 /// Returns a new parameter environment with the same clauses, but
1817 /// which "reveals" the true results of projections in all cases
1818 /// (even for associated types that are specializable). This is
1819 /// the desired behavior during codegen and certain other special
1820 /// contexts; normally though we want to use `Reveal::UserFacing`,
1821 /// which is the default.
1822 pub fn with_reveal_all(self) -> Self {
1823 ty::ParamEnv { reveal: Reveal::All, ..self }
1826 /// Returns this same environment but with no caller bounds.
1827 pub fn without_caller_bounds(self) -> Self {
1828 ty::ParamEnv { caller_bounds: List::empty(), ..self }
1831 /// Creates a suitable environment in which to perform trait
1832 /// queries on the given value. When type-checking, this is simply
1833 /// the pair of the environment plus value. But when reveal is set to
1834 /// All, then if `value` does not reference any type parameters, we will
1835 /// pair it with the empty environment. This improves caching and is generally
1838 /// N.B., we preserve the environment when type-checking because it
1839 /// is possible for the user to have wacky where-clauses like
1840 /// `where Box<u32>: Copy`, which are clearly never
1841 /// satisfiable. We generally want to behave as if they were true,
1842 /// although the surrounding function is never reachable.
1843 pub fn and<T: TypeFoldable<'tcx>>(self, value: T) -> ParamEnvAnd<'tcx, T> {
1845 Reveal::UserFacing => ParamEnvAnd { param_env: self, value },
1848 if value.is_global() {
1849 ParamEnvAnd { param_env: self.without_caller_bounds(), value }
1851 ParamEnvAnd { param_env: self, value }
1858 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1859 pub struct ConstnessAnd<T> {
1860 pub constness: Constness,
1864 // FIXME(ecstaticmorse): Audit all occurrences of `without_const().to_predicate()` to ensure that
1865 // the constness of trait bounds is being propagated correctly.
1866 pub trait WithConstness: Sized {
1868 fn with_constness(self, constness: Constness) -> ConstnessAnd<Self> {
1869 ConstnessAnd { constness, value: self }
1873 fn with_const(self) -> ConstnessAnd<Self> {
1874 self.with_constness(Constness::Const)
1878 fn without_const(self) -> ConstnessAnd<Self> {
1879 self.with_constness(Constness::NotConst)
1883 impl<T> WithConstness for T {}
1885 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TypeFoldable)]
1886 pub struct ParamEnvAnd<'tcx, T> {
1887 pub param_env: ParamEnv<'tcx>,
1891 impl<'tcx, T> ParamEnvAnd<'tcx, T> {
1892 pub fn into_parts(self) -> (ParamEnv<'tcx>, T) {
1893 (self.param_env, self.value)
1897 impl<'a, 'tcx, T> HashStable<StableHashingContext<'a>> for ParamEnvAnd<'tcx, T>
1899 T: HashStable<StableHashingContext<'a>>,
1901 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
1902 let ParamEnvAnd { ref param_env, ref value } = *self;
1904 param_env.hash_stable(hcx, hasher);
1905 value.hash_stable(hcx, hasher);
1909 #[derive(Copy, Clone, Debug, HashStable)]
1910 pub struct Destructor {
1911 /// The `DefId` of the destructor method
1916 #[derive(HashStable)]
1917 pub struct AdtFlags: u32 {
1918 const NO_ADT_FLAGS = 0;
1919 /// Indicates whether the ADT is an enum.
1920 const IS_ENUM = 1 << 0;
1921 /// Indicates whether the ADT is a union.
1922 const IS_UNION = 1 << 1;
1923 /// Indicates whether the ADT is a struct.
1924 const IS_STRUCT = 1 << 2;
1925 /// Indicates whether the ADT is a struct and has a constructor.
1926 const HAS_CTOR = 1 << 3;
1927 /// Indicates whether the type is `PhantomData`.
1928 const IS_PHANTOM_DATA = 1 << 4;
1929 /// Indicates whether the type has a `#[fundamental]` attribute.
1930 const IS_FUNDAMENTAL = 1 << 5;
1931 /// Indicates whether the type is `Box`.
1932 const IS_BOX = 1 << 6;
1933 /// Indicates whether the type is `ManuallyDrop`.
1934 const IS_MANUALLY_DROP = 1 << 7;
1935 // FIXME(matthewjasper) replace these with diagnostic items
1936 /// Indicates whether the type is an `Arc`.
1937 const IS_ARC = 1 << 8;
1938 /// Indicates whether the type is an `Rc`.
1939 const IS_RC = 1 << 9;
1940 /// Indicates whether the variant list of this ADT is `#[non_exhaustive]`.
1941 /// (i.e., this flag is never set unless this ADT is an enum).
1942 const IS_VARIANT_LIST_NON_EXHAUSTIVE = 1 << 10;
1947 #[derive(HashStable)]
1948 pub struct VariantFlags: u32 {
1949 const NO_VARIANT_FLAGS = 0;
1950 /// Indicates whether the field list of this variant is `#[non_exhaustive]`.
1951 const IS_FIELD_LIST_NON_EXHAUSTIVE = 1 << 0;
1955 /// Definition of a variant -- a struct's fields or a enum variant.
1956 #[derive(Debug, HashStable)]
1957 pub struct VariantDef {
1958 /// `DefId` that identifies the variant itself.
1959 /// If this variant belongs to a struct or union, then this is a copy of its `DefId`.
1961 /// `DefId` that identifies the variant's constructor.
1962 /// If this variant is a struct variant, then this is `None`.
1963 pub ctor_def_id: Option<DefId>,
1964 /// Variant or struct name.
1965 #[stable_hasher(project(name))]
1967 /// Discriminant of this variant.
1968 pub discr: VariantDiscr,
1969 /// Fields of this variant.
1970 pub fields: Vec<FieldDef>,
1971 /// Type of constructor of variant.
1972 pub ctor_kind: CtorKind,
1973 /// Flags of the variant (e.g. is field list non-exhaustive)?
1974 flags: VariantFlags,
1975 /// Variant is obtained as part of recovering from a syntactic error.
1976 /// May be incomplete or bogus.
1977 pub recovered: bool,
1980 impl<'tcx> VariantDef {
1981 /// Creates a new `VariantDef`.
1983 /// `variant_did` is the `DefId` that identifies the enum variant (if this `VariantDef`
1984 /// represents an enum variant).
1986 /// `ctor_did` is the `DefId` that identifies the constructor of unit or
1987 /// tuple-variants/structs. If this is a `struct`-variant then this should be `None`.
1989 /// `parent_did` is the `DefId` of the `AdtDef` representing the enum or struct that
1990 /// owns this variant. It is used for checking if a struct has `#[non_exhaustive]` w/out having
1991 /// to go through the redirect of checking the ctor's attributes - but compiling a small crate
1992 /// requires loading the `AdtDef`s for all the structs in the universe (e.g., coherence for any
1993 /// built-in trait), and we do not want to load attributes twice.
1995 /// If someone speeds up attribute loading to not be a performance concern, they can
1996 /// remove this hack and use the constructor `DefId` everywhere.
2000 variant_did: Option<DefId>,
2001 ctor_def_id: Option<DefId>,
2002 discr: VariantDiscr,
2003 fields: Vec<FieldDef>,
2004 ctor_kind: CtorKind,
2010 "VariantDef::new(ident = {:?}, variant_did = {:?}, ctor_def_id = {:?}, discr = {:?},
2011 fields = {:?}, ctor_kind = {:?}, adt_kind = {:?}, parent_did = {:?})",
2012 ident, variant_did, ctor_def_id, discr, fields, ctor_kind, adt_kind, parent_did,
2015 let mut flags = VariantFlags::NO_VARIANT_FLAGS;
2016 if adt_kind == AdtKind::Struct && tcx.has_attr(parent_did, sym::non_exhaustive) {
2017 debug!("found non-exhaustive field list for {:?}", parent_did);
2018 flags = flags | VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE;
2019 } else if let Some(variant_did) = variant_did {
2020 if tcx.has_attr(variant_did, sym::non_exhaustive) {
2021 debug!("found non-exhaustive field list for {:?}", variant_did);
2022 flags = flags | VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE;
2027 def_id: variant_did.unwrap_or(parent_did),
2038 /// Is this field list non-exhaustive?
2040 pub fn is_field_list_non_exhaustive(&self) -> bool {
2041 self.flags.intersects(VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE)
2045 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2046 pub enum VariantDiscr {
2047 /// Explicit value for this variant, i.e., `X = 123`.
2048 /// The `DefId` corresponds to the embedded constant.
2051 /// The previous variant's discriminant plus one.
2052 /// For efficiency reasons, the distance from the
2053 /// last `Explicit` discriminant is being stored,
2054 /// or `0` for the first variant, if it has none.
2058 #[derive(Debug, HashStable)]
2059 pub struct FieldDef {
2061 #[stable_hasher(project(name))]
2063 pub vis: Visibility,
2066 /// The definition of a user-defined type, e.g., a `struct`, `enum`, or `union`.
2068 /// These are all interned (by `intern_adt_def`) into the `adt_defs` table.
2070 /// The initialism *ADT* stands for an [*algebraic data type (ADT)*][adt].
2071 /// This is slightly wrong because `union`s are not ADTs.
2072 /// Moreover, Rust only allows recursive data types through indirection.
2074 /// [adt]: https://en.wikipedia.org/wiki/Algebraic_data_type
2076 /// The `DefId` of the struct, enum or union item.
2078 /// Variants of the ADT. If this is a struct or union, then there will be a single variant.
2079 pub variants: IndexVec<VariantIdx, VariantDef>,
2080 /// Flags of the ADT (e.g., is this a struct? is this non-exhaustive?).
2082 /// Repr options provided by the user.
2083 pub repr: ReprOptions,
2086 impl PartialOrd for AdtDef {
2087 fn partial_cmp(&self, other: &AdtDef) -> Option<Ordering> {
2088 Some(self.cmp(&other))
2092 /// There should be only one AdtDef for each `did`, therefore
2093 /// it is fine to implement `Ord` only based on `did`.
2094 impl Ord for AdtDef {
2095 fn cmp(&self, other: &AdtDef) -> Ordering {
2096 self.did.cmp(&other.did)
2100 impl PartialEq for AdtDef {
2101 // `AdtDef`s are always interned, and this is part of `TyS` equality.
2103 fn eq(&self, other: &Self) -> bool {
2104 ptr::eq(self, other)
2108 impl Eq for AdtDef {}
2110 impl Hash for AdtDef {
2112 fn hash<H: Hasher>(&self, s: &mut H) {
2113 (self as *const AdtDef).hash(s)
2117 impl<'tcx> rustc_serialize::UseSpecializedEncodable for &'tcx AdtDef {
2118 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
2123 impl<'tcx> rustc_serialize::UseSpecializedDecodable for &'tcx AdtDef {}
2125 impl<'a> HashStable<StableHashingContext<'a>> for AdtDef {
2126 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
2128 static CACHE: RefCell<FxHashMap<usize, Fingerprint>> = Default::default();
2131 let hash: Fingerprint = CACHE.with(|cache| {
2132 let addr = self as *const AdtDef as usize;
2133 *cache.borrow_mut().entry(addr).or_insert_with(|| {
2134 let ty::AdtDef { did, ref variants, ref flags, ref repr } = *self;
2136 let mut hasher = StableHasher::new();
2137 did.hash_stable(hcx, &mut hasher);
2138 variants.hash_stable(hcx, &mut hasher);
2139 flags.hash_stable(hcx, &mut hasher);
2140 repr.hash_stable(hcx, &mut hasher);
2146 hash.hash_stable(hcx, hasher);
2150 #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
2157 impl Into<DataTypeKind> for AdtKind {
2158 fn into(self) -> DataTypeKind {
2160 AdtKind::Struct => DataTypeKind::Struct,
2161 AdtKind::Union => DataTypeKind::Union,
2162 AdtKind::Enum => DataTypeKind::Enum,
2168 #[derive(RustcEncodable, RustcDecodable, Default, HashStable)]
2169 pub struct ReprFlags: u8 {
2170 const IS_C = 1 << 0;
2171 const IS_SIMD = 1 << 1;
2172 const IS_TRANSPARENT = 1 << 2;
2173 // Internal only for now. If true, don't reorder fields.
2174 const IS_LINEAR = 1 << 3;
2175 // If true, don't expose any niche to type's context.
2176 const HIDE_NICHE = 1 << 4;
2177 // Any of these flags being set prevent field reordering optimisation.
2178 const IS_UNOPTIMISABLE = ReprFlags::IS_C.bits |
2179 ReprFlags::IS_SIMD.bits |
2180 ReprFlags::IS_LINEAR.bits;
2184 /// Represents the repr options provided by the user,
2185 #[derive(Copy, Clone, Debug, Eq, PartialEq, RustcEncodable, RustcDecodable, Default, HashStable)]
2186 pub struct ReprOptions {
2187 pub int: Option<attr::IntType>,
2188 pub align: Option<Align>,
2189 pub pack: Option<Align>,
2190 pub flags: ReprFlags,
2194 pub fn new(tcx: TyCtxt<'_>, did: DefId) -> ReprOptions {
2195 let mut flags = ReprFlags::empty();
2196 let mut size = None;
2197 let mut max_align: Option<Align> = None;
2198 let mut min_pack: Option<Align> = None;
2199 for attr in tcx.get_attrs(did).iter() {
2200 for r in attr::find_repr_attrs(&tcx.sess.parse_sess, attr) {
2201 flags.insert(match r {
2202 attr::ReprC => ReprFlags::IS_C,
2203 attr::ReprPacked(pack) => {
2204 let pack = Align::from_bytes(pack as u64).unwrap();
2205 min_pack = Some(if let Some(min_pack) = min_pack {
2212 attr::ReprTransparent => ReprFlags::IS_TRANSPARENT,
2213 attr::ReprNoNiche => ReprFlags::HIDE_NICHE,
2214 attr::ReprSimd => ReprFlags::IS_SIMD,
2215 attr::ReprInt(i) => {
2219 attr::ReprAlign(align) => {
2220 max_align = max_align.max(Some(Align::from_bytes(align as u64).unwrap()));
2227 // This is here instead of layout because the choice must make it into metadata.
2228 if !tcx.consider_optimizing(|| format!("Reorder fields of {:?}", tcx.def_path_str(did))) {
2229 flags.insert(ReprFlags::IS_LINEAR);
2231 ReprOptions { int: size, align: max_align, pack: min_pack, flags }
2235 pub fn simd(&self) -> bool {
2236 self.flags.contains(ReprFlags::IS_SIMD)
2239 pub fn c(&self) -> bool {
2240 self.flags.contains(ReprFlags::IS_C)
2243 pub fn packed(&self) -> bool {
2247 pub fn transparent(&self) -> bool {
2248 self.flags.contains(ReprFlags::IS_TRANSPARENT)
2251 pub fn linear(&self) -> bool {
2252 self.flags.contains(ReprFlags::IS_LINEAR)
2255 pub fn hide_niche(&self) -> bool {
2256 self.flags.contains(ReprFlags::HIDE_NICHE)
2259 pub fn discr_type(&self) -> attr::IntType {
2260 self.int.unwrap_or(attr::SignedInt(ast::IntTy::Isize))
2263 /// Returns `true` if this `#[repr()]` should inhabit "smart enum
2264 /// layout" optimizations, such as representing `Foo<&T>` as a
2266 pub fn inhibit_enum_layout_opt(&self) -> bool {
2267 self.c() || self.int.is_some()
2270 /// Returns `true` if this `#[repr()]` should inhibit struct field reordering
2271 /// optimizations, such as with `repr(C)`, `repr(packed(1))`, or `repr(<int>)`.
2272 pub fn inhibit_struct_field_reordering_opt(&self) -> bool {
2273 if let Some(pack) = self.pack {
2274 if pack.bytes() == 1 {
2278 self.flags.intersects(ReprFlags::IS_UNOPTIMISABLE) || self.int.is_some()
2281 /// Returns `true` if this `#[repr()]` should inhibit union ABI optimisations.
2282 pub fn inhibit_union_abi_opt(&self) -> bool {
2288 /// Creates a new `AdtDef`.
2293 variants: IndexVec<VariantIdx, VariantDef>,
2296 debug!("AdtDef::new({:?}, {:?}, {:?}, {:?})", did, kind, variants, repr);
2297 let mut flags = AdtFlags::NO_ADT_FLAGS;
2299 if kind == AdtKind::Enum && tcx.has_attr(did, sym::non_exhaustive) {
2300 debug!("found non-exhaustive variant list for {:?}", did);
2301 flags = flags | AdtFlags::IS_VARIANT_LIST_NON_EXHAUSTIVE;
2304 flags |= match kind {
2305 AdtKind::Enum => AdtFlags::IS_ENUM,
2306 AdtKind::Union => AdtFlags::IS_UNION,
2307 AdtKind::Struct => AdtFlags::IS_STRUCT,
2310 if kind == AdtKind::Struct && variants[VariantIdx::new(0)].ctor_def_id.is_some() {
2311 flags |= AdtFlags::HAS_CTOR;
2314 let attrs = tcx.get_attrs(did);
2315 if attr::contains_name(&attrs, sym::fundamental) {
2316 flags |= AdtFlags::IS_FUNDAMENTAL;
2318 if Some(did) == tcx.lang_items().phantom_data() {
2319 flags |= AdtFlags::IS_PHANTOM_DATA;
2321 if Some(did) == tcx.lang_items().owned_box() {
2322 flags |= AdtFlags::IS_BOX;
2324 if Some(did) == tcx.lang_items().manually_drop() {
2325 flags |= AdtFlags::IS_MANUALLY_DROP;
2327 if Some(did) == tcx.lang_items().arc() {
2328 flags |= AdtFlags::IS_ARC;
2330 if Some(did) == tcx.lang_items().rc() {
2331 flags |= AdtFlags::IS_RC;
2334 AdtDef { did, variants, flags, repr }
2337 /// Returns `true` if this is a struct.
2339 pub fn is_struct(&self) -> bool {
2340 self.flags.contains(AdtFlags::IS_STRUCT)
2343 /// Returns `true` if this is a union.
2345 pub fn is_union(&self) -> bool {
2346 self.flags.contains(AdtFlags::IS_UNION)
2349 /// Returns `true` if this is a enum.
2351 pub fn is_enum(&self) -> bool {
2352 self.flags.contains(AdtFlags::IS_ENUM)
2355 /// Returns `true` if the variant list of this ADT is `#[non_exhaustive]`.
2357 pub fn is_variant_list_non_exhaustive(&self) -> bool {
2358 self.flags.contains(AdtFlags::IS_VARIANT_LIST_NON_EXHAUSTIVE)
2361 /// Returns the kind of the ADT.
2363 pub fn adt_kind(&self) -> AdtKind {
2366 } else if self.is_union() {
2373 /// Returns a description of this abstract data type.
2374 pub fn descr(&self) -> &'static str {
2375 match self.adt_kind() {
2376 AdtKind::Struct => "struct",
2377 AdtKind::Union => "union",
2378 AdtKind::Enum => "enum",
2382 /// Returns a description of a variant of this abstract data type.
2384 pub fn variant_descr(&self) -> &'static str {
2385 match self.adt_kind() {
2386 AdtKind::Struct => "struct",
2387 AdtKind::Union => "union",
2388 AdtKind::Enum => "variant",
2392 /// If this function returns `true`, it implies that `is_struct` must return `true`.
2394 pub fn has_ctor(&self) -> bool {
2395 self.flags.contains(AdtFlags::HAS_CTOR)
2398 /// Returns `true` if this type is `#[fundamental]` for the purposes
2399 /// of coherence checking.
2401 pub fn is_fundamental(&self) -> bool {
2402 self.flags.contains(AdtFlags::IS_FUNDAMENTAL)
2405 /// Returns `true` if this is `PhantomData<T>`.
2407 pub fn is_phantom_data(&self) -> bool {
2408 self.flags.contains(AdtFlags::IS_PHANTOM_DATA)
2411 /// Returns `true` if this is `Arc<T>`.
2412 pub fn is_arc(&self) -> bool {
2413 self.flags.contains(AdtFlags::IS_ARC)
2416 /// Returns `true` if this is `Rc<T>`.
2417 pub fn is_rc(&self) -> bool {
2418 self.flags.contains(AdtFlags::IS_RC)
2421 /// Returns `true` if this is Box<T>.
2423 pub fn is_box(&self) -> bool {
2424 self.flags.contains(AdtFlags::IS_BOX)
2427 /// Returns `true` if this is `ManuallyDrop<T>`.
2429 pub fn is_manually_drop(&self) -> bool {
2430 self.flags.contains(AdtFlags::IS_MANUALLY_DROP)
2433 /// Returns `true` if this type has a destructor.
2434 pub fn has_dtor(&self, tcx: TyCtxt<'tcx>) -> bool {
2435 self.destructor(tcx).is_some()
2438 /// Asserts this is a struct or union and returns its unique variant.
2439 pub fn non_enum_variant(&self) -> &VariantDef {
2440 assert!(self.is_struct() || self.is_union());
2441 &self.variants[VariantIdx::new(0)]
2445 pub fn predicates(&self, tcx: TyCtxt<'tcx>) -> GenericPredicates<'tcx> {
2446 tcx.predicates_of(self.did)
2449 /// Returns an iterator over all fields contained
2452 pub fn all_fields(&self) -> impl Iterator<Item = &FieldDef> + Clone {
2453 self.variants.iter().flat_map(|v| v.fields.iter())
2456 pub fn is_payloadfree(&self) -> bool {
2457 !self.variants.is_empty() && self.variants.iter().all(|v| v.fields.is_empty())
2460 /// Return a `VariantDef` given a variant id.
2461 pub fn variant_with_id(&self, vid: DefId) -> &VariantDef {
2462 self.variants.iter().find(|v| v.def_id == vid).expect("variant_with_id: unknown variant")
2465 /// Return a `VariantDef` given a constructor id.
2466 pub fn variant_with_ctor_id(&self, cid: DefId) -> &VariantDef {
2469 .find(|v| v.ctor_def_id == Some(cid))
2470 .expect("variant_with_ctor_id: unknown variant")
2473 /// Return the index of `VariantDef` given a variant id.
2474 pub fn variant_index_with_id(&self, vid: DefId) -> VariantIdx {
2477 .find(|(_, v)| v.def_id == vid)
2478 .expect("variant_index_with_id: unknown variant")
2482 /// Return the index of `VariantDef` given a constructor id.
2483 pub fn variant_index_with_ctor_id(&self, cid: DefId) -> VariantIdx {
2486 .find(|(_, v)| v.ctor_def_id == Some(cid))
2487 .expect("variant_index_with_ctor_id: unknown variant")
2491 pub fn variant_of_res(&self, res: Res) -> &VariantDef {
2493 Res::Def(DefKind::Variant, vid) => self.variant_with_id(vid),
2494 Res::Def(DefKind::Ctor(..), cid) => self.variant_with_ctor_id(cid),
2495 Res::Def(DefKind::Struct, _)
2496 | Res::Def(DefKind::Union, _)
2497 | Res::Def(DefKind::TyAlias, _)
2498 | Res::Def(DefKind::AssocTy, _)
2500 | Res::SelfCtor(..) => self.non_enum_variant(),
2501 _ => bug!("unexpected res {:?} in variant_of_res", res),
2506 pub fn eval_explicit_discr(&self, tcx: TyCtxt<'tcx>, expr_did: DefId) -> Option<Discr<'tcx>> {
2507 let param_env = tcx.param_env(expr_did);
2508 let repr_type = self.repr.discr_type();
2509 match tcx.const_eval_poly(expr_did) {
2511 let ty = repr_type.to_ty(tcx);
2512 if let Some(b) = val.try_to_bits_for_ty(tcx, param_env, ty) {
2513 trace!("discriminants: {} ({:?})", b, repr_type);
2514 Some(Discr { val: b, ty })
2516 info!("invalid enum discriminant: {:#?}", val);
2517 crate::mir::interpret::struct_error(
2518 tcx.at(tcx.def_span(expr_did)),
2519 "constant evaluation of enum discriminant resulted in non-integer",
2525 Err(ErrorHandled::Reported) => {
2526 if !expr_did.is_local() {
2528 tcx.def_span(expr_did),
2529 "variant discriminant evaluation succeeded \
2530 in its crate but failed locally"
2535 Err(ErrorHandled::TooGeneric) => {
2536 span_bug!(tcx.def_span(expr_did), "enum discriminant depends on generic arguments",)
2542 pub fn discriminants(
2545 ) -> impl Iterator<Item = (VariantIdx, Discr<'tcx>)> + Captures<'tcx> {
2546 let repr_type = self.repr.discr_type();
2547 let initial = repr_type.initial_discriminant(tcx);
2548 let mut prev_discr = None::<Discr<'tcx>>;
2549 self.variants.iter_enumerated().map(move |(i, v)| {
2550 let mut discr = prev_discr.map_or(initial, |d| d.wrap_incr(tcx));
2551 if let VariantDiscr::Explicit(expr_did) = v.discr {
2552 if let Some(new_discr) = self.eval_explicit_discr(tcx, expr_did) {
2556 prev_discr = Some(discr);
2563 pub fn variant_range(&self) -> Range<VariantIdx> {
2564 VariantIdx::new(0)..VariantIdx::new(self.variants.len())
2567 /// Computes the discriminant value used by a specific variant.
2568 /// Unlike `discriminants`, this is (amortized) constant-time,
2569 /// only doing at most one query for evaluating an explicit
2570 /// discriminant (the last one before the requested variant),
2571 /// assuming there are no constant-evaluation errors there.
2573 pub fn discriminant_for_variant(
2576 variant_index: VariantIdx,
2578 let (val, offset) = self.discriminant_def_for_variant(variant_index);
2579 let explicit_value = val
2580 .and_then(|expr_did| self.eval_explicit_discr(tcx, expr_did))
2581 .unwrap_or_else(|| self.repr.discr_type().initial_discriminant(tcx));
2582 explicit_value.checked_add(tcx, offset as u128).0
2585 /// Yields a `DefId` for the discriminant and an offset to add to it
2586 /// Alternatively, if there is no explicit discriminant, returns the
2587 /// inferred discriminant directly.
2588 pub fn discriminant_def_for_variant(&self, variant_index: VariantIdx) -> (Option<DefId>, u32) {
2589 let mut explicit_index = variant_index.as_u32();
2592 match self.variants[VariantIdx::from_u32(explicit_index)].discr {
2593 ty::VariantDiscr::Relative(0) => {
2597 ty::VariantDiscr::Relative(distance) => {
2598 explicit_index -= distance;
2600 ty::VariantDiscr::Explicit(did) => {
2601 expr_did = Some(did);
2606 (expr_did, variant_index.as_u32() - explicit_index)
2609 pub fn destructor(&self, tcx: TyCtxt<'tcx>) -> Option<Destructor> {
2610 tcx.adt_destructor(self.did)
2613 /// Returns a list of types such that `Self: Sized` if and only
2614 /// if that type is `Sized`, or `TyErr` if this type is recursive.
2616 /// Oddly enough, checking that the sized-constraint is `Sized` is
2617 /// actually more expressive than checking all members:
2618 /// the `Sized` trait is inductive, so an associated type that references
2619 /// `Self` would prevent its containing ADT from being `Sized`.
2621 /// Due to normalization being eager, this applies even if
2622 /// the associated type is behind a pointer (e.g., issue #31299).
2623 pub fn sized_constraint(&self, tcx: TyCtxt<'tcx>) -> &'tcx [Ty<'tcx>] {
2624 tcx.adt_sized_constraint(self.did).0
2628 impl<'tcx> FieldDef {
2629 /// Returns the type of this field. The `subst` is typically obtained
2630 /// via the second field of `TyKind::AdtDef`.
2631 pub fn ty(&self, tcx: TyCtxt<'tcx>, subst: SubstsRef<'tcx>) -> Ty<'tcx> {
2632 tcx.type_of(self.did).subst(tcx, subst)
2636 /// Represents the various closure traits in the language. This
2637 /// will determine the type of the environment (`self`, in the
2638 /// desugaring) argument that the closure expects.
2640 /// You can get the environment type of a closure using
2641 /// `tcx.closure_env_ty()`.
2642 #[derive(Clone, Copy, PartialOrd, Ord, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
2643 #[derive(HashStable)]
2644 pub enum ClosureKind {
2645 // Warning: Ordering is significant here! The ordering is chosen
2646 // because the trait Fn is a subtrait of FnMut and so in turn, and
2647 // hence we order it so that Fn < FnMut < FnOnce.
2653 impl<'tcx> ClosureKind {
2654 // This is the initial value used when doing upvar inference.
2655 pub const LATTICE_BOTTOM: ClosureKind = ClosureKind::Fn;
2657 pub fn trait_did(&self, tcx: TyCtxt<'tcx>) -> DefId {
2659 ClosureKind::Fn => tcx.require_lang_item(FnTraitLangItem, None),
2660 ClosureKind::FnMut => tcx.require_lang_item(FnMutTraitLangItem, None),
2661 ClosureKind::FnOnce => tcx.require_lang_item(FnOnceTraitLangItem, None),
2665 /// Returns `true` if this a type that impls this closure kind
2666 /// must also implement `other`.
2667 pub fn extends(self, other: ty::ClosureKind) -> bool {
2668 match (self, other) {
2669 (ClosureKind::Fn, ClosureKind::Fn) => true,
2670 (ClosureKind::Fn, ClosureKind::FnMut) => true,
2671 (ClosureKind::Fn, ClosureKind::FnOnce) => true,
2672 (ClosureKind::FnMut, ClosureKind::FnMut) => true,
2673 (ClosureKind::FnMut, ClosureKind::FnOnce) => true,
2674 (ClosureKind::FnOnce, ClosureKind::FnOnce) => true,
2679 /// Returns the representative scalar type for this closure kind.
2680 /// See `TyS::to_opt_closure_kind` for more details.
2681 pub fn to_ty(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
2683 ty::ClosureKind::Fn => tcx.types.i8,
2684 ty::ClosureKind::FnMut => tcx.types.i16,
2685 ty::ClosureKind::FnOnce => tcx.types.i32,
2690 impl<'tcx> TyS<'tcx> {
2691 /// Iterator that walks `self` and any types reachable from
2692 /// `self`, in depth-first order. Note that just walks the types
2693 /// that appear in `self`, it does not descend into the fields of
2694 /// structs or variants. For example:
2697 /// isize => { isize }
2698 /// Foo<Bar<isize>> => { Foo<Bar<isize>>, Bar<isize>, isize }
2699 /// [isize] => { [isize], isize }
2701 pub fn walk(&'tcx self) -> TypeWalker<'tcx> {
2702 TypeWalker::new(self)
2705 /// Iterator that walks the immediate children of `self`. Hence
2706 /// `Foo<Bar<i32>, u32>` yields the sequence `[Bar<i32>, u32]`
2707 /// (but not `i32`, like `walk`).
2708 pub fn walk_shallow(&'tcx self) -> smallvec::IntoIter<walk::TypeWalkerArray<'tcx>> {
2709 walk::walk_shallow(self)
2712 /// Walks `ty` and any types appearing within `ty`, invoking the
2713 /// callback `f` on each type. If the callback returns `false`, then the
2714 /// children of the current type are ignored.
2716 /// Note: prefer `ty.walk()` where possible.
2717 pub fn maybe_walk<F>(&'tcx self, mut f: F)
2719 F: FnMut(Ty<'tcx>) -> bool,
2721 let mut walker = self.walk();
2722 while let Some(ty) = walker.next() {
2724 walker.skip_current_subtree();
2731 pub fn from_mutbl(m: hir::Mutability) -> BorrowKind {
2733 hir::Mutability::Mut => MutBorrow,
2734 hir::Mutability::Not => ImmBorrow,
2738 /// Returns a mutability `m` such that an `&m T` pointer could be used to obtain this borrow
2739 /// kind. Because borrow kinds are richer than mutabilities, we sometimes have to pick a
2740 /// mutability that is stronger than necessary so that it at least *would permit* the borrow in
2742 pub fn to_mutbl_lossy(self) -> hir::Mutability {
2744 MutBorrow => hir::Mutability::Mut,
2745 ImmBorrow => hir::Mutability::Not,
2747 // We have no type corresponding to a unique imm borrow, so
2748 // use `&mut`. It gives all the capabilities of an `&uniq`
2749 // and hence is a safe "over approximation".
2750 UniqueImmBorrow => hir::Mutability::Mut,
2754 pub fn to_user_str(&self) -> &'static str {
2756 MutBorrow => "mutable",
2757 ImmBorrow => "immutable",
2758 UniqueImmBorrow => "uniquely immutable",
2763 #[derive(Debug, Clone)]
2764 pub enum Attributes<'tcx> {
2765 Owned(Lrc<[ast::Attribute]>),
2766 Borrowed(&'tcx [ast::Attribute]),
2769 impl<'tcx> ::std::ops::Deref for Attributes<'tcx> {
2770 type Target = [ast::Attribute];
2772 fn deref(&self) -> &[ast::Attribute] {
2774 &Attributes::Owned(ref data) => &data,
2775 &Attributes::Borrowed(data) => data,
2780 #[derive(Debug, PartialEq, Eq)]
2781 pub enum ImplOverlapKind {
2782 /// These impls are always allowed to overlap.
2784 /// Whether or not the impl is permitted due to the trait being a `#[marker]` trait
2787 /// These impls are allowed to overlap, but that raises
2788 /// an issue #33140 future-compatibility warning.
2790 /// Some background: in Rust 1.0, the trait-object types `Send + Sync` (today's
2791 /// `dyn Send + Sync`) and `Sync + Send` (now `dyn Sync + Send`) were different.
2793 /// The widely-used version 0.1.0 of the crate `traitobject` had accidentally relied
2794 /// that difference, making what reduces to the following set of impls:
2798 /// impl Trait for dyn Send + Sync {}
2799 /// impl Trait for dyn Sync + Send {}
2802 /// Obviously, once we made these types be identical, that code causes a coherence
2803 /// error and a fairly big headache for us. However, luckily for us, the trait
2804 /// `Trait` used in this case is basically a marker trait, and therefore having
2805 /// overlapping impls for it is sound.
2807 /// To handle this, we basically regard the trait as a marker trait, with an additional
2808 /// future-compatibility warning. To avoid accidentally "stabilizing" this feature,
2809 /// it has the following restrictions:
2811 /// 1. The trait must indeed be a marker-like trait (i.e., no items), and must be
2813 /// 2. The trait-ref of both impls must be equal.
2814 /// 3. The trait-ref of both impls must be a trait object type consisting only of
2816 /// 4. Neither of the impls can have any where-clauses.
2818 /// Once `traitobject` 0.1.0 is no longer an active concern, this hack can be removed.
2822 impl<'tcx> TyCtxt<'tcx> {
2823 pub fn body_tables(self, body: hir::BodyId) -> &'tcx TypeckTables<'tcx> {
2824 self.typeck_tables_of(self.hir().body_owner_def_id(body))
2827 /// Returns an iterator of the `DefId`s for all body-owners in this
2828 /// crate. If you would prefer to iterate over the bodies
2829 /// themselves, you can do `self.hir().krate().body_ids.iter()`.
2830 pub fn body_owners(self) -> impl Iterator<Item = DefId> + Captures<'tcx> + 'tcx {
2835 .map(move |&body_id| self.hir().body_owner_def_id(body_id))
2838 pub fn par_body_owners<F: Fn(DefId) + sync::Sync + sync::Send>(self, f: F) {
2839 par_iter(&self.hir().krate().body_ids)
2840 .for_each(|&body_id| f(self.hir().body_owner_def_id(body_id)));
2843 pub fn provided_trait_methods(self, id: DefId) -> impl 'tcx + Iterator<Item = &'tcx AssocItem> {
2844 self.associated_items(id)
2845 .in_definition_order()
2846 .filter(|item| item.kind == AssocKind::Method && item.defaultness.has_value())
2849 pub fn trait_relevant_for_never(self, did: DefId) -> bool {
2850 self.associated_items(did).in_definition_order().any(|item| item.relevant_for_never())
2853 pub fn opt_item_name(self, def_id: DefId) -> Option<Ident> {
2854 self.hir().as_local_hir_id(def_id).and_then(|hir_id| self.hir().get(hir_id).ident())
2857 pub fn opt_associated_item(self, def_id: DefId) -> Option<AssocItem> {
2858 let is_associated_item = if let Some(hir_id) = self.hir().as_local_hir_id(def_id) {
2859 match self.hir().get(hir_id) {
2860 Node::TraitItem(_) | Node::ImplItem(_) => true,
2864 match self.def_kind(def_id) {
2865 Some(DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy) => true,
2870 is_associated_item.then(|| self.associated_item(def_id))
2873 pub fn field_index(self, hir_id: hir::HirId, tables: &TypeckTables<'_>) -> usize {
2874 tables.field_indices().get(hir_id).cloned().expect("no index for a field")
2877 pub fn find_field_index(self, ident: Ident, variant: &VariantDef) -> Option<usize> {
2878 variant.fields.iter().position(|field| self.hygienic_eq(ident, field.ident, variant.def_id))
2881 /// Returns `true` if the impls are the same polarity and the trait either
2882 /// has no items or is annotated #[marker] and prevents item overrides.
2883 pub fn impls_are_allowed_to_overlap(
2887 ) -> Option<ImplOverlapKind> {
2888 // If either trait impl references an error, they're allowed to overlap,
2889 // as one of them essentially doesn't exist.
2890 if self.impl_trait_ref(def_id1).map_or(false, |tr| tr.references_error())
2891 || self.impl_trait_ref(def_id2).map_or(false, |tr| tr.references_error())
2893 return Some(ImplOverlapKind::Permitted { marker: false });
2896 match (self.impl_polarity(def_id1), self.impl_polarity(def_id2)) {
2897 (ImplPolarity::Reservation, _) | (_, ImplPolarity::Reservation) => {
2898 // `#[rustc_reservation_impl]` impls don't overlap with anything
2900 "impls_are_allowed_to_overlap({:?}, {:?}) = Some(Permitted) (reservations)",
2903 return Some(ImplOverlapKind::Permitted { marker: false });
2905 (ImplPolarity::Positive, ImplPolarity::Negative)
2906 | (ImplPolarity::Negative, ImplPolarity::Positive) => {
2907 // `impl AutoTrait for Type` + `impl !AutoTrait for Type`
2909 "impls_are_allowed_to_overlap({:?}, {:?}) - None (differing polarities)",
2914 (ImplPolarity::Positive, ImplPolarity::Positive)
2915 | (ImplPolarity::Negative, ImplPolarity::Negative) => {}
2918 let is_marker_overlap = {
2919 let is_marker_impl = |def_id: DefId| -> bool {
2920 let trait_ref = self.impl_trait_ref(def_id);
2921 trait_ref.map_or(false, |tr| self.trait_def(tr.def_id).is_marker)
2923 is_marker_impl(def_id1) && is_marker_impl(def_id2)
2926 if is_marker_overlap {
2928 "impls_are_allowed_to_overlap({:?}, {:?}) = Some(Permitted) (marker overlap)",
2931 Some(ImplOverlapKind::Permitted { marker: true })
2933 if let Some(self_ty1) = self.issue33140_self_ty(def_id1) {
2934 if let Some(self_ty2) = self.issue33140_self_ty(def_id2) {
2935 if self_ty1 == self_ty2 {
2937 "impls_are_allowed_to_overlap({:?}, {:?}) - issue #33140 HACK",
2940 return Some(ImplOverlapKind::Issue33140);
2943 "impls_are_allowed_to_overlap({:?}, {:?}) - found {:?} != {:?}",
2944 def_id1, def_id2, self_ty1, self_ty2
2950 debug!("impls_are_allowed_to_overlap({:?}, {:?}) = None", def_id1, def_id2);
2955 /// Returns `ty::VariantDef` if `res` refers to a struct,
2956 /// or variant or their constructors, panics otherwise.
2957 pub fn expect_variant_res(self, res: Res) -> &'tcx VariantDef {
2959 Res::Def(DefKind::Variant, did) => {
2960 let enum_did = self.parent(did).unwrap();
2961 self.adt_def(enum_did).variant_with_id(did)
2963 Res::Def(DefKind::Struct, did) | Res::Def(DefKind::Union, did) => {
2964 self.adt_def(did).non_enum_variant()
2966 Res::Def(DefKind::Ctor(CtorOf::Variant, ..), variant_ctor_did) => {
2967 let variant_did = self.parent(variant_ctor_did).unwrap();
2968 let enum_did = self.parent(variant_did).unwrap();
2969 self.adt_def(enum_did).variant_with_ctor_id(variant_ctor_did)
2971 Res::Def(DefKind::Ctor(CtorOf::Struct, ..), ctor_did) => {
2972 let struct_did = self.parent(ctor_did).expect("struct ctor has no parent");
2973 self.adt_def(struct_did).non_enum_variant()
2975 _ => bug!("expect_variant_res used with unexpected res {:?}", res),
2979 pub fn item_name(self, id: DefId) -> Symbol {
2980 if id.index == CRATE_DEF_INDEX {
2981 self.original_crate_name(id.krate)
2983 let def_key = self.def_key(id);
2984 match def_key.disambiguated_data.data {
2985 // The name of a constructor is that of its parent.
2986 rustc_hir::definitions::DefPathData::Ctor => {
2987 self.item_name(DefId { krate: id.krate, index: def_key.parent.unwrap() })
2989 _ => def_key.disambiguated_data.data.get_opt_name().unwrap_or_else(|| {
2990 bug!("item_name: no name for {:?}", self.def_path(id));
2996 /// Returns the possibly-auto-generated MIR of a `(DefId, Subst)` pair.
2997 pub fn instance_mir(self, instance: ty::InstanceDef<'tcx>) -> ReadOnlyBodyAndCache<'tcx, 'tcx> {
2999 ty::InstanceDef::Item(did) => self.optimized_mir(did).unwrap_read_only(),
3000 ty::InstanceDef::VtableShim(..)
3001 | ty::InstanceDef::ReifyShim(..)
3002 | ty::InstanceDef::Intrinsic(..)
3003 | ty::InstanceDef::FnPtrShim(..)
3004 | ty::InstanceDef::Virtual(..)
3005 | ty::InstanceDef::ClosureOnceShim { .. }
3006 | ty::InstanceDef::DropGlue(..)
3007 | ty::InstanceDef::CloneShim(..) => self.mir_shims(instance).unwrap_read_only(),
3011 /// Gets the attributes of a definition.
3012 pub fn get_attrs(self, did: DefId) -> Attributes<'tcx> {
3013 if let Some(id) = self.hir().as_local_hir_id(did) {
3014 Attributes::Borrowed(self.hir().attrs(id))
3016 Attributes::Borrowed(self.item_attrs(did))
3020 /// Determines whether an item is annotated with an attribute.
3021 pub fn has_attr(self, did: DefId, attr: Symbol) -> bool {
3022 attr::contains_name(&self.get_attrs(did), attr)
3025 /// Returns `true` if this is an `auto trait`.
3026 pub fn trait_is_auto(self, trait_def_id: DefId) -> bool {
3027 self.trait_def(trait_def_id).has_auto_impl
3030 pub fn generator_layout(self, def_id: DefId) -> &'tcx GeneratorLayout<'tcx> {
3031 self.optimized_mir(def_id).generator_layout.as_ref().unwrap()
3034 /// Given the `DefId` of an impl, returns the `DefId` of the trait it implements.
3035 /// If it implements no trait, returns `None`.
3036 pub fn trait_id_of_impl(self, def_id: DefId) -> Option<DefId> {
3037 self.impl_trait_ref(def_id).map(|tr| tr.def_id)
3040 /// If the given defid describes a method belonging to an impl, returns the
3041 /// `DefId` of the impl that the method belongs to; otherwise, returns `None`.
3042 pub fn impl_of_method(self, def_id: DefId) -> Option<DefId> {
3043 self.opt_associated_item(def_id).and_then(|trait_item| match trait_item.container {
3044 TraitContainer(_) => None,
3045 ImplContainer(def_id) => Some(def_id),
3049 /// Looks up the span of `impl_did` if the impl is local; otherwise returns `Err`
3050 /// with the name of the crate containing the impl.
3051 pub fn span_of_impl(self, impl_did: DefId) -> Result<Span, Symbol> {
3052 if impl_did.is_local() {
3053 let hir_id = self.hir().as_local_hir_id(impl_did).unwrap();
3054 Ok(self.hir().span(hir_id))
3056 Err(self.crate_name(impl_did.krate))
3060 /// Hygienically compares a use-site name (`use_name`) for a field or an associated item with
3061 /// its supposed definition name (`def_name`). The method also needs `DefId` of the supposed
3062 /// definition's parent/scope to perform comparison.
3063 pub fn hygienic_eq(self, use_name: Ident, def_name: Ident, def_parent_def_id: DefId) -> bool {
3064 // We could use `Ident::eq` here, but we deliberately don't. The name
3065 // comparison fails frequently, and we want to avoid the expensive
3066 // `normalize_to_macros_2_0()` calls required for the span comparison whenever possible.
3067 use_name.name == def_name.name
3071 .hygienic_eq(def_name.span.ctxt(), self.expansion_that_defined(def_parent_def_id))
3074 fn expansion_that_defined(self, scope: DefId) -> ExpnId {
3075 match scope.as_local() {
3076 Some(scope) => self.hir().definitions().expansion_that_defined(scope),
3077 None => ExpnId::root(),
3081 pub fn adjust_ident(self, mut ident: Ident, scope: DefId) -> Ident {
3082 ident.span.normalize_to_macros_2_0_and_adjust(self.expansion_that_defined(scope));
3086 pub fn adjust_ident_and_get_scope(
3091 ) -> (Ident, DefId) {
3093 match ident.span.normalize_to_macros_2_0_and_adjust(self.expansion_that_defined(scope))
3095 Some(actual_expansion) => {
3096 self.hir().definitions().parent_module_of_macro_def(actual_expansion)
3098 None => self.parent_module(block).to_def_id(),
3103 pub fn is_object_safe(self, key: DefId) -> bool {
3104 self.object_safety_violations(key).is_empty()
3108 #[derive(Clone, HashStable)]
3109 pub struct AdtSizedConstraint<'tcx>(pub &'tcx [Ty<'tcx>]);
3111 /// Yields the parent function's `DefId` if `def_id` is an `impl Trait` definition.
3112 pub fn is_impl_trait_defn(tcx: TyCtxt<'_>, def_id: DefId) -> Option<DefId> {
3113 if let Some(hir_id) = tcx.hir().as_local_hir_id(def_id) {
3114 if let Node::Item(item) = tcx.hir().get(hir_id) {
3115 if let hir::ItemKind::OpaqueTy(ref opaque_ty) = item.kind {
3116 return opaque_ty.impl_trait_fn;
3123 pub fn provide(providers: &mut ty::query::Providers<'_>) {
3124 context::provide(providers);
3125 erase_regions::provide(providers);
3126 layout::provide(providers);
3127 super::util::bug::provide(providers);
3128 *providers = ty::query::Providers {
3129 trait_impls_of: trait_def::trait_impls_of_provider,
3130 all_local_trait_impls: trait_def::all_local_trait_impls,
3135 /// A map for the local crate mapping each type to a vector of its
3136 /// inherent impls. This is not meant to be used outside of coherence;
3137 /// rather, you should request the vector for a specific type via
3138 /// `tcx.inherent_impls(def_id)` so as to minimize your dependencies
3139 /// (constructing this map requires touching the entire crate).
3140 #[derive(Clone, Debug, Default, HashStable)]
3141 pub struct CrateInherentImpls {
3142 pub inherent_impls: DefIdMap<Vec<DefId>>,
3145 #[derive(Clone, Copy, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
3146 pub struct SymbolName {
3147 // FIXME: we don't rely on interning or equality here - better have
3148 // this be a `&'tcx str`.
3153 pub fn new(name: &str) -> SymbolName {
3154 SymbolName { name: Symbol::intern(name) }
3158 impl PartialOrd for SymbolName {
3159 fn partial_cmp(&self, other: &SymbolName) -> Option<Ordering> {
3160 self.name.as_str().partial_cmp(&other.name.as_str())
3164 /// Ordering must use the chars to ensure reproducible builds.
3165 impl Ord for SymbolName {
3166 fn cmp(&self, other: &SymbolName) -> Ordering {
3167 self.name.as_str().cmp(&other.name.as_str())
3171 impl fmt::Display for SymbolName {
3172 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
3173 fmt::Display::fmt(&self.name, fmt)
3177 impl fmt::Debug for SymbolName {
3178 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
3179 fmt::Display::fmt(&self.name, fmt)