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};
31 use rustc_hir::def::{CtorKind, CtorOf, DefKind, Namespace, Res};
32 use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, LocalDefId, CRATE_DEF_INDEX};
33 use rustc_hir::lang_items::{FnMutTraitLangItem, FnOnceTraitLangItem, FnTraitLangItem};
34 use rustc_hir::{Constness, GlobMap, Node, TraitMap};
35 use rustc_index::vec::{Idx, IndexVec};
36 use rustc_macros::HashStable;
37 use rustc_serialize::{self, Encodable, Encoder};
38 use rustc_session::DataTypeKind;
39 use rustc_span::hygiene::ExpnId;
40 use rustc_span::symbol::{kw, sym, Symbol};
42 use rustc_target::abi::{Align, VariantIdx};
44 use std::cell::RefCell;
45 use std::cmp::{self, Ordering};
47 use std::hash::{Hash, Hasher};
53 pub use self::sty::BoundRegion::*;
54 pub use self::sty::InferTy::*;
55 pub use self::sty::RegionKind;
56 pub use self::sty::RegionKind::*;
57 pub use self::sty::TyKind::*;
58 pub use self::sty::{Binder, BoundTy, BoundTyKind, BoundVar, DebruijnIndex, INNERMOST};
59 pub use self::sty::{BoundRegion, EarlyBoundRegion, FreeRegion, Region};
60 pub use self::sty::{CanonicalPolyFnSig, FnSig, GenSig, PolyFnSig, PolyGenSig};
61 pub use self::sty::{ClosureSubsts, GeneratorSubsts, TypeAndMut, UpvarSubsts};
62 pub use self::sty::{Const, ConstKind, ExistentialProjection, PolyExistentialProjection};
63 pub use self::sty::{ConstVid, FloatVid, IntVid, RegionVid, TyVid};
64 pub use self::sty::{ExistentialPredicate, InferConst, InferTy, ParamConst, ParamTy, ProjectionTy};
65 pub use self::sty::{ExistentialTraitRef, PolyExistentialTraitRef};
66 pub use self::sty::{PolyTraitRef, TraitRef, TyKind};
67 pub use crate::ty::diagnostics::*;
69 pub use self::binding::BindingMode;
70 pub use self::binding::BindingMode::*;
72 pub use self::context::{tls, FreeRegionInfo, TyCtxt};
73 pub use self::context::{
74 CanonicalUserType, CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations, ResolvedOpaqueTy,
75 UserType, UserTypeAnnotationIndex,
77 pub use self::context::{
78 CtxtInterners, GeneratorInteriorTypeCause, GlobalCtxt, Lift, TypeckTables,
81 pub use self::instance::{Instance, InstanceDef};
83 pub use self::trait_def::TraitDef;
85 pub use self::query::queries;
98 pub mod free_region_map;
99 pub mod inhabitedness;
101 pub mod normalize_erasing_regions;
115 mod structural_impls;
120 pub struct ResolverOutputs {
121 pub definitions: rustc_hir::definitions::Definitions,
122 pub cstore: Box<CrateStoreDyn>,
123 pub extern_crate_map: NodeMap<CrateNum>,
124 pub trait_map: TraitMap<NodeId>,
125 pub maybe_unused_trait_imports: NodeSet,
126 pub maybe_unused_extern_crates: Vec<(NodeId, Span)>,
127 pub export_map: ExportMap<NodeId>,
128 pub glob_map: GlobMap,
129 /// Extern prelude entries. The value is `true` if the entry was introduced
130 /// via `extern crate` item and not `--extern` option or compiler built-in.
131 pub extern_prelude: FxHashMap<Name, bool>,
134 #[derive(Clone, Copy, PartialEq, Eq, Debug, HashStable)]
135 pub enum AssocItemContainer {
136 TraitContainer(DefId),
137 ImplContainer(DefId),
140 impl AssocItemContainer {
141 /// Asserts that this is the `DefId` of an associated item declared
142 /// in a trait, and returns the trait `DefId`.
143 pub fn assert_trait(&self) -> DefId {
145 TraitContainer(id) => id,
146 _ => bug!("associated item has wrong container type: {:?}", self),
150 pub fn id(&self) -> DefId {
152 TraitContainer(id) => id,
153 ImplContainer(id) => id,
158 /// The "header" of an impl is everything outside the body: a Self type, a trait
159 /// ref (in the case of a trait impl), and a set of predicates (from the
160 /// bounds / where-clauses).
161 #[derive(Clone, Debug, TypeFoldable)]
162 pub struct ImplHeader<'tcx> {
163 pub impl_def_id: DefId,
164 pub self_ty: Ty<'tcx>,
165 pub trait_ref: Option<TraitRef<'tcx>>,
166 pub predicates: Vec<Predicate<'tcx>>,
169 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable)]
170 pub enum ImplPolarity {
171 /// `impl Trait for Type`
173 /// `impl !Trait for Type`
175 /// `#[rustc_reservation_impl] impl Trait for Type`
177 /// This is a "stability hack", not a real Rust feature.
178 /// See #64631 for details.
182 #[derive(Copy, Clone, Debug, PartialEq, HashStable)]
183 pub struct AssocItem {
185 #[stable_hasher(project(name))]
189 pub defaultness: hir::Defaultness,
190 pub container: AssocItemContainer,
192 /// Whether this is a method with an explicit self
193 /// as its first parameter, allowing method calls.
194 pub fn_has_self_parameter: bool,
197 #[derive(Copy, Clone, PartialEq, Debug, HashStable)]
206 pub fn namespace(&self) -> Namespace {
208 ty::AssocKind::OpaqueTy | ty::AssocKind::Type => Namespace::TypeNS,
209 ty::AssocKind::Const | ty::AssocKind::Fn => Namespace::ValueNS,
213 pub fn as_def_kind(&self) -> DefKind {
215 AssocKind::Const => DefKind::AssocConst,
216 AssocKind::Fn => DefKind::AssocFn,
217 AssocKind::Type => DefKind::AssocTy,
218 AssocKind::OpaqueTy => DefKind::AssocOpaqueTy,
224 /// Tests whether the associated item admits a non-trivial implementation
226 pub fn relevant_for_never(&self) -> bool {
228 AssocKind::OpaqueTy | AssocKind::Const | AssocKind::Type => true,
229 // FIXME(canndrew): Be more thorough here, check if any argument is uninhabited.
230 AssocKind::Fn => !self.fn_has_self_parameter,
234 pub fn signature(&self, tcx: TyCtxt<'_>) -> String {
236 ty::AssocKind::Fn => {
237 // We skip the binder here because the binder would deanonymize all
238 // late-bound regions, and we don't want method signatures to show up
239 // `as for<'r> fn(&'r MyType)`. Pretty-printing handles late-bound
240 // regions just fine, showing `fn(&MyType)`.
241 tcx.fn_sig(self.def_id).skip_binder().to_string()
243 ty::AssocKind::Type => format!("type {};", self.ident),
244 // FIXME(type_alias_impl_trait): we should print bounds here too.
245 ty::AssocKind::OpaqueTy => format!("type {};", self.ident),
246 ty::AssocKind::Const => {
247 format!("const {}: {:?};", self.ident, tcx.type_of(self.def_id))
253 /// A list of `ty::AssocItem`s in definition order that allows for efficient lookup by name.
255 /// When doing lookup by name, we try to postpone hygienic comparison for as long as possible since
256 /// it is relatively expensive. Instead, items are indexed by `Symbol` and hygienic comparison is
257 /// done only on items with the same name.
258 #[derive(Debug, Clone, PartialEq, HashStable)]
259 pub struct AssociatedItems {
260 items: SortedIndexMultiMap<u32, Symbol, ty::AssocItem>,
263 impl AssociatedItems {
264 /// Constructs an `AssociatedItems` map from a series of `ty::AssocItem`s in definition order.
265 pub fn new(items_in_def_order: impl IntoIterator<Item = ty::AssocItem>) -> Self {
266 let items = items_in_def_order.into_iter().map(|item| (item.ident.name, item)).collect();
267 AssociatedItems { items }
270 /// Returns a slice of associated items in the order they were defined.
272 /// New code should avoid relying on definition order. If you need a particular associated item
273 /// for a known trait, make that trait a lang item instead of indexing this array.
274 pub fn in_definition_order(&self) -> impl '_ + Iterator<Item = &ty::AssocItem> {
275 self.items.iter().map(|(_, v)| v)
278 /// Returns an iterator over all associated items with the given name, ignoring hygiene.
279 pub fn filter_by_name_unhygienic(
282 ) -> impl '_ + Iterator<Item = &ty::AssocItem> {
283 self.items.get_by_key(&name)
286 /// Returns an iterator over all associated items with the given name.
288 /// Multiple items may have the same name if they are in different `Namespace`s. For example,
289 /// an associated type can have the same name as a method. Use one of the `find_by_name_and_*`
290 /// methods below if you know which item you are looking for.
291 pub fn filter_by_name(
295 parent_def_id: DefId,
296 ) -> impl 'a + Iterator<Item = &'a ty::AssocItem> {
297 self.filter_by_name_unhygienic(ident.name)
298 .filter(move |item| tcx.hygienic_eq(ident, item.ident, parent_def_id))
301 /// Returns the associated item with the given name and `AssocKind`, if one exists.
302 pub fn find_by_name_and_kind(
307 parent_def_id: DefId,
308 ) -> Option<&ty::AssocItem> {
309 self.filter_by_name_unhygienic(ident.name)
310 .filter(|item| item.kind == kind)
311 .find(|item| tcx.hygienic_eq(ident, item.ident, parent_def_id))
314 /// Returns the associated item with the given name in the given `Namespace`, if one exists.
315 pub fn find_by_name_and_namespace(
320 parent_def_id: DefId,
321 ) -> Option<&ty::AssocItem> {
322 self.filter_by_name_unhygienic(ident.name)
323 .filter(|item| item.kind.namespace() == ns)
324 .find(|item| tcx.hygienic_eq(ident, item.ident, parent_def_id))
328 #[derive(Clone, Debug, PartialEq, Eq, Copy, RustcEncodable, RustcDecodable, HashStable)]
329 pub enum Visibility {
330 /// Visible everywhere (including in other crates).
332 /// Visible only in the given crate-local module.
334 /// Not visible anywhere in the local crate. This is the visibility of private external items.
338 pub trait DefIdTree: Copy {
339 fn parent(self, id: DefId) -> Option<DefId>;
341 fn is_descendant_of(self, mut descendant: DefId, ancestor: DefId) -> bool {
342 if descendant.krate != ancestor.krate {
346 while descendant != ancestor {
347 match self.parent(descendant) {
348 Some(parent) => descendant = parent,
349 None => return false,
356 impl<'tcx> DefIdTree for TyCtxt<'tcx> {
357 fn parent(self, id: DefId) -> Option<DefId> {
358 self.def_key(id).parent.map(|index| DefId { index, ..id })
363 pub fn from_hir(visibility: &hir::Visibility<'_>, id: hir::HirId, tcx: TyCtxt<'_>) -> Self {
364 match visibility.node {
365 hir::VisibilityKind::Public => Visibility::Public,
366 hir::VisibilityKind::Crate(_) => Visibility::Restricted(DefId::local(CRATE_DEF_INDEX)),
367 hir::VisibilityKind::Restricted { ref path, .. } => match path.res {
368 // If there is no resolution, `resolve` will have already reported an error, so
369 // assume that the visibility is public to avoid reporting more privacy errors.
370 Res::Err => Visibility::Public,
371 def => Visibility::Restricted(def.def_id()),
373 hir::VisibilityKind::Inherited => {
374 Visibility::Restricted(tcx.parent_module(id).to_def_id())
379 /// Returns `true` if an item with this visibility is accessible from the given block.
380 pub fn is_accessible_from<T: DefIdTree>(self, module: DefId, tree: T) -> bool {
381 let restriction = match self {
382 // Public items are visible everywhere.
383 Visibility::Public => return true,
384 // Private items from other crates are visible nowhere.
385 Visibility::Invisible => return false,
386 // Restricted items are visible in an arbitrary local module.
387 Visibility::Restricted(other) if other.krate != module.krate => return false,
388 Visibility::Restricted(module) => module,
391 tree.is_descendant_of(module, restriction)
394 /// Returns `true` if this visibility is at least as accessible as the given visibility
395 pub fn is_at_least<T: DefIdTree>(self, vis: Visibility, tree: T) -> bool {
396 let vis_restriction = match vis {
397 Visibility::Public => return self == Visibility::Public,
398 Visibility::Invisible => return true,
399 Visibility::Restricted(module) => module,
402 self.is_accessible_from(vis_restriction, tree)
405 // Returns `true` if this item is visible anywhere in the local crate.
406 pub fn is_visible_locally(self) -> bool {
408 Visibility::Public => true,
409 Visibility::Restricted(def_id) => def_id.is_local(),
410 Visibility::Invisible => false,
415 #[derive(Copy, Clone, PartialEq, RustcDecodable, RustcEncodable, HashStable)]
417 Covariant, // T<A> <: T<B> iff A <: B -- e.g., function return type
418 Invariant, // T<A> <: T<B> iff B == A -- e.g., type of mutable cell
419 Contravariant, // T<A> <: T<B> iff B <: A -- e.g., function param type
420 Bivariant, // T<A> <: T<B> -- e.g., unused type parameter
423 /// The crate variances map is computed during typeck and contains the
424 /// variance of every item in the local crate. You should not use it
425 /// directly, because to do so will make your pass dependent on the
426 /// HIR of every item in the local crate. Instead, use
427 /// `tcx.variances_of()` to get the variance for a *particular*
429 #[derive(HashStable)]
430 pub struct CrateVariancesMap<'tcx> {
431 /// For each item with generics, maps to a vector of the variance
432 /// of its generics. If an item has no generics, it will have no
434 pub variances: FxHashMap<DefId, &'tcx [ty::Variance]>,
438 /// `a.xform(b)` combines the variance of a context with the
439 /// variance of a type with the following meaning. If we are in a
440 /// context with variance `a`, and we encounter a type argument in
441 /// a position with variance `b`, then `a.xform(b)` is the new
442 /// variance with which the argument appears.
448 /// Here, the "ambient" variance starts as covariant. `*mut T` is
449 /// invariant with respect to `T`, so the variance in which the
450 /// `Vec<i32>` appears is `Covariant.xform(Invariant)`, which
451 /// yields `Invariant`. Now, the type `Vec<T>` is covariant with
452 /// respect to its type argument `T`, and hence the variance of
453 /// the `i32` here is `Invariant.xform(Covariant)`, which results
454 /// (again) in `Invariant`.
458 /// fn(*const Vec<i32>, *mut Vec<i32)
460 /// The ambient variance is covariant. A `fn` type is
461 /// contravariant with respect to its parameters, so the variance
462 /// within which both pointer types appear is
463 /// `Covariant.xform(Contravariant)`, or `Contravariant`. `*const
464 /// T` is covariant with respect to `T`, so the variance within
465 /// which the first `Vec<i32>` appears is
466 /// `Contravariant.xform(Covariant)` or `Contravariant`. The same
467 /// is true for its `i32` argument. In the `*mut T` case, the
468 /// variance of `Vec<i32>` is `Contravariant.xform(Invariant)`,
469 /// and hence the outermost type is `Invariant` with respect to
470 /// `Vec<i32>` (and its `i32` argument).
472 /// Source: Figure 1 of "Taming the Wildcards:
473 /// Combining Definition- and Use-Site Variance" published in PLDI'11.
474 pub fn xform(self, v: ty::Variance) -> ty::Variance {
476 // Figure 1, column 1.
477 (ty::Covariant, ty::Covariant) => ty::Covariant,
478 (ty::Covariant, ty::Contravariant) => ty::Contravariant,
479 (ty::Covariant, ty::Invariant) => ty::Invariant,
480 (ty::Covariant, ty::Bivariant) => ty::Bivariant,
482 // Figure 1, column 2.
483 (ty::Contravariant, ty::Covariant) => ty::Contravariant,
484 (ty::Contravariant, ty::Contravariant) => ty::Covariant,
485 (ty::Contravariant, ty::Invariant) => ty::Invariant,
486 (ty::Contravariant, ty::Bivariant) => ty::Bivariant,
488 // Figure 1, column 3.
489 (ty::Invariant, _) => ty::Invariant,
491 // Figure 1, column 4.
492 (ty::Bivariant, _) => ty::Bivariant,
497 // Contains information needed to resolve types and (in the future) look up
498 // the types of AST nodes.
499 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
500 pub struct CReaderCacheKey {
506 /// Flags that we track on types. These flags are propagated upwards
507 /// through the type during type construction, so that we can quickly check
508 /// whether the type has various kinds of types in it without recursing
509 /// over the type itself.
510 pub struct TypeFlags: u32 {
511 // Does this have parameters? Used to determine whether substitution is
513 /// Does this have [Param]?
514 const HAS_TY_PARAM = 1 << 0;
515 /// Does this have [ReEarlyBound]?
516 const HAS_RE_PARAM = 1 << 1;
517 /// Does this have [ConstKind::Param]?
518 const HAS_CT_PARAM = 1 << 2;
520 const NEEDS_SUBST = TypeFlags::HAS_TY_PARAM.bits
521 | TypeFlags::HAS_RE_PARAM.bits
522 | TypeFlags::HAS_CT_PARAM.bits;
524 /// Does this have [Infer]?
525 const HAS_TY_INFER = 1 << 3;
526 /// Does this have [ReVar]?
527 const HAS_RE_INFER = 1 << 4;
528 /// Does this have [ConstKind::Infer]?
529 const HAS_CT_INFER = 1 << 5;
531 /// Does this have inference variables? Used to determine whether
532 /// inference is required.
533 const NEEDS_INFER = TypeFlags::HAS_TY_INFER.bits
534 | TypeFlags::HAS_RE_INFER.bits
535 | TypeFlags::HAS_CT_INFER.bits;
537 /// Does this have [Placeholder]?
538 const HAS_TY_PLACEHOLDER = 1 << 6;
539 /// Does this have [RePlaceholder]?
540 const HAS_RE_PLACEHOLDER = 1 << 7;
541 /// Does this have [ConstKind::Placeholder]?
542 const HAS_CT_PLACEHOLDER = 1 << 8;
544 /// `true` if there are "names" of regions and so forth
545 /// that are local to a particular fn/inferctxt
546 const HAS_FREE_LOCAL_REGIONS = 1 << 9;
548 /// `true` if there are "names" of types and regions and so forth
549 /// that are local to a particular fn
550 const HAS_FREE_LOCAL_NAMES = TypeFlags::HAS_TY_PARAM.bits
551 | TypeFlags::HAS_CT_PARAM.bits
552 | TypeFlags::HAS_TY_INFER.bits
553 | TypeFlags::HAS_CT_INFER.bits
554 | TypeFlags::HAS_TY_PLACEHOLDER.bits
555 | TypeFlags::HAS_CT_PLACEHOLDER.bits
556 | TypeFlags::HAS_FREE_LOCAL_REGIONS.bits;
558 /// Does this have [Projection] or [UnnormalizedProjection]?
559 const HAS_TY_PROJECTION = 1 << 10;
560 /// Does this have [Opaque]?
561 const HAS_TY_OPAQUE = 1 << 11;
562 /// Does this have [ConstKind::Unevaluated]?
563 const HAS_CT_PROJECTION = 1 << 12;
565 /// Could this type be normalized further?
566 const HAS_PROJECTION = TypeFlags::HAS_TY_PROJECTION.bits
567 | TypeFlags::HAS_TY_OPAQUE.bits
568 | TypeFlags::HAS_CT_PROJECTION.bits;
570 /// Is an error type reachable?
571 const HAS_TY_ERR = 1 << 13;
573 /// Does this have any region that "appears free" in the type?
574 /// Basically anything but [ReLateBound] and [ReErased].
575 const HAS_FREE_REGIONS = 1 << 14;
577 /// Does this have any [ReLateBound] regions? Used to check
578 /// if a global bound is safe to evaluate.
579 const HAS_RE_LATE_BOUND = 1 << 15;
581 /// Does this have any [ReErased] regions?
582 const HAS_RE_ERASED = 1 << 16;
584 /// Does this value have parameters/placeholders/inference variables which could be
585 /// replaced later, in a way that would change the results of `impl` specialization?
586 const STILL_FURTHER_SPECIALIZABLE = 1 << 17;
590 #[allow(rustc::usage_of_ty_tykind)]
591 pub struct TyS<'tcx> {
592 pub kind: TyKind<'tcx>,
593 pub flags: TypeFlags,
595 /// This is a kind of confusing thing: it stores the smallest
598 /// (a) the binder itself captures nothing but
599 /// (b) all the late-bound things within the type are captured
600 /// by some sub-binder.
602 /// So, for a type without any late-bound things, like `u32`, this
603 /// will be *innermost*, because that is the innermost binder that
604 /// captures nothing. But for a type `&'D u32`, where `'D` is a
605 /// late-bound region with De Bruijn index `D`, this would be `D + 1`
606 /// -- the binder itself does not capture `D`, but `D` is captured
607 /// by an inner binder.
609 /// We call this concept an "exclusive" binder `D` because all
610 /// De Bruijn indices within the type are contained within `0..D`
612 outer_exclusive_binder: ty::DebruijnIndex,
615 // `TyS` is used a lot. Make sure it doesn't unintentionally get bigger.
616 #[cfg(target_arch = "x86_64")]
617 static_assert_size!(TyS<'_>, 32);
619 impl<'tcx> Ord for TyS<'tcx> {
620 fn cmp(&self, other: &TyS<'tcx>) -> Ordering {
621 self.kind.cmp(&other.kind)
625 impl<'tcx> PartialOrd for TyS<'tcx> {
626 fn partial_cmp(&self, other: &TyS<'tcx>) -> Option<Ordering> {
627 Some(self.kind.cmp(&other.kind))
631 impl<'tcx> PartialEq for TyS<'tcx> {
633 fn eq(&self, other: &TyS<'tcx>) -> bool {
637 impl<'tcx> Eq for TyS<'tcx> {}
639 impl<'tcx> Hash for TyS<'tcx> {
640 fn hash<H: Hasher>(&self, s: &mut H) {
641 (self as *const TyS<'_>).hash(s)
645 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for ty::TyS<'tcx> {
646 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
650 // The other fields just provide fast access to information that is
651 // also contained in `kind`, so no need to hash them.
654 outer_exclusive_binder: _,
657 kind.hash_stable(hcx, hasher);
661 #[rustc_diagnostic_item = "Ty"]
662 pub type Ty<'tcx> = &'tcx TyS<'tcx>;
664 impl<'tcx> rustc_serialize::UseSpecializedEncodable for Ty<'tcx> {}
665 impl<'tcx> rustc_serialize::UseSpecializedDecodable for Ty<'tcx> {}
667 pub type CanonicalTy<'tcx> = Canonical<'tcx, Ty<'tcx>>;
670 /// A dummy type used to force `List` to be unsized while not requiring references to it be wide
672 type OpaqueListContents;
675 /// A wrapper for slices with the additional invariant
676 /// that the slice is interned and no other slice with
677 /// the same contents can exist in the same context.
678 /// This means we can use pointer for both
679 /// equality comparisons and hashing.
680 /// Note: `Slice` was already taken by the `Ty`.
685 opaque: OpaqueListContents,
688 unsafe impl<T: Sync> Sync for List<T> {}
690 impl<T: Copy> List<T> {
692 fn from_arena<'tcx>(arena: &'tcx Arena<'tcx>, slice: &[T]) -> &'tcx List<T> {
693 assert!(!mem::needs_drop::<T>());
694 assert!(mem::size_of::<T>() != 0);
695 assert!(!slice.is_empty());
697 // Align up the size of the len (usize) field
698 let align = mem::align_of::<T>();
699 let align_mask = align - 1;
700 let offset = mem::size_of::<usize>();
701 let offset = (offset + align_mask) & !align_mask;
703 let size = offset + slice.len() * mem::size_of::<T>();
707 .alloc_raw(size, cmp::max(mem::align_of::<T>(), mem::align_of::<usize>()));
709 let result = &mut *(mem.as_mut_ptr() as *mut List<T>);
711 result.len = slice.len();
713 // Write the elements
714 let arena_slice = slice::from_raw_parts_mut(result.data.as_mut_ptr(), result.len);
715 arena_slice.copy_from_slice(slice);
722 impl<T: fmt::Debug> fmt::Debug for List<T> {
723 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
728 impl<T: Encodable> Encodable for List<T> {
730 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
735 impl<T> Ord for List<T>
739 fn cmp(&self, other: &List<T>) -> Ordering {
740 if self == other { Ordering::Equal } else { <[T] as Ord>::cmp(&**self, &**other) }
744 impl<T> PartialOrd for List<T>
748 fn partial_cmp(&self, other: &List<T>) -> Option<Ordering> {
750 Some(Ordering::Equal)
752 <[T] as PartialOrd>::partial_cmp(&**self, &**other)
757 impl<T: PartialEq> PartialEq for List<T> {
759 fn eq(&self, other: &List<T>) -> bool {
763 impl<T: Eq> Eq for List<T> {}
765 impl<T> Hash for List<T> {
767 fn hash<H: Hasher>(&self, s: &mut H) {
768 (self as *const List<T>).hash(s)
772 impl<T> Deref for List<T> {
775 fn deref(&self) -> &[T] {
780 impl<T> AsRef<[T]> for List<T> {
782 fn as_ref(&self) -> &[T] {
783 unsafe { slice::from_raw_parts(self.data.as_ptr(), self.len) }
787 impl<'a, T> IntoIterator for &'a List<T> {
789 type IntoIter = <&'a [T] as IntoIterator>::IntoIter;
791 fn into_iter(self) -> Self::IntoIter {
796 impl<'tcx> rustc_serialize::UseSpecializedDecodable for &'tcx List<Ty<'tcx>> {}
800 pub fn empty<'a>() -> &'a List<T> {
801 #[repr(align(64), C)]
802 struct EmptySlice([u8; 64]);
803 static EMPTY_SLICE: EmptySlice = EmptySlice([0; 64]);
804 assert!(mem::align_of::<T>() <= 64);
805 unsafe { &*(&EMPTY_SLICE as *const _ as *const List<T>) }
809 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
810 pub struct UpvarPath {
811 pub hir_id: hir::HirId,
814 /// Upvars do not get their own `NodeId`. Instead, we use the pair of
815 /// the original var ID (that is, the root variable that is referenced
816 /// by the upvar) and the ID of the closure expression.
817 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
819 pub var_path: UpvarPath,
820 pub closure_expr_id: LocalDefId,
823 #[derive(Clone, PartialEq, Debug, RustcEncodable, RustcDecodable, Copy, HashStable)]
824 pub enum BorrowKind {
825 /// Data must be immutable and is aliasable.
828 /// Data must be immutable but not aliasable. This kind of borrow
829 /// cannot currently be expressed by the user and is used only in
830 /// implicit closure bindings. It is needed when the closure
831 /// is borrowing or mutating a mutable referent, e.g.:
833 /// let x: &mut isize = ...;
834 /// let y = || *x += 5;
836 /// If we were to try to translate this closure into a more explicit
837 /// form, we'd encounter an error with the code as written:
839 /// struct Env { x: & &mut isize }
840 /// let x: &mut isize = ...;
841 /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
842 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
844 /// This is then illegal because you cannot mutate a `&mut` found
845 /// in an aliasable location. To solve, you'd have to translate with
846 /// an `&mut` borrow:
848 /// struct Env { x: & &mut isize }
849 /// let x: &mut isize = ...;
850 /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
851 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
853 /// Now the assignment to `**env.x` is legal, but creating a
854 /// mutable pointer to `x` is not because `x` is not mutable. We
855 /// could fix this by declaring `x` as `let mut x`. This is ok in
856 /// user code, if awkward, but extra weird for closures, since the
857 /// borrow is hidden.
859 /// So we introduce a "unique imm" borrow -- the referent is
860 /// immutable, but not aliasable. This solves the problem. For
861 /// simplicity, we don't give users the way to express this
862 /// borrow, it's just used when translating closures.
865 /// Data is mutable and not aliasable.
869 /// Information describing the capture of an upvar. This is computed
870 /// during `typeck`, specifically by `regionck`.
871 #[derive(PartialEq, Clone, Debug, Copy, RustcEncodable, RustcDecodable, HashStable)]
872 pub enum UpvarCapture<'tcx> {
873 /// Upvar is captured by value. This is always true when the
874 /// closure is labeled `move`, but can also be true in other cases
875 /// depending on inference.
878 /// Upvar is captured by reference.
879 ByRef(UpvarBorrow<'tcx>),
882 #[derive(PartialEq, Clone, Copy, RustcEncodable, RustcDecodable, HashStable)]
883 pub struct UpvarBorrow<'tcx> {
884 /// The kind of borrow: by-ref upvars have access to shared
885 /// immutable borrows, which are not part of the normal language
887 pub kind: BorrowKind,
889 /// Region of the resulting reference.
890 pub region: ty::Region<'tcx>,
893 pub type UpvarListMap = FxHashMap<DefId, FxIndexMap<hir::HirId, UpvarId>>;
894 pub type UpvarCaptureMap<'tcx> = FxHashMap<UpvarId, UpvarCapture<'tcx>>;
896 #[derive(Clone, Copy, PartialEq, Eq)]
897 pub enum IntVarValue {
899 UintType(ast::UintTy),
902 #[derive(Clone, Copy, PartialEq, Eq)]
903 pub struct FloatVarValue(pub ast::FloatTy);
905 impl ty::EarlyBoundRegion {
906 pub fn to_bound_region(&self) -> ty::BoundRegion {
907 ty::BoundRegion::BrNamed(self.def_id, self.name)
910 /// Does this early bound region have a name? Early bound regions normally
911 /// always have names except when using anonymous lifetimes (`'_`).
912 pub fn has_name(&self) -> bool {
913 self.name != kw::UnderscoreLifetime
917 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
918 pub enum GenericParamDefKind {
922 object_lifetime_default: ObjectLifetimeDefault,
923 synthetic: Option<hir::SyntheticTyParamKind>,
928 impl GenericParamDefKind {
929 pub fn descr(&self) -> &'static str {
931 GenericParamDefKind::Lifetime => "lifetime",
932 GenericParamDefKind::Type { .. } => "type",
933 GenericParamDefKind::Const => "constant",
938 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
939 pub struct GenericParamDef {
944 /// `pure_wrt_drop`, set by the (unsafe) `#[may_dangle]` attribute
945 /// on generic parameter `'a`/`T`, asserts data behind the parameter
946 /// `'a`/`T` won't be accessed during the parent type's `Drop` impl.
947 pub pure_wrt_drop: bool,
949 pub kind: GenericParamDefKind,
952 impl GenericParamDef {
953 pub fn to_early_bound_region_data(&self) -> ty::EarlyBoundRegion {
954 if let GenericParamDefKind::Lifetime = self.kind {
955 ty::EarlyBoundRegion { def_id: self.def_id, index: self.index, name: self.name }
957 bug!("cannot convert a non-lifetime parameter def to an early bound region")
961 pub fn to_bound_region(&self) -> ty::BoundRegion {
962 if let GenericParamDefKind::Lifetime = self.kind {
963 self.to_early_bound_region_data().to_bound_region()
965 bug!("cannot convert a non-lifetime parameter def to an early bound region")
971 pub struct GenericParamCount {
972 pub lifetimes: usize,
977 /// Information about the formal type/lifetime parameters associated
978 /// with an item or method. Analogous to `hir::Generics`.
980 /// The ordering of parameters is the same as in `Subst` (excluding child generics):
981 /// `Self` (optionally), `Lifetime` params..., `Type` params...
982 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
983 pub struct Generics {
984 pub parent: Option<DefId>,
985 pub parent_count: usize,
986 pub params: Vec<GenericParamDef>,
988 /// Reverse map to the `index` field of each `GenericParamDef`.
989 #[stable_hasher(ignore)]
990 pub param_def_id_to_index: FxHashMap<DefId, u32>,
993 pub has_late_bound_regions: Option<Span>,
996 impl<'tcx> Generics {
997 pub fn count(&self) -> usize {
998 self.parent_count + self.params.len()
1001 pub fn own_counts(&self) -> GenericParamCount {
1002 // We could cache this as a property of `GenericParamCount`, but
1003 // the aim is to refactor this away entirely eventually and the
1004 // presence of this method will be a constant reminder.
1005 let mut own_counts: GenericParamCount = Default::default();
1007 for param in &self.params {
1009 GenericParamDefKind::Lifetime => own_counts.lifetimes += 1,
1010 GenericParamDefKind::Type { .. } => own_counts.types += 1,
1011 GenericParamDefKind::Const => own_counts.consts += 1,
1018 pub fn requires_monomorphization(&self, tcx: TyCtxt<'tcx>) -> bool {
1019 if self.own_requires_monomorphization() {
1023 if let Some(parent_def_id) = self.parent {
1024 let parent = tcx.generics_of(parent_def_id);
1025 parent.requires_monomorphization(tcx)
1031 pub fn own_requires_monomorphization(&self) -> bool {
1032 for param in &self.params {
1034 GenericParamDefKind::Type { .. } | GenericParamDefKind::Const => return true,
1035 GenericParamDefKind::Lifetime => {}
1041 pub fn param_at(&'tcx self, param_index: usize, tcx: TyCtxt<'tcx>) -> &'tcx GenericParamDef {
1042 if let Some(index) = param_index.checked_sub(self.parent_count) {
1045 tcx.generics_of(self.parent.expect("parent_count > 0 but no parent?"))
1046 .param_at(param_index, tcx)
1050 pub fn region_param(
1052 param: &EarlyBoundRegion,
1054 ) -> &'tcx GenericParamDef {
1055 let param = self.param_at(param.index as usize, tcx);
1057 GenericParamDefKind::Lifetime => param,
1058 _ => bug!("expected lifetime parameter, but found another generic parameter"),
1062 /// Returns the `GenericParamDef` associated with this `ParamTy`.
1063 pub fn type_param(&'tcx self, param: &ParamTy, tcx: TyCtxt<'tcx>) -> &'tcx GenericParamDef {
1064 let param = self.param_at(param.index as usize, tcx);
1066 GenericParamDefKind::Type { .. } => param,
1067 _ => bug!("expected type parameter, but found another generic parameter"),
1071 /// Returns the `ConstParameterDef` associated with this `ParamConst`.
1072 pub fn const_param(&'tcx self, param: &ParamConst, tcx: TyCtxt<'tcx>) -> &GenericParamDef {
1073 let param = self.param_at(param.index as usize, tcx);
1075 GenericParamDefKind::Const => param,
1076 _ => bug!("expected const parameter, but found another generic parameter"),
1081 /// Bounds on generics.
1082 #[derive(Copy, Clone, Default, Debug, RustcEncodable, RustcDecodable, HashStable)]
1083 pub struct GenericPredicates<'tcx> {
1084 pub parent: Option<DefId>,
1085 pub predicates: &'tcx [(Predicate<'tcx>, Span)],
1088 impl<'tcx> GenericPredicates<'tcx> {
1092 substs: SubstsRef<'tcx>,
1093 ) -> InstantiatedPredicates<'tcx> {
1094 let mut instantiated = InstantiatedPredicates::empty();
1095 self.instantiate_into(tcx, &mut instantiated, substs);
1099 pub fn instantiate_own(
1102 substs: SubstsRef<'tcx>,
1103 ) -> InstantiatedPredicates<'tcx> {
1104 InstantiatedPredicates {
1105 predicates: self.predicates.iter().map(|(p, _)| p.subst(tcx, substs)).collect(),
1106 spans: self.predicates.iter().map(|(_, sp)| *sp).collect(),
1110 fn instantiate_into(
1113 instantiated: &mut InstantiatedPredicates<'tcx>,
1114 substs: SubstsRef<'tcx>,
1116 if let Some(def_id) = self.parent {
1117 tcx.predicates_of(def_id).instantiate_into(tcx, instantiated, substs);
1119 instantiated.predicates.extend(self.predicates.iter().map(|(p, _)| p.subst(tcx, substs)));
1120 instantiated.spans.extend(self.predicates.iter().map(|(_, sp)| *sp));
1123 pub fn instantiate_identity(&self, tcx: TyCtxt<'tcx>) -> InstantiatedPredicates<'tcx> {
1124 let mut instantiated = InstantiatedPredicates::empty();
1125 self.instantiate_identity_into(tcx, &mut instantiated);
1129 fn instantiate_identity_into(
1132 instantiated: &mut InstantiatedPredicates<'tcx>,
1134 if let Some(def_id) = self.parent {
1135 tcx.predicates_of(def_id).instantiate_identity_into(tcx, instantiated);
1137 instantiated.predicates.extend(self.predicates.iter().map(|(p, _)| p));
1138 instantiated.spans.extend(self.predicates.iter().map(|(_, s)| s));
1141 pub fn instantiate_supertrait(
1144 poly_trait_ref: &ty::PolyTraitRef<'tcx>,
1145 ) -> InstantiatedPredicates<'tcx> {
1146 assert_eq!(self.parent, None);
1147 InstantiatedPredicates {
1151 .map(|(pred, _)| pred.subst_supertrait(tcx, poly_trait_ref))
1153 spans: self.predicates.iter().map(|(_, sp)| *sp).collect(),
1158 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1159 #[derive(HashStable, TypeFoldable)]
1160 pub enum Predicate<'tcx> {
1161 /// Corresponds to `where Foo: Bar<A, B, C>`. `Foo` here would be
1162 /// the `Self` type of the trait reference and `A`, `B`, and `C`
1163 /// would be the type parameters.
1165 /// A trait predicate will have `Constness::Const` if it originates
1166 /// from a bound on a `const fn` without the `?const` opt-out (e.g.,
1167 /// `const fn foobar<Foo: Bar>() {}`).
1168 Trait(PolyTraitPredicate<'tcx>, Constness),
1171 RegionOutlives(PolyRegionOutlivesPredicate<'tcx>),
1174 TypeOutlives(PolyTypeOutlivesPredicate<'tcx>),
1176 /// `where <T as TraitRef>::Name == X`, approximately.
1177 /// See the `ProjectionPredicate` struct for details.
1178 Projection(PolyProjectionPredicate<'tcx>),
1180 /// No syntax: `T` well-formed.
1181 WellFormed(Ty<'tcx>),
1183 /// Trait must be object-safe.
1186 /// No direct syntax. May be thought of as `where T: FnFoo<...>`
1187 /// for some substitutions `...` and `T` being a closure type.
1188 /// Satisfied (or refuted) once we know the closure's kind.
1189 ClosureKind(DefId, SubstsRef<'tcx>, ClosureKind),
1192 Subtype(PolySubtypePredicate<'tcx>),
1194 /// Constant initializer must evaluate successfully.
1195 ConstEvaluatable(DefId, SubstsRef<'tcx>),
1198 /// The crate outlives map is computed during typeck and contains the
1199 /// outlives of every item in the local crate. You should not use it
1200 /// directly, because to do so will make your pass dependent on the
1201 /// HIR of every item in the local crate. Instead, use
1202 /// `tcx.inferred_outlives_of()` to get the outlives for a *particular*
1204 #[derive(HashStable)]
1205 pub struct CratePredicatesMap<'tcx> {
1206 /// For each struct with outlive bounds, maps to a vector of the
1207 /// predicate of its outlive bounds. If an item has no outlives
1208 /// bounds, it will have no entry.
1209 pub predicates: FxHashMap<DefId, &'tcx [(ty::Predicate<'tcx>, Span)]>,
1212 impl<'tcx> AsRef<Predicate<'tcx>> for Predicate<'tcx> {
1213 fn as_ref(&self) -> &Predicate<'tcx> {
1218 impl<'tcx> Predicate<'tcx> {
1219 /// Performs a substitution suitable for going from a
1220 /// poly-trait-ref to supertraits that must hold if that
1221 /// poly-trait-ref holds. This is slightly different from a normal
1222 /// substitution in terms of what happens with bound regions. See
1223 /// lengthy comment below for details.
1224 pub fn subst_supertrait(
1227 trait_ref: &ty::PolyTraitRef<'tcx>,
1228 ) -> ty::Predicate<'tcx> {
1229 // The interaction between HRTB and supertraits is not entirely
1230 // obvious. Let me walk you (and myself) through an example.
1232 // Let's start with an easy case. Consider two traits:
1234 // trait Foo<'a>: Bar<'a,'a> { }
1235 // trait Bar<'b,'c> { }
1237 // Now, if we have a trait reference `for<'x> T: Foo<'x>`, then
1238 // we can deduce that `for<'x> T: Bar<'x,'x>`. Basically, if we
1239 // knew that `Foo<'x>` (for any 'x) then we also know that
1240 // `Bar<'x,'x>` (for any 'x). This more-or-less falls out from
1241 // normal substitution.
1243 // In terms of why this is sound, the idea is that whenever there
1244 // is an impl of `T:Foo<'a>`, it must show that `T:Bar<'a,'a>`
1245 // holds. So if there is an impl of `T:Foo<'a>` that applies to
1246 // all `'a`, then we must know that `T:Bar<'a,'a>` holds for all
1249 // Another example to be careful of is this:
1251 // trait Foo1<'a>: for<'b> Bar1<'a,'b> { }
1252 // trait Bar1<'b,'c> { }
1254 // Here, if we have `for<'x> T: Foo1<'x>`, then what do we know?
1255 // The answer is that we know `for<'x,'b> T: Bar1<'x,'b>`. The
1256 // reason is similar to the previous example: any impl of
1257 // `T:Foo1<'x>` must show that `for<'b> T: Bar1<'x, 'b>`. So
1258 // basically we would want to collapse the bound lifetimes from
1259 // the input (`trait_ref`) and the supertraits.
1261 // To achieve this in practice is fairly straightforward. Let's
1262 // consider the more complicated scenario:
1264 // - We start out with `for<'x> T: Foo1<'x>`. In this case, `'x`
1265 // has a De Bruijn index of 1. We want to produce `for<'x,'b> T: Bar1<'x,'b>`,
1266 // where both `'x` and `'b` would have a DB index of 1.
1267 // The substitution from the input trait-ref is therefore going to be
1268 // `'a => 'x` (where `'x` has a DB index of 1).
1269 // - The super-trait-ref is `for<'b> Bar1<'a,'b>`, where `'a` is an
1270 // early-bound parameter and `'b' is a late-bound parameter with a
1272 // - If we replace `'a` with `'x` from the input, it too will have
1273 // a DB index of 1, and thus we'll have `for<'x,'b> Bar1<'x,'b>`
1274 // just as we wanted.
1276 // There is only one catch. If we just apply the substitution `'a
1277 // => 'x` to `for<'b> Bar1<'a,'b>`, the substitution code will
1278 // adjust the DB index because we substituting into a binder (it
1279 // tries to be so smart...) resulting in `for<'x> for<'b>
1280 // Bar1<'x,'b>` (we have no syntax for this, so use your
1281 // imagination). Basically the 'x will have DB index of 2 and 'b
1282 // will have DB index of 1. Not quite what we want. So we apply
1283 // the substitution to the *contents* of the trait reference,
1284 // rather than the trait reference itself (put another way, the
1285 // substitution code expects equal binding levels in the values
1286 // from the substitution and the value being substituted into, and
1287 // this trick achieves that).
1289 let substs = &trait_ref.skip_binder().substs;
1291 Predicate::Trait(ref binder, constness) => {
1292 Predicate::Trait(binder.map_bound(|data| data.subst(tcx, substs)), constness)
1294 Predicate::Subtype(ref binder) => {
1295 Predicate::Subtype(binder.map_bound(|data| data.subst(tcx, substs)))
1297 Predicate::RegionOutlives(ref binder) => {
1298 Predicate::RegionOutlives(binder.map_bound(|data| data.subst(tcx, substs)))
1300 Predicate::TypeOutlives(ref binder) => {
1301 Predicate::TypeOutlives(binder.map_bound(|data| data.subst(tcx, substs)))
1303 Predicate::Projection(ref binder) => {
1304 Predicate::Projection(binder.map_bound(|data| data.subst(tcx, substs)))
1306 Predicate::WellFormed(data) => Predicate::WellFormed(data.subst(tcx, substs)),
1307 Predicate::ObjectSafe(trait_def_id) => Predicate::ObjectSafe(trait_def_id),
1308 Predicate::ClosureKind(closure_def_id, closure_substs, kind) => {
1309 Predicate::ClosureKind(closure_def_id, closure_substs.subst(tcx, substs), kind)
1311 Predicate::ConstEvaluatable(def_id, const_substs) => {
1312 Predicate::ConstEvaluatable(def_id, const_substs.subst(tcx, substs))
1318 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1319 #[derive(HashStable, TypeFoldable)]
1320 pub struct TraitPredicate<'tcx> {
1321 pub trait_ref: TraitRef<'tcx>,
1324 pub type PolyTraitPredicate<'tcx> = ty::Binder<TraitPredicate<'tcx>>;
1326 impl<'tcx> TraitPredicate<'tcx> {
1327 pub fn def_id(&self) -> DefId {
1328 self.trait_ref.def_id
1331 pub fn self_ty(&self) -> Ty<'tcx> {
1332 self.trait_ref.self_ty()
1336 impl<'tcx> PolyTraitPredicate<'tcx> {
1337 pub fn def_id(&self) -> DefId {
1338 // Ok to skip binder since trait `DefId` does not care about regions.
1339 self.skip_binder().def_id()
1343 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, RustcEncodable, RustcDecodable)]
1344 #[derive(HashStable, TypeFoldable)]
1345 pub struct OutlivesPredicate<A, B>(pub A, pub B); // `A: B`
1346 pub type PolyOutlivesPredicate<A, B> = ty::Binder<OutlivesPredicate<A, B>>;
1347 pub type RegionOutlivesPredicate<'tcx> = OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>;
1348 pub type TypeOutlivesPredicate<'tcx> = OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>;
1349 pub type PolyRegionOutlivesPredicate<'tcx> = ty::Binder<RegionOutlivesPredicate<'tcx>>;
1350 pub type PolyTypeOutlivesPredicate<'tcx> = ty::Binder<TypeOutlivesPredicate<'tcx>>;
1352 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
1353 #[derive(HashStable, TypeFoldable)]
1354 pub struct SubtypePredicate<'tcx> {
1355 pub a_is_expected: bool,
1359 pub type PolySubtypePredicate<'tcx> = ty::Binder<SubtypePredicate<'tcx>>;
1361 /// This kind of predicate has no *direct* correspondent in the
1362 /// syntax, but it roughly corresponds to the syntactic forms:
1364 /// 1. `T: TraitRef<..., Item = Type>`
1365 /// 2. `<T as TraitRef<...>>::Item == Type` (NYI)
1367 /// In particular, form #1 is "desugared" to the combination of a
1368 /// normal trait predicate (`T: TraitRef<...>`) and one of these
1369 /// predicates. Form #2 is a broader form in that it also permits
1370 /// equality between arbitrary types. Processing an instance of
1371 /// Form #2 eventually yields one of these `ProjectionPredicate`
1372 /// instances to normalize the LHS.
1373 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1374 #[derive(HashStable, TypeFoldable)]
1375 pub struct ProjectionPredicate<'tcx> {
1376 pub projection_ty: ProjectionTy<'tcx>,
1380 pub type PolyProjectionPredicate<'tcx> = Binder<ProjectionPredicate<'tcx>>;
1382 impl<'tcx> PolyProjectionPredicate<'tcx> {
1383 /// Returns the `DefId` of the associated item being projected.
1384 pub fn item_def_id(&self) -> DefId {
1385 self.skip_binder().projection_ty.item_def_id
1389 pub fn to_poly_trait_ref(&self, tcx: TyCtxt<'tcx>) -> PolyTraitRef<'tcx> {
1390 // Note: unlike with `TraitRef::to_poly_trait_ref()`,
1391 // `self.0.trait_ref` is permitted to have escaping regions.
1392 // This is because here `self` has a `Binder` and so does our
1393 // return value, so we are preserving the number of binding
1395 self.map_bound(|predicate| predicate.projection_ty.trait_ref(tcx))
1398 pub fn ty(&self) -> Binder<Ty<'tcx>> {
1399 self.map_bound(|predicate| predicate.ty)
1402 /// The `DefId` of the `TraitItem` for the associated type.
1404 /// Note that this is not the `DefId` of the `TraitRef` containing this
1405 /// associated type, which is in `tcx.associated_item(projection_def_id()).container`.
1406 pub fn projection_def_id(&self) -> DefId {
1407 // Ok to skip binder since trait `DefId` does not care about regions.
1408 self.skip_binder().projection_ty.item_def_id
1412 pub trait ToPolyTraitRef<'tcx> {
1413 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx>;
1416 impl<'tcx> ToPolyTraitRef<'tcx> for TraitRef<'tcx> {
1417 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
1418 ty::Binder::dummy(*self)
1422 impl<'tcx> ToPolyTraitRef<'tcx> for PolyTraitPredicate<'tcx> {
1423 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
1424 self.map_bound_ref(|trait_pred| trait_pred.trait_ref)
1428 pub trait ToPredicate<'tcx> {
1429 fn to_predicate(&self) -> Predicate<'tcx>;
1432 impl<'tcx> ToPredicate<'tcx> for ConstnessAnd<TraitRef<'tcx>> {
1433 fn to_predicate(&self) -> Predicate<'tcx> {
1434 ty::Predicate::Trait(
1435 ty::Binder::dummy(ty::TraitPredicate { trait_ref: self.value }),
1441 impl<'tcx> ToPredicate<'tcx> for ConstnessAnd<&TraitRef<'tcx>> {
1442 fn to_predicate(&self) -> Predicate<'tcx> {
1443 ty::Predicate::Trait(
1444 ty::Binder::dummy(ty::TraitPredicate { trait_ref: *self.value }),
1450 impl<'tcx> ToPredicate<'tcx> for ConstnessAnd<PolyTraitRef<'tcx>> {
1451 fn to_predicate(&self) -> Predicate<'tcx> {
1452 ty::Predicate::Trait(self.value.to_poly_trait_predicate(), self.constness)
1456 impl<'tcx> ToPredicate<'tcx> for ConstnessAnd<&PolyTraitRef<'tcx>> {
1457 fn to_predicate(&self) -> Predicate<'tcx> {
1458 ty::Predicate::Trait(self.value.to_poly_trait_predicate(), self.constness)
1462 impl<'tcx> ToPredicate<'tcx> for PolyRegionOutlivesPredicate<'tcx> {
1463 fn to_predicate(&self) -> Predicate<'tcx> {
1464 Predicate::RegionOutlives(*self)
1468 impl<'tcx> ToPredicate<'tcx> for PolyTypeOutlivesPredicate<'tcx> {
1469 fn to_predicate(&self) -> Predicate<'tcx> {
1470 Predicate::TypeOutlives(*self)
1474 impl<'tcx> ToPredicate<'tcx> for PolyProjectionPredicate<'tcx> {
1475 fn to_predicate(&self) -> Predicate<'tcx> {
1476 Predicate::Projection(*self)
1480 impl<'tcx> Predicate<'tcx> {
1481 pub fn to_opt_poly_trait_ref(&self) -> Option<PolyTraitRef<'tcx>> {
1483 Predicate::Trait(ref t, _) => Some(t.to_poly_trait_ref()),
1484 Predicate::Projection(..)
1485 | Predicate::Subtype(..)
1486 | Predicate::RegionOutlives(..)
1487 | Predicate::WellFormed(..)
1488 | Predicate::ObjectSafe(..)
1489 | Predicate::ClosureKind(..)
1490 | Predicate::TypeOutlives(..)
1491 | Predicate::ConstEvaluatable(..) => None,
1495 pub fn to_opt_type_outlives(&self) -> Option<PolyTypeOutlivesPredicate<'tcx>> {
1497 Predicate::TypeOutlives(data) => Some(data),
1498 Predicate::Trait(..)
1499 | Predicate::Projection(..)
1500 | Predicate::Subtype(..)
1501 | Predicate::RegionOutlives(..)
1502 | Predicate::WellFormed(..)
1503 | Predicate::ObjectSafe(..)
1504 | Predicate::ClosureKind(..)
1505 | Predicate::ConstEvaluatable(..) => None,
1510 /// Represents the bounds declared on a particular set of type
1511 /// parameters. Should eventually be generalized into a flag list of
1512 /// where-clauses. You can obtain a `InstantiatedPredicates` list from a
1513 /// `GenericPredicates` by using the `instantiate` method. Note that this method
1514 /// reflects an important semantic invariant of `InstantiatedPredicates`: while
1515 /// the `GenericPredicates` are expressed in terms of the bound type
1516 /// parameters of the impl/trait/whatever, an `InstantiatedPredicates` instance
1517 /// represented a set of bounds for some particular instantiation,
1518 /// meaning that the generic parameters have been substituted with
1523 /// struct Foo<T, U: Bar<T>> { ... }
1525 /// Here, the `GenericPredicates` for `Foo` would contain a list of bounds like
1526 /// `[[], [U:Bar<T>]]`. Now if there were some particular reference
1527 /// like `Foo<isize,usize>`, then the `InstantiatedPredicates` would be `[[],
1528 /// [usize:Bar<isize>]]`.
1529 #[derive(Clone, Debug, TypeFoldable)]
1530 pub struct InstantiatedPredicates<'tcx> {
1531 pub predicates: Vec<Predicate<'tcx>>,
1532 pub spans: Vec<Span>,
1535 impl<'tcx> InstantiatedPredicates<'tcx> {
1536 pub fn empty() -> InstantiatedPredicates<'tcx> {
1537 InstantiatedPredicates { predicates: vec![], spans: vec![] }
1540 pub fn is_empty(&self) -> bool {
1541 self.predicates.is_empty()
1545 rustc_index::newtype_index! {
1546 /// "Universes" are used during type- and trait-checking in the
1547 /// presence of `for<..>` binders to control what sets of names are
1548 /// visible. Universes are arranged into a tree: the root universe
1549 /// contains names that are always visible. Each child then adds a new
1550 /// set of names that are visible, in addition to those of its parent.
1551 /// We say that the child universe "extends" the parent universe with
1554 /// To make this more concrete, consider this program:
1558 /// fn bar<T>(x: T) {
1559 /// let y: for<'a> fn(&'a u8, Foo) = ...;
1563 /// The struct name `Foo` is in the root universe U0. But the type
1564 /// parameter `T`, introduced on `bar`, is in an extended universe U1
1565 /// -- i.e., within `bar`, we can name both `T` and `Foo`, but outside
1566 /// of `bar`, we cannot name `T`. Then, within the type of `y`, the
1567 /// region `'a` is in a universe U2 that extends U1, because we can
1568 /// name it inside the fn type but not outside.
1570 /// Universes are used to do type- and trait-checking around these
1571 /// "forall" binders (also called **universal quantification**). The
1572 /// idea is that when, in the body of `bar`, we refer to `T` as a
1573 /// type, we aren't referring to any type in particular, but rather a
1574 /// kind of "fresh" type that is distinct from all other types we have
1575 /// actually declared. This is called a **placeholder** type, and we
1576 /// use universes to talk about this. In other words, a type name in
1577 /// universe 0 always corresponds to some "ground" type that the user
1578 /// declared, but a type name in a non-zero universe is a placeholder
1579 /// type -- an idealized representative of "types in general" that we
1580 /// use for checking generic functions.
1581 pub struct UniverseIndex {
1583 DEBUG_FORMAT = "U{}",
1587 impl UniverseIndex {
1588 pub const ROOT: UniverseIndex = UniverseIndex::from_u32(0);
1590 /// Returns the "next" universe index in order -- this new index
1591 /// is considered to extend all previous universes. This
1592 /// corresponds to entering a `forall` quantifier. So, for
1593 /// example, suppose we have this type in universe `U`:
1596 /// for<'a> fn(&'a u32)
1599 /// Once we "enter" into this `for<'a>` quantifier, we are in a
1600 /// new universe that extends `U` -- in this new universe, we can
1601 /// name the region `'a`, but that region was not nameable from
1602 /// `U` because it was not in scope there.
1603 pub fn next_universe(self) -> UniverseIndex {
1604 UniverseIndex::from_u32(self.private.checked_add(1).unwrap())
1607 /// Returns `true` if `self` can name a name from `other` -- in other words,
1608 /// if the set of names in `self` is a superset of those in
1609 /// `other` (`self >= other`).
1610 pub fn can_name(self, other: UniverseIndex) -> bool {
1611 self.private >= other.private
1614 /// Returns `true` if `self` cannot name some names from `other` -- in other
1615 /// words, if the set of names in `self` is a strict subset of
1616 /// those in `other` (`self < other`).
1617 pub fn cannot_name(self, other: UniverseIndex) -> bool {
1618 self.private < other.private
1622 /// The "placeholder index" fully defines a placeholder region.
1623 /// Placeholder regions are identified by both a **universe** as well
1624 /// as a "bound-region" within that universe. The `bound_region` is
1625 /// basically a name -- distinct bound regions within the same
1626 /// universe are just two regions with an unknown relationship to one
1628 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, PartialOrd, Ord)]
1629 pub struct Placeholder<T> {
1630 pub universe: UniverseIndex,
1634 impl<'a, T> HashStable<StableHashingContext<'a>> for Placeholder<T>
1636 T: HashStable<StableHashingContext<'a>>,
1638 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
1639 self.universe.hash_stable(hcx, hasher);
1640 self.name.hash_stable(hcx, hasher);
1644 pub type PlaceholderRegion = Placeholder<BoundRegion>;
1646 pub type PlaceholderType = Placeholder<BoundVar>;
1648 pub type PlaceholderConst = Placeholder<BoundVar>;
1650 /// When type checking, we use the `ParamEnv` to track
1651 /// details about the set of where-clauses that are in scope at this
1652 /// particular point.
1653 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable, TypeFoldable)]
1654 pub struct ParamEnv<'tcx> {
1655 /// `Obligation`s that the caller must satisfy. This is basically
1656 /// the set of bounds on the in-scope type parameters, translated
1657 /// into `Obligation`s, and elaborated and normalized.
1658 pub caller_bounds: &'tcx List<ty::Predicate<'tcx>>,
1660 /// Typically, this is `Reveal::UserFacing`, but during codegen we
1661 /// want `Reveal::All` -- note that this is always paired with an
1662 /// empty environment. To get that, use `ParamEnv::reveal()`.
1663 pub reveal: traits::Reveal,
1665 /// If this `ParamEnv` comes from a call to `tcx.param_env(def_id)`,
1666 /// register that `def_id` (useful for transitioning to the chalk trait
1668 pub def_id: Option<DefId>,
1671 impl<'tcx> ParamEnv<'tcx> {
1672 /// Construct a trait environment suitable for contexts where
1673 /// there are no where-clauses in scope. Hidden types (like `impl
1674 /// Trait`) are left hidden, so this is suitable for ordinary
1677 pub fn empty() -> Self {
1678 Self::new(List::empty(), Reveal::UserFacing, None)
1681 /// Construct a trait environment with no where-clauses in scope
1682 /// where the values of all `impl Trait` and other hidden types
1683 /// are revealed. This is suitable for monomorphized, post-typeck
1684 /// environments like codegen or doing optimizations.
1686 /// N.B., if you want to have predicates in scope, use `ParamEnv::new`,
1687 /// or invoke `param_env.with_reveal_all()`.
1689 pub fn reveal_all() -> Self {
1690 Self::new(List::empty(), Reveal::All, None)
1693 /// Construct a trait environment with the given set of predicates.
1696 caller_bounds: &'tcx List<ty::Predicate<'tcx>>,
1698 def_id: Option<DefId>,
1700 ty::ParamEnv { caller_bounds, reveal, def_id }
1703 /// Returns a new parameter environment with the same clauses, but
1704 /// which "reveals" the true results of projections in all cases
1705 /// (even for associated types that are specializable). This is
1706 /// the desired behavior during codegen and certain other special
1707 /// contexts; normally though we want to use `Reveal::UserFacing`,
1708 /// which is the default.
1709 pub fn with_reveal_all(self) -> Self {
1710 ty::ParamEnv { reveal: Reveal::All, ..self }
1713 /// Returns this same environment but with no caller bounds.
1714 pub fn without_caller_bounds(self) -> Self {
1715 ty::ParamEnv { caller_bounds: List::empty(), ..self }
1718 /// Creates a suitable environment in which to perform trait
1719 /// queries on the given value. When type-checking, this is simply
1720 /// the pair of the environment plus value. But when reveal is set to
1721 /// All, then if `value` does not reference any type parameters, we will
1722 /// pair it with the empty environment. This improves caching and is generally
1725 /// N.B., we preserve the environment when type-checking because it
1726 /// is possible for the user to have wacky where-clauses like
1727 /// `where Box<u32>: Copy`, which are clearly never
1728 /// satisfiable. We generally want to behave as if they were true,
1729 /// although the surrounding function is never reachable.
1730 pub fn and<T: TypeFoldable<'tcx>>(self, value: T) -> ParamEnvAnd<'tcx, T> {
1732 Reveal::UserFacing => ParamEnvAnd { param_env: self, value },
1735 if value.is_global() {
1736 ParamEnvAnd { param_env: self.without_caller_bounds(), value }
1738 ParamEnvAnd { param_env: self, value }
1745 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1746 pub struct ConstnessAnd<T> {
1747 pub constness: Constness,
1751 // FIXME(ecstaticmorse): Audit all occurrences of `without_const().to_predicate()` to ensure that
1752 // the constness of trait bounds is being propagated correctly.
1753 pub trait WithConstness: Sized {
1755 fn with_constness(self, constness: Constness) -> ConstnessAnd<Self> {
1756 ConstnessAnd { constness, value: self }
1760 fn with_const(self) -> ConstnessAnd<Self> {
1761 self.with_constness(Constness::Const)
1765 fn without_const(self) -> ConstnessAnd<Self> {
1766 self.with_constness(Constness::NotConst)
1770 impl<T> WithConstness for T {}
1772 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TypeFoldable)]
1773 pub struct ParamEnvAnd<'tcx, T> {
1774 pub param_env: ParamEnv<'tcx>,
1778 impl<'tcx, T> ParamEnvAnd<'tcx, T> {
1779 pub fn into_parts(self) -> (ParamEnv<'tcx>, T) {
1780 (self.param_env, self.value)
1784 impl<'a, 'tcx, T> HashStable<StableHashingContext<'a>> for ParamEnvAnd<'tcx, T>
1786 T: HashStable<StableHashingContext<'a>>,
1788 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
1789 let ParamEnvAnd { ref param_env, ref value } = *self;
1791 param_env.hash_stable(hcx, hasher);
1792 value.hash_stable(hcx, hasher);
1796 #[derive(Copy, Clone, Debug, HashStable)]
1797 pub struct Destructor {
1798 /// The `DefId` of the destructor method
1803 #[derive(HashStable)]
1804 pub struct AdtFlags: u32 {
1805 const NO_ADT_FLAGS = 0;
1806 /// Indicates whether the ADT is an enum.
1807 const IS_ENUM = 1 << 0;
1808 /// Indicates whether the ADT is a union.
1809 const IS_UNION = 1 << 1;
1810 /// Indicates whether the ADT is a struct.
1811 const IS_STRUCT = 1 << 2;
1812 /// Indicates whether the ADT is a struct and has a constructor.
1813 const HAS_CTOR = 1 << 3;
1814 /// Indicates whether the type is `PhantomData`.
1815 const IS_PHANTOM_DATA = 1 << 4;
1816 /// Indicates whether the type has a `#[fundamental]` attribute.
1817 const IS_FUNDAMENTAL = 1 << 5;
1818 /// Indicates whether the type is `Box`.
1819 const IS_BOX = 1 << 6;
1820 /// Indicates whether the type is `ManuallyDrop`.
1821 const IS_MANUALLY_DROP = 1 << 7;
1822 /// Indicates whether the variant list of this ADT is `#[non_exhaustive]`.
1823 /// (i.e., this flag is never set unless this ADT is an enum).
1824 const IS_VARIANT_LIST_NON_EXHAUSTIVE = 1 << 8;
1829 #[derive(HashStable)]
1830 pub struct VariantFlags: u32 {
1831 const NO_VARIANT_FLAGS = 0;
1832 /// Indicates whether the field list of this variant is `#[non_exhaustive]`.
1833 const IS_FIELD_LIST_NON_EXHAUSTIVE = 1 << 0;
1837 /// Definition of a variant -- a struct's fields or a enum variant.
1838 #[derive(Debug, HashStable)]
1839 pub struct VariantDef {
1840 /// `DefId` that identifies the variant itself.
1841 /// If this variant belongs to a struct or union, then this is a copy of its `DefId`.
1843 /// `DefId` that identifies the variant's constructor.
1844 /// If this variant is a struct variant, then this is `None`.
1845 pub ctor_def_id: Option<DefId>,
1846 /// Variant or struct name.
1847 #[stable_hasher(project(name))]
1849 /// Discriminant of this variant.
1850 pub discr: VariantDiscr,
1851 /// Fields of this variant.
1852 pub fields: Vec<FieldDef>,
1853 /// Type of constructor of variant.
1854 pub ctor_kind: CtorKind,
1855 /// Flags of the variant (e.g. is field list non-exhaustive)?
1856 flags: VariantFlags,
1857 /// Variant is obtained as part of recovering from a syntactic error.
1858 /// May be incomplete or bogus.
1859 pub recovered: bool,
1862 impl<'tcx> VariantDef {
1863 /// Creates a new `VariantDef`.
1865 /// `variant_did` is the `DefId` that identifies the enum variant (if this `VariantDef`
1866 /// represents an enum variant).
1868 /// `ctor_did` is the `DefId` that identifies the constructor of unit or
1869 /// tuple-variants/structs. If this is a `struct`-variant then this should be `None`.
1871 /// `parent_did` is the `DefId` of the `AdtDef` representing the enum or struct that
1872 /// owns this variant. It is used for checking if a struct has `#[non_exhaustive]` w/out having
1873 /// to go through the redirect of checking the ctor's attributes - but compiling a small crate
1874 /// requires loading the `AdtDef`s for all the structs in the universe (e.g., coherence for any
1875 /// built-in trait), and we do not want to load attributes twice.
1877 /// If someone speeds up attribute loading to not be a performance concern, they can
1878 /// remove this hack and use the constructor `DefId` everywhere.
1882 variant_did: Option<DefId>,
1883 ctor_def_id: Option<DefId>,
1884 discr: VariantDiscr,
1885 fields: Vec<FieldDef>,
1886 ctor_kind: CtorKind,
1892 "VariantDef::new(ident = {:?}, variant_did = {:?}, ctor_def_id = {:?}, discr = {:?},
1893 fields = {:?}, ctor_kind = {:?}, adt_kind = {:?}, parent_did = {:?})",
1894 ident, variant_did, ctor_def_id, discr, fields, ctor_kind, adt_kind, parent_did,
1897 let mut flags = VariantFlags::NO_VARIANT_FLAGS;
1898 if adt_kind == AdtKind::Struct && tcx.has_attr(parent_did, sym::non_exhaustive) {
1899 debug!("found non-exhaustive field list for {:?}", parent_did);
1900 flags = flags | VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE;
1901 } else if let Some(variant_did) = variant_did {
1902 if tcx.has_attr(variant_did, sym::non_exhaustive) {
1903 debug!("found non-exhaustive field list for {:?}", variant_did);
1904 flags = flags | VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE;
1909 def_id: variant_did.unwrap_or(parent_did),
1920 /// Is this field list non-exhaustive?
1922 pub fn is_field_list_non_exhaustive(&self) -> bool {
1923 self.flags.intersects(VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE)
1927 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
1928 pub enum VariantDiscr {
1929 /// Explicit value for this variant, i.e., `X = 123`.
1930 /// The `DefId` corresponds to the embedded constant.
1933 /// The previous variant's discriminant plus one.
1934 /// For efficiency reasons, the distance from the
1935 /// last `Explicit` discriminant is being stored,
1936 /// or `0` for the first variant, if it has none.
1940 #[derive(Debug, HashStable)]
1941 pub struct FieldDef {
1943 #[stable_hasher(project(name))]
1945 pub vis: Visibility,
1948 /// The definition of a user-defined type, e.g., a `struct`, `enum`, or `union`.
1950 /// These are all interned (by `intern_adt_def`) into the `adt_defs` table.
1952 /// The initialism *ADT* stands for an [*algebraic data type (ADT)*][adt].
1953 /// This is slightly wrong because `union`s are not ADTs.
1954 /// Moreover, Rust only allows recursive data types through indirection.
1956 /// [adt]: https://en.wikipedia.org/wiki/Algebraic_data_type
1958 /// The `DefId` of the struct, enum or union item.
1960 /// Variants of the ADT. If this is a struct or union, then there will be a single variant.
1961 pub variants: IndexVec<VariantIdx, VariantDef>,
1962 /// Flags of the ADT (e.g., is this a struct? is this non-exhaustive?).
1964 /// Repr options provided by the user.
1965 pub repr: ReprOptions,
1968 impl PartialOrd for AdtDef {
1969 fn partial_cmp(&self, other: &AdtDef) -> Option<Ordering> {
1970 Some(self.cmp(&other))
1974 /// There should be only one AdtDef for each `did`, therefore
1975 /// it is fine to implement `Ord` only based on `did`.
1976 impl Ord for AdtDef {
1977 fn cmp(&self, other: &AdtDef) -> Ordering {
1978 self.did.cmp(&other.did)
1982 impl PartialEq for AdtDef {
1983 // `AdtDef`s are always interned, and this is part of `TyS` equality.
1985 fn eq(&self, other: &Self) -> bool {
1986 ptr::eq(self, other)
1990 impl Eq for AdtDef {}
1992 impl Hash for AdtDef {
1994 fn hash<H: Hasher>(&self, s: &mut H) {
1995 (self as *const AdtDef).hash(s)
1999 impl<'tcx> rustc_serialize::UseSpecializedEncodable for &'tcx AdtDef {
2000 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
2005 impl<'tcx> rustc_serialize::UseSpecializedDecodable for &'tcx AdtDef {}
2007 impl<'a> HashStable<StableHashingContext<'a>> for AdtDef {
2008 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
2010 static CACHE: RefCell<FxHashMap<usize, Fingerprint>> = Default::default();
2013 let hash: Fingerprint = CACHE.with(|cache| {
2014 let addr = self as *const AdtDef as usize;
2015 *cache.borrow_mut().entry(addr).or_insert_with(|| {
2016 let ty::AdtDef { did, ref variants, ref flags, ref repr } = *self;
2018 let mut hasher = StableHasher::new();
2019 did.hash_stable(hcx, &mut hasher);
2020 variants.hash_stable(hcx, &mut hasher);
2021 flags.hash_stable(hcx, &mut hasher);
2022 repr.hash_stable(hcx, &mut hasher);
2028 hash.hash_stable(hcx, hasher);
2032 #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
2039 impl Into<DataTypeKind> for AdtKind {
2040 fn into(self) -> DataTypeKind {
2042 AdtKind::Struct => DataTypeKind::Struct,
2043 AdtKind::Union => DataTypeKind::Union,
2044 AdtKind::Enum => DataTypeKind::Enum,
2050 #[derive(RustcEncodable, RustcDecodable, Default, HashStable)]
2051 pub struct ReprFlags: u8 {
2052 const IS_C = 1 << 0;
2053 const IS_SIMD = 1 << 1;
2054 const IS_TRANSPARENT = 1 << 2;
2055 // Internal only for now. If true, don't reorder fields.
2056 const IS_LINEAR = 1 << 3;
2057 // If true, don't expose any niche to type's context.
2058 const HIDE_NICHE = 1 << 4;
2059 // Any of these flags being set prevent field reordering optimisation.
2060 const IS_UNOPTIMISABLE = ReprFlags::IS_C.bits |
2061 ReprFlags::IS_SIMD.bits |
2062 ReprFlags::IS_LINEAR.bits;
2066 /// Represents the repr options provided by the user,
2067 #[derive(Copy, Clone, Debug, Eq, PartialEq, RustcEncodable, RustcDecodable, Default, HashStable)]
2068 pub struct ReprOptions {
2069 pub int: Option<attr::IntType>,
2070 pub align: Option<Align>,
2071 pub pack: Option<Align>,
2072 pub flags: ReprFlags,
2076 pub fn new(tcx: TyCtxt<'_>, did: DefId) -> ReprOptions {
2077 let mut flags = ReprFlags::empty();
2078 let mut size = None;
2079 let mut max_align: Option<Align> = None;
2080 let mut min_pack: Option<Align> = None;
2081 for attr in tcx.get_attrs(did).iter() {
2082 for r in attr::find_repr_attrs(&tcx.sess.parse_sess, attr) {
2083 flags.insert(match r {
2084 attr::ReprC => ReprFlags::IS_C,
2085 attr::ReprPacked(pack) => {
2086 let pack = Align::from_bytes(pack as u64).unwrap();
2087 min_pack = Some(if let Some(min_pack) = min_pack {
2094 attr::ReprTransparent => ReprFlags::IS_TRANSPARENT,
2095 attr::ReprNoNiche => ReprFlags::HIDE_NICHE,
2096 attr::ReprSimd => ReprFlags::IS_SIMD,
2097 attr::ReprInt(i) => {
2101 attr::ReprAlign(align) => {
2102 max_align = max_align.max(Some(Align::from_bytes(align as u64).unwrap()));
2109 // This is here instead of layout because the choice must make it into metadata.
2110 if !tcx.consider_optimizing(|| format!("Reorder fields of {:?}", tcx.def_path_str(did))) {
2111 flags.insert(ReprFlags::IS_LINEAR);
2113 ReprOptions { int: size, align: max_align, pack: min_pack, flags }
2117 pub fn simd(&self) -> bool {
2118 self.flags.contains(ReprFlags::IS_SIMD)
2121 pub fn c(&self) -> bool {
2122 self.flags.contains(ReprFlags::IS_C)
2125 pub fn packed(&self) -> bool {
2129 pub fn transparent(&self) -> bool {
2130 self.flags.contains(ReprFlags::IS_TRANSPARENT)
2133 pub fn linear(&self) -> bool {
2134 self.flags.contains(ReprFlags::IS_LINEAR)
2137 pub fn hide_niche(&self) -> bool {
2138 self.flags.contains(ReprFlags::HIDE_NICHE)
2141 pub fn discr_type(&self) -> attr::IntType {
2142 self.int.unwrap_or(attr::SignedInt(ast::IntTy::Isize))
2145 /// Returns `true` if this `#[repr()]` should inhabit "smart enum
2146 /// layout" optimizations, such as representing `Foo<&T>` as a
2148 pub fn inhibit_enum_layout_opt(&self) -> bool {
2149 self.c() || self.int.is_some()
2152 /// Returns `true` if this `#[repr()]` should inhibit struct field reordering
2153 /// optimizations, such as with `repr(C)`, `repr(packed(1))`, or `repr(<int>)`.
2154 pub fn inhibit_struct_field_reordering_opt(&self) -> bool {
2155 if let Some(pack) = self.pack {
2156 if pack.bytes() == 1 {
2160 self.flags.intersects(ReprFlags::IS_UNOPTIMISABLE) || self.int.is_some()
2163 /// Returns `true` if this `#[repr()]` should inhibit union ABI optimisations.
2164 pub fn inhibit_union_abi_opt(&self) -> bool {
2170 /// Creates a new `AdtDef`.
2175 variants: IndexVec<VariantIdx, VariantDef>,
2178 debug!("AdtDef::new({:?}, {:?}, {:?}, {:?})", did, kind, variants, repr);
2179 let mut flags = AdtFlags::NO_ADT_FLAGS;
2181 if kind == AdtKind::Enum && tcx.has_attr(did, sym::non_exhaustive) {
2182 debug!("found non-exhaustive variant list for {:?}", did);
2183 flags = flags | AdtFlags::IS_VARIANT_LIST_NON_EXHAUSTIVE;
2186 flags |= match kind {
2187 AdtKind::Enum => AdtFlags::IS_ENUM,
2188 AdtKind::Union => AdtFlags::IS_UNION,
2189 AdtKind::Struct => AdtFlags::IS_STRUCT,
2192 if kind == AdtKind::Struct && variants[VariantIdx::new(0)].ctor_def_id.is_some() {
2193 flags |= AdtFlags::HAS_CTOR;
2196 let attrs = tcx.get_attrs(did);
2197 if attr::contains_name(&attrs, sym::fundamental) {
2198 flags |= AdtFlags::IS_FUNDAMENTAL;
2200 if Some(did) == tcx.lang_items().phantom_data() {
2201 flags |= AdtFlags::IS_PHANTOM_DATA;
2203 if Some(did) == tcx.lang_items().owned_box() {
2204 flags |= AdtFlags::IS_BOX;
2206 if Some(did) == tcx.lang_items().manually_drop() {
2207 flags |= AdtFlags::IS_MANUALLY_DROP;
2210 AdtDef { did, variants, flags, repr }
2213 /// Returns `true` if this is a struct.
2215 pub fn is_struct(&self) -> bool {
2216 self.flags.contains(AdtFlags::IS_STRUCT)
2219 /// Returns `true` if this is a union.
2221 pub fn is_union(&self) -> bool {
2222 self.flags.contains(AdtFlags::IS_UNION)
2225 /// Returns `true` if this is a enum.
2227 pub fn is_enum(&self) -> bool {
2228 self.flags.contains(AdtFlags::IS_ENUM)
2231 /// Returns `true` if the variant list of this ADT is `#[non_exhaustive]`.
2233 pub fn is_variant_list_non_exhaustive(&self) -> bool {
2234 self.flags.contains(AdtFlags::IS_VARIANT_LIST_NON_EXHAUSTIVE)
2237 /// Returns the kind of the ADT.
2239 pub fn adt_kind(&self) -> AdtKind {
2242 } else if self.is_union() {
2249 /// Returns a description of this abstract data type.
2250 pub fn descr(&self) -> &'static str {
2251 match self.adt_kind() {
2252 AdtKind::Struct => "struct",
2253 AdtKind::Union => "union",
2254 AdtKind::Enum => "enum",
2258 /// Returns a description of a variant of this abstract data type.
2260 pub fn variant_descr(&self) -> &'static str {
2261 match self.adt_kind() {
2262 AdtKind::Struct => "struct",
2263 AdtKind::Union => "union",
2264 AdtKind::Enum => "variant",
2268 /// If this function returns `true`, it implies that `is_struct` must return `true`.
2270 pub fn has_ctor(&self) -> bool {
2271 self.flags.contains(AdtFlags::HAS_CTOR)
2274 /// Returns `true` if this type is `#[fundamental]` for the purposes
2275 /// of coherence checking.
2277 pub fn is_fundamental(&self) -> bool {
2278 self.flags.contains(AdtFlags::IS_FUNDAMENTAL)
2281 /// Returns `true` if this is `PhantomData<T>`.
2283 pub fn is_phantom_data(&self) -> bool {
2284 self.flags.contains(AdtFlags::IS_PHANTOM_DATA)
2287 /// Returns `true` if this is Box<T>.
2289 pub fn is_box(&self) -> bool {
2290 self.flags.contains(AdtFlags::IS_BOX)
2293 /// Returns `true` if this is `ManuallyDrop<T>`.
2295 pub fn is_manually_drop(&self) -> bool {
2296 self.flags.contains(AdtFlags::IS_MANUALLY_DROP)
2299 /// Returns `true` if this type has a destructor.
2300 pub fn has_dtor(&self, tcx: TyCtxt<'tcx>) -> bool {
2301 self.destructor(tcx).is_some()
2304 /// Asserts this is a struct or union and returns its unique variant.
2305 pub fn non_enum_variant(&self) -> &VariantDef {
2306 assert!(self.is_struct() || self.is_union());
2307 &self.variants[VariantIdx::new(0)]
2311 pub fn predicates(&self, tcx: TyCtxt<'tcx>) -> GenericPredicates<'tcx> {
2312 tcx.predicates_of(self.did)
2315 /// Returns an iterator over all fields contained
2318 pub fn all_fields(&self) -> impl Iterator<Item = &FieldDef> + Clone {
2319 self.variants.iter().flat_map(|v| v.fields.iter())
2322 pub fn is_payloadfree(&self) -> bool {
2323 !self.variants.is_empty() && self.variants.iter().all(|v| v.fields.is_empty())
2326 /// Return a `VariantDef` given a variant id.
2327 pub fn variant_with_id(&self, vid: DefId) -> &VariantDef {
2328 self.variants.iter().find(|v| v.def_id == vid).expect("variant_with_id: unknown variant")
2331 /// Return a `VariantDef` given a constructor id.
2332 pub fn variant_with_ctor_id(&self, cid: DefId) -> &VariantDef {
2335 .find(|v| v.ctor_def_id == Some(cid))
2336 .expect("variant_with_ctor_id: unknown variant")
2339 /// Return the index of `VariantDef` given a variant id.
2340 pub fn variant_index_with_id(&self, vid: DefId) -> VariantIdx {
2343 .find(|(_, v)| v.def_id == vid)
2344 .expect("variant_index_with_id: unknown variant")
2348 /// Return the index of `VariantDef` given a constructor id.
2349 pub fn variant_index_with_ctor_id(&self, cid: DefId) -> VariantIdx {
2352 .find(|(_, v)| v.ctor_def_id == Some(cid))
2353 .expect("variant_index_with_ctor_id: unknown variant")
2357 pub fn variant_of_res(&self, res: Res) -> &VariantDef {
2359 Res::Def(DefKind::Variant, vid) => self.variant_with_id(vid),
2360 Res::Def(DefKind::Ctor(..), cid) => self.variant_with_ctor_id(cid),
2361 Res::Def(DefKind::Struct, _)
2362 | Res::Def(DefKind::Union, _)
2363 | Res::Def(DefKind::TyAlias, _)
2364 | Res::Def(DefKind::AssocTy, _)
2366 | Res::SelfCtor(..) => self.non_enum_variant(),
2367 _ => bug!("unexpected res {:?} in variant_of_res", res),
2372 pub fn eval_explicit_discr(&self, tcx: TyCtxt<'tcx>, expr_did: DefId) -> Option<Discr<'tcx>> {
2373 let param_env = tcx.param_env(expr_did);
2374 let repr_type = self.repr.discr_type();
2375 match tcx.const_eval_poly(expr_did) {
2377 let ty = repr_type.to_ty(tcx);
2378 if let Some(b) = val.try_to_bits_for_ty(tcx, param_env, ty) {
2379 trace!("discriminants: {} ({:?})", b, repr_type);
2380 Some(Discr { val: b, ty })
2382 info!("invalid enum discriminant: {:#?}", val);
2383 crate::mir::interpret::struct_error(
2384 tcx.at(tcx.def_span(expr_did)),
2385 "constant evaluation of enum discriminant resulted in non-integer",
2391 Err(ErrorHandled::Reported) => {
2392 if !expr_did.is_local() {
2394 tcx.def_span(expr_did),
2395 "variant discriminant evaluation succeeded \
2396 in its crate but failed locally"
2401 Err(ErrorHandled::TooGeneric) => {
2402 span_bug!(tcx.def_span(expr_did), "enum discriminant depends on generic arguments",)
2408 pub fn discriminants(
2411 ) -> impl Iterator<Item = (VariantIdx, Discr<'tcx>)> + Captures<'tcx> {
2412 let repr_type = self.repr.discr_type();
2413 let initial = repr_type.initial_discriminant(tcx);
2414 let mut prev_discr = None::<Discr<'tcx>>;
2415 self.variants.iter_enumerated().map(move |(i, v)| {
2416 let mut discr = prev_discr.map_or(initial, |d| d.wrap_incr(tcx));
2417 if let VariantDiscr::Explicit(expr_did) = v.discr {
2418 if let Some(new_discr) = self.eval_explicit_discr(tcx, expr_did) {
2422 prev_discr = Some(discr);
2429 pub fn variant_range(&self) -> Range<VariantIdx> {
2430 VariantIdx::new(0)..VariantIdx::new(self.variants.len())
2433 /// Computes the discriminant value used by a specific variant.
2434 /// Unlike `discriminants`, this is (amortized) constant-time,
2435 /// only doing at most one query for evaluating an explicit
2436 /// discriminant (the last one before the requested variant),
2437 /// assuming there are no constant-evaluation errors there.
2439 pub fn discriminant_for_variant(
2442 variant_index: VariantIdx,
2444 let (val, offset) = self.discriminant_def_for_variant(variant_index);
2445 let explicit_value = val
2446 .and_then(|expr_did| self.eval_explicit_discr(tcx, expr_did))
2447 .unwrap_or_else(|| self.repr.discr_type().initial_discriminant(tcx));
2448 explicit_value.checked_add(tcx, offset as u128).0
2451 /// Yields a `DefId` for the discriminant and an offset to add to it
2452 /// Alternatively, if there is no explicit discriminant, returns the
2453 /// inferred discriminant directly.
2454 pub fn discriminant_def_for_variant(&self, variant_index: VariantIdx) -> (Option<DefId>, u32) {
2455 let mut explicit_index = variant_index.as_u32();
2458 match self.variants[VariantIdx::from_u32(explicit_index)].discr {
2459 ty::VariantDiscr::Relative(0) => {
2463 ty::VariantDiscr::Relative(distance) => {
2464 explicit_index -= distance;
2466 ty::VariantDiscr::Explicit(did) => {
2467 expr_did = Some(did);
2472 (expr_did, variant_index.as_u32() - explicit_index)
2475 pub fn destructor(&self, tcx: TyCtxt<'tcx>) -> Option<Destructor> {
2476 tcx.adt_destructor(self.did)
2479 /// Returns a list of types such that `Self: Sized` if and only
2480 /// if that type is `Sized`, or `TyErr` if this type is recursive.
2482 /// Oddly enough, checking that the sized-constraint is `Sized` is
2483 /// actually more expressive than checking all members:
2484 /// the `Sized` trait is inductive, so an associated type that references
2485 /// `Self` would prevent its containing ADT from being `Sized`.
2487 /// Due to normalization being eager, this applies even if
2488 /// the associated type is behind a pointer (e.g., issue #31299).
2489 pub fn sized_constraint(&self, tcx: TyCtxt<'tcx>) -> &'tcx [Ty<'tcx>] {
2490 tcx.adt_sized_constraint(self.did).0
2494 impl<'tcx> FieldDef {
2495 /// Returns the type of this field. The `subst` is typically obtained
2496 /// via the second field of `TyKind::AdtDef`.
2497 pub fn ty(&self, tcx: TyCtxt<'tcx>, subst: SubstsRef<'tcx>) -> Ty<'tcx> {
2498 tcx.type_of(self.did).subst(tcx, subst)
2502 /// Represents the various closure traits in the language. This
2503 /// will determine the type of the environment (`self`, in the
2504 /// desugaring) argument that the closure expects.
2506 /// You can get the environment type of a closure using
2507 /// `tcx.closure_env_ty()`.
2508 #[derive(Clone, Copy, PartialOrd, Ord, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
2509 #[derive(HashStable)]
2510 pub enum ClosureKind {
2511 // Warning: Ordering is significant here! The ordering is chosen
2512 // because the trait Fn is a subtrait of FnMut and so in turn, and
2513 // hence we order it so that Fn < FnMut < FnOnce.
2519 impl<'tcx> ClosureKind {
2520 // This is the initial value used when doing upvar inference.
2521 pub const LATTICE_BOTTOM: ClosureKind = ClosureKind::Fn;
2523 pub fn trait_did(&self, tcx: TyCtxt<'tcx>) -> DefId {
2525 ClosureKind::Fn => tcx.require_lang_item(FnTraitLangItem, None),
2526 ClosureKind::FnMut => tcx.require_lang_item(FnMutTraitLangItem, None),
2527 ClosureKind::FnOnce => tcx.require_lang_item(FnOnceTraitLangItem, None),
2531 /// Returns `true` if this a type that impls this closure kind
2532 /// must also implement `other`.
2533 pub fn extends(self, other: ty::ClosureKind) -> bool {
2534 match (self, other) {
2535 (ClosureKind::Fn, ClosureKind::Fn) => true,
2536 (ClosureKind::Fn, ClosureKind::FnMut) => true,
2537 (ClosureKind::Fn, ClosureKind::FnOnce) => true,
2538 (ClosureKind::FnMut, ClosureKind::FnMut) => true,
2539 (ClosureKind::FnMut, ClosureKind::FnOnce) => true,
2540 (ClosureKind::FnOnce, ClosureKind::FnOnce) => true,
2545 /// Returns the representative scalar type for this closure kind.
2546 /// See `TyS::to_opt_closure_kind` for more details.
2547 pub fn to_ty(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
2549 ty::ClosureKind::Fn => tcx.types.i8,
2550 ty::ClosureKind::FnMut => tcx.types.i16,
2551 ty::ClosureKind::FnOnce => tcx.types.i32,
2557 pub fn from_mutbl(m: hir::Mutability) -> BorrowKind {
2559 hir::Mutability::Mut => MutBorrow,
2560 hir::Mutability::Not => ImmBorrow,
2564 /// Returns a mutability `m` such that an `&m T` pointer could be used to obtain this borrow
2565 /// kind. Because borrow kinds are richer than mutabilities, we sometimes have to pick a
2566 /// mutability that is stronger than necessary so that it at least *would permit* the borrow in
2568 pub fn to_mutbl_lossy(self) -> hir::Mutability {
2570 MutBorrow => hir::Mutability::Mut,
2571 ImmBorrow => hir::Mutability::Not,
2573 // We have no type corresponding to a unique imm borrow, so
2574 // use `&mut`. It gives all the capabilities of an `&uniq`
2575 // and hence is a safe "over approximation".
2576 UniqueImmBorrow => hir::Mutability::Mut,
2580 pub fn to_user_str(&self) -> &'static str {
2582 MutBorrow => "mutable",
2583 ImmBorrow => "immutable",
2584 UniqueImmBorrow => "uniquely immutable",
2589 pub type Attributes<'tcx> = &'tcx [ast::Attribute];
2591 #[derive(Debug, PartialEq, Eq)]
2592 pub enum ImplOverlapKind {
2593 /// These impls are always allowed to overlap.
2595 /// Whether or not the impl is permitted due to the trait being a `#[marker]` trait
2598 /// These impls are allowed to overlap, but that raises
2599 /// an issue #33140 future-compatibility warning.
2601 /// Some background: in Rust 1.0, the trait-object types `Send + Sync` (today's
2602 /// `dyn Send + Sync`) and `Sync + Send` (now `dyn Sync + Send`) were different.
2604 /// The widely-used version 0.1.0 of the crate `traitobject` had accidentally relied
2605 /// that difference, making what reduces to the following set of impls:
2609 /// impl Trait for dyn Send + Sync {}
2610 /// impl Trait for dyn Sync + Send {}
2613 /// Obviously, once we made these types be identical, that code causes a coherence
2614 /// error and a fairly big headache for us. However, luckily for us, the trait
2615 /// `Trait` used in this case is basically a marker trait, and therefore having
2616 /// overlapping impls for it is sound.
2618 /// To handle this, we basically regard the trait as a marker trait, with an additional
2619 /// future-compatibility warning. To avoid accidentally "stabilizing" this feature,
2620 /// it has the following restrictions:
2622 /// 1. The trait must indeed be a marker-like trait (i.e., no items), and must be
2624 /// 2. The trait-ref of both impls must be equal.
2625 /// 3. The trait-ref of both impls must be a trait object type consisting only of
2627 /// 4. Neither of the impls can have any where-clauses.
2629 /// Once `traitobject` 0.1.0 is no longer an active concern, this hack can be removed.
2633 impl<'tcx> TyCtxt<'tcx> {
2634 pub fn body_tables(self, body: hir::BodyId) -> &'tcx TypeckTables<'tcx> {
2635 self.typeck_tables_of(self.hir().body_owner_def_id(body).to_def_id())
2638 /// Returns an iterator of the `DefId`s for all body-owners in this
2639 /// crate. If you would prefer to iterate over the bodies
2640 /// themselves, you can do `self.hir().krate().body_ids.iter()`.
2641 pub fn body_owners(self) -> impl Iterator<Item = LocalDefId> + Captures<'tcx> + 'tcx {
2646 .map(move |&body_id| self.hir().body_owner_def_id(body_id))
2649 pub fn par_body_owners<F: Fn(LocalDefId) + sync::Sync + sync::Send>(self, f: F) {
2650 par_iter(&self.hir().krate().body_ids)
2651 .for_each(|&body_id| f(self.hir().body_owner_def_id(body_id)));
2654 pub fn provided_trait_methods(self, id: DefId) -> impl 'tcx + Iterator<Item = &'tcx AssocItem> {
2655 self.associated_items(id)
2656 .in_definition_order()
2657 .filter(|item| item.kind == AssocKind::Fn && item.defaultness.has_value())
2660 pub fn trait_relevant_for_never(self, did: DefId) -> bool {
2661 self.associated_items(did).in_definition_order().any(|item| item.relevant_for_never())
2664 pub fn opt_item_name(self, def_id: DefId) -> Option<Ident> {
2665 self.hir().as_local_hir_id(def_id).and_then(|hir_id| self.hir().get(hir_id).ident())
2668 pub fn opt_associated_item(self, def_id: DefId) -> Option<AssocItem> {
2669 let is_associated_item = if let Some(hir_id) = self.hir().as_local_hir_id(def_id) {
2670 match self.hir().get(hir_id) {
2671 Node::TraitItem(_) | Node::ImplItem(_) => true,
2675 match self.def_kind(def_id) {
2676 Some(DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy) => true,
2681 is_associated_item.then(|| self.associated_item(def_id))
2684 pub fn field_index(self, hir_id: hir::HirId, tables: &TypeckTables<'_>) -> usize {
2685 tables.field_indices().get(hir_id).cloned().expect("no index for a field")
2688 pub fn find_field_index(self, ident: Ident, variant: &VariantDef) -> Option<usize> {
2689 variant.fields.iter().position(|field| self.hygienic_eq(ident, field.ident, variant.def_id))
2692 /// Returns `true` if the impls are the same polarity and the trait either
2693 /// has no items or is annotated #[marker] and prevents item overrides.
2694 pub fn impls_are_allowed_to_overlap(
2698 ) -> Option<ImplOverlapKind> {
2699 // If either trait impl references an error, they're allowed to overlap,
2700 // as one of them essentially doesn't exist.
2701 if self.impl_trait_ref(def_id1).map_or(false, |tr| tr.references_error())
2702 || self.impl_trait_ref(def_id2).map_or(false, |tr| tr.references_error())
2704 return Some(ImplOverlapKind::Permitted { marker: false });
2707 match (self.impl_polarity(def_id1), self.impl_polarity(def_id2)) {
2708 (ImplPolarity::Reservation, _) | (_, ImplPolarity::Reservation) => {
2709 // `#[rustc_reservation_impl]` impls don't overlap with anything
2711 "impls_are_allowed_to_overlap({:?}, {:?}) = Some(Permitted) (reservations)",
2714 return Some(ImplOverlapKind::Permitted { marker: false });
2716 (ImplPolarity::Positive, ImplPolarity::Negative)
2717 | (ImplPolarity::Negative, ImplPolarity::Positive) => {
2718 // `impl AutoTrait for Type` + `impl !AutoTrait for Type`
2720 "impls_are_allowed_to_overlap({:?}, {:?}) - None (differing polarities)",
2725 (ImplPolarity::Positive, ImplPolarity::Positive)
2726 | (ImplPolarity::Negative, ImplPolarity::Negative) => {}
2729 let is_marker_overlap = {
2730 let is_marker_impl = |def_id: DefId| -> bool {
2731 let trait_ref = self.impl_trait_ref(def_id);
2732 trait_ref.map_or(false, |tr| self.trait_def(tr.def_id).is_marker)
2734 is_marker_impl(def_id1) && is_marker_impl(def_id2)
2737 if is_marker_overlap {
2739 "impls_are_allowed_to_overlap({:?}, {:?}) = Some(Permitted) (marker overlap)",
2742 Some(ImplOverlapKind::Permitted { marker: true })
2744 if let Some(self_ty1) = self.issue33140_self_ty(def_id1) {
2745 if let Some(self_ty2) = self.issue33140_self_ty(def_id2) {
2746 if self_ty1 == self_ty2 {
2748 "impls_are_allowed_to_overlap({:?}, {:?}) - issue #33140 HACK",
2751 return Some(ImplOverlapKind::Issue33140);
2754 "impls_are_allowed_to_overlap({:?}, {:?}) - found {:?} != {:?}",
2755 def_id1, def_id2, self_ty1, self_ty2
2761 debug!("impls_are_allowed_to_overlap({:?}, {:?}) = None", def_id1, def_id2);
2766 /// Returns `ty::VariantDef` if `res` refers to a struct,
2767 /// or variant or their constructors, panics otherwise.
2768 pub fn expect_variant_res(self, res: Res) -> &'tcx VariantDef {
2770 Res::Def(DefKind::Variant, did) => {
2771 let enum_did = self.parent(did).unwrap();
2772 self.adt_def(enum_did).variant_with_id(did)
2774 Res::Def(DefKind::Struct, did) | Res::Def(DefKind::Union, did) => {
2775 self.adt_def(did).non_enum_variant()
2777 Res::Def(DefKind::Ctor(CtorOf::Variant, ..), variant_ctor_did) => {
2778 let variant_did = self.parent(variant_ctor_did).unwrap();
2779 let enum_did = self.parent(variant_did).unwrap();
2780 self.adt_def(enum_did).variant_with_ctor_id(variant_ctor_did)
2782 Res::Def(DefKind::Ctor(CtorOf::Struct, ..), ctor_did) => {
2783 let struct_did = self.parent(ctor_did).expect("struct ctor has no parent");
2784 self.adt_def(struct_did).non_enum_variant()
2786 _ => bug!("expect_variant_res used with unexpected res {:?}", res),
2790 pub fn item_name(self, id: DefId) -> Symbol {
2791 if id.index == CRATE_DEF_INDEX {
2792 self.original_crate_name(id.krate)
2794 let def_key = self.def_key(id);
2795 match def_key.disambiguated_data.data {
2796 // The name of a constructor is that of its parent.
2797 rustc_hir::definitions::DefPathData::Ctor => {
2798 self.item_name(DefId { krate: id.krate, index: def_key.parent.unwrap() })
2800 _ => def_key.disambiguated_data.data.get_opt_name().unwrap_or_else(|| {
2801 bug!("item_name: no name for {:?}", self.def_path(id));
2807 /// Returns the possibly-auto-generated MIR of a `(DefId, Subst)` pair.
2808 pub fn instance_mir(self, instance: ty::InstanceDef<'tcx>) -> ReadOnlyBodyAndCache<'tcx, 'tcx> {
2810 ty::InstanceDef::Item(did) => self.optimized_mir(did).unwrap_read_only(),
2811 ty::InstanceDef::VtableShim(..)
2812 | ty::InstanceDef::ReifyShim(..)
2813 | ty::InstanceDef::Intrinsic(..)
2814 | ty::InstanceDef::FnPtrShim(..)
2815 | ty::InstanceDef::Virtual(..)
2816 | ty::InstanceDef::ClosureOnceShim { .. }
2817 | ty::InstanceDef::DropGlue(..)
2818 | ty::InstanceDef::CloneShim(..) => self.mir_shims(instance).unwrap_read_only(),
2822 /// Gets the attributes of a definition.
2823 pub fn get_attrs(self, did: DefId) -> Attributes<'tcx> {
2824 if let Some(id) = self.hir().as_local_hir_id(did) {
2825 self.hir().attrs(id)
2827 self.item_attrs(did)
2831 /// Determines whether an item is annotated with an attribute.
2832 pub fn has_attr(self, did: DefId, attr: Symbol) -> bool {
2833 attr::contains_name(&self.get_attrs(did), attr)
2836 /// Returns `true` if this is an `auto trait`.
2837 pub fn trait_is_auto(self, trait_def_id: DefId) -> bool {
2838 self.trait_def(trait_def_id).has_auto_impl
2841 pub fn generator_layout(self, def_id: DefId) -> &'tcx GeneratorLayout<'tcx> {
2842 self.optimized_mir(def_id).generator_layout.as_ref().unwrap()
2845 /// Given the `DefId` of an impl, returns the `DefId` of the trait it implements.
2846 /// If it implements no trait, returns `None`.
2847 pub fn trait_id_of_impl(self, def_id: DefId) -> Option<DefId> {
2848 self.impl_trait_ref(def_id).map(|tr| tr.def_id)
2851 /// If the given defid describes a method belonging to an impl, returns the
2852 /// `DefId` of the impl that the method belongs to; otherwise, returns `None`.
2853 pub fn impl_of_method(self, def_id: DefId) -> Option<DefId> {
2854 self.opt_associated_item(def_id).and_then(|trait_item| match trait_item.container {
2855 TraitContainer(_) => None,
2856 ImplContainer(def_id) => Some(def_id),
2860 /// Looks up the span of `impl_did` if the impl is local; otherwise returns `Err`
2861 /// with the name of the crate containing the impl.
2862 pub fn span_of_impl(self, impl_did: DefId) -> Result<Span, Symbol> {
2863 if impl_did.is_local() {
2864 let hir_id = self.hir().as_local_hir_id(impl_did).unwrap();
2865 Ok(self.hir().span(hir_id))
2867 Err(self.crate_name(impl_did.krate))
2871 /// Hygienically compares a use-site name (`use_name`) for a field or an associated item with
2872 /// its supposed definition name (`def_name`). The method also needs `DefId` of the supposed
2873 /// definition's parent/scope to perform comparison.
2874 pub fn hygienic_eq(self, use_name: Ident, def_name: Ident, def_parent_def_id: DefId) -> bool {
2875 // We could use `Ident::eq` here, but we deliberately don't. The name
2876 // comparison fails frequently, and we want to avoid the expensive
2877 // `normalize_to_macros_2_0()` calls required for the span comparison whenever possible.
2878 use_name.name == def_name.name
2882 .hygienic_eq(def_name.span.ctxt(), self.expansion_that_defined(def_parent_def_id))
2885 fn expansion_that_defined(self, scope: DefId) -> ExpnId {
2886 match scope.as_local() {
2887 Some(scope) => self.hir().definitions().expansion_that_defined(scope),
2888 None => ExpnId::root(),
2892 pub fn adjust_ident(self, mut ident: Ident, scope: DefId) -> Ident {
2893 ident.span.normalize_to_macros_2_0_and_adjust(self.expansion_that_defined(scope));
2897 pub fn adjust_ident_and_get_scope(
2902 ) -> (Ident, DefId) {
2904 match ident.span.normalize_to_macros_2_0_and_adjust(self.expansion_that_defined(scope))
2906 Some(actual_expansion) => {
2907 self.hir().definitions().parent_module_of_macro_def(actual_expansion)
2909 None => self.parent_module(block).to_def_id(),
2914 pub fn is_object_safe(self, key: DefId) -> bool {
2915 self.object_safety_violations(key).is_empty()
2919 #[derive(Clone, HashStable)]
2920 pub struct AdtSizedConstraint<'tcx>(pub &'tcx [Ty<'tcx>]);
2922 /// Yields the parent function's `DefId` if `def_id` is an `impl Trait` definition.
2923 pub fn is_impl_trait_defn(tcx: TyCtxt<'_>, def_id: DefId) -> Option<DefId> {
2924 if let Some(hir_id) = tcx.hir().as_local_hir_id(def_id) {
2925 if let Node::Item(item) = tcx.hir().get(hir_id) {
2926 if let hir::ItemKind::OpaqueTy(ref opaque_ty) = item.kind {
2927 return opaque_ty.impl_trait_fn;
2934 pub fn provide(providers: &mut ty::query::Providers<'_>) {
2935 context::provide(providers);
2936 erase_regions::provide(providers);
2937 layout::provide(providers);
2938 super::util::bug::provide(providers);
2939 *providers = ty::query::Providers {
2940 trait_impls_of: trait_def::trait_impls_of_provider,
2941 all_local_trait_impls: trait_def::all_local_trait_impls,
2946 /// A map for the local crate mapping each type to a vector of its
2947 /// inherent impls. This is not meant to be used outside of coherence;
2948 /// rather, you should request the vector for a specific type via
2949 /// `tcx.inherent_impls(def_id)` so as to minimize your dependencies
2950 /// (constructing this map requires touching the entire crate).
2951 #[derive(Clone, Debug, Default, HashStable)]
2952 pub struct CrateInherentImpls {
2953 pub inherent_impls: DefIdMap<Vec<DefId>>,
2956 #[derive(Clone, Copy, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2957 pub struct SymbolName {
2958 // FIXME: we don't rely on interning or equality here - better have
2959 // this be a `&'tcx str`.
2964 pub fn new(name: &str) -> SymbolName {
2965 SymbolName { name: Symbol::intern(name) }
2969 impl PartialOrd for SymbolName {
2970 fn partial_cmp(&self, other: &SymbolName) -> Option<Ordering> {
2971 self.name.as_str().partial_cmp(&other.name.as_str())
2975 /// Ordering must use the chars to ensure reproducible builds.
2976 impl Ord for SymbolName {
2977 fn cmp(&self, other: &SymbolName) -> Ordering {
2978 self.name.as_str().cmp(&other.name.as_str())
2982 impl fmt::Display for SymbolName {
2983 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2984 fmt::Display::fmt(&self.name, fmt)
2988 impl fmt::Debug for SymbolName {
2989 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2990 fmt::Display::fmt(&self.name, fmt)