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 rustc_ast::ast::{self, Ident, Name};
23 use rustc_ast::node_id::{NodeId, NodeMap, NodeSet};
24 use rustc_attr as attr;
25 use rustc_data_structures::captures::Captures;
26 use rustc_data_structures::fingerprint::Fingerprint;
27 use rustc_data_structures::fx::FxHashMap;
28 use rustc_data_structures::fx::FxIndexMap;
29 use rustc_data_structures::sorted_map::SortedIndexMultiMap;
30 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
31 use rustc_data_structures::sync::{self, par_iter, Lrc, ParallelIterator};
33 use rustc_hir::def::{CtorKind, CtorOf, DefKind, Namespace, Res};
34 use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, LocalDefId, CRATE_DEF_INDEX};
35 use rustc_hir::lang_items::{FnMutTraitLangItem, FnOnceTraitLangItem, FnTraitLangItem};
36 use rustc_hir::{Constness, GlobMap, Node, TraitMap};
37 use rustc_index::vec::{Idx, IndexVec};
38 use rustc_macros::HashStable;
39 use rustc_serialize::{self, Encodable, Encoder};
40 use rustc_session::DataTypeKind;
41 use rustc_span::hygiene::ExpnId;
42 use rustc_span::symbol::{kw, sym, Symbol};
44 use rustc_target::abi::{Align, VariantIdx};
46 use std::cell::RefCell;
47 use std::cmp::{self, Ordering};
49 use std::hash::{Hash, Hasher};
55 pub use self::sty::BoundRegion::*;
56 pub use self::sty::InferTy::*;
57 pub use self::sty::RegionKind;
58 pub use self::sty::RegionKind::*;
59 pub use self::sty::TyKind::*;
60 pub use self::sty::{Binder, BoundTy, BoundTyKind, BoundVar, DebruijnIndex, INNERMOST};
61 pub use self::sty::{BoundRegion, EarlyBoundRegion, FreeRegion, Region};
62 pub use self::sty::{CanonicalPolyFnSig, FnSig, GenSig, PolyFnSig, PolyGenSig};
63 pub use self::sty::{ClosureSubsts, GeneratorSubsts, TypeAndMut, UpvarSubsts};
64 pub use self::sty::{Const, ConstKind, ExistentialProjection, PolyExistentialProjection};
65 pub use self::sty::{ConstVid, FloatVid, IntVid, RegionVid, TyVid};
66 pub use self::sty::{ExistentialPredicate, InferConst, InferTy, ParamConst, ParamTy, ProjectionTy};
67 pub use self::sty::{ExistentialTraitRef, PolyExistentialTraitRef};
68 pub use self::sty::{PolyTraitRef, TraitRef, TyKind};
69 pub use crate::ty::diagnostics::*;
71 pub use self::binding::BindingMode;
72 pub use self::binding::BindingMode::*;
74 pub use self::context::{keep_local, tls, FreeRegionInfo, TyCtxt};
75 pub use self::context::{
76 CanonicalUserType, CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations, ResolvedOpaqueTy,
77 UserType, UserTypeAnnotationIndex,
79 pub use self::context::{
80 CtxtInterners, GeneratorInteriorTypeCause, GlobalCtxt, Lift, TypeckTables,
83 pub use self::instance::{Instance, InstanceDef};
85 pub use self::trait_def::TraitDef;
87 pub use self::query::queries;
100 pub mod free_region_map;
101 pub mod inhabitedness;
103 pub mod normalize_erasing_regions;
117 mod structural_impls;
122 pub struct ResolverOutputs {
123 pub definitions: rustc_hir::definitions::Definitions,
124 pub cstore: Box<CrateStoreDyn>,
125 pub extern_crate_map: NodeMap<CrateNum>,
126 pub trait_map: TraitMap<NodeId>,
127 pub maybe_unused_trait_imports: NodeSet,
128 pub maybe_unused_extern_crates: Vec<(NodeId, Span)>,
129 pub export_map: ExportMap<NodeId>,
130 pub glob_map: GlobMap,
131 /// Extern prelude entries. The value is `true` if the entry was introduced
132 /// via `extern crate` item and not `--extern` option or compiler built-in.
133 pub extern_prelude: FxHashMap<Name, bool>,
136 #[derive(Clone, Copy, PartialEq, Eq, Debug, HashStable)]
137 pub enum AssocItemContainer {
138 TraitContainer(DefId),
139 ImplContainer(DefId),
142 impl AssocItemContainer {
143 /// Asserts that this is the `DefId` of an associated item declared
144 /// in a trait, and returns the trait `DefId`.
145 pub fn assert_trait(&self) -> DefId {
147 TraitContainer(id) => id,
148 _ => bug!("associated item has wrong container type: {:?}", self),
152 pub fn id(&self) -> DefId {
154 TraitContainer(id) => id,
155 ImplContainer(id) => id,
160 /// The "header" of an impl is everything outside the body: a Self type, a trait
161 /// ref (in the case of a trait impl), and a set of predicates (from the
162 /// bounds / where-clauses).
163 #[derive(Clone, Debug, TypeFoldable)]
164 pub struct ImplHeader<'tcx> {
165 pub impl_def_id: DefId,
166 pub self_ty: Ty<'tcx>,
167 pub trait_ref: Option<TraitRef<'tcx>>,
168 pub predicates: Vec<Predicate<'tcx>>,
171 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable)]
172 pub enum ImplPolarity {
173 /// `impl Trait for Type`
175 /// `impl !Trait for Type`
177 /// `#[rustc_reservation_impl] impl Trait for Type`
179 /// This is a "stability hack", not a real Rust feature.
180 /// See #64631 for details.
184 #[derive(Copy, Clone, Debug, PartialEq, HashStable)]
185 pub struct AssocItem {
187 #[stable_hasher(project(name))]
191 pub defaultness: hir::Defaultness,
192 pub container: AssocItemContainer,
194 /// Whether this is a method with an explicit self
195 /// as its first argument, allowing method calls.
196 pub method_has_self_argument: bool,
199 #[derive(Copy, Clone, PartialEq, Debug, HashStable)]
208 pub fn suggestion_descr(&self) -> &'static str {
210 ty::AssocKind::Method => "method call",
211 ty::AssocKind::Type | ty::AssocKind::OpaqueTy => "associated type",
212 ty::AssocKind::Const => "associated constant",
216 pub fn namespace(&self) -> Namespace {
218 ty::AssocKind::OpaqueTy | ty::AssocKind::Type => Namespace::TypeNS,
219 ty::AssocKind::Const | ty::AssocKind::Method => Namespace::ValueNS,
225 pub fn def_kind(&self) -> DefKind {
227 AssocKind::Const => DefKind::AssocConst,
228 AssocKind::Method => DefKind::AssocFn,
229 AssocKind::Type => DefKind::AssocTy,
230 AssocKind::OpaqueTy => DefKind::AssocOpaqueTy,
234 /// Tests whether the associated item admits a non-trivial implementation
236 pub fn relevant_for_never(&self) -> bool {
238 AssocKind::OpaqueTy | AssocKind::Const | AssocKind::Type => true,
239 // FIXME(canndrew): Be more thorough here, check if any argument is uninhabited.
240 AssocKind::Method => !self.method_has_self_argument,
244 pub fn signature(&self, tcx: TyCtxt<'_>) -> String {
246 ty::AssocKind::Method => {
247 // We skip the binder here because the binder would deanonymize all
248 // late-bound regions, and we don't want method signatures to show up
249 // `as for<'r> fn(&'r MyType)`. Pretty-printing handles late-bound
250 // regions just fine, showing `fn(&MyType)`.
251 tcx.fn_sig(self.def_id).skip_binder().to_string()
253 ty::AssocKind::Type => format!("type {};", self.ident),
254 // FIXME(type_alias_impl_trait): we should print bounds here too.
255 ty::AssocKind::OpaqueTy => format!("type {};", self.ident),
256 ty::AssocKind::Const => {
257 format!("const {}: {:?};", self.ident, tcx.type_of(self.def_id))
263 /// A list of `ty::AssocItem`s in definition order that allows for efficient lookup by name.
265 /// When doing lookup by name, we try to postpone hygienic comparison for as long as possible since
266 /// it is relatively expensive. Instead, items are indexed by `Symbol` and hygienic comparison is
267 /// done only on items with the same name.
268 #[derive(Debug, Clone, PartialEq, HashStable)]
269 pub struct AssociatedItems {
270 items: SortedIndexMultiMap<u32, Symbol, ty::AssocItem>,
273 impl AssociatedItems {
274 /// Constructs an `AssociatedItems` map from a series of `ty::AssocItem`s in definition order.
275 pub fn new(items_in_def_order: impl IntoIterator<Item = ty::AssocItem>) -> Self {
276 let items = items_in_def_order.into_iter().map(|item| (item.ident.name, item)).collect();
277 AssociatedItems { items }
280 /// Returns a slice of associated items in the order they were defined.
282 /// New code should avoid relying on definition order. If you need a particular associated item
283 /// for a known trait, make that trait a lang item instead of indexing this array.
284 pub fn in_definition_order(&self) -> impl '_ + Iterator<Item = &ty::AssocItem> {
285 self.items.iter().map(|(_, v)| v)
288 /// Returns an iterator over all associated items with the given name, ignoring hygiene.
289 pub fn filter_by_name_unhygienic(
292 ) -> impl '_ + Iterator<Item = &ty::AssocItem> {
293 self.items.get_by_key(&name)
296 /// Returns an iterator over all associated items with the given name.
298 /// Multiple items may have the same name if they are in different `Namespace`s. For example,
299 /// an associated type can have the same name as a method. Use one of the `find_by_name_and_*`
300 /// methods below if you know which item you are looking for.
301 pub fn filter_by_name(
305 parent_def_id: DefId,
306 ) -> impl 'a + Iterator<Item = &'a ty::AssocItem> {
307 self.filter_by_name_unhygienic(ident.name)
308 .filter(move |item| tcx.hygienic_eq(ident, item.ident, parent_def_id))
311 /// Returns the associated item with the given name and `AssocKind`, if one exists.
312 pub fn find_by_name_and_kind(
317 parent_def_id: DefId,
318 ) -> Option<&ty::AssocItem> {
319 self.filter_by_name_unhygienic(ident.name)
320 .filter(|item| item.kind == kind)
321 .find(|item| tcx.hygienic_eq(ident, item.ident, parent_def_id))
324 /// Returns the associated item with the given name in the given `Namespace`, if one exists.
325 pub fn find_by_name_and_namespace(
330 parent_def_id: DefId,
331 ) -> Option<&ty::AssocItem> {
332 self.filter_by_name_unhygienic(ident.name)
333 .filter(|item| item.kind.namespace() == ns)
334 .find(|item| tcx.hygienic_eq(ident, item.ident, parent_def_id))
338 #[derive(Clone, Debug, PartialEq, Eq, Copy, RustcEncodable, RustcDecodable, HashStable)]
339 pub enum Visibility {
340 /// Visible everywhere (including in other crates).
342 /// Visible only in the given crate-local module.
344 /// Not visible anywhere in the local crate. This is the visibility of private external items.
348 pub trait DefIdTree: Copy {
349 fn parent(self, id: DefId) -> Option<DefId>;
351 fn is_descendant_of(self, mut descendant: DefId, ancestor: DefId) -> bool {
352 if descendant.krate != ancestor.krate {
356 while descendant != ancestor {
357 match self.parent(descendant) {
358 Some(parent) => descendant = parent,
359 None => return false,
366 impl<'tcx> DefIdTree for TyCtxt<'tcx> {
367 fn parent(self, id: DefId) -> Option<DefId> {
368 self.def_key(id).parent.map(|index| DefId { index, ..id })
373 pub fn from_hir(visibility: &hir::Visibility<'_>, id: hir::HirId, tcx: TyCtxt<'_>) -> Self {
374 match visibility.node {
375 hir::VisibilityKind::Public => Visibility::Public,
376 hir::VisibilityKind::Crate(_) => Visibility::Restricted(DefId::local(CRATE_DEF_INDEX)),
377 hir::VisibilityKind::Restricted { ref path, .. } => match path.res {
378 // If there is no resolution, `resolve` will have already reported an error, so
379 // assume that the visibility is public to avoid reporting more privacy errors.
380 Res::Err => Visibility::Public,
381 def => Visibility::Restricted(def.def_id()),
383 hir::VisibilityKind::Inherited => {
384 Visibility::Restricted(tcx.parent_module(id).to_def_id())
389 /// Returns `true` if an item with this visibility is accessible from the given block.
390 pub fn is_accessible_from<T: DefIdTree>(self, module: DefId, tree: T) -> bool {
391 let restriction = match self {
392 // Public items are visible everywhere.
393 Visibility::Public => return true,
394 // Private items from other crates are visible nowhere.
395 Visibility::Invisible => return false,
396 // Restricted items are visible in an arbitrary local module.
397 Visibility::Restricted(other) if other.krate != module.krate => return false,
398 Visibility::Restricted(module) => module,
401 tree.is_descendant_of(module, restriction)
404 /// Returns `true` if this visibility is at least as accessible as the given visibility
405 pub fn is_at_least<T: DefIdTree>(self, vis: Visibility, tree: T) -> bool {
406 let vis_restriction = match vis {
407 Visibility::Public => return self == Visibility::Public,
408 Visibility::Invisible => return true,
409 Visibility::Restricted(module) => module,
412 self.is_accessible_from(vis_restriction, tree)
415 // Returns `true` if this item is visible anywhere in the local crate.
416 pub fn is_visible_locally(self) -> bool {
418 Visibility::Public => true,
419 Visibility::Restricted(def_id) => def_id.is_local(),
420 Visibility::Invisible => false,
425 #[derive(Copy, Clone, PartialEq, RustcDecodable, RustcEncodable, HashStable)]
427 Covariant, // T<A> <: T<B> iff A <: B -- e.g., function return type
428 Invariant, // T<A> <: T<B> iff B == A -- e.g., type of mutable cell
429 Contravariant, // T<A> <: T<B> iff B <: A -- e.g., function param type
430 Bivariant, // T<A> <: T<B> -- e.g., unused type parameter
433 /// The crate variances map is computed during typeck and contains the
434 /// variance of every item in the local crate. You should not use it
435 /// directly, because to do so will make your pass dependent on the
436 /// HIR of every item in the local crate. Instead, use
437 /// `tcx.variances_of()` to get the variance for a *particular*
439 #[derive(HashStable)]
440 pub struct CrateVariancesMap<'tcx> {
441 /// For each item with generics, maps to a vector of the variance
442 /// of its generics. If an item has no generics, it will have no
444 pub variances: FxHashMap<DefId, &'tcx [ty::Variance]>,
448 /// `a.xform(b)` combines the variance of a context with the
449 /// variance of a type with the following meaning. If we are in a
450 /// context with variance `a`, and we encounter a type argument in
451 /// a position with variance `b`, then `a.xform(b)` is the new
452 /// variance with which the argument appears.
458 /// Here, the "ambient" variance starts as covariant. `*mut T` is
459 /// invariant with respect to `T`, so the variance in which the
460 /// `Vec<i32>` appears is `Covariant.xform(Invariant)`, which
461 /// yields `Invariant`. Now, the type `Vec<T>` is covariant with
462 /// respect to its type argument `T`, and hence the variance of
463 /// the `i32` here is `Invariant.xform(Covariant)`, which results
464 /// (again) in `Invariant`.
468 /// fn(*const Vec<i32>, *mut Vec<i32)
470 /// The ambient variance is covariant. A `fn` type is
471 /// contravariant with respect to its parameters, so the variance
472 /// within which both pointer types appear is
473 /// `Covariant.xform(Contravariant)`, or `Contravariant`. `*const
474 /// T` is covariant with respect to `T`, so the variance within
475 /// which the first `Vec<i32>` appears is
476 /// `Contravariant.xform(Covariant)` or `Contravariant`. The same
477 /// is true for its `i32` argument. In the `*mut T` case, the
478 /// variance of `Vec<i32>` is `Contravariant.xform(Invariant)`,
479 /// and hence the outermost type is `Invariant` with respect to
480 /// `Vec<i32>` (and its `i32` argument).
482 /// Source: Figure 1 of "Taming the Wildcards:
483 /// Combining Definition- and Use-Site Variance" published in PLDI'11.
484 pub fn xform(self, v: ty::Variance) -> ty::Variance {
486 // Figure 1, column 1.
487 (ty::Covariant, ty::Covariant) => ty::Covariant,
488 (ty::Covariant, ty::Contravariant) => ty::Contravariant,
489 (ty::Covariant, ty::Invariant) => ty::Invariant,
490 (ty::Covariant, ty::Bivariant) => ty::Bivariant,
492 // Figure 1, column 2.
493 (ty::Contravariant, ty::Covariant) => ty::Contravariant,
494 (ty::Contravariant, ty::Contravariant) => ty::Covariant,
495 (ty::Contravariant, ty::Invariant) => ty::Invariant,
496 (ty::Contravariant, ty::Bivariant) => ty::Bivariant,
498 // Figure 1, column 3.
499 (ty::Invariant, _) => ty::Invariant,
501 // Figure 1, column 4.
502 (ty::Bivariant, _) => ty::Bivariant,
507 // Contains information needed to resolve types and (in the future) look up
508 // the types of AST nodes.
509 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
510 pub struct CReaderCacheKey {
516 /// Flags that we track on types. These flags are propagated upwards
517 /// through the type during type construction, so that we can quickly check
518 /// whether the type has various kinds of types in it without recursing
519 /// over the type itself.
520 pub struct TypeFlags: u32 {
521 // Does this have parameters? Used to determine whether substitution is
523 /// Does this have [Param]?
524 const HAS_TY_PARAM = 1 << 0;
525 /// Does this have [ReEarlyBound]?
526 const HAS_RE_PARAM = 1 << 1;
527 /// Does this have [ConstKind::Param]?
528 const HAS_CT_PARAM = 1 << 2;
530 const NEEDS_SUBST = TypeFlags::HAS_TY_PARAM.bits
531 | TypeFlags::HAS_RE_PARAM.bits
532 | TypeFlags::HAS_CT_PARAM.bits;
534 /// Does this have [Infer]?
535 const HAS_TY_INFER = 1 << 3;
536 /// Does this have [ReVar]?
537 const HAS_RE_INFER = 1 << 4;
538 /// Does this have [ConstKind::Infer]?
539 const HAS_CT_INFER = 1 << 5;
541 /// Does this have inference variables? Used to determine whether
542 /// inference is required.
543 const NEEDS_INFER = TypeFlags::HAS_TY_INFER.bits
544 | TypeFlags::HAS_RE_INFER.bits
545 | TypeFlags::HAS_CT_INFER.bits;
547 /// Does this have [Placeholder]?
548 const HAS_TY_PLACEHOLDER = 1 << 6;
549 /// Does this have [RePlaceholder]?
550 const HAS_RE_PLACEHOLDER = 1 << 7;
551 /// Does this have [ConstKind::Placeholder]?
552 const HAS_CT_PLACEHOLDER = 1 << 8;
554 /// `true` if there are "names" of regions and so forth
555 /// that are local to a particular fn/inferctxt
556 const HAS_FREE_LOCAL_REGIONS = 1 << 9;
558 /// `true` if there are "names" of types and regions and so forth
559 /// that are local to a particular fn
560 const HAS_FREE_LOCAL_NAMES = TypeFlags::HAS_TY_PARAM.bits
561 | TypeFlags::HAS_CT_PARAM.bits
562 | TypeFlags::HAS_TY_INFER.bits
563 | TypeFlags::HAS_CT_INFER.bits
564 | TypeFlags::HAS_TY_PLACEHOLDER.bits
565 | TypeFlags::HAS_CT_PLACEHOLDER.bits
566 | TypeFlags::HAS_FREE_LOCAL_REGIONS.bits;
568 /// Does this have [Projection] or [UnnormalizedProjection]?
569 const HAS_TY_PROJECTION = 1 << 10;
570 /// Does this have [Opaque]?
571 const HAS_TY_OPAQUE = 1 << 11;
572 /// Does this have [ConstKind::Unevaluated]?
573 const HAS_CT_PROJECTION = 1 << 12;
575 /// Could this type be normalized further?
576 const HAS_PROJECTION = TypeFlags::HAS_TY_PROJECTION.bits
577 | TypeFlags::HAS_TY_OPAQUE.bits
578 | TypeFlags::HAS_CT_PROJECTION.bits;
580 /// Present if the type belongs in a local type context.
581 /// Set for placeholders and inference variables that are not "Fresh".
582 const KEEP_IN_LOCAL_TCX = 1 << 13;
584 /// Is an error type reachable?
585 const HAS_TY_ERR = 1 << 14;
587 /// Does this have any region that "appears free" in the type?
588 /// Basically anything but [ReLateBound] and [ReErased].
589 const HAS_FREE_REGIONS = 1 << 15;
591 /// Does this have any [ReLateBound] regions? Used to check
592 /// if a global bound is safe to evaluate.
593 const HAS_RE_LATE_BOUND = 1 << 16;
595 /// Does this have any [ReErased] regions?
596 const HAS_RE_ERASED = 1 << 17;
598 /// Does this value have parameters/placeholders/inference variables which could be
599 /// replaced later, in a way that would change the results of `impl` specialization?
600 const STILL_FURTHER_SPECIALIZABLE = 1 << 18;
602 /// Flags representing the nominal content of a type,
603 /// computed by FlagsComputation. If you add a new nominal
604 /// flag, it should be added here too.
605 const NOMINAL_FLAGS = TypeFlags::HAS_TY_PARAM.bits
606 | TypeFlags::HAS_RE_PARAM.bits
607 | TypeFlags::HAS_CT_PARAM.bits
608 | TypeFlags::HAS_TY_INFER.bits
609 | TypeFlags::HAS_RE_INFER.bits
610 | TypeFlags::HAS_CT_INFER.bits
611 | TypeFlags::HAS_TY_PLACEHOLDER.bits
612 | TypeFlags::HAS_RE_PLACEHOLDER.bits
613 | TypeFlags::HAS_CT_PLACEHOLDER.bits
614 | TypeFlags::HAS_FREE_LOCAL_REGIONS.bits
615 | TypeFlags::HAS_TY_PROJECTION.bits
616 | TypeFlags::HAS_TY_OPAQUE.bits
617 | TypeFlags::HAS_CT_PROJECTION.bits
618 | TypeFlags::KEEP_IN_LOCAL_TCX.bits
619 | TypeFlags::HAS_TY_ERR.bits
620 | TypeFlags::HAS_FREE_REGIONS.bits
621 | TypeFlags::HAS_RE_LATE_BOUND.bits
622 | TypeFlags::HAS_RE_ERASED.bits
623 | TypeFlags::STILL_FURTHER_SPECIALIZABLE.bits;
627 #[allow(rustc::usage_of_ty_tykind)]
628 pub struct TyS<'tcx> {
629 pub kind: TyKind<'tcx>,
630 pub flags: TypeFlags,
632 /// This is a kind of confusing thing: it stores the smallest
635 /// (a) the binder itself captures nothing but
636 /// (b) all the late-bound things within the type are captured
637 /// by some sub-binder.
639 /// So, for a type without any late-bound things, like `u32`, this
640 /// will be *innermost*, because that is the innermost binder that
641 /// captures nothing. But for a type `&'D u32`, where `'D` is a
642 /// late-bound region with De Bruijn index `D`, this would be `D + 1`
643 /// -- the binder itself does not capture `D`, but `D` is captured
644 /// by an inner binder.
646 /// We call this concept an "exclusive" binder `D` because all
647 /// De Bruijn indices within the type are contained within `0..D`
649 outer_exclusive_binder: ty::DebruijnIndex,
652 // `TyS` is used a lot. Make sure it doesn't unintentionally get bigger.
653 #[cfg(target_arch = "x86_64")]
654 static_assert_size!(TyS<'_>, 32);
656 impl<'tcx> Ord for TyS<'tcx> {
657 fn cmp(&self, other: &TyS<'tcx>) -> Ordering {
658 self.kind.cmp(&other.kind)
662 impl<'tcx> PartialOrd for TyS<'tcx> {
663 fn partial_cmp(&self, other: &TyS<'tcx>) -> Option<Ordering> {
664 Some(self.kind.cmp(&other.kind))
668 impl<'tcx> PartialEq for TyS<'tcx> {
670 fn eq(&self, other: &TyS<'tcx>) -> bool {
674 impl<'tcx> Eq for TyS<'tcx> {}
676 impl<'tcx> Hash for TyS<'tcx> {
677 fn hash<H: Hasher>(&self, s: &mut H) {
678 (self as *const TyS<'_>).hash(s)
682 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for ty::TyS<'tcx> {
683 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
687 // The other fields just provide fast access to information that is
688 // also contained in `kind`, so no need to hash them.
691 outer_exclusive_binder: _,
694 kind.hash_stable(hcx, hasher);
698 #[rustc_diagnostic_item = "Ty"]
699 pub type Ty<'tcx> = &'tcx TyS<'tcx>;
701 impl<'tcx> rustc_serialize::UseSpecializedEncodable for Ty<'tcx> {}
702 impl<'tcx> rustc_serialize::UseSpecializedDecodable for Ty<'tcx> {}
704 pub type CanonicalTy<'tcx> = Canonical<'tcx, Ty<'tcx>>;
707 /// A dummy type used to force `List` to be unsized while not requiring references to it be wide
709 type OpaqueListContents;
712 /// A wrapper for slices with the additional invariant
713 /// that the slice is interned and no other slice with
714 /// the same contents can exist in the same context.
715 /// This means we can use pointer for both
716 /// equality comparisons and hashing.
717 /// Note: `Slice` was already taken by the `Ty`.
722 opaque: OpaqueListContents,
725 unsafe impl<T: Sync> Sync for List<T> {}
727 impl<T: Copy> List<T> {
729 fn from_arena<'tcx>(arena: &'tcx Arena<'tcx>, slice: &[T]) -> &'tcx List<T> {
730 assert!(!mem::needs_drop::<T>());
731 assert!(mem::size_of::<T>() != 0);
732 assert!(!slice.is_empty());
734 // Align up the size of the len (usize) field
735 let align = mem::align_of::<T>();
736 let align_mask = align - 1;
737 let offset = mem::size_of::<usize>();
738 let offset = (offset + align_mask) & !align_mask;
740 let size = offset + slice.len() * mem::size_of::<T>();
744 .alloc_raw(size, cmp::max(mem::align_of::<T>(), mem::align_of::<usize>()));
746 let result = &mut *(mem.as_mut_ptr() as *mut List<T>);
748 result.len = slice.len();
750 // Write the elements
751 let arena_slice = slice::from_raw_parts_mut(result.data.as_mut_ptr(), result.len);
752 arena_slice.copy_from_slice(slice);
759 impl<T: fmt::Debug> fmt::Debug for List<T> {
760 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
765 impl<T: Encodable> Encodable for List<T> {
767 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
772 impl<T> Ord for List<T>
776 fn cmp(&self, other: &List<T>) -> Ordering {
777 if self == other { Ordering::Equal } else { <[T] as Ord>::cmp(&**self, &**other) }
781 impl<T> PartialOrd for List<T>
785 fn partial_cmp(&self, other: &List<T>) -> Option<Ordering> {
787 Some(Ordering::Equal)
789 <[T] as PartialOrd>::partial_cmp(&**self, &**other)
794 impl<T: PartialEq> PartialEq for List<T> {
796 fn eq(&self, other: &List<T>) -> bool {
800 impl<T: Eq> Eq for List<T> {}
802 impl<T> Hash for List<T> {
804 fn hash<H: Hasher>(&self, s: &mut H) {
805 (self as *const List<T>).hash(s)
809 impl<T> Deref for List<T> {
812 fn deref(&self) -> &[T] {
817 impl<T> AsRef<[T]> for List<T> {
819 fn as_ref(&self) -> &[T] {
820 unsafe { slice::from_raw_parts(self.data.as_ptr(), self.len) }
824 impl<'a, T> IntoIterator for &'a List<T> {
826 type IntoIter = <&'a [T] as IntoIterator>::IntoIter;
828 fn into_iter(self) -> Self::IntoIter {
833 impl<'tcx> rustc_serialize::UseSpecializedDecodable for &'tcx List<Ty<'tcx>> {}
837 pub fn empty<'a>() -> &'a List<T> {
838 #[repr(align(64), C)]
839 struct EmptySlice([u8; 64]);
840 static EMPTY_SLICE: EmptySlice = EmptySlice([0; 64]);
841 assert!(mem::align_of::<T>() <= 64);
842 unsafe { &*(&EMPTY_SLICE as *const _ as *const List<T>) }
846 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
847 pub struct UpvarPath {
848 pub hir_id: hir::HirId,
851 /// Upvars do not get their own `NodeId`. Instead, we use the pair of
852 /// the original var ID (that is, the root variable that is referenced
853 /// by the upvar) and the ID of the closure expression.
854 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
856 pub var_path: UpvarPath,
857 pub closure_expr_id: LocalDefId,
860 #[derive(Clone, PartialEq, Debug, RustcEncodable, RustcDecodable, Copy, HashStable)]
861 pub enum BorrowKind {
862 /// Data must be immutable and is aliasable.
865 /// Data must be immutable but not aliasable. This kind of borrow
866 /// cannot currently be expressed by the user and is used only in
867 /// implicit closure bindings. It is needed when the closure
868 /// is borrowing or mutating a mutable referent, e.g.:
870 /// let x: &mut isize = ...;
871 /// let y = || *x += 5;
873 /// If we were to try to translate this closure into a more explicit
874 /// form, we'd encounter an error with the code as written:
876 /// struct Env { x: & &mut isize }
877 /// let x: &mut isize = ...;
878 /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
879 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
881 /// This is then illegal because you cannot mutate a `&mut` found
882 /// in an aliasable location. To solve, you'd have to translate with
883 /// an `&mut` borrow:
885 /// struct Env { x: & &mut isize }
886 /// let x: &mut isize = ...;
887 /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
888 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
890 /// Now the assignment to `**env.x` is legal, but creating a
891 /// mutable pointer to `x` is not because `x` is not mutable. We
892 /// could fix this by declaring `x` as `let mut x`. This is ok in
893 /// user code, if awkward, but extra weird for closures, since the
894 /// borrow is hidden.
896 /// So we introduce a "unique imm" borrow -- the referent is
897 /// immutable, but not aliasable. This solves the problem. For
898 /// simplicity, we don't give users the way to express this
899 /// borrow, it's just used when translating closures.
902 /// Data is mutable and not aliasable.
906 /// Information describing the capture of an upvar. This is computed
907 /// during `typeck`, specifically by `regionck`.
908 #[derive(PartialEq, Clone, Debug, Copy, RustcEncodable, RustcDecodable, HashStable)]
909 pub enum UpvarCapture<'tcx> {
910 /// Upvar is captured by value. This is always true when the
911 /// closure is labeled `move`, but can also be true in other cases
912 /// depending on inference.
915 /// Upvar is captured by reference.
916 ByRef(UpvarBorrow<'tcx>),
919 #[derive(PartialEq, Clone, Copy, RustcEncodable, RustcDecodable, HashStable)]
920 pub struct UpvarBorrow<'tcx> {
921 /// The kind of borrow: by-ref upvars have access to shared
922 /// immutable borrows, which are not part of the normal language
924 pub kind: BorrowKind,
926 /// Region of the resulting reference.
927 pub region: ty::Region<'tcx>,
930 pub type UpvarListMap = FxHashMap<DefId, FxIndexMap<hir::HirId, UpvarId>>;
931 pub type UpvarCaptureMap<'tcx> = FxHashMap<UpvarId, UpvarCapture<'tcx>>;
933 #[derive(Clone, Copy, PartialEq, Eq)]
934 pub enum IntVarValue {
936 UintType(ast::UintTy),
939 #[derive(Clone, Copy, PartialEq, Eq)]
940 pub struct FloatVarValue(pub ast::FloatTy);
942 impl ty::EarlyBoundRegion {
943 pub fn to_bound_region(&self) -> ty::BoundRegion {
944 ty::BoundRegion::BrNamed(self.def_id, self.name)
947 /// Does this early bound region have a name? Early bound regions normally
948 /// always have names except when using anonymous lifetimes (`'_`).
949 pub fn has_name(&self) -> bool {
950 self.name != kw::UnderscoreLifetime
954 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
955 pub enum GenericParamDefKind {
959 object_lifetime_default: ObjectLifetimeDefault,
960 synthetic: Option<hir::SyntheticTyParamKind>,
965 impl GenericParamDefKind {
966 pub fn descr(&self) -> &'static str {
968 GenericParamDefKind::Lifetime => "lifetime",
969 GenericParamDefKind::Type { .. } => "type",
970 GenericParamDefKind::Const => "constant",
975 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
976 pub struct GenericParamDef {
981 /// `pure_wrt_drop`, set by the (unsafe) `#[may_dangle]` attribute
982 /// on generic parameter `'a`/`T`, asserts data behind the parameter
983 /// `'a`/`T` won't be accessed during the parent type's `Drop` impl.
984 pub pure_wrt_drop: bool,
986 pub kind: GenericParamDefKind,
989 impl GenericParamDef {
990 pub fn to_early_bound_region_data(&self) -> ty::EarlyBoundRegion {
991 if let GenericParamDefKind::Lifetime = self.kind {
992 ty::EarlyBoundRegion { def_id: self.def_id, index: self.index, name: self.name }
994 bug!("cannot convert a non-lifetime parameter def to an early bound region")
998 pub fn to_bound_region(&self) -> ty::BoundRegion {
999 if let GenericParamDefKind::Lifetime = self.kind {
1000 self.to_early_bound_region_data().to_bound_region()
1002 bug!("cannot convert a non-lifetime parameter def to an early bound region")
1008 pub struct GenericParamCount {
1009 pub lifetimes: usize,
1014 /// Information about the formal type/lifetime parameters associated
1015 /// with an item or method. Analogous to `hir::Generics`.
1017 /// The ordering of parameters is the same as in `Subst` (excluding child generics):
1018 /// `Self` (optionally), `Lifetime` params..., `Type` params...
1019 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
1020 pub struct Generics {
1021 pub parent: Option<DefId>,
1022 pub parent_count: usize,
1023 pub params: Vec<GenericParamDef>,
1025 /// Reverse map to the `index` field of each `GenericParamDef`.
1026 #[stable_hasher(ignore)]
1027 pub param_def_id_to_index: FxHashMap<DefId, u32>,
1030 pub has_late_bound_regions: Option<Span>,
1033 impl<'tcx> Generics {
1034 pub fn count(&self) -> usize {
1035 self.parent_count + self.params.len()
1038 pub fn own_counts(&self) -> GenericParamCount {
1039 // We could cache this as a property of `GenericParamCount`, but
1040 // the aim is to refactor this away entirely eventually and the
1041 // presence of this method will be a constant reminder.
1042 let mut own_counts: GenericParamCount = Default::default();
1044 for param in &self.params {
1046 GenericParamDefKind::Lifetime => own_counts.lifetimes += 1,
1047 GenericParamDefKind::Type { .. } => own_counts.types += 1,
1048 GenericParamDefKind::Const => own_counts.consts += 1,
1055 pub fn requires_monomorphization(&self, tcx: TyCtxt<'tcx>) -> bool {
1056 if self.own_requires_monomorphization() {
1060 if let Some(parent_def_id) = self.parent {
1061 let parent = tcx.generics_of(parent_def_id);
1062 parent.requires_monomorphization(tcx)
1068 pub fn own_requires_monomorphization(&self) -> bool {
1069 for param in &self.params {
1071 GenericParamDefKind::Type { .. } | GenericParamDefKind::Const => return true,
1072 GenericParamDefKind::Lifetime => {}
1078 pub fn param_at(&'tcx self, param_index: usize, tcx: TyCtxt<'tcx>) -> &'tcx GenericParamDef {
1079 if let Some(index) = param_index.checked_sub(self.parent_count) {
1082 tcx.generics_of(self.parent.expect("parent_count > 0 but no parent?"))
1083 .param_at(param_index, tcx)
1087 pub fn region_param(
1089 param: &EarlyBoundRegion,
1091 ) -> &'tcx GenericParamDef {
1092 let param = self.param_at(param.index as usize, tcx);
1094 GenericParamDefKind::Lifetime => param,
1095 _ => bug!("expected lifetime parameter, but found another generic parameter"),
1099 /// Returns the `GenericParamDef` associated with this `ParamTy`.
1100 pub fn type_param(&'tcx self, param: &ParamTy, tcx: TyCtxt<'tcx>) -> &'tcx GenericParamDef {
1101 let param = self.param_at(param.index as usize, tcx);
1103 GenericParamDefKind::Type { .. } => param,
1104 _ => bug!("expected type parameter, but found another generic parameter"),
1108 /// Returns the `ConstParameterDef` associated with this `ParamConst`.
1109 pub fn const_param(&'tcx self, param: &ParamConst, tcx: TyCtxt<'tcx>) -> &GenericParamDef {
1110 let param = self.param_at(param.index as usize, tcx);
1112 GenericParamDefKind::Const => param,
1113 _ => bug!("expected const parameter, but found another generic parameter"),
1118 /// Bounds on generics.
1119 #[derive(Copy, Clone, Default, Debug, RustcEncodable, RustcDecodable, HashStable)]
1120 pub struct GenericPredicates<'tcx> {
1121 pub parent: Option<DefId>,
1122 pub predicates: &'tcx [(Predicate<'tcx>, Span)],
1125 impl<'tcx> GenericPredicates<'tcx> {
1129 substs: SubstsRef<'tcx>,
1130 ) -> InstantiatedPredicates<'tcx> {
1131 let mut instantiated = InstantiatedPredicates::empty();
1132 self.instantiate_into(tcx, &mut instantiated, substs);
1136 pub fn instantiate_own(
1139 substs: SubstsRef<'tcx>,
1140 ) -> InstantiatedPredicates<'tcx> {
1141 InstantiatedPredicates {
1142 predicates: self.predicates.iter().map(|(p, _)| p.subst(tcx, substs)).collect(),
1143 spans: self.predicates.iter().map(|(_, sp)| *sp).collect(),
1147 fn instantiate_into(
1150 instantiated: &mut InstantiatedPredicates<'tcx>,
1151 substs: SubstsRef<'tcx>,
1153 if let Some(def_id) = self.parent {
1154 tcx.predicates_of(def_id).instantiate_into(tcx, instantiated, substs);
1156 instantiated.predicates.extend(self.predicates.iter().map(|(p, _)| p.subst(tcx, substs)));
1157 instantiated.spans.extend(self.predicates.iter().map(|(_, sp)| *sp));
1160 pub fn instantiate_identity(&self, tcx: TyCtxt<'tcx>) -> InstantiatedPredicates<'tcx> {
1161 let mut instantiated = InstantiatedPredicates::empty();
1162 self.instantiate_identity_into(tcx, &mut instantiated);
1166 fn instantiate_identity_into(
1169 instantiated: &mut InstantiatedPredicates<'tcx>,
1171 if let Some(def_id) = self.parent {
1172 tcx.predicates_of(def_id).instantiate_identity_into(tcx, instantiated);
1174 instantiated.predicates.extend(self.predicates.iter().map(|(p, _)| p));
1175 instantiated.spans.extend(self.predicates.iter().map(|(_, s)| s));
1178 pub fn instantiate_supertrait(
1181 poly_trait_ref: &ty::PolyTraitRef<'tcx>,
1182 ) -> InstantiatedPredicates<'tcx> {
1183 assert_eq!(self.parent, None);
1184 InstantiatedPredicates {
1188 .map(|(pred, _)| pred.subst_supertrait(tcx, poly_trait_ref))
1190 spans: self.predicates.iter().map(|(_, sp)| *sp).collect(),
1195 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1196 #[derive(HashStable, TypeFoldable)]
1197 pub enum Predicate<'tcx> {
1198 /// Corresponds to `where Foo: Bar<A, B, C>`. `Foo` here would be
1199 /// the `Self` type of the trait reference and `A`, `B`, and `C`
1200 /// would be the type parameters.
1202 /// A trait predicate will have `Constness::Const` if it originates
1203 /// from a bound on a `const fn` without the `?const` opt-out (e.g.,
1204 /// `const fn foobar<Foo: Bar>() {}`).
1205 Trait(PolyTraitPredicate<'tcx>, Constness),
1208 RegionOutlives(PolyRegionOutlivesPredicate<'tcx>),
1211 TypeOutlives(PolyTypeOutlivesPredicate<'tcx>),
1213 /// `where <T as TraitRef>::Name == X`, approximately.
1214 /// See the `ProjectionPredicate` struct for details.
1215 Projection(PolyProjectionPredicate<'tcx>),
1217 /// No syntax: `T` well-formed.
1218 WellFormed(Ty<'tcx>),
1220 /// Trait must be object-safe.
1223 /// No direct syntax. May be thought of as `where T: FnFoo<...>`
1224 /// for some substitutions `...` and `T` being a closure type.
1225 /// Satisfied (or refuted) once we know the closure's kind.
1226 ClosureKind(DefId, SubstsRef<'tcx>, ClosureKind),
1229 Subtype(PolySubtypePredicate<'tcx>),
1231 /// Constant initializer must evaluate successfully.
1232 ConstEvaluatable(DefId, SubstsRef<'tcx>),
1235 /// The crate outlives map is computed during typeck and contains the
1236 /// outlives of every item in the local crate. You should not use it
1237 /// directly, because to do so will make your pass dependent on the
1238 /// HIR of every item in the local crate. Instead, use
1239 /// `tcx.inferred_outlives_of()` to get the outlives for a *particular*
1241 #[derive(HashStable)]
1242 pub struct CratePredicatesMap<'tcx> {
1243 /// For each struct with outlive bounds, maps to a vector of the
1244 /// predicate of its outlive bounds. If an item has no outlives
1245 /// bounds, it will have no entry.
1246 pub predicates: FxHashMap<DefId, &'tcx [(ty::Predicate<'tcx>, Span)]>,
1249 impl<'tcx> AsRef<Predicate<'tcx>> for Predicate<'tcx> {
1250 fn as_ref(&self) -> &Predicate<'tcx> {
1255 impl<'tcx> Predicate<'tcx> {
1256 /// Performs a substitution suitable for going from a
1257 /// poly-trait-ref to supertraits that must hold if that
1258 /// poly-trait-ref holds. This is slightly different from a normal
1259 /// substitution in terms of what happens with bound regions. See
1260 /// lengthy comment below for details.
1261 pub fn subst_supertrait(
1264 trait_ref: &ty::PolyTraitRef<'tcx>,
1265 ) -> ty::Predicate<'tcx> {
1266 // The interaction between HRTB and supertraits is not entirely
1267 // obvious. Let me walk you (and myself) through an example.
1269 // Let's start with an easy case. Consider two traits:
1271 // trait Foo<'a>: Bar<'a,'a> { }
1272 // trait Bar<'b,'c> { }
1274 // Now, if we have a trait reference `for<'x> T: Foo<'x>`, then
1275 // we can deduce that `for<'x> T: Bar<'x,'x>`. Basically, if we
1276 // knew that `Foo<'x>` (for any 'x) then we also know that
1277 // `Bar<'x,'x>` (for any 'x). This more-or-less falls out from
1278 // normal substitution.
1280 // In terms of why this is sound, the idea is that whenever there
1281 // is an impl of `T:Foo<'a>`, it must show that `T:Bar<'a,'a>`
1282 // holds. So if there is an impl of `T:Foo<'a>` that applies to
1283 // all `'a`, then we must know that `T:Bar<'a,'a>` holds for all
1286 // Another example to be careful of is this:
1288 // trait Foo1<'a>: for<'b> Bar1<'a,'b> { }
1289 // trait Bar1<'b,'c> { }
1291 // Here, if we have `for<'x> T: Foo1<'x>`, then what do we know?
1292 // The answer is that we know `for<'x,'b> T: Bar1<'x,'b>`. The
1293 // reason is similar to the previous example: any impl of
1294 // `T:Foo1<'x>` must show that `for<'b> T: Bar1<'x, 'b>`. So
1295 // basically we would want to collapse the bound lifetimes from
1296 // the input (`trait_ref`) and the supertraits.
1298 // To achieve this in practice is fairly straightforward. Let's
1299 // consider the more complicated scenario:
1301 // - We start out with `for<'x> T: Foo1<'x>`. In this case, `'x`
1302 // has a De Bruijn index of 1. We want to produce `for<'x,'b> T: Bar1<'x,'b>`,
1303 // where both `'x` and `'b` would have a DB index of 1.
1304 // The substitution from the input trait-ref is therefore going to be
1305 // `'a => 'x` (where `'x` has a DB index of 1).
1306 // - The super-trait-ref is `for<'b> Bar1<'a,'b>`, where `'a` is an
1307 // early-bound parameter and `'b' is a late-bound parameter with a
1309 // - If we replace `'a` with `'x` from the input, it too will have
1310 // a DB index of 1, and thus we'll have `for<'x,'b> Bar1<'x,'b>`
1311 // just as we wanted.
1313 // There is only one catch. If we just apply the substitution `'a
1314 // => 'x` to `for<'b> Bar1<'a,'b>`, the substitution code will
1315 // adjust the DB index because we substituting into a binder (it
1316 // tries to be so smart...) resulting in `for<'x> for<'b>
1317 // Bar1<'x,'b>` (we have no syntax for this, so use your
1318 // imagination). Basically the 'x will have DB index of 2 and 'b
1319 // will have DB index of 1. Not quite what we want. So we apply
1320 // the substitution to the *contents* of the trait reference,
1321 // rather than the trait reference itself (put another way, the
1322 // substitution code expects equal binding levels in the values
1323 // from the substitution and the value being substituted into, and
1324 // this trick achieves that).
1326 let substs = &trait_ref.skip_binder().substs;
1328 Predicate::Trait(ref binder, constness) => {
1329 Predicate::Trait(binder.map_bound(|data| data.subst(tcx, substs)), constness)
1331 Predicate::Subtype(ref binder) => {
1332 Predicate::Subtype(binder.map_bound(|data| data.subst(tcx, substs)))
1334 Predicate::RegionOutlives(ref binder) => {
1335 Predicate::RegionOutlives(binder.map_bound(|data| data.subst(tcx, substs)))
1337 Predicate::TypeOutlives(ref binder) => {
1338 Predicate::TypeOutlives(binder.map_bound(|data| data.subst(tcx, substs)))
1340 Predicate::Projection(ref binder) => {
1341 Predicate::Projection(binder.map_bound(|data| data.subst(tcx, substs)))
1343 Predicate::WellFormed(data) => Predicate::WellFormed(data.subst(tcx, substs)),
1344 Predicate::ObjectSafe(trait_def_id) => Predicate::ObjectSafe(trait_def_id),
1345 Predicate::ClosureKind(closure_def_id, closure_substs, kind) => {
1346 Predicate::ClosureKind(closure_def_id, closure_substs.subst(tcx, substs), kind)
1348 Predicate::ConstEvaluatable(def_id, const_substs) => {
1349 Predicate::ConstEvaluatable(def_id, const_substs.subst(tcx, substs))
1355 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1356 #[derive(HashStable, TypeFoldable)]
1357 pub struct TraitPredicate<'tcx> {
1358 pub trait_ref: TraitRef<'tcx>,
1361 pub type PolyTraitPredicate<'tcx> = ty::Binder<TraitPredicate<'tcx>>;
1363 impl<'tcx> TraitPredicate<'tcx> {
1364 pub fn def_id(&self) -> DefId {
1365 self.trait_ref.def_id
1368 pub fn input_types<'a>(&'a self) -> impl DoubleEndedIterator<Item = Ty<'tcx>> + 'a {
1369 self.trait_ref.input_types()
1372 pub fn self_ty(&self) -> Ty<'tcx> {
1373 self.trait_ref.self_ty()
1377 impl<'tcx> PolyTraitPredicate<'tcx> {
1378 pub fn def_id(&self) -> DefId {
1379 // Ok to skip binder since trait `DefId` does not care about regions.
1380 self.skip_binder().def_id()
1384 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, RustcEncodable, RustcDecodable)]
1385 #[derive(HashStable, TypeFoldable)]
1386 pub struct OutlivesPredicate<A, B>(pub A, pub B); // `A: B`
1387 pub type PolyOutlivesPredicate<A, B> = ty::Binder<OutlivesPredicate<A, B>>;
1388 pub type RegionOutlivesPredicate<'tcx> = OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>;
1389 pub type TypeOutlivesPredicate<'tcx> = OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>;
1390 pub type PolyRegionOutlivesPredicate<'tcx> = ty::Binder<RegionOutlivesPredicate<'tcx>>;
1391 pub type PolyTypeOutlivesPredicate<'tcx> = ty::Binder<TypeOutlivesPredicate<'tcx>>;
1393 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
1394 #[derive(HashStable, TypeFoldable)]
1395 pub struct SubtypePredicate<'tcx> {
1396 pub a_is_expected: bool,
1400 pub type PolySubtypePredicate<'tcx> = ty::Binder<SubtypePredicate<'tcx>>;
1402 /// This kind of predicate has no *direct* correspondent in the
1403 /// syntax, but it roughly corresponds to the syntactic forms:
1405 /// 1. `T: TraitRef<..., Item = Type>`
1406 /// 2. `<T as TraitRef<...>>::Item == Type` (NYI)
1408 /// In particular, form #1 is "desugared" to the combination of a
1409 /// normal trait predicate (`T: TraitRef<...>`) and one of these
1410 /// predicates. Form #2 is a broader form in that it also permits
1411 /// equality between arbitrary types. Processing an instance of
1412 /// Form #2 eventually yields one of these `ProjectionPredicate`
1413 /// instances to normalize the LHS.
1414 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1415 #[derive(HashStable, TypeFoldable)]
1416 pub struct ProjectionPredicate<'tcx> {
1417 pub projection_ty: ProjectionTy<'tcx>,
1421 pub type PolyProjectionPredicate<'tcx> = Binder<ProjectionPredicate<'tcx>>;
1423 impl<'tcx> PolyProjectionPredicate<'tcx> {
1424 /// Returns the `DefId` of the associated item being projected.
1425 pub fn item_def_id(&self) -> DefId {
1426 self.skip_binder().projection_ty.item_def_id
1430 pub fn to_poly_trait_ref(&self, tcx: TyCtxt<'tcx>) -> PolyTraitRef<'tcx> {
1431 // Note: unlike with `TraitRef::to_poly_trait_ref()`,
1432 // `self.0.trait_ref` is permitted to have escaping regions.
1433 // This is because here `self` has a `Binder` and so does our
1434 // return value, so we are preserving the number of binding
1436 self.map_bound(|predicate| predicate.projection_ty.trait_ref(tcx))
1439 pub fn ty(&self) -> Binder<Ty<'tcx>> {
1440 self.map_bound(|predicate| predicate.ty)
1443 /// The `DefId` of the `TraitItem` for the associated type.
1445 /// Note that this is not the `DefId` of the `TraitRef` containing this
1446 /// associated type, which is in `tcx.associated_item(projection_def_id()).container`.
1447 pub fn projection_def_id(&self) -> DefId {
1448 // Ok to skip binder since trait `DefId` does not care about regions.
1449 self.skip_binder().projection_ty.item_def_id
1453 pub trait ToPolyTraitRef<'tcx> {
1454 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx>;
1457 impl<'tcx> ToPolyTraitRef<'tcx> for TraitRef<'tcx> {
1458 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
1459 ty::Binder::dummy(*self)
1463 impl<'tcx> ToPolyTraitRef<'tcx> for PolyTraitPredicate<'tcx> {
1464 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
1465 self.map_bound_ref(|trait_pred| trait_pred.trait_ref)
1469 pub trait ToPredicate<'tcx> {
1470 fn to_predicate(&self) -> Predicate<'tcx>;
1473 impl<'tcx> ToPredicate<'tcx> for ConstnessAnd<TraitRef<'tcx>> {
1474 fn to_predicate(&self) -> Predicate<'tcx> {
1475 ty::Predicate::Trait(
1476 ty::Binder::dummy(ty::TraitPredicate { trait_ref: self.value }),
1482 impl<'tcx> ToPredicate<'tcx> for ConstnessAnd<&TraitRef<'tcx>> {
1483 fn to_predicate(&self) -> Predicate<'tcx> {
1484 ty::Predicate::Trait(
1485 ty::Binder::dummy(ty::TraitPredicate { trait_ref: *self.value }),
1491 impl<'tcx> ToPredicate<'tcx> for ConstnessAnd<PolyTraitRef<'tcx>> {
1492 fn to_predicate(&self) -> Predicate<'tcx> {
1493 ty::Predicate::Trait(self.value.to_poly_trait_predicate(), self.constness)
1497 impl<'tcx> ToPredicate<'tcx> for ConstnessAnd<&PolyTraitRef<'tcx>> {
1498 fn to_predicate(&self) -> Predicate<'tcx> {
1499 ty::Predicate::Trait(self.value.to_poly_trait_predicate(), self.constness)
1503 impl<'tcx> ToPredicate<'tcx> for PolyRegionOutlivesPredicate<'tcx> {
1504 fn to_predicate(&self) -> Predicate<'tcx> {
1505 Predicate::RegionOutlives(*self)
1509 impl<'tcx> ToPredicate<'tcx> for PolyTypeOutlivesPredicate<'tcx> {
1510 fn to_predicate(&self) -> Predicate<'tcx> {
1511 Predicate::TypeOutlives(*self)
1515 impl<'tcx> ToPredicate<'tcx> for PolyProjectionPredicate<'tcx> {
1516 fn to_predicate(&self) -> Predicate<'tcx> {
1517 Predicate::Projection(*self)
1521 impl<'tcx> Predicate<'tcx> {
1522 pub fn to_opt_poly_trait_ref(&self) -> Option<PolyTraitRef<'tcx>> {
1524 Predicate::Trait(ref t, _) => Some(t.to_poly_trait_ref()),
1525 Predicate::Projection(..)
1526 | Predicate::Subtype(..)
1527 | Predicate::RegionOutlives(..)
1528 | Predicate::WellFormed(..)
1529 | Predicate::ObjectSafe(..)
1530 | Predicate::ClosureKind(..)
1531 | Predicate::TypeOutlives(..)
1532 | Predicate::ConstEvaluatable(..) => None,
1536 pub fn to_opt_type_outlives(&self) -> Option<PolyTypeOutlivesPredicate<'tcx>> {
1538 Predicate::TypeOutlives(data) => Some(data),
1539 Predicate::Trait(..)
1540 | Predicate::Projection(..)
1541 | Predicate::Subtype(..)
1542 | Predicate::RegionOutlives(..)
1543 | Predicate::WellFormed(..)
1544 | Predicate::ObjectSafe(..)
1545 | Predicate::ClosureKind(..)
1546 | Predicate::ConstEvaluatable(..) => None,
1551 /// Represents the bounds declared on a particular set of type
1552 /// parameters. Should eventually be generalized into a flag list of
1553 /// where-clauses. You can obtain a `InstantiatedPredicates` list from a
1554 /// `GenericPredicates` by using the `instantiate` method. Note that this method
1555 /// reflects an important semantic invariant of `InstantiatedPredicates`: while
1556 /// the `GenericPredicates` are expressed in terms of the bound type
1557 /// parameters of the impl/trait/whatever, an `InstantiatedPredicates` instance
1558 /// represented a set of bounds for some particular instantiation,
1559 /// meaning that the generic parameters have been substituted with
1564 /// struct Foo<T, U: Bar<T>> { ... }
1566 /// Here, the `GenericPredicates` for `Foo` would contain a list of bounds like
1567 /// `[[], [U:Bar<T>]]`. Now if there were some particular reference
1568 /// like `Foo<isize,usize>`, then the `InstantiatedPredicates` would be `[[],
1569 /// [usize:Bar<isize>]]`.
1570 #[derive(Clone, Debug, TypeFoldable)]
1571 pub struct InstantiatedPredicates<'tcx> {
1572 pub predicates: Vec<Predicate<'tcx>>,
1573 pub spans: Vec<Span>,
1576 impl<'tcx> InstantiatedPredicates<'tcx> {
1577 pub fn empty() -> InstantiatedPredicates<'tcx> {
1578 InstantiatedPredicates { predicates: vec![], spans: vec![] }
1581 pub fn is_empty(&self) -> bool {
1582 self.predicates.is_empty()
1586 rustc_index::newtype_index! {
1587 /// "Universes" are used during type- and trait-checking in the
1588 /// presence of `for<..>` binders to control what sets of names are
1589 /// visible. Universes are arranged into a tree: the root universe
1590 /// contains names that are always visible. Each child then adds a new
1591 /// set of names that are visible, in addition to those of its parent.
1592 /// We say that the child universe "extends" the parent universe with
1595 /// To make this more concrete, consider this program:
1599 /// fn bar<T>(x: T) {
1600 /// let y: for<'a> fn(&'a u8, Foo) = ...;
1604 /// The struct name `Foo` is in the root universe U0. But the type
1605 /// parameter `T`, introduced on `bar`, is in an extended universe U1
1606 /// -- i.e., within `bar`, we can name both `T` and `Foo`, but outside
1607 /// of `bar`, we cannot name `T`. Then, within the type of `y`, the
1608 /// region `'a` is in a universe U2 that extends U1, because we can
1609 /// name it inside the fn type but not outside.
1611 /// Universes are used to do type- and trait-checking around these
1612 /// "forall" binders (also called **universal quantification**). The
1613 /// idea is that when, in the body of `bar`, we refer to `T` as a
1614 /// type, we aren't referring to any type in particular, but rather a
1615 /// kind of "fresh" type that is distinct from all other types we have
1616 /// actually declared. This is called a **placeholder** type, and we
1617 /// use universes to talk about this. In other words, a type name in
1618 /// universe 0 always corresponds to some "ground" type that the user
1619 /// declared, but a type name in a non-zero universe is a placeholder
1620 /// type -- an idealized representative of "types in general" that we
1621 /// use for checking generic functions.
1622 pub struct UniverseIndex {
1624 DEBUG_FORMAT = "U{}",
1628 impl UniverseIndex {
1629 pub const ROOT: UniverseIndex = UniverseIndex::from_u32(0);
1631 /// Returns the "next" universe index in order -- this new index
1632 /// is considered to extend all previous universes. This
1633 /// corresponds to entering a `forall` quantifier. So, for
1634 /// example, suppose we have this type in universe `U`:
1637 /// for<'a> fn(&'a u32)
1640 /// Once we "enter" into this `for<'a>` quantifier, we are in a
1641 /// new universe that extends `U` -- in this new universe, we can
1642 /// name the region `'a`, but that region was not nameable from
1643 /// `U` because it was not in scope there.
1644 pub fn next_universe(self) -> UniverseIndex {
1645 UniverseIndex::from_u32(self.private.checked_add(1).unwrap())
1648 /// Returns `true` if `self` can name a name from `other` -- in other words,
1649 /// if the set of names in `self` is a superset of those in
1650 /// `other` (`self >= other`).
1651 pub fn can_name(self, other: UniverseIndex) -> bool {
1652 self.private >= other.private
1655 /// Returns `true` if `self` cannot name some names from `other` -- in other
1656 /// words, if the set of names in `self` is a strict subset of
1657 /// those in `other` (`self < other`).
1658 pub fn cannot_name(self, other: UniverseIndex) -> bool {
1659 self.private < other.private
1663 /// The "placeholder index" fully defines a placeholder region.
1664 /// Placeholder regions are identified by both a **universe** as well
1665 /// as a "bound-region" within that universe. The `bound_region` is
1666 /// basically a name -- distinct bound regions within the same
1667 /// universe are just two regions with an unknown relationship to one
1669 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, PartialOrd, Ord)]
1670 pub struct Placeholder<T> {
1671 pub universe: UniverseIndex,
1675 impl<'a, T> HashStable<StableHashingContext<'a>> for Placeholder<T>
1677 T: HashStable<StableHashingContext<'a>>,
1679 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
1680 self.universe.hash_stable(hcx, hasher);
1681 self.name.hash_stable(hcx, hasher);
1685 pub type PlaceholderRegion = Placeholder<BoundRegion>;
1687 pub type PlaceholderType = Placeholder<BoundVar>;
1689 pub type PlaceholderConst = Placeholder<BoundVar>;
1691 /// When type checking, we use the `ParamEnv` to track
1692 /// details about the set of where-clauses that are in scope at this
1693 /// particular point.
1694 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable, TypeFoldable)]
1695 pub struct ParamEnv<'tcx> {
1696 /// `Obligation`s that the caller must satisfy. This is basically
1697 /// the set of bounds on the in-scope type parameters, translated
1698 /// into `Obligation`s, and elaborated and normalized.
1699 pub caller_bounds: &'tcx List<ty::Predicate<'tcx>>,
1701 /// Typically, this is `Reveal::UserFacing`, but during codegen we
1702 /// want `Reveal::All` -- note that this is always paired with an
1703 /// empty environment. To get that, use `ParamEnv::reveal()`.
1704 pub reveal: traits::Reveal,
1706 /// If this `ParamEnv` comes from a call to `tcx.param_env(def_id)`,
1707 /// register that `def_id` (useful for transitioning to the chalk trait
1709 pub def_id: Option<DefId>,
1712 impl<'tcx> ParamEnv<'tcx> {
1713 /// Construct a trait environment suitable for contexts where
1714 /// there are no where-clauses in scope. Hidden types (like `impl
1715 /// Trait`) are left hidden, so this is suitable for ordinary
1718 pub fn empty() -> Self {
1719 Self::new(List::empty(), Reveal::UserFacing, None)
1722 /// Construct a trait environment with no where-clauses in scope
1723 /// where the values of all `impl Trait` and other hidden types
1724 /// are revealed. This is suitable for monomorphized, post-typeck
1725 /// environments like codegen or doing optimizations.
1727 /// N.B., if you want to have predicates in scope, use `ParamEnv::new`,
1728 /// or invoke `param_env.with_reveal_all()`.
1730 pub fn reveal_all() -> Self {
1731 Self::new(List::empty(), Reveal::All, None)
1734 /// Construct a trait environment with the given set of predicates.
1737 caller_bounds: &'tcx List<ty::Predicate<'tcx>>,
1739 def_id: Option<DefId>,
1741 ty::ParamEnv { caller_bounds, reveal, def_id }
1744 /// Returns a new parameter environment with the same clauses, but
1745 /// which "reveals" the true results of projections in all cases
1746 /// (even for associated types that are specializable). This is
1747 /// the desired behavior during codegen and certain other special
1748 /// contexts; normally though we want to use `Reveal::UserFacing`,
1749 /// which is the default.
1750 pub fn with_reveal_all(self) -> Self {
1751 ty::ParamEnv { reveal: Reveal::All, ..self }
1754 /// Returns this same environment but with no caller bounds.
1755 pub fn without_caller_bounds(self) -> Self {
1756 ty::ParamEnv { caller_bounds: List::empty(), ..self }
1759 /// Creates a suitable environment in which to perform trait
1760 /// queries on the given value. When type-checking, this is simply
1761 /// the pair of the environment plus value. But when reveal is set to
1762 /// All, then if `value` does not reference any type parameters, we will
1763 /// pair it with the empty environment. This improves caching and is generally
1766 /// N.B., we preserve the environment when type-checking because it
1767 /// is possible for the user to have wacky where-clauses like
1768 /// `where Box<u32>: Copy`, which are clearly never
1769 /// satisfiable. We generally want to behave as if they were true,
1770 /// although the surrounding function is never reachable.
1771 pub fn and<T: TypeFoldable<'tcx>>(self, value: T) -> ParamEnvAnd<'tcx, T> {
1773 Reveal::UserFacing => ParamEnvAnd { param_env: self, value },
1776 if value.is_global() {
1777 ParamEnvAnd { param_env: self.without_caller_bounds(), value }
1779 ParamEnvAnd { param_env: self, value }
1786 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1787 pub struct ConstnessAnd<T> {
1788 pub constness: Constness,
1792 // FIXME(ecstaticmorse): Audit all occurrences of `without_const().to_predicate()` to ensure that
1793 // the constness of trait bounds is being propagated correctly.
1794 pub trait WithConstness: Sized {
1796 fn with_constness(self, constness: Constness) -> ConstnessAnd<Self> {
1797 ConstnessAnd { constness, value: self }
1801 fn with_const(self) -> ConstnessAnd<Self> {
1802 self.with_constness(Constness::Const)
1806 fn without_const(self) -> ConstnessAnd<Self> {
1807 self.with_constness(Constness::NotConst)
1811 impl<T> WithConstness for T {}
1813 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TypeFoldable)]
1814 pub struct ParamEnvAnd<'tcx, T> {
1815 pub param_env: ParamEnv<'tcx>,
1819 impl<'tcx, T> ParamEnvAnd<'tcx, T> {
1820 pub fn into_parts(self) -> (ParamEnv<'tcx>, T) {
1821 (self.param_env, self.value)
1825 impl<'a, 'tcx, T> HashStable<StableHashingContext<'a>> for ParamEnvAnd<'tcx, T>
1827 T: HashStable<StableHashingContext<'a>>,
1829 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
1830 let ParamEnvAnd { ref param_env, ref value } = *self;
1832 param_env.hash_stable(hcx, hasher);
1833 value.hash_stable(hcx, hasher);
1837 #[derive(Copy, Clone, Debug, HashStable)]
1838 pub struct Destructor {
1839 /// The `DefId` of the destructor method
1844 #[derive(HashStable)]
1845 pub struct AdtFlags: u32 {
1846 const NO_ADT_FLAGS = 0;
1847 /// Indicates whether the ADT is an enum.
1848 const IS_ENUM = 1 << 0;
1849 /// Indicates whether the ADT is a union.
1850 const IS_UNION = 1 << 1;
1851 /// Indicates whether the ADT is a struct.
1852 const IS_STRUCT = 1 << 2;
1853 /// Indicates whether the ADT is a struct and has a constructor.
1854 const HAS_CTOR = 1 << 3;
1855 /// Indicates whether the type is `PhantomData`.
1856 const IS_PHANTOM_DATA = 1 << 4;
1857 /// Indicates whether the type has a `#[fundamental]` attribute.
1858 const IS_FUNDAMENTAL = 1 << 5;
1859 /// Indicates whether the type is `Box`.
1860 const IS_BOX = 1 << 6;
1861 /// Indicates whether the type is `ManuallyDrop`.
1862 const IS_MANUALLY_DROP = 1 << 7;
1863 // FIXME(matthewjasper) replace these with diagnostic items
1864 /// Indicates whether the type is an `Arc`.
1865 const IS_ARC = 1 << 8;
1866 /// Indicates whether the type is an `Rc`.
1867 const IS_RC = 1 << 9;
1868 /// Indicates whether the variant list of this ADT is `#[non_exhaustive]`.
1869 /// (i.e., this flag is never set unless this ADT is an enum).
1870 const IS_VARIANT_LIST_NON_EXHAUSTIVE = 1 << 10;
1875 #[derive(HashStable)]
1876 pub struct VariantFlags: u32 {
1877 const NO_VARIANT_FLAGS = 0;
1878 /// Indicates whether the field list of this variant is `#[non_exhaustive]`.
1879 const IS_FIELD_LIST_NON_EXHAUSTIVE = 1 << 0;
1883 /// Definition of a variant -- a struct's fields or a enum variant.
1884 #[derive(Debug, HashStable)]
1885 pub struct VariantDef {
1886 /// `DefId` that identifies the variant itself.
1887 /// If this variant belongs to a struct or union, then this is a copy of its `DefId`.
1889 /// `DefId` that identifies the variant's constructor.
1890 /// If this variant is a struct variant, then this is `None`.
1891 pub ctor_def_id: Option<DefId>,
1892 /// Variant or struct name.
1893 #[stable_hasher(project(name))]
1895 /// Discriminant of this variant.
1896 pub discr: VariantDiscr,
1897 /// Fields of this variant.
1898 pub fields: Vec<FieldDef>,
1899 /// Type of constructor of variant.
1900 pub ctor_kind: CtorKind,
1901 /// Flags of the variant (e.g. is field list non-exhaustive)?
1902 flags: VariantFlags,
1903 /// Variant is obtained as part of recovering from a syntactic error.
1904 /// May be incomplete or bogus.
1905 pub recovered: bool,
1908 impl<'tcx> VariantDef {
1909 /// Creates a new `VariantDef`.
1911 /// `variant_did` is the `DefId` that identifies the enum variant (if this `VariantDef`
1912 /// represents an enum variant).
1914 /// `ctor_did` is the `DefId` that identifies the constructor of unit or
1915 /// tuple-variants/structs. If this is a `struct`-variant then this should be `None`.
1917 /// `parent_did` is the `DefId` of the `AdtDef` representing the enum or struct that
1918 /// owns this variant. It is used for checking if a struct has `#[non_exhaustive]` w/out having
1919 /// to go through the redirect of checking the ctor's attributes - but compiling a small crate
1920 /// requires loading the `AdtDef`s for all the structs in the universe (e.g., coherence for any
1921 /// built-in trait), and we do not want to load attributes twice.
1923 /// If someone speeds up attribute loading to not be a performance concern, they can
1924 /// remove this hack and use the constructor `DefId` everywhere.
1928 variant_did: Option<DefId>,
1929 ctor_def_id: Option<DefId>,
1930 discr: VariantDiscr,
1931 fields: Vec<FieldDef>,
1932 ctor_kind: CtorKind,
1938 "VariantDef::new(ident = {:?}, variant_did = {:?}, ctor_def_id = {:?}, discr = {:?},
1939 fields = {:?}, ctor_kind = {:?}, adt_kind = {:?}, parent_did = {:?})",
1940 ident, variant_did, ctor_def_id, discr, fields, ctor_kind, adt_kind, parent_did,
1943 let mut flags = VariantFlags::NO_VARIANT_FLAGS;
1944 if adt_kind == AdtKind::Struct && tcx.has_attr(parent_did, sym::non_exhaustive) {
1945 debug!("found non-exhaustive field list for {:?}", parent_did);
1946 flags = flags | VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE;
1947 } else if let Some(variant_did) = variant_did {
1948 if tcx.has_attr(variant_did, sym::non_exhaustive) {
1949 debug!("found non-exhaustive field list for {:?}", variant_did);
1950 flags = flags | VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE;
1955 def_id: variant_did.unwrap_or(parent_did),
1966 /// Is this field list non-exhaustive?
1968 pub fn is_field_list_non_exhaustive(&self) -> bool {
1969 self.flags.intersects(VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE)
1973 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
1974 pub enum VariantDiscr {
1975 /// Explicit value for this variant, i.e., `X = 123`.
1976 /// The `DefId` corresponds to the embedded constant.
1979 /// The previous variant's discriminant plus one.
1980 /// For efficiency reasons, the distance from the
1981 /// last `Explicit` discriminant is being stored,
1982 /// or `0` for the first variant, if it has none.
1986 #[derive(Debug, HashStable)]
1987 pub struct FieldDef {
1989 #[stable_hasher(project(name))]
1991 pub vis: Visibility,
1994 /// The definition of a user-defined type, e.g., a `struct`, `enum`, or `union`.
1996 /// These are all interned (by `intern_adt_def`) into the `adt_defs` table.
1998 /// The initialism *ADT* stands for an [*algebraic data type (ADT)*][adt].
1999 /// This is slightly wrong because `union`s are not ADTs.
2000 /// Moreover, Rust only allows recursive data types through indirection.
2002 /// [adt]: https://en.wikipedia.org/wiki/Algebraic_data_type
2004 /// The `DefId` of the struct, enum or union item.
2006 /// Variants of the ADT. If this is a struct or union, then there will be a single variant.
2007 pub variants: IndexVec<VariantIdx, VariantDef>,
2008 /// Flags of the ADT (e.g., is this a struct? is this non-exhaustive?).
2010 /// Repr options provided by the user.
2011 pub repr: ReprOptions,
2014 impl PartialOrd for AdtDef {
2015 fn partial_cmp(&self, other: &AdtDef) -> Option<Ordering> {
2016 Some(self.cmp(&other))
2020 /// There should be only one AdtDef for each `did`, therefore
2021 /// it is fine to implement `Ord` only based on `did`.
2022 impl Ord for AdtDef {
2023 fn cmp(&self, other: &AdtDef) -> Ordering {
2024 self.did.cmp(&other.did)
2028 impl PartialEq for AdtDef {
2029 // `AdtDef`s are always interned, and this is part of `TyS` equality.
2031 fn eq(&self, other: &Self) -> bool {
2032 ptr::eq(self, other)
2036 impl Eq for AdtDef {}
2038 impl Hash for AdtDef {
2040 fn hash<H: Hasher>(&self, s: &mut H) {
2041 (self as *const AdtDef).hash(s)
2045 impl<'tcx> rustc_serialize::UseSpecializedEncodable for &'tcx AdtDef {
2046 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
2051 impl<'tcx> rustc_serialize::UseSpecializedDecodable for &'tcx AdtDef {}
2053 impl<'a> HashStable<StableHashingContext<'a>> for AdtDef {
2054 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
2056 static CACHE: RefCell<FxHashMap<usize, Fingerprint>> = Default::default();
2059 let hash: Fingerprint = CACHE.with(|cache| {
2060 let addr = self as *const AdtDef as usize;
2061 *cache.borrow_mut().entry(addr).or_insert_with(|| {
2062 let ty::AdtDef { did, ref variants, ref flags, ref repr } = *self;
2064 let mut hasher = StableHasher::new();
2065 did.hash_stable(hcx, &mut hasher);
2066 variants.hash_stable(hcx, &mut hasher);
2067 flags.hash_stable(hcx, &mut hasher);
2068 repr.hash_stable(hcx, &mut hasher);
2074 hash.hash_stable(hcx, hasher);
2078 #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
2085 impl Into<DataTypeKind> for AdtKind {
2086 fn into(self) -> DataTypeKind {
2088 AdtKind::Struct => DataTypeKind::Struct,
2089 AdtKind::Union => DataTypeKind::Union,
2090 AdtKind::Enum => DataTypeKind::Enum,
2096 #[derive(RustcEncodable, RustcDecodable, Default, HashStable)]
2097 pub struct ReprFlags: u8 {
2098 const IS_C = 1 << 0;
2099 const IS_SIMD = 1 << 1;
2100 const IS_TRANSPARENT = 1 << 2;
2101 // Internal only for now. If true, don't reorder fields.
2102 const IS_LINEAR = 1 << 3;
2103 // If true, don't expose any niche to type's context.
2104 const HIDE_NICHE = 1 << 4;
2105 // Any of these flags being set prevent field reordering optimisation.
2106 const IS_UNOPTIMISABLE = ReprFlags::IS_C.bits |
2107 ReprFlags::IS_SIMD.bits |
2108 ReprFlags::IS_LINEAR.bits;
2112 /// Represents the repr options provided by the user,
2113 #[derive(Copy, Clone, Debug, Eq, PartialEq, RustcEncodable, RustcDecodable, Default, HashStable)]
2114 pub struct ReprOptions {
2115 pub int: Option<attr::IntType>,
2116 pub align: Option<Align>,
2117 pub pack: Option<Align>,
2118 pub flags: ReprFlags,
2122 pub fn new(tcx: TyCtxt<'_>, did: DefId) -> ReprOptions {
2123 let mut flags = ReprFlags::empty();
2124 let mut size = None;
2125 let mut max_align: Option<Align> = None;
2126 let mut min_pack: Option<Align> = None;
2127 for attr in tcx.get_attrs(did).iter() {
2128 for r in attr::find_repr_attrs(&tcx.sess.parse_sess, attr) {
2129 flags.insert(match r {
2130 attr::ReprC => ReprFlags::IS_C,
2131 attr::ReprPacked(pack) => {
2132 let pack = Align::from_bytes(pack as u64).unwrap();
2133 min_pack = Some(if let Some(min_pack) = min_pack {
2140 attr::ReprTransparent => ReprFlags::IS_TRANSPARENT,
2141 attr::ReprNoNiche => ReprFlags::HIDE_NICHE,
2142 attr::ReprSimd => ReprFlags::IS_SIMD,
2143 attr::ReprInt(i) => {
2147 attr::ReprAlign(align) => {
2148 max_align = max_align.max(Some(Align::from_bytes(align as u64).unwrap()));
2155 // This is here instead of layout because the choice must make it into metadata.
2156 if !tcx.consider_optimizing(|| format!("Reorder fields of {:?}", tcx.def_path_str(did))) {
2157 flags.insert(ReprFlags::IS_LINEAR);
2159 ReprOptions { int: size, align: max_align, pack: min_pack, flags }
2163 pub fn simd(&self) -> bool {
2164 self.flags.contains(ReprFlags::IS_SIMD)
2167 pub fn c(&self) -> bool {
2168 self.flags.contains(ReprFlags::IS_C)
2171 pub fn packed(&self) -> bool {
2175 pub fn transparent(&self) -> bool {
2176 self.flags.contains(ReprFlags::IS_TRANSPARENT)
2179 pub fn linear(&self) -> bool {
2180 self.flags.contains(ReprFlags::IS_LINEAR)
2183 pub fn hide_niche(&self) -> bool {
2184 self.flags.contains(ReprFlags::HIDE_NICHE)
2187 pub fn discr_type(&self) -> attr::IntType {
2188 self.int.unwrap_or(attr::SignedInt(ast::IntTy::Isize))
2191 /// Returns `true` if this `#[repr()]` should inhabit "smart enum
2192 /// layout" optimizations, such as representing `Foo<&T>` as a
2194 pub fn inhibit_enum_layout_opt(&self) -> bool {
2195 self.c() || self.int.is_some()
2198 /// Returns `true` if this `#[repr()]` should inhibit struct field reordering
2199 /// optimizations, such as with `repr(C)`, `repr(packed(1))`, or `repr(<int>)`.
2200 pub fn inhibit_struct_field_reordering_opt(&self) -> bool {
2201 if let Some(pack) = self.pack {
2202 if pack.bytes() == 1 {
2206 self.flags.intersects(ReprFlags::IS_UNOPTIMISABLE) || self.int.is_some()
2209 /// Returns `true` if this `#[repr()]` should inhibit union ABI optimisations.
2210 pub fn inhibit_union_abi_opt(&self) -> bool {
2216 /// Creates a new `AdtDef`.
2221 variants: IndexVec<VariantIdx, VariantDef>,
2224 debug!("AdtDef::new({:?}, {:?}, {:?}, {:?})", did, kind, variants, repr);
2225 let mut flags = AdtFlags::NO_ADT_FLAGS;
2227 if kind == AdtKind::Enum && tcx.has_attr(did, sym::non_exhaustive) {
2228 debug!("found non-exhaustive variant list for {:?}", did);
2229 flags = flags | AdtFlags::IS_VARIANT_LIST_NON_EXHAUSTIVE;
2232 flags |= match kind {
2233 AdtKind::Enum => AdtFlags::IS_ENUM,
2234 AdtKind::Union => AdtFlags::IS_UNION,
2235 AdtKind::Struct => AdtFlags::IS_STRUCT,
2238 if kind == AdtKind::Struct && variants[VariantIdx::new(0)].ctor_def_id.is_some() {
2239 flags |= AdtFlags::HAS_CTOR;
2242 let attrs = tcx.get_attrs(did);
2243 if attr::contains_name(&attrs, sym::fundamental) {
2244 flags |= AdtFlags::IS_FUNDAMENTAL;
2246 if Some(did) == tcx.lang_items().phantom_data() {
2247 flags |= AdtFlags::IS_PHANTOM_DATA;
2249 if Some(did) == tcx.lang_items().owned_box() {
2250 flags |= AdtFlags::IS_BOX;
2252 if Some(did) == tcx.lang_items().manually_drop() {
2253 flags |= AdtFlags::IS_MANUALLY_DROP;
2255 if Some(did) == tcx.lang_items().arc() {
2256 flags |= AdtFlags::IS_ARC;
2258 if Some(did) == tcx.lang_items().rc() {
2259 flags |= AdtFlags::IS_RC;
2262 AdtDef { did, variants, flags, repr }
2265 /// Returns `true` if this is a struct.
2267 pub fn is_struct(&self) -> bool {
2268 self.flags.contains(AdtFlags::IS_STRUCT)
2271 /// Returns `true` if this is a union.
2273 pub fn is_union(&self) -> bool {
2274 self.flags.contains(AdtFlags::IS_UNION)
2277 /// Returns `true` if this is a enum.
2279 pub fn is_enum(&self) -> bool {
2280 self.flags.contains(AdtFlags::IS_ENUM)
2283 /// Returns `true` if the variant list of this ADT is `#[non_exhaustive]`.
2285 pub fn is_variant_list_non_exhaustive(&self) -> bool {
2286 self.flags.contains(AdtFlags::IS_VARIANT_LIST_NON_EXHAUSTIVE)
2289 /// Returns the kind of the ADT.
2291 pub fn adt_kind(&self) -> AdtKind {
2294 } else if self.is_union() {
2301 /// Returns a description of this abstract data type.
2302 pub fn descr(&self) -> &'static str {
2303 match self.adt_kind() {
2304 AdtKind::Struct => "struct",
2305 AdtKind::Union => "union",
2306 AdtKind::Enum => "enum",
2310 /// Returns a description of a variant of this abstract data type.
2312 pub fn variant_descr(&self) -> &'static str {
2313 match self.adt_kind() {
2314 AdtKind::Struct => "struct",
2315 AdtKind::Union => "union",
2316 AdtKind::Enum => "variant",
2320 /// If this function returns `true`, it implies that `is_struct` must return `true`.
2322 pub fn has_ctor(&self) -> bool {
2323 self.flags.contains(AdtFlags::HAS_CTOR)
2326 /// Returns `true` if this type is `#[fundamental]` for the purposes
2327 /// of coherence checking.
2329 pub fn is_fundamental(&self) -> bool {
2330 self.flags.contains(AdtFlags::IS_FUNDAMENTAL)
2333 /// Returns `true` if this is `PhantomData<T>`.
2335 pub fn is_phantom_data(&self) -> bool {
2336 self.flags.contains(AdtFlags::IS_PHANTOM_DATA)
2339 /// Returns `true` if this is `Arc<T>`.
2340 pub fn is_arc(&self) -> bool {
2341 self.flags.contains(AdtFlags::IS_ARC)
2344 /// Returns `true` if this is `Rc<T>`.
2345 pub fn is_rc(&self) -> bool {
2346 self.flags.contains(AdtFlags::IS_RC)
2349 /// Returns `true` if this is Box<T>.
2351 pub fn is_box(&self) -> bool {
2352 self.flags.contains(AdtFlags::IS_BOX)
2355 /// Returns `true` if this is `ManuallyDrop<T>`.
2357 pub fn is_manually_drop(&self) -> bool {
2358 self.flags.contains(AdtFlags::IS_MANUALLY_DROP)
2361 /// Returns `true` if this type has a destructor.
2362 pub fn has_dtor(&self, tcx: TyCtxt<'tcx>) -> bool {
2363 self.destructor(tcx).is_some()
2366 /// Asserts this is a struct or union and returns its unique variant.
2367 pub fn non_enum_variant(&self) -> &VariantDef {
2368 assert!(self.is_struct() || self.is_union());
2369 &self.variants[VariantIdx::new(0)]
2373 pub fn predicates(&self, tcx: TyCtxt<'tcx>) -> GenericPredicates<'tcx> {
2374 tcx.predicates_of(self.did)
2377 /// Returns an iterator over all fields contained
2380 pub fn all_fields(&self) -> impl Iterator<Item = &FieldDef> + Clone {
2381 self.variants.iter().flat_map(|v| v.fields.iter())
2384 pub fn is_payloadfree(&self) -> bool {
2385 !self.variants.is_empty() && self.variants.iter().all(|v| v.fields.is_empty())
2388 /// Return a `VariantDef` given a variant id.
2389 pub fn variant_with_id(&self, vid: DefId) -> &VariantDef {
2390 self.variants.iter().find(|v| v.def_id == vid).expect("variant_with_id: unknown variant")
2393 /// Return a `VariantDef` given a constructor id.
2394 pub fn variant_with_ctor_id(&self, cid: DefId) -> &VariantDef {
2397 .find(|v| v.ctor_def_id == Some(cid))
2398 .expect("variant_with_ctor_id: unknown variant")
2401 /// Return the index of `VariantDef` given a variant id.
2402 pub fn variant_index_with_id(&self, vid: DefId) -> VariantIdx {
2405 .find(|(_, v)| v.def_id == vid)
2406 .expect("variant_index_with_id: unknown variant")
2410 /// Return the index of `VariantDef` given a constructor id.
2411 pub fn variant_index_with_ctor_id(&self, cid: DefId) -> VariantIdx {
2414 .find(|(_, v)| v.ctor_def_id == Some(cid))
2415 .expect("variant_index_with_ctor_id: unknown variant")
2419 pub fn variant_of_res(&self, res: Res) -> &VariantDef {
2421 Res::Def(DefKind::Variant, vid) => self.variant_with_id(vid),
2422 Res::Def(DefKind::Ctor(..), cid) => self.variant_with_ctor_id(cid),
2423 Res::Def(DefKind::Struct, _)
2424 | Res::Def(DefKind::Union, _)
2425 | Res::Def(DefKind::TyAlias, _)
2426 | Res::Def(DefKind::AssocTy, _)
2428 | Res::SelfCtor(..) => self.non_enum_variant(),
2429 _ => bug!("unexpected res {:?} in variant_of_res", res),
2434 pub fn eval_explicit_discr(&self, tcx: TyCtxt<'tcx>, expr_did: DefId) -> Option<Discr<'tcx>> {
2435 let param_env = tcx.param_env(expr_did);
2436 let repr_type = self.repr.discr_type();
2437 match tcx.const_eval_poly(expr_did) {
2439 let ty = repr_type.to_ty(tcx);
2440 if let Some(b) = val.try_to_bits_for_ty(tcx, param_env, ty) {
2441 trace!("discriminants: {} ({:?})", b, repr_type);
2442 Some(Discr { val: b, ty })
2444 info!("invalid enum discriminant: {:#?}", val);
2445 crate::mir::interpret::struct_error(
2446 tcx.at(tcx.def_span(expr_did)),
2447 "constant evaluation of enum discriminant resulted in non-integer",
2453 Err(ErrorHandled::Reported) => {
2454 if !expr_did.is_local() {
2456 tcx.def_span(expr_did),
2457 "variant discriminant evaluation succeeded \
2458 in its crate but failed locally"
2463 Err(ErrorHandled::TooGeneric) => {
2464 span_bug!(tcx.def_span(expr_did), "enum discriminant depends on generic arguments",)
2470 pub fn discriminants(
2473 ) -> impl Iterator<Item = (VariantIdx, Discr<'tcx>)> + Captures<'tcx> {
2474 let repr_type = self.repr.discr_type();
2475 let initial = repr_type.initial_discriminant(tcx);
2476 let mut prev_discr = None::<Discr<'tcx>>;
2477 self.variants.iter_enumerated().map(move |(i, v)| {
2478 let mut discr = prev_discr.map_or(initial, |d| d.wrap_incr(tcx));
2479 if let VariantDiscr::Explicit(expr_did) = v.discr {
2480 if let Some(new_discr) = self.eval_explicit_discr(tcx, expr_did) {
2484 prev_discr = Some(discr);
2491 pub fn variant_range(&self) -> Range<VariantIdx> {
2492 VariantIdx::new(0)..VariantIdx::new(self.variants.len())
2495 /// Computes the discriminant value used by a specific variant.
2496 /// Unlike `discriminants`, this is (amortized) constant-time,
2497 /// only doing at most one query for evaluating an explicit
2498 /// discriminant (the last one before the requested variant),
2499 /// assuming there are no constant-evaluation errors there.
2501 pub fn discriminant_for_variant(
2504 variant_index: VariantIdx,
2506 let (val, offset) = self.discriminant_def_for_variant(variant_index);
2507 let explicit_value = val
2508 .and_then(|expr_did| self.eval_explicit_discr(tcx, expr_did))
2509 .unwrap_or_else(|| self.repr.discr_type().initial_discriminant(tcx));
2510 explicit_value.checked_add(tcx, offset as u128).0
2513 /// Yields a `DefId` for the discriminant and an offset to add to it
2514 /// Alternatively, if there is no explicit discriminant, returns the
2515 /// inferred discriminant directly.
2516 pub fn discriminant_def_for_variant(&self, variant_index: VariantIdx) -> (Option<DefId>, u32) {
2517 let mut explicit_index = variant_index.as_u32();
2520 match self.variants[VariantIdx::from_u32(explicit_index)].discr {
2521 ty::VariantDiscr::Relative(0) => {
2525 ty::VariantDiscr::Relative(distance) => {
2526 explicit_index -= distance;
2528 ty::VariantDiscr::Explicit(did) => {
2529 expr_did = Some(did);
2534 (expr_did, variant_index.as_u32() - explicit_index)
2537 pub fn destructor(&self, tcx: TyCtxt<'tcx>) -> Option<Destructor> {
2538 tcx.adt_destructor(self.did)
2541 /// Returns a list of types such that `Self: Sized` if and only
2542 /// if that type is `Sized`, or `TyErr` if this type is recursive.
2544 /// Oddly enough, checking that the sized-constraint is `Sized` is
2545 /// actually more expressive than checking all members:
2546 /// the `Sized` trait is inductive, so an associated type that references
2547 /// `Self` would prevent its containing ADT from being `Sized`.
2549 /// Due to normalization being eager, this applies even if
2550 /// the associated type is behind a pointer (e.g., issue #31299).
2551 pub fn sized_constraint(&self, tcx: TyCtxt<'tcx>) -> &'tcx [Ty<'tcx>] {
2552 tcx.adt_sized_constraint(self.did).0
2556 impl<'tcx> FieldDef {
2557 /// Returns the type of this field. The `subst` is typically obtained
2558 /// via the second field of `TyKind::AdtDef`.
2559 pub fn ty(&self, tcx: TyCtxt<'tcx>, subst: SubstsRef<'tcx>) -> Ty<'tcx> {
2560 tcx.type_of(self.did).subst(tcx, subst)
2564 /// Represents the various closure traits in the language. This
2565 /// will determine the type of the environment (`self`, in the
2566 /// desugaring) argument that the closure expects.
2568 /// You can get the environment type of a closure using
2569 /// `tcx.closure_env_ty()`.
2570 #[derive(Clone, Copy, PartialOrd, Ord, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
2571 #[derive(HashStable)]
2572 pub enum ClosureKind {
2573 // Warning: Ordering is significant here! The ordering is chosen
2574 // because the trait Fn is a subtrait of FnMut and so in turn, and
2575 // hence we order it so that Fn < FnMut < FnOnce.
2581 impl<'tcx> ClosureKind {
2582 // This is the initial value used when doing upvar inference.
2583 pub const LATTICE_BOTTOM: ClosureKind = ClosureKind::Fn;
2585 pub fn trait_did(&self, tcx: TyCtxt<'tcx>) -> DefId {
2587 ClosureKind::Fn => tcx.require_lang_item(FnTraitLangItem, None),
2588 ClosureKind::FnMut => tcx.require_lang_item(FnMutTraitLangItem, None),
2589 ClosureKind::FnOnce => tcx.require_lang_item(FnOnceTraitLangItem, None),
2593 /// Returns `true` if this a type that impls this closure kind
2594 /// must also implement `other`.
2595 pub fn extends(self, other: ty::ClosureKind) -> bool {
2596 match (self, other) {
2597 (ClosureKind::Fn, ClosureKind::Fn) => true,
2598 (ClosureKind::Fn, ClosureKind::FnMut) => true,
2599 (ClosureKind::Fn, ClosureKind::FnOnce) => true,
2600 (ClosureKind::FnMut, ClosureKind::FnMut) => true,
2601 (ClosureKind::FnMut, ClosureKind::FnOnce) => true,
2602 (ClosureKind::FnOnce, ClosureKind::FnOnce) => true,
2607 /// Returns the representative scalar type for this closure kind.
2608 /// See `TyS::to_opt_closure_kind` for more details.
2609 pub fn to_ty(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
2611 ty::ClosureKind::Fn => tcx.types.i8,
2612 ty::ClosureKind::FnMut => tcx.types.i16,
2613 ty::ClosureKind::FnOnce => tcx.types.i32,
2619 pub fn from_mutbl(m: hir::Mutability) -> BorrowKind {
2621 hir::Mutability::Mut => MutBorrow,
2622 hir::Mutability::Not => ImmBorrow,
2626 /// Returns a mutability `m` such that an `&m T` pointer could be used to obtain this borrow
2627 /// kind. Because borrow kinds are richer than mutabilities, we sometimes have to pick a
2628 /// mutability that is stronger than necessary so that it at least *would permit* the borrow in
2630 pub fn to_mutbl_lossy(self) -> hir::Mutability {
2632 MutBorrow => hir::Mutability::Mut,
2633 ImmBorrow => hir::Mutability::Not,
2635 // We have no type corresponding to a unique imm borrow, so
2636 // use `&mut`. It gives all the capabilities of an `&uniq`
2637 // and hence is a safe "over approximation".
2638 UniqueImmBorrow => hir::Mutability::Mut,
2642 pub fn to_user_str(&self) -> &'static str {
2644 MutBorrow => "mutable",
2645 ImmBorrow => "immutable",
2646 UniqueImmBorrow => "uniquely immutable",
2651 #[derive(Debug, Clone)]
2652 pub enum Attributes<'tcx> {
2653 Owned(Lrc<[ast::Attribute]>),
2654 Borrowed(&'tcx [ast::Attribute]),
2657 impl<'tcx> ::std::ops::Deref for Attributes<'tcx> {
2658 type Target = [ast::Attribute];
2660 fn deref(&self) -> &[ast::Attribute] {
2662 &Attributes::Owned(ref data) => &data,
2663 &Attributes::Borrowed(data) => data,
2668 #[derive(Debug, PartialEq, Eq)]
2669 pub enum ImplOverlapKind {
2670 /// These impls are always allowed to overlap.
2672 /// Whether or not the impl is permitted due to the trait being a `#[marker]` trait
2675 /// These impls are allowed to overlap, but that raises
2676 /// an issue #33140 future-compatibility warning.
2678 /// Some background: in Rust 1.0, the trait-object types `Send + Sync` (today's
2679 /// `dyn Send + Sync`) and `Sync + Send` (now `dyn Sync + Send`) were different.
2681 /// The widely-used version 0.1.0 of the crate `traitobject` had accidentally relied
2682 /// that difference, making what reduces to the following set of impls:
2686 /// impl Trait for dyn Send + Sync {}
2687 /// impl Trait for dyn Sync + Send {}
2690 /// Obviously, once we made these types be identical, that code causes a coherence
2691 /// error and a fairly big headache for us. However, luckily for us, the trait
2692 /// `Trait` used in this case is basically a marker trait, and therefore having
2693 /// overlapping impls for it is sound.
2695 /// To handle this, we basically regard the trait as a marker trait, with an additional
2696 /// future-compatibility warning. To avoid accidentally "stabilizing" this feature,
2697 /// it has the following restrictions:
2699 /// 1. The trait must indeed be a marker-like trait (i.e., no items), and must be
2701 /// 2. The trait-ref of both impls must be equal.
2702 /// 3. The trait-ref of both impls must be a trait object type consisting only of
2704 /// 4. Neither of the impls can have any where-clauses.
2706 /// Once `traitobject` 0.1.0 is no longer an active concern, this hack can be removed.
2710 impl<'tcx> TyCtxt<'tcx> {
2711 pub fn body_tables(self, body: hir::BodyId) -> &'tcx TypeckTables<'tcx> {
2712 self.typeck_tables_of(self.hir().body_owner_def_id(body))
2715 /// Returns an iterator of the `DefId`s for all body-owners in this
2716 /// crate. If you would prefer to iterate over the bodies
2717 /// themselves, you can do `self.hir().krate().body_ids.iter()`.
2718 pub fn body_owners(self) -> impl Iterator<Item = DefId> + Captures<'tcx> + 'tcx {
2723 .map(move |&body_id| self.hir().body_owner_def_id(body_id))
2726 pub fn par_body_owners<F: Fn(DefId) + sync::Sync + sync::Send>(self, f: F) {
2727 par_iter(&self.hir().krate().body_ids)
2728 .for_each(|&body_id| f(self.hir().body_owner_def_id(body_id)));
2731 pub fn provided_trait_methods(self, id: DefId) -> impl 'tcx + Iterator<Item = &'tcx AssocItem> {
2732 self.associated_items(id)
2733 .in_definition_order()
2734 .filter(|item| item.kind == AssocKind::Method && item.defaultness.has_value())
2737 pub fn trait_relevant_for_never(self, did: DefId) -> bool {
2738 self.associated_items(did).in_definition_order().any(|item| item.relevant_for_never())
2741 pub fn opt_item_name(self, def_id: DefId) -> Option<Ident> {
2742 self.hir().as_local_hir_id(def_id).and_then(|hir_id| self.hir().get(hir_id).ident())
2745 pub fn opt_associated_item(self, def_id: DefId) -> Option<AssocItem> {
2746 let is_associated_item = if let Some(hir_id) = self.hir().as_local_hir_id(def_id) {
2747 match self.hir().get(hir_id) {
2748 Node::TraitItem(_) | Node::ImplItem(_) => true,
2752 match self.def_kind(def_id) {
2753 Some(DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy) => true,
2758 is_associated_item.then(|| self.associated_item(def_id))
2761 pub fn field_index(self, hir_id: hir::HirId, tables: &TypeckTables<'_>) -> usize {
2762 tables.field_indices().get(hir_id).cloned().expect("no index for a field")
2765 pub fn find_field_index(self, ident: Ident, variant: &VariantDef) -> Option<usize> {
2766 variant.fields.iter().position(|field| self.hygienic_eq(ident, field.ident, variant.def_id))
2769 /// Returns `true` if the impls are the same polarity and the trait either
2770 /// has no items or is annotated #[marker] and prevents item overrides.
2771 pub fn impls_are_allowed_to_overlap(
2775 ) -> Option<ImplOverlapKind> {
2776 // If either trait impl references an error, they're allowed to overlap,
2777 // as one of them essentially doesn't exist.
2778 if self.impl_trait_ref(def_id1).map_or(false, |tr| tr.references_error())
2779 || self.impl_trait_ref(def_id2).map_or(false, |tr| tr.references_error())
2781 return Some(ImplOverlapKind::Permitted { marker: false });
2784 match (self.impl_polarity(def_id1), self.impl_polarity(def_id2)) {
2785 (ImplPolarity::Reservation, _) | (_, ImplPolarity::Reservation) => {
2786 // `#[rustc_reservation_impl]` impls don't overlap with anything
2788 "impls_are_allowed_to_overlap({:?}, {:?}) = Some(Permitted) (reservations)",
2791 return Some(ImplOverlapKind::Permitted { marker: false });
2793 (ImplPolarity::Positive, ImplPolarity::Negative)
2794 | (ImplPolarity::Negative, ImplPolarity::Positive) => {
2795 // `impl AutoTrait for Type` + `impl !AutoTrait for Type`
2797 "impls_are_allowed_to_overlap({:?}, {:?}) - None (differing polarities)",
2802 (ImplPolarity::Positive, ImplPolarity::Positive)
2803 | (ImplPolarity::Negative, ImplPolarity::Negative) => {}
2806 let is_marker_overlap = {
2807 let is_marker_impl = |def_id: DefId| -> bool {
2808 let trait_ref = self.impl_trait_ref(def_id);
2809 trait_ref.map_or(false, |tr| self.trait_def(tr.def_id).is_marker)
2811 is_marker_impl(def_id1) && is_marker_impl(def_id2)
2814 if is_marker_overlap {
2816 "impls_are_allowed_to_overlap({:?}, {:?}) = Some(Permitted) (marker overlap)",
2819 Some(ImplOverlapKind::Permitted { marker: true })
2821 if let Some(self_ty1) = self.issue33140_self_ty(def_id1) {
2822 if let Some(self_ty2) = self.issue33140_self_ty(def_id2) {
2823 if self_ty1 == self_ty2 {
2825 "impls_are_allowed_to_overlap({:?}, {:?}) - issue #33140 HACK",
2828 return Some(ImplOverlapKind::Issue33140);
2831 "impls_are_allowed_to_overlap({:?}, {:?}) - found {:?} != {:?}",
2832 def_id1, def_id2, self_ty1, self_ty2
2838 debug!("impls_are_allowed_to_overlap({:?}, {:?}) = None", def_id1, def_id2);
2843 /// Returns `ty::VariantDef` if `res` refers to a struct,
2844 /// or variant or their constructors, panics otherwise.
2845 pub fn expect_variant_res(self, res: Res) -> &'tcx VariantDef {
2847 Res::Def(DefKind::Variant, did) => {
2848 let enum_did = self.parent(did).unwrap();
2849 self.adt_def(enum_did).variant_with_id(did)
2851 Res::Def(DefKind::Struct, did) | Res::Def(DefKind::Union, did) => {
2852 self.adt_def(did).non_enum_variant()
2854 Res::Def(DefKind::Ctor(CtorOf::Variant, ..), variant_ctor_did) => {
2855 let variant_did = self.parent(variant_ctor_did).unwrap();
2856 let enum_did = self.parent(variant_did).unwrap();
2857 self.adt_def(enum_did).variant_with_ctor_id(variant_ctor_did)
2859 Res::Def(DefKind::Ctor(CtorOf::Struct, ..), ctor_did) => {
2860 let struct_did = self.parent(ctor_did).expect("struct ctor has no parent");
2861 self.adt_def(struct_did).non_enum_variant()
2863 _ => bug!("expect_variant_res used with unexpected res {:?}", res),
2867 pub fn item_name(self, id: DefId) -> Symbol {
2868 if id.index == CRATE_DEF_INDEX {
2869 self.original_crate_name(id.krate)
2871 let def_key = self.def_key(id);
2872 match def_key.disambiguated_data.data {
2873 // The name of a constructor is that of its parent.
2874 rustc_hir::definitions::DefPathData::Ctor => {
2875 self.item_name(DefId { krate: id.krate, index: def_key.parent.unwrap() })
2877 _ => def_key.disambiguated_data.data.get_opt_name().unwrap_or_else(|| {
2878 bug!("item_name: no name for {:?}", self.def_path(id));
2884 /// Returns the possibly-auto-generated MIR of a `(DefId, Subst)` pair.
2885 pub fn instance_mir(self, instance: ty::InstanceDef<'tcx>) -> ReadOnlyBodyAndCache<'tcx, 'tcx> {
2887 ty::InstanceDef::Item(did) => self.optimized_mir(did).unwrap_read_only(),
2888 ty::InstanceDef::VtableShim(..)
2889 | ty::InstanceDef::ReifyShim(..)
2890 | ty::InstanceDef::Intrinsic(..)
2891 | ty::InstanceDef::FnPtrShim(..)
2892 | ty::InstanceDef::Virtual(..)
2893 | ty::InstanceDef::ClosureOnceShim { .. }
2894 | ty::InstanceDef::DropGlue(..)
2895 | ty::InstanceDef::CloneShim(..) => self.mir_shims(instance).unwrap_read_only(),
2899 /// Gets the attributes of a definition.
2900 pub fn get_attrs(self, did: DefId) -> Attributes<'tcx> {
2901 if let Some(id) = self.hir().as_local_hir_id(did) {
2902 Attributes::Borrowed(self.hir().attrs(id))
2904 Attributes::Owned(self.item_attrs(did))
2908 /// Determines whether an item is annotated with an attribute.
2909 pub fn has_attr(self, did: DefId, attr: Symbol) -> bool {
2910 attr::contains_name(&self.get_attrs(did), attr)
2913 /// Returns `true` if this is an `auto trait`.
2914 pub fn trait_is_auto(self, trait_def_id: DefId) -> bool {
2915 self.trait_def(trait_def_id).has_auto_impl
2918 pub fn generator_layout(self, def_id: DefId) -> &'tcx GeneratorLayout<'tcx> {
2919 self.optimized_mir(def_id).generator_layout.as_ref().unwrap()
2922 /// Given the `DefId` of an impl, returns the `DefId` of the trait it implements.
2923 /// If it implements no trait, returns `None`.
2924 pub fn trait_id_of_impl(self, def_id: DefId) -> Option<DefId> {
2925 self.impl_trait_ref(def_id).map(|tr| tr.def_id)
2928 /// If the given defid describes a method belonging to an impl, returns the
2929 /// `DefId` of the impl that the method belongs to; otherwise, returns `None`.
2930 pub fn impl_of_method(self, def_id: DefId) -> Option<DefId> {
2931 self.opt_associated_item(def_id).and_then(|trait_item| match trait_item.container {
2932 TraitContainer(_) => None,
2933 ImplContainer(def_id) => Some(def_id),
2937 /// Looks up the span of `impl_did` if the impl is local; otherwise returns `Err`
2938 /// with the name of the crate containing the impl.
2939 pub fn span_of_impl(self, impl_did: DefId) -> Result<Span, Symbol> {
2940 if impl_did.is_local() {
2941 let hir_id = self.hir().as_local_hir_id(impl_did).unwrap();
2942 Ok(self.hir().span(hir_id))
2944 Err(self.crate_name(impl_did.krate))
2948 /// Hygienically compares a use-site name (`use_name`) for a field or an associated item with
2949 /// its supposed definition name (`def_name`). The method also needs `DefId` of the supposed
2950 /// definition's parent/scope to perform comparison.
2951 pub fn hygienic_eq(self, use_name: Ident, def_name: Ident, def_parent_def_id: DefId) -> bool {
2952 // We could use `Ident::eq` here, but we deliberately don't. The name
2953 // comparison fails frequently, and we want to avoid the expensive
2954 // `normalize_to_macros_2_0()` calls required for the span comparison whenever possible.
2955 use_name.name == def_name.name
2959 .hygienic_eq(def_name.span.ctxt(), self.expansion_that_defined(def_parent_def_id))
2962 fn expansion_that_defined(self, scope: DefId) -> ExpnId {
2963 match scope.as_local() {
2964 Some(scope) => self.hir().definitions().expansion_that_defined(scope),
2965 None => ExpnId::root(),
2969 pub fn adjust_ident(self, mut ident: Ident, scope: DefId) -> Ident {
2970 ident.span.normalize_to_macros_2_0_and_adjust(self.expansion_that_defined(scope));
2974 pub fn adjust_ident_and_get_scope(
2979 ) -> (Ident, DefId) {
2981 match ident.span.normalize_to_macros_2_0_and_adjust(self.expansion_that_defined(scope))
2983 Some(actual_expansion) => {
2984 self.hir().definitions().parent_module_of_macro_def(actual_expansion)
2986 None => self.parent_module(block).to_def_id(),
2991 pub fn is_object_safe(self, key: DefId) -> bool {
2992 self.object_safety_violations(key).is_empty()
2996 #[derive(Clone, HashStable)]
2997 pub struct AdtSizedConstraint<'tcx>(pub &'tcx [Ty<'tcx>]);
2999 /// Yields the parent function's `DefId` if `def_id` is an `impl Trait` definition.
3000 pub fn is_impl_trait_defn(tcx: TyCtxt<'_>, def_id: DefId) -> Option<DefId> {
3001 if let Some(hir_id) = tcx.hir().as_local_hir_id(def_id) {
3002 if let Node::Item(item) = tcx.hir().get(hir_id) {
3003 if let hir::ItemKind::OpaqueTy(ref opaque_ty) = item.kind {
3004 return opaque_ty.impl_trait_fn;
3011 pub fn provide(providers: &mut ty::query::Providers<'_>) {
3012 context::provide(providers);
3013 erase_regions::provide(providers);
3014 layout::provide(providers);
3015 super::util::bug::provide(providers);
3016 *providers = ty::query::Providers {
3017 trait_impls_of: trait_def::trait_impls_of_provider,
3018 all_local_trait_impls: trait_def::all_local_trait_impls,
3023 /// A map for the local crate mapping each type to a vector of its
3024 /// inherent impls. This is not meant to be used outside of coherence;
3025 /// rather, you should request the vector for a specific type via
3026 /// `tcx.inherent_impls(def_id)` so as to minimize your dependencies
3027 /// (constructing this map requires touching the entire crate).
3028 #[derive(Clone, Debug, Default, HashStable)]
3029 pub struct CrateInherentImpls {
3030 pub inherent_impls: DefIdMap<Vec<DefId>>,
3033 #[derive(Clone, Copy, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
3034 pub struct SymbolName {
3035 // FIXME: we don't rely on interning or equality here - better have
3036 // this be a `&'tcx str`.
3041 pub fn new(name: &str) -> SymbolName {
3042 SymbolName { name: Symbol::intern(name) }
3046 impl PartialOrd for SymbolName {
3047 fn partial_cmp(&self, other: &SymbolName) -> Option<Ordering> {
3048 self.name.as_str().partial_cmp(&other.name.as_str())
3052 /// Ordering must use the chars to ensure reproducible builds.
3053 impl Ord for SymbolName {
3054 fn cmp(&self, other: &SymbolName) -> Ordering {
3055 self.name.as_str().cmp(&other.name.as_str())
3059 impl fmt::Display for SymbolName {
3060 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
3061 fmt::Display::fmt(&self.name, fmt)
3065 impl fmt::Debug for SymbolName {
3066 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
3067 fmt::Display::fmt(&self.name, fmt)