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 /// Flags representing the nominal content of a type,
601 /// computed by FlagsComputation. If you add a new nominal
602 /// flag, it should be added here too.
603 const NOMINAL_FLAGS = TypeFlags::HAS_TY_PARAM.bits
604 | TypeFlags::HAS_RE_PARAM.bits
605 | TypeFlags::HAS_CT_PARAM.bits
606 | TypeFlags::HAS_TY_INFER.bits
607 | TypeFlags::HAS_RE_INFER.bits
608 | TypeFlags::HAS_CT_INFER.bits
609 | TypeFlags::HAS_TY_PLACEHOLDER.bits
610 | TypeFlags::HAS_RE_PLACEHOLDER.bits
611 | TypeFlags::HAS_CT_PLACEHOLDER.bits
612 | TypeFlags::HAS_FREE_LOCAL_REGIONS.bits
613 | TypeFlags::HAS_TY_PROJECTION.bits
614 | TypeFlags::HAS_TY_OPAQUE.bits
615 | TypeFlags::HAS_CT_PROJECTION.bits
616 | TypeFlags::KEEP_IN_LOCAL_TCX.bits
617 | TypeFlags::HAS_TY_ERR.bits
618 | TypeFlags::HAS_FREE_REGIONS.bits
619 | TypeFlags::HAS_RE_LATE_BOUND.bits
620 | TypeFlags::HAS_RE_ERASED.bits;
624 #[allow(rustc::usage_of_ty_tykind)]
625 pub struct TyS<'tcx> {
626 pub kind: TyKind<'tcx>,
627 pub flags: TypeFlags,
629 /// This is a kind of confusing thing: it stores the smallest
632 /// (a) the binder itself captures nothing but
633 /// (b) all the late-bound things within the type are captured
634 /// by some sub-binder.
636 /// So, for a type without any late-bound things, like `u32`, this
637 /// will be *innermost*, because that is the innermost binder that
638 /// captures nothing. But for a type `&'D u32`, where `'D` is a
639 /// late-bound region with De Bruijn index `D`, this would be `D + 1`
640 /// -- the binder itself does not capture `D`, but `D` is captured
641 /// by an inner binder.
643 /// We call this concept an "exclusive" binder `D` because all
644 /// De Bruijn indices within the type are contained within `0..D`
646 outer_exclusive_binder: ty::DebruijnIndex,
649 // `TyS` is used a lot. Make sure it doesn't unintentionally get bigger.
650 #[cfg(target_arch = "x86_64")]
651 static_assert_size!(TyS<'_>, 32);
653 impl<'tcx> Ord for TyS<'tcx> {
654 fn cmp(&self, other: &TyS<'tcx>) -> Ordering {
655 self.kind.cmp(&other.kind)
659 impl<'tcx> PartialOrd for TyS<'tcx> {
660 fn partial_cmp(&self, other: &TyS<'tcx>) -> Option<Ordering> {
661 Some(self.kind.cmp(&other.kind))
665 impl<'tcx> PartialEq for TyS<'tcx> {
667 fn eq(&self, other: &TyS<'tcx>) -> bool {
671 impl<'tcx> Eq for TyS<'tcx> {}
673 impl<'tcx> Hash for TyS<'tcx> {
674 fn hash<H: Hasher>(&self, s: &mut H) {
675 (self as *const TyS<'_>).hash(s)
679 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for ty::TyS<'tcx> {
680 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
684 // The other fields just provide fast access to information that is
685 // also contained in `kind`, so no need to hash them.
688 outer_exclusive_binder: _,
691 kind.hash_stable(hcx, hasher);
695 #[rustc_diagnostic_item = "Ty"]
696 pub type Ty<'tcx> = &'tcx TyS<'tcx>;
698 impl<'tcx> rustc_serialize::UseSpecializedEncodable for Ty<'tcx> {}
699 impl<'tcx> rustc_serialize::UseSpecializedDecodable for Ty<'tcx> {}
701 pub type CanonicalTy<'tcx> = Canonical<'tcx, Ty<'tcx>>;
704 /// A dummy type used to force `List` to be unsized while not requiring references to it be wide
706 type OpaqueListContents;
709 /// A wrapper for slices with the additional invariant
710 /// that the slice is interned and no other slice with
711 /// the same contents can exist in the same context.
712 /// This means we can use pointer for both
713 /// equality comparisons and hashing.
714 /// Note: `Slice` was already taken by the `Ty`.
719 opaque: OpaqueListContents,
722 unsafe impl<T: Sync> Sync for List<T> {}
724 impl<T: Copy> List<T> {
726 fn from_arena<'tcx>(arena: &'tcx Arena<'tcx>, slice: &[T]) -> &'tcx List<T> {
727 assert!(!mem::needs_drop::<T>());
728 assert!(mem::size_of::<T>() != 0);
729 assert!(!slice.is_empty());
731 // Align up the size of the len (usize) field
732 let align = mem::align_of::<T>();
733 let align_mask = align - 1;
734 let offset = mem::size_of::<usize>();
735 let offset = (offset + align_mask) & !align_mask;
737 let size = offset + slice.len() * mem::size_of::<T>();
741 .alloc_raw(size, cmp::max(mem::align_of::<T>(), mem::align_of::<usize>()));
743 let result = &mut *(mem.as_mut_ptr() as *mut List<T>);
745 result.len = slice.len();
747 // Write the elements
748 let arena_slice = slice::from_raw_parts_mut(result.data.as_mut_ptr(), result.len);
749 arena_slice.copy_from_slice(slice);
756 impl<T: fmt::Debug> fmt::Debug for List<T> {
757 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
762 impl<T: Encodable> Encodable for List<T> {
764 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
769 impl<T> Ord for List<T>
773 fn cmp(&self, other: &List<T>) -> Ordering {
774 if self == other { Ordering::Equal } else { <[T] as Ord>::cmp(&**self, &**other) }
778 impl<T> PartialOrd for List<T>
782 fn partial_cmp(&self, other: &List<T>) -> Option<Ordering> {
784 Some(Ordering::Equal)
786 <[T] as PartialOrd>::partial_cmp(&**self, &**other)
791 impl<T: PartialEq> PartialEq for List<T> {
793 fn eq(&self, other: &List<T>) -> bool {
797 impl<T: Eq> Eq for List<T> {}
799 impl<T> Hash for List<T> {
801 fn hash<H: Hasher>(&self, s: &mut H) {
802 (self as *const List<T>).hash(s)
806 impl<T> Deref for List<T> {
809 fn deref(&self) -> &[T] {
814 impl<T> AsRef<[T]> for List<T> {
816 fn as_ref(&self) -> &[T] {
817 unsafe { slice::from_raw_parts(self.data.as_ptr(), self.len) }
821 impl<'a, T> IntoIterator for &'a List<T> {
823 type IntoIter = <&'a [T] as IntoIterator>::IntoIter;
825 fn into_iter(self) -> Self::IntoIter {
830 impl<'tcx> rustc_serialize::UseSpecializedDecodable for &'tcx List<Ty<'tcx>> {}
834 pub fn empty<'a>() -> &'a List<T> {
835 #[repr(align(64), C)]
836 struct EmptySlice([u8; 64]);
837 static EMPTY_SLICE: EmptySlice = EmptySlice([0; 64]);
838 assert!(mem::align_of::<T>() <= 64);
839 unsafe { &*(&EMPTY_SLICE as *const _ as *const List<T>) }
843 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
844 pub struct UpvarPath {
845 pub hir_id: hir::HirId,
848 /// Upvars do not get their own `NodeId`. Instead, we use the pair of
849 /// the original var ID (that is, the root variable that is referenced
850 /// by the upvar) and the ID of the closure expression.
851 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
853 pub var_path: UpvarPath,
854 pub closure_expr_id: LocalDefId,
857 #[derive(Clone, PartialEq, Debug, RustcEncodable, RustcDecodable, Copy, HashStable)]
858 pub enum BorrowKind {
859 /// Data must be immutable and is aliasable.
862 /// Data must be immutable but not aliasable. This kind of borrow
863 /// cannot currently be expressed by the user and is used only in
864 /// implicit closure bindings. It is needed when the closure
865 /// is borrowing or mutating a mutable referent, e.g.:
867 /// let x: &mut isize = ...;
868 /// let y = || *x += 5;
870 /// If we were to try to translate this closure into a more explicit
871 /// form, we'd encounter an error with the code as written:
873 /// struct Env { x: & &mut isize }
874 /// let x: &mut isize = ...;
875 /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
876 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
878 /// This is then illegal because you cannot mutate a `&mut` found
879 /// in an aliasable location. To solve, you'd have to translate with
880 /// an `&mut` borrow:
882 /// struct Env { x: & &mut isize }
883 /// let x: &mut isize = ...;
884 /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
885 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
887 /// Now the assignment to `**env.x` is legal, but creating a
888 /// mutable pointer to `x` is not because `x` is not mutable. We
889 /// could fix this by declaring `x` as `let mut x`. This is ok in
890 /// user code, if awkward, but extra weird for closures, since the
891 /// borrow is hidden.
893 /// So we introduce a "unique imm" borrow -- the referent is
894 /// immutable, but not aliasable. This solves the problem. For
895 /// simplicity, we don't give users the way to express this
896 /// borrow, it's just used when translating closures.
899 /// Data is mutable and not aliasable.
903 /// Information describing the capture of an upvar. This is computed
904 /// during `typeck`, specifically by `regionck`.
905 #[derive(PartialEq, Clone, Debug, Copy, RustcEncodable, RustcDecodable, HashStable)]
906 pub enum UpvarCapture<'tcx> {
907 /// Upvar is captured by value. This is always true when the
908 /// closure is labeled `move`, but can also be true in other cases
909 /// depending on inference.
912 /// Upvar is captured by reference.
913 ByRef(UpvarBorrow<'tcx>),
916 #[derive(PartialEq, Clone, Copy, RustcEncodable, RustcDecodable, HashStable)]
917 pub struct UpvarBorrow<'tcx> {
918 /// The kind of borrow: by-ref upvars have access to shared
919 /// immutable borrows, which are not part of the normal language
921 pub kind: BorrowKind,
923 /// Region of the resulting reference.
924 pub region: ty::Region<'tcx>,
927 pub type UpvarListMap = FxHashMap<DefId, FxIndexMap<hir::HirId, UpvarId>>;
928 pub type UpvarCaptureMap<'tcx> = FxHashMap<UpvarId, UpvarCapture<'tcx>>;
930 #[derive(Clone, Copy, PartialEq, Eq)]
931 pub enum IntVarValue {
933 UintType(ast::UintTy),
936 #[derive(Clone, Copy, PartialEq, Eq)]
937 pub struct FloatVarValue(pub ast::FloatTy);
939 impl ty::EarlyBoundRegion {
940 pub fn to_bound_region(&self) -> ty::BoundRegion {
941 ty::BoundRegion::BrNamed(self.def_id, self.name)
944 /// Does this early bound region have a name? Early bound regions normally
945 /// always have names except when using anonymous lifetimes (`'_`).
946 pub fn has_name(&self) -> bool {
947 self.name != kw::UnderscoreLifetime
951 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
952 pub enum GenericParamDefKind {
956 object_lifetime_default: ObjectLifetimeDefault,
957 synthetic: Option<hir::SyntheticTyParamKind>,
962 impl GenericParamDefKind {
963 pub fn descr(&self) -> &'static str {
965 GenericParamDefKind::Lifetime => "lifetime",
966 GenericParamDefKind::Type { .. } => "type",
967 GenericParamDefKind::Const => "constant",
972 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
973 pub struct GenericParamDef {
978 /// `pure_wrt_drop`, set by the (unsafe) `#[may_dangle]` attribute
979 /// on generic parameter `'a`/`T`, asserts data behind the parameter
980 /// `'a`/`T` won't be accessed during the parent type's `Drop` impl.
981 pub pure_wrt_drop: bool,
983 pub kind: GenericParamDefKind,
986 impl GenericParamDef {
987 pub fn to_early_bound_region_data(&self) -> ty::EarlyBoundRegion {
988 if let GenericParamDefKind::Lifetime = self.kind {
989 ty::EarlyBoundRegion { def_id: self.def_id, index: self.index, name: self.name }
991 bug!("cannot convert a non-lifetime parameter def to an early bound region")
995 pub fn to_bound_region(&self) -> ty::BoundRegion {
996 if let GenericParamDefKind::Lifetime = self.kind {
997 self.to_early_bound_region_data().to_bound_region()
999 bug!("cannot convert a non-lifetime parameter def to an early bound region")
1005 pub struct GenericParamCount {
1006 pub lifetimes: usize,
1011 /// Information about the formal type/lifetime parameters associated
1012 /// with an item or method. Analogous to `hir::Generics`.
1014 /// The ordering of parameters is the same as in `Subst` (excluding child generics):
1015 /// `Self` (optionally), `Lifetime` params..., `Type` params...
1016 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
1017 pub struct Generics {
1018 pub parent: Option<DefId>,
1019 pub parent_count: usize,
1020 pub params: Vec<GenericParamDef>,
1022 /// Reverse map to the `index` field of each `GenericParamDef`.
1023 #[stable_hasher(ignore)]
1024 pub param_def_id_to_index: FxHashMap<DefId, u32>,
1027 pub has_late_bound_regions: Option<Span>,
1030 impl<'tcx> Generics {
1031 pub fn count(&self) -> usize {
1032 self.parent_count + self.params.len()
1035 pub fn own_counts(&self) -> GenericParamCount {
1036 // We could cache this as a property of `GenericParamCount`, but
1037 // the aim is to refactor this away entirely eventually and the
1038 // presence of this method will be a constant reminder.
1039 let mut own_counts: GenericParamCount = Default::default();
1041 for param in &self.params {
1043 GenericParamDefKind::Lifetime => own_counts.lifetimes += 1,
1044 GenericParamDefKind::Type { .. } => own_counts.types += 1,
1045 GenericParamDefKind::Const => own_counts.consts += 1,
1052 pub fn requires_monomorphization(&self, tcx: TyCtxt<'tcx>) -> bool {
1053 if self.own_requires_monomorphization() {
1057 if let Some(parent_def_id) = self.parent {
1058 let parent = tcx.generics_of(parent_def_id);
1059 parent.requires_monomorphization(tcx)
1065 pub fn own_requires_monomorphization(&self) -> bool {
1066 for param in &self.params {
1068 GenericParamDefKind::Type { .. } | GenericParamDefKind::Const => return true,
1069 GenericParamDefKind::Lifetime => {}
1075 pub fn region_param(
1077 param: &EarlyBoundRegion,
1079 ) -> &'tcx GenericParamDef {
1080 if let Some(index) = param.index.checked_sub(self.parent_count as u32) {
1081 let param = &self.params[index as usize];
1083 GenericParamDefKind::Lifetime => param,
1084 _ => bug!("expected lifetime parameter, but found another generic parameter"),
1087 tcx.generics_of(self.parent.expect("parent_count > 0 but no parent?"))
1088 .region_param(param, tcx)
1092 /// Returns the `GenericParamDef` associated with this `ParamTy`.
1093 pub fn type_param(&'tcx self, param: &ParamTy, tcx: TyCtxt<'tcx>) -> &'tcx GenericParamDef {
1094 if let Some(index) = param.index.checked_sub(self.parent_count as u32) {
1095 let param = &self.params[index as usize];
1097 GenericParamDefKind::Type { .. } => param,
1098 _ => bug!("expected type parameter, but found another generic parameter"),
1101 tcx.generics_of(self.parent.expect("parent_count > 0 but no parent?"))
1102 .type_param(param, tcx)
1106 /// Returns the `ConstParameterDef` associated with this `ParamConst`.
1107 pub fn const_param(&'tcx self, param: &ParamConst, tcx: TyCtxt<'tcx>) -> &GenericParamDef {
1108 if let Some(index) = param.index.checked_sub(self.parent_count as u32) {
1109 let param = &self.params[index as usize];
1111 GenericParamDefKind::Const => param,
1112 _ => bug!("expected const parameter, but found another generic parameter"),
1115 tcx.generics_of(self.parent.expect("parent_count>0 but no parent?"))
1116 .const_param(param, tcx)
1121 /// Bounds on generics.
1122 #[derive(Copy, Clone, Default, Debug, RustcEncodable, RustcDecodable, HashStable)]
1123 pub struct GenericPredicates<'tcx> {
1124 pub parent: Option<DefId>,
1125 pub predicates: &'tcx [(Predicate<'tcx>, Span)],
1128 impl<'tcx> GenericPredicates<'tcx> {
1132 substs: SubstsRef<'tcx>,
1133 ) -> InstantiatedPredicates<'tcx> {
1134 let mut instantiated = InstantiatedPredicates::empty();
1135 self.instantiate_into(tcx, &mut instantiated, substs);
1139 pub fn instantiate_own(
1142 substs: SubstsRef<'tcx>,
1143 ) -> InstantiatedPredicates<'tcx> {
1144 InstantiatedPredicates {
1145 predicates: self.predicates.iter().map(|(p, _)| p.subst(tcx, substs)).collect(),
1146 spans: self.predicates.iter().map(|(_, sp)| *sp).collect(),
1150 fn instantiate_into(
1153 instantiated: &mut InstantiatedPredicates<'tcx>,
1154 substs: SubstsRef<'tcx>,
1156 if let Some(def_id) = self.parent {
1157 tcx.predicates_of(def_id).instantiate_into(tcx, instantiated, substs);
1159 instantiated.predicates.extend(self.predicates.iter().map(|(p, _)| p.subst(tcx, substs)));
1160 instantiated.spans.extend(self.predicates.iter().map(|(_, sp)| *sp));
1163 pub fn instantiate_identity(&self, tcx: TyCtxt<'tcx>) -> InstantiatedPredicates<'tcx> {
1164 let mut instantiated = InstantiatedPredicates::empty();
1165 self.instantiate_identity_into(tcx, &mut instantiated);
1169 fn instantiate_identity_into(
1172 instantiated: &mut InstantiatedPredicates<'tcx>,
1174 if let Some(def_id) = self.parent {
1175 tcx.predicates_of(def_id).instantiate_identity_into(tcx, instantiated);
1177 instantiated.predicates.extend(self.predicates.iter().map(|(p, _)| p));
1178 instantiated.spans.extend(self.predicates.iter().map(|(_, s)| s));
1181 pub fn instantiate_supertrait(
1184 poly_trait_ref: &ty::PolyTraitRef<'tcx>,
1185 ) -> InstantiatedPredicates<'tcx> {
1186 assert_eq!(self.parent, None);
1187 InstantiatedPredicates {
1191 .map(|(pred, _)| pred.subst_supertrait(tcx, poly_trait_ref))
1193 spans: self.predicates.iter().map(|(_, sp)| *sp).collect(),
1198 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1199 #[derive(HashStable, TypeFoldable)]
1200 pub enum Predicate<'tcx> {
1201 /// Corresponds to `where Foo: Bar<A, B, C>`. `Foo` here would be
1202 /// the `Self` type of the trait reference and `A`, `B`, and `C`
1203 /// would be the type parameters.
1205 /// A trait predicate will have `Constness::Const` if it originates
1206 /// from a bound on a `const fn` without the `?const` opt-out (e.g.,
1207 /// `const fn foobar<Foo: Bar>() {}`).
1208 Trait(PolyTraitPredicate<'tcx>, Constness),
1211 RegionOutlives(PolyRegionOutlivesPredicate<'tcx>),
1214 TypeOutlives(PolyTypeOutlivesPredicate<'tcx>),
1216 /// `where <T as TraitRef>::Name == X`, approximately.
1217 /// See the `ProjectionPredicate` struct for details.
1218 Projection(PolyProjectionPredicate<'tcx>),
1220 /// No syntax: `T` well-formed.
1221 WellFormed(Ty<'tcx>),
1223 /// Trait must be object-safe.
1226 /// No direct syntax. May be thought of as `where T: FnFoo<...>`
1227 /// for some substitutions `...` and `T` being a closure type.
1228 /// Satisfied (or refuted) once we know the closure's kind.
1229 ClosureKind(DefId, SubstsRef<'tcx>, ClosureKind),
1232 Subtype(PolySubtypePredicate<'tcx>),
1234 /// Constant initializer must evaluate successfully.
1235 ConstEvaluatable(DefId, SubstsRef<'tcx>),
1238 /// The crate outlives map is computed during typeck and contains the
1239 /// outlives of every item in the local crate. You should not use it
1240 /// directly, because to do so will make your pass dependent on the
1241 /// HIR of every item in the local crate. Instead, use
1242 /// `tcx.inferred_outlives_of()` to get the outlives for a *particular*
1244 #[derive(HashStable)]
1245 pub struct CratePredicatesMap<'tcx> {
1246 /// For each struct with outlive bounds, maps to a vector of the
1247 /// predicate of its outlive bounds. If an item has no outlives
1248 /// bounds, it will have no entry.
1249 pub predicates: FxHashMap<DefId, &'tcx [(ty::Predicate<'tcx>, Span)]>,
1252 impl<'tcx> AsRef<Predicate<'tcx>> for Predicate<'tcx> {
1253 fn as_ref(&self) -> &Predicate<'tcx> {
1258 impl<'tcx> Predicate<'tcx> {
1259 /// Performs a substitution suitable for going from a
1260 /// poly-trait-ref to supertraits that must hold if that
1261 /// poly-trait-ref holds. This is slightly different from a normal
1262 /// substitution in terms of what happens with bound regions. See
1263 /// lengthy comment below for details.
1264 pub fn subst_supertrait(
1267 trait_ref: &ty::PolyTraitRef<'tcx>,
1268 ) -> ty::Predicate<'tcx> {
1269 // The interaction between HRTB and supertraits is not entirely
1270 // obvious. Let me walk you (and myself) through an example.
1272 // Let's start with an easy case. Consider two traits:
1274 // trait Foo<'a>: Bar<'a,'a> { }
1275 // trait Bar<'b,'c> { }
1277 // Now, if we have a trait reference `for<'x> T: Foo<'x>`, then
1278 // we can deduce that `for<'x> T: Bar<'x,'x>`. Basically, if we
1279 // knew that `Foo<'x>` (for any 'x) then we also know that
1280 // `Bar<'x,'x>` (for any 'x). This more-or-less falls out from
1281 // normal substitution.
1283 // In terms of why this is sound, the idea is that whenever there
1284 // is an impl of `T:Foo<'a>`, it must show that `T:Bar<'a,'a>`
1285 // holds. So if there is an impl of `T:Foo<'a>` that applies to
1286 // all `'a`, then we must know that `T:Bar<'a,'a>` holds for all
1289 // Another example to be careful of is this:
1291 // trait Foo1<'a>: for<'b> Bar1<'a,'b> { }
1292 // trait Bar1<'b,'c> { }
1294 // Here, if we have `for<'x> T: Foo1<'x>`, then what do we know?
1295 // The answer is that we know `for<'x,'b> T: Bar1<'x,'b>`. The
1296 // reason is similar to the previous example: any impl of
1297 // `T:Foo1<'x>` must show that `for<'b> T: Bar1<'x, 'b>`. So
1298 // basically we would want to collapse the bound lifetimes from
1299 // the input (`trait_ref`) and the supertraits.
1301 // To achieve this in practice is fairly straightforward. Let's
1302 // consider the more complicated scenario:
1304 // - We start out with `for<'x> T: Foo1<'x>`. In this case, `'x`
1305 // has a De Bruijn index of 1. We want to produce `for<'x,'b> T: Bar1<'x,'b>`,
1306 // where both `'x` and `'b` would have a DB index of 1.
1307 // The substitution from the input trait-ref is therefore going to be
1308 // `'a => 'x` (where `'x` has a DB index of 1).
1309 // - The super-trait-ref is `for<'b> Bar1<'a,'b>`, where `'a` is an
1310 // early-bound parameter and `'b' is a late-bound parameter with a
1312 // - If we replace `'a` with `'x` from the input, it too will have
1313 // a DB index of 1, and thus we'll have `for<'x,'b> Bar1<'x,'b>`
1314 // just as we wanted.
1316 // There is only one catch. If we just apply the substitution `'a
1317 // => 'x` to `for<'b> Bar1<'a,'b>`, the substitution code will
1318 // adjust the DB index because we substituting into a binder (it
1319 // tries to be so smart...) resulting in `for<'x> for<'b>
1320 // Bar1<'x,'b>` (we have no syntax for this, so use your
1321 // imagination). Basically the 'x will have DB index of 2 and 'b
1322 // will have DB index of 1. Not quite what we want. So we apply
1323 // the substitution to the *contents* of the trait reference,
1324 // rather than the trait reference itself (put another way, the
1325 // substitution code expects equal binding levels in the values
1326 // from the substitution and the value being substituted into, and
1327 // this trick achieves that).
1329 let substs = &trait_ref.skip_binder().substs;
1331 Predicate::Trait(ref binder, constness) => {
1332 Predicate::Trait(binder.map_bound(|data| data.subst(tcx, substs)), constness)
1334 Predicate::Subtype(ref binder) => {
1335 Predicate::Subtype(binder.map_bound(|data| data.subst(tcx, substs)))
1337 Predicate::RegionOutlives(ref binder) => {
1338 Predicate::RegionOutlives(binder.map_bound(|data| data.subst(tcx, substs)))
1340 Predicate::TypeOutlives(ref binder) => {
1341 Predicate::TypeOutlives(binder.map_bound(|data| data.subst(tcx, substs)))
1343 Predicate::Projection(ref binder) => {
1344 Predicate::Projection(binder.map_bound(|data| data.subst(tcx, substs)))
1346 Predicate::WellFormed(data) => Predicate::WellFormed(data.subst(tcx, substs)),
1347 Predicate::ObjectSafe(trait_def_id) => Predicate::ObjectSafe(trait_def_id),
1348 Predicate::ClosureKind(closure_def_id, closure_substs, kind) => {
1349 Predicate::ClosureKind(closure_def_id, closure_substs.subst(tcx, substs), kind)
1351 Predicate::ConstEvaluatable(def_id, const_substs) => {
1352 Predicate::ConstEvaluatable(def_id, const_substs.subst(tcx, substs))
1358 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1359 #[derive(HashStable, TypeFoldable)]
1360 pub struct TraitPredicate<'tcx> {
1361 pub trait_ref: TraitRef<'tcx>,
1364 pub type PolyTraitPredicate<'tcx> = ty::Binder<TraitPredicate<'tcx>>;
1366 impl<'tcx> TraitPredicate<'tcx> {
1367 pub fn def_id(&self) -> DefId {
1368 self.trait_ref.def_id
1371 pub fn input_types<'a>(&'a self) -> impl DoubleEndedIterator<Item = Ty<'tcx>> + 'a {
1372 self.trait_ref.input_types()
1375 pub fn self_ty(&self) -> Ty<'tcx> {
1376 self.trait_ref.self_ty()
1380 impl<'tcx> PolyTraitPredicate<'tcx> {
1381 pub fn def_id(&self) -> DefId {
1382 // Ok to skip binder since trait `DefId` does not care about regions.
1383 self.skip_binder().def_id()
1387 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, RustcEncodable, RustcDecodable)]
1388 #[derive(HashStable, TypeFoldable)]
1389 pub struct OutlivesPredicate<A, B>(pub A, pub B); // `A: B`
1390 pub type PolyOutlivesPredicate<A, B> = ty::Binder<OutlivesPredicate<A, B>>;
1391 pub type RegionOutlivesPredicate<'tcx> = OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>;
1392 pub type TypeOutlivesPredicate<'tcx> = OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>;
1393 pub type PolyRegionOutlivesPredicate<'tcx> = ty::Binder<RegionOutlivesPredicate<'tcx>>;
1394 pub type PolyTypeOutlivesPredicate<'tcx> = ty::Binder<TypeOutlivesPredicate<'tcx>>;
1396 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
1397 #[derive(HashStable, TypeFoldable)]
1398 pub struct SubtypePredicate<'tcx> {
1399 pub a_is_expected: bool,
1403 pub type PolySubtypePredicate<'tcx> = ty::Binder<SubtypePredicate<'tcx>>;
1405 /// This kind of predicate has no *direct* correspondent in the
1406 /// syntax, but it roughly corresponds to the syntactic forms:
1408 /// 1. `T: TraitRef<..., Item = Type>`
1409 /// 2. `<T as TraitRef<...>>::Item == Type` (NYI)
1411 /// In particular, form #1 is "desugared" to the combination of a
1412 /// normal trait predicate (`T: TraitRef<...>`) and one of these
1413 /// predicates. Form #2 is a broader form in that it also permits
1414 /// equality between arbitrary types. Processing an instance of
1415 /// Form #2 eventually yields one of these `ProjectionPredicate`
1416 /// instances to normalize the LHS.
1417 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1418 #[derive(HashStable, TypeFoldable)]
1419 pub struct ProjectionPredicate<'tcx> {
1420 pub projection_ty: ProjectionTy<'tcx>,
1424 pub type PolyProjectionPredicate<'tcx> = Binder<ProjectionPredicate<'tcx>>;
1426 impl<'tcx> PolyProjectionPredicate<'tcx> {
1427 /// Returns the `DefId` of the associated item being projected.
1428 pub fn item_def_id(&self) -> DefId {
1429 self.skip_binder().projection_ty.item_def_id
1433 pub fn to_poly_trait_ref(&self, tcx: TyCtxt<'tcx>) -> PolyTraitRef<'tcx> {
1434 // Note: unlike with `TraitRef::to_poly_trait_ref()`,
1435 // `self.0.trait_ref` is permitted to have escaping regions.
1436 // This is because here `self` has a `Binder` and so does our
1437 // return value, so we are preserving the number of binding
1439 self.map_bound(|predicate| predicate.projection_ty.trait_ref(tcx))
1442 pub fn ty(&self) -> Binder<Ty<'tcx>> {
1443 self.map_bound(|predicate| predicate.ty)
1446 /// The `DefId` of the `TraitItem` for the associated type.
1448 /// Note that this is not the `DefId` of the `TraitRef` containing this
1449 /// associated type, which is in `tcx.associated_item(projection_def_id()).container`.
1450 pub fn projection_def_id(&self) -> DefId {
1451 // Ok to skip binder since trait `DefId` does not care about regions.
1452 self.skip_binder().projection_ty.item_def_id
1456 pub trait ToPolyTraitRef<'tcx> {
1457 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx>;
1460 impl<'tcx> ToPolyTraitRef<'tcx> for TraitRef<'tcx> {
1461 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
1462 ty::Binder::dummy(*self)
1466 impl<'tcx> ToPolyTraitRef<'tcx> for PolyTraitPredicate<'tcx> {
1467 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
1468 self.map_bound_ref(|trait_pred| trait_pred.trait_ref)
1472 pub trait ToPredicate<'tcx> {
1473 fn to_predicate(&self) -> Predicate<'tcx>;
1476 impl<'tcx> ToPredicate<'tcx> for ConstnessAnd<TraitRef<'tcx>> {
1477 fn to_predicate(&self) -> Predicate<'tcx> {
1478 ty::Predicate::Trait(
1479 ty::Binder::dummy(ty::TraitPredicate { trait_ref: self.value }),
1485 impl<'tcx> ToPredicate<'tcx> for ConstnessAnd<&TraitRef<'tcx>> {
1486 fn to_predicate(&self) -> Predicate<'tcx> {
1487 ty::Predicate::Trait(
1488 ty::Binder::dummy(ty::TraitPredicate { trait_ref: *self.value }),
1494 impl<'tcx> ToPredicate<'tcx> for ConstnessAnd<PolyTraitRef<'tcx>> {
1495 fn to_predicate(&self) -> Predicate<'tcx> {
1496 ty::Predicate::Trait(self.value.to_poly_trait_predicate(), self.constness)
1500 impl<'tcx> ToPredicate<'tcx> for ConstnessAnd<&PolyTraitRef<'tcx>> {
1501 fn to_predicate(&self) -> Predicate<'tcx> {
1502 ty::Predicate::Trait(self.value.to_poly_trait_predicate(), self.constness)
1506 impl<'tcx> ToPredicate<'tcx> for PolyRegionOutlivesPredicate<'tcx> {
1507 fn to_predicate(&self) -> Predicate<'tcx> {
1508 Predicate::RegionOutlives(*self)
1512 impl<'tcx> ToPredicate<'tcx> for PolyTypeOutlivesPredicate<'tcx> {
1513 fn to_predicate(&self) -> Predicate<'tcx> {
1514 Predicate::TypeOutlives(*self)
1518 impl<'tcx> ToPredicate<'tcx> for PolyProjectionPredicate<'tcx> {
1519 fn to_predicate(&self) -> Predicate<'tcx> {
1520 Predicate::Projection(*self)
1524 // A custom iterator used by `Predicate::walk_tys`.
1525 enum WalkTysIter<'tcx, I, J, K>
1527 I: Iterator<Item = Ty<'tcx>>,
1528 J: Iterator<Item = Ty<'tcx>>,
1529 K: Iterator<Item = Ty<'tcx>>,
1533 Two(Ty<'tcx>, Ty<'tcx>),
1539 impl<'tcx, I, J, K> Iterator for WalkTysIter<'tcx, I, J, K>
1541 I: Iterator<Item = Ty<'tcx>>,
1542 J: Iterator<Item = Ty<'tcx>>,
1543 K: Iterator<Item = Ty<'tcx>>,
1545 type Item = Ty<'tcx>;
1547 fn next(&mut self) -> Option<Ty<'tcx>> {
1549 WalkTysIter::None => None,
1550 WalkTysIter::One(item) => {
1551 *self = WalkTysIter::None;
1554 WalkTysIter::Two(item1, item2) => {
1555 *self = WalkTysIter::One(item2);
1558 WalkTysIter::Types(ref mut iter) => iter.next(),
1559 WalkTysIter::InputTypes(ref mut iter) => iter.next(),
1560 WalkTysIter::ProjectionTypes(ref mut iter) => iter.next(),
1565 impl<'tcx> Predicate<'tcx> {
1566 /// Iterates over the types in this predicate. Note that in all
1567 /// cases this is skipping over a binder, so late-bound regions
1568 /// with depth 0 are bound by the predicate.
1569 pub fn walk_tys(&'a self) -> impl Iterator<Item = Ty<'tcx>> + 'a {
1571 ty::Predicate::Trait(ref data, _) => {
1572 WalkTysIter::InputTypes(data.skip_binder().input_types())
1574 ty::Predicate::Subtype(binder) => {
1575 let SubtypePredicate { a, b, a_is_expected: _ } = binder.skip_binder();
1576 WalkTysIter::Two(a, b)
1578 ty::Predicate::TypeOutlives(binder) => WalkTysIter::One(binder.skip_binder().0),
1579 ty::Predicate::RegionOutlives(..) => WalkTysIter::None,
1580 ty::Predicate::Projection(ref data) => {
1581 let inner = data.skip_binder();
1582 WalkTysIter::ProjectionTypes(
1583 inner.projection_ty.substs.types().chain(Some(inner.ty)),
1586 ty::Predicate::WellFormed(data) => WalkTysIter::One(data),
1587 ty::Predicate::ObjectSafe(_trait_def_id) => WalkTysIter::None,
1588 ty::Predicate::ClosureKind(_closure_def_id, closure_substs, _kind) => {
1589 WalkTysIter::Types(closure_substs.types())
1591 ty::Predicate::ConstEvaluatable(_, substs) => WalkTysIter::Types(substs.types()),
1595 pub fn to_opt_poly_trait_ref(&self) -> Option<PolyTraitRef<'tcx>> {
1597 Predicate::Trait(ref t, _) => Some(t.to_poly_trait_ref()),
1598 Predicate::Projection(..)
1599 | Predicate::Subtype(..)
1600 | Predicate::RegionOutlives(..)
1601 | Predicate::WellFormed(..)
1602 | Predicate::ObjectSafe(..)
1603 | Predicate::ClosureKind(..)
1604 | Predicate::TypeOutlives(..)
1605 | Predicate::ConstEvaluatable(..) => None,
1609 pub fn to_opt_type_outlives(&self) -> Option<PolyTypeOutlivesPredicate<'tcx>> {
1611 Predicate::TypeOutlives(data) => Some(data),
1612 Predicate::Trait(..)
1613 | Predicate::Projection(..)
1614 | Predicate::Subtype(..)
1615 | Predicate::RegionOutlives(..)
1616 | Predicate::WellFormed(..)
1617 | Predicate::ObjectSafe(..)
1618 | Predicate::ClosureKind(..)
1619 | Predicate::ConstEvaluatable(..) => None,
1624 /// Represents the bounds declared on a particular set of type
1625 /// parameters. Should eventually be generalized into a flag list of
1626 /// where-clauses. You can obtain a `InstantiatedPredicates` list from a
1627 /// `GenericPredicates` by using the `instantiate` method. Note that this method
1628 /// reflects an important semantic invariant of `InstantiatedPredicates`: while
1629 /// the `GenericPredicates` are expressed in terms of the bound type
1630 /// parameters of the impl/trait/whatever, an `InstantiatedPredicates` instance
1631 /// represented a set of bounds for some particular instantiation,
1632 /// meaning that the generic parameters have been substituted with
1637 /// struct Foo<T, U: Bar<T>> { ... }
1639 /// Here, the `GenericPredicates` for `Foo` would contain a list of bounds like
1640 /// `[[], [U:Bar<T>]]`. Now if there were some particular reference
1641 /// like `Foo<isize,usize>`, then the `InstantiatedPredicates` would be `[[],
1642 /// [usize:Bar<isize>]]`.
1643 #[derive(Clone, Debug, TypeFoldable)]
1644 pub struct InstantiatedPredicates<'tcx> {
1645 pub predicates: Vec<Predicate<'tcx>>,
1646 pub spans: Vec<Span>,
1649 impl<'tcx> InstantiatedPredicates<'tcx> {
1650 pub fn empty() -> InstantiatedPredicates<'tcx> {
1651 InstantiatedPredicates { predicates: vec![], spans: vec![] }
1654 pub fn is_empty(&self) -> bool {
1655 self.predicates.is_empty()
1659 rustc_index::newtype_index! {
1660 /// "Universes" are used during type- and trait-checking in the
1661 /// presence of `for<..>` binders to control what sets of names are
1662 /// visible. Universes are arranged into a tree: the root universe
1663 /// contains names that are always visible. Each child then adds a new
1664 /// set of names that are visible, in addition to those of its parent.
1665 /// We say that the child universe "extends" the parent universe with
1668 /// To make this more concrete, consider this program:
1672 /// fn bar<T>(x: T) {
1673 /// let y: for<'a> fn(&'a u8, Foo) = ...;
1677 /// The struct name `Foo` is in the root universe U0. But the type
1678 /// parameter `T`, introduced on `bar`, is in an extended universe U1
1679 /// -- i.e., within `bar`, we can name both `T` and `Foo`, but outside
1680 /// of `bar`, we cannot name `T`. Then, within the type of `y`, the
1681 /// region `'a` is in a universe U2 that extends U1, because we can
1682 /// name it inside the fn type but not outside.
1684 /// Universes are used to do type- and trait-checking around these
1685 /// "forall" binders (also called **universal quantification**). The
1686 /// idea is that when, in the body of `bar`, we refer to `T` as a
1687 /// type, we aren't referring to any type in particular, but rather a
1688 /// kind of "fresh" type that is distinct from all other types we have
1689 /// actually declared. This is called a **placeholder** type, and we
1690 /// use universes to talk about this. In other words, a type name in
1691 /// universe 0 always corresponds to some "ground" type that the user
1692 /// declared, but a type name in a non-zero universe is a placeholder
1693 /// type -- an idealized representative of "types in general" that we
1694 /// use for checking generic functions.
1695 pub struct UniverseIndex {
1697 DEBUG_FORMAT = "U{}",
1701 impl UniverseIndex {
1702 pub const ROOT: UniverseIndex = UniverseIndex::from_u32(0);
1704 /// Returns the "next" universe index in order -- this new index
1705 /// is considered to extend all previous universes. This
1706 /// corresponds to entering a `forall` quantifier. So, for
1707 /// example, suppose we have this type in universe `U`:
1710 /// for<'a> fn(&'a u32)
1713 /// Once we "enter" into this `for<'a>` quantifier, we are in a
1714 /// new universe that extends `U` -- in this new universe, we can
1715 /// name the region `'a`, but that region was not nameable from
1716 /// `U` because it was not in scope there.
1717 pub fn next_universe(self) -> UniverseIndex {
1718 UniverseIndex::from_u32(self.private.checked_add(1).unwrap())
1721 /// Returns `true` if `self` can name a name from `other` -- in other words,
1722 /// if the set of names in `self` is a superset of those in
1723 /// `other` (`self >= other`).
1724 pub fn can_name(self, other: UniverseIndex) -> bool {
1725 self.private >= other.private
1728 /// Returns `true` if `self` cannot name some names from `other` -- in other
1729 /// words, if the set of names in `self` is a strict subset of
1730 /// those in `other` (`self < other`).
1731 pub fn cannot_name(self, other: UniverseIndex) -> bool {
1732 self.private < other.private
1736 /// The "placeholder index" fully defines a placeholder region.
1737 /// Placeholder regions are identified by both a **universe** as well
1738 /// as a "bound-region" within that universe. The `bound_region` is
1739 /// basically a name -- distinct bound regions within the same
1740 /// universe are just two regions with an unknown relationship to one
1742 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, PartialOrd, Ord)]
1743 pub struct Placeholder<T> {
1744 pub universe: UniverseIndex,
1748 impl<'a, T> HashStable<StableHashingContext<'a>> for Placeholder<T>
1750 T: HashStable<StableHashingContext<'a>>,
1752 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
1753 self.universe.hash_stable(hcx, hasher);
1754 self.name.hash_stable(hcx, hasher);
1758 pub type PlaceholderRegion = Placeholder<BoundRegion>;
1760 pub type PlaceholderType = Placeholder<BoundVar>;
1762 pub type PlaceholderConst = Placeholder<BoundVar>;
1764 /// When type checking, we use the `ParamEnv` to track
1765 /// details about the set of where-clauses that are in scope at this
1766 /// particular point.
1767 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable, TypeFoldable)]
1768 pub struct ParamEnv<'tcx> {
1769 /// `Obligation`s that the caller must satisfy. This is basically
1770 /// the set of bounds on the in-scope type parameters, translated
1771 /// into `Obligation`s, and elaborated and normalized.
1772 pub caller_bounds: &'tcx List<ty::Predicate<'tcx>>,
1774 /// Typically, this is `Reveal::UserFacing`, but during codegen we
1775 /// want `Reveal::All` -- note that this is always paired with an
1776 /// empty environment. To get that, use `ParamEnv::reveal()`.
1777 pub reveal: traits::Reveal,
1779 /// If this `ParamEnv` comes from a call to `tcx.param_env(def_id)`,
1780 /// register that `def_id` (useful for transitioning to the chalk trait
1782 pub def_id: Option<DefId>,
1785 impl<'tcx> ParamEnv<'tcx> {
1786 /// Construct a trait environment suitable for contexts where
1787 /// there are no where-clauses in scope. Hidden types (like `impl
1788 /// Trait`) are left hidden, so this is suitable for ordinary
1791 pub fn empty() -> Self {
1792 Self::new(List::empty(), Reveal::UserFacing, None)
1795 /// Construct a trait environment with no where-clauses in scope
1796 /// where the values of all `impl Trait` and other hidden types
1797 /// are revealed. This is suitable for monomorphized, post-typeck
1798 /// environments like codegen or doing optimizations.
1800 /// N.B., if you want to have predicates in scope, use `ParamEnv::new`,
1801 /// or invoke `param_env.with_reveal_all()`.
1803 pub fn reveal_all() -> Self {
1804 Self::new(List::empty(), Reveal::All, None)
1807 /// Construct a trait environment with the given set of predicates.
1810 caller_bounds: &'tcx List<ty::Predicate<'tcx>>,
1812 def_id: Option<DefId>,
1814 ty::ParamEnv { caller_bounds, reveal, def_id }
1817 /// Returns a new parameter environment with the same clauses, but
1818 /// which "reveals" the true results of projections in all cases
1819 /// (even for associated types that are specializable). This is
1820 /// the desired behavior during codegen and certain other special
1821 /// contexts; normally though we want to use `Reveal::UserFacing`,
1822 /// which is the default.
1823 pub fn with_reveal_all(self) -> Self {
1824 ty::ParamEnv { reveal: Reveal::All, ..self }
1827 /// Returns this same environment but with no caller bounds.
1828 pub fn without_caller_bounds(self) -> Self {
1829 ty::ParamEnv { caller_bounds: List::empty(), ..self }
1832 /// Creates a suitable environment in which to perform trait
1833 /// queries on the given value. When type-checking, this is simply
1834 /// the pair of the environment plus value. But when reveal is set to
1835 /// All, then if `value` does not reference any type parameters, we will
1836 /// pair it with the empty environment. This improves caching and is generally
1839 /// N.B., we preserve the environment when type-checking because it
1840 /// is possible for the user to have wacky where-clauses like
1841 /// `where Box<u32>: Copy`, which are clearly never
1842 /// satisfiable. We generally want to behave as if they were true,
1843 /// although the surrounding function is never reachable.
1844 pub fn and<T: TypeFoldable<'tcx>>(self, value: T) -> ParamEnvAnd<'tcx, T> {
1846 Reveal::UserFacing => ParamEnvAnd { param_env: self, value },
1849 if value.is_global() {
1850 ParamEnvAnd { param_env: self.without_caller_bounds(), value }
1852 ParamEnvAnd { param_env: self, value }
1859 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1860 pub struct ConstnessAnd<T> {
1861 pub constness: Constness,
1865 // FIXME(ecstaticmorse): Audit all occurrences of `without_const().to_predicate()` to ensure that
1866 // the constness of trait bounds is being propagated correctly.
1867 pub trait WithConstness: Sized {
1869 fn with_constness(self, constness: Constness) -> ConstnessAnd<Self> {
1870 ConstnessAnd { constness, value: self }
1874 fn with_const(self) -> ConstnessAnd<Self> {
1875 self.with_constness(Constness::Const)
1879 fn without_const(self) -> ConstnessAnd<Self> {
1880 self.with_constness(Constness::NotConst)
1884 impl<T> WithConstness for T {}
1886 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TypeFoldable)]
1887 pub struct ParamEnvAnd<'tcx, T> {
1888 pub param_env: ParamEnv<'tcx>,
1892 impl<'tcx, T> ParamEnvAnd<'tcx, T> {
1893 pub fn into_parts(self) -> (ParamEnv<'tcx>, T) {
1894 (self.param_env, self.value)
1898 impl<'a, 'tcx, T> HashStable<StableHashingContext<'a>> for ParamEnvAnd<'tcx, T>
1900 T: HashStable<StableHashingContext<'a>>,
1902 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
1903 let ParamEnvAnd { ref param_env, ref value } = *self;
1905 param_env.hash_stable(hcx, hasher);
1906 value.hash_stable(hcx, hasher);
1910 #[derive(Copy, Clone, Debug, HashStable)]
1911 pub struct Destructor {
1912 /// The `DefId` of the destructor method
1917 #[derive(HashStable)]
1918 pub struct AdtFlags: u32 {
1919 const NO_ADT_FLAGS = 0;
1920 /// Indicates whether the ADT is an enum.
1921 const IS_ENUM = 1 << 0;
1922 /// Indicates whether the ADT is a union.
1923 const IS_UNION = 1 << 1;
1924 /// Indicates whether the ADT is a struct.
1925 const IS_STRUCT = 1 << 2;
1926 /// Indicates whether the ADT is a struct and has a constructor.
1927 const HAS_CTOR = 1 << 3;
1928 /// Indicates whether the type is `PhantomData`.
1929 const IS_PHANTOM_DATA = 1 << 4;
1930 /// Indicates whether the type has a `#[fundamental]` attribute.
1931 const IS_FUNDAMENTAL = 1 << 5;
1932 /// Indicates whether the type is `Box`.
1933 const IS_BOX = 1 << 6;
1934 /// Indicates whether the type is `ManuallyDrop`.
1935 const IS_MANUALLY_DROP = 1 << 7;
1936 // FIXME(matthewjasper) replace these with diagnostic items
1937 /// Indicates whether the type is an `Arc`.
1938 const IS_ARC = 1 << 8;
1939 /// Indicates whether the type is an `Rc`.
1940 const IS_RC = 1 << 9;
1941 /// Indicates whether the variant list of this ADT is `#[non_exhaustive]`.
1942 /// (i.e., this flag is never set unless this ADT is an enum).
1943 const IS_VARIANT_LIST_NON_EXHAUSTIVE = 1 << 10;
1948 #[derive(HashStable)]
1949 pub struct VariantFlags: u32 {
1950 const NO_VARIANT_FLAGS = 0;
1951 /// Indicates whether the field list of this variant is `#[non_exhaustive]`.
1952 const IS_FIELD_LIST_NON_EXHAUSTIVE = 1 << 0;
1956 /// Definition of a variant -- a struct's fields or a enum variant.
1957 #[derive(Debug, HashStable)]
1958 pub struct VariantDef {
1959 /// `DefId` that identifies the variant itself.
1960 /// If this variant belongs to a struct or union, then this is a copy of its `DefId`.
1962 /// `DefId` that identifies the variant's constructor.
1963 /// If this variant is a struct variant, then this is `None`.
1964 pub ctor_def_id: Option<DefId>,
1965 /// Variant or struct name.
1966 #[stable_hasher(project(name))]
1968 /// Discriminant of this variant.
1969 pub discr: VariantDiscr,
1970 /// Fields of this variant.
1971 pub fields: Vec<FieldDef>,
1972 /// Type of constructor of variant.
1973 pub ctor_kind: CtorKind,
1974 /// Flags of the variant (e.g. is field list non-exhaustive)?
1975 flags: VariantFlags,
1976 /// Variant is obtained as part of recovering from a syntactic error.
1977 /// May be incomplete or bogus.
1978 pub recovered: bool,
1981 impl<'tcx> VariantDef {
1982 /// Creates a new `VariantDef`.
1984 /// `variant_did` is the `DefId` that identifies the enum variant (if this `VariantDef`
1985 /// represents an enum variant).
1987 /// `ctor_did` is the `DefId` that identifies the constructor of unit or
1988 /// tuple-variants/structs. If this is a `struct`-variant then this should be `None`.
1990 /// `parent_did` is the `DefId` of the `AdtDef` representing the enum or struct that
1991 /// owns this variant. It is used for checking if a struct has `#[non_exhaustive]` w/out having
1992 /// to go through the redirect of checking the ctor's attributes - but compiling a small crate
1993 /// requires loading the `AdtDef`s for all the structs in the universe (e.g., coherence for any
1994 /// built-in trait), and we do not want to load attributes twice.
1996 /// If someone speeds up attribute loading to not be a performance concern, they can
1997 /// remove this hack and use the constructor `DefId` everywhere.
2001 variant_did: Option<DefId>,
2002 ctor_def_id: Option<DefId>,
2003 discr: VariantDiscr,
2004 fields: Vec<FieldDef>,
2005 ctor_kind: CtorKind,
2011 "VariantDef::new(ident = {:?}, variant_did = {:?}, ctor_def_id = {:?}, discr = {:?},
2012 fields = {:?}, ctor_kind = {:?}, adt_kind = {:?}, parent_did = {:?})",
2013 ident, variant_did, ctor_def_id, discr, fields, ctor_kind, adt_kind, parent_did,
2016 let mut flags = VariantFlags::NO_VARIANT_FLAGS;
2017 if adt_kind == AdtKind::Struct && tcx.has_attr(parent_did, sym::non_exhaustive) {
2018 debug!("found non-exhaustive field list for {:?}", parent_did);
2019 flags = flags | VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE;
2020 } else if let Some(variant_did) = variant_did {
2021 if tcx.has_attr(variant_did, sym::non_exhaustive) {
2022 debug!("found non-exhaustive field list for {:?}", variant_did);
2023 flags = flags | VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE;
2028 def_id: variant_did.unwrap_or(parent_did),
2039 /// Is this field list non-exhaustive?
2041 pub fn is_field_list_non_exhaustive(&self) -> bool {
2042 self.flags.intersects(VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE)
2046 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2047 pub enum VariantDiscr {
2048 /// Explicit value for this variant, i.e., `X = 123`.
2049 /// The `DefId` corresponds to the embedded constant.
2052 /// The previous variant's discriminant plus one.
2053 /// For efficiency reasons, the distance from the
2054 /// last `Explicit` discriminant is being stored,
2055 /// or `0` for the first variant, if it has none.
2059 #[derive(Debug, HashStable)]
2060 pub struct FieldDef {
2062 #[stable_hasher(project(name))]
2064 pub vis: Visibility,
2067 /// The definition of a user-defined type, e.g., a `struct`, `enum`, or `union`.
2069 /// These are all interned (by `intern_adt_def`) into the `adt_defs` table.
2071 /// The initialism *ADT* stands for an [*algebraic data type (ADT)*][adt].
2072 /// This is slightly wrong because `union`s are not ADTs.
2073 /// Moreover, Rust only allows recursive data types through indirection.
2075 /// [adt]: https://en.wikipedia.org/wiki/Algebraic_data_type
2077 /// The `DefId` of the struct, enum or union item.
2079 /// Variants of the ADT. If this is a struct or union, then there will be a single variant.
2080 pub variants: IndexVec<VariantIdx, VariantDef>,
2081 /// Flags of the ADT (e.g., is this a struct? is this non-exhaustive?).
2083 /// Repr options provided by the user.
2084 pub repr: ReprOptions,
2087 impl PartialOrd for AdtDef {
2088 fn partial_cmp(&self, other: &AdtDef) -> Option<Ordering> {
2089 Some(self.cmp(&other))
2093 /// There should be only one AdtDef for each `did`, therefore
2094 /// it is fine to implement `Ord` only based on `did`.
2095 impl Ord for AdtDef {
2096 fn cmp(&self, other: &AdtDef) -> Ordering {
2097 self.did.cmp(&other.did)
2101 impl PartialEq for AdtDef {
2102 // `AdtDef`s are always interned, and this is part of `TyS` equality.
2104 fn eq(&self, other: &Self) -> bool {
2105 ptr::eq(self, other)
2109 impl Eq for AdtDef {}
2111 impl Hash for AdtDef {
2113 fn hash<H: Hasher>(&self, s: &mut H) {
2114 (self as *const AdtDef).hash(s)
2118 impl<'tcx> rustc_serialize::UseSpecializedEncodable for &'tcx AdtDef {
2119 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
2124 impl<'tcx> rustc_serialize::UseSpecializedDecodable for &'tcx AdtDef {}
2126 impl<'a> HashStable<StableHashingContext<'a>> for AdtDef {
2127 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
2129 static CACHE: RefCell<FxHashMap<usize, Fingerprint>> = Default::default();
2132 let hash: Fingerprint = CACHE.with(|cache| {
2133 let addr = self as *const AdtDef as usize;
2134 *cache.borrow_mut().entry(addr).or_insert_with(|| {
2135 let ty::AdtDef { did, ref variants, ref flags, ref repr } = *self;
2137 let mut hasher = StableHasher::new();
2138 did.hash_stable(hcx, &mut hasher);
2139 variants.hash_stable(hcx, &mut hasher);
2140 flags.hash_stable(hcx, &mut hasher);
2141 repr.hash_stable(hcx, &mut hasher);
2147 hash.hash_stable(hcx, hasher);
2151 #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
2158 impl Into<DataTypeKind> for AdtKind {
2159 fn into(self) -> DataTypeKind {
2161 AdtKind::Struct => DataTypeKind::Struct,
2162 AdtKind::Union => DataTypeKind::Union,
2163 AdtKind::Enum => DataTypeKind::Enum,
2169 #[derive(RustcEncodable, RustcDecodable, Default, HashStable)]
2170 pub struct ReprFlags: u8 {
2171 const IS_C = 1 << 0;
2172 const IS_SIMD = 1 << 1;
2173 const IS_TRANSPARENT = 1 << 2;
2174 // Internal only for now. If true, don't reorder fields.
2175 const IS_LINEAR = 1 << 3;
2176 // If true, don't expose any niche to type's context.
2177 const HIDE_NICHE = 1 << 4;
2178 // Any of these flags being set prevent field reordering optimisation.
2179 const IS_UNOPTIMISABLE = ReprFlags::IS_C.bits |
2180 ReprFlags::IS_SIMD.bits |
2181 ReprFlags::IS_LINEAR.bits;
2185 /// Represents the repr options provided by the user,
2186 #[derive(Copy, Clone, Debug, Eq, PartialEq, RustcEncodable, RustcDecodable, Default, HashStable)]
2187 pub struct ReprOptions {
2188 pub int: Option<attr::IntType>,
2189 pub align: Option<Align>,
2190 pub pack: Option<Align>,
2191 pub flags: ReprFlags,
2195 pub fn new(tcx: TyCtxt<'_>, did: DefId) -> ReprOptions {
2196 let mut flags = ReprFlags::empty();
2197 let mut size = None;
2198 let mut max_align: Option<Align> = None;
2199 let mut min_pack: Option<Align> = None;
2200 for attr in tcx.get_attrs(did).iter() {
2201 for r in attr::find_repr_attrs(&tcx.sess.parse_sess, attr) {
2202 flags.insert(match r {
2203 attr::ReprC => ReprFlags::IS_C,
2204 attr::ReprPacked(pack) => {
2205 let pack = Align::from_bytes(pack as u64).unwrap();
2206 min_pack = Some(if let Some(min_pack) = min_pack {
2213 attr::ReprTransparent => ReprFlags::IS_TRANSPARENT,
2214 attr::ReprNoNiche => ReprFlags::HIDE_NICHE,
2215 attr::ReprSimd => ReprFlags::IS_SIMD,
2216 attr::ReprInt(i) => {
2220 attr::ReprAlign(align) => {
2221 max_align = max_align.max(Some(Align::from_bytes(align as u64).unwrap()));
2228 // This is here instead of layout because the choice must make it into metadata.
2229 if !tcx.consider_optimizing(|| format!("Reorder fields of {:?}", tcx.def_path_str(did))) {
2230 flags.insert(ReprFlags::IS_LINEAR);
2232 ReprOptions { int: size, align: max_align, pack: min_pack, flags }
2236 pub fn simd(&self) -> bool {
2237 self.flags.contains(ReprFlags::IS_SIMD)
2240 pub fn c(&self) -> bool {
2241 self.flags.contains(ReprFlags::IS_C)
2244 pub fn packed(&self) -> bool {
2248 pub fn transparent(&self) -> bool {
2249 self.flags.contains(ReprFlags::IS_TRANSPARENT)
2252 pub fn linear(&self) -> bool {
2253 self.flags.contains(ReprFlags::IS_LINEAR)
2256 pub fn hide_niche(&self) -> bool {
2257 self.flags.contains(ReprFlags::HIDE_NICHE)
2260 pub fn discr_type(&self) -> attr::IntType {
2261 self.int.unwrap_or(attr::SignedInt(ast::IntTy::Isize))
2264 /// Returns `true` if this `#[repr()]` should inhabit "smart enum
2265 /// layout" optimizations, such as representing `Foo<&T>` as a
2267 pub fn inhibit_enum_layout_opt(&self) -> bool {
2268 self.c() || self.int.is_some()
2271 /// Returns `true` if this `#[repr()]` should inhibit struct field reordering
2272 /// optimizations, such as with `repr(C)`, `repr(packed(1))`, or `repr(<int>)`.
2273 pub fn inhibit_struct_field_reordering_opt(&self) -> bool {
2274 if let Some(pack) = self.pack {
2275 if pack.bytes() == 1 {
2279 self.flags.intersects(ReprFlags::IS_UNOPTIMISABLE) || self.int.is_some()
2282 /// Returns `true` if this `#[repr()]` should inhibit union ABI optimisations.
2283 pub fn inhibit_union_abi_opt(&self) -> bool {
2289 /// Creates a new `AdtDef`.
2294 variants: IndexVec<VariantIdx, VariantDef>,
2297 debug!("AdtDef::new({:?}, {:?}, {:?}, {:?})", did, kind, variants, repr);
2298 let mut flags = AdtFlags::NO_ADT_FLAGS;
2300 if kind == AdtKind::Enum && tcx.has_attr(did, sym::non_exhaustive) {
2301 debug!("found non-exhaustive variant list for {:?}", did);
2302 flags = flags | AdtFlags::IS_VARIANT_LIST_NON_EXHAUSTIVE;
2305 flags |= match kind {
2306 AdtKind::Enum => AdtFlags::IS_ENUM,
2307 AdtKind::Union => AdtFlags::IS_UNION,
2308 AdtKind::Struct => AdtFlags::IS_STRUCT,
2311 if kind == AdtKind::Struct && variants[VariantIdx::new(0)].ctor_def_id.is_some() {
2312 flags |= AdtFlags::HAS_CTOR;
2315 let attrs = tcx.get_attrs(did);
2316 if attr::contains_name(&attrs, sym::fundamental) {
2317 flags |= AdtFlags::IS_FUNDAMENTAL;
2319 if Some(did) == tcx.lang_items().phantom_data() {
2320 flags |= AdtFlags::IS_PHANTOM_DATA;
2322 if Some(did) == tcx.lang_items().owned_box() {
2323 flags |= AdtFlags::IS_BOX;
2325 if Some(did) == tcx.lang_items().manually_drop() {
2326 flags |= AdtFlags::IS_MANUALLY_DROP;
2328 if Some(did) == tcx.lang_items().arc() {
2329 flags |= AdtFlags::IS_ARC;
2331 if Some(did) == tcx.lang_items().rc() {
2332 flags |= AdtFlags::IS_RC;
2335 AdtDef { did, variants, flags, repr }
2338 /// Returns `true` if this is a struct.
2340 pub fn is_struct(&self) -> bool {
2341 self.flags.contains(AdtFlags::IS_STRUCT)
2344 /// Returns `true` if this is a union.
2346 pub fn is_union(&self) -> bool {
2347 self.flags.contains(AdtFlags::IS_UNION)
2350 /// Returns `true` if this is a enum.
2352 pub fn is_enum(&self) -> bool {
2353 self.flags.contains(AdtFlags::IS_ENUM)
2356 /// Returns `true` if the variant list of this ADT is `#[non_exhaustive]`.
2358 pub fn is_variant_list_non_exhaustive(&self) -> bool {
2359 self.flags.contains(AdtFlags::IS_VARIANT_LIST_NON_EXHAUSTIVE)
2362 /// Returns the kind of the ADT.
2364 pub fn adt_kind(&self) -> AdtKind {
2367 } else if self.is_union() {
2374 /// Returns a description of this abstract data type.
2375 pub fn descr(&self) -> &'static str {
2376 match self.adt_kind() {
2377 AdtKind::Struct => "struct",
2378 AdtKind::Union => "union",
2379 AdtKind::Enum => "enum",
2383 /// Returns a description of a variant of this abstract data type.
2385 pub fn variant_descr(&self) -> &'static str {
2386 match self.adt_kind() {
2387 AdtKind::Struct => "struct",
2388 AdtKind::Union => "union",
2389 AdtKind::Enum => "variant",
2393 /// If this function returns `true`, it implies that `is_struct` must return `true`.
2395 pub fn has_ctor(&self) -> bool {
2396 self.flags.contains(AdtFlags::HAS_CTOR)
2399 /// Returns `true` if this type is `#[fundamental]` for the purposes
2400 /// of coherence checking.
2402 pub fn is_fundamental(&self) -> bool {
2403 self.flags.contains(AdtFlags::IS_FUNDAMENTAL)
2406 /// Returns `true` if this is `PhantomData<T>`.
2408 pub fn is_phantom_data(&self) -> bool {
2409 self.flags.contains(AdtFlags::IS_PHANTOM_DATA)
2412 /// Returns `true` if this is `Arc<T>`.
2413 pub fn is_arc(&self) -> bool {
2414 self.flags.contains(AdtFlags::IS_ARC)
2417 /// Returns `true` if this is `Rc<T>`.
2418 pub fn is_rc(&self) -> bool {
2419 self.flags.contains(AdtFlags::IS_RC)
2422 /// Returns `true` if this is Box<T>.
2424 pub fn is_box(&self) -> bool {
2425 self.flags.contains(AdtFlags::IS_BOX)
2428 /// Returns `true` if this is `ManuallyDrop<T>`.
2430 pub fn is_manually_drop(&self) -> bool {
2431 self.flags.contains(AdtFlags::IS_MANUALLY_DROP)
2434 /// Returns `true` if this type has a destructor.
2435 pub fn has_dtor(&self, tcx: TyCtxt<'tcx>) -> bool {
2436 self.destructor(tcx).is_some()
2439 /// Asserts this is a struct or union and returns its unique variant.
2440 pub fn non_enum_variant(&self) -> &VariantDef {
2441 assert!(self.is_struct() || self.is_union());
2442 &self.variants[VariantIdx::new(0)]
2446 pub fn predicates(&self, tcx: TyCtxt<'tcx>) -> GenericPredicates<'tcx> {
2447 tcx.predicates_of(self.did)
2450 /// Returns an iterator over all fields contained
2453 pub fn all_fields(&self) -> impl Iterator<Item = &FieldDef> + Clone {
2454 self.variants.iter().flat_map(|v| v.fields.iter())
2457 pub fn is_payloadfree(&self) -> bool {
2458 !self.variants.is_empty() && self.variants.iter().all(|v| v.fields.is_empty())
2461 /// Return a `VariantDef` given a variant id.
2462 pub fn variant_with_id(&self, vid: DefId) -> &VariantDef {
2463 self.variants.iter().find(|v| v.def_id == vid).expect("variant_with_id: unknown variant")
2466 /// Return a `VariantDef` given a constructor id.
2467 pub fn variant_with_ctor_id(&self, cid: DefId) -> &VariantDef {
2470 .find(|v| v.ctor_def_id == Some(cid))
2471 .expect("variant_with_ctor_id: unknown variant")
2474 /// Return the index of `VariantDef` given a variant id.
2475 pub fn variant_index_with_id(&self, vid: DefId) -> VariantIdx {
2478 .find(|(_, v)| v.def_id == vid)
2479 .expect("variant_index_with_id: unknown variant")
2483 /// Return the index of `VariantDef` given a constructor id.
2484 pub fn variant_index_with_ctor_id(&self, cid: DefId) -> VariantIdx {
2487 .find(|(_, v)| v.ctor_def_id == Some(cid))
2488 .expect("variant_index_with_ctor_id: unknown variant")
2492 pub fn variant_of_res(&self, res: Res) -> &VariantDef {
2494 Res::Def(DefKind::Variant, vid) => self.variant_with_id(vid),
2495 Res::Def(DefKind::Ctor(..), cid) => self.variant_with_ctor_id(cid),
2496 Res::Def(DefKind::Struct, _)
2497 | Res::Def(DefKind::Union, _)
2498 | Res::Def(DefKind::TyAlias, _)
2499 | Res::Def(DefKind::AssocTy, _)
2501 | Res::SelfCtor(..) => self.non_enum_variant(),
2502 _ => bug!("unexpected res {:?} in variant_of_res", res),
2507 pub fn eval_explicit_discr(&self, tcx: TyCtxt<'tcx>, expr_did: DefId) -> Option<Discr<'tcx>> {
2508 let param_env = tcx.param_env(expr_did);
2509 let repr_type = self.repr.discr_type();
2510 match tcx.const_eval_poly(expr_did) {
2512 let ty = repr_type.to_ty(tcx);
2513 if let Some(b) = val.try_to_bits_for_ty(tcx, param_env, ty) {
2514 trace!("discriminants: {} ({:?})", b, repr_type);
2515 Some(Discr { val: b, ty })
2517 info!("invalid enum discriminant: {:#?}", val);
2518 crate::mir::interpret::struct_error(
2519 tcx.at(tcx.def_span(expr_did)),
2520 "constant evaluation of enum discriminant resulted in non-integer",
2526 Err(ErrorHandled::Reported) => {
2527 if !expr_did.is_local() {
2529 tcx.def_span(expr_did),
2530 "variant discriminant evaluation succeeded \
2531 in its crate but failed locally"
2536 Err(ErrorHandled::TooGeneric) => {
2537 span_bug!(tcx.def_span(expr_did), "enum discriminant depends on generic arguments",)
2543 pub fn discriminants(
2546 ) -> impl Iterator<Item = (VariantIdx, Discr<'tcx>)> + Captures<'tcx> {
2547 let repr_type = self.repr.discr_type();
2548 let initial = repr_type.initial_discriminant(tcx);
2549 let mut prev_discr = None::<Discr<'tcx>>;
2550 self.variants.iter_enumerated().map(move |(i, v)| {
2551 let mut discr = prev_discr.map_or(initial, |d| d.wrap_incr(tcx));
2552 if let VariantDiscr::Explicit(expr_did) = v.discr {
2553 if let Some(new_discr) = self.eval_explicit_discr(tcx, expr_did) {
2557 prev_discr = Some(discr);
2564 pub fn variant_range(&self) -> Range<VariantIdx> {
2565 VariantIdx::new(0)..VariantIdx::new(self.variants.len())
2568 /// Computes the discriminant value used by a specific variant.
2569 /// Unlike `discriminants`, this is (amortized) constant-time,
2570 /// only doing at most one query for evaluating an explicit
2571 /// discriminant (the last one before the requested variant),
2572 /// assuming there are no constant-evaluation errors there.
2574 pub fn discriminant_for_variant(
2577 variant_index: VariantIdx,
2579 let (val, offset) = self.discriminant_def_for_variant(variant_index);
2580 let explicit_value = val
2581 .and_then(|expr_did| self.eval_explicit_discr(tcx, expr_did))
2582 .unwrap_or_else(|| self.repr.discr_type().initial_discriminant(tcx));
2583 explicit_value.checked_add(tcx, offset as u128).0
2586 /// Yields a `DefId` for the discriminant and an offset to add to it
2587 /// Alternatively, if there is no explicit discriminant, returns the
2588 /// inferred discriminant directly.
2589 pub fn discriminant_def_for_variant(&self, variant_index: VariantIdx) -> (Option<DefId>, u32) {
2590 let mut explicit_index = variant_index.as_u32();
2593 match self.variants[VariantIdx::from_u32(explicit_index)].discr {
2594 ty::VariantDiscr::Relative(0) => {
2598 ty::VariantDiscr::Relative(distance) => {
2599 explicit_index -= distance;
2601 ty::VariantDiscr::Explicit(did) => {
2602 expr_did = Some(did);
2607 (expr_did, variant_index.as_u32() - explicit_index)
2610 pub fn destructor(&self, tcx: TyCtxt<'tcx>) -> Option<Destructor> {
2611 tcx.adt_destructor(self.did)
2614 /// Returns a list of types such that `Self: Sized` if and only
2615 /// if that type is `Sized`, or `TyErr` if this type is recursive.
2617 /// Oddly enough, checking that the sized-constraint is `Sized` is
2618 /// actually more expressive than checking all members:
2619 /// the `Sized` trait is inductive, so an associated type that references
2620 /// `Self` would prevent its containing ADT from being `Sized`.
2622 /// Due to normalization being eager, this applies even if
2623 /// the associated type is behind a pointer (e.g., issue #31299).
2624 pub fn sized_constraint(&self, tcx: TyCtxt<'tcx>) -> &'tcx [Ty<'tcx>] {
2625 tcx.adt_sized_constraint(self.did).0
2629 impl<'tcx> FieldDef {
2630 /// Returns the type of this field. The `subst` is typically obtained
2631 /// via the second field of `TyKind::AdtDef`.
2632 pub fn ty(&self, tcx: TyCtxt<'tcx>, subst: SubstsRef<'tcx>) -> Ty<'tcx> {
2633 tcx.type_of(self.did).subst(tcx, subst)
2637 /// Represents the various closure traits in the language. This
2638 /// will determine the type of the environment (`self`, in the
2639 /// desugaring) argument that the closure expects.
2641 /// You can get the environment type of a closure using
2642 /// `tcx.closure_env_ty()`.
2643 #[derive(Clone, Copy, PartialOrd, Ord, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
2644 #[derive(HashStable)]
2645 pub enum ClosureKind {
2646 // Warning: Ordering is significant here! The ordering is chosen
2647 // because the trait Fn is a subtrait of FnMut and so in turn, and
2648 // hence we order it so that Fn < FnMut < FnOnce.
2654 impl<'tcx> ClosureKind {
2655 // This is the initial value used when doing upvar inference.
2656 pub const LATTICE_BOTTOM: ClosureKind = ClosureKind::Fn;
2658 pub fn trait_did(&self, tcx: TyCtxt<'tcx>) -> DefId {
2660 ClosureKind::Fn => tcx.require_lang_item(FnTraitLangItem, None),
2661 ClosureKind::FnMut => tcx.require_lang_item(FnMutTraitLangItem, None),
2662 ClosureKind::FnOnce => tcx.require_lang_item(FnOnceTraitLangItem, None),
2666 /// Returns `true` if this a type that impls this closure kind
2667 /// must also implement `other`.
2668 pub fn extends(self, other: ty::ClosureKind) -> bool {
2669 match (self, other) {
2670 (ClosureKind::Fn, ClosureKind::Fn) => true,
2671 (ClosureKind::Fn, ClosureKind::FnMut) => true,
2672 (ClosureKind::Fn, ClosureKind::FnOnce) => true,
2673 (ClosureKind::FnMut, ClosureKind::FnMut) => true,
2674 (ClosureKind::FnMut, ClosureKind::FnOnce) => true,
2675 (ClosureKind::FnOnce, ClosureKind::FnOnce) => true,
2680 /// Returns the representative scalar type for this closure kind.
2681 /// See `TyS::to_opt_closure_kind` for more details.
2682 pub fn to_ty(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
2684 ty::ClosureKind::Fn => tcx.types.i8,
2685 ty::ClosureKind::FnMut => tcx.types.i16,
2686 ty::ClosureKind::FnOnce => tcx.types.i32,
2691 impl<'tcx> TyS<'tcx> {
2692 /// Iterator that walks `self` and any types reachable from
2693 /// `self`, in depth-first order. Note that just walks the types
2694 /// that appear in `self`, it does not descend into the fields of
2695 /// structs or variants. For example:
2698 /// isize => { isize }
2699 /// Foo<Bar<isize>> => { Foo<Bar<isize>>, Bar<isize>, isize }
2700 /// [isize] => { [isize], isize }
2702 pub fn walk(&'tcx self) -> TypeWalker<'tcx> {
2703 TypeWalker::new(self)
2706 /// Iterator that walks the immediate children of `self`. Hence
2707 /// `Foo<Bar<i32>, u32>` yields the sequence `[Bar<i32>, u32]`
2708 /// (but not `i32`, like `walk`).
2709 pub fn walk_shallow(&'tcx self) -> smallvec::IntoIter<walk::TypeWalkerArray<'tcx>> {
2710 walk::walk_shallow(self)
2713 /// Walks `ty` and any types appearing within `ty`, invoking the
2714 /// callback `f` on each type. If the callback returns `false`, then the
2715 /// children of the current type are ignored.
2717 /// Note: prefer `ty.walk()` where possible.
2718 pub fn maybe_walk<F>(&'tcx self, mut f: F)
2720 F: FnMut(Ty<'tcx>) -> bool,
2722 let mut walker = self.walk();
2723 while let Some(ty) = walker.next() {
2725 walker.skip_current_subtree();
2732 pub fn from_mutbl(m: hir::Mutability) -> BorrowKind {
2734 hir::Mutability::Mut => MutBorrow,
2735 hir::Mutability::Not => ImmBorrow,
2739 /// Returns a mutability `m` such that an `&m T` pointer could be used to obtain this borrow
2740 /// kind. Because borrow kinds are richer than mutabilities, we sometimes have to pick a
2741 /// mutability that is stronger than necessary so that it at least *would permit* the borrow in
2743 pub fn to_mutbl_lossy(self) -> hir::Mutability {
2745 MutBorrow => hir::Mutability::Mut,
2746 ImmBorrow => hir::Mutability::Not,
2748 // We have no type corresponding to a unique imm borrow, so
2749 // use `&mut`. It gives all the capabilities of an `&uniq`
2750 // and hence is a safe "over approximation".
2751 UniqueImmBorrow => hir::Mutability::Mut,
2755 pub fn to_user_str(&self) -> &'static str {
2757 MutBorrow => "mutable",
2758 ImmBorrow => "immutable",
2759 UniqueImmBorrow => "uniquely immutable",
2764 #[derive(Debug, Clone)]
2765 pub enum Attributes<'tcx> {
2766 Owned(Lrc<[ast::Attribute]>),
2767 Borrowed(&'tcx [ast::Attribute]),
2770 impl<'tcx> ::std::ops::Deref for Attributes<'tcx> {
2771 type Target = [ast::Attribute];
2773 fn deref(&self) -> &[ast::Attribute] {
2775 &Attributes::Owned(ref data) => &data,
2776 &Attributes::Borrowed(data) => data,
2781 #[derive(Debug, PartialEq, Eq)]
2782 pub enum ImplOverlapKind {
2783 /// These impls are always allowed to overlap.
2785 /// Whether or not the impl is permitted due to the trait being a `#[marker]` trait
2788 /// These impls are allowed to overlap, but that raises
2789 /// an issue #33140 future-compatibility warning.
2791 /// Some background: in Rust 1.0, the trait-object types `Send + Sync` (today's
2792 /// `dyn Send + Sync`) and `Sync + Send` (now `dyn Sync + Send`) were different.
2794 /// The widely-used version 0.1.0 of the crate `traitobject` had accidentally relied
2795 /// that difference, making what reduces to the following set of impls:
2799 /// impl Trait for dyn Send + Sync {}
2800 /// impl Trait for dyn Sync + Send {}
2803 /// Obviously, once we made these types be identical, that code causes a coherence
2804 /// error and a fairly big headache for us. However, luckily for us, the trait
2805 /// `Trait` used in this case is basically a marker trait, and therefore having
2806 /// overlapping impls for it is sound.
2808 /// To handle this, we basically regard the trait as a marker trait, with an additional
2809 /// future-compatibility warning. To avoid accidentally "stabilizing" this feature,
2810 /// it has the following restrictions:
2812 /// 1. The trait must indeed be a marker-like trait (i.e., no items), and must be
2814 /// 2. The trait-ref of both impls must be equal.
2815 /// 3. The trait-ref of both impls must be a trait object type consisting only of
2817 /// 4. Neither of the impls can have any where-clauses.
2819 /// Once `traitobject` 0.1.0 is no longer an active concern, this hack can be removed.
2823 impl<'tcx> TyCtxt<'tcx> {
2824 pub fn body_tables(self, body: hir::BodyId) -> &'tcx TypeckTables<'tcx> {
2825 self.typeck_tables_of(self.hir().body_owner_def_id(body))
2828 /// Returns an iterator of the `DefId`s for all body-owners in this
2829 /// crate. If you would prefer to iterate over the bodies
2830 /// themselves, you can do `self.hir().krate().body_ids.iter()`.
2831 pub fn body_owners(self) -> impl Iterator<Item = DefId> + Captures<'tcx> + 'tcx {
2836 .map(move |&body_id| self.hir().body_owner_def_id(body_id))
2839 pub fn par_body_owners<F: Fn(DefId) + sync::Sync + sync::Send>(self, f: F) {
2840 par_iter(&self.hir().krate().body_ids)
2841 .for_each(|&body_id| f(self.hir().body_owner_def_id(body_id)));
2844 pub fn provided_trait_methods(self, id: DefId) -> impl 'tcx + Iterator<Item = &'tcx AssocItem> {
2845 self.associated_items(id)
2846 .in_definition_order()
2847 .filter(|item| item.kind == AssocKind::Method && item.defaultness.has_value())
2850 pub fn trait_relevant_for_never(self, did: DefId) -> bool {
2851 self.associated_items(did).in_definition_order().any(|item| item.relevant_for_never())
2854 pub fn opt_item_name(self, def_id: DefId) -> Option<Ident> {
2855 self.hir().as_local_hir_id(def_id).and_then(|hir_id| self.hir().get(hir_id).ident())
2858 pub fn opt_associated_item(self, def_id: DefId) -> Option<AssocItem> {
2859 let is_associated_item = if let Some(hir_id) = self.hir().as_local_hir_id(def_id) {
2860 match self.hir().get(hir_id) {
2861 Node::TraitItem(_) | Node::ImplItem(_) => true,
2865 match self.def_kind(def_id) {
2866 Some(DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy) => true,
2871 is_associated_item.then(|| self.associated_item(def_id))
2874 pub fn field_index(self, hir_id: hir::HirId, tables: &TypeckTables<'_>) -> usize {
2875 tables.field_indices().get(hir_id).cloned().expect("no index for a field")
2878 pub fn find_field_index(self, ident: Ident, variant: &VariantDef) -> Option<usize> {
2879 variant.fields.iter().position(|field| self.hygienic_eq(ident, field.ident, variant.def_id))
2882 /// Returns `true` if the impls are the same polarity and the trait either
2883 /// has no items or is annotated #[marker] and prevents item overrides.
2884 pub fn impls_are_allowed_to_overlap(
2888 ) -> Option<ImplOverlapKind> {
2889 // If either trait impl references an error, they're allowed to overlap,
2890 // as one of them essentially doesn't exist.
2891 if self.impl_trait_ref(def_id1).map_or(false, |tr| tr.references_error())
2892 || self.impl_trait_ref(def_id2).map_or(false, |tr| tr.references_error())
2894 return Some(ImplOverlapKind::Permitted { marker: false });
2897 match (self.impl_polarity(def_id1), self.impl_polarity(def_id2)) {
2898 (ImplPolarity::Reservation, _) | (_, ImplPolarity::Reservation) => {
2899 // `#[rustc_reservation_impl]` impls don't overlap with anything
2901 "impls_are_allowed_to_overlap({:?}, {:?}) = Some(Permitted) (reservations)",
2904 return Some(ImplOverlapKind::Permitted { marker: false });
2906 (ImplPolarity::Positive, ImplPolarity::Negative)
2907 | (ImplPolarity::Negative, ImplPolarity::Positive) => {
2908 // `impl AutoTrait for Type` + `impl !AutoTrait for Type`
2910 "impls_are_allowed_to_overlap({:?}, {:?}) - None (differing polarities)",
2915 (ImplPolarity::Positive, ImplPolarity::Positive)
2916 | (ImplPolarity::Negative, ImplPolarity::Negative) => {}
2919 let is_marker_overlap = {
2920 let is_marker_impl = |def_id: DefId| -> bool {
2921 let trait_ref = self.impl_trait_ref(def_id);
2922 trait_ref.map_or(false, |tr| self.trait_def(tr.def_id).is_marker)
2924 is_marker_impl(def_id1) && is_marker_impl(def_id2)
2927 if is_marker_overlap {
2929 "impls_are_allowed_to_overlap({:?}, {:?}) = Some(Permitted) (marker overlap)",
2932 Some(ImplOverlapKind::Permitted { marker: true })
2934 if let Some(self_ty1) = self.issue33140_self_ty(def_id1) {
2935 if let Some(self_ty2) = self.issue33140_self_ty(def_id2) {
2936 if self_ty1 == self_ty2 {
2938 "impls_are_allowed_to_overlap({:?}, {:?}) - issue #33140 HACK",
2941 return Some(ImplOverlapKind::Issue33140);
2944 "impls_are_allowed_to_overlap({:?}, {:?}) - found {:?} != {:?}",
2945 def_id1, def_id2, self_ty1, self_ty2
2951 debug!("impls_are_allowed_to_overlap({:?}, {:?}) = None", def_id1, def_id2);
2956 /// Returns `ty::VariantDef` if `res` refers to a struct,
2957 /// or variant or their constructors, panics otherwise.
2958 pub fn expect_variant_res(self, res: Res) -> &'tcx VariantDef {
2960 Res::Def(DefKind::Variant, did) => {
2961 let enum_did = self.parent(did).unwrap();
2962 self.adt_def(enum_did).variant_with_id(did)
2964 Res::Def(DefKind::Struct, did) | Res::Def(DefKind::Union, did) => {
2965 self.adt_def(did).non_enum_variant()
2967 Res::Def(DefKind::Ctor(CtorOf::Variant, ..), variant_ctor_did) => {
2968 let variant_did = self.parent(variant_ctor_did).unwrap();
2969 let enum_did = self.parent(variant_did).unwrap();
2970 self.adt_def(enum_did).variant_with_ctor_id(variant_ctor_did)
2972 Res::Def(DefKind::Ctor(CtorOf::Struct, ..), ctor_did) => {
2973 let struct_did = self.parent(ctor_did).expect("struct ctor has no parent");
2974 self.adt_def(struct_did).non_enum_variant()
2976 _ => bug!("expect_variant_res used with unexpected res {:?}", res),
2980 pub fn item_name(self, id: DefId) -> Symbol {
2981 if id.index == CRATE_DEF_INDEX {
2982 self.original_crate_name(id.krate)
2984 let def_key = self.def_key(id);
2985 match def_key.disambiguated_data.data {
2986 // The name of a constructor is that of its parent.
2987 rustc_hir::definitions::DefPathData::Ctor => {
2988 self.item_name(DefId { krate: id.krate, index: def_key.parent.unwrap() })
2990 _ => def_key.disambiguated_data.data.get_opt_name().unwrap_or_else(|| {
2991 bug!("item_name: no name for {:?}", self.def_path(id));
2997 /// Returns the possibly-auto-generated MIR of a `(DefId, Subst)` pair.
2998 pub fn instance_mir(self, instance: ty::InstanceDef<'tcx>) -> ReadOnlyBodyAndCache<'tcx, 'tcx> {
3000 ty::InstanceDef::Item(did) => self.optimized_mir(did).unwrap_read_only(),
3001 ty::InstanceDef::VtableShim(..)
3002 | ty::InstanceDef::ReifyShim(..)
3003 | ty::InstanceDef::Intrinsic(..)
3004 | ty::InstanceDef::FnPtrShim(..)
3005 | ty::InstanceDef::Virtual(..)
3006 | ty::InstanceDef::ClosureOnceShim { .. }
3007 | ty::InstanceDef::DropGlue(..)
3008 | ty::InstanceDef::CloneShim(..) => self.mir_shims(instance).unwrap_read_only(),
3012 /// Gets the attributes of a definition.
3013 pub fn get_attrs(self, did: DefId) -> Attributes<'tcx> {
3014 if let Some(id) = self.hir().as_local_hir_id(did) {
3015 Attributes::Borrowed(self.hir().attrs(id))
3017 Attributes::Owned(self.item_attrs(did))
3021 /// Determines whether an item is annotated with an attribute.
3022 pub fn has_attr(self, did: DefId, attr: Symbol) -> bool {
3023 attr::contains_name(&self.get_attrs(did), attr)
3026 /// Returns `true` if this is an `auto trait`.
3027 pub fn trait_is_auto(self, trait_def_id: DefId) -> bool {
3028 self.trait_def(trait_def_id).has_auto_impl
3031 pub fn generator_layout(self, def_id: DefId) -> &'tcx GeneratorLayout<'tcx> {
3032 self.optimized_mir(def_id).generator_layout.as_ref().unwrap()
3035 /// Given the `DefId` of an impl, returns the `DefId` of the trait it implements.
3036 /// If it implements no trait, returns `None`.
3037 pub fn trait_id_of_impl(self, def_id: DefId) -> Option<DefId> {
3038 self.impl_trait_ref(def_id).map(|tr| tr.def_id)
3041 /// If the given defid describes a method belonging to an impl, returns the
3042 /// `DefId` of the impl that the method belongs to; otherwise, returns `None`.
3043 pub fn impl_of_method(self, def_id: DefId) -> Option<DefId> {
3044 self.opt_associated_item(def_id).and_then(|trait_item| match trait_item.container {
3045 TraitContainer(_) => None,
3046 ImplContainer(def_id) => Some(def_id),
3050 /// Looks up the span of `impl_did` if the impl is local; otherwise returns `Err`
3051 /// with the name of the crate containing the impl.
3052 pub fn span_of_impl(self, impl_did: DefId) -> Result<Span, Symbol> {
3053 if impl_did.is_local() {
3054 let hir_id = self.hir().as_local_hir_id(impl_did).unwrap();
3055 Ok(self.hir().span(hir_id))
3057 Err(self.crate_name(impl_did.krate))
3061 /// Hygienically compares a use-site name (`use_name`) for a field or an associated item with
3062 /// its supposed definition name (`def_name`). The method also needs `DefId` of the supposed
3063 /// definition's parent/scope to perform comparison.
3064 pub fn hygienic_eq(self, use_name: Ident, def_name: Ident, def_parent_def_id: DefId) -> bool {
3065 // We could use `Ident::eq` here, but we deliberately don't. The name
3066 // comparison fails frequently, and we want to avoid the expensive
3067 // `normalize_to_macros_2_0()` calls required for the span comparison whenever possible.
3068 use_name.name == def_name.name
3072 .hygienic_eq(def_name.span.ctxt(), self.expansion_that_defined(def_parent_def_id))
3075 fn expansion_that_defined(self, scope: DefId) -> ExpnId {
3076 match scope.as_local() {
3077 Some(scope) => self.hir().definitions().expansion_that_defined(scope),
3078 None => ExpnId::root(),
3082 pub fn adjust_ident(self, mut ident: Ident, scope: DefId) -> Ident {
3083 ident.span.normalize_to_macros_2_0_and_adjust(self.expansion_that_defined(scope));
3087 pub fn adjust_ident_and_get_scope(
3092 ) -> (Ident, DefId) {
3094 match ident.span.normalize_to_macros_2_0_and_adjust(self.expansion_that_defined(scope))
3096 Some(actual_expansion) => {
3097 self.hir().definitions().parent_module_of_macro_def(actual_expansion)
3099 None => self.parent_module(block).to_def_id(),
3104 pub fn is_object_safe(self, key: DefId) -> bool {
3105 self.object_safety_violations(key).is_empty()
3109 #[derive(Clone, HashStable)]
3110 pub struct AdtSizedConstraint<'tcx>(pub &'tcx [Ty<'tcx>]);
3112 /// Yields the parent function's `DefId` if `def_id` is an `impl Trait` definition.
3113 pub fn is_impl_trait_defn(tcx: TyCtxt<'_>, def_id: DefId) -> Option<DefId> {
3114 if let Some(hir_id) = tcx.hir().as_local_hir_id(def_id) {
3115 if let Node::Item(item) = tcx.hir().get(hir_id) {
3116 if let hir::ItemKind::OpaqueTy(ref opaque_ty) = item.kind {
3117 return opaque_ty.impl_trait_fn;
3124 pub fn provide(providers: &mut ty::query::Providers<'_>) {
3125 context::provide(providers);
3126 erase_regions::provide(providers);
3127 layout::provide(providers);
3128 super::util::bug::provide(providers);
3129 *providers = ty::query::Providers {
3130 trait_impls_of: trait_def::trait_impls_of_provider,
3131 all_local_trait_impls: trait_def::all_local_trait_impls,
3136 /// A map for the local crate mapping each type to a vector of its
3137 /// inherent impls. This is not meant to be used outside of coherence;
3138 /// rather, you should request the vector for a specific type via
3139 /// `tcx.inherent_impls(def_id)` so as to minimize your dependencies
3140 /// (constructing this map requires touching the entire crate).
3141 #[derive(Clone, Debug, Default, HashStable)]
3142 pub struct CrateInherentImpls {
3143 pub inherent_impls: DefIdMap<Vec<DefId>>,
3146 #[derive(Clone, Copy, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
3147 pub struct SymbolName {
3148 // FIXME: we don't rely on interning or equality here - better have
3149 // this be a `&'tcx str`.
3154 pub fn new(name: &str) -> SymbolName {
3155 SymbolName { name: Symbol::intern(name) }
3159 impl PartialOrd for SymbolName {
3160 fn partial_cmp(&self, other: &SymbolName) -> Option<Ordering> {
3161 self.name.as_str().partial_cmp(&other.name.as_str())
3165 /// Ordering must use the chars to ensure reproducible builds.
3166 impl Ord for SymbolName {
3167 fn cmp(&self, other: &SymbolName) -> Ordering {
3168 self.name.as_str().cmp(&other.name.as_str())
3172 impl fmt::Display for SymbolName {
3173 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
3174 fmt::Display::fmt(&self.name, fmt)
3178 impl fmt::Debug for SymbolName {
3179 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
3180 fmt::Display::fmt(&self.name, fmt)