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 be unsized while not requiring references to it be wide
605 type OpaqueListContents;
608 /// A wrapper for slices with the additional invariant
609 /// that the slice is interned and no other slice with
610 /// the same contents can exist in the same context.
611 /// This means we can use pointer for both
612 /// equality comparisons and hashing.
613 /// Note: `Slice` was already taken by the `Ty`.
618 opaque: OpaqueListContents,
621 unsafe impl<T: Sync> Sync for List<T> {}
623 impl<T: Copy> List<T> {
625 fn from_arena<'tcx>(arena: &'tcx SyncDroplessArena, slice: &[T]) -> &'tcx List<T> {
626 assert!(!mem::needs_drop::<T>());
627 assert!(mem::size_of::<T>() != 0);
628 assert!(slice.len() != 0);
630 // Align up the size of the len (usize) field
631 let align = mem::align_of::<T>();
632 let align_mask = align - 1;
633 let offset = mem::size_of::<usize>();
634 let offset = (offset + align_mask) & !align_mask;
636 let size = offset + slice.len() * mem::size_of::<T>();
638 let mem = arena.alloc_raw(
640 cmp::max(mem::align_of::<T>(), mem::align_of::<usize>()));
642 let result = &mut *(mem.as_mut_ptr() as *mut List<T>);
644 result.len = slice.len();
646 // Write the elements
647 let arena_slice = slice::from_raw_parts_mut(result.data.as_mut_ptr(), result.len);
648 arena_slice.copy_from_slice(slice);
655 impl<T: fmt::Debug> fmt::Debug for List<T> {
656 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
661 impl<T: Encodable> Encodable for List<T> {
663 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
668 impl<T> Ord for List<T> where T: Ord {
669 fn cmp(&self, other: &List<T>) -> Ordering {
670 if self == other { Ordering::Equal } else {
671 <[T] as Ord>::cmp(&**self, &**other)
676 impl<T> PartialOrd for List<T> where T: PartialOrd {
677 fn partial_cmp(&self, other: &List<T>) -> Option<Ordering> {
678 if self == other { Some(Ordering::Equal) } else {
679 <[T] as PartialOrd>::partial_cmp(&**self, &**other)
684 impl<T: PartialEq> PartialEq for List<T> {
686 fn eq(&self, other: &List<T>) -> bool {
690 impl<T: Eq> Eq for List<T> {}
692 impl<T> Hash for List<T> {
694 fn hash<H: Hasher>(&self, s: &mut H) {
695 (self as *const List<T>).hash(s)
699 impl<T> Deref for List<T> {
702 fn deref(&self) -> &[T] {
704 slice::from_raw_parts(self.data.as_ptr(), self.len)
709 impl<'a, T> IntoIterator for &'a List<T> {
711 type IntoIter = <&'a [T] as IntoIterator>::IntoIter;
713 fn into_iter(self) -> Self::IntoIter {
718 impl<'tcx> rustc_serialize::UseSpecializedDecodable for &'tcx List<Ty<'tcx>> {}
722 pub fn empty<'a>() -> &'a List<T> {
723 #[repr(align(64), C)]
724 struct EmptySlice([u8; 64]);
725 static EMPTY_SLICE: EmptySlice = EmptySlice([0; 64]);
726 assert!(mem::align_of::<T>() <= 64);
728 &*(&EMPTY_SLICE as *const _ as *const List<T>)
733 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
734 pub struct UpvarPath {
735 pub hir_id: hir::HirId,
738 /// Upvars do not get their own `NodeId`. Instead, we use the pair of
739 /// the original var ID (that is, the root variable that is referenced
740 /// by the upvar) and the ID of the closure expression.
741 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
743 pub var_path: UpvarPath,
744 pub closure_expr_id: LocalDefId,
747 #[derive(Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable, Copy, HashStable)]
748 pub enum BorrowKind {
749 /// Data must be immutable and is aliasable.
752 /// Data must be immutable but not aliasable. This kind of borrow
753 /// cannot currently be expressed by the user and is used only in
754 /// implicit closure bindings. It is needed when the closure
755 /// is borrowing or mutating a mutable referent, e.g.:
757 /// let x: &mut isize = ...;
758 /// let y = || *x += 5;
760 /// If we were to try to translate this closure into a more explicit
761 /// form, we'd encounter an error with the code as written:
763 /// struct Env { x: & &mut isize }
764 /// let x: &mut isize = ...;
765 /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
766 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
768 /// This is then illegal because you cannot mutate a `&mut` found
769 /// in an aliasable location. To solve, you'd have to translate with
770 /// an `&mut` borrow:
772 /// struct Env { x: & &mut isize }
773 /// let x: &mut isize = ...;
774 /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
775 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
777 /// Now the assignment to `**env.x` is legal, but creating a
778 /// mutable pointer to `x` is not because `x` is not mutable. We
779 /// could fix this by declaring `x` as `let mut x`. This is ok in
780 /// user code, if awkward, but extra weird for closures, since the
781 /// borrow is hidden.
783 /// So we introduce a "unique imm" borrow -- the referent is
784 /// immutable, but not aliasable. This solves the problem. For
785 /// simplicity, we don't give users the way to express this
786 /// borrow, it's just used when translating closures.
789 /// Data is mutable and not aliasable.
793 /// Information describing the capture of an upvar. This is computed
794 /// during `typeck`, specifically by `regionck`.
795 #[derive(PartialEq, Clone, Debug, Copy, RustcEncodable, RustcDecodable, HashStable)]
796 pub enum UpvarCapture<'tcx> {
797 /// Upvar is captured by value. This is always true when the
798 /// closure is labeled `move`, but can also be true in other cases
799 /// depending on inference.
802 /// Upvar is captured by reference.
803 ByRef(UpvarBorrow<'tcx>),
806 #[derive(PartialEq, Clone, Copy, RustcEncodable, RustcDecodable, HashStable)]
807 pub struct UpvarBorrow<'tcx> {
808 /// The kind of borrow: by-ref upvars have access to shared
809 /// immutable borrows, which are not part of the normal language
811 pub kind: BorrowKind,
813 /// Region of the resulting reference.
814 pub region: ty::Region<'tcx>,
817 pub type UpvarListMap = FxHashMap<DefId, FxIndexMap<hir::HirId, UpvarId>>;
818 pub type UpvarCaptureMap<'tcx> = FxHashMap<UpvarId, UpvarCapture<'tcx>>;
820 #[derive(Copy, Clone)]
821 pub struct ClosureUpvar<'tcx> {
827 #[derive(Clone, Copy, PartialEq, Eq)]
828 pub enum IntVarValue {
830 UintType(ast::UintTy),
833 #[derive(Clone, Copy, PartialEq, Eq)]
834 pub struct FloatVarValue(pub ast::FloatTy);
836 impl ty::EarlyBoundRegion {
837 pub fn to_bound_region(&self) -> ty::BoundRegion {
838 ty::BoundRegion::BrNamed(self.def_id, self.name)
841 /// Does this early bound region have a name? Early bound regions normally
842 /// always have names except when using anonymous lifetimes (`'_`).
843 pub fn has_name(&self) -> bool {
844 self.name != kw::UnderscoreLifetime.as_interned_str()
848 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
849 pub enum GenericParamDefKind {
853 object_lifetime_default: ObjectLifetimeDefault,
854 synthetic: Option<hir::SyntheticTyParamKind>,
859 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable)]
860 pub struct GenericParamDef {
861 pub name: InternedString,
865 /// `pure_wrt_drop`, set by the (unsafe) `#[may_dangle]` attribute
866 /// on generic parameter `'a`/`T`, asserts data behind the parameter
867 /// `'a`/`T` won't be accessed during the parent type's `Drop` impl.
868 pub pure_wrt_drop: bool,
870 pub kind: GenericParamDefKind,
873 impl GenericParamDef {
874 pub fn to_early_bound_region_data(&self) -> ty::EarlyBoundRegion {
875 if let GenericParamDefKind::Lifetime = self.kind {
876 ty::EarlyBoundRegion {
882 bug!("cannot convert a non-lifetime parameter def to an early bound region")
886 pub fn to_bound_region(&self) -> ty::BoundRegion {
887 if let GenericParamDefKind::Lifetime = self.kind {
888 self.to_early_bound_region_data().to_bound_region()
890 bug!("cannot convert a non-lifetime parameter def to an early bound region")
896 pub struct GenericParamCount {
897 pub lifetimes: usize,
902 /// Information about the formal type/lifetime parameters associated
903 /// with an item or method. Analogous to `hir::Generics`.
905 /// The ordering of parameters is the same as in `Subst` (excluding child generics):
906 /// `Self` (optionally), `Lifetime` params..., `Type` params...
907 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
908 pub struct Generics {
909 pub parent: Option<DefId>,
910 pub parent_count: usize,
911 pub params: Vec<GenericParamDef>,
913 /// Reverse map to the `index` field of each `GenericParamDef`.
914 #[stable_hasher(ignore)]
915 pub param_def_id_to_index: FxHashMap<DefId, u32>,
918 pub has_late_bound_regions: Option<Span>,
921 impl<'tcx> Generics {
922 pub fn count(&self) -> usize {
923 self.parent_count + self.params.len()
926 pub fn own_counts(&self) -> GenericParamCount {
927 // We could cache this as a property of `GenericParamCount`, but
928 // the aim is to refactor this away entirely eventually and the
929 // presence of this method will be a constant reminder.
930 let mut own_counts: GenericParamCount = Default::default();
932 for param in &self.params {
934 GenericParamDefKind::Lifetime => own_counts.lifetimes += 1,
935 GenericParamDefKind::Type { .. } => own_counts.types += 1,
936 GenericParamDefKind::Const => own_counts.consts += 1,
943 pub fn requires_monomorphization(&self, tcx: TyCtxt<'tcx>) -> bool {
944 if self.own_requires_monomorphization() {
948 if let Some(parent_def_id) = self.parent {
949 let parent = tcx.generics_of(parent_def_id);
950 parent.requires_monomorphization(tcx)
956 pub fn own_requires_monomorphization(&self) -> bool {
957 for param in &self.params {
959 GenericParamDefKind::Type { .. } | GenericParamDefKind::Const => return true,
960 GenericParamDefKind::Lifetime => {}
968 param: &EarlyBoundRegion,
970 ) -> &'tcx GenericParamDef {
971 if let Some(index) = param.index.checked_sub(self.parent_count as u32) {
972 let param = &self.params[index as usize];
974 GenericParamDefKind::Lifetime => param,
975 _ => bug!("expected lifetime parameter, but found another generic parameter")
978 tcx.generics_of(self.parent.expect("parent_count > 0 but no parent?"))
979 .region_param(param, tcx)
983 /// Returns the `GenericParamDef` associated with this `ParamTy`.
984 pub fn type_param(&'tcx self, param: &ParamTy, tcx: TyCtxt<'tcx>) -> &'tcx GenericParamDef {
985 if let Some(index) = param.index.checked_sub(self.parent_count as u32) {
986 let param = &self.params[index as usize];
988 GenericParamDefKind::Type { .. } => param,
989 _ => bug!("expected type parameter, but found another generic parameter")
992 tcx.generics_of(self.parent.expect("parent_count > 0 but no parent?"))
993 .type_param(param, tcx)
997 /// Returns the `ConstParameterDef` associated with this `ParamConst`.
998 pub fn const_param(&'tcx self, param: &ParamConst, tcx: TyCtxt<'tcx>) -> &GenericParamDef {
999 if let Some(index) = param.index.checked_sub(self.parent_count as u32) {
1000 let param = &self.params[index as usize];
1002 GenericParamDefKind::Const => param,
1003 _ => bug!("expected const parameter, but found another generic parameter")
1006 tcx.generics_of(self.parent.expect("parent_count>0 but no parent?"))
1007 .const_param(param, tcx)
1012 /// Bounds on generics.
1013 #[derive(Clone, Default, Debug, HashStable)]
1014 pub struct GenericPredicates<'tcx> {
1015 pub parent: Option<DefId>,
1016 pub predicates: Vec<(Predicate<'tcx>, Span)>,
1019 impl<'tcx> rustc_serialize::UseSpecializedEncodable for GenericPredicates<'tcx> {}
1020 impl<'tcx> rustc_serialize::UseSpecializedDecodable for GenericPredicates<'tcx> {}
1022 impl<'tcx> GenericPredicates<'tcx> {
1026 substs: SubstsRef<'tcx>,
1027 ) -> InstantiatedPredicates<'tcx> {
1028 let mut instantiated = InstantiatedPredicates::empty();
1029 self.instantiate_into(tcx, &mut instantiated, substs);
1033 pub fn instantiate_own(
1036 substs: SubstsRef<'tcx>,
1037 ) -> InstantiatedPredicates<'tcx> {
1038 InstantiatedPredicates {
1039 predicates: self.predicates.iter().map(|(p, _)| p.subst(tcx, substs)).collect(),
1043 fn instantiate_into(
1046 instantiated: &mut InstantiatedPredicates<'tcx>,
1047 substs: SubstsRef<'tcx>,
1049 if let Some(def_id) = self.parent {
1050 tcx.predicates_of(def_id).instantiate_into(tcx, instantiated, substs);
1052 instantiated.predicates.extend(
1053 self.predicates.iter().map(|(p, _)| p.subst(tcx, substs)),
1057 pub fn instantiate_identity(&self, tcx: TyCtxt<'tcx>) -> InstantiatedPredicates<'tcx> {
1058 let mut instantiated = InstantiatedPredicates::empty();
1059 self.instantiate_identity_into(tcx, &mut instantiated);
1063 fn instantiate_identity_into(
1066 instantiated: &mut InstantiatedPredicates<'tcx>,
1068 if let Some(def_id) = self.parent {
1069 tcx.predicates_of(def_id).instantiate_identity_into(tcx, instantiated);
1071 instantiated.predicates.extend(self.predicates.iter().map(|&(p, _)| p))
1074 pub fn instantiate_supertrait(
1077 poly_trait_ref: &ty::PolyTraitRef<'tcx>,
1078 ) -> InstantiatedPredicates<'tcx> {
1079 assert_eq!(self.parent, None);
1080 InstantiatedPredicates {
1081 predicates: self.predicates.iter().map(|(pred, _)| {
1082 pred.subst_supertrait(tcx, poly_trait_ref)
1088 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
1089 pub enum Predicate<'tcx> {
1090 /// Corresponds to `where Foo: Bar<A, B, C>`. `Foo` here would be
1091 /// the `Self` type of the trait reference and `A`, `B`, and `C`
1092 /// would be the type parameters.
1093 Trait(PolyTraitPredicate<'tcx>),
1096 RegionOutlives(PolyRegionOutlivesPredicate<'tcx>),
1099 TypeOutlives(PolyTypeOutlivesPredicate<'tcx>),
1101 /// `where <T as TraitRef>::Name == X`, approximately.
1102 /// See the `ProjectionPredicate` struct for details.
1103 Projection(PolyProjectionPredicate<'tcx>),
1105 /// No syntax: `T` well-formed.
1106 WellFormed(Ty<'tcx>),
1108 /// Trait must be object-safe.
1111 /// No direct syntax. May be thought of as `where T: FnFoo<...>`
1112 /// for some substitutions `...` and `T` being a closure type.
1113 /// Satisfied (or refuted) once we know the closure's kind.
1114 ClosureKind(DefId, SubstsRef<'tcx>, ClosureKind),
1117 Subtype(PolySubtypePredicate<'tcx>),
1119 /// Constant initializer must evaluate successfully.
1120 ConstEvaluatable(DefId, SubstsRef<'tcx>),
1123 /// The crate outlives map is computed during typeck and contains the
1124 /// outlives of every item in the local crate. You should not use it
1125 /// directly, because to do so will make your pass dependent on the
1126 /// HIR of every item in the local crate. Instead, use
1127 /// `tcx.inferred_outlives_of()` to get the outlives for a *particular*
1129 #[derive(HashStable)]
1130 pub struct CratePredicatesMap<'tcx> {
1131 /// For each struct with outlive bounds, maps to a vector of the
1132 /// predicate of its outlive bounds. If an item has no outlives
1133 /// bounds, it will have no entry.
1134 pub predicates: FxHashMap<DefId, &'tcx [ty::Predicate<'tcx>]>,
1137 impl<'tcx> AsRef<Predicate<'tcx>> for Predicate<'tcx> {
1138 fn as_ref(&self) -> &Predicate<'tcx> {
1143 impl<'tcx> Predicate<'tcx> {
1144 /// Performs a substitution suitable for going from a
1145 /// poly-trait-ref to supertraits that must hold if that
1146 /// poly-trait-ref holds. This is slightly different from a normal
1147 /// substitution in terms of what happens with bound regions. See
1148 /// lengthy comment below for details.
1149 pub fn subst_supertrait(
1152 trait_ref: &ty::PolyTraitRef<'tcx>,
1153 ) -> ty::Predicate<'tcx> {
1154 // The interaction between HRTB and supertraits is not entirely
1155 // obvious. Let me walk you (and myself) through an example.
1157 // Let's start with an easy case. Consider two traits:
1159 // trait Foo<'a>: Bar<'a,'a> { }
1160 // trait Bar<'b,'c> { }
1162 // Now, if we have a trait reference `for<'x> T: Foo<'x>`, then
1163 // we can deduce that `for<'x> T: Bar<'x,'x>`. Basically, if we
1164 // knew that `Foo<'x>` (for any 'x) then we also know that
1165 // `Bar<'x,'x>` (for any 'x). This more-or-less falls out from
1166 // normal substitution.
1168 // In terms of why this is sound, the idea is that whenever there
1169 // is an impl of `T:Foo<'a>`, it must show that `T:Bar<'a,'a>`
1170 // holds. So if there is an impl of `T:Foo<'a>` that applies to
1171 // all `'a`, then we must know that `T:Bar<'a,'a>` holds for all
1174 // Another example to be careful of is this:
1176 // trait Foo1<'a>: for<'b> Bar1<'a,'b> { }
1177 // trait Bar1<'b,'c> { }
1179 // Here, if we have `for<'x> T: Foo1<'x>`, then what do we know?
1180 // The answer is that we know `for<'x,'b> T: Bar1<'x,'b>`. The
1181 // reason is similar to the previous example: any impl of
1182 // `T:Foo1<'x>` must show that `for<'b> T: Bar1<'x, 'b>`. So
1183 // basically we would want to collapse the bound lifetimes from
1184 // the input (`trait_ref`) and the supertraits.
1186 // To achieve this in practice is fairly straightforward. Let's
1187 // consider the more complicated scenario:
1189 // - We start out with `for<'x> T: Foo1<'x>`. In this case, `'x`
1190 // has a De Bruijn index of 1. We want to produce `for<'x,'b> T: Bar1<'x,'b>`,
1191 // where both `'x` and `'b` would have a DB index of 1.
1192 // The substitution from the input trait-ref is therefore going to be
1193 // `'a => 'x` (where `'x` has a DB index of 1).
1194 // - The super-trait-ref is `for<'b> Bar1<'a,'b>`, where `'a` is an
1195 // early-bound parameter and `'b' is a late-bound parameter with a
1197 // - If we replace `'a` with `'x` from the input, it too will have
1198 // a DB index of 1, and thus we'll have `for<'x,'b> Bar1<'x,'b>`
1199 // just as we wanted.
1201 // There is only one catch. If we just apply the substitution `'a
1202 // => 'x` to `for<'b> Bar1<'a,'b>`, the substitution code will
1203 // adjust the DB index because we substituting into a binder (it
1204 // tries to be so smart...) resulting in `for<'x> for<'b>
1205 // Bar1<'x,'b>` (we have no syntax for this, so use your
1206 // imagination). Basically the 'x will have DB index of 2 and 'b
1207 // will have DB index of 1. Not quite what we want. So we apply
1208 // the substitution to the *contents* of the trait reference,
1209 // rather than the trait reference itself (put another way, the
1210 // substitution code expects equal binding levels in the values
1211 // from the substitution and the value being substituted into, and
1212 // this trick achieves that).
1214 let substs = &trait_ref.skip_binder().substs;
1216 Predicate::Trait(ref binder) =>
1217 Predicate::Trait(binder.map_bound(|data| data.subst(tcx, substs))),
1218 Predicate::Subtype(ref binder) =>
1219 Predicate::Subtype(binder.map_bound(|data| data.subst(tcx, substs))),
1220 Predicate::RegionOutlives(ref binder) =>
1221 Predicate::RegionOutlives(binder.map_bound(|data| data.subst(tcx, substs))),
1222 Predicate::TypeOutlives(ref binder) =>
1223 Predicate::TypeOutlives(binder.map_bound(|data| data.subst(tcx, substs))),
1224 Predicate::Projection(ref binder) =>
1225 Predicate::Projection(binder.map_bound(|data| data.subst(tcx, substs))),
1226 Predicate::WellFormed(data) =>
1227 Predicate::WellFormed(data.subst(tcx, substs)),
1228 Predicate::ObjectSafe(trait_def_id) =>
1229 Predicate::ObjectSafe(trait_def_id),
1230 Predicate::ClosureKind(closure_def_id, closure_substs, kind) =>
1231 Predicate::ClosureKind(closure_def_id, closure_substs.subst(tcx, substs), kind),
1232 Predicate::ConstEvaluatable(def_id, const_substs) =>
1233 Predicate::ConstEvaluatable(def_id, const_substs.subst(tcx, substs)),
1238 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
1239 pub struct TraitPredicate<'tcx> {
1240 pub trait_ref: TraitRef<'tcx>
1243 pub type PolyTraitPredicate<'tcx> = ty::Binder<TraitPredicate<'tcx>>;
1245 impl<'tcx> TraitPredicate<'tcx> {
1246 pub fn def_id(&self) -> DefId {
1247 self.trait_ref.def_id
1250 pub fn input_types<'a>(&'a self) -> impl DoubleEndedIterator<Item = Ty<'tcx>> + 'a {
1251 self.trait_ref.input_types()
1254 pub fn self_ty(&self) -> Ty<'tcx> {
1255 self.trait_ref.self_ty()
1259 impl<'tcx> PolyTraitPredicate<'tcx> {
1260 pub fn def_id(&self) -> DefId {
1261 // Ok to skip binder since trait `DefId` does not care about regions.
1262 self.skip_binder().def_id()
1266 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord,
1267 Hash, Debug, RustcEncodable, RustcDecodable, HashStable)]
1268 pub struct OutlivesPredicate<A, B>(pub A, pub B); // `A: B`
1269 pub type PolyOutlivesPredicate<A, B> = ty::Binder<OutlivesPredicate<A, B>>;
1270 pub type RegionOutlivesPredicate<'tcx> = OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>;
1271 pub type TypeOutlivesPredicate<'tcx> = OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>;
1272 pub type PolyRegionOutlivesPredicate<'tcx> = ty::Binder<RegionOutlivesPredicate<'tcx>>;
1273 pub type PolyTypeOutlivesPredicate<'tcx> = ty::Binder<TypeOutlivesPredicate<'tcx>>;
1275 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable, HashStable)]
1276 pub struct SubtypePredicate<'tcx> {
1277 pub a_is_expected: bool,
1281 pub type PolySubtypePredicate<'tcx> = ty::Binder<SubtypePredicate<'tcx>>;
1283 /// This kind of predicate has no *direct* correspondent in the
1284 /// syntax, but it roughly corresponds to the syntactic forms:
1286 /// 1. `T: TraitRef<..., Item = Type>`
1287 /// 2. `<T as TraitRef<...>>::Item == Type` (NYI)
1289 /// In particular, form #1 is "desugared" to the combination of a
1290 /// normal trait predicate (`T: TraitRef<...>`) and one of these
1291 /// predicates. Form #2 is a broader form in that it also permits
1292 /// equality between arbitrary types. Processing an instance of
1293 /// Form #2 eventually yields one of these `ProjectionPredicate`
1294 /// instances to normalize the LHS.
1295 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
1296 pub struct ProjectionPredicate<'tcx> {
1297 pub projection_ty: ProjectionTy<'tcx>,
1301 pub type PolyProjectionPredicate<'tcx> = Binder<ProjectionPredicate<'tcx>>;
1303 impl<'tcx> PolyProjectionPredicate<'tcx> {
1304 /// Returns the `DefId` of the associated item being projected.
1305 pub fn item_def_id(&self) -> DefId {
1306 self.skip_binder().projection_ty.item_def_id
1310 pub fn to_poly_trait_ref(&self, tcx: TyCtxt<'_>) -> PolyTraitRef<'tcx> {
1311 // Note: unlike with `TraitRef::to_poly_trait_ref()`,
1312 // `self.0.trait_ref` is permitted to have escaping regions.
1313 // This is because here `self` has a `Binder` and so does our
1314 // return value, so we are preserving the number of binding
1316 self.map_bound(|predicate| predicate.projection_ty.trait_ref(tcx))
1319 pub fn ty(&self) -> Binder<Ty<'tcx>> {
1320 self.map_bound(|predicate| predicate.ty)
1323 /// The `DefId` of the `TraitItem` for the associated type.
1325 /// Note that this is not the `DefId` of the `TraitRef` containing this
1326 /// associated type, which is in `tcx.associated_item(projection_def_id()).container`.
1327 pub fn projection_def_id(&self) -> DefId {
1328 // Ok to skip binder since trait `DefId` does not care about regions.
1329 self.skip_binder().projection_ty.item_def_id
1333 pub trait ToPolyTraitRef<'tcx> {
1334 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx>;
1337 impl<'tcx> ToPolyTraitRef<'tcx> for TraitRef<'tcx> {
1338 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
1339 ty::Binder::dummy(self.clone())
1343 impl<'tcx> ToPolyTraitRef<'tcx> for PolyTraitPredicate<'tcx> {
1344 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
1345 self.map_bound_ref(|trait_pred| trait_pred.trait_ref)
1349 pub trait ToPredicate<'tcx> {
1350 fn to_predicate(&self) -> Predicate<'tcx>;
1353 impl<'tcx> ToPredicate<'tcx> for TraitRef<'tcx> {
1354 fn to_predicate(&self) -> Predicate<'tcx> {
1355 ty::Predicate::Trait(ty::Binder::dummy(ty::TraitPredicate {
1356 trait_ref: self.clone()
1361 impl<'tcx> ToPredicate<'tcx> for PolyTraitRef<'tcx> {
1362 fn to_predicate(&self) -> Predicate<'tcx> {
1363 ty::Predicate::Trait(self.to_poly_trait_predicate())
1367 impl<'tcx> ToPredicate<'tcx> for PolyRegionOutlivesPredicate<'tcx> {
1368 fn to_predicate(&self) -> Predicate<'tcx> {
1369 Predicate::RegionOutlives(self.clone())
1373 impl<'tcx> ToPredicate<'tcx> for PolyTypeOutlivesPredicate<'tcx> {
1374 fn to_predicate(&self) -> Predicate<'tcx> {
1375 Predicate::TypeOutlives(self.clone())
1379 impl<'tcx> ToPredicate<'tcx> for PolyProjectionPredicate<'tcx> {
1380 fn to_predicate(&self) -> Predicate<'tcx> {
1381 Predicate::Projection(self.clone())
1385 // A custom iterator used by `Predicate::walk_tys`.
1386 enum WalkTysIter<'tcx, I, J, K>
1387 where I: Iterator<Item = Ty<'tcx>>,
1388 J: Iterator<Item = Ty<'tcx>>,
1389 K: Iterator<Item = Ty<'tcx>>
1393 Two(Ty<'tcx>, Ty<'tcx>),
1399 impl<'tcx, I, J, K> Iterator for WalkTysIter<'tcx, I, J, K>
1400 where I: Iterator<Item = Ty<'tcx>>,
1401 J: Iterator<Item = Ty<'tcx>>,
1402 K: Iterator<Item = Ty<'tcx>>
1404 type Item = Ty<'tcx>;
1406 fn next(&mut self) -> Option<Ty<'tcx>> {
1408 WalkTysIter::None => None,
1409 WalkTysIter::One(item) => {
1410 *self = WalkTysIter::None;
1413 WalkTysIter::Two(item1, item2) => {
1414 *self = WalkTysIter::One(item2);
1417 WalkTysIter::Types(ref mut iter) => {
1420 WalkTysIter::InputTypes(ref mut iter) => {
1423 WalkTysIter::ProjectionTypes(ref mut iter) => {
1430 impl<'tcx> Predicate<'tcx> {
1431 /// Iterates over the types in this predicate. Note that in all
1432 /// cases this is skipping over a binder, so late-bound regions
1433 /// with depth 0 are bound by the predicate.
1434 pub fn walk_tys(&'a self) -> impl Iterator<Item = Ty<'tcx>> + 'a {
1436 ty::Predicate::Trait(ref data) => {
1437 WalkTysIter::InputTypes(data.skip_binder().input_types())
1439 ty::Predicate::Subtype(binder) => {
1440 let SubtypePredicate { a, b, a_is_expected: _ } = binder.skip_binder();
1441 WalkTysIter::Two(a, b)
1443 ty::Predicate::TypeOutlives(binder) => {
1444 WalkTysIter::One(binder.skip_binder().0)
1446 ty::Predicate::RegionOutlives(..) => {
1449 ty::Predicate::Projection(ref data) => {
1450 let inner = data.skip_binder();
1451 WalkTysIter::ProjectionTypes(
1452 inner.projection_ty.substs.types().chain(Some(inner.ty)))
1454 ty::Predicate::WellFormed(data) => {
1455 WalkTysIter::One(data)
1457 ty::Predicate::ObjectSafe(_trait_def_id) => {
1460 ty::Predicate::ClosureKind(_closure_def_id, closure_substs, _kind) => {
1461 WalkTysIter::Types(closure_substs.types())
1463 ty::Predicate::ConstEvaluatable(_, substs) => {
1464 WalkTysIter::Types(substs.types())
1469 pub fn to_opt_poly_trait_ref(&self) -> Option<PolyTraitRef<'tcx>> {
1471 Predicate::Trait(ref t) => {
1472 Some(t.to_poly_trait_ref())
1474 Predicate::Projection(..) |
1475 Predicate::Subtype(..) |
1476 Predicate::RegionOutlives(..) |
1477 Predicate::WellFormed(..) |
1478 Predicate::ObjectSafe(..) |
1479 Predicate::ClosureKind(..) |
1480 Predicate::TypeOutlives(..) |
1481 Predicate::ConstEvaluatable(..) => {
1487 pub fn to_opt_type_outlives(&self) -> Option<PolyTypeOutlivesPredicate<'tcx>> {
1489 Predicate::TypeOutlives(data) => {
1492 Predicate::Trait(..) |
1493 Predicate::Projection(..) |
1494 Predicate::Subtype(..) |
1495 Predicate::RegionOutlives(..) |
1496 Predicate::WellFormed(..) |
1497 Predicate::ObjectSafe(..) |
1498 Predicate::ClosureKind(..) |
1499 Predicate::ConstEvaluatable(..) => {
1506 /// Represents the bounds declared on a particular set of type
1507 /// parameters. Should eventually be generalized into a flag list of
1508 /// where-clauses. You can obtain a `InstantiatedPredicates` list from a
1509 /// `GenericPredicates` by using the `instantiate` method. Note that this method
1510 /// reflects an important semantic invariant of `InstantiatedPredicates`: while
1511 /// the `GenericPredicates` are expressed in terms of the bound type
1512 /// parameters of the impl/trait/whatever, an `InstantiatedPredicates` instance
1513 /// represented a set of bounds for some particular instantiation,
1514 /// meaning that the generic parameters have been substituted with
1519 /// struct Foo<T, U: Bar<T>> { ... }
1521 /// Here, the `GenericPredicates` for `Foo` would contain a list of bounds like
1522 /// `[[], [U:Bar<T>]]`. Now if there were some particular reference
1523 /// like `Foo<isize,usize>`, then the `InstantiatedPredicates` would be `[[],
1524 /// [usize:Bar<isize>]]`.
1525 #[derive(Clone, Debug)]
1526 pub struct InstantiatedPredicates<'tcx> {
1527 pub predicates: Vec<Predicate<'tcx>>,
1530 impl<'tcx> InstantiatedPredicates<'tcx> {
1531 pub fn empty() -> InstantiatedPredicates<'tcx> {
1532 InstantiatedPredicates { predicates: vec![] }
1535 pub fn is_empty(&self) -> bool {
1536 self.predicates.is_empty()
1540 rustc_index::newtype_index! {
1541 /// "Universes" are used during type- and trait-checking in the
1542 /// presence of `for<..>` binders to control what sets of names are
1543 /// visible. Universes are arranged into a tree: the root universe
1544 /// contains names that are always visible. Each child then adds a new
1545 /// set of names that are visible, in addition to those of its parent.
1546 /// We say that the child universe "extends" the parent universe with
1549 /// To make this more concrete, consider this program:
1553 /// fn bar<T>(x: T) {
1554 /// let y: for<'a> fn(&'a u8, Foo) = ...;
1558 /// The struct name `Foo` is in the root universe U0. But the type
1559 /// parameter `T`, introduced on `bar`, is in an extended universe U1
1560 /// -- i.e., within `bar`, we can name both `T` and `Foo`, but outside
1561 /// of `bar`, we cannot name `T`. Then, within the type of `y`, the
1562 /// region `'a` is in a universe U2 that extends U1, because we can
1563 /// name it inside the fn type but not outside.
1565 /// Universes are used to do type- and trait-checking around these
1566 /// "forall" binders (also called **universal quantification**). The
1567 /// idea is that when, in the body of `bar`, we refer to `T` as a
1568 /// type, we aren't referring to any type in particular, but rather a
1569 /// kind of "fresh" type that is distinct from all other types we have
1570 /// actually declared. This is called a **placeholder** type, and we
1571 /// use universes to talk about this. In other words, a type name in
1572 /// universe 0 always corresponds to some "ground" type that the user
1573 /// declared, but a type name in a non-zero universe is a placeholder
1574 /// type -- an idealized representative of "types in general" that we
1575 /// use for checking generic functions.
1576 pub struct UniverseIndex {
1577 DEBUG_FORMAT = "U{}",
1581 impl_stable_hash_for!(struct UniverseIndex { private });
1583 impl UniverseIndex {
1584 pub const ROOT: UniverseIndex = UniverseIndex::from_u32_const(0);
1586 /// Returns the "next" universe index in order -- this new index
1587 /// is considered to extend all previous universes. This
1588 /// corresponds to entering a `forall` quantifier. So, for
1589 /// example, suppose we have this type in universe `U`:
1592 /// for<'a> fn(&'a u32)
1595 /// Once we "enter" into this `for<'a>` quantifier, we are in a
1596 /// new universe that extends `U` -- in this new universe, we can
1597 /// name the region `'a`, but that region was not nameable from
1598 /// `U` because it was not in scope there.
1599 pub fn next_universe(self) -> UniverseIndex {
1600 UniverseIndex::from_u32(self.private.checked_add(1).unwrap())
1603 /// Returns `true` if `self` can name a name from `other` -- in other words,
1604 /// if the set of names in `self` is a superset of those in
1605 /// `other` (`self >= other`).
1606 pub fn can_name(self, other: UniverseIndex) -> bool {
1607 self.private >= other.private
1610 /// Returns `true` if `self` cannot name some names from `other` -- in other
1611 /// words, if the set of names in `self` is a strict subset of
1612 /// those in `other` (`self < other`).
1613 pub fn cannot_name(self, other: UniverseIndex) -> bool {
1614 self.private < other.private
1618 /// The "placeholder index" fully defines a placeholder region.
1619 /// Placeholder regions are identified by both a **universe** as well
1620 /// as a "bound-region" within that universe. The `bound_region` is
1621 /// basically a name -- distinct bound regions within the same
1622 /// universe are just two regions with an unknown relationship to one
1624 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, PartialOrd, Ord)]
1625 pub struct Placeholder<T> {
1626 pub universe: UniverseIndex,
1630 impl<'a, T> HashStable<StableHashingContext<'a>> for Placeholder<T>
1632 T: HashStable<StableHashingContext<'a>>,
1634 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
1635 self.universe.hash_stable(hcx, hasher);
1636 self.name.hash_stable(hcx, hasher);
1640 pub type PlaceholderRegion = Placeholder<BoundRegion>;
1642 pub type PlaceholderType = Placeholder<BoundVar>;
1644 pub type PlaceholderConst = Placeholder<BoundVar>;
1646 /// When type checking, we use the `ParamEnv` to track
1647 /// details about the set of where-clauses that are in scope at this
1648 /// particular point.
1649 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable)]
1650 pub struct ParamEnv<'tcx> {
1651 /// `Obligation`s that the caller must satisfy. This is basically
1652 /// the set of bounds on the in-scope type parameters, translated
1653 /// into `Obligation`s, and elaborated and normalized.
1654 pub caller_bounds: &'tcx List<ty::Predicate<'tcx>>,
1656 /// Typically, this is `Reveal::UserFacing`, but during codegen we
1657 /// want `Reveal::All` -- note that this is always paired with an
1658 /// empty environment. To get that, use `ParamEnv::reveal()`.
1659 pub reveal: traits::Reveal,
1661 /// If this `ParamEnv` comes from a call to `tcx.param_env(def_id)`,
1662 /// register that `def_id` (useful for transitioning to the chalk trait
1664 pub def_id: Option<DefId>,
1667 impl<'tcx> ParamEnv<'tcx> {
1668 /// Construct a trait environment suitable for contexts where
1669 /// there are no where-clauses in scope. Hidden types (like `impl
1670 /// Trait`) are left hidden, so this is suitable for ordinary
1673 pub fn empty() -> Self {
1674 Self::new(List::empty(), Reveal::UserFacing, None)
1677 /// Construct a trait environment with no where-clauses in scope
1678 /// where the values of all `impl Trait` and other hidden types
1679 /// are revealed. This is suitable for monomorphized, post-typeck
1680 /// environments like codegen or doing optimizations.
1682 /// N.B., if you want to have predicates in scope, use `ParamEnv::new`,
1683 /// or invoke `param_env.with_reveal_all()`.
1685 pub fn reveal_all() -> Self {
1686 Self::new(List::empty(), Reveal::All, None)
1689 /// Construct a trait environment with the given set of predicates.
1692 caller_bounds: &'tcx List<ty::Predicate<'tcx>>,
1694 def_id: Option<DefId>
1696 ty::ParamEnv { caller_bounds, reveal, def_id }
1699 /// Returns a new parameter environment with the same clauses, but
1700 /// which "reveals" the true results of projections in all cases
1701 /// (even for associated types that are specializable). This is
1702 /// the desired behavior during codegen and certain other special
1703 /// contexts; normally though we want to use `Reveal::UserFacing`,
1704 /// which is the default.
1705 pub fn with_reveal_all(self) -> Self {
1706 ty::ParamEnv { reveal: Reveal::All, ..self }
1709 /// Returns this same environment but with no caller bounds.
1710 pub fn without_caller_bounds(self) -> Self {
1711 ty::ParamEnv { caller_bounds: List::empty(), ..self }
1714 /// Creates a suitable environment in which to perform trait
1715 /// queries on the given value. When type-checking, this is simply
1716 /// the pair of the environment plus value. But when reveal is set to
1717 /// All, then if `value` does not reference any type parameters, we will
1718 /// pair it with the empty environment. This improves caching and is generally
1721 /// N.B., we preserve the environment when type-checking because it
1722 /// is possible for the user to have wacky where-clauses like
1723 /// `where Box<u32>: Copy`, which are clearly never
1724 /// satisfiable. We generally want to behave as if they were true,
1725 /// although the surrounding function is never reachable.
1726 pub fn and<T: TypeFoldable<'tcx>>(self, value: T) -> ParamEnvAnd<'tcx, T> {
1728 Reveal::UserFacing => {
1736 if value.has_placeholders()
1737 || value.needs_infer()
1738 || value.has_param_types()
1746 param_env: self.without_caller_bounds(),
1755 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1756 pub struct ParamEnvAnd<'tcx, T> {
1757 pub param_env: ParamEnv<'tcx>,
1761 impl<'tcx, T> ParamEnvAnd<'tcx, T> {
1762 pub fn into_parts(self) -> (ParamEnv<'tcx>, T) {
1763 (self.param_env, self.value)
1767 impl<'a, 'tcx, T> HashStable<StableHashingContext<'a>> for ParamEnvAnd<'tcx, T>
1769 T: HashStable<StableHashingContext<'a>>,
1771 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
1777 param_env.hash_stable(hcx, hasher);
1778 value.hash_stable(hcx, hasher);
1782 #[derive(Copy, Clone, Debug, HashStable)]
1783 pub struct Destructor {
1784 /// The `DefId` of the destructor method
1789 #[derive(HashStable)]
1790 pub struct AdtFlags: u32 {
1791 const NO_ADT_FLAGS = 0;
1792 /// Indicates whether the ADT is an enum.
1793 const IS_ENUM = 1 << 0;
1794 /// Indicates whether the ADT is a union.
1795 const IS_UNION = 1 << 1;
1796 /// Indicates whether the ADT is a struct.
1797 const IS_STRUCT = 1 << 2;
1798 /// Indicates whether the ADT is a struct and has a constructor.
1799 const HAS_CTOR = 1 << 3;
1800 /// Indicates whether the type is a `PhantomData`.
1801 const IS_PHANTOM_DATA = 1 << 4;
1802 /// Indicates whether the type has a `#[fundamental]` attribute.
1803 const IS_FUNDAMENTAL = 1 << 5;
1804 /// Indicates whether the type is a `Box`.
1805 const IS_BOX = 1 << 6;
1806 /// Indicates whether the type is an `Arc`.
1807 const IS_ARC = 1 << 7;
1808 /// Indicates whether the type is an `Rc`.
1809 const IS_RC = 1 << 8;
1810 /// Indicates whether the variant list of this ADT is `#[non_exhaustive]`.
1811 /// (i.e., this flag is never set unless this ADT is an enum).
1812 const IS_VARIANT_LIST_NON_EXHAUSTIVE = 1 << 9;
1817 #[derive(HashStable)]
1818 pub struct VariantFlags: u32 {
1819 const NO_VARIANT_FLAGS = 0;
1820 /// Indicates whether the field list of this variant is `#[non_exhaustive]`.
1821 const IS_FIELD_LIST_NON_EXHAUSTIVE = 1 << 0;
1825 /// Definition of a variant -- a struct's fields or a enum variant.
1827 pub struct VariantDef {
1828 /// `DefId` that identifies the variant itself.
1829 /// If this variant belongs to a struct or union, then this is a copy of its `DefId`.
1831 /// `DefId` that identifies the variant's constructor.
1832 /// If this variant is a struct variant, then this is `None`.
1833 pub ctor_def_id: Option<DefId>,
1834 /// Variant or struct name.
1836 /// Discriminant of this variant.
1837 pub discr: VariantDiscr,
1838 /// Fields of this variant.
1839 pub fields: Vec<FieldDef>,
1840 /// Type of constructor of variant.
1841 pub ctor_kind: CtorKind,
1842 /// Flags of the variant (e.g. is field list non-exhaustive)?
1843 flags: VariantFlags,
1844 /// Variant is obtained as part of recovering from a syntactic error.
1845 /// May be incomplete or bogus.
1846 pub recovered: bool,
1849 impl<'tcx> VariantDef {
1850 /// Creates a new `VariantDef`.
1852 /// `variant_did` is the `DefId` that identifies the enum variant (if this `VariantDef`
1853 /// represents an enum variant).
1855 /// `ctor_did` is the `DefId` that identifies the constructor of unit or
1856 /// tuple-variants/structs. If this is a `struct`-variant then this should be `None`.
1858 /// `parent_did` is the `DefId` of the `AdtDef` representing the enum or struct that
1859 /// owns this variant. It is used for checking if a struct has `#[non_exhaustive]` w/out having
1860 /// to go through the redirect of checking the ctor's attributes - but compiling a small crate
1861 /// requires loading the `AdtDef`s for all the structs in the universe (e.g., coherence for any
1862 /// built-in trait), and we do not want to load attributes twice.
1864 /// If someone speeds up attribute loading to not be a performance concern, they can
1865 /// remove this hack and use the constructor `DefId` everywhere.
1869 variant_did: Option<DefId>,
1870 ctor_def_id: Option<DefId>,
1871 discr: VariantDiscr,
1872 fields: Vec<FieldDef>,
1873 ctor_kind: CtorKind,
1879 "VariantDef::new(ident = {:?}, variant_did = {:?}, ctor_def_id = {:?}, discr = {:?},
1880 fields = {:?}, ctor_kind = {:?}, adt_kind = {:?}, parent_did = {:?})",
1881 ident, variant_did, ctor_def_id, discr, fields, ctor_kind, adt_kind, parent_did,
1884 let mut flags = VariantFlags::NO_VARIANT_FLAGS;
1885 if adt_kind == AdtKind::Struct && tcx.has_attr(parent_did, sym::non_exhaustive) {
1886 debug!("found non-exhaustive field list for {:?}", parent_did);
1887 flags = flags | VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE;
1888 } else if let Some(variant_did) = variant_did {
1889 if tcx.has_attr(variant_did, sym::non_exhaustive) {
1890 debug!("found non-exhaustive field list for {:?}", variant_did);
1891 flags = flags | VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE;
1896 def_id: variant_did.unwrap_or(parent_did),
1907 /// Is this field list non-exhaustive?
1909 pub fn is_field_list_non_exhaustive(&self) -> bool {
1910 self.flags.intersects(VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE)
1914 impl_stable_hash_for!(struct VariantDef {
1917 ident -> (ident.name),
1925 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
1926 pub enum VariantDiscr {
1927 /// Explicit value for this variant, i.e., `X = 123`.
1928 /// The `DefId` corresponds to the embedded constant.
1931 /// The previous variant's discriminant plus one.
1932 /// For efficiency reasons, the distance from the
1933 /// last `Explicit` discriminant is being stored,
1934 /// or `0` for the first variant, if it has none.
1938 #[derive(Debug, HashStable)]
1939 pub struct FieldDef {
1941 #[stable_hasher(project(name))]
1943 pub vis: Visibility,
1946 /// The definition of a user-defined type, e.g., a `struct`, `enum`, or `union`.
1948 /// These are all interned (by `intern_adt_def`) into the `adt_defs` table.
1950 /// The initialism *"Adt"* stands for an [*algebraic data type (ADT)*][adt].
1951 /// This is slightly wrong because `union`s are not ADTs.
1952 /// Moreover, Rust only allows recursive data types through indirection.
1954 /// [adt]: https://en.wikipedia.org/wiki/Algebraic_data_type
1956 /// `DefId` of the struct, enum or union item.
1958 /// Variants of the ADT. If this is a struct or union, then there will be a single variant.
1959 pub variants: IndexVec<self::layout::VariantIdx, VariantDef>,
1960 /// Flags of the ADT (e.g. is this a struct? is this non-exhaustive?)
1962 /// Repr options provided by the user.
1963 pub repr: ReprOptions,
1966 impl PartialOrd for AdtDef {
1967 fn partial_cmp(&self, other: &AdtDef) -> Option<Ordering> {
1968 Some(self.cmp(&other))
1972 /// There should be only one AdtDef for each `did`, therefore
1973 /// it is fine to implement `Ord` only based on `did`.
1974 impl Ord for AdtDef {
1975 fn cmp(&self, other: &AdtDef) -> Ordering {
1976 self.did.cmp(&other.did)
1980 impl PartialEq for AdtDef {
1981 // AdtDef are always interned and this is part of TyS equality
1983 fn eq(&self, other: &Self) -> bool { ptr::eq(self, other) }
1986 impl Eq for AdtDef {}
1988 impl Hash for AdtDef {
1990 fn hash<H: Hasher>(&self, s: &mut H) {
1991 (self as *const AdtDef).hash(s)
1995 impl<'tcx> rustc_serialize::UseSpecializedEncodable for &'tcx AdtDef {
1996 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
2001 impl<'tcx> rustc_serialize::UseSpecializedDecodable for &'tcx AdtDef {}
2004 impl<'a> HashStable<StableHashingContext<'a>> for AdtDef {
2005 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
2007 static CACHE: RefCell<FxHashMap<usize, Fingerprint>> = Default::default();
2010 let hash: Fingerprint = CACHE.with(|cache| {
2011 let addr = self as *const AdtDef as usize;
2012 *cache.borrow_mut().entry(addr).or_insert_with(|| {
2020 let mut hasher = StableHasher::new();
2021 did.hash_stable(hcx, &mut hasher);
2022 variants.hash_stable(hcx, &mut hasher);
2023 flags.hash_stable(hcx, &mut hasher);
2024 repr.hash_stable(hcx, &mut hasher);
2030 hash.hash_stable(hcx, hasher);
2034 #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
2035 pub enum AdtKind { Struct, Union, Enum }
2037 impl Into<DataTypeKind> for AdtKind {
2038 fn into(self) -> DataTypeKind {
2040 AdtKind::Struct => DataTypeKind::Struct,
2041 AdtKind::Union => DataTypeKind::Union,
2042 AdtKind::Enum => DataTypeKind::Enum,
2048 #[derive(RustcEncodable, RustcDecodable, Default)]
2049 pub struct ReprFlags: u8 {
2050 const IS_C = 1 << 0;
2051 const IS_SIMD = 1 << 1;
2052 const IS_TRANSPARENT = 1 << 2;
2053 // Internal only for now. If true, don't reorder fields.
2054 const IS_LINEAR = 1 << 3;
2056 // Any of these flags being set prevent field reordering optimisation.
2057 const IS_UNOPTIMISABLE = ReprFlags::IS_C.bits |
2058 ReprFlags::IS_SIMD.bits |
2059 ReprFlags::IS_LINEAR.bits;
2063 impl_stable_hash_for!(struct ReprFlags {
2067 /// Represents the repr options provided by the user,
2068 #[derive(Copy, Clone, Debug, Eq, PartialEq, RustcEncodable, RustcDecodable, Default)]
2069 pub struct ReprOptions {
2070 pub int: Option<attr::IntType>,
2071 pub align: Option<Align>,
2072 pub pack: Option<Align>,
2073 pub flags: ReprFlags,
2076 impl_stable_hash_for!(struct ReprOptions {
2084 pub fn new(tcx: TyCtxt<'_>, did: DefId) -> ReprOptions {
2085 let mut flags = ReprFlags::empty();
2086 let mut size = None;
2087 let mut max_align: Option<Align> = None;
2088 let mut min_pack: Option<Align> = None;
2089 for attr in tcx.get_attrs(did).iter() {
2090 for r in attr::find_repr_attrs(&tcx.sess.parse_sess, attr) {
2091 flags.insert(match r {
2092 attr::ReprC => ReprFlags::IS_C,
2093 attr::ReprPacked(pack) => {
2094 let pack = Align::from_bytes(pack as u64).unwrap();
2095 min_pack = Some(if let Some(min_pack) = min_pack {
2102 attr::ReprTransparent => ReprFlags::IS_TRANSPARENT,
2103 attr::ReprSimd => ReprFlags::IS_SIMD,
2104 attr::ReprInt(i) => {
2108 attr::ReprAlign(align) => {
2109 max_align = max_align.max(Some(Align::from_bytes(align as u64).unwrap()));
2116 // This is here instead of layout because the choice must make it into metadata.
2117 if !tcx.consider_optimizing(|| format!("Reorder fields of {:?}", tcx.def_path_str(did))) {
2118 flags.insert(ReprFlags::IS_LINEAR);
2120 ReprOptions { int: size, align: max_align, pack: min_pack, flags: flags }
2124 pub fn simd(&self) -> bool { self.flags.contains(ReprFlags::IS_SIMD) }
2126 pub fn c(&self) -> bool { self.flags.contains(ReprFlags::IS_C) }
2128 pub fn packed(&self) -> bool { self.pack.is_some() }
2130 pub fn transparent(&self) -> bool { self.flags.contains(ReprFlags::IS_TRANSPARENT) }
2132 pub fn linear(&self) -> bool { self.flags.contains(ReprFlags::IS_LINEAR) }
2134 pub fn discr_type(&self) -> attr::IntType {
2135 self.int.unwrap_or(attr::SignedInt(ast::IntTy::Isize))
2138 /// Returns `true` if this `#[repr()]` should inhabit "smart enum
2139 /// layout" optimizations, such as representing `Foo<&T>` as a
2141 pub fn inhibit_enum_layout_opt(&self) -> bool {
2142 self.c() || self.int.is_some()
2145 /// Returns `true` if this `#[repr()]` should inhibit struct field reordering
2146 /// optimizations, such as with `repr(C)`, `repr(packed(1))`, or `repr(<int>)`.
2147 pub fn inhibit_struct_field_reordering_opt(&self) -> bool {
2148 if let Some(pack) = self.pack {
2149 if pack.bytes() == 1 {
2153 self.flags.intersects(ReprFlags::IS_UNOPTIMISABLE) || self.int.is_some()
2156 /// Returns `true` if this `#[repr()]` should inhibit union ABI optimisations.
2157 pub fn inhibit_union_abi_opt(&self) -> bool {
2163 /// Creates a new `AdtDef`.
2168 variants: IndexVec<VariantIdx, VariantDef>,
2171 debug!("AdtDef::new({:?}, {:?}, {:?}, {:?})", did, kind, variants, repr);
2172 let mut flags = AdtFlags::NO_ADT_FLAGS;
2174 if kind == AdtKind::Enum && tcx.has_attr(did, sym::non_exhaustive) {
2175 debug!("found non-exhaustive variant list for {:?}", did);
2176 flags = flags | AdtFlags::IS_VARIANT_LIST_NON_EXHAUSTIVE;
2179 flags |= match kind {
2180 AdtKind::Enum => AdtFlags::IS_ENUM,
2181 AdtKind::Union => AdtFlags::IS_UNION,
2182 AdtKind::Struct => AdtFlags::IS_STRUCT,
2185 if kind == AdtKind::Struct && variants[VariantIdx::new(0)].ctor_def_id.is_some() {
2186 flags |= AdtFlags::HAS_CTOR;
2189 let attrs = tcx.get_attrs(did);
2190 if attr::contains_name(&attrs, sym::fundamental) {
2191 flags |= AdtFlags::IS_FUNDAMENTAL;
2193 if Some(did) == tcx.lang_items().phantom_data() {
2194 flags |= AdtFlags::IS_PHANTOM_DATA;
2196 if Some(did) == tcx.lang_items().owned_box() {
2197 flags |= AdtFlags::IS_BOX;
2199 if Some(did) == tcx.lang_items().arc() {
2200 flags |= AdtFlags::IS_ARC;
2202 if Some(did) == tcx.lang_items().rc() {
2203 flags |= AdtFlags::IS_RC;
2214 /// Returns `true` if this is a struct.
2216 pub fn is_struct(&self) -> bool {
2217 self.flags.contains(AdtFlags::IS_STRUCT)
2220 /// Returns `true` if this is a union.
2222 pub fn is_union(&self) -> bool {
2223 self.flags.contains(AdtFlags::IS_UNION)
2226 /// Returns `true` if this is a enum.
2228 pub fn is_enum(&self) -> bool {
2229 self.flags.contains(AdtFlags::IS_ENUM)
2232 /// Returns `true` if the variant list of this ADT is `#[non_exhaustive]`.
2234 pub fn is_variant_list_non_exhaustive(&self) -> bool {
2235 self.flags.contains(AdtFlags::IS_VARIANT_LIST_NON_EXHAUSTIVE)
2238 /// Returns the kind of the ADT.
2240 pub fn adt_kind(&self) -> AdtKind {
2243 } else if self.is_union() {
2250 /// Returns a description of this abstract data type.
2251 pub fn descr(&self) -> &'static str {
2252 match self.adt_kind() {
2253 AdtKind::Struct => "struct",
2254 AdtKind::Union => "union",
2255 AdtKind::Enum => "enum",
2259 /// Returns a description of a variant of this abstract data type.
2261 pub fn variant_descr(&self) -> &'static str {
2262 match self.adt_kind() {
2263 AdtKind::Struct => "struct",
2264 AdtKind::Union => "union",
2265 AdtKind::Enum => "variant",
2269 /// If this function returns `true`, it implies that `is_struct` must return `true`.
2271 pub fn has_ctor(&self) -> bool {
2272 self.flags.contains(AdtFlags::HAS_CTOR)
2275 /// Returns `true` if this type is `#[fundamental]` for the purposes
2276 /// of coherence checking.
2278 pub fn is_fundamental(&self) -> bool {
2279 self.flags.contains(AdtFlags::IS_FUNDAMENTAL)
2282 /// Returns `true` if this is `PhantomData<T>`.
2284 pub fn is_phantom_data(&self) -> bool {
2285 self.flags.contains(AdtFlags::IS_PHANTOM_DATA)
2288 /// Returns `true` if this is `Arc<T>`.
2289 pub fn is_arc(&self) -> bool {
2290 self.flags.contains(AdtFlags::IS_ARC)
2293 /// Returns `true` if this is `Rc<T>`.
2294 pub fn is_rc(&self) -> bool {
2295 self.flags.contains(AdtFlags::IS_RC)
2298 /// Returns `true` if this is Box<T>.
2300 pub fn is_box(&self) -> bool {
2301 self.flags.contains(AdtFlags::IS_BOX)
2304 /// Returns `true` if this type has a destructor.
2305 pub fn has_dtor(&self, tcx: TyCtxt<'tcx>) -> bool {
2306 self.destructor(tcx).is_some()
2309 /// Asserts this is a struct or union and returns its unique variant.
2310 pub fn non_enum_variant(&self) -> &VariantDef {
2311 assert!(self.is_struct() || self.is_union());
2312 &self.variants[VariantIdx::new(0)]
2316 pub fn predicates(&self, tcx: TyCtxt<'tcx>) -> &'tcx GenericPredicates<'tcx> {
2317 tcx.predicates_of(self.did)
2320 /// Returns an iterator over all fields contained
2323 pub fn all_fields(&self) -> impl Iterator<Item=&FieldDef> + Clone {
2324 self.variants.iter().flat_map(|v| v.fields.iter())
2327 pub fn is_payloadfree(&self) -> bool {
2328 !self.variants.is_empty() &&
2329 self.variants.iter().all(|v| v.fields.is_empty())
2332 /// Return a `VariantDef` given a variant id.
2333 pub fn variant_with_id(&self, vid: DefId) -> &VariantDef {
2334 self.variants.iter().find(|v| v.def_id == vid)
2335 .expect("variant_with_id: unknown variant")
2338 /// Return a `VariantDef` given a constructor id.
2339 pub fn variant_with_ctor_id(&self, cid: DefId) -> &VariantDef {
2340 self.variants.iter().find(|v| v.ctor_def_id == Some(cid))
2341 .expect("variant_with_ctor_id: unknown variant")
2344 /// Return the index of `VariantDef` given a variant id.
2345 pub fn variant_index_with_id(&self, vid: DefId) -> VariantIdx {
2346 self.variants.iter_enumerated().find(|(_, v)| v.def_id == vid)
2347 .expect("variant_index_with_id: unknown variant").0
2350 /// Return the index of `VariantDef` given a constructor id.
2351 pub fn variant_index_with_ctor_id(&self, cid: DefId) -> VariantIdx {
2352 self.variants.iter_enumerated().find(|(_, v)| v.ctor_def_id == Some(cid))
2353 .expect("variant_index_with_ctor_id: unknown variant").0
2356 pub fn variant_of_res(&self, res: Res) -> &VariantDef {
2358 Res::Def(DefKind::Variant, vid) => self.variant_with_id(vid),
2359 Res::Def(DefKind::Ctor(..), cid) => self.variant_with_ctor_id(cid),
2360 Res::Def(DefKind::Struct, _) | Res::Def(DefKind::Union, _) |
2361 Res::Def(DefKind::TyAlias, _) | Res::Def(DefKind::AssocTy, _) | Res::SelfTy(..) |
2362 Res::SelfCtor(..) => self.non_enum_variant(),
2363 _ => bug!("unexpected res {:?} in variant_of_res", res)
2368 pub fn eval_explicit_discr(&self, tcx: TyCtxt<'tcx>, expr_did: DefId) -> Option<Discr<'tcx>> {
2369 let param_env = tcx.param_env(expr_did);
2370 let repr_type = self.repr.discr_type();
2371 let substs = InternalSubsts::identity_for_item(tcx, expr_did);
2372 let instance = ty::Instance::new(expr_did, substs);
2373 let cid = GlobalId {
2377 match tcx.const_eval(param_env.and(cid)) {
2379 // FIXME: Find the right type and use it instead of `val.ty` here
2380 if let Some(b) = val.try_eval_bits(tcx, param_env, val.ty) {
2381 trace!("discriminants: {} ({:?})", b, repr_type);
2387 info!("invalid enum discriminant: {:#?}", val);
2388 crate::mir::interpret::struct_error(
2389 tcx.at(tcx.def_span(expr_did)),
2390 "constant evaluation of enum discriminant resulted in non-integer",
2395 Err(ErrorHandled::Reported) => {
2396 if !expr_did.is_local() {
2397 span_bug!(tcx.def_span(expr_did),
2398 "variant discriminant evaluation succeeded \
2399 in its crate but failed locally");
2403 Err(ErrorHandled::TooGeneric) => span_bug!(
2404 tcx.def_span(expr_did),
2405 "enum discriminant depends on generic arguments",
2411 pub fn discriminants(
2414 ) -> impl Iterator<Item = (VariantIdx, Discr<'tcx>)> + Captures<'tcx> {
2415 let repr_type = self.repr.discr_type();
2416 let initial = repr_type.initial_discriminant(tcx);
2417 let mut prev_discr = None::<Discr<'tcx>>;
2418 self.variants.iter_enumerated().map(move |(i, v)| {
2419 let mut discr = prev_discr.map_or(initial, |d| d.wrap_incr(tcx));
2420 if let VariantDiscr::Explicit(expr_did) = v.discr {
2421 if let Some(new_discr) = self.eval_explicit_discr(tcx, expr_did) {
2425 prev_discr = Some(discr);
2432 pub fn variant_range(&self) -> Range<VariantIdx> {
2433 (VariantIdx::new(0)..VariantIdx::new(self.variants.len()))
2436 /// Computes the discriminant value used by a specific variant.
2437 /// Unlike `discriminants`, this is (amortized) constant-time,
2438 /// only doing at most one query for evaluating an explicit
2439 /// discriminant (the last one before the requested variant),
2440 /// assuming there are no constant-evaluation errors there.
2442 pub fn discriminant_for_variant(
2445 variant_index: VariantIdx,
2447 let (val, offset) = self.discriminant_def_for_variant(variant_index);
2448 let explicit_value = val
2449 .and_then(|expr_did| self.eval_explicit_discr(tcx, expr_did))
2450 .unwrap_or_else(|| self.repr.discr_type().initial_discriminant(tcx));
2451 explicit_value.checked_add(tcx, offset as u128).0
2454 /// Yields a `DefId` for the discriminant and an offset to add to it
2455 /// Alternatively, if there is no explicit discriminant, returns the
2456 /// inferred discriminant directly.
2457 pub fn discriminant_def_for_variant(
2459 variant_index: VariantIdx,
2460 ) -> (Option<DefId>, u32) {
2461 let mut explicit_index = variant_index.as_u32();
2464 match self.variants[VariantIdx::from_u32(explicit_index)].discr {
2465 ty::VariantDiscr::Relative(0) => {
2469 ty::VariantDiscr::Relative(distance) => {
2470 explicit_index -= distance;
2472 ty::VariantDiscr::Explicit(did) => {
2473 expr_did = Some(did);
2478 (expr_did, variant_index.as_u32() - explicit_index)
2481 pub fn destructor(&self, tcx: TyCtxt<'tcx>) -> Option<Destructor> {
2482 tcx.adt_destructor(self.did)
2485 /// Returns a list of types such that `Self: Sized` if and only
2486 /// if that type is `Sized`, or `TyErr` if this type is recursive.
2488 /// Oddly enough, checking that the sized-constraint is `Sized` is
2489 /// actually more expressive than checking all members:
2490 /// the `Sized` trait is inductive, so an associated type that references
2491 /// `Self` would prevent its containing ADT from being `Sized`.
2493 /// Due to normalization being eager, this applies even if
2494 /// the associated type is behind a pointer (e.g., issue #31299).
2495 pub fn sized_constraint(&self, tcx: TyCtxt<'tcx>) -> &'tcx [Ty<'tcx>] {
2496 tcx.adt_sized_constraint(self.did).0
2499 fn sized_constraint_for_ty(&self, tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Vec<Ty<'tcx>> {
2500 let result = match ty.kind {
2501 Bool | Char | Int(..) | Uint(..) | Float(..) |
2502 RawPtr(..) | Ref(..) | FnDef(..) | FnPtr(_) |
2503 Array(..) | Closure(..) | Generator(..) | Never => {
2512 GeneratorWitness(..) => {
2513 // these are never sized - return the target type
2520 Some(ty) => self.sized_constraint_for_ty(tcx, ty.expect_ty()),
2524 Adt(adt, substs) => {
2526 let adt_tys = adt.sized_constraint(tcx);
2527 debug!("sized_constraint_for_ty({:?}) intermediate = {:?}",
2530 .map(|ty| ty.subst(tcx, substs))
2531 .flat_map(|ty| self.sized_constraint_for_ty(tcx, ty))
2535 Projection(..) | Opaque(..) => {
2536 // must calculate explicitly.
2537 // FIXME: consider special-casing always-Sized projections
2541 UnnormalizedProjection(..) => bug!("only used with chalk-engine"),
2544 // perf hack: if there is a `T: Sized` bound, then
2545 // we know that `T` is Sized and do not need to check
2548 let sized_trait = match tcx.lang_items().sized_trait() {
2550 _ => return vec![ty]
2552 let sized_predicate = Binder::dummy(TraitRef {
2553 def_id: sized_trait,
2554 substs: tcx.mk_substs_trait(ty, &[])
2556 let predicates = &tcx.predicates_of(self.did).predicates;
2557 if predicates.iter().any(|(p, _)| *p == sized_predicate) {
2567 bug!("unexpected type `{:?}` in sized_constraint_for_ty",
2571 debug!("sized_constraint_for_ty({:?}) = {:?}", ty, result);
2576 impl<'tcx> FieldDef {
2577 /// Returns the type of this field. The `subst` is typically obtained
2578 /// via the second field of `TyKind::AdtDef`.
2579 pub fn ty(&self, tcx: TyCtxt<'tcx>, subst: SubstsRef<'tcx>) -> Ty<'tcx> {
2580 tcx.type_of(self.did).subst(tcx, subst)
2584 /// Represents the various closure traits in the language. This
2585 /// will determine the type of the environment (`self`, in the
2586 /// desugaring) argument that the closure expects.
2588 /// You can get the environment type of a closure using
2589 /// `tcx.closure_env_ty()`.
2590 #[derive(Clone, Copy, PartialOrd, Ord, PartialEq, Eq, Hash, Debug,
2591 RustcEncodable, RustcDecodable, HashStable)]
2592 pub enum ClosureKind {
2593 // Warning: Ordering is significant here! The ordering is chosen
2594 // because the trait Fn is a subtrait of FnMut and so in turn, and
2595 // hence we order it so that Fn < FnMut < FnOnce.
2601 impl<'tcx> ClosureKind {
2602 // This is the initial value used when doing upvar inference.
2603 pub const LATTICE_BOTTOM: ClosureKind = ClosureKind::Fn;
2605 pub fn trait_did(&self, tcx: TyCtxt<'tcx>) -> DefId {
2607 ClosureKind::Fn => tcx.require_lang_item(FnTraitLangItem, None),
2608 ClosureKind::FnMut => {
2609 tcx.require_lang_item(FnMutTraitLangItem, None)
2611 ClosureKind::FnOnce => {
2612 tcx.require_lang_item(FnOnceTraitLangItem, None)
2617 /// Returns `true` if this a type that impls this closure kind
2618 /// must also implement `other`.
2619 pub fn extends(self, other: ty::ClosureKind) -> bool {
2620 match (self, other) {
2621 (ClosureKind::Fn, ClosureKind::Fn) => true,
2622 (ClosureKind::Fn, ClosureKind::FnMut) => true,
2623 (ClosureKind::Fn, ClosureKind::FnOnce) => true,
2624 (ClosureKind::FnMut, ClosureKind::FnMut) => true,
2625 (ClosureKind::FnMut, ClosureKind::FnOnce) => true,
2626 (ClosureKind::FnOnce, ClosureKind::FnOnce) => true,
2631 /// Returns the representative scalar type for this closure kind.
2632 /// See `TyS::to_opt_closure_kind` for more details.
2633 pub fn to_ty(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
2635 ty::ClosureKind::Fn => tcx.types.i8,
2636 ty::ClosureKind::FnMut => tcx.types.i16,
2637 ty::ClosureKind::FnOnce => tcx.types.i32,
2642 impl<'tcx> TyS<'tcx> {
2643 /// Iterator that walks `self` and any types reachable from
2644 /// `self`, in depth-first order. Note that just walks the types
2645 /// that appear in `self`, it does not descend into the fields of
2646 /// structs or variants. For example:
2649 /// isize => { isize }
2650 /// Foo<Bar<isize>> => { Foo<Bar<isize>>, Bar<isize>, isize }
2651 /// [isize] => { [isize], isize }
2653 pub fn walk(&'tcx self) -> TypeWalker<'tcx> {
2654 TypeWalker::new(self)
2657 /// Iterator that walks the immediate children of `self`. Hence
2658 /// `Foo<Bar<i32>, u32>` yields the sequence `[Bar<i32>, u32]`
2659 /// (but not `i32`, like `walk`).
2660 pub fn walk_shallow(&'tcx self) -> smallvec::IntoIter<walk::TypeWalkerArray<'tcx>> {
2661 walk::walk_shallow(self)
2664 /// Walks `ty` and any types appearing within `ty`, invoking the
2665 /// callback `f` on each type. If the callback returns `false`, then the
2666 /// children of the current type are ignored.
2668 /// Note: prefer `ty.walk()` where possible.
2669 pub fn maybe_walk<F>(&'tcx self, mut f: F)
2670 where F: FnMut(Ty<'tcx>) -> bool
2672 let mut walker = self.walk();
2673 while let Some(ty) = walker.next() {
2675 walker.skip_current_subtree();
2682 pub fn from_mutbl(m: hir::Mutability) -> BorrowKind {
2684 hir::MutMutable => MutBorrow,
2685 hir::MutImmutable => ImmBorrow,
2689 /// Returns a mutability `m` such that an `&m T` pointer could be used to obtain this borrow
2690 /// kind. Because borrow kinds are richer than mutabilities, we sometimes have to pick a
2691 /// mutability that is stronger than necessary so that it at least *would permit* the borrow in
2693 pub fn to_mutbl_lossy(self) -> hir::Mutability {
2695 MutBorrow => hir::MutMutable,
2696 ImmBorrow => hir::MutImmutable,
2698 // We have no type corresponding to a unique imm borrow, so
2699 // use `&mut`. It gives all the capabilities of an `&uniq`
2700 // and hence is a safe "over approximation".
2701 UniqueImmBorrow => hir::MutMutable,
2705 pub fn to_user_str(&self) -> &'static str {
2707 MutBorrow => "mutable",
2708 ImmBorrow => "immutable",
2709 UniqueImmBorrow => "uniquely immutable",
2714 #[derive(Debug, Clone)]
2715 pub enum Attributes<'tcx> {
2716 Owned(Lrc<[ast::Attribute]>),
2717 Borrowed(&'tcx [ast::Attribute]),
2720 impl<'tcx> ::std::ops::Deref for Attributes<'tcx> {
2721 type Target = [ast::Attribute];
2723 fn deref(&self) -> &[ast::Attribute] {
2725 &Attributes::Owned(ref data) => &data,
2726 &Attributes::Borrowed(data) => data
2731 #[derive(Debug, PartialEq, Eq)]
2732 pub enum ImplOverlapKind {
2733 /// These impls are always allowed to overlap.
2735 /// These impls are allowed to overlap, but that raises
2736 /// an issue #33140 future-compatibility warning.
2738 /// Some background: in Rust 1.0, the trait-object types `Send + Sync` (today's
2739 /// `dyn Send + Sync`) and `Sync + Send` (now `dyn Sync + Send`) were different.
2741 /// The widely-used version 0.1.0 of the crate `traitobject` had accidentally relied
2742 /// that difference, making what reduces to the following set of impls:
2746 /// impl Trait for dyn Send + Sync {}
2747 /// impl Trait for dyn Sync + Send {}
2750 /// Obviously, once we made these types be identical, that code causes a coherence
2751 /// error and a fairly big headache for us. However, luckily for us, the trait
2752 /// `Trait` used in this case is basically a marker trait, and therefore having
2753 /// overlapping impls for it is sound.
2755 /// To handle this, we basically regard the trait as a marker trait, with an additional
2756 /// future-compatibility warning. To avoid accidentally "stabilizing" this feature,
2757 /// it has the following restrictions:
2759 /// 1. The trait must indeed be a marker-like trait (i.e., no items), and must be
2761 /// 2. The trait-ref of both impls must be equal.
2762 /// 3. The trait-ref of both impls must be a trait object type consisting only of
2764 /// 4. Neither of the impls can have any where-clauses.
2766 /// Once `traitobject` 0.1.0 is no longer an active concern, this hack can be removed.
2770 impl<'tcx> TyCtxt<'tcx> {
2771 pub fn body_tables(self, body: hir::BodyId) -> &'tcx TypeckTables<'tcx> {
2772 self.typeck_tables_of(self.hir().body_owner_def_id(body))
2775 /// Returns an iterator of the `DefId`s for all body-owners in this
2776 /// crate. If you would prefer to iterate over the bodies
2777 /// themselves, you can do `self.hir().krate().body_ids.iter()`.
2778 pub fn body_owners(self) -> impl Iterator<Item = DefId> + Captures<'tcx> + 'tcx {
2782 .map(move |&body_id| self.hir().body_owner_def_id(body_id))
2785 pub fn par_body_owners<F: Fn(DefId) + sync::Sync + sync::Send>(self, f: F) {
2786 par_iter(&self.hir().krate().body_ids).for_each(|&body_id| {
2787 f(self.hir().body_owner_def_id(body_id))
2791 pub fn provided_trait_methods(self, id: DefId) -> Vec<AssocItem> {
2792 self.associated_items(id)
2793 .filter(|item| item.kind == AssocKind::Method && item.defaultness.has_value())
2797 pub fn trait_relevant_for_never(self, did: DefId) -> bool {
2798 self.associated_items(did).any(|item| {
2799 item.relevant_for_never()
2803 pub fn opt_item_name(self, def_id: DefId) -> Option<Ident> {
2804 self.hir().as_local_hir_id(def_id).and_then(|hir_id| self.hir().get(hir_id).ident())
2807 pub fn opt_associated_item(self, def_id: DefId) -> Option<AssocItem> {
2808 let is_associated_item = if let Some(hir_id) = self.hir().as_local_hir_id(def_id) {
2809 match self.hir().get(hir_id) {
2810 Node::TraitItem(_) | Node::ImplItem(_) => true,
2814 match self.def_kind(def_id).expect("no def for `DefId`") {
2817 | DefKind::AssocTy => true,
2822 if is_associated_item {
2823 Some(self.associated_item(def_id))
2829 fn associated_item_from_trait_item_ref(self,
2830 parent_def_id: DefId,
2831 parent_vis: &hir::Visibility,
2832 trait_item_ref: &hir::TraitItemRef)
2834 let def_id = self.hir().local_def_id(trait_item_ref.id.hir_id);
2835 let (kind, has_self) = match trait_item_ref.kind {
2836 hir::AssocItemKind::Const => (ty::AssocKind::Const, false),
2837 hir::AssocItemKind::Method { has_self } => {
2838 (ty::AssocKind::Method, has_self)
2840 hir::AssocItemKind::Type => (ty::AssocKind::Type, false),
2841 hir::AssocItemKind::OpaqueTy => bug!("only impls can have opaque types"),
2845 ident: trait_item_ref.ident,
2847 // Visibility of trait items is inherited from their traits.
2848 vis: Visibility::from_hir(parent_vis, trait_item_ref.id.hir_id, self),
2849 defaultness: trait_item_ref.defaultness,
2851 container: TraitContainer(parent_def_id),
2852 method_has_self_argument: has_self
2856 fn associated_item_from_impl_item_ref(self,
2857 parent_def_id: DefId,
2858 impl_item_ref: &hir::ImplItemRef)
2860 let def_id = self.hir().local_def_id(impl_item_ref.id.hir_id);
2861 let (kind, has_self) = match impl_item_ref.kind {
2862 hir::AssocItemKind::Const => (ty::AssocKind::Const, false),
2863 hir::AssocItemKind::Method { has_self } => {
2864 (ty::AssocKind::Method, has_self)
2866 hir::AssocItemKind::Type => (ty::AssocKind::Type, false),
2867 hir::AssocItemKind::OpaqueTy => (ty::AssocKind::OpaqueTy, false),
2871 ident: impl_item_ref.ident,
2873 // Visibility of trait impl items doesn't matter.
2874 vis: ty::Visibility::from_hir(&impl_item_ref.vis, impl_item_ref.id.hir_id, self),
2875 defaultness: impl_item_ref.defaultness,
2877 container: ImplContainer(parent_def_id),
2878 method_has_self_argument: has_self
2882 pub fn field_index(self, hir_id: hir::HirId, tables: &TypeckTables<'_>) -> usize {
2883 tables.field_indices().get(hir_id).cloned().expect("no index for a field")
2886 pub fn find_field_index(self, ident: Ident, variant: &VariantDef) -> Option<usize> {
2887 variant.fields.iter().position(|field| {
2888 self.hygienic_eq(ident, field.ident, variant.def_id)
2892 pub fn associated_items(self, def_id: DefId) -> AssocItemsIterator<'tcx> {
2893 // Ideally, we would use `-> impl Iterator` here, but it falls
2894 // afoul of the conservative "capture [restrictions]" we put
2895 // in place, so we use a hand-written iterator.
2897 // [restrictions]: https://github.com/rust-lang/rust/issues/34511#issuecomment-373423999
2898 AssocItemsIterator {
2900 def_ids: self.associated_item_def_ids(def_id),
2905 /// Returns `true` if the impls are the same polarity and the trait either
2906 /// has no items or is annotated #[marker] and prevents item overrides.
2907 pub fn impls_are_allowed_to_overlap(self, def_id1: DefId, def_id2: DefId)
2908 -> Option<ImplOverlapKind>
2910 // If either trait impl references an error, they're allowed to overlap,
2911 // as one of them essentially doesn't exist.
2912 if self.impl_trait_ref(def_id1).map_or(false, |tr| tr.references_error()) ||
2913 self.impl_trait_ref(def_id2).map_or(false, |tr| tr.references_error()) {
2914 return Some(ImplOverlapKind::Permitted);
2917 match (self.impl_polarity(def_id1), self.impl_polarity(def_id2)) {
2918 (ImplPolarity::Reservation, _) |
2919 (_, ImplPolarity::Reservation) => {
2920 // `#[rustc_reservation_impl]` impls don't overlap with anything
2921 debug!("impls_are_allowed_to_overlap({:?}, {:?}) = Some(Permitted) (reservations)",
2923 return Some(ImplOverlapKind::Permitted);
2925 (ImplPolarity::Positive, ImplPolarity::Negative) |
2926 (ImplPolarity::Negative, ImplPolarity::Positive) => {
2927 // `impl AutoTrait for Type` + `impl !AutoTrait for Type`
2928 debug!("impls_are_allowed_to_overlap({:?}, {:?}) - None (differing polarities)",
2932 (ImplPolarity::Positive, ImplPolarity::Positive) |
2933 (ImplPolarity::Negative, ImplPolarity::Negative) => {}
2936 let is_marker_overlap = if self.features().overlapping_marker_traits {
2937 let trait1_is_empty = self.impl_trait_ref(def_id1)
2938 .map_or(false, |trait_ref| {
2939 self.associated_item_def_ids(trait_ref.def_id).is_empty()
2941 let trait2_is_empty = self.impl_trait_ref(def_id2)
2942 .map_or(false, |trait_ref| {
2943 self.associated_item_def_ids(trait_ref.def_id).is_empty()
2945 trait1_is_empty && trait2_is_empty
2947 let is_marker_impl = |def_id: DefId| -> bool {
2948 let trait_ref = self.impl_trait_ref(def_id);
2949 trait_ref.map_or(false, |tr| self.trait_def(tr.def_id).is_marker)
2951 is_marker_impl(def_id1) && is_marker_impl(def_id2)
2955 if is_marker_overlap {
2956 debug!("impls_are_allowed_to_overlap({:?}, {:?}) = Some(Permitted) (marker overlap)",
2958 Some(ImplOverlapKind::Permitted)
2960 if let Some(self_ty1) = self.issue33140_self_ty(def_id1) {
2961 if let Some(self_ty2) = self.issue33140_self_ty(def_id2) {
2962 if self_ty1 == self_ty2 {
2963 debug!("impls_are_allowed_to_overlap({:?}, {:?}) - issue #33140 HACK",
2965 return Some(ImplOverlapKind::Issue33140);
2967 debug!("impls_are_allowed_to_overlap({:?}, {:?}) - found {:?} != {:?}",
2968 def_id1, def_id2, self_ty1, self_ty2);
2973 debug!("impls_are_allowed_to_overlap({:?}, {:?}) = None",
2979 /// Returns `ty::VariantDef` if `res` refers to a struct,
2980 /// or variant or their constructors, panics otherwise.
2981 pub fn expect_variant_res(self, res: Res) -> &'tcx VariantDef {
2983 Res::Def(DefKind::Variant, did) => {
2984 let enum_did = self.parent(did).unwrap();
2985 self.adt_def(enum_did).variant_with_id(did)
2987 Res::Def(DefKind::Struct, did) | Res::Def(DefKind::Union, did) => {
2988 self.adt_def(did).non_enum_variant()
2990 Res::Def(DefKind::Ctor(CtorOf::Variant, ..), variant_ctor_did) => {
2991 let variant_did = self.parent(variant_ctor_did).unwrap();
2992 let enum_did = self.parent(variant_did).unwrap();
2993 self.adt_def(enum_did).variant_with_ctor_id(variant_ctor_did)
2995 Res::Def(DefKind::Ctor(CtorOf::Struct, ..), ctor_did) => {
2996 let struct_did = self.parent(ctor_did).expect("struct ctor has no parent");
2997 self.adt_def(struct_did).non_enum_variant()
2999 _ => bug!("expect_variant_res used with unexpected res {:?}", res)
3003 pub fn item_name(self, id: DefId) -> Symbol {
3004 if id.index == CRATE_DEF_INDEX {
3005 self.original_crate_name(id.krate)
3007 let def_key = self.def_key(id);
3008 match def_key.disambiguated_data.data {
3009 // The name of a constructor is that of its parent.
3010 hir_map::DefPathData::Ctor =>
3011 self.item_name(DefId {
3013 index: def_key.parent.unwrap()
3015 _ => def_key.disambiguated_data.data.get_opt_name().unwrap_or_else(|| {
3016 bug!("item_name: no name for {:?}", self.def_path(id));
3022 /// Returns the possibly-auto-generated MIR of a `(DefId, Subst)` pair.
3023 pub fn instance_mir(self, instance: ty::InstanceDef<'tcx>) -> &'tcx Body<'tcx> {
3025 ty::InstanceDef::Item(did) => {
3026 self.optimized_mir(did)
3028 ty::InstanceDef::VtableShim(..) |
3029 ty::InstanceDef::ReifyShim(..) |
3030 ty::InstanceDef::Intrinsic(..) |
3031 ty::InstanceDef::FnPtrShim(..) |
3032 ty::InstanceDef::Virtual(..) |
3033 ty::InstanceDef::ClosureOnceShim { .. } |
3034 ty::InstanceDef::DropGlue(..) |
3035 ty::InstanceDef::CloneShim(..) => {
3036 self.mir_shims(instance)
3041 /// Gets the attributes of a definition.
3042 pub fn get_attrs(self, did: DefId) -> Attributes<'tcx> {
3043 if let Some(id) = self.hir().as_local_hir_id(did) {
3044 Attributes::Borrowed(self.hir().attrs(id))
3046 Attributes::Owned(self.item_attrs(did))
3050 /// Determines whether an item is annotated with an attribute.
3051 pub fn has_attr(self, did: DefId, attr: Symbol) -> bool {
3052 attr::contains_name(&self.get_attrs(did), attr)
3055 /// Returns `true` if this is an `auto trait`.
3056 pub fn trait_is_auto(self, trait_def_id: DefId) -> bool {
3057 self.trait_def(trait_def_id).has_auto_impl
3060 pub fn generator_layout(self, def_id: DefId) -> &'tcx GeneratorLayout<'tcx> {
3061 self.optimized_mir(def_id).generator_layout.as_ref().unwrap()
3064 /// Given the `DefId` of an impl, returns the `DefId` of the trait it implements.
3065 /// If it implements no trait, returns `None`.
3066 pub fn trait_id_of_impl(self, def_id: DefId) -> Option<DefId> {
3067 self.impl_trait_ref(def_id).map(|tr| tr.def_id)
3070 /// If the given defid describes a method belonging to an impl, returns the
3071 /// `DefId` of the impl that the method belongs to; otherwise, returns `None`.
3072 pub fn impl_of_method(self, def_id: DefId) -> Option<DefId> {
3073 let item = if def_id.krate != LOCAL_CRATE {
3074 if let Some(DefKind::Method) = self.def_kind(def_id) {
3075 Some(self.associated_item(def_id))
3080 self.opt_associated_item(def_id)
3083 item.and_then(|trait_item|
3084 match trait_item.container {
3085 TraitContainer(_) => None,
3086 ImplContainer(def_id) => Some(def_id),
3091 /// Looks up the span of `impl_did` if the impl is local; otherwise returns `Err`
3092 /// with the name of the crate containing the impl.
3093 pub fn span_of_impl(self, impl_did: DefId) -> Result<Span, Symbol> {
3094 if impl_did.is_local() {
3095 let hir_id = self.hir().as_local_hir_id(impl_did).unwrap();
3096 Ok(self.hir().span(hir_id))
3098 Err(self.crate_name(impl_did.krate))
3102 /// Hygienically compares a use-site name (`use_name`) for a field or an associated item with
3103 /// its supposed definition name (`def_name`). The method also needs `DefId` of the supposed
3104 /// definition's parent/scope to perform comparison.
3105 pub fn hygienic_eq(self, use_name: Ident, def_name: Ident, def_parent_def_id: DefId) -> bool {
3106 // We could use `Ident::eq` here, but we deliberately don't. The name
3107 // comparison fails frequently, and we want to avoid the expensive
3108 // `modern()` calls required for the span comparison whenever possible.
3109 use_name.name == def_name.name &&
3110 use_name.span.ctxt().hygienic_eq(def_name.span.ctxt(),
3111 self.expansion_that_defined(def_parent_def_id))
3114 fn expansion_that_defined(self, scope: DefId) -> ExpnId {
3116 LOCAL_CRATE => self.hir().definitions().expansion_that_defined(scope.index),
3117 _ => ExpnId::root(),
3121 pub fn adjust_ident(self, mut ident: Ident, scope: DefId) -> Ident {
3122 ident.span.modernize_and_adjust(self.expansion_that_defined(scope));
3126 pub fn adjust_ident_and_get_scope(self, mut ident: Ident, scope: DefId, block: hir::HirId)
3128 let scope = match ident.span.modernize_and_adjust(self.expansion_that_defined(scope)) {
3129 Some(actual_expansion) =>
3130 self.hir().definitions().parent_module_of_macro_def(actual_expansion),
3131 None => self.hir().get_module_parent(block),
3137 pub struct AssocItemsIterator<'tcx> {
3139 def_ids: &'tcx [DefId],
3143 impl Iterator for AssocItemsIterator<'_> {
3144 type Item = AssocItem;
3146 fn next(&mut self) -> Option<AssocItem> {
3147 let def_id = self.def_ids.get(self.next_index)?;
3148 self.next_index += 1;
3149 Some(self.tcx.associated_item(*def_id))
3153 fn associated_item(tcx: TyCtxt<'_>, def_id: DefId) -> AssocItem {
3154 let id = tcx.hir().as_local_hir_id(def_id).unwrap();
3155 let parent_id = tcx.hir().get_parent_item(id);
3156 let parent_def_id = tcx.hir().local_def_id(parent_id);
3157 let parent_item = tcx.hir().expect_item(parent_id);
3158 match parent_item.kind {
3159 hir::ItemKind::Impl(.., ref impl_item_refs) => {
3160 if let Some(impl_item_ref) = impl_item_refs.iter().find(|i| i.id.hir_id == id) {
3161 let assoc_item = tcx.associated_item_from_impl_item_ref(parent_def_id,
3163 debug_assert_eq!(assoc_item.def_id, def_id);
3168 hir::ItemKind::Trait(.., ref trait_item_refs) => {
3169 if let Some(trait_item_ref) = trait_item_refs.iter().find(|i| i.id.hir_id == id) {
3170 let assoc_item = tcx.associated_item_from_trait_item_ref(parent_def_id,
3173 debug_assert_eq!(assoc_item.def_id, def_id);
3181 span_bug!(parent_item.span,
3182 "unexpected parent of trait or impl item or item not found: {:?}",
3186 #[derive(Clone, HashStable)]
3187 pub struct AdtSizedConstraint<'tcx>(pub &'tcx [Ty<'tcx>]);
3189 /// Calculates the `Sized` constraint.
3191 /// In fact, there are only a few options for the types in the constraint:
3192 /// - an obviously-unsized type
3193 /// - a type parameter or projection whose Sizedness can't be known
3194 /// - a tuple of type parameters or projections, if there are multiple
3196 /// - a Error, if a type contained itself. The representability
3197 /// check should catch this case.
3198 fn adt_sized_constraint(tcx: TyCtxt<'_>, def_id: DefId) -> AdtSizedConstraint<'_> {
3199 let def = tcx.adt_def(def_id);
3201 let result = tcx.mk_type_list(def.variants.iter().flat_map(|v| {
3204 def.sized_constraint_for_ty(tcx, tcx.type_of(f.did))
3207 debug!("adt_sized_constraint: {:?} => {:?}", def, result);
3209 AdtSizedConstraint(result)
3212 fn associated_item_def_ids(tcx: TyCtxt<'_>, def_id: DefId) -> &[DefId] {
3213 let id = tcx.hir().as_local_hir_id(def_id).unwrap();
3214 let item = tcx.hir().expect_item(id);
3216 hir::ItemKind::Trait(.., ref trait_item_refs) => {
3217 tcx.arena.alloc_from_iter(
3218 trait_item_refs.iter()
3219 .map(|trait_item_ref| trait_item_ref.id)
3220 .map(|id| tcx.hir().local_def_id(id.hir_id))
3223 hir::ItemKind::Impl(.., ref impl_item_refs) => {
3224 tcx.arena.alloc_from_iter(
3225 impl_item_refs.iter()
3226 .map(|impl_item_ref| impl_item_ref.id)
3227 .map(|id| tcx.hir().local_def_id(id.hir_id))
3230 hir::ItemKind::TraitAlias(..) => &[],
3231 _ => span_bug!(item.span, "associated_item_def_ids: not impl or trait")
3235 fn def_span(tcx: TyCtxt<'_>, def_id: DefId) -> Span {
3236 tcx.hir().span_if_local(def_id).unwrap()
3239 /// If the given `DefId` describes an item belonging to a trait,
3240 /// returns the `DefId` of the trait that the trait item belongs to;
3241 /// otherwise, returns `None`.
3242 fn trait_of_item(tcx: TyCtxt<'_>, def_id: DefId) -> Option<DefId> {
3243 tcx.opt_associated_item(def_id)
3244 .and_then(|associated_item| {
3245 match associated_item.container {
3246 TraitContainer(def_id) => Some(def_id),
3247 ImplContainer(_) => None
3252 /// Yields the parent function's `DefId` if `def_id` is an `impl Trait` definition.
3253 pub fn is_impl_trait_defn(tcx: TyCtxt<'_>, def_id: DefId) -> Option<DefId> {
3254 if let Some(hir_id) = tcx.hir().as_local_hir_id(def_id) {
3255 if let Node::Item(item) = tcx.hir().get(hir_id) {
3256 if let hir::ItemKind::OpaqueTy(ref opaque_ty) = item.kind {
3257 return opaque_ty.impl_trait_fn;
3264 /// See `ParamEnv` struct definition for details.
3265 fn param_env(tcx: TyCtxt<'_>, def_id: DefId) -> ParamEnv<'_> {
3266 // The param_env of an impl Trait type is its defining function's param_env
3267 if let Some(parent) = is_impl_trait_defn(tcx, def_id) {
3268 return param_env(tcx, parent);
3270 // Compute the bounds on Self and the type parameters.
3272 let InstantiatedPredicates { predicates } =
3273 tcx.predicates_of(def_id).instantiate_identity(tcx);
3275 // Finally, we have to normalize the bounds in the environment, in
3276 // case they contain any associated type projections. This process
3277 // can yield errors if the put in illegal associated types, like
3278 // `<i32 as Foo>::Bar` where `i32` does not implement `Foo`. We
3279 // report these errors right here; this doesn't actually feel
3280 // right to me, because constructing the environment feels like a
3281 // kind of a "idempotent" action, but I'm not sure where would be
3282 // a better place. In practice, we construct environments for
3283 // every fn once during type checking, and we'll abort if there
3284 // are any errors at that point, so after type checking you can be
3285 // sure that this will succeed without errors anyway.
3287 let unnormalized_env = ty::ParamEnv::new(
3288 tcx.intern_predicates(&predicates),
3289 traits::Reveal::UserFacing,
3290 if tcx.sess.opts.debugging_opts.chalk { Some(def_id) } else { None }
3293 let body_id = tcx.hir().as_local_hir_id(def_id).map_or(hir::DUMMY_HIR_ID, |id| {
3294 tcx.hir().maybe_body_owned_by(id).map_or(id, |body| body.hir_id)
3296 let cause = traits::ObligationCause::misc(tcx.def_span(def_id), body_id);
3297 traits::normalize_param_env_or_error(tcx, def_id, unnormalized_env, cause)
3300 fn crate_disambiguator(tcx: TyCtxt<'_>, crate_num: CrateNum) -> CrateDisambiguator {
3301 assert_eq!(crate_num, LOCAL_CRATE);
3302 tcx.sess.local_crate_disambiguator()
3305 fn original_crate_name(tcx: TyCtxt<'_>, crate_num: CrateNum) -> Symbol {
3306 assert_eq!(crate_num, LOCAL_CRATE);
3307 tcx.crate_name.clone()
3310 fn crate_hash(tcx: TyCtxt<'_>, crate_num: CrateNum) -> Svh {
3311 assert_eq!(crate_num, LOCAL_CRATE);
3312 tcx.hir().crate_hash
3315 fn instance_def_size_estimate<'tcx>(tcx: TyCtxt<'tcx>, instance_def: InstanceDef<'tcx>) -> usize {
3316 match instance_def {
3317 InstanceDef::Item(..) |
3318 InstanceDef::DropGlue(..) => {
3319 let mir = tcx.instance_mir(instance_def);
3320 mir.basic_blocks().iter().map(|bb| bb.statements.len()).sum()
3322 // Estimate the size of other compiler-generated shims to be 1.
3327 /// If `def_id` is an issue 33140 hack impl, returns its self type; otherwise, returns `None`.
3329 /// See [`ImplOverlapKind::Issue33140`] for more details.
3330 fn issue33140_self_ty(tcx: TyCtxt<'_>, def_id: DefId) -> Option<Ty<'_>> {
3331 debug!("issue33140_self_ty({:?})", def_id);
3333 let trait_ref = tcx.impl_trait_ref(def_id).unwrap_or_else(|| {
3334 bug!("issue33140_self_ty called on inherent impl {:?}", def_id)
3337 debug!("issue33140_self_ty({:?}), trait-ref={:?}", def_id, trait_ref);
3339 let is_marker_like =
3340 tcx.impl_polarity(def_id) == ty::ImplPolarity::Positive &&
3341 tcx.associated_item_def_ids(trait_ref.def_id).is_empty();
3343 // Check whether these impls would be ok for a marker trait.
3344 if !is_marker_like {
3345 debug!("issue33140_self_ty - not marker-like!");
3349 // impl must be `impl Trait for dyn Marker1 + Marker2 + ...`
3350 if trait_ref.substs.len() != 1 {
3351 debug!("issue33140_self_ty - impl has substs!");
3355 let predicates = tcx.predicates_of(def_id);
3356 if predicates.parent.is_some() || !predicates.predicates.is_empty() {
3357 debug!("issue33140_self_ty - impl has predicates {:?}!", predicates);
3361 let self_ty = trait_ref.self_ty();
3362 let self_ty_matches = match self_ty.kind {
3363 ty::Dynamic(ref data, ty::ReStatic) => data.principal().is_none(),
3367 if self_ty_matches {
3368 debug!("issue33140_self_ty - MATCHES!");
3371 debug!("issue33140_self_ty - non-matching self type");
3376 /// Check if a function is async.
3377 fn asyncness(tcx: TyCtxt<'_>, def_id: DefId) -> hir::IsAsync {
3378 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap_or_else(|| {
3379 bug!("asyncness: expected local `DefId`, got `{:?}`", def_id)
3382 let node = tcx.hir().get(hir_id);
3384 let fn_like = hir::map::blocks::FnLikeNode::from_node(node).unwrap_or_else(|| {
3385 bug!("asyncness: expected fn-like node but got `{:?}`", def_id);
3392 pub fn provide(providers: &mut ty::query::Providers<'_>) {
3393 context::provide(providers);
3394 erase_regions::provide(providers);
3395 layout::provide(providers);
3396 util::provide(providers);
3397 constness::provide(providers);
3398 *providers = ty::query::Providers {
3401 associated_item_def_ids,
3402 adt_sized_constraint,
3406 crate_disambiguator,
3407 original_crate_name,
3409 trait_impls_of: trait_def::trait_impls_of_provider,
3410 instance_def_size_estimate,
3416 /// A map for the local crate mapping each type to a vector of its
3417 /// inherent impls. This is not meant to be used outside of coherence;
3418 /// rather, you should request the vector for a specific type via
3419 /// `tcx.inherent_impls(def_id)` so as to minimize your dependencies
3420 /// (constructing this map requires touching the entire crate).
3421 #[derive(Clone, Debug, Default, HashStable)]
3422 pub struct CrateInherentImpls {
3423 pub inherent_impls: DefIdMap<Vec<DefId>>,
3426 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable)]
3427 pub struct SymbolName {
3428 // FIXME: we don't rely on interning or equality here - better have
3429 // this be a `&'tcx str`.
3430 pub name: InternedString
3433 impl_stable_hash_for!(struct self::SymbolName {
3438 pub fn new(name: &str) -> SymbolName {
3440 name: InternedString::intern(name)
3445 impl fmt::Display for SymbolName {
3446 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
3447 fmt::Display::fmt(&self.name, fmt)
3451 impl fmt::Debug for SymbolName {
3452 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
3453 fmt::Display::fmt(&self.name, fmt)