1 pub use self::fold::{TypeFoldable, TypeVisitor};
2 pub use self::AssocItemContainer::*;
3 pub use self::BorrowKind::*;
4 pub use self::IntVarValue::*;
5 pub use self::Variance::*;
7 use crate::arena::Arena;
8 use crate::hir::exports::ExportMap;
9 use crate::ich::StableHashingContext;
10 use crate::infer::canonical::Canonical;
11 use crate::middle::cstore::CrateStoreDyn;
12 use crate::middle::resolve_lifetime::ObjectLifetimeDefault;
13 use crate::mir::interpret::ErrorHandled;
14 use crate::mir::GeneratorLayout;
15 use crate::mir::ReadOnlyBodyAndCache;
16 use crate::traits::{self, Reveal};
18 use crate::ty::subst::{InternalSubsts, Subst, SubstsRef};
19 use crate::ty::util::{Discr, IntTypeExt};
20 use rustc_ast::ast::{self, Ident, Name};
21 use rustc_ast::node_id::{NodeId, NodeMap, NodeSet};
22 use rustc_attr as attr;
23 use rustc_data_structures::captures::Captures;
24 use rustc_data_structures::fingerprint::Fingerprint;
25 use rustc_data_structures::fx::FxHashMap;
26 use rustc_data_structures::fx::FxIndexMap;
27 use rustc_data_structures::sorted_map::SortedIndexMultiMap;
28 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
29 use rustc_data_structures::sync::{self, par_iter, ParallelIterator};
30 use rustc_errors::ErrorReported;
32 use rustc_hir::def::{CtorKind, CtorOf, DefKind, Namespace, Res};
33 use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, LocalDefId, CRATE_DEF_INDEX};
34 use rustc_hir::lang_items::{FnMutTraitLangItem, FnOnceTraitLangItem, FnTraitLangItem};
35 use rustc_hir::{Constness, GlobMap, Node, TraitMap};
36 use rustc_index::vec::{Idx, IndexVec};
37 use rustc_macros::HashStable;
38 use rustc_serialize::{self, Encodable, Encoder};
39 use rustc_session::DataTypeKind;
40 use rustc_span::hygiene::ExpnId;
41 use rustc_span::symbol::{kw, sym, Symbol};
43 use rustc_target::abi::{Align, VariantIdx};
45 use std::cell::RefCell;
46 use std::cmp::{self, Ordering};
48 use std::hash::{Hash, Hasher};
54 pub use self::sty::BoundRegion::*;
55 pub use self::sty::InferTy::*;
56 pub use self::sty::RegionKind;
57 pub use self::sty::RegionKind::*;
58 pub use self::sty::TyKind::*;
59 pub use self::sty::{Binder, BoundTy, BoundTyKind, BoundVar, DebruijnIndex, INNERMOST};
60 pub use self::sty::{BoundRegion, EarlyBoundRegion, FreeRegion, Region};
61 pub use self::sty::{CanonicalPolyFnSig, FnSig, GenSig, PolyFnSig, PolyGenSig};
62 pub use self::sty::{ClosureSubsts, GeneratorSubsts, TypeAndMut, UpvarSubsts};
63 pub use self::sty::{Const, ConstKind, ExistentialProjection, PolyExistentialProjection};
64 pub use self::sty::{ConstVid, FloatVid, IntVid, RegionVid, TyVid};
65 pub use self::sty::{ExistentialPredicate, InferConst, InferTy, ParamConst, ParamTy, ProjectionTy};
66 pub use self::sty::{ExistentialTraitRef, PolyExistentialTraitRef};
67 pub use self::sty::{PolyTraitRef, TraitRef, TyKind};
68 pub use crate::ty::diagnostics::*;
70 pub use self::binding::BindingMode;
71 pub use self::binding::BindingMode::*;
73 pub use self::context::{tls, FreeRegionInfo, TyCtxt};
74 pub use self::context::{
75 CanonicalUserType, CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations, ResolvedOpaqueTy,
76 UserType, UserTypeAnnotationIndex,
78 pub use self::context::{
79 CtxtInterners, GeneratorInteriorTypeCause, GlobalCtxt, Lift, TypeckTables,
82 pub use self::instance::{Instance, InstanceDef};
84 pub use self::trait_def::TraitDef;
86 pub use self::query::queries;
99 pub mod free_region_map;
100 pub mod inhabitedness;
102 pub mod normalize_erasing_regions;
116 mod structural_impls;
121 pub struct ResolverOutputs {
122 pub definitions: rustc_hir::definitions::Definitions,
123 pub cstore: Box<CrateStoreDyn>,
124 pub extern_crate_map: NodeMap<CrateNum>,
125 pub trait_map: TraitMap<NodeId>,
126 pub maybe_unused_trait_imports: NodeSet,
127 pub maybe_unused_extern_crates: Vec<(NodeId, Span)>,
128 pub export_map: ExportMap<NodeId>,
129 pub glob_map: GlobMap,
130 /// Extern prelude entries. The value is `true` if the entry was introduced
131 /// via `extern crate` item and not `--extern` option or compiler built-in.
132 pub extern_prelude: FxHashMap<Name, bool>,
135 #[derive(Clone, Copy, PartialEq, Eq, Debug, HashStable)]
136 pub enum AssocItemContainer {
137 TraitContainer(DefId),
138 ImplContainer(DefId),
141 impl AssocItemContainer {
142 /// Asserts that this is the `DefId` of an associated item declared
143 /// in a trait, and returns the trait `DefId`.
144 pub fn assert_trait(&self) -> DefId {
146 TraitContainer(id) => id,
147 _ => bug!("associated item has wrong container type: {:?}", self),
151 pub fn id(&self) -> DefId {
153 TraitContainer(id) => id,
154 ImplContainer(id) => id,
159 /// The "header" of an impl is everything outside the body: a Self type, a trait
160 /// ref (in the case of a trait impl), and a set of predicates (from the
161 /// bounds / where-clauses).
162 #[derive(Clone, Debug, TypeFoldable)]
163 pub struct ImplHeader<'tcx> {
164 pub impl_def_id: DefId,
165 pub self_ty: Ty<'tcx>,
166 pub trait_ref: Option<TraitRef<'tcx>>,
167 pub predicates: Vec<Predicate<'tcx>>,
170 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable)]
171 pub enum ImplPolarity {
172 /// `impl Trait for Type`
174 /// `impl !Trait for Type`
176 /// `#[rustc_reservation_impl] impl Trait for Type`
178 /// This is a "stability hack", not a real Rust feature.
179 /// See #64631 for details.
183 #[derive(Copy, Clone, Debug, PartialEq, HashStable)]
184 pub struct AssocItem {
186 #[stable_hasher(project(name))]
190 pub defaultness: hir::Defaultness,
191 pub container: AssocItemContainer,
193 /// Whether this is a method with an explicit self
194 /// as its first parameter, allowing method calls.
195 pub fn_has_self_parameter: bool,
198 #[derive(Copy, Clone, PartialEq, Debug, HashStable)]
207 pub fn namespace(&self) -> Namespace {
209 ty::AssocKind::OpaqueTy | ty::AssocKind::Type => Namespace::TypeNS,
210 ty::AssocKind::Const | ty::AssocKind::Fn => Namespace::ValueNS,
214 pub fn as_def_kind(&self) -> DefKind {
216 AssocKind::Const => DefKind::AssocConst,
217 AssocKind::Fn => DefKind::AssocFn,
218 AssocKind::Type => DefKind::AssocTy,
219 AssocKind::OpaqueTy => DefKind::AssocOpaqueTy,
225 /// Tests whether the associated item admits a non-trivial implementation
227 pub fn relevant_for_never(&self) -> bool {
229 AssocKind::OpaqueTy | AssocKind::Const | AssocKind::Type => true,
230 // FIXME(canndrew): Be more thorough here, check if any argument is uninhabited.
231 AssocKind::Fn => !self.fn_has_self_parameter,
235 pub fn signature(&self, tcx: TyCtxt<'_>) -> String {
237 ty::AssocKind::Fn => {
238 // We skip the binder here because the binder would deanonymize all
239 // late-bound regions, and we don't want method signatures to show up
240 // `as for<'r> fn(&'r MyType)`. Pretty-printing handles late-bound
241 // regions just fine, showing `fn(&MyType)`.
242 tcx.fn_sig(self.def_id).skip_binder().to_string()
244 ty::AssocKind::Type => format!("type {};", self.ident),
245 // FIXME(type_alias_impl_trait): we should print bounds here too.
246 ty::AssocKind::OpaqueTy => format!("type {};", self.ident),
247 ty::AssocKind::Const => {
248 format!("const {}: {:?};", self.ident, tcx.type_of(self.def_id))
254 /// A list of `ty::AssocItem`s in definition order that allows for efficient lookup by name.
256 /// When doing lookup by name, we try to postpone hygienic comparison for as long as possible since
257 /// it is relatively expensive. Instead, items are indexed by `Symbol` and hygienic comparison is
258 /// done only on items with the same name.
259 #[derive(Debug, Clone, PartialEq, HashStable)]
260 pub struct AssociatedItems {
261 items: SortedIndexMultiMap<u32, Symbol, ty::AssocItem>,
264 impl AssociatedItems {
265 /// Constructs an `AssociatedItems` map from a series of `ty::AssocItem`s in definition order.
266 pub fn new(items_in_def_order: impl IntoIterator<Item = ty::AssocItem>) -> Self {
267 let items = items_in_def_order.into_iter().map(|item| (item.ident.name, item)).collect();
268 AssociatedItems { items }
271 /// Returns a slice of associated items in the order they were defined.
273 /// New code should avoid relying on definition order. If you need a particular associated item
274 /// for a known trait, make that trait a lang item instead of indexing this array.
275 pub fn in_definition_order(&self) -> impl '_ + Iterator<Item = &ty::AssocItem> {
276 self.items.iter().map(|(_, v)| v)
279 /// Returns an iterator over all associated items with the given name, ignoring hygiene.
280 pub fn filter_by_name_unhygienic(
283 ) -> impl '_ + Iterator<Item = &ty::AssocItem> {
284 self.items.get_by_key(&name)
287 /// Returns an iterator over all associated items with the given name.
289 /// Multiple items may have the same name if they are in different `Namespace`s. For example,
290 /// an associated type can have the same name as a method. Use one of the `find_by_name_and_*`
291 /// methods below if you know which item you are looking for.
292 pub fn filter_by_name(
296 parent_def_id: DefId,
297 ) -> impl 'a + Iterator<Item = &'a ty::AssocItem> {
298 self.filter_by_name_unhygienic(ident.name)
299 .filter(move |item| tcx.hygienic_eq(ident, item.ident, parent_def_id))
302 /// Returns the associated item with the given name and `AssocKind`, if one exists.
303 pub fn find_by_name_and_kind(
308 parent_def_id: DefId,
309 ) -> Option<&ty::AssocItem> {
310 self.filter_by_name_unhygienic(ident.name)
311 .filter(|item| item.kind == kind)
312 .find(|item| tcx.hygienic_eq(ident, item.ident, parent_def_id))
315 /// Returns the associated item with the given name in the given `Namespace`, if one exists.
316 pub fn find_by_name_and_namespace(
321 parent_def_id: DefId,
322 ) -> Option<&ty::AssocItem> {
323 self.filter_by_name_unhygienic(ident.name)
324 .filter(|item| item.kind.namespace() == ns)
325 .find(|item| tcx.hygienic_eq(ident, item.ident, parent_def_id))
329 #[derive(Clone, Debug, PartialEq, Eq, Copy, RustcEncodable, RustcDecodable, HashStable)]
330 pub enum Visibility {
331 /// Visible everywhere (including in other crates).
333 /// Visible only in the given crate-local module.
335 /// Not visible anywhere in the local crate. This is the visibility of private external items.
339 pub trait DefIdTree: Copy {
340 fn parent(self, id: DefId) -> Option<DefId>;
342 fn is_descendant_of(self, mut descendant: DefId, ancestor: DefId) -> bool {
343 if descendant.krate != ancestor.krate {
347 while descendant != ancestor {
348 match self.parent(descendant) {
349 Some(parent) => descendant = parent,
350 None => return false,
357 impl<'tcx> DefIdTree for TyCtxt<'tcx> {
358 fn parent(self, id: DefId) -> Option<DefId> {
359 self.def_key(id).parent.map(|index| DefId { index, ..id })
364 pub fn from_hir(visibility: &hir::Visibility<'_>, id: hir::HirId, tcx: TyCtxt<'_>) -> Self {
365 match visibility.node {
366 hir::VisibilityKind::Public => Visibility::Public,
367 hir::VisibilityKind::Crate(_) => Visibility::Restricted(DefId::local(CRATE_DEF_INDEX)),
368 hir::VisibilityKind::Restricted { ref path, .. } => match path.res {
369 // If there is no resolution, `resolve` will have already reported an error, so
370 // assume that the visibility is public to avoid reporting more privacy errors.
371 Res::Err => Visibility::Public,
372 def => Visibility::Restricted(def.def_id()),
374 hir::VisibilityKind::Inherited => {
375 Visibility::Restricted(tcx.parent_module(id).to_def_id())
380 /// Returns `true` if an item with this visibility is accessible from the given block.
381 pub fn is_accessible_from<T: DefIdTree>(self, module: DefId, tree: T) -> bool {
382 let restriction = match self {
383 // Public items are visible everywhere.
384 Visibility::Public => return true,
385 // Private items from other crates are visible nowhere.
386 Visibility::Invisible => return false,
387 // Restricted items are visible in an arbitrary local module.
388 Visibility::Restricted(other) if other.krate != module.krate => return false,
389 Visibility::Restricted(module) => module,
392 tree.is_descendant_of(module, restriction)
395 /// Returns `true` if this visibility is at least as accessible as the given visibility
396 pub fn is_at_least<T: DefIdTree>(self, vis: Visibility, tree: T) -> bool {
397 let vis_restriction = match vis {
398 Visibility::Public => return self == Visibility::Public,
399 Visibility::Invisible => return true,
400 Visibility::Restricted(module) => module,
403 self.is_accessible_from(vis_restriction, tree)
406 // Returns `true` if this item is visible anywhere in the local crate.
407 pub fn is_visible_locally(self) -> bool {
409 Visibility::Public => true,
410 Visibility::Restricted(def_id) => def_id.is_local(),
411 Visibility::Invisible => false,
416 #[derive(Copy, Clone, PartialEq, RustcDecodable, RustcEncodable, HashStable)]
418 Covariant, // T<A> <: T<B> iff A <: B -- e.g., function return type
419 Invariant, // T<A> <: T<B> iff B == A -- e.g., type of mutable cell
420 Contravariant, // T<A> <: T<B> iff B <: A -- e.g., function param type
421 Bivariant, // T<A> <: T<B> -- e.g., unused type parameter
424 /// The crate variances map is computed during typeck and contains the
425 /// variance of every item in the local crate. You should not use it
426 /// directly, because to do so will make your pass dependent on the
427 /// HIR of every item in the local crate. Instead, use
428 /// `tcx.variances_of()` to get the variance for a *particular*
430 #[derive(HashStable)]
431 pub struct CrateVariancesMap<'tcx> {
432 /// For each item with generics, maps to a vector of the variance
433 /// of its generics. If an item has no generics, it will have no
435 pub variances: FxHashMap<DefId, &'tcx [ty::Variance]>,
439 /// `a.xform(b)` combines the variance of a context with the
440 /// variance of a type with the following meaning. If we are in a
441 /// context with variance `a`, and we encounter a type argument in
442 /// a position with variance `b`, then `a.xform(b)` is the new
443 /// variance with which the argument appears.
449 /// Here, the "ambient" variance starts as covariant. `*mut T` is
450 /// invariant with respect to `T`, so the variance in which the
451 /// `Vec<i32>` appears is `Covariant.xform(Invariant)`, which
452 /// yields `Invariant`. Now, the type `Vec<T>` is covariant with
453 /// respect to its type argument `T`, and hence the variance of
454 /// the `i32` here is `Invariant.xform(Covariant)`, which results
455 /// (again) in `Invariant`.
459 /// fn(*const Vec<i32>, *mut Vec<i32)
461 /// The ambient variance is covariant. A `fn` type is
462 /// contravariant with respect to its parameters, so the variance
463 /// within which both pointer types appear is
464 /// `Covariant.xform(Contravariant)`, or `Contravariant`. `*const
465 /// T` is covariant with respect to `T`, so the variance within
466 /// which the first `Vec<i32>` appears is
467 /// `Contravariant.xform(Covariant)` or `Contravariant`. The same
468 /// is true for its `i32` argument. In the `*mut T` case, the
469 /// variance of `Vec<i32>` is `Contravariant.xform(Invariant)`,
470 /// and hence the outermost type is `Invariant` with respect to
471 /// `Vec<i32>` (and its `i32` argument).
473 /// Source: Figure 1 of "Taming the Wildcards:
474 /// Combining Definition- and Use-Site Variance" published in PLDI'11.
475 pub fn xform(self, v: ty::Variance) -> ty::Variance {
477 // Figure 1, column 1.
478 (ty::Covariant, ty::Covariant) => ty::Covariant,
479 (ty::Covariant, ty::Contravariant) => ty::Contravariant,
480 (ty::Covariant, ty::Invariant) => ty::Invariant,
481 (ty::Covariant, ty::Bivariant) => ty::Bivariant,
483 // Figure 1, column 2.
484 (ty::Contravariant, ty::Covariant) => ty::Contravariant,
485 (ty::Contravariant, ty::Contravariant) => ty::Covariant,
486 (ty::Contravariant, ty::Invariant) => ty::Invariant,
487 (ty::Contravariant, ty::Bivariant) => ty::Bivariant,
489 // Figure 1, column 3.
490 (ty::Invariant, _) => ty::Invariant,
492 // Figure 1, column 4.
493 (ty::Bivariant, _) => ty::Bivariant,
498 // Contains information needed to resolve types and (in the future) look up
499 // the types of AST nodes.
500 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
501 pub struct CReaderCacheKey {
507 /// Flags that we track on types. These flags are propagated upwards
508 /// through the type during type construction, so that we can quickly check
509 /// whether the type has various kinds of types in it without recursing
510 /// over the type itself.
511 pub struct TypeFlags: u32 {
512 // Does this have parameters? Used to determine whether substitution is
514 /// Does this have [Param]?
515 const HAS_TY_PARAM = 1 << 0;
516 /// Does this have [ReEarlyBound]?
517 const HAS_RE_PARAM = 1 << 1;
518 /// Does this have [ConstKind::Param]?
519 const HAS_CT_PARAM = 1 << 2;
521 const NEEDS_SUBST = TypeFlags::HAS_TY_PARAM.bits
522 | TypeFlags::HAS_RE_PARAM.bits
523 | TypeFlags::HAS_CT_PARAM.bits;
525 /// Does this have [Infer]?
526 const HAS_TY_INFER = 1 << 3;
527 /// Does this have [ReVar]?
528 const HAS_RE_INFER = 1 << 4;
529 /// Does this have [ConstKind::Infer]?
530 const HAS_CT_INFER = 1 << 5;
532 /// Does this have inference variables? Used to determine whether
533 /// inference is required.
534 const NEEDS_INFER = TypeFlags::HAS_TY_INFER.bits
535 | TypeFlags::HAS_RE_INFER.bits
536 | TypeFlags::HAS_CT_INFER.bits;
538 /// Does this have [Placeholder]?
539 const HAS_TY_PLACEHOLDER = 1 << 6;
540 /// Does this have [RePlaceholder]?
541 const HAS_RE_PLACEHOLDER = 1 << 7;
542 /// Does this have [ConstKind::Placeholder]?
543 const HAS_CT_PLACEHOLDER = 1 << 8;
545 /// `true` if there are "names" of regions and so forth
546 /// that are local to a particular fn/inferctxt
547 const HAS_FREE_LOCAL_REGIONS = 1 << 9;
549 /// `true` if there are "names" of types and regions and so forth
550 /// that are local to a particular fn
551 const HAS_FREE_LOCAL_NAMES = TypeFlags::HAS_TY_PARAM.bits
552 | TypeFlags::HAS_CT_PARAM.bits
553 | TypeFlags::HAS_TY_INFER.bits
554 | TypeFlags::HAS_CT_INFER.bits
555 | TypeFlags::HAS_TY_PLACEHOLDER.bits
556 | TypeFlags::HAS_CT_PLACEHOLDER.bits
557 | TypeFlags::HAS_FREE_LOCAL_REGIONS.bits;
559 /// Does this have [Projection] or [UnnormalizedProjection]?
560 const HAS_TY_PROJECTION = 1 << 10;
561 /// Does this have [Opaque]?
562 const HAS_TY_OPAQUE = 1 << 11;
563 /// Does this have [ConstKind::Unevaluated]?
564 const HAS_CT_PROJECTION = 1 << 12;
566 /// Could this type be normalized further?
567 const HAS_PROJECTION = TypeFlags::HAS_TY_PROJECTION.bits
568 | TypeFlags::HAS_TY_OPAQUE.bits
569 | TypeFlags::HAS_CT_PROJECTION.bits;
571 /// Is an error type/const reachable?
572 const HAS_ERROR = 1 << 13;
574 /// Does this have any region that "appears free" in the type?
575 /// Basically anything but [ReLateBound] and [ReErased].
576 const HAS_FREE_REGIONS = 1 << 14;
578 /// Does this have any [ReLateBound] regions? Used to check
579 /// if a global bound is safe to evaluate.
580 const HAS_RE_LATE_BOUND = 1 << 15;
582 /// Does this have any [ReErased] regions?
583 const HAS_RE_ERASED = 1 << 16;
585 /// Does this value have parameters/placeholders/inference variables which could be
586 /// replaced later, in a way that would change the results of `impl` specialization?
587 const STILL_FURTHER_SPECIALIZABLE = 1 << 17;
591 #[allow(rustc::usage_of_ty_tykind)]
592 pub struct TyS<'tcx> {
593 pub kind: TyKind<'tcx>,
594 pub flags: TypeFlags,
596 /// This is a kind of confusing thing: it stores the smallest
599 /// (a) the binder itself captures nothing but
600 /// (b) all the late-bound things within the type are captured
601 /// by some sub-binder.
603 /// So, for a type without any late-bound things, like `u32`, this
604 /// will be *innermost*, because that is the innermost binder that
605 /// captures nothing. But for a type `&'D u32`, where `'D` is a
606 /// late-bound region with De Bruijn index `D`, this would be `D + 1`
607 /// -- the binder itself does not capture `D`, but `D` is captured
608 /// by an inner binder.
610 /// We call this concept an "exclusive" binder `D` because all
611 /// De Bruijn indices within the type are contained within `0..D`
613 outer_exclusive_binder: ty::DebruijnIndex,
616 // `TyS` is used a lot. Make sure it doesn't unintentionally get bigger.
617 #[cfg(target_arch = "x86_64")]
618 static_assert_size!(TyS<'_>, 32);
620 impl<'tcx> Ord for TyS<'tcx> {
621 fn cmp(&self, other: &TyS<'tcx>) -> Ordering {
622 self.kind.cmp(&other.kind)
626 impl<'tcx> PartialOrd for TyS<'tcx> {
627 fn partial_cmp(&self, other: &TyS<'tcx>) -> Option<Ordering> {
628 Some(self.kind.cmp(&other.kind))
632 impl<'tcx> PartialEq for TyS<'tcx> {
634 fn eq(&self, other: &TyS<'tcx>) -> bool {
638 impl<'tcx> Eq for TyS<'tcx> {}
640 impl<'tcx> Hash for TyS<'tcx> {
641 fn hash<H: Hasher>(&self, s: &mut H) {
642 (self as *const TyS<'_>).hash(s)
646 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for ty::TyS<'tcx> {
647 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
651 // The other fields just provide fast access to information that is
652 // also contained in `kind`, so no need to hash them.
655 outer_exclusive_binder: _,
658 kind.hash_stable(hcx, hasher);
662 #[rustc_diagnostic_item = "Ty"]
663 pub type Ty<'tcx> = &'tcx TyS<'tcx>;
665 impl<'tcx> rustc_serialize::UseSpecializedEncodable for Ty<'tcx> {}
666 impl<'tcx> rustc_serialize::UseSpecializedDecodable for Ty<'tcx> {}
668 pub type CanonicalTy<'tcx> = Canonical<'tcx, Ty<'tcx>>;
671 /// A dummy type used to force `List` to be unsized while not requiring references to it be wide
673 type OpaqueListContents;
676 /// A wrapper for slices with the additional invariant
677 /// that the slice is interned and no other slice with
678 /// the same contents can exist in the same context.
679 /// This means we can use pointer for both
680 /// equality comparisons and hashing.
681 /// Note: `Slice` was already taken by the `Ty`.
686 opaque: OpaqueListContents,
689 unsafe impl<T: Sync> Sync for List<T> {}
691 impl<T: Copy> List<T> {
693 fn from_arena<'tcx>(arena: &'tcx Arena<'tcx>, slice: &[T]) -> &'tcx List<T> {
694 assert!(!mem::needs_drop::<T>());
695 assert!(mem::size_of::<T>() != 0);
696 assert!(!slice.is_empty());
698 // Align up the size of the len (usize) field
699 let align = mem::align_of::<T>();
700 let align_mask = align - 1;
701 let offset = mem::size_of::<usize>();
702 let offset = (offset + align_mask) & !align_mask;
704 let size = offset + slice.len() * mem::size_of::<T>();
708 .alloc_raw(size, cmp::max(mem::align_of::<T>(), mem::align_of::<usize>()));
710 let result = &mut *(mem.as_mut_ptr() as *mut List<T>);
712 result.len = slice.len();
714 // Write the elements
715 let arena_slice = slice::from_raw_parts_mut(result.data.as_mut_ptr(), result.len);
716 arena_slice.copy_from_slice(slice);
723 impl<T: fmt::Debug> fmt::Debug for List<T> {
724 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
729 impl<T: Encodable> Encodable for List<T> {
731 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
736 impl<T> Ord for List<T>
740 fn cmp(&self, other: &List<T>) -> Ordering {
741 if self == other { Ordering::Equal } else { <[T] as Ord>::cmp(&**self, &**other) }
745 impl<T> PartialOrd for List<T>
749 fn partial_cmp(&self, other: &List<T>) -> Option<Ordering> {
751 Some(Ordering::Equal)
753 <[T] as PartialOrd>::partial_cmp(&**self, &**other)
758 impl<T: PartialEq> PartialEq for List<T> {
760 fn eq(&self, other: &List<T>) -> bool {
764 impl<T: Eq> Eq for List<T> {}
766 impl<T> Hash for List<T> {
768 fn hash<H: Hasher>(&self, s: &mut H) {
769 (self as *const List<T>).hash(s)
773 impl<T> Deref for List<T> {
776 fn deref(&self) -> &[T] {
781 impl<T> AsRef<[T]> for List<T> {
783 fn as_ref(&self) -> &[T] {
784 unsafe { slice::from_raw_parts(self.data.as_ptr(), self.len) }
788 impl<'a, T> IntoIterator for &'a List<T> {
790 type IntoIter = <&'a [T] as IntoIterator>::IntoIter;
792 fn into_iter(self) -> Self::IntoIter {
797 impl<'tcx> rustc_serialize::UseSpecializedDecodable for &'tcx List<Ty<'tcx>> {}
801 pub fn empty<'a>() -> &'a List<T> {
802 #[repr(align(64), C)]
803 struct EmptySlice([u8; 64]);
804 static EMPTY_SLICE: EmptySlice = EmptySlice([0; 64]);
805 assert!(mem::align_of::<T>() <= 64);
806 unsafe { &*(&EMPTY_SLICE as *const _ as *const List<T>) }
810 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
811 pub struct UpvarPath {
812 pub hir_id: hir::HirId,
815 /// Upvars do not get their own `NodeId`. Instead, we use the pair of
816 /// the original var ID (that is, the root variable that is referenced
817 /// by the upvar) and the ID of the closure expression.
818 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
820 pub var_path: UpvarPath,
821 pub closure_expr_id: LocalDefId,
824 #[derive(Clone, PartialEq, Debug, RustcEncodable, RustcDecodable, Copy, HashStable)]
825 pub enum BorrowKind {
826 /// Data must be immutable and is aliasable.
829 /// Data must be immutable but not aliasable. This kind of borrow
830 /// cannot currently be expressed by the user and is used only in
831 /// implicit closure bindings. It is needed when the closure
832 /// is borrowing or mutating a mutable referent, e.g.:
834 /// let x: &mut isize = ...;
835 /// let y = || *x += 5;
837 /// If we were to try to translate this closure into a more explicit
838 /// form, we'd encounter an error with the code as written:
840 /// struct Env { x: & &mut isize }
841 /// let x: &mut isize = ...;
842 /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
843 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
845 /// This is then illegal because you cannot mutate a `&mut` found
846 /// in an aliasable location. To solve, you'd have to translate with
847 /// an `&mut` borrow:
849 /// struct Env { x: & &mut isize }
850 /// let x: &mut isize = ...;
851 /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
852 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
854 /// Now the assignment to `**env.x` is legal, but creating a
855 /// mutable pointer to `x` is not because `x` is not mutable. We
856 /// could fix this by declaring `x` as `let mut x`. This is ok in
857 /// user code, if awkward, but extra weird for closures, since the
858 /// borrow is hidden.
860 /// So we introduce a "unique imm" borrow -- the referent is
861 /// immutable, but not aliasable. This solves the problem. For
862 /// simplicity, we don't give users the way to express this
863 /// borrow, it's just used when translating closures.
866 /// Data is mutable and not aliasable.
870 /// Information describing the capture of an upvar. This is computed
871 /// during `typeck`, specifically by `regionck`.
872 #[derive(PartialEq, Clone, Debug, Copy, RustcEncodable, RustcDecodable, HashStable)]
873 pub enum UpvarCapture<'tcx> {
874 /// Upvar is captured by value. This is always true when the
875 /// closure is labeled `move`, but can also be true in other cases
876 /// depending on inference.
879 /// Upvar is captured by reference.
880 ByRef(UpvarBorrow<'tcx>),
883 #[derive(PartialEq, Clone, Copy, RustcEncodable, RustcDecodable, HashStable)]
884 pub struct UpvarBorrow<'tcx> {
885 /// The kind of borrow: by-ref upvars have access to shared
886 /// immutable borrows, which are not part of the normal language
888 pub kind: BorrowKind,
890 /// Region of the resulting reference.
891 pub region: ty::Region<'tcx>,
894 pub type UpvarListMap = FxHashMap<DefId, FxIndexMap<hir::HirId, UpvarId>>;
895 pub type UpvarCaptureMap<'tcx> = FxHashMap<UpvarId, UpvarCapture<'tcx>>;
897 #[derive(Clone, Copy, PartialEq, Eq)]
898 pub enum IntVarValue {
900 UintType(ast::UintTy),
903 #[derive(Clone, Copy, PartialEq, Eq)]
904 pub struct FloatVarValue(pub ast::FloatTy);
906 impl ty::EarlyBoundRegion {
907 pub fn to_bound_region(&self) -> ty::BoundRegion {
908 ty::BoundRegion::BrNamed(self.def_id, self.name)
911 /// Does this early bound region have a name? Early bound regions normally
912 /// always have names except when using anonymous lifetimes (`'_`).
913 pub fn has_name(&self) -> bool {
914 self.name != kw::UnderscoreLifetime
918 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
919 pub enum GenericParamDefKind {
923 object_lifetime_default: ObjectLifetimeDefault,
924 synthetic: Option<hir::SyntheticTyParamKind>,
929 impl GenericParamDefKind {
930 pub fn descr(&self) -> &'static str {
932 GenericParamDefKind::Lifetime => "lifetime",
933 GenericParamDefKind::Type { .. } => "type",
934 GenericParamDefKind::Const => "constant",
939 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
940 pub struct GenericParamDef {
945 /// `pure_wrt_drop`, set by the (unsafe) `#[may_dangle]` attribute
946 /// on generic parameter `'a`/`T`, asserts data behind the parameter
947 /// `'a`/`T` won't be accessed during the parent type's `Drop` impl.
948 pub pure_wrt_drop: bool,
950 pub kind: GenericParamDefKind,
953 impl GenericParamDef {
954 pub fn to_early_bound_region_data(&self) -> ty::EarlyBoundRegion {
955 if let GenericParamDefKind::Lifetime = self.kind {
956 ty::EarlyBoundRegion { def_id: self.def_id, index: self.index, name: self.name }
958 bug!("cannot convert a non-lifetime parameter def to an early bound region")
962 pub fn to_bound_region(&self) -> ty::BoundRegion {
963 if let GenericParamDefKind::Lifetime = self.kind {
964 self.to_early_bound_region_data().to_bound_region()
966 bug!("cannot convert a non-lifetime parameter def to an early bound region")
972 pub struct GenericParamCount {
973 pub lifetimes: usize,
978 /// Information about the formal type/lifetime parameters associated
979 /// with an item or method. Analogous to `hir::Generics`.
981 /// The ordering of parameters is the same as in `Subst` (excluding child generics):
982 /// `Self` (optionally), `Lifetime` params..., `Type` params...
983 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
984 pub struct Generics {
985 pub parent: Option<DefId>,
986 pub parent_count: usize,
987 pub params: Vec<GenericParamDef>,
989 /// Reverse map to the `index` field of each `GenericParamDef`.
990 #[stable_hasher(ignore)]
991 pub param_def_id_to_index: FxHashMap<DefId, u32>,
994 pub has_late_bound_regions: Option<Span>,
997 impl<'tcx> Generics {
998 pub fn count(&self) -> usize {
999 self.parent_count + self.params.len()
1002 pub fn own_counts(&self) -> GenericParamCount {
1003 // We could cache this as a property of `GenericParamCount`, but
1004 // the aim is to refactor this away entirely eventually and the
1005 // presence of this method will be a constant reminder.
1006 let mut own_counts: GenericParamCount = Default::default();
1008 for param in &self.params {
1010 GenericParamDefKind::Lifetime => own_counts.lifetimes += 1,
1011 GenericParamDefKind::Type { .. } => own_counts.types += 1,
1012 GenericParamDefKind::Const => own_counts.consts += 1,
1019 pub fn requires_monomorphization(&self, tcx: TyCtxt<'tcx>) -> bool {
1020 if self.own_requires_monomorphization() {
1024 if let Some(parent_def_id) = self.parent {
1025 let parent = tcx.generics_of(parent_def_id);
1026 parent.requires_monomorphization(tcx)
1032 pub fn own_requires_monomorphization(&self) -> bool {
1033 for param in &self.params {
1035 GenericParamDefKind::Type { .. } | GenericParamDefKind::Const => return true,
1036 GenericParamDefKind::Lifetime => {}
1042 pub fn param_at(&'tcx self, param_index: usize, tcx: TyCtxt<'tcx>) -> &'tcx GenericParamDef {
1043 if let Some(index) = param_index.checked_sub(self.parent_count) {
1046 tcx.generics_of(self.parent.expect("parent_count > 0 but no parent?"))
1047 .param_at(param_index, tcx)
1051 pub fn region_param(
1053 param: &EarlyBoundRegion,
1055 ) -> &'tcx GenericParamDef {
1056 let param = self.param_at(param.index as usize, tcx);
1058 GenericParamDefKind::Lifetime => param,
1059 _ => bug!("expected lifetime parameter, but found another generic parameter"),
1063 /// Returns the `GenericParamDef` associated with this `ParamTy`.
1064 pub fn type_param(&'tcx self, param: &ParamTy, tcx: TyCtxt<'tcx>) -> &'tcx GenericParamDef {
1065 let param = self.param_at(param.index as usize, tcx);
1067 GenericParamDefKind::Type { .. } => param,
1068 _ => bug!("expected type parameter, but found another generic parameter"),
1072 /// Returns the `ConstParameterDef` associated with this `ParamConst`.
1073 pub fn const_param(&'tcx self, param: &ParamConst, tcx: TyCtxt<'tcx>) -> &GenericParamDef {
1074 let param = self.param_at(param.index as usize, tcx);
1076 GenericParamDefKind::Const => param,
1077 _ => bug!("expected const parameter, but found another generic parameter"),
1082 /// Bounds on generics.
1083 #[derive(Copy, Clone, Default, Debug, RustcEncodable, RustcDecodable, HashStable)]
1084 pub struct GenericPredicates<'tcx> {
1085 pub parent: Option<DefId>,
1086 pub predicates: &'tcx [(Predicate<'tcx>, Span)],
1089 impl<'tcx> GenericPredicates<'tcx> {
1093 substs: SubstsRef<'tcx>,
1094 ) -> InstantiatedPredicates<'tcx> {
1095 let mut instantiated = InstantiatedPredicates::empty();
1096 self.instantiate_into(tcx, &mut instantiated, substs);
1100 pub fn instantiate_own(
1103 substs: SubstsRef<'tcx>,
1104 ) -> InstantiatedPredicates<'tcx> {
1105 InstantiatedPredicates {
1106 predicates: self.predicates.iter().map(|(p, _)| p.subst(tcx, substs)).collect(),
1107 spans: self.predicates.iter().map(|(_, sp)| *sp).collect(),
1111 fn instantiate_into(
1114 instantiated: &mut InstantiatedPredicates<'tcx>,
1115 substs: SubstsRef<'tcx>,
1117 if let Some(def_id) = self.parent {
1118 tcx.predicates_of(def_id).instantiate_into(tcx, instantiated, substs);
1120 instantiated.predicates.extend(self.predicates.iter().map(|(p, _)| p.subst(tcx, substs)));
1121 instantiated.spans.extend(self.predicates.iter().map(|(_, sp)| *sp));
1124 pub fn instantiate_identity(&self, tcx: TyCtxt<'tcx>) -> InstantiatedPredicates<'tcx> {
1125 let mut instantiated = InstantiatedPredicates::empty();
1126 self.instantiate_identity_into(tcx, &mut instantiated);
1130 fn instantiate_identity_into(
1133 instantiated: &mut InstantiatedPredicates<'tcx>,
1135 if let Some(def_id) = self.parent {
1136 tcx.predicates_of(def_id).instantiate_identity_into(tcx, instantiated);
1138 instantiated.predicates.extend(self.predicates.iter().map(|(p, _)| p));
1139 instantiated.spans.extend(self.predicates.iter().map(|(_, s)| s));
1142 pub fn instantiate_supertrait(
1145 poly_trait_ref: &ty::PolyTraitRef<'tcx>,
1146 ) -> InstantiatedPredicates<'tcx> {
1147 assert_eq!(self.parent, None);
1148 InstantiatedPredicates {
1152 .map(|(pred, _)| pred.subst_supertrait(tcx, poly_trait_ref))
1154 spans: self.predicates.iter().map(|(_, sp)| *sp).collect(),
1159 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1160 #[derive(HashStable, TypeFoldable)]
1161 pub enum Predicate<'tcx> {
1162 /// Corresponds to `where Foo: Bar<A, B, C>`. `Foo` here would be
1163 /// the `Self` type of the trait reference and `A`, `B`, and `C`
1164 /// would be the type parameters.
1166 /// A trait predicate will have `Constness::Const` if it originates
1167 /// from a bound on a `const fn` without the `?const` opt-out (e.g.,
1168 /// `const fn foobar<Foo: Bar>() {}`).
1169 Trait(PolyTraitPredicate<'tcx>, Constness),
1172 RegionOutlives(PolyRegionOutlivesPredicate<'tcx>),
1175 TypeOutlives(PolyTypeOutlivesPredicate<'tcx>),
1177 /// `where <T as TraitRef>::Name == X`, approximately.
1178 /// See the `ProjectionPredicate` struct for details.
1179 Projection(PolyProjectionPredicate<'tcx>),
1181 /// No syntax: `T` well-formed.
1182 WellFormed(Ty<'tcx>),
1184 /// Trait must be object-safe.
1187 /// No direct syntax. May be thought of as `where T: FnFoo<...>`
1188 /// for some substitutions `...` and `T` being a closure type.
1189 /// Satisfied (or refuted) once we know the closure's kind.
1190 ClosureKind(DefId, SubstsRef<'tcx>, ClosureKind),
1193 Subtype(PolySubtypePredicate<'tcx>),
1195 /// Constant initializer must evaluate successfully.
1196 ConstEvaluatable(DefId, SubstsRef<'tcx>),
1199 /// The crate outlives map is computed during typeck and contains the
1200 /// outlives of every item in the local crate. You should not use it
1201 /// directly, because to do so will make your pass dependent on the
1202 /// HIR of every item in the local crate. Instead, use
1203 /// `tcx.inferred_outlives_of()` to get the outlives for a *particular*
1205 #[derive(HashStable)]
1206 pub struct CratePredicatesMap<'tcx> {
1207 /// For each struct with outlive bounds, maps to a vector of the
1208 /// predicate of its outlive bounds. If an item has no outlives
1209 /// bounds, it will have no entry.
1210 pub predicates: FxHashMap<DefId, &'tcx [(ty::Predicate<'tcx>, Span)]>,
1213 impl<'tcx> AsRef<Predicate<'tcx>> for Predicate<'tcx> {
1214 fn as_ref(&self) -> &Predicate<'tcx> {
1219 impl<'tcx> Predicate<'tcx> {
1220 /// Performs a substitution suitable for going from a
1221 /// poly-trait-ref to supertraits that must hold if that
1222 /// poly-trait-ref holds. This is slightly different from a normal
1223 /// substitution in terms of what happens with bound regions. See
1224 /// lengthy comment below for details.
1225 pub fn subst_supertrait(
1228 trait_ref: &ty::PolyTraitRef<'tcx>,
1229 ) -> ty::Predicate<'tcx> {
1230 // The interaction between HRTB and supertraits is not entirely
1231 // obvious. Let me walk you (and myself) through an example.
1233 // Let's start with an easy case. Consider two traits:
1235 // trait Foo<'a>: Bar<'a,'a> { }
1236 // trait Bar<'b,'c> { }
1238 // Now, if we have a trait reference `for<'x> T: Foo<'x>`, then
1239 // we can deduce that `for<'x> T: Bar<'x,'x>`. Basically, if we
1240 // knew that `Foo<'x>` (for any 'x) then we also know that
1241 // `Bar<'x,'x>` (for any 'x). This more-or-less falls out from
1242 // normal substitution.
1244 // In terms of why this is sound, the idea is that whenever there
1245 // is an impl of `T:Foo<'a>`, it must show that `T:Bar<'a,'a>`
1246 // holds. So if there is an impl of `T:Foo<'a>` that applies to
1247 // all `'a`, then we must know that `T:Bar<'a,'a>` holds for all
1250 // Another example to be careful of is this:
1252 // trait Foo1<'a>: for<'b> Bar1<'a,'b> { }
1253 // trait Bar1<'b,'c> { }
1255 // Here, if we have `for<'x> T: Foo1<'x>`, then what do we know?
1256 // The answer is that we know `for<'x,'b> T: Bar1<'x,'b>`. The
1257 // reason is similar to the previous example: any impl of
1258 // `T:Foo1<'x>` must show that `for<'b> T: Bar1<'x, 'b>`. So
1259 // basically we would want to collapse the bound lifetimes from
1260 // the input (`trait_ref`) and the supertraits.
1262 // To achieve this in practice is fairly straightforward. Let's
1263 // consider the more complicated scenario:
1265 // - We start out with `for<'x> T: Foo1<'x>`. In this case, `'x`
1266 // has a De Bruijn index of 1. We want to produce `for<'x,'b> T: Bar1<'x,'b>`,
1267 // where both `'x` and `'b` would have a DB index of 1.
1268 // The substitution from the input trait-ref is therefore going to be
1269 // `'a => 'x` (where `'x` has a DB index of 1).
1270 // - The super-trait-ref is `for<'b> Bar1<'a,'b>`, where `'a` is an
1271 // early-bound parameter and `'b' is a late-bound parameter with a
1273 // - If we replace `'a` with `'x` from the input, it too will have
1274 // a DB index of 1, and thus we'll have `for<'x,'b> Bar1<'x,'b>`
1275 // just as we wanted.
1277 // There is only one catch. If we just apply the substitution `'a
1278 // => 'x` to `for<'b> Bar1<'a,'b>`, the substitution code will
1279 // adjust the DB index because we substituting into a binder (it
1280 // tries to be so smart...) resulting in `for<'x> for<'b>
1281 // Bar1<'x,'b>` (we have no syntax for this, so use your
1282 // imagination). Basically the 'x will have DB index of 2 and 'b
1283 // will have DB index of 1. Not quite what we want. So we apply
1284 // the substitution to the *contents* of the trait reference,
1285 // rather than the trait reference itself (put another way, the
1286 // substitution code expects equal binding levels in the values
1287 // from the substitution and the value being substituted into, and
1288 // this trick achieves that).
1290 let substs = &trait_ref.skip_binder().substs;
1292 Predicate::Trait(ref binder, constness) => {
1293 Predicate::Trait(binder.map_bound(|data| data.subst(tcx, substs)), constness)
1295 Predicate::Subtype(ref binder) => {
1296 Predicate::Subtype(binder.map_bound(|data| data.subst(tcx, substs)))
1298 Predicate::RegionOutlives(ref binder) => {
1299 Predicate::RegionOutlives(binder.map_bound(|data| data.subst(tcx, substs)))
1301 Predicate::TypeOutlives(ref binder) => {
1302 Predicate::TypeOutlives(binder.map_bound(|data| data.subst(tcx, substs)))
1304 Predicate::Projection(ref binder) => {
1305 Predicate::Projection(binder.map_bound(|data| data.subst(tcx, substs)))
1307 Predicate::WellFormed(data) => Predicate::WellFormed(data.subst(tcx, substs)),
1308 Predicate::ObjectSafe(trait_def_id) => Predicate::ObjectSafe(trait_def_id),
1309 Predicate::ClosureKind(closure_def_id, closure_substs, kind) => {
1310 Predicate::ClosureKind(closure_def_id, closure_substs.subst(tcx, substs), kind)
1312 Predicate::ConstEvaluatable(def_id, const_substs) => {
1313 Predicate::ConstEvaluatable(def_id, const_substs.subst(tcx, substs))
1319 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1320 #[derive(HashStable, TypeFoldable)]
1321 pub struct TraitPredicate<'tcx> {
1322 pub trait_ref: TraitRef<'tcx>,
1325 pub type PolyTraitPredicate<'tcx> = ty::Binder<TraitPredicate<'tcx>>;
1327 impl<'tcx> TraitPredicate<'tcx> {
1328 pub fn def_id(&self) -> DefId {
1329 self.trait_ref.def_id
1332 pub fn self_ty(&self) -> Ty<'tcx> {
1333 self.trait_ref.self_ty()
1337 impl<'tcx> PolyTraitPredicate<'tcx> {
1338 pub fn def_id(&self) -> DefId {
1339 // Ok to skip binder since trait `DefId` does not care about regions.
1340 self.skip_binder().def_id()
1344 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, RustcEncodable, RustcDecodable)]
1345 #[derive(HashStable, TypeFoldable)]
1346 pub struct OutlivesPredicate<A, B>(pub A, pub B); // `A: B`
1347 pub type PolyOutlivesPredicate<A, B> = ty::Binder<OutlivesPredicate<A, B>>;
1348 pub type RegionOutlivesPredicate<'tcx> = OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>;
1349 pub type TypeOutlivesPredicate<'tcx> = OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>;
1350 pub type PolyRegionOutlivesPredicate<'tcx> = ty::Binder<RegionOutlivesPredicate<'tcx>>;
1351 pub type PolyTypeOutlivesPredicate<'tcx> = ty::Binder<TypeOutlivesPredicate<'tcx>>;
1353 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
1354 #[derive(HashStable, TypeFoldable)]
1355 pub struct SubtypePredicate<'tcx> {
1356 pub a_is_expected: bool,
1360 pub type PolySubtypePredicate<'tcx> = ty::Binder<SubtypePredicate<'tcx>>;
1362 /// This kind of predicate has no *direct* correspondent in the
1363 /// syntax, but it roughly corresponds to the syntactic forms:
1365 /// 1. `T: TraitRef<..., Item = Type>`
1366 /// 2. `<T as TraitRef<...>>::Item == Type` (NYI)
1368 /// In particular, form #1 is "desugared" to the combination of a
1369 /// normal trait predicate (`T: TraitRef<...>`) and one of these
1370 /// predicates. Form #2 is a broader form in that it also permits
1371 /// equality between arbitrary types. Processing an instance of
1372 /// Form #2 eventually yields one of these `ProjectionPredicate`
1373 /// instances to normalize the LHS.
1374 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1375 #[derive(HashStable, TypeFoldable)]
1376 pub struct ProjectionPredicate<'tcx> {
1377 pub projection_ty: ProjectionTy<'tcx>,
1381 pub type PolyProjectionPredicate<'tcx> = Binder<ProjectionPredicate<'tcx>>;
1383 impl<'tcx> PolyProjectionPredicate<'tcx> {
1384 /// Returns the `DefId` of the associated item being projected.
1385 pub fn item_def_id(&self) -> DefId {
1386 self.skip_binder().projection_ty.item_def_id
1390 pub fn to_poly_trait_ref(&self, tcx: TyCtxt<'tcx>) -> PolyTraitRef<'tcx> {
1391 // Note: unlike with `TraitRef::to_poly_trait_ref()`,
1392 // `self.0.trait_ref` is permitted to have escaping regions.
1393 // This is because here `self` has a `Binder` and so does our
1394 // return value, so we are preserving the number of binding
1396 self.map_bound(|predicate| predicate.projection_ty.trait_ref(tcx))
1399 pub fn ty(&self) -> Binder<Ty<'tcx>> {
1400 self.map_bound(|predicate| predicate.ty)
1403 /// The `DefId` of the `TraitItem` for the associated type.
1405 /// Note that this is not the `DefId` of the `TraitRef` containing this
1406 /// associated type, which is in `tcx.associated_item(projection_def_id()).container`.
1407 pub fn projection_def_id(&self) -> DefId {
1408 // Ok to skip binder since trait `DefId` does not care about regions.
1409 self.skip_binder().projection_ty.item_def_id
1413 pub trait ToPolyTraitRef<'tcx> {
1414 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx>;
1417 impl<'tcx> ToPolyTraitRef<'tcx> for TraitRef<'tcx> {
1418 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
1419 ty::Binder::dummy(*self)
1423 impl<'tcx> ToPolyTraitRef<'tcx> for PolyTraitPredicate<'tcx> {
1424 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
1425 self.map_bound_ref(|trait_pred| trait_pred.trait_ref)
1429 pub trait ToPredicate<'tcx> {
1430 fn to_predicate(&self) -> Predicate<'tcx>;
1433 impl<'tcx> ToPredicate<'tcx> for ConstnessAnd<TraitRef<'tcx>> {
1434 fn to_predicate(&self) -> Predicate<'tcx> {
1435 ty::Predicate::Trait(
1436 ty::Binder::dummy(ty::TraitPredicate { trait_ref: self.value }),
1442 impl<'tcx> ToPredicate<'tcx> for ConstnessAnd<&TraitRef<'tcx>> {
1443 fn to_predicate(&self) -> Predicate<'tcx> {
1444 ty::Predicate::Trait(
1445 ty::Binder::dummy(ty::TraitPredicate { trait_ref: *self.value }),
1451 impl<'tcx> ToPredicate<'tcx> for ConstnessAnd<PolyTraitRef<'tcx>> {
1452 fn to_predicate(&self) -> Predicate<'tcx> {
1453 ty::Predicate::Trait(self.value.to_poly_trait_predicate(), self.constness)
1457 impl<'tcx> ToPredicate<'tcx> for ConstnessAnd<&PolyTraitRef<'tcx>> {
1458 fn to_predicate(&self) -> Predicate<'tcx> {
1459 ty::Predicate::Trait(self.value.to_poly_trait_predicate(), self.constness)
1463 impl<'tcx> ToPredicate<'tcx> for PolyRegionOutlivesPredicate<'tcx> {
1464 fn to_predicate(&self) -> Predicate<'tcx> {
1465 Predicate::RegionOutlives(*self)
1469 impl<'tcx> ToPredicate<'tcx> for PolyTypeOutlivesPredicate<'tcx> {
1470 fn to_predicate(&self) -> Predicate<'tcx> {
1471 Predicate::TypeOutlives(*self)
1475 impl<'tcx> ToPredicate<'tcx> for PolyProjectionPredicate<'tcx> {
1476 fn to_predicate(&self) -> Predicate<'tcx> {
1477 Predicate::Projection(*self)
1481 impl<'tcx> Predicate<'tcx> {
1482 pub fn to_opt_poly_trait_ref(&self) -> Option<PolyTraitRef<'tcx>> {
1484 Predicate::Trait(ref t, _) => Some(t.to_poly_trait_ref()),
1485 Predicate::Projection(..)
1486 | Predicate::Subtype(..)
1487 | Predicate::RegionOutlives(..)
1488 | Predicate::WellFormed(..)
1489 | Predicate::ObjectSafe(..)
1490 | Predicate::ClosureKind(..)
1491 | Predicate::TypeOutlives(..)
1492 | Predicate::ConstEvaluatable(..) => None,
1496 pub fn to_opt_type_outlives(&self) -> Option<PolyTypeOutlivesPredicate<'tcx>> {
1498 Predicate::TypeOutlives(data) => Some(data),
1499 Predicate::Trait(..)
1500 | Predicate::Projection(..)
1501 | Predicate::Subtype(..)
1502 | Predicate::RegionOutlives(..)
1503 | Predicate::WellFormed(..)
1504 | Predicate::ObjectSafe(..)
1505 | Predicate::ClosureKind(..)
1506 | Predicate::ConstEvaluatable(..) => None,
1511 /// Represents the bounds declared on a particular set of type
1512 /// parameters. Should eventually be generalized into a flag list of
1513 /// where-clauses. You can obtain a `InstantiatedPredicates` list from a
1514 /// `GenericPredicates` by using the `instantiate` method. Note that this method
1515 /// reflects an important semantic invariant of `InstantiatedPredicates`: while
1516 /// the `GenericPredicates` are expressed in terms of the bound type
1517 /// parameters of the impl/trait/whatever, an `InstantiatedPredicates` instance
1518 /// represented a set of bounds for some particular instantiation,
1519 /// meaning that the generic parameters have been substituted with
1524 /// struct Foo<T, U: Bar<T>> { ... }
1526 /// Here, the `GenericPredicates` for `Foo` would contain a list of bounds like
1527 /// `[[], [U:Bar<T>]]`. Now if there were some particular reference
1528 /// like `Foo<isize,usize>`, then the `InstantiatedPredicates` would be `[[],
1529 /// [usize:Bar<isize>]]`.
1530 #[derive(Clone, Debug, TypeFoldable)]
1531 pub struct InstantiatedPredicates<'tcx> {
1532 pub predicates: Vec<Predicate<'tcx>>,
1533 pub spans: Vec<Span>,
1536 impl<'tcx> InstantiatedPredicates<'tcx> {
1537 pub fn empty() -> InstantiatedPredicates<'tcx> {
1538 InstantiatedPredicates { predicates: vec![], spans: vec![] }
1541 pub fn is_empty(&self) -> bool {
1542 self.predicates.is_empty()
1546 rustc_index::newtype_index! {
1547 /// "Universes" are used during type- and trait-checking in the
1548 /// presence of `for<..>` binders to control what sets of names are
1549 /// visible. Universes are arranged into a tree: the root universe
1550 /// contains names that are always visible. Each child then adds a new
1551 /// set of names that are visible, in addition to those of its parent.
1552 /// We say that the child universe "extends" the parent universe with
1555 /// To make this more concrete, consider this program:
1559 /// fn bar<T>(x: T) {
1560 /// let y: for<'a> fn(&'a u8, Foo) = ...;
1564 /// The struct name `Foo` is in the root universe U0. But the type
1565 /// parameter `T`, introduced on `bar`, is in an extended universe U1
1566 /// -- i.e., within `bar`, we can name both `T` and `Foo`, but outside
1567 /// of `bar`, we cannot name `T`. Then, within the type of `y`, the
1568 /// region `'a` is in a universe U2 that extends U1, because we can
1569 /// name it inside the fn type but not outside.
1571 /// Universes are used to do type- and trait-checking around these
1572 /// "forall" binders (also called **universal quantification**). The
1573 /// idea is that when, in the body of `bar`, we refer to `T` as a
1574 /// type, we aren't referring to any type in particular, but rather a
1575 /// kind of "fresh" type that is distinct from all other types we have
1576 /// actually declared. This is called a **placeholder** type, and we
1577 /// use universes to talk about this. In other words, a type name in
1578 /// universe 0 always corresponds to some "ground" type that the user
1579 /// declared, but a type name in a non-zero universe is a placeholder
1580 /// type -- an idealized representative of "types in general" that we
1581 /// use for checking generic functions.
1582 pub struct UniverseIndex {
1584 DEBUG_FORMAT = "U{}",
1588 impl UniverseIndex {
1589 pub const ROOT: UniverseIndex = UniverseIndex::from_u32(0);
1591 /// Returns the "next" universe index in order -- this new index
1592 /// is considered to extend all previous universes. This
1593 /// corresponds to entering a `forall` quantifier. So, for
1594 /// example, suppose we have this type in universe `U`:
1597 /// for<'a> fn(&'a u32)
1600 /// Once we "enter" into this `for<'a>` quantifier, we are in a
1601 /// new universe that extends `U` -- in this new universe, we can
1602 /// name the region `'a`, but that region was not nameable from
1603 /// `U` because it was not in scope there.
1604 pub fn next_universe(self) -> UniverseIndex {
1605 UniverseIndex::from_u32(self.private.checked_add(1).unwrap())
1608 /// Returns `true` if `self` can name a name from `other` -- in other words,
1609 /// if the set of names in `self` is a superset of those in
1610 /// `other` (`self >= other`).
1611 pub fn can_name(self, other: UniverseIndex) -> bool {
1612 self.private >= other.private
1615 /// Returns `true` if `self` cannot name some names from `other` -- in other
1616 /// words, if the set of names in `self` is a strict subset of
1617 /// those in `other` (`self < other`).
1618 pub fn cannot_name(self, other: UniverseIndex) -> bool {
1619 self.private < other.private
1623 /// The "placeholder index" fully defines a placeholder region.
1624 /// Placeholder regions are identified by both a **universe** as well
1625 /// as a "bound-region" within that universe. The `bound_region` is
1626 /// basically a name -- distinct bound regions within the same
1627 /// universe are just two regions with an unknown relationship to one
1629 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, PartialOrd, Ord)]
1630 pub struct Placeholder<T> {
1631 pub universe: UniverseIndex,
1635 impl<'a, T> HashStable<StableHashingContext<'a>> for Placeholder<T>
1637 T: HashStable<StableHashingContext<'a>>,
1639 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
1640 self.universe.hash_stable(hcx, hasher);
1641 self.name.hash_stable(hcx, hasher);
1645 pub type PlaceholderRegion = Placeholder<BoundRegion>;
1647 pub type PlaceholderType = Placeholder<BoundVar>;
1649 pub type PlaceholderConst = Placeholder<BoundVar>;
1651 /// When type checking, we use the `ParamEnv` to track
1652 /// details about the set of where-clauses that are in scope at this
1653 /// particular point.
1654 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable, TypeFoldable)]
1655 pub struct ParamEnv<'tcx> {
1656 /// `Obligation`s that the caller must satisfy. This is basically
1657 /// the set of bounds on the in-scope type parameters, translated
1658 /// into `Obligation`s, and elaborated and normalized.
1659 pub caller_bounds: &'tcx List<ty::Predicate<'tcx>>,
1661 /// Typically, this is `Reveal::UserFacing`, but during codegen we
1662 /// want `Reveal::All` -- note that this is always paired with an
1663 /// empty environment. To get that, use `ParamEnv::reveal()`.
1664 pub reveal: traits::Reveal,
1666 /// If this `ParamEnv` comes from a call to `tcx.param_env(def_id)`,
1667 /// register that `def_id` (useful for transitioning to the chalk trait
1669 pub def_id: Option<DefId>,
1672 impl<'tcx> ParamEnv<'tcx> {
1673 /// Construct a trait environment suitable for contexts where
1674 /// there are no where-clauses in scope. Hidden types (like `impl
1675 /// Trait`) are left hidden, so this is suitable for ordinary
1678 pub fn empty() -> Self {
1679 Self::new(List::empty(), Reveal::UserFacing, None)
1682 /// Construct a trait environment with no where-clauses in scope
1683 /// where the values of all `impl Trait` and other hidden types
1684 /// are revealed. This is suitable for monomorphized, post-typeck
1685 /// environments like codegen or doing optimizations.
1687 /// N.B., if you want to have predicates in scope, use `ParamEnv::new`,
1688 /// or invoke `param_env.with_reveal_all()`.
1690 pub fn reveal_all() -> Self {
1691 Self::new(List::empty(), Reveal::All, None)
1694 /// Construct a trait environment with the given set of predicates.
1697 caller_bounds: &'tcx List<ty::Predicate<'tcx>>,
1699 def_id: Option<DefId>,
1701 ty::ParamEnv { caller_bounds, reveal, def_id }
1704 /// Returns a new parameter environment with the same clauses, but
1705 /// which "reveals" the true results of projections in all cases
1706 /// (even for associated types that are specializable). This is
1707 /// the desired behavior during codegen and certain other special
1708 /// contexts; normally though we want to use `Reveal::UserFacing`,
1709 /// which is the default.
1710 pub fn with_reveal_all(self) -> Self {
1711 ty::ParamEnv { reveal: Reveal::All, ..self }
1714 /// Returns this same environment but with no caller bounds.
1715 pub fn without_caller_bounds(self) -> Self {
1716 ty::ParamEnv { caller_bounds: List::empty(), ..self }
1719 /// Creates a suitable environment in which to perform trait
1720 /// queries on the given value. When type-checking, this is simply
1721 /// the pair of the environment plus value. But when reveal is set to
1722 /// All, then if `value` does not reference any type parameters, we will
1723 /// pair it with the empty environment. This improves caching and is generally
1726 /// N.B., we preserve the environment when type-checking because it
1727 /// is possible for the user to have wacky where-clauses like
1728 /// `where Box<u32>: Copy`, which are clearly never
1729 /// satisfiable. We generally want to behave as if they were true,
1730 /// although the surrounding function is never reachable.
1731 pub fn and<T: TypeFoldable<'tcx>>(self, value: T) -> ParamEnvAnd<'tcx, T> {
1733 Reveal::UserFacing => ParamEnvAnd { param_env: self, value },
1736 if value.is_global() {
1737 ParamEnvAnd { param_env: self.without_caller_bounds(), value }
1739 ParamEnvAnd { param_env: self, value }
1746 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1747 pub struct ConstnessAnd<T> {
1748 pub constness: Constness,
1752 // FIXME(ecstaticmorse): Audit all occurrences of `without_const().to_predicate()` to ensure that
1753 // the constness of trait bounds is being propagated correctly.
1754 pub trait WithConstness: Sized {
1756 fn with_constness(self, constness: Constness) -> ConstnessAnd<Self> {
1757 ConstnessAnd { constness, value: self }
1761 fn with_const(self) -> ConstnessAnd<Self> {
1762 self.with_constness(Constness::Const)
1766 fn without_const(self) -> ConstnessAnd<Self> {
1767 self.with_constness(Constness::NotConst)
1771 impl<T> WithConstness for T {}
1773 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TypeFoldable)]
1774 pub struct ParamEnvAnd<'tcx, T> {
1775 pub param_env: ParamEnv<'tcx>,
1779 impl<'tcx, T> ParamEnvAnd<'tcx, T> {
1780 pub fn into_parts(self) -> (ParamEnv<'tcx>, T) {
1781 (self.param_env, self.value)
1785 impl<'a, 'tcx, T> HashStable<StableHashingContext<'a>> for ParamEnvAnd<'tcx, T>
1787 T: HashStable<StableHashingContext<'a>>,
1789 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
1790 let ParamEnvAnd { ref param_env, ref value } = *self;
1792 param_env.hash_stable(hcx, hasher);
1793 value.hash_stable(hcx, hasher);
1797 #[derive(Copy, Clone, Debug, HashStable)]
1798 pub struct Destructor {
1799 /// The `DefId` of the destructor method
1804 #[derive(HashStable)]
1805 pub struct AdtFlags: u32 {
1806 const NO_ADT_FLAGS = 0;
1807 /// Indicates whether the ADT is an enum.
1808 const IS_ENUM = 1 << 0;
1809 /// Indicates whether the ADT is a union.
1810 const IS_UNION = 1 << 1;
1811 /// Indicates whether the ADT is a struct.
1812 const IS_STRUCT = 1 << 2;
1813 /// Indicates whether the ADT is a struct and has a constructor.
1814 const HAS_CTOR = 1 << 3;
1815 /// Indicates whether the type is `PhantomData`.
1816 const IS_PHANTOM_DATA = 1 << 4;
1817 /// Indicates whether the type has a `#[fundamental]` attribute.
1818 const IS_FUNDAMENTAL = 1 << 5;
1819 /// Indicates whether the type is `Box`.
1820 const IS_BOX = 1 << 6;
1821 /// Indicates whether the type is `ManuallyDrop`.
1822 const IS_MANUALLY_DROP = 1 << 7;
1823 /// Indicates whether the variant list of this ADT is `#[non_exhaustive]`.
1824 /// (i.e., this flag is never set unless this ADT is an enum).
1825 const IS_VARIANT_LIST_NON_EXHAUSTIVE = 1 << 8;
1830 #[derive(HashStable)]
1831 pub struct VariantFlags: u32 {
1832 const NO_VARIANT_FLAGS = 0;
1833 /// Indicates whether the field list of this variant is `#[non_exhaustive]`.
1834 const IS_FIELD_LIST_NON_EXHAUSTIVE = 1 << 0;
1838 /// Definition of a variant -- a struct's fields or a enum variant.
1839 #[derive(Debug, HashStable)]
1840 pub struct VariantDef {
1841 /// `DefId` that identifies the variant itself.
1842 /// If this variant belongs to a struct or union, then this is a copy of its `DefId`.
1844 /// `DefId` that identifies the variant's constructor.
1845 /// If this variant is a struct variant, then this is `None`.
1846 pub ctor_def_id: Option<DefId>,
1847 /// Variant or struct name.
1848 #[stable_hasher(project(name))]
1850 /// Discriminant of this variant.
1851 pub discr: VariantDiscr,
1852 /// Fields of this variant.
1853 pub fields: Vec<FieldDef>,
1854 /// Type of constructor of variant.
1855 pub ctor_kind: CtorKind,
1856 /// Flags of the variant (e.g. is field list non-exhaustive)?
1857 flags: VariantFlags,
1858 /// Variant is obtained as part of recovering from a syntactic error.
1859 /// May be incomplete or bogus.
1860 pub recovered: bool,
1863 impl<'tcx> VariantDef {
1864 /// Creates a new `VariantDef`.
1866 /// `variant_did` is the `DefId` that identifies the enum variant (if this `VariantDef`
1867 /// represents an enum variant).
1869 /// `ctor_did` is the `DefId` that identifies the constructor of unit or
1870 /// tuple-variants/structs. If this is a `struct`-variant then this should be `None`.
1872 /// `parent_did` is the `DefId` of the `AdtDef` representing the enum or struct that
1873 /// owns this variant. It is used for checking if a struct has `#[non_exhaustive]` w/out having
1874 /// to go through the redirect of checking the ctor's attributes - but compiling a small crate
1875 /// requires loading the `AdtDef`s for all the structs in the universe (e.g., coherence for any
1876 /// built-in trait), and we do not want to load attributes twice.
1878 /// If someone speeds up attribute loading to not be a performance concern, they can
1879 /// remove this hack and use the constructor `DefId` everywhere.
1883 variant_did: Option<DefId>,
1884 ctor_def_id: Option<DefId>,
1885 discr: VariantDiscr,
1886 fields: Vec<FieldDef>,
1887 ctor_kind: CtorKind,
1893 "VariantDef::new(ident = {:?}, variant_did = {:?}, ctor_def_id = {:?}, discr = {:?},
1894 fields = {:?}, ctor_kind = {:?}, adt_kind = {:?}, parent_did = {:?})",
1895 ident, variant_did, ctor_def_id, discr, fields, ctor_kind, adt_kind, parent_did,
1898 let mut flags = VariantFlags::NO_VARIANT_FLAGS;
1899 if adt_kind == AdtKind::Struct && tcx.has_attr(parent_did, sym::non_exhaustive) {
1900 debug!("found non-exhaustive field list for {:?}", parent_did);
1901 flags = flags | VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE;
1902 } else if let Some(variant_did) = variant_did {
1903 if tcx.has_attr(variant_did, sym::non_exhaustive) {
1904 debug!("found non-exhaustive field list for {:?}", variant_did);
1905 flags = flags | VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE;
1910 def_id: variant_did.unwrap_or(parent_did),
1921 /// Is this field list non-exhaustive?
1923 pub fn is_field_list_non_exhaustive(&self) -> bool {
1924 self.flags.intersects(VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE)
1928 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
1929 pub enum VariantDiscr {
1930 /// Explicit value for this variant, i.e., `X = 123`.
1931 /// The `DefId` corresponds to the embedded constant.
1934 /// The previous variant's discriminant plus one.
1935 /// For efficiency reasons, the distance from the
1936 /// last `Explicit` discriminant is being stored,
1937 /// or `0` for the first variant, if it has none.
1941 #[derive(Debug, HashStable)]
1942 pub struct FieldDef {
1944 #[stable_hasher(project(name))]
1946 pub vis: Visibility,
1949 /// The definition of a user-defined type, e.g., a `struct`, `enum`, or `union`.
1951 /// These are all interned (by `intern_adt_def`) into the `adt_defs` table.
1953 /// The initialism *ADT* stands for an [*algebraic data type (ADT)*][adt].
1954 /// This is slightly wrong because `union`s are not ADTs.
1955 /// Moreover, Rust only allows recursive data types through indirection.
1957 /// [adt]: https://en.wikipedia.org/wiki/Algebraic_data_type
1959 /// The `DefId` of the struct, enum or union item.
1961 /// Variants of the ADT. If this is a struct or union, then there will be a single variant.
1962 pub variants: IndexVec<VariantIdx, VariantDef>,
1963 /// Flags of the ADT (e.g., is this a struct? is this non-exhaustive?).
1965 /// Repr options provided by the user.
1966 pub repr: ReprOptions,
1969 impl PartialOrd for AdtDef {
1970 fn partial_cmp(&self, other: &AdtDef) -> Option<Ordering> {
1971 Some(self.cmp(&other))
1975 /// There should be only one AdtDef for each `did`, therefore
1976 /// it is fine to implement `Ord` only based on `did`.
1977 impl Ord for AdtDef {
1978 fn cmp(&self, other: &AdtDef) -> Ordering {
1979 self.did.cmp(&other.did)
1983 impl PartialEq for AdtDef {
1984 // `AdtDef`s are always interned, and this is part of `TyS` equality.
1986 fn eq(&self, other: &Self) -> bool {
1987 ptr::eq(self, other)
1991 impl Eq for AdtDef {}
1993 impl Hash for AdtDef {
1995 fn hash<H: Hasher>(&self, s: &mut H) {
1996 (self as *const AdtDef).hash(s)
2000 impl<'tcx> rustc_serialize::UseSpecializedEncodable for &'tcx AdtDef {
2001 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
2006 impl<'tcx> rustc_serialize::UseSpecializedDecodable for &'tcx AdtDef {}
2008 impl<'a> HashStable<StableHashingContext<'a>> for AdtDef {
2009 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
2011 static CACHE: RefCell<FxHashMap<usize, Fingerprint>> = Default::default();
2014 let hash: Fingerprint = CACHE.with(|cache| {
2015 let addr = self as *const AdtDef as usize;
2016 *cache.borrow_mut().entry(addr).or_insert_with(|| {
2017 let ty::AdtDef { did, ref variants, ref flags, ref repr } = *self;
2019 let mut hasher = StableHasher::new();
2020 did.hash_stable(hcx, &mut hasher);
2021 variants.hash_stable(hcx, &mut hasher);
2022 flags.hash_stable(hcx, &mut hasher);
2023 repr.hash_stable(hcx, &mut hasher);
2029 hash.hash_stable(hcx, hasher);
2033 #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
2040 impl Into<DataTypeKind> for AdtKind {
2041 fn into(self) -> DataTypeKind {
2043 AdtKind::Struct => DataTypeKind::Struct,
2044 AdtKind::Union => DataTypeKind::Union,
2045 AdtKind::Enum => DataTypeKind::Enum,
2051 #[derive(RustcEncodable, RustcDecodable, Default, HashStable)]
2052 pub struct ReprFlags: u8 {
2053 const IS_C = 1 << 0;
2054 const IS_SIMD = 1 << 1;
2055 const IS_TRANSPARENT = 1 << 2;
2056 // Internal only for now. If true, don't reorder fields.
2057 const IS_LINEAR = 1 << 3;
2058 // If true, don't expose any niche to type's context.
2059 const HIDE_NICHE = 1 << 4;
2060 // Any of these flags being set prevent field reordering optimisation.
2061 const IS_UNOPTIMISABLE = ReprFlags::IS_C.bits |
2062 ReprFlags::IS_SIMD.bits |
2063 ReprFlags::IS_LINEAR.bits;
2067 /// Represents the repr options provided by the user,
2068 #[derive(Copy, Clone, Debug, Eq, PartialEq, RustcEncodable, RustcDecodable, Default, HashStable)]
2069 pub struct ReprOptions {
2070 pub int: Option<attr::IntType>,
2071 pub align: Option<Align>,
2072 pub pack: Option<Align>,
2073 pub flags: ReprFlags,
2077 pub fn new(tcx: TyCtxt<'_>, did: DefId) -> ReprOptions {
2078 let mut flags = ReprFlags::empty();
2079 let mut size = None;
2080 let mut max_align: Option<Align> = None;
2081 let mut min_pack: Option<Align> = None;
2082 for attr in tcx.get_attrs(did).iter() {
2083 for r in attr::find_repr_attrs(&tcx.sess.parse_sess, attr) {
2084 flags.insert(match r {
2085 attr::ReprC => ReprFlags::IS_C,
2086 attr::ReprPacked(pack) => {
2087 let pack = Align::from_bytes(pack as u64).unwrap();
2088 min_pack = Some(if let Some(min_pack) = min_pack {
2095 attr::ReprTransparent => ReprFlags::IS_TRANSPARENT,
2096 attr::ReprNoNiche => ReprFlags::HIDE_NICHE,
2097 attr::ReprSimd => ReprFlags::IS_SIMD,
2098 attr::ReprInt(i) => {
2102 attr::ReprAlign(align) => {
2103 max_align = max_align.max(Some(Align::from_bytes(align as u64).unwrap()));
2110 // This is here instead of layout because the choice must make it into metadata.
2111 if !tcx.consider_optimizing(|| format!("Reorder fields of {:?}", tcx.def_path_str(did))) {
2112 flags.insert(ReprFlags::IS_LINEAR);
2114 ReprOptions { int: size, align: max_align, pack: min_pack, flags }
2118 pub fn simd(&self) -> bool {
2119 self.flags.contains(ReprFlags::IS_SIMD)
2122 pub fn c(&self) -> bool {
2123 self.flags.contains(ReprFlags::IS_C)
2126 pub fn packed(&self) -> bool {
2130 pub fn transparent(&self) -> bool {
2131 self.flags.contains(ReprFlags::IS_TRANSPARENT)
2134 pub fn linear(&self) -> bool {
2135 self.flags.contains(ReprFlags::IS_LINEAR)
2138 pub fn hide_niche(&self) -> bool {
2139 self.flags.contains(ReprFlags::HIDE_NICHE)
2142 pub fn discr_type(&self) -> attr::IntType {
2143 self.int.unwrap_or(attr::SignedInt(ast::IntTy::Isize))
2146 /// Returns `true` if this `#[repr()]` should inhabit "smart enum
2147 /// layout" optimizations, such as representing `Foo<&T>` as a
2149 pub fn inhibit_enum_layout_opt(&self) -> bool {
2150 self.c() || self.int.is_some()
2153 /// Returns `true` if this `#[repr()]` should inhibit struct field reordering
2154 /// optimizations, such as with `repr(C)`, `repr(packed(1))`, or `repr(<int>)`.
2155 pub fn inhibit_struct_field_reordering_opt(&self) -> bool {
2156 if let Some(pack) = self.pack {
2157 if pack.bytes() == 1 {
2161 self.flags.intersects(ReprFlags::IS_UNOPTIMISABLE) || self.int.is_some()
2164 /// Returns `true` if this `#[repr()]` should inhibit union ABI optimisations.
2165 pub fn inhibit_union_abi_opt(&self) -> bool {
2171 /// Creates a new `AdtDef`.
2176 variants: IndexVec<VariantIdx, VariantDef>,
2179 debug!("AdtDef::new({:?}, {:?}, {:?}, {:?})", did, kind, variants, repr);
2180 let mut flags = AdtFlags::NO_ADT_FLAGS;
2182 if kind == AdtKind::Enum && tcx.has_attr(did, sym::non_exhaustive) {
2183 debug!("found non-exhaustive variant list for {:?}", did);
2184 flags = flags | AdtFlags::IS_VARIANT_LIST_NON_EXHAUSTIVE;
2187 flags |= match kind {
2188 AdtKind::Enum => AdtFlags::IS_ENUM,
2189 AdtKind::Union => AdtFlags::IS_UNION,
2190 AdtKind::Struct => AdtFlags::IS_STRUCT,
2193 if kind == AdtKind::Struct && variants[VariantIdx::new(0)].ctor_def_id.is_some() {
2194 flags |= AdtFlags::HAS_CTOR;
2197 let attrs = tcx.get_attrs(did);
2198 if attr::contains_name(&attrs, sym::fundamental) {
2199 flags |= AdtFlags::IS_FUNDAMENTAL;
2201 if Some(did) == tcx.lang_items().phantom_data() {
2202 flags |= AdtFlags::IS_PHANTOM_DATA;
2204 if Some(did) == tcx.lang_items().owned_box() {
2205 flags |= AdtFlags::IS_BOX;
2207 if Some(did) == tcx.lang_items().manually_drop() {
2208 flags |= AdtFlags::IS_MANUALLY_DROP;
2211 AdtDef { did, variants, flags, repr }
2214 /// Returns `true` if this is a struct.
2216 pub fn is_struct(&self) -> bool {
2217 self.flags.contains(AdtFlags::IS_STRUCT)
2220 /// Returns `true` if this is a union.
2222 pub fn is_union(&self) -> bool {
2223 self.flags.contains(AdtFlags::IS_UNION)
2226 /// Returns `true` if this is a enum.
2228 pub fn is_enum(&self) -> bool {
2229 self.flags.contains(AdtFlags::IS_ENUM)
2232 /// Returns `true` if the variant list of this ADT is `#[non_exhaustive]`.
2234 pub fn is_variant_list_non_exhaustive(&self) -> bool {
2235 self.flags.contains(AdtFlags::IS_VARIANT_LIST_NON_EXHAUSTIVE)
2238 /// Returns the kind of the ADT.
2240 pub fn adt_kind(&self) -> AdtKind {
2243 } else if self.is_union() {
2250 /// Returns a description of this abstract data type.
2251 pub fn descr(&self) -> &'static str {
2252 match self.adt_kind() {
2253 AdtKind::Struct => "struct",
2254 AdtKind::Union => "union",
2255 AdtKind::Enum => "enum",
2259 /// Returns a description of a variant of this abstract data type.
2261 pub fn variant_descr(&self) -> &'static str {
2262 match self.adt_kind() {
2263 AdtKind::Struct => "struct",
2264 AdtKind::Union => "union",
2265 AdtKind::Enum => "variant",
2269 /// If this function returns `true`, it implies that `is_struct` must return `true`.
2271 pub fn has_ctor(&self) -> bool {
2272 self.flags.contains(AdtFlags::HAS_CTOR)
2275 /// Returns `true` if this type is `#[fundamental]` for the purposes
2276 /// of coherence checking.
2278 pub fn is_fundamental(&self) -> bool {
2279 self.flags.contains(AdtFlags::IS_FUNDAMENTAL)
2282 /// Returns `true` if this is `PhantomData<T>`.
2284 pub fn is_phantom_data(&self) -> bool {
2285 self.flags.contains(AdtFlags::IS_PHANTOM_DATA)
2288 /// Returns `true` if this is Box<T>.
2290 pub fn is_box(&self) -> bool {
2291 self.flags.contains(AdtFlags::IS_BOX)
2294 /// Returns `true` if this is `ManuallyDrop<T>`.
2296 pub fn is_manually_drop(&self) -> bool {
2297 self.flags.contains(AdtFlags::IS_MANUALLY_DROP)
2300 /// Returns `true` if this type has a destructor.
2301 pub fn has_dtor(&self, tcx: TyCtxt<'tcx>) -> bool {
2302 self.destructor(tcx).is_some()
2305 /// Asserts this is a struct or union and returns its unique variant.
2306 pub fn non_enum_variant(&self) -> &VariantDef {
2307 assert!(self.is_struct() || self.is_union());
2308 &self.variants[VariantIdx::new(0)]
2312 pub fn predicates(&self, tcx: TyCtxt<'tcx>) -> GenericPredicates<'tcx> {
2313 tcx.predicates_of(self.did)
2316 /// Returns an iterator over all fields contained
2319 pub fn all_fields(&self) -> impl Iterator<Item = &FieldDef> + Clone {
2320 self.variants.iter().flat_map(|v| v.fields.iter())
2323 pub fn is_payloadfree(&self) -> bool {
2324 !self.variants.is_empty() && self.variants.iter().all(|v| v.fields.is_empty())
2327 /// Return a `VariantDef` given a variant id.
2328 pub fn variant_with_id(&self, vid: DefId) -> &VariantDef {
2329 self.variants.iter().find(|v| v.def_id == vid).expect("variant_with_id: unknown variant")
2332 /// Return a `VariantDef` given a constructor id.
2333 pub fn variant_with_ctor_id(&self, cid: DefId) -> &VariantDef {
2336 .find(|v| v.ctor_def_id == Some(cid))
2337 .expect("variant_with_ctor_id: unknown variant")
2340 /// Return the index of `VariantDef` given a variant id.
2341 pub fn variant_index_with_id(&self, vid: DefId) -> VariantIdx {
2344 .find(|(_, v)| v.def_id == vid)
2345 .expect("variant_index_with_id: unknown variant")
2349 /// Return the index of `VariantDef` given a constructor id.
2350 pub fn variant_index_with_ctor_id(&self, cid: DefId) -> VariantIdx {
2353 .find(|(_, v)| v.ctor_def_id == Some(cid))
2354 .expect("variant_index_with_ctor_id: unknown variant")
2358 pub fn variant_of_res(&self, res: Res) -> &VariantDef {
2360 Res::Def(DefKind::Variant, vid) => self.variant_with_id(vid),
2361 Res::Def(DefKind::Ctor(..), cid) => self.variant_with_ctor_id(cid),
2362 Res::Def(DefKind::Struct, _)
2363 | Res::Def(DefKind::Union, _)
2364 | Res::Def(DefKind::TyAlias, _)
2365 | Res::Def(DefKind::AssocTy, _)
2367 | Res::SelfCtor(..) => self.non_enum_variant(),
2368 _ => bug!("unexpected res {:?} in variant_of_res", res),
2373 pub fn eval_explicit_discr(&self, tcx: TyCtxt<'tcx>, expr_did: DefId) -> Option<Discr<'tcx>> {
2374 let param_env = tcx.param_env(expr_did);
2375 let repr_type = self.repr.discr_type();
2376 match tcx.const_eval_poly(expr_did) {
2378 let ty = repr_type.to_ty(tcx);
2379 if let Some(b) = val.try_to_bits_for_ty(tcx, param_env, ty) {
2380 trace!("discriminants: {} ({:?})", b, repr_type);
2381 Some(Discr { val: b, ty })
2383 info!("invalid enum discriminant: {:#?}", val);
2384 crate::mir::interpret::struct_error(
2385 tcx.at(tcx.def_span(expr_did)),
2386 "constant evaluation of enum discriminant resulted in non-integer",
2392 Err(ErrorHandled::Reported(ErrorReported) | ErrorHandled::Linted) => {
2393 if !expr_did.is_local() {
2395 tcx.def_span(expr_did),
2396 "variant discriminant evaluation succeeded \
2397 in its crate but failed locally"
2402 Err(ErrorHandled::TooGeneric) => {
2403 tcx.sess.delay_span_bug(
2404 tcx.def_span(expr_did),
2405 "enum discriminant depends on generic arguments",
2413 pub fn discriminants(
2416 ) -> impl Iterator<Item = (VariantIdx, Discr<'tcx>)> + Captures<'tcx> {
2417 let repr_type = self.repr.discr_type();
2418 let initial = repr_type.initial_discriminant(tcx);
2419 let mut prev_discr = None::<Discr<'tcx>>;
2420 self.variants.iter_enumerated().map(move |(i, v)| {
2421 let mut discr = prev_discr.map_or(initial, |d| d.wrap_incr(tcx));
2422 if let VariantDiscr::Explicit(expr_did) = v.discr {
2423 if let Some(new_discr) = self.eval_explicit_discr(tcx, expr_did) {
2427 prev_discr = Some(discr);
2434 pub fn variant_range(&self) -> Range<VariantIdx> {
2435 VariantIdx::new(0)..VariantIdx::new(self.variants.len())
2438 /// Computes the discriminant value used by a specific variant.
2439 /// Unlike `discriminants`, this is (amortized) constant-time,
2440 /// only doing at most one query for evaluating an explicit
2441 /// discriminant (the last one before the requested variant),
2442 /// assuming there are no constant-evaluation errors there.
2444 pub fn discriminant_for_variant(
2447 variant_index: VariantIdx,
2449 let (val, offset) = self.discriminant_def_for_variant(variant_index);
2450 let explicit_value = val
2451 .and_then(|expr_did| self.eval_explicit_discr(tcx, expr_did))
2452 .unwrap_or_else(|| self.repr.discr_type().initial_discriminant(tcx));
2453 explicit_value.checked_add(tcx, offset as u128).0
2456 /// Yields a `DefId` for the discriminant and an offset to add to it
2457 /// Alternatively, if there is no explicit discriminant, returns the
2458 /// inferred discriminant directly.
2459 pub fn discriminant_def_for_variant(&self, variant_index: VariantIdx) -> (Option<DefId>, u32) {
2460 let mut explicit_index = variant_index.as_u32();
2463 match self.variants[VariantIdx::from_u32(explicit_index)].discr {
2464 ty::VariantDiscr::Relative(0) => {
2468 ty::VariantDiscr::Relative(distance) => {
2469 explicit_index -= distance;
2471 ty::VariantDiscr::Explicit(did) => {
2472 expr_did = Some(did);
2477 (expr_did, variant_index.as_u32() - explicit_index)
2480 pub fn destructor(&self, tcx: TyCtxt<'tcx>) -> Option<Destructor> {
2481 tcx.adt_destructor(self.did)
2484 /// Returns a list of types such that `Self: Sized` if and only
2485 /// if that type is `Sized`, or `TyErr` if this type is recursive.
2487 /// Oddly enough, checking that the sized-constraint is `Sized` is
2488 /// actually more expressive than checking all members:
2489 /// the `Sized` trait is inductive, so an associated type that references
2490 /// `Self` would prevent its containing ADT from being `Sized`.
2492 /// Due to normalization being eager, this applies even if
2493 /// the associated type is behind a pointer (e.g., issue #31299).
2494 pub fn sized_constraint(&self, tcx: TyCtxt<'tcx>) -> &'tcx [Ty<'tcx>] {
2495 tcx.adt_sized_constraint(self.did).0
2499 impl<'tcx> FieldDef {
2500 /// Returns the type of this field. The `subst` is typically obtained
2501 /// via the second field of `TyKind::AdtDef`.
2502 pub fn ty(&self, tcx: TyCtxt<'tcx>, subst: SubstsRef<'tcx>) -> Ty<'tcx> {
2503 tcx.type_of(self.did).subst(tcx, subst)
2507 /// Represents the various closure traits in the language. This
2508 /// will determine the type of the environment (`self`, in the
2509 /// desugaring) argument that the closure expects.
2511 /// You can get the environment type of a closure using
2512 /// `tcx.closure_env_ty()`.
2513 #[derive(Clone, Copy, PartialOrd, Ord, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
2514 #[derive(HashStable)]
2515 pub enum ClosureKind {
2516 // Warning: Ordering is significant here! The ordering is chosen
2517 // because the trait Fn is a subtrait of FnMut and so in turn, and
2518 // hence we order it so that Fn < FnMut < FnOnce.
2524 impl<'tcx> ClosureKind {
2525 // This is the initial value used when doing upvar inference.
2526 pub const LATTICE_BOTTOM: ClosureKind = ClosureKind::Fn;
2528 pub fn trait_did(&self, tcx: TyCtxt<'tcx>) -> DefId {
2530 ClosureKind::Fn => tcx.require_lang_item(FnTraitLangItem, None),
2531 ClosureKind::FnMut => tcx.require_lang_item(FnMutTraitLangItem, None),
2532 ClosureKind::FnOnce => tcx.require_lang_item(FnOnceTraitLangItem, None),
2536 /// Returns `true` if this a type that impls this closure kind
2537 /// must also implement `other`.
2538 pub fn extends(self, other: ty::ClosureKind) -> bool {
2539 match (self, other) {
2540 (ClosureKind::Fn, ClosureKind::Fn) => true,
2541 (ClosureKind::Fn, ClosureKind::FnMut) => true,
2542 (ClosureKind::Fn, ClosureKind::FnOnce) => true,
2543 (ClosureKind::FnMut, ClosureKind::FnMut) => true,
2544 (ClosureKind::FnMut, ClosureKind::FnOnce) => true,
2545 (ClosureKind::FnOnce, ClosureKind::FnOnce) => true,
2550 /// Returns the representative scalar type for this closure kind.
2551 /// See `TyS::to_opt_closure_kind` for more details.
2552 pub fn to_ty(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
2554 ty::ClosureKind::Fn => tcx.types.i8,
2555 ty::ClosureKind::FnMut => tcx.types.i16,
2556 ty::ClosureKind::FnOnce => tcx.types.i32,
2562 pub fn from_mutbl(m: hir::Mutability) -> BorrowKind {
2564 hir::Mutability::Mut => MutBorrow,
2565 hir::Mutability::Not => ImmBorrow,
2569 /// Returns a mutability `m` such that an `&m T` pointer could be used to obtain this borrow
2570 /// kind. Because borrow kinds are richer than mutabilities, we sometimes have to pick a
2571 /// mutability that is stronger than necessary so that it at least *would permit* the borrow in
2573 pub fn to_mutbl_lossy(self) -> hir::Mutability {
2575 MutBorrow => hir::Mutability::Mut,
2576 ImmBorrow => hir::Mutability::Not,
2578 // We have no type corresponding to a unique imm borrow, so
2579 // use `&mut`. It gives all the capabilities of an `&uniq`
2580 // and hence is a safe "over approximation".
2581 UniqueImmBorrow => hir::Mutability::Mut,
2585 pub fn to_user_str(&self) -> &'static str {
2587 MutBorrow => "mutable",
2588 ImmBorrow => "immutable",
2589 UniqueImmBorrow => "uniquely immutable",
2594 pub type Attributes<'tcx> = &'tcx [ast::Attribute];
2596 #[derive(Debug, PartialEq, Eq)]
2597 pub enum ImplOverlapKind {
2598 /// These impls are always allowed to overlap.
2600 /// Whether or not the impl is permitted due to the trait being a `#[marker]` trait
2603 /// These impls are allowed to overlap, but that raises
2604 /// an issue #33140 future-compatibility warning.
2606 /// Some background: in Rust 1.0, the trait-object types `Send + Sync` (today's
2607 /// `dyn Send + Sync`) and `Sync + Send` (now `dyn Sync + Send`) were different.
2609 /// The widely-used version 0.1.0 of the crate `traitobject` had accidentally relied
2610 /// that difference, making what reduces to the following set of impls:
2614 /// impl Trait for dyn Send + Sync {}
2615 /// impl Trait for dyn Sync + Send {}
2618 /// Obviously, once we made these types be identical, that code causes a coherence
2619 /// error and a fairly big headache for us. However, luckily for us, the trait
2620 /// `Trait` used in this case is basically a marker trait, and therefore having
2621 /// overlapping impls for it is sound.
2623 /// To handle this, we basically regard the trait as a marker trait, with an additional
2624 /// future-compatibility warning. To avoid accidentally "stabilizing" this feature,
2625 /// it has the following restrictions:
2627 /// 1. The trait must indeed be a marker-like trait (i.e., no items), and must be
2629 /// 2. The trait-ref of both impls must be equal.
2630 /// 3. The trait-ref of both impls must be a trait object type consisting only of
2632 /// 4. Neither of the impls can have any where-clauses.
2634 /// Once `traitobject` 0.1.0 is no longer an active concern, this hack can be removed.
2638 impl<'tcx> TyCtxt<'tcx> {
2639 pub fn body_tables(self, body: hir::BodyId) -> &'tcx TypeckTables<'tcx> {
2640 self.typeck_tables_of(self.hir().body_owner_def_id(body).to_def_id())
2643 /// Returns an iterator of the `DefId`s for all body-owners in this
2644 /// crate. If you would prefer to iterate over the bodies
2645 /// themselves, you can do `self.hir().krate().body_ids.iter()`.
2646 pub fn body_owners(self) -> impl Iterator<Item = LocalDefId> + Captures<'tcx> + 'tcx {
2651 .map(move |&body_id| self.hir().body_owner_def_id(body_id))
2654 pub fn par_body_owners<F: Fn(LocalDefId) + sync::Sync + sync::Send>(self, f: F) {
2655 par_iter(&self.hir().krate().body_ids)
2656 .for_each(|&body_id| f(self.hir().body_owner_def_id(body_id)));
2659 pub fn provided_trait_methods(self, id: DefId) -> impl 'tcx + Iterator<Item = &'tcx AssocItem> {
2660 self.associated_items(id)
2661 .in_definition_order()
2662 .filter(|item| item.kind == AssocKind::Fn && item.defaultness.has_value())
2665 pub fn trait_relevant_for_never(self, did: DefId) -> bool {
2666 self.associated_items(did).in_definition_order().any(|item| item.relevant_for_never())
2669 pub fn opt_item_name(self, def_id: DefId) -> Option<Ident> {
2670 self.hir().as_local_hir_id(def_id).and_then(|hir_id| self.hir().get(hir_id).ident())
2673 pub fn opt_associated_item(self, def_id: DefId) -> Option<AssocItem> {
2674 let is_associated_item = if let Some(hir_id) = self.hir().as_local_hir_id(def_id) {
2675 match self.hir().get(hir_id) {
2676 Node::TraitItem(_) | Node::ImplItem(_) => true,
2680 match self.def_kind(def_id) {
2681 Some(DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy) => true,
2686 is_associated_item.then(|| self.associated_item(def_id))
2689 pub fn field_index(self, hir_id: hir::HirId, tables: &TypeckTables<'_>) -> usize {
2690 tables.field_indices().get(hir_id).cloned().expect("no index for a field")
2693 pub fn find_field_index(self, ident: Ident, variant: &VariantDef) -> Option<usize> {
2694 variant.fields.iter().position(|field| self.hygienic_eq(ident, field.ident, variant.def_id))
2697 /// Returns `true` if the impls are the same polarity and the trait either
2698 /// has no items or is annotated #[marker] and prevents item overrides.
2699 pub fn impls_are_allowed_to_overlap(
2703 ) -> Option<ImplOverlapKind> {
2704 // If either trait impl references an error, they're allowed to overlap,
2705 // as one of them essentially doesn't exist.
2706 if self.impl_trait_ref(def_id1).map_or(false, |tr| tr.references_error())
2707 || self.impl_trait_ref(def_id2).map_or(false, |tr| tr.references_error())
2709 return Some(ImplOverlapKind::Permitted { marker: false });
2712 match (self.impl_polarity(def_id1), self.impl_polarity(def_id2)) {
2713 (ImplPolarity::Reservation, _) | (_, ImplPolarity::Reservation) => {
2714 // `#[rustc_reservation_impl]` impls don't overlap with anything
2716 "impls_are_allowed_to_overlap({:?}, {:?}) = Some(Permitted) (reservations)",
2719 return Some(ImplOverlapKind::Permitted { marker: false });
2721 (ImplPolarity::Positive, ImplPolarity::Negative)
2722 | (ImplPolarity::Negative, ImplPolarity::Positive) => {
2723 // `impl AutoTrait for Type` + `impl !AutoTrait for Type`
2725 "impls_are_allowed_to_overlap({:?}, {:?}) - None (differing polarities)",
2730 (ImplPolarity::Positive, ImplPolarity::Positive)
2731 | (ImplPolarity::Negative, ImplPolarity::Negative) => {}
2734 let is_marker_overlap = {
2735 let is_marker_impl = |def_id: DefId| -> bool {
2736 let trait_ref = self.impl_trait_ref(def_id);
2737 trait_ref.map_or(false, |tr| self.trait_def(tr.def_id).is_marker)
2739 is_marker_impl(def_id1) && is_marker_impl(def_id2)
2742 if is_marker_overlap {
2744 "impls_are_allowed_to_overlap({:?}, {:?}) = Some(Permitted) (marker overlap)",
2747 Some(ImplOverlapKind::Permitted { marker: true })
2749 if let Some(self_ty1) = self.issue33140_self_ty(def_id1) {
2750 if let Some(self_ty2) = self.issue33140_self_ty(def_id2) {
2751 if self_ty1 == self_ty2 {
2753 "impls_are_allowed_to_overlap({:?}, {:?}) - issue #33140 HACK",
2756 return Some(ImplOverlapKind::Issue33140);
2759 "impls_are_allowed_to_overlap({:?}, {:?}) - found {:?} != {:?}",
2760 def_id1, def_id2, self_ty1, self_ty2
2766 debug!("impls_are_allowed_to_overlap({:?}, {:?}) = None", def_id1, def_id2);
2771 /// Returns `ty::VariantDef` if `res` refers to a struct,
2772 /// or variant or their constructors, panics otherwise.
2773 pub fn expect_variant_res(self, res: Res) -> &'tcx VariantDef {
2775 Res::Def(DefKind::Variant, did) => {
2776 let enum_did = self.parent(did).unwrap();
2777 self.adt_def(enum_did).variant_with_id(did)
2779 Res::Def(DefKind::Struct | DefKind::Union, did) => self.adt_def(did).non_enum_variant(),
2780 Res::Def(DefKind::Ctor(CtorOf::Variant, ..), variant_ctor_did) => {
2781 let variant_did = self.parent(variant_ctor_did).unwrap();
2782 let enum_did = self.parent(variant_did).unwrap();
2783 self.adt_def(enum_did).variant_with_ctor_id(variant_ctor_did)
2785 Res::Def(DefKind::Ctor(CtorOf::Struct, ..), ctor_did) => {
2786 let struct_did = self.parent(ctor_did).expect("struct ctor has no parent");
2787 self.adt_def(struct_did).non_enum_variant()
2789 _ => bug!("expect_variant_res used with unexpected res {:?}", res),
2793 pub fn item_name(self, id: DefId) -> Symbol {
2794 if id.index == CRATE_DEF_INDEX {
2795 self.original_crate_name(id.krate)
2797 let def_key = self.def_key(id);
2798 match def_key.disambiguated_data.data {
2799 // The name of a constructor is that of its parent.
2800 rustc_hir::definitions::DefPathData::Ctor => {
2801 self.item_name(DefId { krate: id.krate, index: def_key.parent.unwrap() })
2803 _ => def_key.disambiguated_data.data.get_opt_name().unwrap_or_else(|| {
2804 bug!("item_name: no name for {:?}", self.def_path(id));
2810 /// Returns the possibly-auto-generated MIR of a `(DefId, Subst)` pair.
2811 pub fn instance_mir(self, instance: ty::InstanceDef<'tcx>) -> ReadOnlyBodyAndCache<'tcx, 'tcx> {
2813 ty::InstanceDef::Item(did) => self.optimized_mir(did).unwrap_read_only(),
2814 ty::InstanceDef::VtableShim(..)
2815 | ty::InstanceDef::ReifyShim(..)
2816 | ty::InstanceDef::Intrinsic(..)
2817 | ty::InstanceDef::FnPtrShim(..)
2818 | ty::InstanceDef::Virtual(..)
2819 | ty::InstanceDef::ClosureOnceShim { .. }
2820 | ty::InstanceDef::DropGlue(..)
2821 | ty::InstanceDef::CloneShim(..) => self.mir_shims(instance).unwrap_read_only(),
2825 /// Gets the attributes of a definition.
2826 pub fn get_attrs(self, did: DefId) -> Attributes<'tcx> {
2827 if let Some(id) = self.hir().as_local_hir_id(did) {
2828 self.hir().attrs(id)
2830 self.item_attrs(did)
2834 /// Determines whether an item is annotated with an attribute.
2835 pub fn has_attr(self, did: DefId, attr: Symbol) -> bool {
2836 attr::contains_name(&self.get_attrs(did), attr)
2839 /// Returns `true` if this is an `auto trait`.
2840 pub fn trait_is_auto(self, trait_def_id: DefId) -> bool {
2841 self.trait_def(trait_def_id).has_auto_impl
2844 pub fn generator_layout(self, def_id: DefId) -> &'tcx GeneratorLayout<'tcx> {
2845 self.optimized_mir(def_id).generator_layout.as_ref().unwrap()
2848 /// Given the `DefId` of an impl, returns the `DefId` of the trait it implements.
2849 /// If it implements no trait, returns `None`.
2850 pub fn trait_id_of_impl(self, def_id: DefId) -> Option<DefId> {
2851 self.impl_trait_ref(def_id).map(|tr| tr.def_id)
2854 /// If the given defid describes a method belonging to an impl, returns the
2855 /// `DefId` of the impl that the method belongs to; otherwise, returns `None`.
2856 pub fn impl_of_method(self, def_id: DefId) -> Option<DefId> {
2857 self.opt_associated_item(def_id).and_then(|trait_item| match trait_item.container {
2858 TraitContainer(_) => None,
2859 ImplContainer(def_id) => Some(def_id),
2863 /// Looks up the span of `impl_did` if the impl is local; otherwise returns `Err`
2864 /// with the name of the crate containing the impl.
2865 pub fn span_of_impl(self, impl_did: DefId) -> Result<Span, Symbol> {
2866 if impl_did.is_local() {
2867 let hir_id = self.hir().as_local_hir_id(impl_did).unwrap();
2868 Ok(self.hir().span(hir_id))
2870 Err(self.crate_name(impl_did.krate))
2874 /// Hygienically compares a use-site name (`use_name`) for a field or an associated item with
2875 /// its supposed definition name (`def_name`). The method also needs `DefId` of the supposed
2876 /// definition's parent/scope to perform comparison.
2877 pub fn hygienic_eq(self, use_name: Ident, def_name: Ident, def_parent_def_id: DefId) -> bool {
2878 // We could use `Ident::eq` here, but we deliberately don't. The name
2879 // comparison fails frequently, and we want to avoid the expensive
2880 // `normalize_to_macros_2_0()` calls required for the span comparison whenever possible.
2881 use_name.name == def_name.name
2885 .hygienic_eq(def_name.span.ctxt(), self.expansion_that_defined(def_parent_def_id))
2888 fn expansion_that_defined(self, scope: DefId) -> ExpnId {
2889 match scope.as_local() {
2890 Some(scope) => self.hir().definitions().expansion_that_defined(scope),
2891 None => ExpnId::root(),
2895 pub fn adjust_ident(self, mut ident: Ident, scope: DefId) -> Ident {
2896 ident.span.normalize_to_macros_2_0_and_adjust(self.expansion_that_defined(scope));
2900 pub fn adjust_ident_and_get_scope(
2905 ) -> (Ident, DefId) {
2907 match ident.span.normalize_to_macros_2_0_and_adjust(self.expansion_that_defined(scope))
2909 Some(actual_expansion) => {
2910 self.hir().definitions().parent_module_of_macro_def(actual_expansion)
2912 None => self.parent_module(block).to_def_id(),
2917 pub fn is_object_safe(self, key: DefId) -> bool {
2918 self.object_safety_violations(key).is_empty()
2922 #[derive(Clone, HashStable)]
2923 pub struct AdtSizedConstraint<'tcx>(pub &'tcx [Ty<'tcx>]);
2925 /// Yields the parent function's `DefId` if `def_id` is an `impl Trait` definition.
2926 pub fn is_impl_trait_defn(tcx: TyCtxt<'_>, def_id: DefId) -> Option<DefId> {
2927 if let Some(hir_id) = tcx.hir().as_local_hir_id(def_id) {
2928 if let Node::Item(item) = tcx.hir().get(hir_id) {
2929 if let hir::ItemKind::OpaqueTy(ref opaque_ty) = item.kind {
2930 return opaque_ty.impl_trait_fn;
2937 pub fn provide(providers: &mut ty::query::Providers<'_>) {
2938 context::provide(providers);
2939 erase_regions::provide(providers);
2940 layout::provide(providers);
2941 super::util::bug::provide(providers);
2942 *providers = ty::query::Providers {
2943 trait_impls_of: trait_def::trait_impls_of_provider,
2944 all_local_trait_impls: trait_def::all_local_trait_impls,
2949 /// A map for the local crate mapping each type to a vector of its
2950 /// inherent impls. This is not meant to be used outside of coherence;
2951 /// rather, you should request the vector for a specific type via
2952 /// `tcx.inherent_impls(def_id)` so as to minimize your dependencies
2953 /// (constructing this map requires touching the entire crate).
2954 #[derive(Clone, Debug, Default, HashStable)]
2955 pub struct CrateInherentImpls {
2956 pub inherent_impls: DefIdMap<Vec<DefId>>,
2959 #[derive(Clone, Copy, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2960 pub struct SymbolName {
2961 // FIXME: we don't rely on interning or equality here - better have
2962 // this be a `&'tcx str`.
2967 pub fn new(name: &str) -> SymbolName {
2968 SymbolName { name: Symbol::intern(name) }
2972 impl PartialOrd for SymbolName {
2973 fn partial_cmp(&self, other: &SymbolName) -> Option<Ordering> {
2974 self.name.as_str().partial_cmp(&other.name.as_str())
2978 /// Ordering must use the chars to ensure reproducible builds.
2979 impl Ord for SymbolName {
2980 fn cmp(&self, other: &SymbolName) -> Ordering {
2981 self.name.as_str().cmp(&other.name.as_str())
2985 impl fmt::Display for SymbolName {
2986 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2987 fmt::Display::fmt(&self.name, fmt)
2991 impl fmt::Debug for SymbolName {
2992 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2993 fmt::Display::fmt(&self.name, fmt)