1 // ignore-tidy-filelength
3 pub use self::Variance::*;
4 pub use self::AssocItemContainer::*;
5 pub use self::BorrowKind::*;
6 pub use self::IntVarValue::*;
7 pub use self::fold::TypeFoldable;
9 use crate::hir::{map as hir_map, GlobMap, TraitMap};
11 use crate::hir::def::{Res, DefKind, CtorOf, CtorKind, ExportMap};
12 use crate::hir::def_id::{CrateNum, DefId, LocalDefId, CRATE_DEF_INDEX, LOCAL_CRATE};
13 use rustc_data_structures::svh::Svh;
14 use rustc_macros::HashStable;
15 use crate::ich::Fingerprint;
16 use crate::ich::StableHashingContext;
17 use crate::infer::canonical::Canonical;
18 use crate::middle::lang_items::{FnTraitLangItem, FnMutTraitLangItem, FnOnceTraitLangItem};
19 use crate::middle::resolve_lifetime::ObjectLifetimeDefault;
21 use crate::mir::interpret::{GlobalId, ErrorHandled};
22 use crate::mir::GeneratorLayout;
23 use crate::session::CrateDisambiguator;
24 use crate::traits::{self, Reveal};
26 use crate::ty::layout::VariantIdx;
27 use crate::ty::subst::{Subst, InternalSubsts, SubstsRef};
28 use crate::ty::util::{IntTypeExt, Discr};
29 use crate::ty::walk::TypeWalker;
30 use crate::util::captures::Captures;
31 use crate::util::nodemap::{NodeSet, DefIdMap, FxHashMap};
32 use arena::SyncDroplessArena;
33 use crate::session::DataTypeKind;
35 use rustc_serialize::{self, Encodable, Encoder};
36 use rustc_target::abi::Align;
37 use std::cell::RefCell;
38 use std::cmp::{self, Ordering};
40 use std::hash::{Hash, Hasher};
42 use rustc_data_structures::sync::{self, Lrc, ParallelIterator, par_iter};
46 use syntax::ast::{self, Name, Ident, NodeId};
48 use syntax::ext::hygiene::ExpnId;
49 use syntax::symbol::{kw, sym, Symbol, InternedString};
53 use rustc_data_structures::fx::FxIndexMap;
54 use rustc_data_structures::stable_hasher::{StableHasher, HashStable};
55 use rustc_index::vec::{Idx, IndexVec};
59 pub use self::sty::{Binder, BoundTy, BoundTyKind, BoundVar, DebruijnIndex, INNERMOST};
60 pub use self::sty::{FnSig, GenSig, CanonicalPolyFnSig, PolyFnSig, PolyGenSig};
61 pub use self::sty::{InferTy, ParamTy, ParamConst, InferConst, ProjectionTy, ExistentialPredicate};
62 pub use self::sty::{ClosureSubsts, GeneratorSubsts, UpvarSubsts, TypeAndMut};
63 pub use self::sty::{TraitRef, TyKind, PolyTraitRef};
64 pub use self::sty::{ExistentialTraitRef, PolyExistentialTraitRef};
65 pub use self::sty::{ExistentialProjection, PolyExistentialProjection, Const};
66 pub use self::sty::{BoundRegion, EarlyBoundRegion, FreeRegion, Region};
67 pub use self::sty::RegionKind;
68 pub use self::sty::{TyVid, IntVid, FloatVid, ConstVid, RegionVid};
69 pub use self::sty::BoundRegion::*;
70 pub use self::sty::InferTy::*;
71 pub use self::sty::RegionKind::*;
72 pub use self::sty::TyKind::*;
74 pub use self::binding::BindingMode;
75 pub use self::binding::BindingMode::*;
77 pub use self::context::{TyCtxt, FreeRegionInfo, AllArenas, tls, keep_local};
78 pub use self::context::{Lift, GeneratorInteriorTypeCause, TypeckTables, CtxtInterners, GlobalCtxt};
79 pub use self::context::{
80 UserTypeAnnotationIndex, UserType, CanonicalUserType,
81 CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations, ResolvedOpaqueTy,
84 pub use self::instance::{Instance, InstanceDef};
86 pub use self::trait_def::TraitDef;
88 pub use self::query::queries;
101 pub mod inhabitedness;
117 mod structural_impls;
123 pub struct Resolutions {
124 pub trait_map: TraitMap,
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, PartialEq, Eq, Hash, Debug)]
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 argument, allowing method calls.
194 pub method_has_self_argument: bool,
197 #[derive(Copy, Clone, PartialEq, Eq, Debug, Hash, RustcEncodable, RustcDecodable, HashStable)]
206 pub fn def_kind(&self) -> DefKind {
208 AssocKind::Const => DefKind::AssocConst,
209 AssocKind::Method => DefKind::Method,
210 AssocKind::Type => DefKind::AssocTy,
211 AssocKind::OpaqueTy => DefKind::AssocOpaqueTy,
215 /// Tests whether the associated item admits a non-trivial implementation
217 pub fn relevant_for_never(&self) -> bool {
219 AssocKind::OpaqueTy |
221 AssocKind::Type => true,
222 // FIXME(canndrew): Be more thorough here, check if any argument is uninhabited.
223 AssocKind::Method => !self.method_has_self_argument,
227 pub fn signature(&self, tcx: TyCtxt<'_>) -> String {
229 ty::AssocKind::Method => {
230 // We skip the binder here because the binder would deanonymize all
231 // late-bound regions, and we don't want method signatures to show up
232 // `as for<'r> fn(&'r MyType)`. Pretty-printing handles late-bound
233 // regions just fine, showing `fn(&MyType)`.
234 tcx.fn_sig(self.def_id).skip_binder().to_string()
236 ty::AssocKind::Type => format!("type {};", self.ident),
237 // FIXME(type_alias_impl_trait): we should print bounds here too.
238 ty::AssocKind::OpaqueTy => format!("type {};", self.ident),
239 ty::AssocKind::Const => {
240 format!("const {}: {:?};", self.ident, tcx.type_of(self.def_id))
246 #[derive(Clone, Debug, PartialEq, Eq, Copy, RustcEncodable, RustcDecodable, HashStable)]
247 pub enum Visibility {
248 /// Visible everywhere (including in other crates).
250 /// Visible only in the given crate-local module.
252 /// Not visible anywhere in the local crate. This is the visibility of private external items.
256 pub trait DefIdTree: Copy {
257 fn parent(self, id: DefId) -> Option<DefId>;
259 fn is_descendant_of(self, mut descendant: DefId, ancestor: DefId) -> bool {
260 if descendant.krate != ancestor.krate {
264 while descendant != ancestor {
265 match self.parent(descendant) {
266 Some(parent) => descendant = parent,
267 None => return false,
274 impl<'tcx> DefIdTree for TyCtxt<'tcx> {
275 fn parent(self, id: DefId) -> Option<DefId> {
276 self.def_key(id).parent.map(|index| DefId { index: index, ..id })
281 pub fn from_hir(visibility: &hir::Visibility, id: hir::HirId, tcx: TyCtxt<'_>) -> Self {
282 match visibility.node {
283 hir::VisibilityKind::Public => Visibility::Public,
284 hir::VisibilityKind::Crate(_) => Visibility::Restricted(DefId::local(CRATE_DEF_INDEX)),
285 hir::VisibilityKind::Restricted { ref path, .. } => match path.res {
286 // If there is no resolution, `resolve` will have already reported an error, so
287 // assume that the visibility is public to avoid reporting more privacy errors.
288 Res::Err => Visibility::Public,
289 def => Visibility::Restricted(def.def_id()),
291 hir::VisibilityKind::Inherited => {
292 Visibility::Restricted(tcx.hir().get_module_parent(id))
297 /// Returns `true` if an item with this visibility is accessible from the given block.
298 pub fn is_accessible_from<T: DefIdTree>(self, module: DefId, tree: T) -> bool {
299 let restriction = match self {
300 // Public items are visible everywhere.
301 Visibility::Public => return true,
302 // Private items from other crates are visible nowhere.
303 Visibility::Invisible => return false,
304 // Restricted items are visible in an arbitrary local module.
305 Visibility::Restricted(other) if other.krate != module.krate => return false,
306 Visibility::Restricted(module) => module,
309 tree.is_descendant_of(module, restriction)
312 /// Returns `true` if this visibility is at least as accessible as the given visibility
313 pub fn is_at_least<T: DefIdTree>(self, vis: Visibility, tree: T) -> bool {
314 let vis_restriction = match vis {
315 Visibility::Public => return self == Visibility::Public,
316 Visibility::Invisible => return true,
317 Visibility::Restricted(module) => module,
320 self.is_accessible_from(vis_restriction, tree)
323 // Returns `true` if this item is visible anywhere in the local crate.
324 pub fn is_visible_locally(self) -> bool {
326 Visibility::Public => true,
327 Visibility::Restricted(def_id) => def_id.is_local(),
328 Visibility::Invisible => false,
333 #[derive(Copy, Clone, PartialEq, Eq, RustcDecodable, RustcEncodable, Hash, HashStable)]
335 Covariant, // T<A> <: T<B> iff A <: B -- e.g., function return type
336 Invariant, // T<A> <: T<B> iff B == A -- e.g., type of mutable cell
337 Contravariant, // T<A> <: T<B> iff B <: A -- e.g., function param type
338 Bivariant, // T<A> <: T<B> -- e.g., unused type parameter
341 /// The crate variances map is computed during typeck and contains the
342 /// variance of every item in the local crate. You should not use it
343 /// directly, because to do so will make your pass dependent on the
344 /// HIR of every item in the local crate. Instead, use
345 /// `tcx.variances_of()` to get the variance for a *particular*
347 #[derive(HashStable)]
348 pub struct CrateVariancesMap<'tcx> {
349 /// For each item with generics, maps to a vector of the variance
350 /// of its generics. If an item has no generics, it will have no
352 pub variances: FxHashMap<DefId, &'tcx [ty::Variance]>,
356 /// `a.xform(b)` combines the variance of a context with the
357 /// variance of a type with the following meaning. If we are in a
358 /// context with variance `a`, and we encounter a type argument in
359 /// a position with variance `b`, then `a.xform(b)` is the new
360 /// variance with which the argument appears.
366 /// Here, the "ambient" variance starts as covariant. `*mut T` is
367 /// invariant with respect to `T`, so the variance in which the
368 /// `Vec<i32>` appears is `Covariant.xform(Invariant)`, which
369 /// yields `Invariant`. Now, the type `Vec<T>` is covariant with
370 /// respect to its type argument `T`, and hence the variance of
371 /// the `i32` here is `Invariant.xform(Covariant)`, which results
372 /// (again) in `Invariant`.
376 /// fn(*const Vec<i32>, *mut Vec<i32)
378 /// The ambient variance is covariant. A `fn` type is
379 /// contravariant with respect to its parameters, so the variance
380 /// within which both pointer types appear is
381 /// `Covariant.xform(Contravariant)`, or `Contravariant`. `*const
382 /// T` is covariant with respect to `T`, so the variance within
383 /// which the first `Vec<i32>` appears is
384 /// `Contravariant.xform(Covariant)` or `Contravariant`. The same
385 /// is true for its `i32` argument. In the `*mut T` case, the
386 /// variance of `Vec<i32>` is `Contravariant.xform(Invariant)`,
387 /// and hence the outermost type is `Invariant` with respect to
388 /// `Vec<i32>` (and its `i32` argument).
390 /// Source: Figure 1 of "Taming the Wildcards:
391 /// Combining Definition- and Use-Site Variance" published in PLDI'11.
392 pub fn xform(self, v: ty::Variance) -> ty::Variance {
394 // Figure 1, column 1.
395 (ty::Covariant, ty::Covariant) => ty::Covariant,
396 (ty::Covariant, ty::Contravariant) => ty::Contravariant,
397 (ty::Covariant, ty::Invariant) => ty::Invariant,
398 (ty::Covariant, ty::Bivariant) => ty::Bivariant,
400 // Figure 1, column 2.
401 (ty::Contravariant, ty::Covariant) => ty::Contravariant,
402 (ty::Contravariant, ty::Contravariant) => ty::Covariant,
403 (ty::Contravariant, ty::Invariant) => ty::Invariant,
404 (ty::Contravariant, ty::Bivariant) => ty::Bivariant,
406 // Figure 1, column 3.
407 (ty::Invariant, _) => ty::Invariant,
409 // Figure 1, column 4.
410 (ty::Bivariant, _) => ty::Bivariant,
415 // Contains information needed to resolve types and (in the future) look up
416 // the types of AST nodes.
417 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
418 pub struct CReaderCacheKey {
423 // Flags that we track on types. These flags are propagated upwards
424 // through the type during type construction, so that we can quickly
425 // check whether the type has various kinds of types in it without
426 // recursing over the type itself.
428 pub struct TypeFlags: u32 {
429 const HAS_PARAMS = 1 << 0;
430 const HAS_TY_INFER = 1 << 1;
431 const HAS_RE_INFER = 1 << 2;
432 const HAS_RE_PLACEHOLDER = 1 << 3;
434 /// Does this have any `ReEarlyBound` regions? Used to
435 /// determine whether substitition is required, since those
436 /// represent regions that are bound in a `ty::Generics` and
437 /// hence may be substituted.
438 const HAS_RE_EARLY_BOUND = 1 << 4;
440 /// Does this have any region that "appears free" in the type?
441 /// Basically anything but `ReLateBound` and `ReErased`.
442 const HAS_FREE_REGIONS = 1 << 5;
444 /// Is an error type reachable?
445 const HAS_TY_ERR = 1 << 6;
446 const HAS_PROJECTION = 1 << 7;
448 // FIXME: Rename this to the actual property since it's used for generators too
449 const HAS_TY_CLOSURE = 1 << 8;
451 /// `true` if there are "names" of types and regions and so forth
452 /// that are local to a particular fn
453 const HAS_FREE_LOCAL_NAMES = 1 << 9;
455 /// Present if the type belongs in a local type context.
456 /// Only set for Infer other than Fresh.
457 const KEEP_IN_LOCAL_TCX = 1 << 10;
459 /// Does this have any `ReLateBound` regions? Used to check
460 /// if a global bound is safe to evaluate.
461 const HAS_RE_LATE_BOUND = 1 << 11;
463 const HAS_TY_PLACEHOLDER = 1 << 12;
465 const HAS_CT_INFER = 1 << 13;
466 const HAS_CT_PLACEHOLDER = 1 << 14;
468 const NEEDS_SUBST = TypeFlags::HAS_PARAMS.bits |
469 TypeFlags::HAS_RE_EARLY_BOUND.bits;
471 /// Flags representing the nominal content of a type,
472 /// computed by FlagsComputation. If you add a new nominal
473 /// flag, it should be added here too.
474 const NOMINAL_FLAGS = TypeFlags::HAS_PARAMS.bits |
475 TypeFlags::HAS_TY_INFER.bits |
476 TypeFlags::HAS_RE_INFER.bits |
477 TypeFlags::HAS_RE_PLACEHOLDER.bits |
478 TypeFlags::HAS_RE_EARLY_BOUND.bits |
479 TypeFlags::HAS_FREE_REGIONS.bits |
480 TypeFlags::HAS_TY_ERR.bits |
481 TypeFlags::HAS_PROJECTION.bits |
482 TypeFlags::HAS_TY_CLOSURE.bits |
483 TypeFlags::HAS_FREE_LOCAL_NAMES.bits |
484 TypeFlags::KEEP_IN_LOCAL_TCX.bits |
485 TypeFlags::HAS_RE_LATE_BOUND.bits |
486 TypeFlags::HAS_TY_PLACEHOLDER.bits |
487 TypeFlags::HAS_CT_INFER.bits |
488 TypeFlags::HAS_CT_PLACEHOLDER.bits;
492 #[allow(rustc::usage_of_ty_tykind)]
493 pub struct TyS<'tcx> {
494 pub kind: TyKind<'tcx>,
495 pub flags: TypeFlags,
497 /// This is a kind of confusing thing: it stores the smallest
500 /// (a) the binder itself captures nothing but
501 /// (b) all the late-bound things within the type are captured
502 /// by some sub-binder.
504 /// So, for a type without any late-bound things, like `u32`, this
505 /// will be *innermost*, because that is the innermost binder that
506 /// captures nothing. But for a type `&'D u32`, where `'D` is a
507 /// late-bound region with De Bruijn index `D`, this would be `D + 1`
508 /// -- the binder itself does not capture `D`, but `D` is captured
509 /// by an inner binder.
511 /// We call this concept an "exclusive" binder `D` because all
512 /// De Bruijn indices within the type are contained within `0..D`
514 outer_exclusive_binder: ty::DebruijnIndex,
517 // `TyS` is used a lot. Make sure it doesn't unintentionally get bigger.
518 #[cfg(target_arch = "x86_64")]
519 static_assert_size!(TyS<'_>, 32);
521 impl<'tcx> Ord for TyS<'tcx> {
522 fn cmp(&self, other: &TyS<'tcx>) -> Ordering {
523 self.kind.cmp(&other.kind)
527 impl<'tcx> PartialOrd for TyS<'tcx> {
528 fn partial_cmp(&self, other: &TyS<'tcx>) -> Option<Ordering> {
529 Some(self.kind.cmp(&other.kind))
533 impl<'tcx> PartialEq for TyS<'tcx> {
535 fn eq(&self, other: &TyS<'tcx>) -> bool {
539 impl<'tcx> Eq for TyS<'tcx> {}
541 impl<'tcx> Hash for TyS<'tcx> {
542 fn hash<H: Hasher>(&self, s: &mut H) {
543 (self as *const TyS<'_>).hash(s)
547 impl<'tcx> TyS<'tcx> {
548 pub fn is_primitive_ty(&self) -> bool {
555 Infer(InferTy::IntVar(_)) |
556 Infer(InferTy::FloatVar(_)) |
557 Infer(InferTy::FreshIntTy(_)) |
558 Infer(InferTy::FreshFloatTy(_)) => true,
559 Ref(_, x, _) => x.is_primitive_ty(),
564 pub fn is_suggestable(&self) -> bool {
572 Projection(..) => false,
578 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for ty::TyS<'tcx> {
579 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
583 // The other fields just provide fast access to information that is
584 // also contained in `kind`, so no need to hash them.
587 outer_exclusive_binder: _,
590 kind.hash_stable(hcx, hasher);
594 #[rustc_diagnostic_item = "Ty"]
595 pub type Ty<'tcx> = &'tcx TyS<'tcx>;
597 impl<'tcx> rustc_serialize::UseSpecializedEncodable for Ty<'tcx> {}
598 impl<'tcx> rustc_serialize::UseSpecializedDecodable for Ty<'tcx> {}
600 pub type CanonicalTy<'tcx> = Canonical<'tcx, Ty<'tcx>>;
603 /// A dummy type used to force `List` to by unsized without requiring fat pointers.
604 type OpaqueListContents;
607 /// A wrapper for slices with the additional invariant
608 /// that the slice is interned and no other slice with
609 /// the same contents can exist in the same context.
610 /// This means we can use pointer for both
611 /// equality comparisons and hashing.
612 /// Note: `Slice` was already taken by the `Ty`.
617 opaque: OpaqueListContents,
620 unsafe impl<T: Sync> Sync for List<T> {}
622 impl<T: Copy> List<T> {
624 fn from_arena<'tcx>(arena: &'tcx SyncDroplessArena, slice: &[T]) -> &'tcx List<T> {
625 assert!(!mem::needs_drop::<T>());
626 assert!(mem::size_of::<T>() != 0);
627 assert!(slice.len() != 0);
629 // Align up the size of the len (usize) field
630 let align = mem::align_of::<T>();
631 let align_mask = align - 1;
632 let offset = mem::size_of::<usize>();
633 let offset = (offset + align_mask) & !align_mask;
635 let size = offset + slice.len() * mem::size_of::<T>();
637 let mem = arena.alloc_raw(
639 cmp::max(mem::align_of::<T>(), mem::align_of::<usize>()));
641 let result = &mut *(mem.as_mut_ptr() as *mut List<T>);
643 result.len = slice.len();
645 // Write the elements
646 let arena_slice = slice::from_raw_parts_mut(result.data.as_mut_ptr(), result.len);
647 arena_slice.copy_from_slice(slice);
654 impl<T: fmt::Debug> fmt::Debug for List<T> {
655 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
660 impl<T: Encodable> Encodable for List<T> {
662 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
667 impl<T> Ord for List<T> where T: Ord {
668 fn cmp(&self, other: &List<T>) -> Ordering {
669 if self == other { Ordering::Equal } else {
670 <[T] as Ord>::cmp(&**self, &**other)
675 impl<T> PartialOrd for List<T> where T: PartialOrd {
676 fn partial_cmp(&self, other: &List<T>) -> Option<Ordering> {
677 if self == other { Some(Ordering::Equal) } else {
678 <[T] as PartialOrd>::partial_cmp(&**self, &**other)
683 impl<T: PartialEq> PartialEq for List<T> {
685 fn eq(&self, other: &List<T>) -> bool {
689 impl<T: Eq> Eq for List<T> {}
691 impl<T> Hash for List<T> {
693 fn hash<H: Hasher>(&self, s: &mut H) {
694 (self as *const List<T>).hash(s)
698 impl<T> Deref for List<T> {
701 fn deref(&self) -> &[T] {
703 slice::from_raw_parts(self.data.as_ptr(), self.len)
708 impl<'a, T> IntoIterator for &'a List<T> {
710 type IntoIter = <&'a [T] as IntoIterator>::IntoIter;
712 fn into_iter(self) -> Self::IntoIter {
717 impl<'tcx> rustc_serialize::UseSpecializedDecodable for &'tcx List<Ty<'tcx>> {}
721 pub fn empty<'a>() -> &'a List<T> {
722 #[repr(align(64), C)]
723 struct EmptySlice([u8; 64]);
724 static EMPTY_SLICE: EmptySlice = EmptySlice([0; 64]);
725 assert!(mem::align_of::<T>() <= 64);
727 &*(&EMPTY_SLICE as *const _ as *const List<T>)
732 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
733 pub struct UpvarPath {
734 pub hir_id: hir::HirId,
737 /// Upvars do not get their own `NodeId`. Instead, we use the pair of
738 /// the original var ID (that is, the root variable that is referenced
739 /// by the upvar) and the ID of the closure expression.
740 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
742 pub var_path: UpvarPath,
743 pub closure_expr_id: LocalDefId,
746 #[derive(Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable, Copy, HashStable)]
747 pub enum BorrowKind {
748 /// Data must be immutable and is aliasable.
751 /// Data must be immutable but not aliasable. This kind of borrow
752 /// cannot currently be expressed by the user and is used only in
753 /// implicit closure bindings. It is needed when the closure
754 /// is borrowing or mutating a mutable referent, e.g.:
756 /// let x: &mut isize = ...;
757 /// let y = || *x += 5;
759 /// If we were to try to translate this closure into a more explicit
760 /// form, we'd encounter an error with the code as written:
762 /// struct Env { x: & &mut isize }
763 /// let x: &mut isize = ...;
764 /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
765 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
767 /// This is then illegal because you cannot mutate a `&mut` found
768 /// in an aliasable location. To solve, you'd have to translate with
769 /// an `&mut` borrow:
771 /// struct Env { x: & &mut isize }
772 /// let x: &mut isize = ...;
773 /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
774 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
776 /// Now the assignment to `**env.x` is legal, but creating a
777 /// mutable pointer to `x` is not because `x` is not mutable. We
778 /// could fix this by declaring `x` as `let mut x`. This is ok in
779 /// user code, if awkward, but extra weird for closures, since the
780 /// borrow is hidden.
782 /// So we introduce a "unique imm" borrow -- the referent is
783 /// immutable, but not aliasable. This solves the problem. For
784 /// simplicity, we don't give users the way to express this
785 /// borrow, it's just used when translating closures.
788 /// Data is mutable and not aliasable.
792 /// Information describing the capture of an upvar. This is computed
793 /// during `typeck`, specifically by `regionck`.
794 #[derive(PartialEq, Clone, Debug, Copy, RustcEncodable, RustcDecodable, HashStable)]
795 pub enum UpvarCapture<'tcx> {
796 /// Upvar is captured by value. This is always true when the
797 /// closure is labeled `move`, but can also be true in other cases
798 /// depending on inference.
801 /// Upvar is captured by reference.
802 ByRef(UpvarBorrow<'tcx>),
805 #[derive(PartialEq, Clone, Copy, RustcEncodable, RustcDecodable, HashStable)]
806 pub struct UpvarBorrow<'tcx> {
807 /// The kind of borrow: by-ref upvars have access to shared
808 /// immutable borrows, which are not part of the normal language
810 pub kind: BorrowKind,
812 /// Region of the resulting reference.
813 pub region: ty::Region<'tcx>,
816 pub type UpvarListMap = FxHashMap<DefId, FxIndexMap<hir::HirId, UpvarId>>;
817 pub type UpvarCaptureMap<'tcx> = FxHashMap<UpvarId, UpvarCapture<'tcx>>;
819 #[derive(Copy, Clone)]
820 pub struct ClosureUpvar<'tcx> {
826 #[derive(Clone, Copy, PartialEq, Eq)]
827 pub enum IntVarValue {
829 UintType(ast::UintTy),
832 #[derive(Clone, Copy, PartialEq, Eq)]
833 pub struct FloatVarValue(pub ast::FloatTy);
835 impl ty::EarlyBoundRegion {
836 pub fn to_bound_region(&self) -> ty::BoundRegion {
837 ty::BoundRegion::BrNamed(self.def_id, self.name)
840 /// Does this early bound region have a name? Early bound regions normally
841 /// always have names except when using anonymous lifetimes (`'_`).
842 pub fn has_name(&self) -> bool {
843 self.name != kw::UnderscoreLifetime.as_interned_str()
847 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
848 pub enum GenericParamDefKind {
852 object_lifetime_default: ObjectLifetimeDefault,
853 synthetic: Option<hir::SyntheticTyParamKind>,
858 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable)]
859 pub struct GenericParamDef {
860 pub name: InternedString,
864 /// `pure_wrt_drop`, set by the (unsafe) `#[may_dangle]` attribute
865 /// on generic parameter `'a`/`T`, asserts data behind the parameter
866 /// `'a`/`T` won't be accessed during the parent type's `Drop` impl.
867 pub pure_wrt_drop: bool,
869 pub kind: GenericParamDefKind,
872 impl GenericParamDef {
873 pub fn to_early_bound_region_data(&self) -> ty::EarlyBoundRegion {
874 if let GenericParamDefKind::Lifetime = self.kind {
875 ty::EarlyBoundRegion {
881 bug!("cannot convert a non-lifetime parameter def to an early bound region")
885 pub fn to_bound_region(&self) -> ty::BoundRegion {
886 if let GenericParamDefKind::Lifetime = self.kind {
887 self.to_early_bound_region_data().to_bound_region()
889 bug!("cannot convert a non-lifetime parameter def to an early bound region")
895 pub struct GenericParamCount {
896 pub lifetimes: usize,
901 /// Information about the formal type/lifetime parameters associated
902 /// with an item or method. Analogous to `hir::Generics`.
904 /// The ordering of parameters is the same as in `Subst` (excluding child generics):
905 /// `Self` (optionally), `Lifetime` params..., `Type` params...
906 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
907 pub struct Generics {
908 pub parent: Option<DefId>,
909 pub parent_count: usize,
910 pub params: Vec<GenericParamDef>,
912 /// Reverse map to the `index` field of each `GenericParamDef`.
913 #[stable_hasher(ignore)]
914 pub param_def_id_to_index: FxHashMap<DefId, u32>,
917 pub has_late_bound_regions: Option<Span>,
920 impl<'tcx> Generics {
921 pub fn count(&self) -> usize {
922 self.parent_count + self.params.len()
925 pub fn own_counts(&self) -> GenericParamCount {
926 // We could cache this as a property of `GenericParamCount`, but
927 // the aim is to refactor this away entirely eventually and the
928 // presence of this method will be a constant reminder.
929 let mut own_counts: GenericParamCount = Default::default();
931 for param in &self.params {
933 GenericParamDefKind::Lifetime => own_counts.lifetimes += 1,
934 GenericParamDefKind::Type { .. } => own_counts.types += 1,
935 GenericParamDefKind::Const => own_counts.consts += 1,
942 pub fn requires_monomorphization(&self, tcx: TyCtxt<'tcx>) -> bool {
943 if self.own_requires_monomorphization() {
947 if let Some(parent_def_id) = self.parent {
948 let parent = tcx.generics_of(parent_def_id);
949 parent.requires_monomorphization(tcx)
955 pub fn own_requires_monomorphization(&self) -> bool {
956 for param in &self.params {
958 GenericParamDefKind::Type { .. } | GenericParamDefKind::Const => return true,
959 GenericParamDefKind::Lifetime => {}
967 param: &EarlyBoundRegion,
969 ) -> &'tcx GenericParamDef {
970 if let Some(index) = param.index.checked_sub(self.parent_count as u32) {
971 let param = &self.params[index as usize];
973 GenericParamDefKind::Lifetime => param,
974 _ => bug!("expected lifetime parameter, but found another generic parameter")
977 tcx.generics_of(self.parent.expect("parent_count > 0 but no parent?"))
978 .region_param(param, tcx)
982 /// Returns the `GenericParamDef` associated with this `ParamTy`.
983 pub fn type_param(&'tcx self, param: &ParamTy, tcx: TyCtxt<'tcx>) -> &'tcx GenericParamDef {
984 if let Some(index) = param.index.checked_sub(self.parent_count as u32) {
985 let param = &self.params[index as usize];
987 GenericParamDefKind::Type { .. } => param,
988 _ => bug!("expected type parameter, but found another generic parameter")
991 tcx.generics_of(self.parent.expect("parent_count > 0 but no parent?"))
992 .type_param(param, tcx)
996 /// Returns the `ConstParameterDef` associated with this `ParamConst`.
997 pub fn const_param(&'tcx self, param: &ParamConst, tcx: TyCtxt<'tcx>) -> &GenericParamDef {
998 if let Some(index) = param.index.checked_sub(self.parent_count as u32) {
999 let param = &self.params[index as usize];
1001 GenericParamDefKind::Const => param,
1002 _ => bug!("expected const parameter, but found another generic parameter")
1005 tcx.generics_of(self.parent.expect("parent_count>0 but no parent?"))
1006 .const_param(param, tcx)
1011 /// Bounds on generics.
1012 #[derive(Clone, Default, Debug, HashStable)]
1013 pub struct GenericPredicates<'tcx> {
1014 pub parent: Option<DefId>,
1015 pub predicates: Vec<(Predicate<'tcx>, Span)>,
1018 impl<'tcx> rustc_serialize::UseSpecializedEncodable for GenericPredicates<'tcx> {}
1019 impl<'tcx> rustc_serialize::UseSpecializedDecodable for GenericPredicates<'tcx> {}
1021 impl<'tcx> GenericPredicates<'tcx> {
1025 substs: SubstsRef<'tcx>,
1026 ) -> InstantiatedPredicates<'tcx> {
1027 let mut instantiated = InstantiatedPredicates::empty();
1028 self.instantiate_into(tcx, &mut instantiated, substs);
1032 pub fn instantiate_own(
1035 substs: SubstsRef<'tcx>,
1036 ) -> InstantiatedPredicates<'tcx> {
1037 InstantiatedPredicates {
1038 predicates: self.predicates.iter().map(|(p, _)| p.subst(tcx, substs)).collect(),
1042 fn instantiate_into(
1045 instantiated: &mut InstantiatedPredicates<'tcx>,
1046 substs: SubstsRef<'tcx>,
1048 if let Some(def_id) = self.parent {
1049 tcx.predicates_of(def_id).instantiate_into(tcx, instantiated, substs);
1051 instantiated.predicates.extend(
1052 self.predicates.iter().map(|(p, _)| p.subst(tcx, substs)),
1056 pub fn instantiate_identity(&self, tcx: TyCtxt<'tcx>) -> InstantiatedPredicates<'tcx> {
1057 let mut instantiated = InstantiatedPredicates::empty();
1058 self.instantiate_identity_into(tcx, &mut instantiated);
1062 fn instantiate_identity_into(
1065 instantiated: &mut InstantiatedPredicates<'tcx>,
1067 if let Some(def_id) = self.parent {
1068 tcx.predicates_of(def_id).instantiate_identity_into(tcx, instantiated);
1070 instantiated.predicates.extend(self.predicates.iter().map(|&(p, _)| p))
1073 pub fn instantiate_supertrait(
1076 poly_trait_ref: &ty::PolyTraitRef<'tcx>,
1077 ) -> InstantiatedPredicates<'tcx> {
1078 assert_eq!(self.parent, None);
1079 InstantiatedPredicates {
1080 predicates: self.predicates.iter().map(|(pred, _)| {
1081 pred.subst_supertrait(tcx, poly_trait_ref)
1087 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
1088 pub enum Predicate<'tcx> {
1089 /// Corresponds to `where Foo: Bar<A, B, C>`. `Foo` here would be
1090 /// the `Self` type of the trait reference and `A`, `B`, and `C`
1091 /// would be the type parameters.
1092 Trait(PolyTraitPredicate<'tcx>),
1095 RegionOutlives(PolyRegionOutlivesPredicate<'tcx>),
1098 TypeOutlives(PolyTypeOutlivesPredicate<'tcx>),
1100 /// `where <T as TraitRef>::Name == X`, approximately.
1101 /// See the `ProjectionPredicate` struct for details.
1102 Projection(PolyProjectionPredicate<'tcx>),
1104 /// No syntax: `T` well-formed.
1105 WellFormed(Ty<'tcx>),
1107 /// Trait must be object-safe.
1110 /// No direct syntax. May be thought of as `where T: FnFoo<...>`
1111 /// for some substitutions `...` and `T` being a closure type.
1112 /// Satisfied (or refuted) once we know the closure's kind.
1113 ClosureKind(DefId, ClosureSubsts<'tcx>, ClosureKind),
1116 Subtype(PolySubtypePredicate<'tcx>),
1118 /// Constant initializer must evaluate successfully.
1119 ConstEvaluatable(DefId, SubstsRef<'tcx>),
1122 /// The crate outlives map is computed during typeck and contains the
1123 /// outlives of every item in the local crate. You should not use it
1124 /// directly, because to do so will make your pass dependent on the
1125 /// HIR of every item in the local crate. Instead, use
1126 /// `tcx.inferred_outlives_of()` to get the outlives for a *particular*
1128 #[derive(HashStable)]
1129 pub struct CratePredicatesMap<'tcx> {
1130 /// For each struct with outlive bounds, maps to a vector of the
1131 /// predicate of its outlive bounds. If an item has no outlives
1132 /// bounds, it will have no entry.
1133 pub predicates: FxHashMap<DefId, &'tcx [ty::Predicate<'tcx>]>,
1136 impl<'tcx> AsRef<Predicate<'tcx>> for Predicate<'tcx> {
1137 fn as_ref(&self) -> &Predicate<'tcx> {
1142 impl<'tcx> Predicate<'tcx> {
1143 /// Performs a substitution suitable for going from a
1144 /// poly-trait-ref to supertraits that must hold if that
1145 /// poly-trait-ref holds. This is slightly different from a normal
1146 /// substitution in terms of what happens with bound regions. See
1147 /// lengthy comment below for details.
1148 pub fn subst_supertrait(
1151 trait_ref: &ty::PolyTraitRef<'tcx>,
1152 ) -> ty::Predicate<'tcx> {
1153 // The interaction between HRTB and supertraits is not entirely
1154 // obvious. Let me walk you (and myself) through an example.
1156 // Let's start with an easy case. Consider two traits:
1158 // trait Foo<'a>: Bar<'a,'a> { }
1159 // trait Bar<'b,'c> { }
1161 // Now, if we have a trait reference `for<'x> T: Foo<'x>`, then
1162 // we can deduce that `for<'x> T: Bar<'x,'x>`. Basically, if we
1163 // knew that `Foo<'x>` (for any 'x) then we also know that
1164 // `Bar<'x,'x>` (for any 'x). This more-or-less falls out from
1165 // normal substitution.
1167 // In terms of why this is sound, the idea is that whenever there
1168 // is an impl of `T:Foo<'a>`, it must show that `T:Bar<'a,'a>`
1169 // holds. So if there is an impl of `T:Foo<'a>` that applies to
1170 // all `'a`, then we must know that `T:Bar<'a,'a>` holds for all
1173 // Another example to be careful of is this:
1175 // trait Foo1<'a>: for<'b> Bar1<'a,'b> { }
1176 // trait Bar1<'b,'c> { }
1178 // Here, if we have `for<'x> T: Foo1<'x>`, then what do we know?
1179 // The answer is that we know `for<'x,'b> T: Bar1<'x,'b>`. The
1180 // reason is similar to the previous example: any impl of
1181 // `T:Foo1<'x>` must show that `for<'b> T: Bar1<'x, 'b>`. So
1182 // basically we would want to collapse the bound lifetimes from
1183 // the input (`trait_ref`) and the supertraits.
1185 // To achieve this in practice is fairly straightforward. Let's
1186 // consider the more complicated scenario:
1188 // - We start out with `for<'x> T: Foo1<'x>`. In this case, `'x`
1189 // has a De Bruijn index of 1. We want to produce `for<'x,'b> T: Bar1<'x,'b>`,
1190 // where both `'x` and `'b` would have a DB index of 1.
1191 // The substitution from the input trait-ref is therefore going to be
1192 // `'a => 'x` (where `'x` has a DB index of 1).
1193 // - The super-trait-ref is `for<'b> Bar1<'a,'b>`, where `'a` is an
1194 // early-bound parameter and `'b' is a late-bound parameter with a
1196 // - If we replace `'a` with `'x` from the input, it too will have
1197 // a DB index of 1, and thus we'll have `for<'x,'b> Bar1<'x,'b>`
1198 // just as we wanted.
1200 // There is only one catch. If we just apply the substitution `'a
1201 // => 'x` to `for<'b> Bar1<'a,'b>`, the substitution code will
1202 // adjust the DB index because we substituting into a binder (it
1203 // tries to be so smart...) resulting in `for<'x> for<'b>
1204 // Bar1<'x,'b>` (we have no syntax for this, so use your
1205 // imagination). Basically the 'x will have DB index of 2 and 'b
1206 // will have DB index of 1. Not quite what we want. So we apply
1207 // the substitution to the *contents* of the trait reference,
1208 // rather than the trait reference itself (put another way, the
1209 // substitution code expects equal binding levels in the values
1210 // from the substitution and the value being substituted into, and
1211 // this trick achieves that).
1213 let substs = &trait_ref.skip_binder().substs;
1215 Predicate::Trait(ref binder) =>
1216 Predicate::Trait(binder.map_bound(|data| data.subst(tcx, substs))),
1217 Predicate::Subtype(ref binder) =>
1218 Predicate::Subtype(binder.map_bound(|data| data.subst(tcx, substs))),
1219 Predicate::RegionOutlives(ref binder) =>
1220 Predicate::RegionOutlives(binder.map_bound(|data| data.subst(tcx, substs))),
1221 Predicate::TypeOutlives(ref binder) =>
1222 Predicate::TypeOutlives(binder.map_bound(|data| data.subst(tcx, substs))),
1223 Predicate::Projection(ref binder) =>
1224 Predicate::Projection(binder.map_bound(|data| data.subst(tcx, substs))),
1225 Predicate::WellFormed(data) =>
1226 Predicate::WellFormed(data.subst(tcx, substs)),
1227 Predicate::ObjectSafe(trait_def_id) =>
1228 Predicate::ObjectSafe(trait_def_id),
1229 Predicate::ClosureKind(closure_def_id, closure_substs, kind) =>
1230 Predicate::ClosureKind(closure_def_id, closure_substs.subst(tcx, substs), kind),
1231 Predicate::ConstEvaluatable(def_id, const_substs) =>
1232 Predicate::ConstEvaluatable(def_id, const_substs.subst(tcx, substs)),
1237 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
1238 pub struct TraitPredicate<'tcx> {
1239 pub trait_ref: TraitRef<'tcx>
1242 pub type PolyTraitPredicate<'tcx> = ty::Binder<TraitPredicate<'tcx>>;
1244 impl<'tcx> TraitPredicate<'tcx> {
1245 pub fn def_id(&self) -> DefId {
1246 self.trait_ref.def_id
1249 pub fn input_types<'a>(&'a self) -> impl DoubleEndedIterator<Item = Ty<'tcx>> + 'a {
1250 self.trait_ref.input_types()
1253 pub fn self_ty(&self) -> Ty<'tcx> {
1254 self.trait_ref.self_ty()
1258 impl<'tcx> PolyTraitPredicate<'tcx> {
1259 pub fn def_id(&self) -> DefId {
1260 // Ok to skip binder since trait `DefId` does not care about regions.
1261 self.skip_binder().def_id()
1265 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord,
1266 Hash, Debug, RustcEncodable, RustcDecodable, HashStable)]
1267 pub struct OutlivesPredicate<A, B>(pub A, pub B); // `A: B`
1268 pub type PolyOutlivesPredicate<A, B> = ty::Binder<OutlivesPredicate<A, B>>;
1269 pub type RegionOutlivesPredicate<'tcx> = OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>;
1270 pub type TypeOutlivesPredicate<'tcx> = OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>;
1271 pub type PolyRegionOutlivesPredicate<'tcx> = ty::Binder<RegionOutlivesPredicate<'tcx>>;
1272 pub type PolyTypeOutlivesPredicate<'tcx> = ty::Binder<TypeOutlivesPredicate<'tcx>>;
1274 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable, HashStable)]
1275 pub struct SubtypePredicate<'tcx> {
1276 pub a_is_expected: bool,
1280 pub type PolySubtypePredicate<'tcx> = ty::Binder<SubtypePredicate<'tcx>>;
1282 /// This kind of predicate has no *direct* correspondent in the
1283 /// syntax, but it roughly corresponds to the syntactic forms:
1285 /// 1. `T: TraitRef<..., Item = Type>`
1286 /// 2. `<T as TraitRef<...>>::Item == Type` (NYI)
1288 /// In particular, form #1 is "desugared" to the combination of a
1289 /// normal trait predicate (`T: TraitRef<...>`) and one of these
1290 /// predicates. Form #2 is a broader form in that it also permits
1291 /// equality between arbitrary types. Processing an instance of
1292 /// Form #2 eventually yields one of these `ProjectionPredicate`
1293 /// instances to normalize the LHS.
1294 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
1295 pub struct ProjectionPredicate<'tcx> {
1296 pub projection_ty: ProjectionTy<'tcx>,
1300 pub type PolyProjectionPredicate<'tcx> = Binder<ProjectionPredicate<'tcx>>;
1302 impl<'tcx> PolyProjectionPredicate<'tcx> {
1303 /// Returns the `DefId` of the associated item being projected.
1304 pub fn item_def_id(&self) -> DefId {
1305 self.skip_binder().projection_ty.item_def_id
1309 pub fn to_poly_trait_ref(&self, tcx: TyCtxt<'_>) -> PolyTraitRef<'tcx> {
1310 // Note: unlike with `TraitRef::to_poly_trait_ref()`,
1311 // `self.0.trait_ref` is permitted to have escaping regions.
1312 // This is because here `self` has a `Binder` and so does our
1313 // return value, so we are preserving the number of binding
1315 self.map_bound(|predicate| predicate.projection_ty.trait_ref(tcx))
1318 pub fn ty(&self) -> Binder<Ty<'tcx>> {
1319 self.map_bound(|predicate| predicate.ty)
1322 /// The `DefId` of the `TraitItem` for the associated type.
1324 /// Note that this is not the `DefId` of the `TraitRef` containing this
1325 /// associated type, which is in `tcx.associated_item(projection_def_id()).container`.
1326 pub fn projection_def_id(&self) -> DefId {
1327 // Ok to skip binder since trait `DefId` does not care about regions.
1328 self.skip_binder().projection_ty.item_def_id
1332 pub trait ToPolyTraitRef<'tcx> {
1333 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx>;
1336 impl<'tcx> ToPolyTraitRef<'tcx> for TraitRef<'tcx> {
1337 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
1338 ty::Binder::dummy(self.clone())
1342 impl<'tcx> ToPolyTraitRef<'tcx> for PolyTraitPredicate<'tcx> {
1343 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
1344 self.map_bound_ref(|trait_pred| trait_pred.trait_ref)
1348 pub trait ToPredicate<'tcx> {
1349 fn to_predicate(&self) -> Predicate<'tcx>;
1352 impl<'tcx> ToPredicate<'tcx> for TraitRef<'tcx> {
1353 fn to_predicate(&self) -> Predicate<'tcx> {
1354 ty::Predicate::Trait(ty::Binder::dummy(ty::TraitPredicate {
1355 trait_ref: self.clone()
1360 impl<'tcx> ToPredicate<'tcx> for PolyTraitRef<'tcx> {
1361 fn to_predicate(&self) -> Predicate<'tcx> {
1362 ty::Predicate::Trait(self.to_poly_trait_predicate())
1366 impl<'tcx> ToPredicate<'tcx> for PolyRegionOutlivesPredicate<'tcx> {
1367 fn to_predicate(&self) -> Predicate<'tcx> {
1368 Predicate::RegionOutlives(self.clone())
1372 impl<'tcx> ToPredicate<'tcx> for PolyTypeOutlivesPredicate<'tcx> {
1373 fn to_predicate(&self) -> Predicate<'tcx> {
1374 Predicate::TypeOutlives(self.clone())
1378 impl<'tcx> ToPredicate<'tcx> for PolyProjectionPredicate<'tcx> {
1379 fn to_predicate(&self) -> Predicate<'tcx> {
1380 Predicate::Projection(self.clone())
1384 // A custom iterator used by `Predicate::walk_tys`.
1385 enum WalkTysIter<'tcx, I, J, K>
1386 where I: Iterator<Item = Ty<'tcx>>,
1387 J: Iterator<Item = Ty<'tcx>>,
1388 K: Iterator<Item = Ty<'tcx>>
1392 Two(Ty<'tcx>, Ty<'tcx>),
1398 impl<'tcx, I, J, K> Iterator for WalkTysIter<'tcx, I, J, K>
1399 where I: Iterator<Item = Ty<'tcx>>,
1400 J: Iterator<Item = Ty<'tcx>>,
1401 K: Iterator<Item = Ty<'tcx>>
1403 type Item = Ty<'tcx>;
1405 fn next(&mut self) -> Option<Ty<'tcx>> {
1407 WalkTysIter::None => None,
1408 WalkTysIter::One(item) => {
1409 *self = WalkTysIter::None;
1412 WalkTysIter::Two(item1, item2) => {
1413 *self = WalkTysIter::One(item2);
1416 WalkTysIter::Types(ref mut iter) => {
1419 WalkTysIter::InputTypes(ref mut iter) => {
1422 WalkTysIter::ProjectionTypes(ref mut iter) => {
1429 impl<'tcx> Predicate<'tcx> {
1430 /// Iterates over the types in this predicate. Note that in all
1431 /// cases this is skipping over a binder, so late-bound regions
1432 /// with depth 0 are bound by the predicate.
1433 pub fn walk_tys(&'a self) -> impl Iterator<Item = Ty<'tcx>> + 'a {
1435 ty::Predicate::Trait(ref data) => {
1436 WalkTysIter::InputTypes(data.skip_binder().input_types())
1438 ty::Predicate::Subtype(binder) => {
1439 let SubtypePredicate { a, b, a_is_expected: _ } = binder.skip_binder();
1440 WalkTysIter::Two(a, b)
1442 ty::Predicate::TypeOutlives(binder) => {
1443 WalkTysIter::One(binder.skip_binder().0)
1445 ty::Predicate::RegionOutlives(..) => {
1448 ty::Predicate::Projection(ref data) => {
1449 let inner = data.skip_binder();
1450 WalkTysIter::ProjectionTypes(
1451 inner.projection_ty.substs.types().chain(Some(inner.ty)))
1453 ty::Predicate::WellFormed(data) => {
1454 WalkTysIter::One(data)
1456 ty::Predicate::ObjectSafe(_trait_def_id) => {
1459 ty::Predicate::ClosureKind(_closure_def_id, closure_substs, _kind) => {
1460 WalkTysIter::Types(closure_substs.substs.types())
1462 ty::Predicate::ConstEvaluatable(_, substs) => {
1463 WalkTysIter::Types(substs.types())
1468 pub fn to_opt_poly_trait_ref(&self) -> Option<PolyTraitRef<'tcx>> {
1470 Predicate::Trait(ref t) => {
1471 Some(t.to_poly_trait_ref())
1473 Predicate::Projection(..) |
1474 Predicate::Subtype(..) |
1475 Predicate::RegionOutlives(..) |
1476 Predicate::WellFormed(..) |
1477 Predicate::ObjectSafe(..) |
1478 Predicate::ClosureKind(..) |
1479 Predicate::TypeOutlives(..) |
1480 Predicate::ConstEvaluatable(..) => {
1486 pub fn to_opt_type_outlives(&self) -> Option<PolyTypeOutlivesPredicate<'tcx>> {
1488 Predicate::TypeOutlives(data) => {
1491 Predicate::Trait(..) |
1492 Predicate::Projection(..) |
1493 Predicate::Subtype(..) |
1494 Predicate::RegionOutlives(..) |
1495 Predicate::WellFormed(..) |
1496 Predicate::ObjectSafe(..) |
1497 Predicate::ClosureKind(..) |
1498 Predicate::ConstEvaluatable(..) => {
1505 /// Represents the bounds declared on a particular set of type
1506 /// parameters. Should eventually be generalized into a flag list of
1507 /// where-clauses. You can obtain a `InstantiatedPredicates` list from a
1508 /// `GenericPredicates` by using the `instantiate` method. Note that this method
1509 /// reflects an important semantic invariant of `InstantiatedPredicates`: while
1510 /// the `GenericPredicates` are expressed in terms of the bound type
1511 /// parameters of the impl/trait/whatever, an `InstantiatedPredicates` instance
1512 /// represented a set of bounds for some particular instantiation,
1513 /// meaning that the generic parameters have been substituted with
1518 /// struct Foo<T, U: Bar<T>> { ... }
1520 /// Here, the `GenericPredicates` for `Foo` would contain a list of bounds like
1521 /// `[[], [U:Bar<T>]]`. Now if there were some particular reference
1522 /// like `Foo<isize,usize>`, then the `InstantiatedPredicates` would be `[[],
1523 /// [usize:Bar<isize>]]`.
1524 #[derive(Clone, Debug)]
1525 pub struct InstantiatedPredicates<'tcx> {
1526 pub predicates: Vec<Predicate<'tcx>>,
1529 impl<'tcx> InstantiatedPredicates<'tcx> {
1530 pub fn empty() -> InstantiatedPredicates<'tcx> {
1531 InstantiatedPredicates { predicates: vec![] }
1534 pub fn is_empty(&self) -> bool {
1535 self.predicates.is_empty()
1539 rustc_index::newtype_index! {
1540 /// "Universes" are used during type- and trait-checking in the
1541 /// presence of `for<..>` binders to control what sets of names are
1542 /// visible. Universes are arranged into a tree: the root universe
1543 /// contains names that are always visible. Each child then adds a new
1544 /// set of names that are visible, in addition to those of its parent.
1545 /// We say that the child universe "extends" the parent universe with
1548 /// To make this more concrete, consider this program:
1552 /// fn bar<T>(x: T) {
1553 /// let y: for<'a> fn(&'a u8, Foo) = ...;
1557 /// The struct name `Foo` is in the root universe U0. But the type
1558 /// parameter `T`, introduced on `bar`, is in an extended universe U1
1559 /// -- i.e., within `bar`, we can name both `T` and `Foo`, but outside
1560 /// of `bar`, we cannot name `T`. Then, within the type of `y`, the
1561 /// region `'a` is in a universe U2 that extends U1, because we can
1562 /// name it inside the fn type but not outside.
1564 /// Universes are used to do type- and trait-checking around these
1565 /// "forall" binders (also called **universal quantification**). The
1566 /// idea is that when, in the body of `bar`, we refer to `T` as a
1567 /// type, we aren't referring to any type in particular, but rather a
1568 /// kind of "fresh" type that is distinct from all other types we have
1569 /// actually declared. This is called a **placeholder** type, and we
1570 /// use universes to talk about this. In other words, a type name in
1571 /// universe 0 always corresponds to some "ground" type that the user
1572 /// declared, but a type name in a non-zero universe is a placeholder
1573 /// type -- an idealized representative of "types in general" that we
1574 /// use for checking generic functions.
1575 pub struct UniverseIndex {
1576 DEBUG_FORMAT = "U{}",
1580 impl_stable_hash_for!(struct UniverseIndex { private });
1582 impl UniverseIndex {
1583 pub const ROOT: UniverseIndex = UniverseIndex::from_u32_const(0);
1585 /// Returns the "next" universe index in order -- this new index
1586 /// is considered to extend all previous universes. This
1587 /// corresponds to entering a `forall` quantifier. So, for
1588 /// example, suppose we have this type in universe `U`:
1591 /// for<'a> fn(&'a u32)
1594 /// Once we "enter" into this `for<'a>` quantifier, we are in a
1595 /// new universe that extends `U` -- in this new universe, we can
1596 /// name the region `'a`, but that region was not nameable from
1597 /// `U` because it was not in scope there.
1598 pub fn next_universe(self) -> UniverseIndex {
1599 UniverseIndex::from_u32(self.private.checked_add(1).unwrap())
1602 /// Returns `true` if `self` can name a name from `other` -- in other words,
1603 /// if the set of names in `self` is a superset of those in
1604 /// `other` (`self >= other`).
1605 pub fn can_name(self, other: UniverseIndex) -> bool {
1606 self.private >= other.private
1609 /// Returns `true` if `self` cannot name some names from `other` -- in other
1610 /// words, if the set of names in `self` is a strict subset of
1611 /// those in `other` (`self < other`).
1612 pub fn cannot_name(self, other: UniverseIndex) -> bool {
1613 self.private < other.private
1617 /// The "placeholder index" fully defines a placeholder region.
1618 /// Placeholder regions are identified by both a **universe** as well
1619 /// as a "bound-region" within that universe. The `bound_region` is
1620 /// basically a name -- distinct bound regions within the same
1621 /// universe are just two regions with an unknown relationship to one
1623 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, PartialOrd, Ord)]
1624 pub struct Placeholder<T> {
1625 pub universe: UniverseIndex,
1629 impl<'a, T> HashStable<StableHashingContext<'a>> for Placeholder<T>
1631 T: HashStable<StableHashingContext<'a>>,
1633 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
1634 self.universe.hash_stable(hcx, hasher);
1635 self.name.hash_stable(hcx, hasher);
1639 pub type PlaceholderRegion = Placeholder<BoundRegion>;
1641 pub type PlaceholderType = Placeholder<BoundVar>;
1643 pub type PlaceholderConst = Placeholder<BoundVar>;
1645 /// When type checking, we use the `ParamEnv` to track
1646 /// details about the set of where-clauses that are in scope at this
1647 /// particular point.
1648 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable)]
1649 pub struct ParamEnv<'tcx> {
1650 /// `Obligation`s that the caller must satisfy. This is basically
1651 /// the set of bounds on the in-scope type parameters, translated
1652 /// into `Obligation`s, and elaborated and normalized.
1653 pub caller_bounds: &'tcx List<ty::Predicate<'tcx>>,
1655 /// Typically, this is `Reveal::UserFacing`, but during codegen we
1656 /// want `Reveal::All` -- note that this is always paired with an
1657 /// empty environment. To get that, use `ParamEnv::reveal()`.
1658 pub reveal: traits::Reveal,
1660 /// If this `ParamEnv` comes from a call to `tcx.param_env(def_id)`,
1661 /// register that `def_id` (useful for transitioning to the chalk trait
1663 pub def_id: Option<DefId>,
1666 impl<'tcx> ParamEnv<'tcx> {
1667 /// Construct a trait environment suitable for contexts where
1668 /// there are no where-clauses in scope. Hidden types (like `impl
1669 /// Trait`) are left hidden, so this is suitable for ordinary
1672 pub fn empty() -> Self {
1673 Self::new(List::empty(), Reveal::UserFacing, None)
1676 /// Construct a trait environment with no where-clauses in scope
1677 /// where the values of all `impl Trait` and other hidden types
1678 /// are revealed. This is suitable for monomorphized, post-typeck
1679 /// environments like codegen or doing optimizations.
1681 /// N.B., if you want to have predicates in scope, use `ParamEnv::new`,
1682 /// or invoke `param_env.with_reveal_all()`.
1684 pub fn reveal_all() -> Self {
1685 Self::new(List::empty(), Reveal::All, None)
1688 /// Construct a trait environment with the given set of predicates.
1691 caller_bounds: &'tcx List<ty::Predicate<'tcx>>,
1693 def_id: Option<DefId>
1695 ty::ParamEnv { caller_bounds, reveal, def_id }
1698 /// Returns a new parameter environment with the same clauses, but
1699 /// which "reveals" the true results of projections in all cases
1700 /// (even for associated types that are specializable). This is
1701 /// the desired behavior during codegen and certain other special
1702 /// contexts; normally though we want to use `Reveal::UserFacing`,
1703 /// which is the default.
1704 pub fn with_reveal_all(self) -> Self {
1705 ty::ParamEnv { reveal: Reveal::All, ..self }
1708 /// Returns this same environment but with no caller bounds.
1709 pub fn without_caller_bounds(self) -> Self {
1710 ty::ParamEnv { caller_bounds: List::empty(), ..self }
1713 /// Creates a suitable environment in which to perform trait
1714 /// queries on the given value. When type-checking, this is simply
1715 /// the pair of the environment plus value. But when reveal is set to
1716 /// All, then if `value` does not reference any type parameters, we will
1717 /// pair it with the empty environment. This improves caching and is generally
1720 /// N.B., we preserve the environment when type-checking because it
1721 /// is possible for the user to have wacky where-clauses like
1722 /// `where Box<u32>: Copy`, which are clearly never
1723 /// satisfiable. We generally want to behave as if they were true,
1724 /// although the surrounding function is never reachable.
1725 pub fn and<T: TypeFoldable<'tcx>>(self, value: T) -> ParamEnvAnd<'tcx, T> {
1727 Reveal::UserFacing => {
1735 if value.has_placeholders()
1736 || value.needs_infer()
1737 || value.has_param_types()
1745 param_env: self.without_caller_bounds(),
1754 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1755 pub struct ParamEnvAnd<'tcx, T> {
1756 pub param_env: ParamEnv<'tcx>,
1760 impl<'tcx, T> ParamEnvAnd<'tcx, T> {
1761 pub fn into_parts(self) -> (ParamEnv<'tcx>, T) {
1762 (self.param_env, self.value)
1766 impl<'a, 'tcx, T> HashStable<StableHashingContext<'a>> for ParamEnvAnd<'tcx, T>
1768 T: HashStable<StableHashingContext<'a>>,
1770 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
1776 param_env.hash_stable(hcx, hasher);
1777 value.hash_stable(hcx, hasher);
1781 #[derive(Copy, Clone, Debug, HashStable)]
1782 pub struct Destructor {
1783 /// The `DefId` of the destructor method
1788 #[derive(HashStable)]
1789 pub struct AdtFlags: u32 {
1790 const NO_ADT_FLAGS = 0;
1791 /// Indicates whether the ADT is an enum.
1792 const IS_ENUM = 1 << 0;
1793 /// Indicates whether the ADT is a union.
1794 const IS_UNION = 1 << 1;
1795 /// Indicates whether the ADT is a struct.
1796 const IS_STRUCT = 1 << 2;
1797 /// Indicates whether the ADT is a struct and has a constructor.
1798 const HAS_CTOR = 1 << 3;
1799 /// Indicates whether the type is a `PhantomData`.
1800 const IS_PHANTOM_DATA = 1 << 4;
1801 /// Indicates whether the type has a `#[fundamental]` attribute.
1802 const IS_FUNDAMENTAL = 1 << 5;
1803 /// Indicates whether the type is a `Box`.
1804 const IS_BOX = 1 << 6;
1805 /// Indicates whether the type is an `Arc`.
1806 const IS_ARC = 1 << 7;
1807 /// Indicates whether the type is an `Rc`.
1808 const IS_RC = 1 << 8;
1809 /// Indicates whether the variant list of this ADT is `#[non_exhaustive]`.
1810 /// (i.e., this flag is never set unless this ADT is an enum).
1811 const IS_VARIANT_LIST_NON_EXHAUSTIVE = 1 << 9;
1816 #[derive(HashStable)]
1817 pub struct VariantFlags: u32 {
1818 const NO_VARIANT_FLAGS = 0;
1819 /// Indicates whether the field list of this variant is `#[non_exhaustive]`.
1820 const IS_FIELD_LIST_NON_EXHAUSTIVE = 1 << 0;
1824 /// Definition of a variant -- a struct's fields or a enum variant.
1826 pub struct VariantDef {
1827 /// `DefId` that identifies the variant itself.
1828 /// If this variant belongs to a struct or union, then this is a copy of its `DefId`.
1830 /// `DefId` that identifies the variant's constructor.
1831 /// If this variant is a struct variant, then this is `None`.
1832 pub ctor_def_id: Option<DefId>,
1833 /// Variant or struct name.
1835 /// Discriminant of this variant.
1836 pub discr: VariantDiscr,
1837 /// Fields of this variant.
1838 pub fields: Vec<FieldDef>,
1839 /// Type of constructor of variant.
1840 pub ctor_kind: CtorKind,
1841 /// Flags of the variant (e.g. is field list non-exhaustive)?
1842 flags: VariantFlags,
1843 /// Variant is obtained as part of recovering from a syntactic error.
1844 /// May be incomplete or bogus.
1845 pub recovered: bool,
1848 impl<'tcx> VariantDef {
1849 /// Creates a new `VariantDef`.
1851 /// `variant_did` is the `DefId` that identifies the enum variant (if this `VariantDef`
1852 /// represents an enum variant).
1854 /// `ctor_did` is the `DefId` that identifies the constructor of unit or
1855 /// tuple-variants/structs. If this is a `struct`-variant then this should be `None`.
1857 /// `parent_did` is the `DefId` of the `AdtDef` representing the enum or struct that
1858 /// owns this variant. It is used for checking if a struct has `#[non_exhaustive]` w/out having
1859 /// to go through the redirect of checking the ctor's attributes - but compiling a small crate
1860 /// requires loading the `AdtDef`s for all the structs in the universe (e.g., coherence for any
1861 /// built-in trait), and we do not want to load attributes twice.
1863 /// If someone speeds up attribute loading to not be a performance concern, they can
1864 /// remove this hack and use the constructor `DefId` everywhere.
1868 variant_did: Option<DefId>,
1869 ctor_def_id: Option<DefId>,
1870 discr: VariantDiscr,
1871 fields: Vec<FieldDef>,
1872 ctor_kind: CtorKind,
1878 "VariantDef::new(ident = {:?}, variant_did = {:?}, ctor_def_id = {:?}, discr = {:?},
1879 fields = {:?}, ctor_kind = {:?}, adt_kind = {:?}, parent_did = {:?})",
1880 ident, variant_did, ctor_def_id, discr, fields, ctor_kind, adt_kind, parent_did,
1883 let mut flags = VariantFlags::NO_VARIANT_FLAGS;
1884 if adt_kind == AdtKind::Struct && tcx.has_attr(parent_did, sym::non_exhaustive) {
1885 debug!("found non-exhaustive field list for {:?}", parent_did);
1886 flags = flags | VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE;
1887 } else if let Some(variant_did) = variant_did {
1888 if tcx.has_attr(variant_did, sym::non_exhaustive) {
1889 debug!("found non-exhaustive field list for {:?}", variant_did);
1890 flags = flags | VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE;
1895 def_id: variant_did.unwrap_or(parent_did),
1906 /// Is this field list non-exhaustive?
1908 pub fn is_field_list_non_exhaustive(&self) -> bool {
1909 self.flags.intersects(VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE)
1913 impl_stable_hash_for!(struct VariantDef {
1916 ident -> (ident.name),
1924 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
1925 pub enum VariantDiscr {
1926 /// Explicit value for this variant, i.e., `X = 123`.
1927 /// The `DefId` corresponds to the embedded constant.
1930 /// The previous variant's discriminant plus one.
1931 /// For efficiency reasons, the distance from the
1932 /// last `Explicit` discriminant is being stored,
1933 /// or `0` for the first variant, if it has none.
1937 #[derive(Debug, HashStable)]
1938 pub struct FieldDef {
1940 #[stable_hasher(project(name))]
1942 pub vis: Visibility,
1945 /// The definition of a user-defined type, e.g., a `struct`, `enum`, or `union`.
1947 /// These are all interned (by `intern_adt_def`) into the `adt_defs` table.
1949 /// The initialism *"Adt"* stands for an [*algebraic data type (ADT)*][adt].
1950 /// This is slightly wrong because `union`s are not ADTs.
1951 /// Moreover, Rust only allows recursive data types through indirection.
1953 /// [adt]: https://en.wikipedia.org/wiki/Algebraic_data_type
1955 /// `DefId` of the struct, enum or union item.
1957 /// Variants of the ADT. If this is a struct or union, then there will be a single variant.
1958 pub variants: IndexVec<self::layout::VariantIdx, VariantDef>,
1959 /// Flags of the ADT (e.g. is this a struct? is this non-exhaustive?)
1961 /// Repr options provided by the user.
1962 pub repr: ReprOptions,
1965 impl PartialOrd for AdtDef {
1966 fn partial_cmp(&self, other: &AdtDef) -> Option<Ordering> {
1967 Some(self.cmp(&other))
1971 /// There should be only one AdtDef for each `did`, therefore
1972 /// it is fine to implement `Ord` only based on `did`.
1973 impl Ord for AdtDef {
1974 fn cmp(&self, other: &AdtDef) -> Ordering {
1975 self.did.cmp(&other.did)
1979 impl PartialEq for AdtDef {
1980 // AdtDef are always interned and this is part of TyS equality
1982 fn eq(&self, other: &Self) -> bool { ptr::eq(self, other) }
1985 impl Eq for AdtDef {}
1987 impl Hash for AdtDef {
1989 fn hash<H: Hasher>(&self, s: &mut H) {
1990 (self as *const AdtDef).hash(s)
1994 impl<'tcx> rustc_serialize::UseSpecializedEncodable for &'tcx AdtDef {
1995 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
2000 impl<'tcx> rustc_serialize::UseSpecializedDecodable for &'tcx AdtDef {}
2003 impl<'a> HashStable<StableHashingContext<'a>> for AdtDef {
2004 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
2006 static CACHE: RefCell<FxHashMap<usize, Fingerprint>> = Default::default();
2009 let hash: Fingerprint = CACHE.with(|cache| {
2010 let addr = self as *const AdtDef as usize;
2011 *cache.borrow_mut().entry(addr).or_insert_with(|| {
2019 let mut hasher = StableHasher::new();
2020 did.hash_stable(hcx, &mut hasher);
2021 variants.hash_stable(hcx, &mut hasher);
2022 flags.hash_stable(hcx, &mut hasher);
2023 repr.hash_stable(hcx, &mut hasher);
2029 hash.hash_stable(hcx, hasher);
2033 #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
2034 pub enum AdtKind { Struct, Union, Enum }
2036 impl Into<DataTypeKind> for AdtKind {
2037 fn into(self) -> DataTypeKind {
2039 AdtKind::Struct => DataTypeKind::Struct,
2040 AdtKind::Union => DataTypeKind::Union,
2041 AdtKind::Enum => DataTypeKind::Enum,
2047 #[derive(RustcEncodable, RustcDecodable, Default)]
2048 pub struct ReprFlags: u8 {
2049 const IS_C = 1 << 0;
2050 const IS_SIMD = 1 << 1;
2051 const IS_TRANSPARENT = 1 << 2;
2052 // Internal only for now. If true, don't reorder fields.
2053 const IS_LINEAR = 1 << 3;
2055 // Any of these flags being set prevent field reordering optimisation.
2056 const IS_UNOPTIMISABLE = ReprFlags::IS_C.bits |
2057 ReprFlags::IS_SIMD.bits |
2058 ReprFlags::IS_LINEAR.bits;
2062 impl_stable_hash_for!(struct ReprFlags {
2066 /// Represents the repr options provided by the user,
2067 #[derive(Copy, Clone, Debug, Eq, PartialEq, RustcEncodable, RustcDecodable, Default)]
2068 pub struct ReprOptions {
2069 pub int: Option<attr::IntType>,
2070 pub align: Option<Align>,
2071 pub pack: Option<Align>,
2072 pub flags: ReprFlags,
2075 impl_stable_hash_for!(struct ReprOptions {
2083 pub fn new(tcx: TyCtxt<'_>, did: DefId) -> ReprOptions {
2084 let mut flags = ReprFlags::empty();
2085 let mut size = None;
2086 let mut max_align: Option<Align> = None;
2087 let mut min_pack: Option<Align> = None;
2088 for attr in tcx.get_attrs(did).iter() {
2089 for r in attr::find_repr_attrs(&tcx.sess.parse_sess, attr) {
2090 flags.insert(match r {
2091 attr::ReprC => ReprFlags::IS_C,
2092 attr::ReprPacked(pack) => {
2093 let pack = Align::from_bytes(pack as u64).unwrap();
2094 min_pack = Some(if let Some(min_pack) = min_pack {
2101 attr::ReprTransparent => ReprFlags::IS_TRANSPARENT,
2102 attr::ReprSimd => ReprFlags::IS_SIMD,
2103 attr::ReprInt(i) => {
2107 attr::ReprAlign(align) => {
2108 max_align = max_align.max(Some(Align::from_bytes(align as u64).unwrap()));
2115 // This is here instead of layout because the choice must make it into metadata.
2116 if !tcx.consider_optimizing(|| format!("Reorder fields of {:?}", tcx.def_path_str(did))) {
2117 flags.insert(ReprFlags::IS_LINEAR);
2119 ReprOptions { int: size, align: max_align, pack: min_pack, flags: flags }
2123 pub fn simd(&self) -> bool { self.flags.contains(ReprFlags::IS_SIMD) }
2125 pub fn c(&self) -> bool { self.flags.contains(ReprFlags::IS_C) }
2127 pub fn packed(&self) -> bool { self.pack.is_some() }
2129 pub fn transparent(&self) -> bool { self.flags.contains(ReprFlags::IS_TRANSPARENT) }
2131 pub fn linear(&self) -> bool { self.flags.contains(ReprFlags::IS_LINEAR) }
2133 pub fn discr_type(&self) -> attr::IntType {
2134 self.int.unwrap_or(attr::SignedInt(ast::IntTy::Isize))
2137 /// Returns `true` if this `#[repr()]` should inhabit "smart enum
2138 /// layout" optimizations, such as representing `Foo<&T>` as a
2140 pub fn inhibit_enum_layout_opt(&self) -> bool {
2141 self.c() || self.int.is_some()
2144 /// Returns `true` if this `#[repr()]` should inhibit struct field reordering
2145 /// optimizations, such as with `repr(C)`, `repr(packed(1))`, or `repr(<int>)`.
2146 pub fn inhibit_struct_field_reordering_opt(&self) -> bool {
2147 if let Some(pack) = self.pack {
2148 if pack.bytes() == 1 {
2152 self.flags.intersects(ReprFlags::IS_UNOPTIMISABLE) || self.int.is_some()
2155 /// Returns `true` if this `#[repr()]` should inhibit union ABI optimisations.
2156 pub fn inhibit_union_abi_opt(&self) -> bool {
2162 /// Creates a new `AdtDef`.
2167 variants: IndexVec<VariantIdx, VariantDef>,
2170 debug!("AdtDef::new({:?}, {:?}, {:?}, {:?})", did, kind, variants, repr);
2171 let mut flags = AdtFlags::NO_ADT_FLAGS;
2173 if kind == AdtKind::Enum && tcx.has_attr(did, sym::non_exhaustive) {
2174 debug!("found non-exhaustive variant list for {:?}", did);
2175 flags = flags | AdtFlags::IS_VARIANT_LIST_NON_EXHAUSTIVE;
2178 flags |= match kind {
2179 AdtKind::Enum => AdtFlags::IS_ENUM,
2180 AdtKind::Union => AdtFlags::IS_UNION,
2181 AdtKind::Struct => AdtFlags::IS_STRUCT,
2184 if kind == AdtKind::Struct && variants[VariantIdx::new(0)].ctor_def_id.is_some() {
2185 flags |= AdtFlags::HAS_CTOR;
2188 let attrs = tcx.get_attrs(did);
2189 if attr::contains_name(&attrs, sym::fundamental) {
2190 flags |= AdtFlags::IS_FUNDAMENTAL;
2192 if Some(did) == tcx.lang_items().phantom_data() {
2193 flags |= AdtFlags::IS_PHANTOM_DATA;
2195 if Some(did) == tcx.lang_items().owned_box() {
2196 flags |= AdtFlags::IS_BOX;
2198 if Some(did) == tcx.lang_items().arc() {
2199 flags |= AdtFlags::IS_ARC;
2201 if Some(did) == tcx.lang_items().rc() {
2202 flags |= AdtFlags::IS_RC;
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 `Arc<T>`.
2288 pub fn is_arc(&self) -> bool {
2289 self.flags.contains(AdtFlags::IS_ARC)
2292 /// Returns `true` if this is `Rc<T>`.
2293 pub fn is_rc(&self) -> bool {
2294 self.flags.contains(AdtFlags::IS_RC)
2297 /// Returns `true` if this is Box<T>.
2299 pub fn is_box(&self) -> bool {
2300 self.flags.contains(AdtFlags::IS_BOX)
2303 /// Returns `true` if this type has a destructor.
2304 pub fn has_dtor(&self, tcx: TyCtxt<'tcx>) -> bool {
2305 self.destructor(tcx).is_some()
2308 /// Asserts this is a struct or union and returns its unique variant.
2309 pub fn non_enum_variant(&self) -> &VariantDef {
2310 assert!(self.is_struct() || self.is_union());
2311 &self.variants[VariantIdx::new(0)]
2315 pub fn predicates(&self, tcx: TyCtxt<'tcx>) -> &'tcx GenericPredicates<'tcx> {
2316 tcx.predicates_of(self.did)
2319 /// Returns an iterator over all fields contained
2322 pub fn all_fields(&self) -> impl Iterator<Item=&FieldDef> + Clone {
2323 self.variants.iter().flat_map(|v| v.fields.iter())
2326 pub fn is_payloadfree(&self) -> bool {
2327 !self.variants.is_empty() &&
2328 self.variants.iter().all(|v| v.fields.is_empty())
2331 /// Return a `VariantDef` given a variant id.
2332 pub fn variant_with_id(&self, vid: DefId) -> &VariantDef {
2333 self.variants.iter().find(|v| v.def_id == vid)
2334 .expect("variant_with_id: unknown variant")
2337 /// Return a `VariantDef` given a constructor id.
2338 pub fn variant_with_ctor_id(&self, cid: DefId) -> &VariantDef {
2339 self.variants.iter().find(|v| v.ctor_def_id == Some(cid))
2340 .expect("variant_with_ctor_id: unknown variant")
2343 /// Return the index of `VariantDef` given a variant id.
2344 pub fn variant_index_with_id(&self, vid: DefId) -> VariantIdx {
2345 self.variants.iter_enumerated().find(|(_, v)| v.def_id == vid)
2346 .expect("variant_index_with_id: unknown variant").0
2349 /// Return the index of `VariantDef` given a constructor id.
2350 pub fn variant_index_with_ctor_id(&self, cid: DefId) -> VariantIdx {
2351 self.variants.iter_enumerated().find(|(_, v)| v.ctor_def_id == Some(cid))
2352 .expect("variant_index_with_ctor_id: unknown variant").0
2355 pub fn variant_of_res(&self, res: Res) -> &VariantDef {
2357 Res::Def(DefKind::Variant, vid) => self.variant_with_id(vid),
2358 Res::Def(DefKind::Ctor(..), cid) => self.variant_with_ctor_id(cid),
2359 Res::Def(DefKind::Struct, _) | Res::Def(DefKind::Union, _) |
2360 Res::Def(DefKind::TyAlias, _) | Res::Def(DefKind::AssocTy, _) | Res::SelfTy(..) |
2361 Res::SelfCtor(..) => self.non_enum_variant(),
2362 _ => bug!("unexpected res {:?} in variant_of_res", res)
2367 pub fn eval_explicit_discr(&self, tcx: TyCtxt<'tcx>, expr_did: DefId) -> Option<Discr<'tcx>> {
2368 let param_env = tcx.param_env(expr_did);
2369 let repr_type = self.repr.discr_type();
2370 let substs = InternalSubsts::identity_for_item(tcx, expr_did);
2371 let instance = ty::Instance::new(expr_did, substs);
2372 let cid = GlobalId {
2376 match tcx.const_eval(param_env.and(cid)) {
2378 // FIXME: Find the right type and use it instead of `val.ty` here
2379 if let Some(b) = val.try_eval_bits(tcx, param_env, val.ty) {
2380 trace!("discriminants: {} ({:?})", b, repr_type);
2386 info!("invalid enum discriminant: {:#?}", val);
2387 crate::mir::interpret::struct_error(
2388 tcx.at(tcx.def_span(expr_did)),
2389 "constant evaluation of enum discriminant resulted in non-integer",
2394 Err(ErrorHandled::Reported) => {
2395 if !expr_did.is_local() {
2396 span_bug!(tcx.def_span(expr_did),
2397 "variant discriminant evaluation succeeded \
2398 in its crate but failed locally");
2402 Err(ErrorHandled::TooGeneric) => span_bug!(
2403 tcx.def_span(expr_did),
2404 "enum discriminant depends on generic arguments",
2410 pub fn discriminants(
2413 ) -> impl Iterator<Item = (VariantIdx, Discr<'tcx>)> + Captures<'tcx> {
2414 let repr_type = self.repr.discr_type();
2415 let initial = repr_type.initial_discriminant(tcx);
2416 let mut prev_discr = None::<Discr<'tcx>>;
2417 self.variants.iter_enumerated().map(move |(i, v)| {
2418 let mut discr = prev_discr.map_or(initial, |d| d.wrap_incr(tcx));
2419 if let VariantDiscr::Explicit(expr_did) = v.discr {
2420 if let Some(new_discr) = self.eval_explicit_discr(tcx, expr_did) {
2424 prev_discr = Some(discr);
2431 pub fn variant_range(&self) -> Range<VariantIdx> {
2432 (VariantIdx::new(0)..VariantIdx::new(self.variants.len()))
2435 /// Computes the discriminant value used by a specific variant.
2436 /// Unlike `discriminants`, this is (amortized) constant-time,
2437 /// only doing at most one query for evaluating an explicit
2438 /// discriminant (the last one before the requested variant),
2439 /// assuming there are no constant-evaluation errors there.
2441 pub fn discriminant_for_variant(
2444 variant_index: VariantIdx,
2446 let (val, offset) = self.discriminant_def_for_variant(variant_index);
2447 let explicit_value = val
2448 .and_then(|expr_did| self.eval_explicit_discr(tcx, expr_did))
2449 .unwrap_or_else(|| self.repr.discr_type().initial_discriminant(tcx));
2450 explicit_value.checked_add(tcx, offset as u128).0
2453 /// Yields a `DefId` for the discriminant and an offset to add to it
2454 /// Alternatively, if there is no explicit discriminant, returns the
2455 /// inferred discriminant directly.
2456 pub fn discriminant_def_for_variant(
2458 variant_index: VariantIdx,
2459 ) -> (Option<DefId>, u32) {
2460 let mut explicit_index = variant_index.as_u32();
2463 match self.variants[VariantIdx::from_u32(explicit_index)].discr {
2464 ty::VariantDiscr::Relative(0) => {
2468 ty::VariantDiscr::Relative(distance) => {
2469 explicit_index -= distance;
2471 ty::VariantDiscr::Explicit(did) => {
2472 expr_did = Some(did);
2477 (expr_did, variant_index.as_u32() - explicit_index)
2480 pub fn destructor(&self, tcx: TyCtxt<'tcx>) -> Option<Destructor> {
2481 tcx.adt_destructor(self.did)
2484 /// Returns a list of types such that `Self: Sized` if and only
2485 /// if that type is `Sized`, or `TyErr` if this type is recursive.
2487 /// Oddly enough, checking that the sized-constraint is `Sized` is
2488 /// actually more expressive than checking all members:
2489 /// the `Sized` trait is inductive, so an associated type that references
2490 /// `Self` would prevent its containing ADT from being `Sized`.
2492 /// Due to normalization being eager, this applies even if
2493 /// the associated type is behind a pointer (e.g., issue #31299).
2494 pub fn sized_constraint(&self, tcx: TyCtxt<'tcx>) -> &'tcx [Ty<'tcx>] {
2495 tcx.adt_sized_constraint(self.did).0
2498 fn sized_constraint_for_ty(&self, tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Vec<Ty<'tcx>> {
2499 let result = match ty.kind {
2500 Bool | Char | Int(..) | Uint(..) | Float(..) |
2501 RawPtr(..) | Ref(..) | FnDef(..) | FnPtr(_) |
2502 Array(..) | Closure(..) | Generator(..) | Never => {
2511 GeneratorWitness(..) => {
2512 // these are never sized - return the target type
2519 Some(ty) => self.sized_constraint_for_ty(tcx, ty.expect_ty()),
2523 Adt(adt, substs) => {
2525 let adt_tys = adt.sized_constraint(tcx);
2526 debug!("sized_constraint_for_ty({:?}) intermediate = {:?}",
2529 .map(|ty| ty.subst(tcx, substs))
2530 .flat_map(|ty| self.sized_constraint_for_ty(tcx, ty))
2534 Projection(..) | Opaque(..) => {
2535 // must calculate explicitly.
2536 // FIXME: consider special-casing always-Sized projections
2540 UnnormalizedProjection(..) => bug!("only used with chalk-engine"),
2543 // perf hack: if there is a `T: Sized` bound, then
2544 // we know that `T` is Sized and do not need to check
2547 let sized_trait = match tcx.lang_items().sized_trait() {
2549 _ => return vec![ty]
2551 let sized_predicate = Binder::dummy(TraitRef {
2552 def_id: sized_trait,
2553 substs: tcx.mk_substs_trait(ty, &[])
2555 let predicates = &tcx.predicates_of(self.did).predicates;
2556 if predicates.iter().any(|(p, _)| *p == sized_predicate) {
2566 bug!("unexpected type `{:?}` in sized_constraint_for_ty",
2570 debug!("sized_constraint_for_ty({:?}) = {:?}", ty, result);
2575 impl<'tcx> FieldDef {
2576 /// Returns the type of this field. The `subst` is typically obtained
2577 /// via the second field of `TyKind::AdtDef`.
2578 pub fn ty(&self, tcx: TyCtxt<'tcx>, subst: SubstsRef<'tcx>) -> Ty<'tcx> {
2579 tcx.type_of(self.did).subst(tcx, subst)
2583 /// Represents the various closure traits in the language. This
2584 /// will determine the type of the environment (`self`, in the
2585 /// desugaring) argument that the closure expects.
2587 /// You can get the environment type of a closure using
2588 /// `tcx.closure_env_ty()`.
2589 #[derive(Clone, Copy, PartialOrd, Ord, PartialEq, Eq, Hash, Debug,
2590 RustcEncodable, RustcDecodable, HashStable)]
2591 pub enum ClosureKind {
2592 // Warning: Ordering is significant here! The ordering is chosen
2593 // because the trait Fn is a subtrait of FnMut and so in turn, and
2594 // hence we order it so that Fn < FnMut < FnOnce.
2600 impl<'tcx> ClosureKind {
2601 // This is the initial value used when doing upvar inference.
2602 pub const LATTICE_BOTTOM: ClosureKind = ClosureKind::Fn;
2604 pub fn trait_did(&self, tcx: TyCtxt<'tcx>) -> DefId {
2606 ClosureKind::Fn => tcx.require_lang_item(FnTraitLangItem, None),
2607 ClosureKind::FnMut => {
2608 tcx.require_lang_item(FnMutTraitLangItem, None)
2610 ClosureKind::FnOnce => {
2611 tcx.require_lang_item(FnOnceTraitLangItem, None)
2616 /// Returns `true` if this a type that impls this closure kind
2617 /// must also implement `other`.
2618 pub fn extends(self, other: ty::ClosureKind) -> bool {
2619 match (self, other) {
2620 (ClosureKind::Fn, ClosureKind::Fn) => true,
2621 (ClosureKind::Fn, ClosureKind::FnMut) => true,
2622 (ClosureKind::Fn, ClosureKind::FnOnce) => true,
2623 (ClosureKind::FnMut, ClosureKind::FnMut) => true,
2624 (ClosureKind::FnMut, ClosureKind::FnOnce) => true,
2625 (ClosureKind::FnOnce, ClosureKind::FnOnce) => true,
2630 /// Returns the representative scalar type for this closure kind.
2631 /// See `TyS::to_opt_closure_kind` for more details.
2632 pub fn to_ty(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
2634 ty::ClosureKind::Fn => tcx.types.i8,
2635 ty::ClosureKind::FnMut => tcx.types.i16,
2636 ty::ClosureKind::FnOnce => tcx.types.i32,
2641 impl<'tcx> TyS<'tcx> {
2642 /// Iterator that walks `self` and any types reachable from
2643 /// `self`, in depth-first order. Note that just walks the types
2644 /// that appear in `self`, it does not descend into the fields of
2645 /// structs or variants. For example:
2648 /// isize => { isize }
2649 /// Foo<Bar<isize>> => { Foo<Bar<isize>>, Bar<isize>, isize }
2650 /// [isize] => { [isize], isize }
2652 pub fn walk(&'tcx self) -> TypeWalker<'tcx> {
2653 TypeWalker::new(self)
2656 /// Iterator that walks the immediate children of `self`. Hence
2657 /// `Foo<Bar<i32>, u32>` yields the sequence `[Bar<i32>, u32]`
2658 /// (but not `i32`, like `walk`).
2659 pub fn walk_shallow(&'tcx self) -> smallvec::IntoIter<walk::TypeWalkerArray<'tcx>> {
2660 walk::walk_shallow(self)
2663 /// Walks `ty` and any types appearing within `ty`, invoking the
2664 /// callback `f` on each type. If the callback returns `false`, then the
2665 /// children of the current type are ignored.
2667 /// Note: prefer `ty.walk()` where possible.
2668 pub fn maybe_walk<F>(&'tcx self, mut f: F)
2669 where F: FnMut(Ty<'tcx>) -> bool
2671 let mut walker = self.walk();
2672 while let Some(ty) = walker.next() {
2674 walker.skip_current_subtree();
2681 pub fn from_mutbl(m: hir::Mutability) -> BorrowKind {
2683 hir::MutMutable => MutBorrow,
2684 hir::MutImmutable => ImmBorrow,
2688 /// Returns a mutability `m` such that an `&m T` pointer could be used to obtain this borrow
2689 /// kind. Because borrow kinds are richer than mutabilities, we sometimes have to pick a
2690 /// mutability that is stronger than necessary so that it at least *would permit* the borrow in
2692 pub fn to_mutbl_lossy(self) -> hir::Mutability {
2694 MutBorrow => hir::MutMutable,
2695 ImmBorrow => hir::MutImmutable,
2697 // We have no type corresponding to a unique imm borrow, so
2698 // use `&mut`. It gives all the capabilities of an `&uniq`
2699 // and hence is a safe "over approximation".
2700 UniqueImmBorrow => hir::MutMutable,
2704 pub fn to_user_str(&self) -> &'static str {
2706 MutBorrow => "mutable",
2707 ImmBorrow => "immutable",
2708 UniqueImmBorrow => "uniquely immutable",
2713 #[derive(Debug, Clone)]
2714 pub enum Attributes<'tcx> {
2715 Owned(Lrc<[ast::Attribute]>),
2716 Borrowed(&'tcx [ast::Attribute]),
2719 impl<'tcx> ::std::ops::Deref for Attributes<'tcx> {
2720 type Target = [ast::Attribute];
2722 fn deref(&self) -> &[ast::Attribute] {
2724 &Attributes::Owned(ref data) => &data,
2725 &Attributes::Borrowed(data) => data
2730 #[derive(Debug, PartialEq, Eq)]
2731 pub enum ImplOverlapKind {
2732 /// These impls are always allowed to overlap.
2734 /// These impls are allowed to overlap, but that raises
2735 /// an issue #33140 future-compatibility warning.
2737 /// Some background: in Rust 1.0, the trait-object types `Send + Sync` (today's
2738 /// `dyn Send + Sync`) and `Sync + Send` (now `dyn Sync + Send`) were different.
2740 /// The widely-used version 0.1.0 of the crate `traitobject` had accidentally relied
2741 /// that difference, making what reduces to the following set of impls:
2745 /// impl Trait for dyn Send + Sync {}
2746 /// impl Trait for dyn Sync + Send {}
2749 /// Obviously, once we made these types be identical, that code causes a coherence
2750 /// error and a fairly big headache for us. However, luckily for us, the trait
2751 /// `Trait` used in this case is basically a marker trait, and therefore having
2752 /// overlapping impls for it is sound.
2754 /// To handle this, we basically regard the trait as a marker trait, with an additional
2755 /// future-compatibility warning. To avoid accidentally "stabilizing" this feature,
2756 /// it has the following restrictions:
2758 /// 1. The trait must indeed be a marker-like trait (i.e., no items), and must be
2760 /// 2. The trait-ref of both impls must be equal.
2761 /// 3. The trait-ref of both impls must be a trait object type consisting only of
2763 /// 4. Neither of the impls can have any where-clauses.
2765 /// Once `traitobject` 0.1.0 is no longer an active concern, this hack can be removed.
2769 impl<'tcx> TyCtxt<'tcx> {
2770 pub fn body_tables(self, body: hir::BodyId) -> &'tcx TypeckTables<'tcx> {
2771 self.typeck_tables_of(self.hir().body_owner_def_id(body))
2774 /// Returns an iterator of the `DefId`s for all body-owners in this
2775 /// crate. If you would prefer to iterate over the bodies
2776 /// themselves, you can do `self.hir().krate().body_ids.iter()`.
2777 pub fn body_owners(self) -> impl Iterator<Item = DefId> + Captures<'tcx> + 'tcx {
2781 .map(move |&body_id| self.hir().body_owner_def_id(body_id))
2784 pub fn par_body_owners<F: Fn(DefId) + sync::Sync + sync::Send>(self, f: F) {
2785 par_iter(&self.hir().krate().body_ids).for_each(|&body_id| {
2786 f(self.hir().body_owner_def_id(body_id))
2790 pub fn provided_trait_methods(self, id: DefId) -> Vec<AssocItem> {
2791 self.associated_items(id)
2792 .filter(|item| item.kind == AssocKind::Method && item.defaultness.has_value())
2796 pub fn trait_relevant_for_never(self, did: DefId) -> bool {
2797 self.associated_items(did).any(|item| {
2798 item.relevant_for_never()
2802 pub fn opt_item_name(self, def_id: DefId) -> Option<Ident> {
2803 self.hir().as_local_hir_id(def_id).and_then(|hir_id| self.hir().get(hir_id).ident())
2806 pub fn opt_associated_item(self, def_id: DefId) -> Option<AssocItem> {
2807 let is_associated_item = if let Some(hir_id) = self.hir().as_local_hir_id(def_id) {
2808 match self.hir().get(hir_id) {
2809 Node::TraitItem(_) | Node::ImplItem(_) => true,
2813 match self.def_kind(def_id).expect("no def for `DefId`") {
2816 | DefKind::AssocTy => true,
2821 if is_associated_item {
2822 Some(self.associated_item(def_id))
2828 fn associated_item_from_trait_item_ref(self,
2829 parent_def_id: DefId,
2830 parent_vis: &hir::Visibility,
2831 trait_item_ref: &hir::TraitItemRef)
2833 let def_id = self.hir().local_def_id(trait_item_ref.id.hir_id);
2834 let (kind, has_self) = match trait_item_ref.kind {
2835 hir::AssocItemKind::Const => (ty::AssocKind::Const, false),
2836 hir::AssocItemKind::Method { has_self } => {
2837 (ty::AssocKind::Method, has_self)
2839 hir::AssocItemKind::Type => (ty::AssocKind::Type, false),
2840 hir::AssocItemKind::OpaqueTy => bug!("only impls can have opaque types"),
2844 ident: trait_item_ref.ident,
2846 // Visibility of trait items is inherited from their traits.
2847 vis: Visibility::from_hir(parent_vis, trait_item_ref.id.hir_id, self),
2848 defaultness: trait_item_ref.defaultness,
2850 container: TraitContainer(parent_def_id),
2851 method_has_self_argument: has_self
2855 fn associated_item_from_impl_item_ref(self,
2856 parent_def_id: DefId,
2857 impl_item_ref: &hir::ImplItemRef)
2859 let def_id = self.hir().local_def_id(impl_item_ref.id.hir_id);
2860 let (kind, has_self) = match impl_item_ref.kind {
2861 hir::AssocItemKind::Const => (ty::AssocKind::Const, false),
2862 hir::AssocItemKind::Method { has_self } => {
2863 (ty::AssocKind::Method, has_self)
2865 hir::AssocItemKind::Type => (ty::AssocKind::Type, false),
2866 hir::AssocItemKind::OpaqueTy => (ty::AssocKind::OpaqueTy, false),
2870 ident: impl_item_ref.ident,
2872 // Visibility of trait impl items doesn't matter.
2873 vis: ty::Visibility::from_hir(&impl_item_ref.vis, impl_item_ref.id.hir_id, self),
2874 defaultness: impl_item_ref.defaultness,
2876 container: ImplContainer(parent_def_id),
2877 method_has_self_argument: has_self
2881 pub fn field_index(self, hir_id: hir::HirId, tables: &TypeckTables<'_>) -> usize {
2882 tables.field_indices().get(hir_id).cloned().expect("no index for a field")
2885 pub fn find_field_index(self, ident: Ident, variant: &VariantDef) -> Option<usize> {
2886 variant.fields.iter().position(|field| {
2887 self.hygienic_eq(ident, field.ident, variant.def_id)
2891 pub fn associated_items(self, def_id: DefId) -> AssocItemsIterator<'tcx> {
2892 // Ideally, we would use `-> impl Iterator` here, but it falls
2893 // afoul of the conservative "capture [restrictions]" we put
2894 // in place, so we use a hand-written iterator.
2896 // [restrictions]: https://github.com/rust-lang/rust/issues/34511#issuecomment-373423999
2897 AssocItemsIterator {
2899 def_ids: self.associated_item_def_ids(def_id),
2904 /// Returns `true` if the impls are the same polarity and the trait either
2905 /// has no items or is annotated #[marker] and prevents item overrides.
2906 pub fn impls_are_allowed_to_overlap(self, def_id1: DefId, def_id2: DefId)
2907 -> Option<ImplOverlapKind>
2909 // If either trait impl references an error, they're allowed to overlap,
2910 // as one of them essentially doesn't exist.
2911 if self.impl_trait_ref(def_id1).map_or(false, |tr| tr.references_error()) ||
2912 self.impl_trait_ref(def_id2).map_or(false, |tr| tr.references_error()) {
2913 return Some(ImplOverlapKind::Permitted);
2916 match (self.impl_polarity(def_id1), self.impl_polarity(def_id2)) {
2917 (ImplPolarity::Reservation, _) |
2918 (_, ImplPolarity::Reservation) => {
2919 // `#[rustc_reservation_impl]` impls don't overlap with anything
2920 debug!("impls_are_allowed_to_overlap({:?}, {:?}) = Some(Permitted) (reservations)",
2922 return Some(ImplOverlapKind::Permitted);
2924 (ImplPolarity::Positive, ImplPolarity::Negative) |
2925 (ImplPolarity::Negative, ImplPolarity::Positive) => {
2926 // `impl AutoTrait for Type` + `impl !AutoTrait for Type`
2927 debug!("impls_are_allowed_to_overlap({:?}, {:?}) - None (differing polarities)",
2931 (ImplPolarity::Positive, ImplPolarity::Positive) |
2932 (ImplPolarity::Negative, ImplPolarity::Negative) => {}
2935 let is_marker_overlap = if self.features().overlapping_marker_traits {
2936 let trait1_is_empty = self.impl_trait_ref(def_id1)
2937 .map_or(false, |trait_ref| {
2938 self.associated_item_def_ids(trait_ref.def_id).is_empty()
2940 let trait2_is_empty = self.impl_trait_ref(def_id2)
2941 .map_or(false, |trait_ref| {
2942 self.associated_item_def_ids(trait_ref.def_id).is_empty()
2944 trait1_is_empty && trait2_is_empty
2946 let is_marker_impl = |def_id: DefId| -> bool {
2947 let trait_ref = self.impl_trait_ref(def_id);
2948 trait_ref.map_or(false, |tr| self.trait_def(tr.def_id).is_marker)
2950 is_marker_impl(def_id1) && is_marker_impl(def_id2)
2954 if is_marker_overlap {
2955 debug!("impls_are_allowed_to_overlap({:?}, {:?}) = Some(Permitted) (marker overlap)",
2957 Some(ImplOverlapKind::Permitted)
2959 if let Some(self_ty1) = self.issue33140_self_ty(def_id1) {
2960 if let Some(self_ty2) = self.issue33140_self_ty(def_id2) {
2961 if self_ty1 == self_ty2 {
2962 debug!("impls_are_allowed_to_overlap({:?}, {:?}) - issue #33140 HACK",
2964 return Some(ImplOverlapKind::Issue33140);
2966 debug!("impls_are_allowed_to_overlap({:?}, {:?}) - found {:?} != {:?}",
2967 def_id1, def_id2, self_ty1, self_ty2);
2972 debug!("impls_are_allowed_to_overlap({:?}, {:?}) = None",
2978 /// Returns `ty::VariantDef` if `res` refers to a struct,
2979 /// or variant or their constructors, panics otherwise.
2980 pub fn expect_variant_res(self, res: Res) -> &'tcx VariantDef {
2982 Res::Def(DefKind::Variant, did) => {
2983 let enum_did = self.parent(did).unwrap();
2984 self.adt_def(enum_did).variant_with_id(did)
2986 Res::Def(DefKind::Struct, did) | Res::Def(DefKind::Union, did) => {
2987 self.adt_def(did).non_enum_variant()
2989 Res::Def(DefKind::Ctor(CtorOf::Variant, ..), variant_ctor_did) => {
2990 let variant_did = self.parent(variant_ctor_did).unwrap();
2991 let enum_did = self.parent(variant_did).unwrap();
2992 self.adt_def(enum_did).variant_with_ctor_id(variant_ctor_did)
2994 Res::Def(DefKind::Ctor(CtorOf::Struct, ..), ctor_did) => {
2995 let struct_did = self.parent(ctor_did).expect("struct ctor has no parent");
2996 self.adt_def(struct_did).non_enum_variant()
2998 _ => bug!("expect_variant_res used with unexpected res {:?}", res)
3002 pub fn item_name(self, id: DefId) -> Symbol {
3003 if id.index == CRATE_DEF_INDEX {
3004 self.original_crate_name(id.krate)
3006 let def_key = self.def_key(id);
3007 match def_key.disambiguated_data.data {
3008 // The name of a constructor is that of its parent.
3009 hir_map::DefPathData::Ctor =>
3010 self.item_name(DefId {
3012 index: def_key.parent.unwrap()
3014 _ => def_key.disambiguated_data.data.get_opt_name().unwrap_or_else(|| {
3015 bug!("item_name: no name for {:?}", self.def_path(id));
3021 /// Returns the possibly-auto-generated MIR of a `(DefId, Subst)` pair.
3022 pub fn instance_mir(self, instance: ty::InstanceDef<'tcx>) -> &'tcx Body<'tcx> {
3024 ty::InstanceDef::Item(did) => {
3025 self.optimized_mir(did)
3027 ty::InstanceDef::VtableShim(..) |
3028 ty::InstanceDef::Intrinsic(..) |
3029 ty::InstanceDef::FnPtrShim(..) |
3030 ty::InstanceDef::Virtual(..) |
3031 ty::InstanceDef::ClosureOnceShim { .. } |
3032 ty::InstanceDef::DropGlue(..) |
3033 ty::InstanceDef::CloneShim(..) => {
3034 self.mir_shims(instance)
3039 /// Gets the attributes of a definition.
3040 pub fn get_attrs(self, did: DefId) -> Attributes<'tcx> {
3041 if let Some(id) = self.hir().as_local_hir_id(did) {
3042 Attributes::Borrowed(self.hir().attrs(id))
3044 Attributes::Owned(self.item_attrs(did))
3048 /// Determines whether an item is annotated with an attribute.
3049 pub fn has_attr(self, did: DefId, attr: Symbol) -> bool {
3050 attr::contains_name(&self.get_attrs(did), attr)
3053 /// Returns `true` if this is an `auto trait`.
3054 pub fn trait_is_auto(self, trait_def_id: DefId) -> bool {
3055 self.trait_def(trait_def_id).has_auto_impl
3058 pub fn generator_layout(self, def_id: DefId) -> &'tcx GeneratorLayout<'tcx> {
3059 self.optimized_mir(def_id).generator_layout.as_ref().unwrap()
3062 /// Given the `DefId` of an impl, returns the `DefId` of the trait it implements.
3063 /// If it implements no trait, returns `None`.
3064 pub fn trait_id_of_impl(self, def_id: DefId) -> Option<DefId> {
3065 self.impl_trait_ref(def_id).map(|tr| tr.def_id)
3068 /// If the given defid describes a method belonging to an impl, returns the
3069 /// `DefId` of the impl that the method belongs to; otherwise, returns `None`.
3070 pub fn impl_of_method(self, def_id: DefId) -> Option<DefId> {
3071 let item = if def_id.krate != LOCAL_CRATE {
3072 if let Some(DefKind::Method) = self.def_kind(def_id) {
3073 Some(self.associated_item(def_id))
3078 self.opt_associated_item(def_id)
3081 item.and_then(|trait_item|
3082 match trait_item.container {
3083 TraitContainer(_) => None,
3084 ImplContainer(def_id) => Some(def_id),
3089 /// Looks up the span of `impl_did` if the impl is local; otherwise returns `Err`
3090 /// with the name of the crate containing the impl.
3091 pub fn span_of_impl(self, impl_did: DefId) -> Result<Span, Symbol> {
3092 if impl_did.is_local() {
3093 let hir_id = self.hir().as_local_hir_id(impl_did).unwrap();
3094 Ok(self.hir().span(hir_id))
3096 Err(self.crate_name(impl_did.krate))
3100 /// Hygienically compares a use-site name (`use_name`) for a field or an associated item with
3101 /// its supposed definition name (`def_name`). The method also needs `DefId` of the supposed
3102 /// definition's parent/scope to perform comparison.
3103 pub fn hygienic_eq(self, use_name: Ident, def_name: Ident, def_parent_def_id: DefId) -> bool {
3104 // We could use `Ident::eq` here, but we deliberately don't. The name
3105 // comparison fails frequently, and we want to avoid the expensive
3106 // `modern()` calls required for the span comparison whenever possible.
3107 use_name.name == def_name.name &&
3108 use_name.span.ctxt().hygienic_eq(def_name.span.ctxt(),
3109 self.expansion_that_defined(def_parent_def_id))
3112 fn expansion_that_defined(self, scope: DefId) -> ExpnId {
3114 LOCAL_CRATE => self.hir().definitions().expansion_that_defined(scope.index),
3115 _ => ExpnId::root(),
3119 pub fn adjust_ident(self, mut ident: Ident, scope: DefId) -> Ident {
3120 ident.span.modernize_and_adjust(self.expansion_that_defined(scope));
3124 pub fn adjust_ident_and_get_scope(self, mut ident: Ident, scope: DefId, block: hir::HirId)
3126 let scope = match ident.span.modernize_and_adjust(self.expansion_that_defined(scope)) {
3127 Some(actual_expansion) =>
3128 self.hir().definitions().parent_module_of_macro_def(actual_expansion),
3129 None => self.hir().get_module_parent(block),
3135 pub struct AssocItemsIterator<'tcx> {
3137 def_ids: &'tcx [DefId],
3141 impl Iterator for AssocItemsIterator<'_> {
3142 type Item = AssocItem;
3144 fn next(&mut self) -> Option<AssocItem> {
3145 let def_id = self.def_ids.get(self.next_index)?;
3146 self.next_index += 1;
3147 Some(self.tcx.associated_item(*def_id))
3151 fn associated_item(tcx: TyCtxt<'_>, def_id: DefId) -> AssocItem {
3152 let id = tcx.hir().as_local_hir_id(def_id).unwrap();
3153 let parent_id = tcx.hir().get_parent_item(id);
3154 let parent_def_id = tcx.hir().local_def_id(parent_id);
3155 let parent_item = tcx.hir().expect_item(parent_id);
3156 match parent_item.kind {
3157 hir::ItemKind::Impl(.., ref impl_item_refs) => {
3158 if let Some(impl_item_ref) = impl_item_refs.iter().find(|i| i.id.hir_id == id) {
3159 let assoc_item = tcx.associated_item_from_impl_item_ref(parent_def_id,
3161 debug_assert_eq!(assoc_item.def_id, def_id);
3166 hir::ItemKind::Trait(.., ref trait_item_refs) => {
3167 if let Some(trait_item_ref) = trait_item_refs.iter().find(|i| i.id.hir_id == id) {
3168 let assoc_item = tcx.associated_item_from_trait_item_ref(parent_def_id,
3171 debug_assert_eq!(assoc_item.def_id, def_id);
3179 span_bug!(parent_item.span,
3180 "unexpected parent of trait or impl item or item not found: {:?}",
3184 #[derive(Clone, HashStable)]
3185 pub struct AdtSizedConstraint<'tcx>(pub &'tcx [Ty<'tcx>]);
3187 /// Calculates the `Sized` constraint.
3189 /// In fact, there are only a few options for the types in the constraint:
3190 /// - an obviously-unsized type
3191 /// - a type parameter or projection whose Sizedness can't be known
3192 /// - a tuple of type parameters or projections, if there are multiple
3194 /// - a Error, if a type contained itself. The representability
3195 /// check should catch this case.
3196 fn adt_sized_constraint(tcx: TyCtxt<'_>, def_id: DefId) -> AdtSizedConstraint<'_> {
3197 let def = tcx.adt_def(def_id);
3199 let result = tcx.mk_type_list(def.variants.iter().flat_map(|v| {
3202 def.sized_constraint_for_ty(tcx, tcx.type_of(f.did))
3205 debug!("adt_sized_constraint: {:?} => {:?}", def, result);
3207 AdtSizedConstraint(result)
3210 fn associated_item_def_ids(tcx: TyCtxt<'_>, def_id: DefId) -> &[DefId] {
3211 let id = tcx.hir().as_local_hir_id(def_id).unwrap();
3212 let item = tcx.hir().expect_item(id);
3214 hir::ItemKind::Trait(.., ref trait_item_refs) => {
3215 tcx.arena.alloc_from_iter(
3216 trait_item_refs.iter()
3217 .map(|trait_item_ref| trait_item_ref.id)
3218 .map(|id| tcx.hir().local_def_id(id.hir_id))
3221 hir::ItemKind::Impl(.., ref impl_item_refs) => {
3222 tcx.arena.alloc_from_iter(
3223 impl_item_refs.iter()
3224 .map(|impl_item_ref| impl_item_ref.id)
3225 .map(|id| tcx.hir().local_def_id(id.hir_id))
3228 hir::ItemKind::TraitAlias(..) => &[],
3229 _ => span_bug!(item.span, "associated_item_def_ids: not impl or trait")
3233 fn def_span(tcx: TyCtxt<'_>, def_id: DefId) -> Span {
3234 tcx.hir().span_if_local(def_id).unwrap()
3237 /// If the given `DefId` describes an item belonging to a trait,
3238 /// returns the `DefId` of the trait that the trait item belongs to;
3239 /// otherwise, returns `None`.
3240 fn trait_of_item(tcx: TyCtxt<'_>, def_id: DefId) -> Option<DefId> {
3241 tcx.opt_associated_item(def_id)
3242 .and_then(|associated_item| {
3243 match associated_item.container {
3244 TraitContainer(def_id) => Some(def_id),
3245 ImplContainer(_) => None
3250 /// Yields the parent function's `DefId` if `def_id` is an `impl Trait` definition.
3251 pub fn is_impl_trait_defn(tcx: TyCtxt<'_>, def_id: DefId) -> Option<DefId> {
3252 if let Some(hir_id) = tcx.hir().as_local_hir_id(def_id) {
3253 if let Node::Item(item) = tcx.hir().get(hir_id) {
3254 if let hir::ItemKind::OpaqueTy(ref opaque_ty) = item.kind {
3255 return opaque_ty.impl_trait_fn;
3262 /// See `ParamEnv` struct definition for details.
3263 fn param_env(tcx: TyCtxt<'_>, def_id: DefId) -> ParamEnv<'_> {
3264 // The param_env of an impl Trait type is its defining function's param_env
3265 if let Some(parent) = is_impl_trait_defn(tcx, def_id) {
3266 return param_env(tcx, parent);
3268 // Compute the bounds on Self and the type parameters.
3270 let InstantiatedPredicates { predicates } =
3271 tcx.predicates_of(def_id).instantiate_identity(tcx);
3273 // Finally, we have to normalize the bounds in the environment, in
3274 // case they contain any associated type projections. This process
3275 // can yield errors if the put in illegal associated types, like
3276 // `<i32 as Foo>::Bar` where `i32` does not implement `Foo`. We
3277 // report these errors right here; this doesn't actually feel
3278 // right to me, because constructing the environment feels like a
3279 // kind of a "idempotent" action, but I'm not sure where would be
3280 // a better place. In practice, we construct environments for
3281 // every fn once during type checking, and we'll abort if there
3282 // are any errors at that point, so after type checking you can be
3283 // sure that this will succeed without errors anyway.
3285 let unnormalized_env = ty::ParamEnv::new(
3286 tcx.intern_predicates(&predicates),
3287 traits::Reveal::UserFacing,
3288 if tcx.sess.opts.debugging_opts.chalk { Some(def_id) } else { None }
3291 let body_id = tcx.hir().as_local_hir_id(def_id).map_or(hir::DUMMY_HIR_ID, |id| {
3292 tcx.hir().maybe_body_owned_by(id).map_or(id, |body| body.hir_id)
3294 let cause = traits::ObligationCause::misc(tcx.def_span(def_id), body_id);
3295 traits::normalize_param_env_or_error(tcx, def_id, unnormalized_env, cause)
3298 fn crate_disambiguator(tcx: TyCtxt<'_>, crate_num: CrateNum) -> CrateDisambiguator {
3299 assert_eq!(crate_num, LOCAL_CRATE);
3300 tcx.sess.local_crate_disambiguator()
3303 fn original_crate_name(tcx: TyCtxt<'_>, crate_num: CrateNum) -> Symbol {
3304 assert_eq!(crate_num, LOCAL_CRATE);
3305 tcx.crate_name.clone()
3308 fn crate_hash(tcx: TyCtxt<'_>, crate_num: CrateNum) -> Svh {
3309 assert_eq!(crate_num, LOCAL_CRATE);
3310 tcx.hir().crate_hash
3313 fn instance_def_size_estimate<'tcx>(tcx: TyCtxt<'tcx>, instance_def: InstanceDef<'tcx>) -> usize {
3314 match instance_def {
3315 InstanceDef::Item(..) |
3316 InstanceDef::DropGlue(..) => {
3317 let mir = tcx.instance_mir(instance_def);
3318 mir.basic_blocks().iter().map(|bb| bb.statements.len()).sum()
3320 // Estimate the size of other compiler-generated shims to be 1.
3325 /// If `def_id` is an issue 33140 hack impl, returns its self type; otherwise, returns `None`.
3327 /// See [`ImplOverlapKind::Issue33140`] for more details.
3328 fn issue33140_self_ty(tcx: TyCtxt<'_>, def_id: DefId) -> Option<Ty<'_>> {
3329 debug!("issue33140_self_ty({:?})", def_id);
3331 let trait_ref = tcx.impl_trait_ref(def_id).unwrap_or_else(|| {
3332 bug!("issue33140_self_ty called on inherent impl {:?}", def_id)
3335 debug!("issue33140_self_ty({:?}), trait-ref={:?}", def_id, trait_ref);
3337 let is_marker_like =
3338 tcx.impl_polarity(def_id) == ty::ImplPolarity::Positive &&
3339 tcx.associated_item_def_ids(trait_ref.def_id).is_empty();
3341 // Check whether these impls would be ok for a marker trait.
3342 if !is_marker_like {
3343 debug!("issue33140_self_ty - not marker-like!");
3347 // impl must be `impl Trait for dyn Marker1 + Marker2 + ...`
3348 if trait_ref.substs.len() != 1 {
3349 debug!("issue33140_self_ty - impl has substs!");
3353 let predicates = tcx.predicates_of(def_id);
3354 if predicates.parent.is_some() || !predicates.predicates.is_empty() {
3355 debug!("issue33140_self_ty - impl has predicates {:?}!", predicates);
3359 let self_ty = trait_ref.self_ty();
3360 let self_ty_matches = match self_ty.kind {
3361 ty::Dynamic(ref data, ty::ReStatic) => data.principal().is_none(),
3365 if self_ty_matches {
3366 debug!("issue33140_self_ty - MATCHES!");
3369 debug!("issue33140_self_ty - non-matching self type");
3374 /// Check if a function is async.
3375 fn asyncness(tcx: TyCtxt<'_>, def_id: DefId) -> hir::IsAsync {
3376 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap_or_else(|| {
3377 bug!("asyncness: expected local `DefId`, got `{:?}`", def_id)
3380 let node = tcx.hir().get(hir_id);
3382 let fn_like = hir::map::blocks::FnLikeNode::from_node(node).unwrap_or_else(|| {
3383 bug!("asyncness: expected fn-like node but got `{:?}`", def_id);
3390 pub fn provide(providers: &mut ty::query::Providers<'_>) {
3391 context::provide(providers);
3392 erase_regions::provide(providers);
3393 layout::provide(providers);
3394 util::provide(providers);
3395 constness::provide(providers);
3396 *providers = ty::query::Providers {
3399 associated_item_def_ids,
3400 adt_sized_constraint,
3404 crate_disambiguator,
3405 original_crate_name,
3407 trait_impls_of: trait_def::trait_impls_of_provider,
3408 instance_def_size_estimate,
3414 /// A map for the local crate mapping each type to a vector of its
3415 /// inherent impls. This is not meant to be used outside of coherence;
3416 /// rather, you should request the vector for a specific type via
3417 /// `tcx.inherent_impls(def_id)` so as to minimize your dependencies
3418 /// (constructing this map requires touching the entire crate).
3419 #[derive(Clone, Debug, Default, HashStable)]
3420 pub struct CrateInherentImpls {
3421 pub inherent_impls: DefIdMap<Vec<DefId>>,
3424 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable)]
3425 pub struct SymbolName {
3426 // FIXME: we don't rely on interning or equality here - better have
3427 // this be a `&'tcx str`.
3428 pub name: InternedString
3431 impl_stable_hash_for!(struct self::SymbolName {
3436 pub fn new(name: &str) -> SymbolName {
3438 name: InternedString::intern(name)
3443 impl fmt::Display for SymbolName {
3444 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
3445 fmt::Display::fmt(&self.name, fmt)
3449 impl fmt::Debug for SymbolName {
3450 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
3451 fmt::Display::fmt(&self.name, fmt)