1 // ignore-tidy-filelength
3 pub use self::fold::{TypeFoldable, TypeVisitor};
4 pub use self::AssocItemContainer::*;
5 pub use self::BorrowKind::*;
6 pub use self::IntVarValue::*;
7 pub use self::Variance::*;
9 use crate::hir::exports::ExportMap;
10 use crate::hir::map as hir_map;
12 use crate::ich::Fingerprint;
13 use crate::ich::StableHashingContext;
14 use crate::infer::canonical::Canonical;
15 use crate::middle::cstore::CrateStoreDyn;
16 use crate::middle::lang_items::{FnMutTraitLangItem, FnOnceTraitLangItem, FnTraitLangItem};
17 use crate::middle::resolve_lifetime::ObjectLifetimeDefault;
18 use crate::mir::interpret::ErrorHandled;
19 use crate::mir::GeneratorLayout;
20 use crate::mir::ReadOnlyBodyAndCache;
21 use crate::session::DataTypeKind;
22 use crate::traits::{self, Reveal};
24 use crate::ty::layout::VariantIdx;
25 use crate::ty::subst::{InternalSubsts, Subst, SubstsRef};
26 use crate::ty::util::{Discr, IntTypeExt};
27 use crate::ty::walk::TypeWalker;
28 use arena::SyncDroplessArena;
29 use rustc_data_structures::captures::Captures;
30 use rustc_data_structures::fx::FxHashMap;
31 use rustc_data_structures::fx::FxIndexMap;
32 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
33 use rustc_data_structures::sync::{self, par_iter, Lrc, ParallelIterator};
35 use rustc_hir::def::{CtorKind, CtorOf, DefKind, Res};
36 use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, LocalDefId, CRATE_DEF_INDEX, LOCAL_CRATE};
37 use rustc_hir::{GlobMap, Node, TraitMap};
38 use rustc_index::vec::{Idx, IndexVec};
39 use rustc_macros::HashStable;
40 use rustc_serialize::{self, Encodable, Encoder};
41 use rustc_session::node_id::{NodeMap, NodeSet};
42 use rustc_span::hygiene::ExpnId;
43 use rustc_span::symbol::{kw, sym, Symbol};
45 use rustc_target::abi::Align;
47 use std::cell::RefCell;
48 use std::cmp::{self, Ordering};
50 use std::hash::{Hash, Hasher};
55 use syntax::ast::{self, Ident, Name, NodeId};
58 pub use self::sty::BoundRegion::*;
59 pub use self::sty::InferTy::*;
60 pub use self::sty::RegionKind;
61 pub use self::sty::RegionKind::*;
62 pub use self::sty::TyKind::*;
63 pub use self::sty::{Binder, BoundTy, BoundTyKind, BoundVar, DebruijnIndex, INNERMOST};
64 pub use self::sty::{BoundRegion, EarlyBoundRegion, FreeRegion, Region};
65 pub use self::sty::{CanonicalPolyFnSig, FnSig, GenSig, PolyFnSig, PolyGenSig};
66 pub use self::sty::{ClosureSubsts, GeneratorSubsts, TypeAndMut, UpvarSubsts};
67 pub use self::sty::{Const, ConstKind, ExistentialProjection, PolyExistentialProjection};
68 pub use self::sty::{ConstVid, FloatVid, IntVid, RegionVid, TyVid};
69 pub use self::sty::{ExistentialPredicate, InferConst, InferTy, ParamConst, ParamTy, ProjectionTy};
70 pub use self::sty::{ExistentialTraitRef, PolyExistentialTraitRef};
71 pub use self::sty::{PolyTraitRef, TraitRef, TyKind};
72 pub use crate::ty::diagnostics::*;
74 pub use self::binding::BindingMode;
75 pub use self::binding::BindingMode::*;
77 pub use self::context::{keep_local, tls, AllArenas, FreeRegionInfo, TyCtxt};
78 pub use self::context::{
79 CanonicalUserType, CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations, ResolvedOpaqueTy,
80 UserType, UserTypeAnnotationIndex,
82 pub use self::context::{
83 CtxtInterners, GeneratorInteriorTypeCause, GlobalCtxt, Lift, TypeckTables,
86 pub use self::instance::{Instance, InstanceDef};
88 pub use self::trait_def::TraitDef;
90 pub use self::query::queries;
103 pub mod free_region_map;
104 pub mod inhabitedness;
106 pub mod normalize_erasing_regions;
120 mod structural_impls;
125 pub struct ResolverOutputs {
126 pub definitions: hir_map::Definitions,
127 pub cstore: Box<CrateStoreDyn>,
128 pub extern_crate_map: NodeMap<CrateNum>,
129 pub trait_map: TraitMap,
130 pub maybe_unused_trait_imports: NodeSet,
131 pub maybe_unused_extern_crates: Vec<(NodeId, Span)>,
132 pub export_map: ExportMap<NodeId>,
133 pub glob_map: GlobMap,
134 /// Extern prelude entries. The value is `true` if the entry was introduced
135 /// via `extern crate` item and not `--extern` option or compiler built-in.
136 pub extern_prelude: FxHashMap<Name, bool>,
139 #[derive(Clone, Copy, PartialEq, Eq, Debug, HashStable)]
140 pub enum AssocItemContainer {
141 TraitContainer(DefId),
142 ImplContainer(DefId),
145 impl AssocItemContainer {
146 /// Asserts that this is the `DefId` of an associated item declared
147 /// in a trait, and returns the trait `DefId`.
148 pub fn assert_trait(&self) -> DefId {
150 TraitContainer(id) => id,
151 _ => bug!("associated item has wrong container type: {:?}", self),
155 pub fn id(&self) -> DefId {
157 TraitContainer(id) => id,
158 ImplContainer(id) => id,
163 /// The "header" of an impl is everything outside the body: a Self type, a trait
164 /// ref (in the case of a trait impl), and a set of predicates (from the
165 /// bounds / where-clauses).
166 #[derive(Clone, Debug, TypeFoldable)]
167 pub struct ImplHeader<'tcx> {
168 pub impl_def_id: DefId,
169 pub self_ty: Ty<'tcx>,
170 pub trait_ref: Option<TraitRef<'tcx>>,
171 pub predicates: Vec<Predicate<'tcx>>,
174 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable)]
175 pub enum ImplPolarity {
176 /// `impl Trait for Type`
178 /// `impl !Trait for Type`
180 /// `#[rustc_reservation_impl] impl Trait for Type`
182 /// This is a "stability hack", not a real Rust feature.
183 /// See #64631 for details.
187 #[derive(Copy, Clone, Debug, PartialEq, HashStable)]
188 pub struct AssocItem {
190 #[stable_hasher(project(name))]
194 pub defaultness: hir::Defaultness,
195 pub container: AssocItemContainer,
197 /// Whether this is a method with an explicit self
198 /// as its first argument, allowing method calls.
199 pub method_has_self_argument: bool,
202 #[derive(Copy, Clone, PartialEq, Debug, HashStable)]
211 pub fn suggestion_descr(&self) -> &'static str {
213 ty::AssocKind::Method => "method call",
214 ty::AssocKind::Type | ty::AssocKind::OpaqueTy => "associated type",
215 ty::AssocKind::Const => "associated constant",
221 pub fn def_kind(&self) -> DefKind {
223 AssocKind::Const => DefKind::AssocConst,
224 AssocKind::Method => DefKind::Method,
225 AssocKind::Type => DefKind::AssocTy,
226 AssocKind::OpaqueTy => DefKind::AssocOpaqueTy,
230 /// Tests whether the associated item admits a non-trivial implementation
232 pub fn relevant_for_never(&self) -> bool {
234 AssocKind::OpaqueTy | AssocKind::Const | AssocKind::Type => true,
235 // FIXME(canndrew): Be more thorough here, check if any argument is uninhabited.
236 AssocKind::Method => !self.method_has_self_argument,
240 pub fn signature(&self, tcx: TyCtxt<'_>) -> String {
242 ty::AssocKind::Method => {
243 // We skip the binder here because the binder would deanonymize all
244 // late-bound regions, and we don't want method signatures to show up
245 // `as for<'r> fn(&'r MyType)`. Pretty-printing handles late-bound
246 // regions just fine, showing `fn(&MyType)`.
247 tcx.fn_sig(self.def_id).skip_binder().to_string()
249 ty::AssocKind::Type => format!("type {};", self.ident),
250 // FIXME(type_alias_impl_trait): we should print bounds here too.
251 ty::AssocKind::OpaqueTy => format!("type {};", self.ident),
252 ty::AssocKind::Const => {
253 format!("const {}: {:?};", self.ident, tcx.type_of(self.def_id))
259 #[derive(Clone, Debug, PartialEq, Eq, Copy, RustcEncodable, RustcDecodable, HashStable)]
260 pub enum Visibility {
261 /// Visible everywhere (including in other crates).
263 /// Visible only in the given crate-local module.
265 /// Not visible anywhere in the local crate. This is the visibility of private external items.
269 pub trait DefIdTree: Copy {
270 fn parent(self, id: DefId) -> Option<DefId>;
272 fn is_descendant_of(self, mut descendant: DefId, ancestor: DefId) -> bool {
273 if descendant.krate != ancestor.krate {
277 while descendant != ancestor {
278 match self.parent(descendant) {
279 Some(parent) => descendant = parent,
280 None => return false,
287 impl<'tcx> DefIdTree for TyCtxt<'tcx> {
288 fn parent(self, id: DefId) -> Option<DefId> {
289 self.def_key(id).parent.map(|index| DefId { index: index, ..id })
294 pub fn from_hir(visibility: &hir::Visibility<'_>, id: hir::HirId, tcx: TyCtxt<'_>) -> Self {
295 match visibility.node {
296 hir::VisibilityKind::Public => Visibility::Public,
297 hir::VisibilityKind::Crate(_) => Visibility::Restricted(DefId::local(CRATE_DEF_INDEX)),
298 hir::VisibilityKind::Restricted { ref path, .. } => match path.res {
299 // If there is no resolution, `resolve` will have already reported an error, so
300 // assume that the visibility is public to avoid reporting more privacy errors.
301 Res::Err => Visibility::Public,
302 def => Visibility::Restricted(def.def_id()),
304 hir::VisibilityKind::Inherited => {
305 Visibility::Restricted(tcx.hir().get_module_parent(id))
310 /// Returns `true` if an item with this visibility is accessible from the given block.
311 pub fn is_accessible_from<T: DefIdTree>(self, module: DefId, tree: T) -> bool {
312 let restriction = match self {
313 // Public items are visible everywhere.
314 Visibility::Public => return true,
315 // Private items from other crates are visible nowhere.
316 Visibility::Invisible => return false,
317 // Restricted items are visible in an arbitrary local module.
318 Visibility::Restricted(other) if other.krate != module.krate => return false,
319 Visibility::Restricted(module) => module,
322 tree.is_descendant_of(module, restriction)
325 /// Returns `true` if this visibility is at least as accessible as the given visibility
326 pub fn is_at_least<T: DefIdTree>(self, vis: Visibility, tree: T) -> bool {
327 let vis_restriction = match vis {
328 Visibility::Public => return self == Visibility::Public,
329 Visibility::Invisible => return true,
330 Visibility::Restricted(module) => module,
333 self.is_accessible_from(vis_restriction, tree)
336 // Returns `true` if this item is visible anywhere in the local crate.
337 pub fn is_visible_locally(self) -> bool {
339 Visibility::Public => true,
340 Visibility::Restricted(def_id) => def_id.is_local(),
341 Visibility::Invisible => false,
346 #[derive(Copy, Clone, PartialEq, RustcDecodable, RustcEncodable, HashStable)]
348 Covariant, // T<A> <: T<B> iff A <: B -- e.g., function return type
349 Invariant, // T<A> <: T<B> iff B == A -- e.g., type of mutable cell
350 Contravariant, // T<A> <: T<B> iff B <: A -- e.g., function param type
351 Bivariant, // T<A> <: T<B> -- e.g., unused type parameter
354 /// The crate variances map is computed during typeck and contains the
355 /// variance of every item in the local crate. You should not use it
356 /// directly, because to do so will make your pass dependent on the
357 /// HIR of every item in the local crate. Instead, use
358 /// `tcx.variances_of()` to get the variance for a *particular*
360 #[derive(HashStable)]
361 pub struct CrateVariancesMap<'tcx> {
362 /// For each item with generics, maps to a vector of the variance
363 /// of its generics. If an item has no generics, it will have no
365 pub variances: FxHashMap<DefId, &'tcx [ty::Variance]>,
369 /// `a.xform(b)` combines the variance of a context with the
370 /// variance of a type with the following meaning. If we are in a
371 /// context with variance `a`, and we encounter a type argument in
372 /// a position with variance `b`, then `a.xform(b)` is the new
373 /// variance with which the argument appears.
379 /// Here, the "ambient" variance starts as covariant. `*mut T` is
380 /// invariant with respect to `T`, so the variance in which the
381 /// `Vec<i32>` appears is `Covariant.xform(Invariant)`, which
382 /// yields `Invariant`. Now, the type `Vec<T>` is covariant with
383 /// respect to its type argument `T`, and hence the variance of
384 /// the `i32` here is `Invariant.xform(Covariant)`, which results
385 /// (again) in `Invariant`.
389 /// fn(*const Vec<i32>, *mut Vec<i32)
391 /// The ambient variance is covariant. A `fn` type is
392 /// contravariant with respect to its parameters, so the variance
393 /// within which both pointer types appear is
394 /// `Covariant.xform(Contravariant)`, or `Contravariant`. `*const
395 /// T` is covariant with respect to `T`, so the variance within
396 /// which the first `Vec<i32>` appears is
397 /// `Contravariant.xform(Covariant)` or `Contravariant`. The same
398 /// is true for its `i32` argument. In the `*mut T` case, the
399 /// variance of `Vec<i32>` is `Contravariant.xform(Invariant)`,
400 /// and hence the outermost type is `Invariant` with respect to
401 /// `Vec<i32>` (and its `i32` argument).
403 /// Source: Figure 1 of "Taming the Wildcards:
404 /// Combining Definition- and Use-Site Variance" published in PLDI'11.
405 pub fn xform(self, v: ty::Variance) -> ty::Variance {
407 // Figure 1, column 1.
408 (ty::Covariant, ty::Covariant) => ty::Covariant,
409 (ty::Covariant, ty::Contravariant) => ty::Contravariant,
410 (ty::Covariant, ty::Invariant) => ty::Invariant,
411 (ty::Covariant, ty::Bivariant) => ty::Bivariant,
413 // Figure 1, column 2.
414 (ty::Contravariant, ty::Covariant) => ty::Contravariant,
415 (ty::Contravariant, ty::Contravariant) => ty::Covariant,
416 (ty::Contravariant, ty::Invariant) => ty::Invariant,
417 (ty::Contravariant, ty::Bivariant) => ty::Bivariant,
419 // Figure 1, column 3.
420 (ty::Invariant, _) => ty::Invariant,
422 // Figure 1, column 4.
423 (ty::Bivariant, _) => ty::Bivariant,
428 // Contains information needed to resolve types and (in the future) look up
429 // the types of AST nodes.
430 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
431 pub struct CReaderCacheKey {
436 // Flags that we track on types. These flags are propagated upwards
437 // through the type during type construction, so that we can quickly
438 // check whether the type has various kinds of types in it without
439 // recursing over the type itself.
441 pub struct TypeFlags: u32 {
442 const HAS_PARAMS = 1 << 0;
443 const HAS_TY_INFER = 1 << 1;
444 const HAS_RE_INFER = 1 << 2;
445 const HAS_RE_PLACEHOLDER = 1 << 3;
447 /// Does this have any `ReEarlyBound` regions? Used to
448 /// determine whether substitition is required, since those
449 /// represent regions that are bound in a `ty::Generics` and
450 /// hence may be substituted.
451 const HAS_RE_EARLY_BOUND = 1 << 4;
453 /// Does this have any region that "appears free" in the type?
454 /// Basically anything but `ReLateBound` and `ReErased`.
455 const HAS_FREE_REGIONS = 1 << 5;
457 /// Is an error type reachable?
458 const HAS_TY_ERR = 1 << 6;
459 const HAS_PROJECTION = 1 << 7;
461 // FIXME: Rename this to the actual property since it's used for generators too
462 const HAS_TY_CLOSURE = 1 << 8;
464 /// `true` if there are "names" of types and regions and so forth
465 /// that are local to a particular fn
466 const HAS_FREE_LOCAL_NAMES = 1 << 9;
468 /// Present if the type belongs in a local type context.
469 /// Only set for Infer other than Fresh.
470 const KEEP_IN_LOCAL_TCX = 1 << 10;
472 /// Does this have any `ReLateBound` regions? Used to check
473 /// if a global bound is safe to evaluate.
474 const HAS_RE_LATE_BOUND = 1 << 11;
476 const HAS_TY_PLACEHOLDER = 1 << 12;
478 const HAS_CT_INFER = 1 << 13;
479 const HAS_CT_PLACEHOLDER = 1 << 14;
481 const NEEDS_SUBST = TypeFlags::HAS_PARAMS.bits |
482 TypeFlags::HAS_RE_EARLY_BOUND.bits;
484 /// Flags representing the nominal content of a type,
485 /// computed by FlagsComputation. If you add a new nominal
486 /// flag, it should be added here too.
487 const NOMINAL_FLAGS = TypeFlags::HAS_PARAMS.bits |
488 TypeFlags::HAS_TY_INFER.bits |
489 TypeFlags::HAS_RE_INFER.bits |
490 TypeFlags::HAS_RE_PLACEHOLDER.bits |
491 TypeFlags::HAS_RE_EARLY_BOUND.bits |
492 TypeFlags::HAS_FREE_REGIONS.bits |
493 TypeFlags::HAS_TY_ERR.bits |
494 TypeFlags::HAS_PROJECTION.bits |
495 TypeFlags::HAS_TY_CLOSURE.bits |
496 TypeFlags::HAS_FREE_LOCAL_NAMES.bits |
497 TypeFlags::KEEP_IN_LOCAL_TCX.bits |
498 TypeFlags::HAS_RE_LATE_BOUND.bits |
499 TypeFlags::HAS_TY_PLACEHOLDER.bits |
500 TypeFlags::HAS_CT_INFER.bits |
501 TypeFlags::HAS_CT_PLACEHOLDER.bits;
505 #[allow(rustc::usage_of_ty_tykind)]
506 pub struct TyS<'tcx> {
507 pub kind: TyKind<'tcx>,
508 pub flags: TypeFlags,
510 /// This is a kind of confusing thing: it stores the smallest
513 /// (a) the binder itself captures nothing but
514 /// (b) all the late-bound things within the type are captured
515 /// by some sub-binder.
517 /// So, for a type without any late-bound things, like `u32`, this
518 /// will be *innermost*, because that is the innermost binder that
519 /// captures nothing. But for a type `&'D u32`, where `'D` is a
520 /// late-bound region with De Bruijn index `D`, this would be `D + 1`
521 /// -- the binder itself does not capture `D`, but `D` is captured
522 /// by an inner binder.
524 /// We call this concept an "exclusive" binder `D` because all
525 /// De Bruijn indices within the type are contained within `0..D`
527 outer_exclusive_binder: ty::DebruijnIndex,
530 // `TyS` is used a lot. Make sure it doesn't unintentionally get bigger.
531 #[cfg(target_arch = "x86_64")]
532 static_assert_size!(TyS<'_>, 32);
534 impl<'tcx> Ord for TyS<'tcx> {
535 fn cmp(&self, other: &TyS<'tcx>) -> Ordering {
536 self.kind.cmp(&other.kind)
540 impl<'tcx> PartialOrd for TyS<'tcx> {
541 fn partial_cmp(&self, other: &TyS<'tcx>) -> Option<Ordering> {
542 Some(self.kind.cmp(&other.kind))
546 impl<'tcx> PartialEq for TyS<'tcx> {
548 fn eq(&self, other: &TyS<'tcx>) -> bool {
552 impl<'tcx> Eq for TyS<'tcx> {}
554 impl<'tcx> Hash for TyS<'tcx> {
555 fn hash<H: Hasher>(&self, s: &mut H) {
556 (self as *const TyS<'_>).hash(s)
560 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for ty::TyS<'tcx> {
561 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
565 // The other fields just provide fast access to information that is
566 // also contained in `kind`, so no need to hash them.
569 outer_exclusive_binder: _,
572 kind.hash_stable(hcx, hasher);
576 #[rustc_diagnostic_item = "Ty"]
577 pub type Ty<'tcx> = &'tcx TyS<'tcx>;
579 impl<'tcx> rustc_serialize::UseSpecializedEncodable for Ty<'tcx> {}
580 impl<'tcx> rustc_serialize::UseSpecializedDecodable for Ty<'tcx> {}
582 pub type CanonicalTy<'tcx> = Canonical<'tcx, Ty<'tcx>>;
585 /// A dummy type used to force `List` to be unsized while not requiring references to it be wide
587 type OpaqueListContents;
590 /// A wrapper for slices with the additional invariant
591 /// that the slice is interned and no other slice with
592 /// the same contents can exist in the same context.
593 /// This means we can use pointer for both
594 /// equality comparisons and hashing.
595 /// Note: `Slice` was already taken by the `Ty`.
600 opaque: OpaqueListContents,
603 unsafe impl<T: Sync> Sync for List<T> {}
605 impl<T: Copy> List<T> {
607 fn from_arena<'tcx>(arena: &'tcx SyncDroplessArena, slice: &[T]) -> &'tcx List<T> {
608 assert!(!mem::needs_drop::<T>());
609 assert!(mem::size_of::<T>() != 0);
610 assert!(slice.len() != 0);
612 // Align up the size of the len (usize) field
613 let align = mem::align_of::<T>();
614 let align_mask = align - 1;
615 let offset = mem::size_of::<usize>();
616 let offset = (offset + align_mask) & !align_mask;
618 let size = offset + slice.len() * mem::size_of::<T>();
620 let mem = arena.alloc_raw(size, cmp::max(mem::align_of::<T>(), mem::align_of::<usize>()));
622 let result = &mut *(mem.as_mut_ptr() as *mut List<T>);
624 result.len = slice.len();
626 // Write the elements
627 let arena_slice = slice::from_raw_parts_mut(result.data.as_mut_ptr(), result.len);
628 arena_slice.copy_from_slice(slice);
635 impl<T: fmt::Debug> fmt::Debug for List<T> {
636 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
641 impl<T: Encodable> Encodable for List<T> {
643 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
648 impl<T> Ord for List<T>
652 fn cmp(&self, other: &List<T>) -> Ordering {
653 if self == other { Ordering::Equal } else { <[T] as Ord>::cmp(&**self, &**other) }
657 impl<T> PartialOrd for List<T>
661 fn partial_cmp(&self, other: &List<T>) -> Option<Ordering> {
663 Some(Ordering::Equal)
665 <[T] as PartialOrd>::partial_cmp(&**self, &**other)
670 impl<T: PartialEq> PartialEq for List<T> {
672 fn eq(&self, other: &List<T>) -> bool {
676 impl<T: Eq> Eq for List<T> {}
678 impl<T> Hash for List<T> {
680 fn hash<H: Hasher>(&self, s: &mut H) {
681 (self as *const List<T>).hash(s)
685 impl<T> Deref for List<T> {
688 fn deref(&self) -> &[T] {
693 impl<T> AsRef<[T]> for List<T> {
695 fn as_ref(&self) -> &[T] {
696 unsafe { slice::from_raw_parts(self.data.as_ptr(), self.len) }
700 impl<'a, T> IntoIterator for &'a List<T> {
702 type IntoIter = <&'a [T] as IntoIterator>::IntoIter;
704 fn into_iter(self) -> Self::IntoIter {
709 impl<'tcx> rustc_serialize::UseSpecializedDecodable for &'tcx List<Ty<'tcx>> {}
713 pub fn empty<'a>() -> &'a List<T> {
714 #[repr(align(64), C)]
715 struct EmptySlice([u8; 64]);
716 static EMPTY_SLICE: EmptySlice = EmptySlice([0; 64]);
717 assert!(mem::align_of::<T>() <= 64);
718 unsafe { &*(&EMPTY_SLICE as *const _ as *const List<T>) }
722 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
723 pub struct UpvarPath {
724 pub hir_id: hir::HirId,
727 /// Upvars do not get their own `NodeId`. Instead, we use the pair of
728 /// the original var ID (that is, the root variable that is referenced
729 /// by the upvar) and the ID of the closure expression.
730 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
732 pub var_path: UpvarPath,
733 pub closure_expr_id: LocalDefId,
736 #[derive(Clone, PartialEq, Debug, RustcEncodable, RustcDecodable, Copy, HashStable)]
737 pub enum BorrowKind {
738 /// Data must be immutable and is aliasable.
741 /// Data must be immutable but not aliasable. This kind of borrow
742 /// cannot currently be expressed by the user and is used only in
743 /// implicit closure bindings. It is needed when the closure
744 /// is borrowing or mutating a mutable referent, e.g.:
746 /// let x: &mut isize = ...;
747 /// let y = || *x += 5;
749 /// If we were to try to translate this closure into a more explicit
750 /// form, we'd encounter an error with the code as written:
752 /// struct Env { x: & &mut isize }
753 /// let x: &mut isize = ...;
754 /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
755 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
757 /// This is then illegal because you cannot mutate a `&mut` found
758 /// in an aliasable location. To solve, you'd have to translate with
759 /// an `&mut` borrow:
761 /// struct Env { x: & &mut isize }
762 /// let x: &mut isize = ...;
763 /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
764 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
766 /// Now the assignment to `**env.x` is legal, but creating a
767 /// mutable pointer to `x` is not because `x` is not mutable. We
768 /// could fix this by declaring `x` as `let mut x`. This is ok in
769 /// user code, if awkward, but extra weird for closures, since the
770 /// borrow is hidden.
772 /// So we introduce a "unique imm" borrow -- the referent is
773 /// immutable, but not aliasable. This solves the problem. For
774 /// simplicity, we don't give users the way to express this
775 /// borrow, it's just used when translating closures.
778 /// Data is mutable and not aliasable.
782 /// Information describing the capture of an upvar. This is computed
783 /// during `typeck`, specifically by `regionck`.
784 #[derive(PartialEq, Clone, Debug, Copy, RustcEncodable, RustcDecodable, HashStable)]
785 pub enum UpvarCapture<'tcx> {
786 /// Upvar is captured by value. This is always true when the
787 /// closure is labeled `move`, but can also be true in other cases
788 /// depending on inference.
791 /// Upvar is captured by reference.
792 ByRef(UpvarBorrow<'tcx>),
795 #[derive(PartialEq, Clone, Copy, RustcEncodable, RustcDecodable, HashStable)]
796 pub struct UpvarBorrow<'tcx> {
797 /// The kind of borrow: by-ref upvars have access to shared
798 /// immutable borrows, which are not part of the normal language
800 pub kind: BorrowKind,
802 /// Region of the resulting reference.
803 pub region: ty::Region<'tcx>,
806 pub type UpvarListMap = FxHashMap<DefId, FxIndexMap<hir::HirId, UpvarId>>;
807 pub type UpvarCaptureMap<'tcx> = FxHashMap<UpvarId, UpvarCapture<'tcx>>;
809 #[derive(Clone, Copy, PartialEq, Eq)]
810 pub enum IntVarValue {
812 UintType(ast::UintTy),
815 #[derive(Clone, Copy, PartialEq, Eq)]
816 pub struct FloatVarValue(pub ast::FloatTy);
818 impl ty::EarlyBoundRegion {
819 pub fn to_bound_region(&self) -> ty::BoundRegion {
820 ty::BoundRegion::BrNamed(self.def_id, self.name)
823 /// Does this early bound region have a name? Early bound regions normally
824 /// always have names except when using anonymous lifetimes (`'_`).
825 pub fn has_name(&self) -> bool {
826 self.name != kw::UnderscoreLifetime
830 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
831 pub enum GenericParamDefKind {
835 object_lifetime_default: ObjectLifetimeDefault,
836 synthetic: Option<hir::SyntheticTyParamKind>,
841 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable)]
842 pub struct GenericParamDef {
847 /// `pure_wrt_drop`, set by the (unsafe) `#[may_dangle]` attribute
848 /// on generic parameter `'a`/`T`, asserts data behind the parameter
849 /// `'a`/`T` won't be accessed during the parent type's `Drop` impl.
850 pub pure_wrt_drop: bool,
852 pub kind: GenericParamDefKind,
855 impl GenericParamDef {
856 pub fn to_early_bound_region_data(&self) -> ty::EarlyBoundRegion {
857 if let GenericParamDefKind::Lifetime = self.kind {
858 ty::EarlyBoundRegion { def_id: self.def_id, index: self.index, name: self.name }
860 bug!("cannot convert a non-lifetime parameter def to an early bound region")
864 pub fn to_bound_region(&self) -> ty::BoundRegion {
865 if let GenericParamDefKind::Lifetime = self.kind {
866 self.to_early_bound_region_data().to_bound_region()
868 bug!("cannot convert a non-lifetime parameter def to an early bound region")
874 pub struct GenericParamCount {
875 pub lifetimes: usize,
880 /// Information about the formal type/lifetime parameters associated
881 /// with an item or method. Analogous to `hir::Generics`.
883 /// The ordering of parameters is the same as in `Subst` (excluding child generics):
884 /// `Self` (optionally), `Lifetime` params..., `Type` params...
885 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
886 pub struct Generics {
887 pub parent: Option<DefId>,
888 pub parent_count: usize,
889 pub params: Vec<GenericParamDef>,
891 /// Reverse map to the `index` field of each `GenericParamDef`.
892 #[stable_hasher(ignore)]
893 pub param_def_id_to_index: FxHashMap<DefId, u32>,
896 pub has_late_bound_regions: Option<Span>,
899 impl<'tcx> Generics {
900 pub fn count(&self) -> usize {
901 self.parent_count + self.params.len()
904 pub fn own_counts(&self) -> GenericParamCount {
905 // We could cache this as a property of `GenericParamCount`, but
906 // the aim is to refactor this away entirely eventually and the
907 // presence of this method will be a constant reminder.
908 let mut own_counts: GenericParamCount = Default::default();
910 for param in &self.params {
912 GenericParamDefKind::Lifetime => own_counts.lifetimes += 1,
913 GenericParamDefKind::Type { .. } => own_counts.types += 1,
914 GenericParamDefKind::Const => own_counts.consts += 1,
921 pub fn requires_monomorphization(&self, tcx: TyCtxt<'tcx>) -> bool {
922 if self.own_requires_monomorphization() {
926 if let Some(parent_def_id) = self.parent {
927 let parent = tcx.generics_of(parent_def_id);
928 parent.requires_monomorphization(tcx)
934 pub fn own_requires_monomorphization(&self) -> bool {
935 for param in &self.params {
937 GenericParamDefKind::Type { .. } | GenericParamDefKind::Const => return true,
938 GenericParamDefKind::Lifetime => {}
946 param: &EarlyBoundRegion,
948 ) -> &'tcx GenericParamDef {
949 if let Some(index) = param.index.checked_sub(self.parent_count as u32) {
950 let param = &self.params[index as usize];
952 GenericParamDefKind::Lifetime => param,
953 _ => bug!("expected lifetime parameter, but found another generic parameter"),
956 tcx.generics_of(self.parent.expect("parent_count > 0 but no parent?"))
957 .region_param(param, tcx)
961 /// Returns the `GenericParamDef` associated with this `ParamTy`.
962 pub fn type_param(&'tcx self, param: &ParamTy, tcx: TyCtxt<'tcx>) -> &'tcx GenericParamDef {
963 if let Some(index) = param.index.checked_sub(self.parent_count as u32) {
964 let param = &self.params[index as usize];
966 GenericParamDefKind::Type { .. } => param,
967 _ => bug!("expected type parameter, but found another generic parameter"),
970 tcx.generics_of(self.parent.expect("parent_count > 0 but no parent?"))
971 .type_param(param, tcx)
975 /// Returns the `ConstParameterDef` associated with this `ParamConst`.
976 pub fn const_param(&'tcx self, param: &ParamConst, tcx: TyCtxt<'tcx>) -> &GenericParamDef {
977 if let Some(index) = param.index.checked_sub(self.parent_count as u32) {
978 let param = &self.params[index as usize];
980 GenericParamDefKind::Const => param,
981 _ => bug!("expected const parameter, but found another generic parameter"),
984 tcx.generics_of(self.parent.expect("parent_count>0 but no parent?"))
985 .const_param(param, tcx)
990 /// Bounds on generics.
991 #[derive(Copy, Clone, Default, Debug, RustcEncodable, RustcDecodable, HashStable)]
992 pub struct GenericPredicates<'tcx> {
993 pub parent: Option<DefId>,
994 pub predicates: &'tcx [(Predicate<'tcx>, Span)],
997 impl<'tcx> GenericPredicates<'tcx> {
1001 substs: SubstsRef<'tcx>,
1002 ) -> InstantiatedPredicates<'tcx> {
1003 let mut instantiated = InstantiatedPredicates::empty();
1004 self.instantiate_into(tcx, &mut instantiated, substs);
1008 pub fn instantiate_own(
1011 substs: SubstsRef<'tcx>,
1012 ) -> InstantiatedPredicates<'tcx> {
1013 InstantiatedPredicates {
1014 predicates: self.predicates.iter().map(|(p, _)| p.subst(tcx, substs)).collect(),
1018 fn instantiate_into(
1021 instantiated: &mut InstantiatedPredicates<'tcx>,
1022 substs: SubstsRef<'tcx>,
1024 if let Some(def_id) = self.parent {
1025 tcx.predicates_of(def_id).instantiate_into(tcx, instantiated, substs);
1027 instantiated.predicates.extend(self.predicates.iter().map(|(p, _)| p.subst(tcx, substs)));
1030 pub fn instantiate_identity(&self, tcx: TyCtxt<'tcx>) -> InstantiatedPredicates<'tcx> {
1031 let mut instantiated = InstantiatedPredicates::empty();
1032 self.instantiate_identity_into(tcx, &mut instantiated);
1036 fn instantiate_identity_into(
1039 instantiated: &mut InstantiatedPredicates<'tcx>,
1041 if let Some(def_id) = self.parent {
1042 tcx.predicates_of(def_id).instantiate_identity_into(tcx, instantiated);
1044 instantiated.predicates.extend(self.predicates.iter().map(|&(p, _)| p))
1047 pub fn instantiate_supertrait(
1050 poly_trait_ref: &ty::PolyTraitRef<'tcx>,
1051 ) -> InstantiatedPredicates<'tcx> {
1052 assert_eq!(self.parent, None);
1053 InstantiatedPredicates {
1057 .map(|(pred, _)| pred.subst_supertrait(tcx, poly_trait_ref))
1063 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1064 #[derive(HashStable, TypeFoldable)]
1065 pub enum Predicate<'tcx> {
1066 /// Corresponds to `where Foo: Bar<A, B, C>`. `Foo` here would be
1067 /// the `Self` type of the trait reference and `A`, `B`, and `C`
1068 /// would be the type parameters.
1069 Trait(PolyTraitPredicate<'tcx>),
1072 RegionOutlives(PolyRegionOutlivesPredicate<'tcx>),
1075 TypeOutlives(PolyTypeOutlivesPredicate<'tcx>),
1077 /// `where <T as TraitRef>::Name == X`, approximately.
1078 /// See the `ProjectionPredicate` struct for details.
1079 Projection(PolyProjectionPredicate<'tcx>),
1081 /// No syntax: `T` well-formed.
1082 WellFormed(Ty<'tcx>),
1084 /// Trait must be object-safe.
1087 /// No direct syntax. May be thought of as `where T: FnFoo<...>`
1088 /// for some substitutions `...` and `T` being a closure type.
1089 /// Satisfied (or refuted) once we know the closure's kind.
1090 ClosureKind(DefId, SubstsRef<'tcx>, ClosureKind),
1093 Subtype(PolySubtypePredicate<'tcx>),
1095 /// Constant initializer must evaluate successfully.
1096 ConstEvaluatable(DefId, SubstsRef<'tcx>),
1099 /// The crate outlives map is computed during typeck and contains the
1100 /// outlives of every item in the local crate. You should not use it
1101 /// directly, because to do so will make your pass dependent on the
1102 /// HIR of every item in the local crate. Instead, use
1103 /// `tcx.inferred_outlives_of()` to get the outlives for a *particular*
1105 #[derive(HashStable)]
1106 pub struct CratePredicatesMap<'tcx> {
1107 /// For each struct with outlive bounds, maps to a vector of the
1108 /// predicate of its outlive bounds. If an item has no outlives
1109 /// bounds, it will have no entry.
1110 pub predicates: FxHashMap<DefId, &'tcx [(ty::Predicate<'tcx>, Span)]>,
1113 impl<'tcx> AsRef<Predicate<'tcx>> for Predicate<'tcx> {
1114 fn as_ref(&self) -> &Predicate<'tcx> {
1119 impl<'tcx> Predicate<'tcx> {
1120 /// Performs a substitution suitable for going from a
1121 /// poly-trait-ref to supertraits that must hold if that
1122 /// poly-trait-ref holds. This is slightly different from a normal
1123 /// substitution in terms of what happens with bound regions. See
1124 /// lengthy comment below for details.
1125 pub fn subst_supertrait(
1128 trait_ref: &ty::PolyTraitRef<'tcx>,
1129 ) -> ty::Predicate<'tcx> {
1130 // The interaction between HRTB and supertraits is not entirely
1131 // obvious. Let me walk you (and myself) through an example.
1133 // Let's start with an easy case. Consider two traits:
1135 // trait Foo<'a>: Bar<'a,'a> { }
1136 // trait Bar<'b,'c> { }
1138 // Now, if we have a trait reference `for<'x> T: Foo<'x>`, then
1139 // we can deduce that `for<'x> T: Bar<'x,'x>`. Basically, if we
1140 // knew that `Foo<'x>` (for any 'x) then we also know that
1141 // `Bar<'x,'x>` (for any 'x). This more-or-less falls out from
1142 // normal substitution.
1144 // In terms of why this is sound, the idea is that whenever there
1145 // is an impl of `T:Foo<'a>`, it must show that `T:Bar<'a,'a>`
1146 // holds. So if there is an impl of `T:Foo<'a>` that applies to
1147 // all `'a`, then we must know that `T:Bar<'a,'a>` holds for all
1150 // Another example to be careful of is this:
1152 // trait Foo1<'a>: for<'b> Bar1<'a,'b> { }
1153 // trait Bar1<'b,'c> { }
1155 // Here, if we have `for<'x> T: Foo1<'x>`, then what do we know?
1156 // The answer is that we know `for<'x,'b> T: Bar1<'x,'b>`. The
1157 // reason is similar to the previous example: any impl of
1158 // `T:Foo1<'x>` must show that `for<'b> T: Bar1<'x, 'b>`. So
1159 // basically we would want to collapse the bound lifetimes from
1160 // the input (`trait_ref`) and the supertraits.
1162 // To achieve this in practice is fairly straightforward. Let's
1163 // consider the more complicated scenario:
1165 // - We start out with `for<'x> T: Foo1<'x>`. In this case, `'x`
1166 // has a De Bruijn index of 1. We want to produce `for<'x,'b> T: Bar1<'x,'b>`,
1167 // where both `'x` and `'b` would have a DB index of 1.
1168 // The substitution from the input trait-ref is therefore going to be
1169 // `'a => 'x` (where `'x` has a DB index of 1).
1170 // - The super-trait-ref is `for<'b> Bar1<'a,'b>`, where `'a` is an
1171 // early-bound parameter and `'b' is a late-bound parameter with a
1173 // - If we replace `'a` with `'x` from the input, it too will have
1174 // a DB index of 1, and thus we'll have `for<'x,'b> Bar1<'x,'b>`
1175 // just as we wanted.
1177 // There is only one catch. If we just apply the substitution `'a
1178 // => 'x` to `for<'b> Bar1<'a,'b>`, the substitution code will
1179 // adjust the DB index because we substituting into a binder (it
1180 // tries to be so smart...) resulting in `for<'x> for<'b>
1181 // Bar1<'x,'b>` (we have no syntax for this, so use your
1182 // imagination). Basically the 'x will have DB index of 2 and 'b
1183 // will have DB index of 1. Not quite what we want. So we apply
1184 // the substitution to the *contents* of the trait reference,
1185 // rather than the trait reference itself (put another way, the
1186 // substitution code expects equal binding levels in the values
1187 // from the substitution and the value being substituted into, and
1188 // this trick achieves that).
1190 let substs = &trait_ref.skip_binder().substs;
1192 Predicate::Trait(ref binder) => {
1193 Predicate::Trait(binder.map_bound(|data| data.subst(tcx, substs)))
1195 Predicate::Subtype(ref binder) => {
1196 Predicate::Subtype(binder.map_bound(|data| data.subst(tcx, substs)))
1198 Predicate::RegionOutlives(ref binder) => {
1199 Predicate::RegionOutlives(binder.map_bound(|data| data.subst(tcx, substs)))
1201 Predicate::TypeOutlives(ref binder) => {
1202 Predicate::TypeOutlives(binder.map_bound(|data| data.subst(tcx, substs)))
1204 Predicate::Projection(ref binder) => {
1205 Predicate::Projection(binder.map_bound(|data| data.subst(tcx, substs)))
1207 Predicate::WellFormed(data) => Predicate::WellFormed(data.subst(tcx, substs)),
1208 Predicate::ObjectSafe(trait_def_id) => Predicate::ObjectSafe(trait_def_id),
1209 Predicate::ClosureKind(closure_def_id, closure_substs, kind) => {
1210 Predicate::ClosureKind(closure_def_id, closure_substs.subst(tcx, substs), kind)
1212 Predicate::ConstEvaluatable(def_id, const_substs) => {
1213 Predicate::ConstEvaluatable(def_id, const_substs.subst(tcx, substs))
1219 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1220 #[derive(HashStable, TypeFoldable)]
1221 pub struct TraitPredicate<'tcx> {
1222 pub trait_ref: TraitRef<'tcx>,
1225 pub type PolyTraitPredicate<'tcx> = ty::Binder<TraitPredicate<'tcx>>;
1227 impl<'tcx> TraitPredicate<'tcx> {
1228 pub fn def_id(&self) -> DefId {
1229 self.trait_ref.def_id
1232 pub fn input_types<'a>(&'a self) -> impl DoubleEndedIterator<Item = Ty<'tcx>> + 'a {
1233 self.trait_ref.input_types()
1236 pub fn self_ty(&self) -> Ty<'tcx> {
1237 self.trait_ref.self_ty()
1241 impl<'tcx> PolyTraitPredicate<'tcx> {
1242 pub fn def_id(&self) -> DefId {
1243 // Ok to skip binder since trait `DefId` does not care about regions.
1244 self.skip_binder().def_id()
1248 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, RustcEncodable, RustcDecodable)]
1249 #[derive(HashStable, TypeFoldable)]
1250 pub struct OutlivesPredicate<A, B>(pub A, pub B); // `A: B`
1251 pub type PolyOutlivesPredicate<A, B> = ty::Binder<OutlivesPredicate<A, B>>;
1252 pub type RegionOutlivesPredicate<'tcx> = OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>;
1253 pub type TypeOutlivesPredicate<'tcx> = OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>;
1254 pub type PolyRegionOutlivesPredicate<'tcx> = ty::Binder<RegionOutlivesPredicate<'tcx>>;
1255 pub type PolyTypeOutlivesPredicate<'tcx> = ty::Binder<TypeOutlivesPredicate<'tcx>>;
1257 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
1258 #[derive(HashStable, TypeFoldable)]
1259 pub struct SubtypePredicate<'tcx> {
1260 pub a_is_expected: bool,
1264 pub type PolySubtypePredicate<'tcx> = ty::Binder<SubtypePredicate<'tcx>>;
1266 /// This kind of predicate has no *direct* correspondent in the
1267 /// syntax, but it roughly corresponds to the syntactic forms:
1269 /// 1. `T: TraitRef<..., Item = Type>`
1270 /// 2. `<T as TraitRef<...>>::Item == Type` (NYI)
1272 /// In particular, form #1 is "desugared" to the combination of a
1273 /// normal trait predicate (`T: TraitRef<...>`) and one of these
1274 /// predicates. Form #2 is a broader form in that it also permits
1275 /// equality between arbitrary types. Processing an instance of
1276 /// Form #2 eventually yields one of these `ProjectionPredicate`
1277 /// instances to normalize the LHS.
1278 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1279 #[derive(HashStable, TypeFoldable)]
1280 pub struct ProjectionPredicate<'tcx> {
1281 pub projection_ty: ProjectionTy<'tcx>,
1285 pub type PolyProjectionPredicate<'tcx> = Binder<ProjectionPredicate<'tcx>>;
1287 impl<'tcx> PolyProjectionPredicate<'tcx> {
1288 /// Returns the `DefId` of the associated item being projected.
1289 pub fn item_def_id(&self) -> DefId {
1290 self.skip_binder().projection_ty.item_def_id
1294 pub fn to_poly_trait_ref(&self, tcx: TyCtxt<'tcx>) -> PolyTraitRef<'tcx> {
1295 // Note: unlike with `TraitRef::to_poly_trait_ref()`,
1296 // `self.0.trait_ref` is permitted to have escaping regions.
1297 // This is because here `self` has a `Binder` and so does our
1298 // return value, so we are preserving the number of binding
1300 self.map_bound(|predicate| predicate.projection_ty.trait_ref(tcx))
1303 pub fn ty(&self) -> Binder<Ty<'tcx>> {
1304 self.map_bound(|predicate| predicate.ty)
1307 /// The `DefId` of the `TraitItem` for the associated type.
1309 /// Note that this is not the `DefId` of the `TraitRef` containing this
1310 /// associated type, which is in `tcx.associated_item(projection_def_id()).container`.
1311 pub fn projection_def_id(&self) -> DefId {
1312 // Ok to skip binder since trait `DefId` does not care about regions.
1313 self.skip_binder().projection_ty.item_def_id
1317 pub trait ToPolyTraitRef<'tcx> {
1318 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx>;
1321 impl<'tcx> ToPolyTraitRef<'tcx> for TraitRef<'tcx> {
1322 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
1323 ty::Binder::dummy(self.clone())
1327 impl<'tcx> ToPolyTraitRef<'tcx> for PolyTraitPredicate<'tcx> {
1328 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
1329 self.map_bound_ref(|trait_pred| trait_pred.trait_ref)
1333 pub trait ToPredicate<'tcx> {
1334 fn to_predicate(&self) -> Predicate<'tcx>;
1337 impl<'tcx> ToPredicate<'tcx> for TraitRef<'tcx> {
1338 fn to_predicate(&self) -> Predicate<'tcx> {
1339 ty::Predicate::Trait(ty::Binder::dummy(ty::TraitPredicate { trait_ref: self.clone() }))
1343 impl<'tcx> ToPredicate<'tcx> for PolyTraitRef<'tcx> {
1344 fn to_predicate(&self) -> Predicate<'tcx> {
1345 ty::Predicate::Trait(self.to_poly_trait_predicate())
1349 impl<'tcx> ToPredicate<'tcx> for PolyRegionOutlivesPredicate<'tcx> {
1350 fn to_predicate(&self) -> Predicate<'tcx> {
1351 Predicate::RegionOutlives(self.clone())
1355 impl<'tcx> ToPredicate<'tcx> for PolyTypeOutlivesPredicate<'tcx> {
1356 fn to_predicate(&self) -> Predicate<'tcx> {
1357 Predicate::TypeOutlives(self.clone())
1361 impl<'tcx> ToPredicate<'tcx> for PolyProjectionPredicate<'tcx> {
1362 fn to_predicate(&self) -> Predicate<'tcx> {
1363 Predicate::Projection(self.clone())
1367 // A custom iterator used by `Predicate::walk_tys`.
1368 enum WalkTysIter<'tcx, I, J, K>
1370 I: Iterator<Item = Ty<'tcx>>,
1371 J: Iterator<Item = Ty<'tcx>>,
1372 K: Iterator<Item = Ty<'tcx>>,
1376 Two(Ty<'tcx>, Ty<'tcx>),
1382 impl<'tcx, I, J, K> Iterator for WalkTysIter<'tcx, I, J, K>
1384 I: Iterator<Item = Ty<'tcx>>,
1385 J: Iterator<Item = Ty<'tcx>>,
1386 K: Iterator<Item = Ty<'tcx>>,
1388 type Item = Ty<'tcx>;
1390 fn next(&mut self) -> Option<Ty<'tcx>> {
1392 WalkTysIter::None => None,
1393 WalkTysIter::One(item) => {
1394 *self = WalkTysIter::None;
1397 WalkTysIter::Two(item1, item2) => {
1398 *self = WalkTysIter::One(item2);
1401 WalkTysIter::Types(ref mut iter) => iter.next(),
1402 WalkTysIter::InputTypes(ref mut iter) => iter.next(),
1403 WalkTysIter::ProjectionTypes(ref mut iter) => iter.next(),
1408 impl<'tcx> Predicate<'tcx> {
1409 /// Iterates over the types in this predicate. Note that in all
1410 /// cases this is skipping over a binder, so late-bound regions
1411 /// with depth 0 are bound by the predicate.
1412 pub fn walk_tys(&'a self) -> impl Iterator<Item = Ty<'tcx>> + 'a {
1414 ty::Predicate::Trait(ref data) => {
1415 WalkTysIter::InputTypes(data.skip_binder().input_types())
1417 ty::Predicate::Subtype(binder) => {
1418 let SubtypePredicate { a, b, a_is_expected: _ } = binder.skip_binder();
1419 WalkTysIter::Two(a, b)
1421 ty::Predicate::TypeOutlives(binder) => WalkTysIter::One(binder.skip_binder().0),
1422 ty::Predicate::RegionOutlives(..) => WalkTysIter::None,
1423 ty::Predicate::Projection(ref data) => {
1424 let inner = data.skip_binder();
1425 WalkTysIter::ProjectionTypes(
1426 inner.projection_ty.substs.types().chain(Some(inner.ty)),
1429 ty::Predicate::WellFormed(data) => WalkTysIter::One(data),
1430 ty::Predicate::ObjectSafe(_trait_def_id) => WalkTysIter::None,
1431 ty::Predicate::ClosureKind(_closure_def_id, closure_substs, _kind) => {
1432 WalkTysIter::Types(closure_substs.types())
1434 ty::Predicate::ConstEvaluatable(_, substs) => WalkTysIter::Types(substs.types()),
1438 pub fn to_opt_poly_trait_ref(&self) -> Option<PolyTraitRef<'tcx>> {
1440 Predicate::Trait(ref t) => Some(t.to_poly_trait_ref()),
1441 Predicate::Projection(..)
1442 | Predicate::Subtype(..)
1443 | Predicate::RegionOutlives(..)
1444 | Predicate::WellFormed(..)
1445 | Predicate::ObjectSafe(..)
1446 | Predicate::ClosureKind(..)
1447 | Predicate::TypeOutlives(..)
1448 | Predicate::ConstEvaluatable(..) => None,
1452 pub fn to_opt_type_outlives(&self) -> Option<PolyTypeOutlivesPredicate<'tcx>> {
1454 Predicate::TypeOutlives(data) => Some(data),
1455 Predicate::Trait(..)
1456 | Predicate::Projection(..)
1457 | Predicate::Subtype(..)
1458 | Predicate::RegionOutlives(..)
1459 | Predicate::WellFormed(..)
1460 | Predicate::ObjectSafe(..)
1461 | Predicate::ClosureKind(..)
1462 | Predicate::ConstEvaluatable(..) => None,
1467 /// Represents the bounds declared on a particular set of type
1468 /// parameters. Should eventually be generalized into a flag list of
1469 /// where-clauses. You can obtain a `InstantiatedPredicates` list from a
1470 /// `GenericPredicates` by using the `instantiate` method. Note that this method
1471 /// reflects an important semantic invariant of `InstantiatedPredicates`: while
1472 /// the `GenericPredicates` are expressed in terms of the bound type
1473 /// parameters of the impl/trait/whatever, an `InstantiatedPredicates` instance
1474 /// represented a set of bounds for some particular instantiation,
1475 /// meaning that the generic parameters have been substituted with
1480 /// struct Foo<T, U: Bar<T>> { ... }
1482 /// Here, the `GenericPredicates` for `Foo` would contain a list of bounds like
1483 /// `[[], [U:Bar<T>]]`. Now if there were some particular reference
1484 /// like `Foo<isize,usize>`, then the `InstantiatedPredicates` would be `[[],
1485 /// [usize:Bar<isize>]]`.
1486 #[derive(Clone, Debug, TypeFoldable)]
1487 pub struct InstantiatedPredicates<'tcx> {
1488 pub predicates: Vec<Predicate<'tcx>>,
1491 impl<'tcx> InstantiatedPredicates<'tcx> {
1492 pub fn empty() -> InstantiatedPredicates<'tcx> {
1493 InstantiatedPredicates { predicates: vec![] }
1496 pub fn is_empty(&self) -> bool {
1497 self.predicates.is_empty()
1501 rustc_index::newtype_index! {
1502 /// "Universes" are used during type- and trait-checking in the
1503 /// presence of `for<..>` binders to control what sets of names are
1504 /// visible. Universes are arranged into a tree: the root universe
1505 /// contains names that are always visible. Each child then adds a new
1506 /// set of names that are visible, in addition to those of its parent.
1507 /// We say that the child universe "extends" the parent universe with
1510 /// To make this more concrete, consider this program:
1514 /// fn bar<T>(x: T) {
1515 /// let y: for<'a> fn(&'a u8, Foo) = ...;
1519 /// The struct name `Foo` is in the root universe U0. But the type
1520 /// parameter `T`, introduced on `bar`, is in an extended universe U1
1521 /// -- i.e., within `bar`, we can name both `T` and `Foo`, but outside
1522 /// of `bar`, we cannot name `T`. Then, within the type of `y`, the
1523 /// region `'a` is in a universe U2 that extends U1, because we can
1524 /// name it inside the fn type but not outside.
1526 /// Universes are used to do type- and trait-checking around these
1527 /// "forall" binders (also called **universal quantification**). The
1528 /// idea is that when, in the body of `bar`, we refer to `T` as a
1529 /// type, we aren't referring to any type in particular, but rather a
1530 /// kind of "fresh" type that is distinct from all other types we have
1531 /// actually declared. This is called a **placeholder** type, and we
1532 /// use universes to talk about this. In other words, a type name in
1533 /// universe 0 always corresponds to some "ground" type that the user
1534 /// declared, but a type name in a non-zero universe is a placeholder
1535 /// type -- an idealized representative of "types in general" that we
1536 /// use for checking generic functions.
1537 pub struct UniverseIndex {
1539 DEBUG_FORMAT = "U{}",
1543 impl UniverseIndex {
1544 pub const ROOT: UniverseIndex = UniverseIndex::from_u32_const(0);
1546 /// Returns the "next" universe index in order -- this new index
1547 /// is considered to extend all previous universes. This
1548 /// corresponds to entering a `forall` quantifier. So, for
1549 /// example, suppose we have this type in universe `U`:
1552 /// for<'a> fn(&'a u32)
1555 /// Once we "enter" into this `for<'a>` quantifier, we are in a
1556 /// new universe that extends `U` -- in this new universe, we can
1557 /// name the region `'a`, but that region was not nameable from
1558 /// `U` because it was not in scope there.
1559 pub fn next_universe(self) -> UniverseIndex {
1560 UniverseIndex::from_u32(self.private.checked_add(1).unwrap())
1563 /// Returns `true` if `self` can name a name from `other` -- in other words,
1564 /// if the set of names in `self` is a superset of those in
1565 /// `other` (`self >= other`).
1566 pub fn can_name(self, other: UniverseIndex) -> bool {
1567 self.private >= other.private
1570 /// Returns `true` if `self` cannot name some names from `other` -- in other
1571 /// words, if the set of names in `self` is a strict subset of
1572 /// those in `other` (`self < other`).
1573 pub fn cannot_name(self, other: UniverseIndex) -> bool {
1574 self.private < other.private
1578 /// The "placeholder index" fully defines a placeholder region.
1579 /// Placeholder regions are identified by both a **universe** as well
1580 /// as a "bound-region" within that universe. The `bound_region` is
1581 /// basically a name -- distinct bound regions within the same
1582 /// universe are just two regions with an unknown relationship to one
1584 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, PartialOrd, Ord)]
1585 pub struct Placeholder<T> {
1586 pub universe: UniverseIndex,
1590 impl<'a, T> HashStable<StableHashingContext<'a>> for Placeholder<T>
1592 T: HashStable<StableHashingContext<'a>>,
1594 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
1595 self.universe.hash_stable(hcx, hasher);
1596 self.name.hash_stable(hcx, hasher);
1600 pub type PlaceholderRegion = Placeholder<BoundRegion>;
1602 pub type PlaceholderType = Placeholder<BoundVar>;
1604 pub type PlaceholderConst = Placeholder<BoundVar>;
1606 /// When type checking, we use the `ParamEnv` to track
1607 /// details about the set of where-clauses that are in scope at this
1608 /// particular point.
1609 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable, TypeFoldable)]
1610 pub struct ParamEnv<'tcx> {
1611 /// `Obligation`s that the caller must satisfy. This is basically
1612 /// the set of bounds on the in-scope type parameters, translated
1613 /// into `Obligation`s, and elaborated and normalized.
1614 pub caller_bounds: &'tcx List<ty::Predicate<'tcx>>,
1616 /// Typically, this is `Reveal::UserFacing`, but during codegen we
1617 /// want `Reveal::All` -- note that this is always paired with an
1618 /// empty environment. To get that, use `ParamEnv::reveal()`.
1619 pub reveal: traits::Reveal,
1621 /// If this `ParamEnv` comes from a call to `tcx.param_env(def_id)`,
1622 /// register that `def_id` (useful for transitioning to the chalk trait
1624 pub def_id: Option<DefId>,
1627 impl<'tcx> ParamEnv<'tcx> {
1628 /// Construct a trait environment suitable for contexts where
1629 /// there are no where-clauses in scope. Hidden types (like `impl
1630 /// Trait`) are left hidden, so this is suitable for ordinary
1633 pub fn empty() -> Self {
1634 Self::new(List::empty(), Reveal::UserFacing, None)
1637 /// Construct a trait environment with no where-clauses in scope
1638 /// where the values of all `impl Trait` and other hidden types
1639 /// are revealed. This is suitable for monomorphized, post-typeck
1640 /// environments like codegen or doing optimizations.
1642 /// N.B., if you want to have predicates in scope, use `ParamEnv::new`,
1643 /// or invoke `param_env.with_reveal_all()`.
1645 pub fn reveal_all() -> Self {
1646 Self::new(List::empty(), Reveal::All, None)
1649 /// Construct a trait environment with the given set of predicates.
1652 caller_bounds: &'tcx List<ty::Predicate<'tcx>>,
1654 def_id: Option<DefId>,
1656 ty::ParamEnv { caller_bounds, reveal, def_id }
1659 /// Returns a new parameter environment with the same clauses, but
1660 /// which "reveals" the true results of projections in all cases
1661 /// (even for associated types that are specializable). This is
1662 /// the desired behavior during codegen and certain other special
1663 /// contexts; normally though we want to use `Reveal::UserFacing`,
1664 /// which is the default.
1665 pub fn with_reveal_all(self) -> Self {
1666 ty::ParamEnv { reveal: Reveal::All, ..self }
1669 /// Returns this same environment but with no caller bounds.
1670 pub fn without_caller_bounds(self) -> Self {
1671 ty::ParamEnv { caller_bounds: List::empty(), ..self }
1674 /// Creates a suitable environment in which to perform trait
1675 /// queries on the given value. When type-checking, this is simply
1676 /// the pair of the environment plus value. But when reveal is set to
1677 /// All, then if `value` does not reference any type parameters, we will
1678 /// pair it with the empty environment. This improves caching and is generally
1681 /// N.B., we preserve the environment when type-checking because it
1682 /// is possible for the user to have wacky where-clauses like
1683 /// `where Box<u32>: Copy`, which are clearly never
1684 /// satisfiable. We generally want to behave as if they were true,
1685 /// although the surrounding function is never reachable.
1686 pub fn and<T: TypeFoldable<'tcx>>(self, value: T) -> ParamEnvAnd<'tcx, T> {
1688 Reveal::UserFacing => ParamEnvAnd { param_env: self, value },
1691 if value.has_placeholders() || value.needs_infer() || value.has_param_types() {
1692 ParamEnvAnd { param_env: self, value }
1694 ParamEnvAnd { param_env: self.without_caller_bounds(), value }
1701 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TypeFoldable)]
1702 pub struct ParamEnvAnd<'tcx, T> {
1703 pub param_env: ParamEnv<'tcx>,
1707 impl<'tcx, T> ParamEnvAnd<'tcx, T> {
1708 pub fn into_parts(self) -> (ParamEnv<'tcx>, T) {
1709 (self.param_env, self.value)
1713 impl<'a, 'tcx, T> HashStable<StableHashingContext<'a>> for ParamEnvAnd<'tcx, T>
1715 T: HashStable<StableHashingContext<'a>>,
1717 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
1718 let ParamEnvAnd { ref param_env, ref value } = *self;
1720 param_env.hash_stable(hcx, hasher);
1721 value.hash_stable(hcx, hasher);
1725 #[derive(Copy, Clone, Debug, HashStable)]
1726 pub struct Destructor {
1727 /// The `DefId` of the destructor method
1732 #[derive(HashStable)]
1733 pub struct AdtFlags: u32 {
1734 const NO_ADT_FLAGS = 0;
1735 /// Indicates whether the ADT is an enum.
1736 const IS_ENUM = 1 << 0;
1737 /// Indicates whether the ADT is a union.
1738 const IS_UNION = 1 << 1;
1739 /// Indicates whether the ADT is a struct.
1740 const IS_STRUCT = 1 << 2;
1741 /// Indicates whether the ADT is a struct and has a constructor.
1742 const HAS_CTOR = 1 << 3;
1743 /// Indicates whether the type is a `PhantomData`.
1744 const IS_PHANTOM_DATA = 1 << 4;
1745 /// Indicates whether the type has a `#[fundamental]` attribute.
1746 const IS_FUNDAMENTAL = 1 << 5;
1747 /// Indicates whether the type is a `Box`.
1748 const IS_BOX = 1 << 6;
1749 /// Indicates whether the type is an `Arc`.
1750 const IS_ARC = 1 << 7;
1751 /// Indicates whether the type is an `Rc`.
1752 const IS_RC = 1 << 8;
1753 /// Indicates whether the variant list of this ADT is `#[non_exhaustive]`.
1754 /// (i.e., this flag is never set unless this ADT is an enum).
1755 const IS_VARIANT_LIST_NON_EXHAUSTIVE = 1 << 9;
1760 #[derive(HashStable)]
1761 pub struct VariantFlags: u32 {
1762 const NO_VARIANT_FLAGS = 0;
1763 /// Indicates whether the field list of this variant is `#[non_exhaustive]`.
1764 const IS_FIELD_LIST_NON_EXHAUSTIVE = 1 << 0;
1768 /// Definition of a variant -- a struct's fields or a enum variant.
1769 #[derive(Debug, HashStable)]
1770 pub struct VariantDef {
1771 /// `DefId` that identifies the variant itself.
1772 /// If this variant belongs to a struct or union, then this is a copy of its `DefId`.
1774 /// `DefId` that identifies the variant's constructor.
1775 /// If this variant is a struct variant, then this is `None`.
1776 pub ctor_def_id: Option<DefId>,
1777 /// Variant or struct name.
1778 #[stable_hasher(project(name))]
1780 /// Discriminant of this variant.
1781 pub discr: VariantDiscr,
1782 /// Fields of this variant.
1783 pub fields: Vec<FieldDef>,
1784 /// Type of constructor of variant.
1785 pub ctor_kind: CtorKind,
1786 /// Flags of the variant (e.g. is field list non-exhaustive)?
1787 flags: VariantFlags,
1788 /// Variant is obtained as part of recovering from a syntactic error.
1789 /// May be incomplete or bogus.
1790 pub recovered: bool,
1793 impl<'tcx> VariantDef {
1794 /// Creates a new `VariantDef`.
1796 /// `variant_did` is the `DefId` that identifies the enum variant (if this `VariantDef`
1797 /// represents an enum variant).
1799 /// `ctor_did` is the `DefId` that identifies the constructor of unit or
1800 /// tuple-variants/structs. If this is a `struct`-variant then this should be `None`.
1802 /// `parent_did` is the `DefId` of the `AdtDef` representing the enum or struct that
1803 /// owns this variant. It is used for checking if a struct has `#[non_exhaustive]` w/out having
1804 /// to go through the redirect of checking the ctor's attributes - but compiling a small crate
1805 /// requires loading the `AdtDef`s for all the structs in the universe (e.g., coherence for any
1806 /// built-in trait), and we do not want to load attributes twice.
1808 /// If someone speeds up attribute loading to not be a performance concern, they can
1809 /// remove this hack and use the constructor `DefId` everywhere.
1813 variant_did: Option<DefId>,
1814 ctor_def_id: Option<DefId>,
1815 discr: VariantDiscr,
1816 fields: Vec<FieldDef>,
1817 ctor_kind: CtorKind,
1823 "VariantDef::new(ident = {:?}, variant_did = {:?}, ctor_def_id = {:?}, discr = {:?},
1824 fields = {:?}, ctor_kind = {:?}, adt_kind = {:?}, parent_did = {:?})",
1825 ident, variant_did, ctor_def_id, discr, fields, ctor_kind, adt_kind, parent_did,
1828 let mut flags = VariantFlags::NO_VARIANT_FLAGS;
1829 if adt_kind == AdtKind::Struct && tcx.has_attr(parent_did, sym::non_exhaustive) {
1830 debug!("found non-exhaustive field list for {:?}", parent_did);
1831 flags = flags | VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE;
1832 } else if let Some(variant_did) = variant_did {
1833 if tcx.has_attr(variant_did, sym::non_exhaustive) {
1834 debug!("found non-exhaustive field list for {:?}", variant_did);
1835 flags = flags | VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE;
1840 def_id: variant_did.unwrap_or(parent_did),
1851 /// Is this field list non-exhaustive?
1853 pub fn is_field_list_non_exhaustive(&self) -> bool {
1854 self.flags.intersects(VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE)
1858 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
1859 pub enum VariantDiscr {
1860 /// Explicit value for this variant, i.e., `X = 123`.
1861 /// The `DefId` corresponds to the embedded constant.
1864 /// The previous variant's discriminant plus one.
1865 /// For efficiency reasons, the distance from the
1866 /// last `Explicit` discriminant is being stored,
1867 /// or `0` for the first variant, if it has none.
1871 #[derive(Debug, HashStable)]
1872 pub struct FieldDef {
1874 #[stable_hasher(project(name))]
1876 pub vis: Visibility,
1879 /// The definition of a user-defined type, e.g., a `struct`, `enum`, or `union`.
1881 /// These are all interned (by `intern_adt_def`) into the `adt_defs` table.
1883 /// The initialism *ADT* stands for an [*algebraic data type (ADT)*][adt].
1884 /// This is slightly wrong because `union`s are not ADTs.
1885 /// Moreover, Rust only allows recursive data types through indirection.
1887 /// [adt]: https://en.wikipedia.org/wiki/Algebraic_data_type
1889 /// The `DefId` of the struct, enum or union item.
1891 /// Variants of the ADT. If this is a struct or union, then there will be a single variant.
1892 pub variants: IndexVec<self::layout::VariantIdx, VariantDef>,
1893 /// Flags of the ADT (e.g., is this a struct? is this non-exhaustive?).
1895 /// Repr options provided by the user.
1896 pub repr: ReprOptions,
1899 impl PartialOrd for AdtDef {
1900 fn partial_cmp(&self, other: &AdtDef) -> Option<Ordering> {
1901 Some(self.cmp(&other))
1905 /// There should be only one AdtDef for each `did`, therefore
1906 /// it is fine to implement `Ord` only based on `did`.
1907 impl Ord for AdtDef {
1908 fn cmp(&self, other: &AdtDef) -> Ordering {
1909 self.did.cmp(&other.did)
1913 impl PartialEq for AdtDef {
1914 // `AdtDef`s are always interned, and this is part of `TyS` equality.
1916 fn eq(&self, other: &Self) -> bool {
1917 ptr::eq(self, other)
1921 impl Eq for AdtDef {}
1923 impl Hash for AdtDef {
1925 fn hash<H: Hasher>(&self, s: &mut H) {
1926 (self as *const AdtDef).hash(s)
1930 impl<'tcx> rustc_serialize::UseSpecializedEncodable for &'tcx AdtDef {
1931 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1936 impl<'tcx> rustc_serialize::UseSpecializedDecodable for &'tcx AdtDef {}
1938 impl<'a> HashStable<StableHashingContext<'a>> for AdtDef {
1939 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
1941 static CACHE: RefCell<FxHashMap<usize, Fingerprint>> = Default::default();
1944 let hash: Fingerprint = CACHE.with(|cache| {
1945 let addr = self as *const AdtDef as usize;
1946 *cache.borrow_mut().entry(addr).or_insert_with(|| {
1947 let ty::AdtDef { did, ref variants, ref flags, ref repr } = *self;
1949 let mut hasher = StableHasher::new();
1950 did.hash_stable(hcx, &mut hasher);
1951 variants.hash_stable(hcx, &mut hasher);
1952 flags.hash_stable(hcx, &mut hasher);
1953 repr.hash_stable(hcx, &mut hasher);
1959 hash.hash_stable(hcx, hasher);
1963 #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
1970 impl Into<DataTypeKind> for AdtKind {
1971 fn into(self) -> DataTypeKind {
1973 AdtKind::Struct => DataTypeKind::Struct,
1974 AdtKind::Union => DataTypeKind::Union,
1975 AdtKind::Enum => DataTypeKind::Enum,
1981 #[derive(RustcEncodable, RustcDecodable, Default, HashStable)]
1982 pub struct ReprFlags: u8 {
1983 const IS_C = 1 << 0;
1984 const IS_SIMD = 1 << 1;
1985 const IS_TRANSPARENT = 1 << 2;
1986 // Internal only for now. If true, don't reorder fields.
1987 const IS_LINEAR = 1 << 3;
1989 // Any of these flags being set prevent field reordering optimisation.
1990 const IS_UNOPTIMISABLE = ReprFlags::IS_C.bits |
1991 ReprFlags::IS_SIMD.bits |
1992 ReprFlags::IS_LINEAR.bits;
1996 /// Represents the repr options provided by the user,
1997 #[derive(Copy, Clone, Debug, Eq, PartialEq, RustcEncodable, RustcDecodable, Default, HashStable)]
1998 pub struct ReprOptions {
1999 pub int: Option<attr::IntType>,
2000 pub align: Option<Align>,
2001 pub pack: Option<Align>,
2002 pub flags: ReprFlags,
2006 pub fn new(tcx: TyCtxt<'_>, did: DefId) -> ReprOptions {
2007 let mut flags = ReprFlags::empty();
2008 let mut size = None;
2009 let mut max_align: Option<Align> = None;
2010 let mut min_pack: Option<Align> = None;
2011 for attr in tcx.get_attrs(did).iter() {
2012 for r in attr::find_repr_attrs(&tcx.sess.parse_sess, attr) {
2013 flags.insert(match r {
2014 attr::ReprC => ReprFlags::IS_C,
2015 attr::ReprPacked(pack) => {
2016 let pack = Align::from_bytes(pack as u64).unwrap();
2017 min_pack = Some(if let Some(min_pack) = min_pack {
2024 attr::ReprTransparent => ReprFlags::IS_TRANSPARENT,
2025 attr::ReprSimd => ReprFlags::IS_SIMD,
2026 attr::ReprInt(i) => {
2030 attr::ReprAlign(align) => {
2031 max_align = max_align.max(Some(Align::from_bytes(align as u64).unwrap()));
2038 // This is here instead of layout because the choice must make it into metadata.
2039 if !tcx.consider_optimizing(|| format!("Reorder fields of {:?}", tcx.def_path_str(did))) {
2040 flags.insert(ReprFlags::IS_LINEAR);
2042 ReprOptions { int: size, align: max_align, pack: min_pack, flags: flags }
2046 pub fn simd(&self) -> bool {
2047 self.flags.contains(ReprFlags::IS_SIMD)
2050 pub fn c(&self) -> bool {
2051 self.flags.contains(ReprFlags::IS_C)
2054 pub fn packed(&self) -> bool {
2058 pub fn transparent(&self) -> bool {
2059 self.flags.contains(ReprFlags::IS_TRANSPARENT)
2062 pub fn linear(&self) -> bool {
2063 self.flags.contains(ReprFlags::IS_LINEAR)
2066 pub fn discr_type(&self) -> attr::IntType {
2067 self.int.unwrap_or(attr::SignedInt(ast::IntTy::Isize))
2070 /// Returns `true` if this `#[repr()]` should inhabit "smart enum
2071 /// layout" optimizations, such as representing `Foo<&T>` as a
2073 pub fn inhibit_enum_layout_opt(&self) -> bool {
2074 self.c() || self.int.is_some()
2077 /// Returns `true` if this `#[repr()]` should inhibit struct field reordering
2078 /// optimizations, such as with `repr(C)`, `repr(packed(1))`, or `repr(<int>)`.
2079 pub fn inhibit_struct_field_reordering_opt(&self) -> bool {
2080 if let Some(pack) = self.pack {
2081 if pack.bytes() == 1 {
2085 self.flags.intersects(ReprFlags::IS_UNOPTIMISABLE) || self.int.is_some()
2088 /// Returns `true` if this `#[repr()]` should inhibit union ABI optimisations.
2089 pub fn inhibit_union_abi_opt(&self) -> bool {
2095 /// Creates a new `AdtDef`.
2100 variants: IndexVec<VariantIdx, VariantDef>,
2103 debug!("AdtDef::new({:?}, {:?}, {:?}, {:?})", did, kind, variants, repr);
2104 let mut flags = AdtFlags::NO_ADT_FLAGS;
2106 if kind == AdtKind::Enum && tcx.has_attr(did, sym::non_exhaustive) {
2107 debug!("found non-exhaustive variant list for {:?}", did);
2108 flags = flags | AdtFlags::IS_VARIANT_LIST_NON_EXHAUSTIVE;
2111 flags |= match kind {
2112 AdtKind::Enum => AdtFlags::IS_ENUM,
2113 AdtKind::Union => AdtFlags::IS_UNION,
2114 AdtKind::Struct => AdtFlags::IS_STRUCT,
2117 if kind == AdtKind::Struct && variants[VariantIdx::new(0)].ctor_def_id.is_some() {
2118 flags |= AdtFlags::HAS_CTOR;
2121 let attrs = tcx.get_attrs(did);
2122 if attr::contains_name(&attrs, sym::fundamental) {
2123 flags |= AdtFlags::IS_FUNDAMENTAL;
2125 if Some(did) == tcx.lang_items().phantom_data() {
2126 flags |= AdtFlags::IS_PHANTOM_DATA;
2128 if Some(did) == tcx.lang_items().owned_box() {
2129 flags |= AdtFlags::IS_BOX;
2131 if Some(did) == tcx.lang_items().arc() {
2132 flags |= AdtFlags::IS_ARC;
2134 if Some(did) == tcx.lang_items().rc() {
2135 flags |= AdtFlags::IS_RC;
2138 AdtDef { did, variants, flags, repr }
2141 /// Returns `true` if this is a struct.
2143 pub fn is_struct(&self) -> bool {
2144 self.flags.contains(AdtFlags::IS_STRUCT)
2147 /// Returns `true` if this is a union.
2149 pub fn is_union(&self) -> bool {
2150 self.flags.contains(AdtFlags::IS_UNION)
2153 /// Returns `true` if this is a enum.
2155 pub fn is_enum(&self) -> bool {
2156 self.flags.contains(AdtFlags::IS_ENUM)
2159 /// Returns `true` if the variant list of this ADT is `#[non_exhaustive]`.
2161 pub fn is_variant_list_non_exhaustive(&self) -> bool {
2162 self.flags.contains(AdtFlags::IS_VARIANT_LIST_NON_EXHAUSTIVE)
2165 /// Returns the kind of the ADT.
2167 pub fn adt_kind(&self) -> AdtKind {
2170 } else if self.is_union() {
2177 /// Returns a description of this abstract data type.
2178 pub fn descr(&self) -> &'static str {
2179 match self.adt_kind() {
2180 AdtKind::Struct => "struct",
2181 AdtKind::Union => "union",
2182 AdtKind::Enum => "enum",
2186 /// Returns a description of a variant of this abstract data type.
2188 pub fn variant_descr(&self) -> &'static str {
2189 match self.adt_kind() {
2190 AdtKind::Struct => "struct",
2191 AdtKind::Union => "union",
2192 AdtKind::Enum => "variant",
2196 /// If this function returns `true`, it implies that `is_struct` must return `true`.
2198 pub fn has_ctor(&self) -> bool {
2199 self.flags.contains(AdtFlags::HAS_CTOR)
2202 /// Returns `true` if this type is `#[fundamental]` for the purposes
2203 /// of coherence checking.
2205 pub fn is_fundamental(&self) -> bool {
2206 self.flags.contains(AdtFlags::IS_FUNDAMENTAL)
2209 /// Returns `true` if this is `PhantomData<T>`.
2211 pub fn is_phantom_data(&self) -> bool {
2212 self.flags.contains(AdtFlags::IS_PHANTOM_DATA)
2215 /// Returns `true` if this is `Arc<T>`.
2216 pub fn is_arc(&self) -> bool {
2217 self.flags.contains(AdtFlags::IS_ARC)
2220 /// Returns `true` if this is `Rc<T>`.
2221 pub fn is_rc(&self) -> bool {
2222 self.flags.contains(AdtFlags::IS_RC)
2225 /// Returns `true` if this is Box<T>.
2227 pub fn is_box(&self) -> bool {
2228 self.flags.contains(AdtFlags::IS_BOX)
2231 /// Returns `true` if this type has a destructor.
2232 pub fn has_dtor(&self, tcx: TyCtxt<'tcx>) -> bool {
2233 self.destructor(tcx).is_some()
2236 /// Asserts this is a struct or union and returns its unique variant.
2237 pub fn non_enum_variant(&self) -> &VariantDef {
2238 assert!(self.is_struct() || self.is_union());
2239 &self.variants[VariantIdx::new(0)]
2243 pub fn predicates(&self, tcx: TyCtxt<'tcx>) -> GenericPredicates<'tcx> {
2244 tcx.predicates_of(self.did)
2247 /// Returns an iterator over all fields contained
2250 pub fn all_fields(&self) -> impl Iterator<Item = &FieldDef> + Clone {
2251 self.variants.iter().flat_map(|v| v.fields.iter())
2254 pub fn is_payloadfree(&self) -> bool {
2255 !self.variants.is_empty() && self.variants.iter().all(|v| v.fields.is_empty())
2258 /// Return a `VariantDef` given a variant id.
2259 pub fn variant_with_id(&self, vid: DefId) -> &VariantDef {
2260 self.variants.iter().find(|v| v.def_id == vid).expect("variant_with_id: unknown variant")
2263 /// Return a `VariantDef` given a constructor id.
2264 pub fn variant_with_ctor_id(&self, cid: DefId) -> &VariantDef {
2267 .find(|v| v.ctor_def_id == Some(cid))
2268 .expect("variant_with_ctor_id: unknown variant")
2271 /// Return the index of `VariantDef` given a variant id.
2272 pub fn variant_index_with_id(&self, vid: DefId) -> VariantIdx {
2275 .find(|(_, v)| v.def_id == vid)
2276 .expect("variant_index_with_id: unknown variant")
2280 /// Return the index of `VariantDef` given a constructor id.
2281 pub fn variant_index_with_ctor_id(&self, cid: DefId) -> VariantIdx {
2284 .find(|(_, v)| v.ctor_def_id == Some(cid))
2285 .expect("variant_index_with_ctor_id: unknown variant")
2289 pub fn variant_of_res(&self, res: Res) -> &VariantDef {
2291 Res::Def(DefKind::Variant, vid) => self.variant_with_id(vid),
2292 Res::Def(DefKind::Ctor(..), cid) => self.variant_with_ctor_id(cid),
2293 Res::Def(DefKind::Struct, _)
2294 | Res::Def(DefKind::Union, _)
2295 | Res::Def(DefKind::TyAlias, _)
2296 | Res::Def(DefKind::AssocTy, _)
2298 | Res::SelfCtor(..) => self.non_enum_variant(),
2299 _ => bug!("unexpected res {:?} in variant_of_res", res),
2304 pub fn eval_explicit_discr(&self, tcx: TyCtxt<'tcx>, expr_did: DefId) -> Option<Discr<'tcx>> {
2305 let param_env = tcx.param_env(expr_did);
2306 let repr_type = self.repr.discr_type();
2307 match tcx.const_eval_poly(expr_did) {
2309 // FIXME: Find the right type and use it instead of `val.ty` here
2310 if let Some(b) = val.try_eval_bits(tcx, param_env, val.ty) {
2311 trace!("discriminants: {} ({:?})", b, repr_type);
2312 Some(Discr { val: b, ty: val.ty })
2314 info!("invalid enum discriminant: {:#?}", val);
2315 crate::mir::interpret::struct_error(
2316 tcx.at(tcx.def_span(expr_did)),
2317 "constant evaluation of enum discriminant resulted in non-integer",
2323 Err(ErrorHandled::Reported) => {
2324 if !expr_did.is_local() {
2326 tcx.def_span(expr_did),
2327 "variant discriminant evaluation succeeded \
2328 in its crate but failed locally"
2333 Err(ErrorHandled::TooGeneric) => {
2334 span_bug!(tcx.def_span(expr_did), "enum discriminant depends on generic arguments",)
2340 pub fn discriminants(
2343 ) -> impl Iterator<Item = (VariantIdx, Discr<'tcx>)> + Captures<'tcx> {
2344 let repr_type = self.repr.discr_type();
2345 let initial = repr_type.initial_discriminant(tcx);
2346 let mut prev_discr = None::<Discr<'tcx>>;
2347 self.variants.iter_enumerated().map(move |(i, v)| {
2348 let mut discr = prev_discr.map_or(initial, |d| d.wrap_incr(tcx));
2349 if let VariantDiscr::Explicit(expr_did) = v.discr {
2350 if let Some(new_discr) = self.eval_explicit_discr(tcx, expr_did) {
2354 prev_discr = Some(discr);
2361 pub fn variant_range(&self) -> Range<VariantIdx> {
2362 (VariantIdx::new(0)..VariantIdx::new(self.variants.len()))
2365 /// Computes the discriminant value used by a specific variant.
2366 /// Unlike `discriminants`, this is (amortized) constant-time,
2367 /// only doing at most one query for evaluating an explicit
2368 /// discriminant (the last one before the requested variant),
2369 /// assuming there are no constant-evaluation errors there.
2371 pub fn discriminant_for_variant(
2374 variant_index: VariantIdx,
2376 let (val, offset) = self.discriminant_def_for_variant(variant_index);
2377 let explicit_value = val
2378 .and_then(|expr_did| self.eval_explicit_discr(tcx, expr_did))
2379 .unwrap_or_else(|| self.repr.discr_type().initial_discriminant(tcx));
2380 explicit_value.checked_add(tcx, offset as u128).0
2383 /// Yields a `DefId` for the discriminant and an offset to add to it
2384 /// Alternatively, if there is no explicit discriminant, returns the
2385 /// inferred discriminant directly.
2386 pub fn discriminant_def_for_variant(&self, variant_index: VariantIdx) -> (Option<DefId>, u32) {
2387 let mut explicit_index = variant_index.as_u32();
2390 match self.variants[VariantIdx::from_u32(explicit_index)].discr {
2391 ty::VariantDiscr::Relative(0) => {
2395 ty::VariantDiscr::Relative(distance) => {
2396 explicit_index -= distance;
2398 ty::VariantDiscr::Explicit(did) => {
2399 expr_did = Some(did);
2404 (expr_did, variant_index.as_u32() - explicit_index)
2407 pub fn destructor(&self, tcx: TyCtxt<'tcx>) -> Option<Destructor> {
2408 tcx.adt_destructor(self.did)
2411 /// Returns a list of types such that `Self: Sized` if and only
2412 /// if that type is `Sized`, or `TyErr` if this type is recursive.
2414 /// Oddly enough, checking that the sized-constraint is `Sized` is
2415 /// actually more expressive than checking all members:
2416 /// the `Sized` trait is inductive, so an associated type that references
2417 /// `Self` would prevent its containing ADT from being `Sized`.
2419 /// Due to normalization being eager, this applies even if
2420 /// the associated type is behind a pointer (e.g., issue #31299).
2421 pub fn sized_constraint(&self, tcx: TyCtxt<'tcx>) -> &'tcx [Ty<'tcx>] {
2422 tcx.adt_sized_constraint(self.did).0
2426 impl<'tcx> FieldDef {
2427 /// Returns the type of this field. The `subst` is typically obtained
2428 /// via the second field of `TyKind::AdtDef`.
2429 pub fn ty(&self, tcx: TyCtxt<'tcx>, subst: SubstsRef<'tcx>) -> Ty<'tcx> {
2430 tcx.type_of(self.did).subst(tcx, subst)
2434 /// Represents the various closure traits in the language. This
2435 /// will determine the type of the environment (`self`, in the
2436 /// desugaring) argument that the closure expects.
2438 /// You can get the environment type of a closure using
2439 /// `tcx.closure_env_ty()`.
2453 pub enum ClosureKind {
2454 // Warning: Ordering is significant here! The ordering is chosen
2455 // because the trait Fn is a subtrait of FnMut and so in turn, and
2456 // hence we order it so that Fn < FnMut < FnOnce.
2462 impl<'tcx> ClosureKind {
2463 // This is the initial value used when doing upvar inference.
2464 pub const LATTICE_BOTTOM: ClosureKind = ClosureKind::Fn;
2466 pub fn trait_did(&self, tcx: TyCtxt<'tcx>) -> DefId {
2468 ClosureKind::Fn => tcx.require_lang_item(FnTraitLangItem, None),
2469 ClosureKind::FnMut => tcx.require_lang_item(FnMutTraitLangItem, None),
2470 ClosureKind::FnOnce => tcx.require_lang_item(FnOnceTraitLangItem, None),
2474 /// Returns `true` if this a type that impls this closure kind
2475 /// must also implement `other`.
2476 pub fn extends(self, other: ty::ClosureKind) -> bool {
2477 match (self, other) {
2478 (ClosureKind::Fn, ClosureKind::Fn) => true,
2479 (ClosureKind::Fn, ClosureKind::FnMut) => true,
2480 (ClosureKind::Fn, ClosureKind::FnOnce) => true,
2481 (ClosureKind::FnMut, ClosureKind::FnMut) => true,
2482 (ClosureKind::FnMut, ClosureKind::FnOnce) => true,
2483 (ClosureKind::FnOnce, ClosureKind::FnOnce) => true,
2488 /// Returns the representative scalar type for this closure kind.
2489 /// See `TyS::to_opt_closure_kind` for more details.
2490 pub fn to_ty(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
2492 ty::ClosureKind::Fn => tcx.types.i8,
2493 ty::ClosureKind::FnMut => tcx.types.i16,
2494 ty::ClosureKind::FnOnce => tcx.types.i32,
2499 impl<'tcx> TyS<'tcx> {
2500 /// Iterator that walks `self` and any types reachable from
2501 /// `self`, in depth-first order. Note that just walks the types
2502 /// that appear in `self`, it does not descend into the fields of
2503 /// structs or variants. For example:
2506 /// isize => { isize }
2507 /// Foo<Bar<isize>> => { Foo<Bar<isize>>, Bar<isize>, isize }
2508 /// [isize] => { [isize], isize }
2510 pub fn walk(&'tcx self) -> TypeWalker<'tcx> {
2511 TypeWalker::new(self)
2514 /// Iterator that walks the immediate children of `self`. Hence
2515 /// `Foo<Bar<i32>, u32>` yields the sequence `[Bar<i32>, u32]`
2516 /// (but not `i32`, like `walk`).
2517 pub fn walk_shallow(&'tcx self) -> smallvec::IntoIter<walk::TypeWalkerArray<'tcx>> {
2518 walk::walk_shallow(self)
2521 /// Walks `ty` and any types appearing within `ty`, invoking the
2522 /// callback `f` on each type. If the callback returns `false`, then the
2523 /// children of the current type are ignored.
2525 /// Note: prefer `ty.walk()` where possible.
2526 pub fn maybe_walk<F>(&'tcx self, mut f: F)
2528 F: FnMut(Ty<'tcx>) -> bool,
2530 let mut walker = self.walk();
2531 while let Some(ty) = walker.next() {
2533 walker.skip_current_subtree();
2540 pub fn from_mutbl(m: hir::Mutability) -> BorrowKind {
2542 hir::Mutability::Mut => MutBorrow,
2543 hir::Mutability::Not => ImmBorrow,
2547 /// Returns a mutability `m` such that an `&m T` pointer could be used to obtain this borrow
2548 /// kind. Because borrow kinds are richer than mutabilities, we sometimes have to pick a
2549 /// mutability that is stronger than necessary so that it at least *would permit* the borrow in
2551 pub fn to_mutbl_lossy(self) -> hir::Mutability {
2553 MutBorrow => hir::Mutability::Mut,
2554 ImmBorrow => hir::Mutability::Not,
2556 // We have no type corresponding to a unique imm borrow, so
2557 // use `&mut`. It gives all the capabilities of an `&uniq`
2558 // and hence is a safe "over approximation".
2559 UniqueImmBorrow => hir::Mutability::Mut,
2563 pub fn to_user_str(&self) -> &'static str {
2565 MutBorrow => "mutable",
2566 ImmBorrow => "immutable",
2567 UniqueImmBorrow => "uniquely immutable",
2572 #[derive(Debug, Clone)]
2573 pub enum Attributes<'tcx> {
2574 Owned(Lrc<[ast::Attribute]>),
2575 Borrowed(&'tcx [ast::Attribute]),
2578 impl<'tcx> ::std::ops::Deref for Attributes<'tcx> {
2579 type Target = [ast::Attribute];
2581 fn deref(&self) -> &[ast::Attribute] {
2583 &Attributes::Owned(ref data) => &data,
2584 &Attributes::Borrowed(data) => data,
2589 #[derive(Debug, PartialEq, Eq)]
2590 pub enum ImplOverlapKind {
2591 /// These impls are always allowed to overlap.
2593 /// These impls are allowed to overlap, but that raises
2594 /// an issue #33140 future-compatibility warning.
2596 /// Some background: in Rust 1.0, the trait-object types `Send + Sync` (today's
2597 /// `dyn Send + Sync`) and `Sync + Send` (now `dyn Sync + Send`) were different.
2599 /// The widely-used version 0.1.0 of the crate `traitobject` had accidentally relied
2600 /// that difference, making what reduces to the following set of impls:
2604 /// impl Trait for dyn Send + Sync {}
2605 /// impl Trait for dyn Sync + Send {}
2608 /// Obviously, once we made these types be identical, that code causes a coherence
2609 /// error and a fairly big headache for us. However, luckily for us, the trait
2610 /// `Trait` used in this case is basically a marker trait, and therefore having
2611 /// overlapping impls for it is sound.
2613 /// To handle this, we basically regard the trait as a marker trait, with an additional
2614 /// future-compatibility warning. To avoid accidentally "stabilizing" this feature,
2615 /// it has the following restrictions:
2617 /// 1. The trait must indeed be a marker-like trait (i.e., no items), and must be
2619 /// 2. The trait-ref of both impls must be equal.
2620 /// 3. The trait-ref of both impls must be a trait object type consisting only of
2622 /// 4. Neither of the impls can have any where-clauses.
2624 /// Once `traitobject` 0.1.0 is no longer an active concern, this hack can be removed.
2628 impl<'tcx> TyCtxt<'tcx> {
2629 pub fn body_tables(self, body: hir::BodyId) -> &'tcx TypeckTables<'tcx> {
2630 self.typeck_tables_of(self.hir().body_owner_def_id(body))
2633 /// Returns an iterator of the `DefId`s for all body-owners in this
2634 /// crate. If you would prefer to iterate over the bodies
2635 /// themselves, you can do `self.hir().krate().body_ids.iter()`.
2636 pub fn body_owners(self) -> impl Iterator<Item = DefId> + Captures<'tcx> + 'tcx {
2641 .map(move |&body_id| self.hir().body_owner_def_id(body_id))
2644 pub fn par_body_owners<F: Fn(DefId) + sync::Sync + sync::Send>(self, f: F) {
2645 par_iter(&self.hir().krate().body_ids)
2646 .for_each(|&body_id| f(self.hir().body_owner_def_id(body_id)));
2649 pub fn provided_trait_methods(self, id: DefId) -> Vec<AssocItem> {
2650 self.associated_items(id)
2651 .filter(|item| item.kind == AssocKind::Method && item.defaultness.has_value())
2655 pub fn trait_relevant_for_never(self, did: DefId) -> bool {
2656 self.associated_items(did).any(|item| item.relevant_for_never())
2659 pub fn opt_item_name(self, def_id: DefId) -> Option<Ident> {
2660 self.hir().as_local_hir_id(def_id).and_then(|hir_id| self.hir().get(hir_id).ident())
2663 pub fn opt_associated_item(self, def_id: DefId) -> Option<AssocItem> {
2664 let is_associated_item = if let Some(hir_id) = self.hir().as_local_hir_id(def_id) {
2665 match self.hir().get(hir_id) {
2666 Node::TraitItem(_) | Node::ImplItem(_) => true,
2670 match self.def_kind(def_id).expect("no def for `DefId`") {
2671 DefKind::AssocConst | DefKind::Method | DefKind::AssocTy => true,
2676 is_associated_item.then(|| self.associated_item(def_id))
2679 pub fn field_index(self, hir_id: hir::HirId, tables: &TypeckTables<'_>) -> usize {
2680 tables.field_indices().get(hir_id).cloned().expect("no index for a field")
2683 pub fn find_field_index(self, ident: Ident, variant: &VariantDef) -> Option<usize> {
2684 variant.fields.iter().position(|field| self.hygienic_eq(ident, field.ident, variant.def_id))
2687 pub fn associated_items(self, def_id: DefId) -> AssocItemsIterator<'tcx> {
2688 // Ideally, we would use `-> impl Iterator` here, but it falls
2689 // afoul of the conservative "capture [restrictions]" we put
2690 // in place, so we use a hand-written iterator.
2692 // [restrictions]: https://github.com/rust-lang/rust/issues/34511#issuecomment-373423999
2693 AssocItemsIterator {
2695 def_ids: self.associated_item_def_ids(def_id),
2700 /// Returns `true` if the impls are the same polarity and the trait either
2701 /// has no items or is annotated #[marker] and prevents item overrides.
2702 pub fn impls_are_allowed_to_overlap(
2706 ) -> Option<ImplOverlapKind> {
2707 // If either trait impl references an error, they're allowed to overlap,
2708 // as one of them essentially doesn't exist.
2709 if self.impl_trait_ref(def_id1).map_or(false, |tr| tr.references_error())
2710 || self.impl_trait_ref(def_id2).map_or(false, |tr| tr.references_error())
2712 return Some(ImplOverlapKind::Permitted);
2715 match (self.impl_polarity(def_id1), self.impl_polarity(def_id2)) {
2716 (ImplPolarity::Reservation, _) | (_, ImplPolarity::Reservation) => {
2717 // `#[rustc_reservation_impl]` impls don't overlap with anything
2719 "impls_are_allowed_to_overlap({:?}, {:?}) = Some(Permitted) (reservations)",
2722 return Some(ImplOverlapKind::Permitted);
2724 (ImplPolarity::Positive, ImplPolarity::Negative)
2725 | (ImplPolarity::Negative, ImplPolarity::Positive) => {
2726 // `impl AutoTrait for Type` + `impl !AutoTrait for Type`
2728 "impls_are_allowed_to_overlap({:?}, {:?}) - None (differing polarities)",
2733 (ImplPolarity::Positive, ImplPolarity::Positive)
2734 | (ImplPolarity::Negative, ImplPolarity::Negative) => {}
2737 let is_marker_overlap = if self.features().overlapping_marker_traits {
2738 let trait1_is_empty = self.impl_trait_ref(def_id1).map_or(false, |trait_ref| {
2739 self.associated_item_def_ids(trait_ref.def_id).is_empty()
2741 let trait2_is_empty = self.impl_trait_ref(def_id2).map_or(false, |trait_ref| {
2742 self.associated_item_def_ids(trait_ref.def_id).is_empty()
2744 trait1_is_empty && trait2_is_empty
2746 let is_marker_impl = |def_id: DefId| -> bool {
2747 let trait_ref = self.impl_trait_ref(def_id);
2748 trait_ref.map_or(false, |tr| self.trait_def(tr.def_id).is_marker)
2750 is_marker_impl(def_id1) && is_marker_impl(def_id2)
2753 if is_marker_overlap {
2755 "impls_are_allowed_to_overlap({:?}, {:?}) = Some(Permitted) (marker overlap)",
2758 Some(ImplOverlapKind::Permitted)
2760 if let Some(self_ty1) = self.issue33140_self_ty(def_id1) {
2761 if let Some(self_ty2) = self.issue33140_self_ty(def_id2) {
2762 if self_ty1 == self_ty2 {
2764 "impls_are_allowed_to_overlap({:?}, {:?}) - issue #33140 HACK",
2767 return Some(ImplOverlapKind::Issue33140);
2770 "impls_are_allowed_to_overlap({:?}, {:?}) - found {:?} != {:?}",
2771 def_id1, def_id2, self_ty1, self_ty2
2777 debug!("impls_are_allowed_to_overlap({:?}, {:?}) = None", def_id1, def_id2);
2782 /// Returns `ty::VariantDef` if `res` refers to a struct,
2783 /// or variant or their constructors, panics otherwise.
2784 pub fn expect_variant_res(self, res: Res) -> &'tcx VariantDef {
2786 Res::Def(DefKind::Variant, did) => {
2787 let enum_did = self.parent(did).unwrap();
2788 self.adt_def(enum_did).variant_with_id(did)
2790 Res::Def(DefKind::Struct, did) | Res::Def(DefKind::Union, did) => {
2791 self.adt_def(did).non_enum_variant()
2793 Res::Def(DefKind::Ctor(CtorOf::Variant, ..), variant_ctor_did) => {
2794 let variant_did = self.parent(variant_ctor_did).unwrap();
2795 let enum_did = self.parent(variant_did).unwrap();
2796 self.adt_def(enum_did).variant_with_ctor_id(variant_ctor_did)
2798 Res::Def(DefKind::Ctor(CtorOf::Struct, ..), ctor_did) => {
2799 let struct_did = self.parent(ctor_did).expect("struct ctor has no parent");
2800 self.adt_def(struct_did).non_enum_variant()
2802 _ => bug!("expect_variant_res used with unexpected res {:?}", res),
2806 pub fn item_name(self, id: DefId) -> Symbol {
2807 if id.index == CRATE_DEF_INDEX {
2808 self.original_crate_name(id.krate)
2810 let def_key = self.def_key(id);
2811 match def_key.disambiguated_data.data {
2812 // The name of a constructor is that of its parent.
2813 hir_map::DefPathData::Ctor => {
2814 self.item_name(DefId { krate: id.krate, index: def_key.parent.unwrap() })
2816 _ => def_key.disambiguated_data.data.get_opt_name().unwrap_or_else(|| {
2817 bug!("item_name: no name for {:?}", self.def_path(id));
2823 /// Returns the possibly-auto-generated MIR of a `(DefId, Subst)` pair.
2824 pub fn instance_mir(self, instance: ty::InstanceDef<'tcx>) -> ReadOnlyBodyAndCache<'tcx, 'tcx> {
2826 ty::InstanceDef::Item(did) => self.optimized_mir(did).unwrap_read_only(),
2827 ty::InstanceDef::VtableShim(..)
2828 | ty::InstanceDef::ReifyShim(..)
2829 | ty::InstanceDef::Intrinsic(..)
2830 | ty::InstanceDef::FnPtrShim(..)
2831 | ty::InstanceDef::Virtual(..)
2832 | ty::InstanceDef::ClosureOnceShim { .. }
2833 | ty::InstanceDef::DropGlue(..)
2834 | ty::InstanceDef::CloneShim(..) => self.mir_shims(instance).unwrap_read_only(),
2838 /// Gets the attributes of a definition.
2839 pub fn get_attrs(self, did: DefId) -> Attributes<'tcx> {
2840 if let Some(id) = self.hir().as_local_hir_id(did) {
2841 Attributes::Borrowed(self.hir().attrs(id))
2843 Attributes::Owned(self.item_attrs(did))
2847 /// Determines whether an item is annotated with an attribute.
2848 pub fn has_attr(self, did: DefId, attr: Symbol) -> bool {
2849 attr::contains_name(&self.get_attrs(did), attr)
2852 /// Returns `true` if this is an `auto trait`.
2853 pub fn trait_is_auto(self, trait_def_id: DefId) -> bool {
2854 self.trait_def(trait_def_id).has_auto_impl
2857 pub fn generator_layout(self, def_id: DefId) -> &'tcx GeneratorLayout<'tcx> {
2858 self.optimized_mir(def_id).generator_layout.as_ref().unwrap()
2861 /// Given the `DefId` of an impl, returns the `DefId` of the trait it implements.
2862 /// If it implements no trait, returns `None`.
2863 pub fn trait_id_of_impl(self, def_id: DefId) -> Option<DefId> {
2864 self.impl_trait_ref(def_id).map(|tr| tr.def_id)
2867 /// If the given defid describes a method belonging to an impl, returns the
2868 /// `DefId` of the impl that the method belongs to; otherwise, returns `None`.
2869 pub fn impl_of_method(self, def_id: DefId) -> Option<DefId> {
2870 let item = if def_id.krate != LOCAL_CRATE {
2871 if let Some(DefKind::Method) = self.def_kind(def_id) {
2872 Some(self.associated_item(def_id))
2877 self.opt_associated_item(def_id)
2880 item.and_then(|trait_item| match trait_item.container {
2881 TraitContainer(_) => None,
2882 ImplContainer(def_id) => Some(def_id),
2886 /// Looks up the span of `impl_did` if the impl is local; otherwise returns `Err`
2887 /// with the name of the crate containing the impl.
2888 pub fn span_of_impl(self, impl_did: DefId) -> Result<Span, Symbol> {
2889 if impl_did.is_local() {
2890 let hir_id = self.hir().as_local_hir_id(impl_did).unwrap();
2891 Ok(self.hir().span(hir_id))
2893 Err(self.crate_name(impl_did.krate))
2897 /// Hygienically compares a use-site name (`use_name`) for a field or an associated item with
2898 /// its supposed definition name (`def_name`). The method also needs `DefId` of the supposed
2899 /// definition's parent/scope to perform comparison.
2900 pub fn hygienic_eq(self, use_name: Ident, def_name: Ident, def_parent_def_id: DefId) -> bool {
2901 // We could use `Ident::eq` here, but we deliberately don't. The name
2902 // comparison fails frequently, and we want to avoid the expensive
2903 // `modern()` calls required for the span comparison whenever possible.
2904 use_name.name == def_name.name
2908 .hygienic_eq(def_name.span.ctxt(), self.expansion_that_defined(def_parent_def_id))
2911 fn expansion_that_defined(self, scope: DefId) -> ExpnId {
2913 LOCAL_CRATE => self.hir().definitions().expansion_that_defined(scope.index),
2914 _ => ExpnId::root(),
2918 pub fn adjust_ident(self, mut ident: Ident, scope: DefId) -> Ident {
2919 ident.span.modernize_and_adjust(self.expansion_that_defined(scope));
2923 pub fn adjust_ident_and_get_scope(
2928 ) -> (Ident, DefId) {
2929 let scope = match ident.span.modernize_and_adjust(self.expansion_that_defined(scope)) {
2930 Some(actual_expansion) => {
2931 self.hir().definitions().parent_module_of_macro_def(actual_expansion)
2933 None => self.hir().get_module_parent(block),
2940 pub struct AssocItemsIterator<'tcx> {
2942 def_ids: &'tcx [DefId],
2946 impl Iterator for AssocItemsIterator<'_> {
2947 type Item = AssocItem;
2949 fn next(&mut self) -> Option<AssocItem> {
2950 let def_id = self.def_ids.get(self.next_index)?;
2951 self.next_index += 1;
2952 Some(self.tcx.associated_item(*def_id))
2956 #[derive(Clone, HashStable)]
2957 pub struct AdtSizedConstraint<'tcx>(pub &'tcx [Ty<'tcx>]);
2959 /// Yields the parent function's `DefId` if `def_id` is an `impl Trait` definition.
2960 pub fn is_impl_trait_defn(tcx: TyCtxt<'_>, def_id: DefId) -> Option<DefId> {
2961 if let Some(hir_id) = tcx.hir().as_local_hir_id(def_id) {
2962 if let Node::Item(item) = tcx.hir().get(hir_id) {
2963 if let hir::ItemKind::OpaqueTy(ref opaque_ty) = item.kind {
2964 return opaque_ty.impl_trait_fn;
2971 pub fn provide(providers: &mut ty::query::Providers<'_>) {
2972 context::provide(providers);
2973 erase_regions::provide(providers);
2974 layout::provide(providers);
2976 ty::query::Providers { trait_impls_of: trait_def::trait_impls_of_provider, ..*providers };
2979 /// A map for the local crate mapping each type to a vector of its
2980 /// inherent impls. This is not meant to be used outside of coherence;
2981 /// rather, you should request the vector for a specific type via
2982 /// `tcx.inherent_impls(def_id)` so as to minimize your dependencies
2983 /// (constructing this map requires touching the entire crate).
2984 #[derive(Clone, Debug, Default, HashStable)]
2985 pub struct CrateInherentImpls {
2986 pub inherent_impls: DefIdMap<Vec<DefId>>,
2989 #[derive(Clone, Copy, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2990 pub struct SymbolName {
2991 // FIXME: we don't rely on interning or equality here - better have
2992 // this be a `&'tcx str`.
2997 pub fn new(name: &str) -> SymbolName {
2998 SymbolName { name: Symbol::intern(name) }
3002 impl PartialOrd for SymbolName {
3003 fn partial_cmp(&self, other: &SymbolName) -> Option<Ordering> {
3004 self.name.as_str().partial_cmp(&other.name.as_str())
3008 /// Ordering must use the chars to ensure reproducible builds.
3009 impl Ord for SymbolName {
3010 fn cmp(&self, other: &SymbolName) -> Ordering {
3011 self.name.as_str().cmp(&other.name.as_str())
3015 impl fmt::Display for SymbolName {
3016 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
3017 fmt::Display::fmt(&self.name, fmt)
3021 impl fmt::Debug for SymbolName {
3022 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
3023 fmt::Display::fmt(&self.name, fmt)