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::arena::Arena;
10 use crate::hir::exports::ExportMap;
11 use crate::hir::map as hir_map;
13 use crate::ich::Fingerprint;
14 use crate::ich::StableHashingContext;
15 use crate::infer::canonical::Canonical;
16 use crate::middle::cstore::CrateStoreDyn;
17 use crate::middle::lang_items::{FnMutTraitLangItem, FnOnceTraitLangItem, FnTraitLangItem};
18 use crate::middle::resolve_lifetime::ObjectLifetimeDefault;
19 use crate::mir::interpret::ErrorHandled;
20 use crate::mir::GeneratorLayout;
21 use crate::mir::ReadOnlyBodyAndCache;
22 use crate::session::DataTypeKind;
23 use crate::traits::{self, Reveal};
25 use crate::ty::layout::VariantIdx;
26 use crate::ty::subst::{InternalSubsts, Subst, SubstsRef};
27 use crate::ty::util::{Discr, IntTypeExt};
28 use crate::ty::walk::TypeWalker;
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, 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 Arena<'tcx>, 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>();
622 .alloc_raw(size, cmp::max(mem::align_of::<T>(), mem::align_of::<usize>()));
624 let result = &mut *(mem.as_mut_ptr() as *mut List<T>);
626 result.len = slice.len();
628 // Write the elements
629 let arena_slice = slice::from_raw_parts_mut(result.data.as_mut_ptr(), result.len);
630 arena_slice.copy_from_slice(slice);
637 impl<T: fmt::Debug> fmt::Debug for List<T> {
638 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
643 impl<T: Encodable> Encodable for List<T> {
645 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
650 impl<T> Ord for List<T>
654 fn cmp(&self, other: &List<T>) -> Ordering {
655 if self == other { Ordering::Equal } else { <[T] as Ord>::cmp(&**self, &**other) }
659 impl<T> PartialOrd for List<T>
663 fn partial_cmp(&self, other: &List<T>) -> Option<Ordering> {
665 Some(Ordering::Equal)
667 <[T] as PartialOrd>::partial_cmp(&**self, &**other)
672 impl<T: PartialEq> PartialEq for List<T> {
674 fn eq(&self, other: &List<T>) -> bool {
678 impl<T: Eq> Eq for List<T> {}
680 impl<T> Hash for List<T> {
682 fn hash<H: Hasher>(&self, s: &mut H) {
683 (self as *const List<T>).hash(s)
687 impl<T> Deref for List<T> {
690 fn deref(&self) -> &[T] {
695 impl<T> AsRef<[T]> for List<T> {
697 fn as_ref(&self) -> &[T] {
698 unsafe { slice::from_raw_parts(self.data.as_ptr(), self.len) }
702 impl<'a, T> IntoIterator for &'a List<T> {
704 type IntoIter = <&'a [T] as IntoIterator>::IntoIter;
706 fn into_iter(self) -> Self::IntoIter {
711 impl<'tcx> rustc_serialize::UseSpecializedDecodable for &'tcx List<Ty<'tcx>> {}
715 pub fn empty<'a>() -> &'a List<T> {
716 #[repr(align(64), C)]
717 struct EmptySlice([u8; 64]);
718 static EMPTY_SLICE: EmptySlice = EmptySlice([0; 64]);
719 assert!(mem::align_of::<T>() <= 64);
720 unsafe { &*(&EMPTY_SLICE as *const _ as *const List<T>) }
724 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
725 pub struct UpvarPath {
726 pub hir_id: hir::HirId,
729 /// Upvars do not get their own `NodeId`. Instead, we use the pair of
730 /// the original var ID (that is, the root variable that is referenced
731 /// by the upvar) and the ID of the closure expression.
732 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
734 pub var_path: UpvarPath,
735 pub closure_expr_id: LocalDefId,
738 #[derive(Clone, PartialEq, Debug, RustcEncodable, RustcDecodable, Copy, HashStable)]
739 pub enum BorrowKind {
740 /// Data must be immutable and is aliasable.
743 /// Data must be immutable but not aliasable. This kind of borrow
744 /// cannot currently be expressed by the user and is used only in
745 /// implicit closure bindings. It is needed when the closure
746 /// is borrowing or mutating a mutable referent, e.g.:
748 /// let x: &mut isize = ...;
749 /// let y = || *x += 5;
751 /// If we were to try to translate this closure into a more explicit
752 /// form, we'd encounter an error with the code as written:
754 /// struct Env { x: & &mut isize }
755 /// let x: &mut isize = ...;
756 /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
757 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
759 /// This is then illegal because you cannot mutate a `&mut` found
760 /// in an aliasable location. To solve, you'd have to translate with
761 /// an `&mut` borrow:
763 /// struct Env { x: & &mut isize }
764 /// let x: &mut isize = ...;
765 /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
766 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
768 /// Now the assignment to `**env.x` is legal, but creating a
769 /// mutable pointer to `x` is not because `x` is not mutable. We
770 /// could fix this by declaring `x` as `let mut x`. This is ok in
771 /// user code, if awkward, but extra weird for closures, since the
772 /// borrow is hidden.
774 /// So we introduce a "unique imm" borrow -- the referent is
775 /// immutable, but not aliasable. This solves the problem. For
776 /// simplicity, we don't give users the way to express this
777 /// borrow, it's just used when translating closures.
780 /// Data is mutable and not aliasable.
784 /// Information describing the capture of an upvar. This is computed
785 /// during `typeck`, specifically by `regionck`.
786 #[derive(PartialEq, Clone, Debug, Copy, RustcEncodable, RustcDecodable, HashStable)]
787 pub enum UpvarCapture<'tcx> {
788 /// Upvar is captured by value. This is always true when the
789 /// closure is labeled `move`, but can also be true in other cases
790 /// depending on inference.
793 /// Upvar is captured by reference.
794 ByRef(UpvarBorrow<'tcx>),
797 #[derive(PartialEq, Clone, Copy, RustcEncodable, RustcDecodable, HashStable)]
798 pub struct UpvarBorrow<'tcx> {
799 /// The kind of borrow: by-ref upvars have access to shared
800 /// immutable borrows, which are not part of the normal language
802 pub kind: BorrowKind,
804 /// Region of the resulting reference.
805 pub region: ty::Region<'tcx>,
808 pub type UpvarListMap = FxHashMap<DefId, FxIndexMap<hir::HirId, UpvarId>>;
809 pub type UpvarCaptureMap<'tcx> = FxHashMap<UpvarId, UpvarCapture<'tcx>>;
811 #[derive(Clone, Copy, PartialEq, Eq)]
812 pub enum IntVarValue {
814 UintType(ast::UintTy),
817 #[derive(Clone, Copy, PartialEq, Eq)]
818 pub struct FloatVarValue(pub ast::FloatTy);
820 impl ty::EarlyBoundRegion {
821 pub fn to_bound_region(&self) -> ty::BoundRegion {
822 ty::BoundRegion::BrNamed(self.def_id, self.name)
825 /// Does this early bound region have a name? Early bound regions normally
826 /// always have names except when using anonymous lifetimes (`'_`).
827 pub fn has_name(&self) -> bool {
828 self.name != kw::UnderscoreLifetime
832 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
833 pub enum GenericParamDefKind {
837 object_lifetime_default: ObjectLifetimeDefault,
838 synthetic: Option<hir::SyntheticTyParamKind>,
843 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable)]
844 pub struct GenericParamDef {
849 /// `pure_wrt_drop`, set by the (unsafe) `#[may_dangle]` attribute
850 /// on generic parameter `'a`/`T`, asserts data behind the parameter
851 /// `'a`/`T` won't be accessed during the parent type's `Drop` impl.
852 pub pure_wrt_drop: bool,
854 pub kind: GenericParamDefKind,
857 impl GenericParamDef {
858 pub fn to_early_bound_region_data(&self) -> ty::EarlyBoundRegion {
859 if let GenericParamDefKind::Lifetime = self.kind {
860 ty::EarlyBoundRegion { def_id: self.def_id, index: self.index, name: self.name }
862 bug!("cannot convert a non-lifetime parameter def to an early bound region")
866 pub fn to_bound_region(&self) -> ty::BoundRegion {
867 if let GenericParamDefKind::Lifetime = self.kind {
868 self.to_early_bound_region_data().to_bound_region()
870 bug!("cannot convert a non-lifetime parameter def to an early bound region")
876 pub struct GenericParamCount {
877 pub lifetimes: usize,
882 /// Information about the formal type/lifetime parameters associated
883 /// with an item or method. Analogous to `hir::Generics`.
885 /// The ordering of parameters is the same as in `Subst` (excluding child generics):
886 /// `Self` (optionally), `Lifetime` params..., `Type` params...
887 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
888 pub struct Generics {
889 pub parent: Option<DefId>,
890 pub parent_count: usize,
891 pub params: Vec<GenericParamDef>,
893 /// Reverse map to the `index` field of each `GenericParamDef`.
894 #[stable_hasher(ignore)]
895 pub param_def_id_to_index: FxHashMap<DefId, u32>,
898 pub has_late_bound_regions: Option<Span>,
901 impl<'tcx> Generics {
902 pub fn count(&self) -> usize {
903 self.parent_count + self.params.len()
906 pub fn own_counts(&self) -> GenericParamCount {
907 // We could cache this as a property of `GenericParamCount`, but
908 // the aim is to refactor this away entirely eventually and the
909 // presence of this method will be a constant reminder.
910 let mut own_counts: GenericParamCount = Default::default();
912 for param in &self.params {
914 GenericParamDefKind::Lifetime => own_counts.lifetimes += 1,
915 GenericParamDefKind::Type { .. } => own_counts.types += 1,
916 GenericParamDefKind::Const => own_counts.consts += 1,
923 pub fn requires_monomorphization(&self, tcx: TyCtxt<'tcx>) -> bool {
924 if self.own_requires_monomorphization() {
928 if let Some(parent_def_id) = self.parent {
929 let parent = tcx.generics_of(parent_def_id);
930 parent.requires_monomorphization(tcx)
936 pub fn own_requires_monomorphization(&self) -> bool {
937 for param in &self.params {
939 GenericParamDefKind::Type { .. } | GenericParamDefKind::Const => return true,
940 GenericParamDefKind::Lifetime => {}
948 param: &EarlyBoundRegion,
950 ) -> &'tcx GenericParamDef {
951 if let Some(index) = param.index.checked_sub(self.parent_count as u32) {
952 let param = &self.params[index as usize];
954 GenericParamDefKind::Lifetime => param,
955 _ => bug!("expected lifetime parameter, but found another generic parameter"),
958 tcx.generics_of(self.parent.expect("parent_count > 0 but no parent?"))
959 .region_param(param, tcx)
963 /// Returns the `GenericParamDef` associated with this `ParamTy`.
964 pub fn type_param(&'tcx self, param: &ParamTy, tcx: TyCtxt<'tcx>) -> &'tcx GenericParamDef {
965 if let Some(index) = param.index.checked_sub(self.parent_count as u32) {
966 let param = &self.params[index as usize];
968 GenericParamDefKind::Type { .. } => param,
969 _ => bug!("expected type parameter, but found another generic parameter"),
972 tcx.generics_of(self.parent.expect("parent_count > 0 but no parent?"))
973 .type_param(param, tcx)
977 /// Returns the `ConstParameterDef` associated with this `ParamConst`.
978 pub fn const_param(&'tcx self, param: &ParamConst, tcx: TyCtxt<'tcx>) -> &GenericParamDef {
979 if let Some(index) = param.index.checked_sub(self.parent_count as u32) {
980 let param = &self.params[index as usize];
982 GenericParamDefKind::Const => param,
983 _ => bug!("expected const parameter, but found another generic parameter"),
986 tcx.generics_of(self.parent.expect("parent_count>0 but no parent?"))
987 .const_param(param, tcx)
992 /// Bounds on generics.
993 #[derive(Copy, Clone, Default, Debug, RustcEncodable, RustcDecodable, HashStable)]
994 pub struct GenericPredicates<'tcx> {
995 pub parent: Option<DefId>,
996 pub predicates: &'tcx [(Predicate<'tcx>, Span)],
999 impl<'tcx> GenericPredicates<'tcx> {
1003 substs: SubstsRef<'tcx>,
1004 ) -> InstantiatedPredicates<'tcx> {
1005 let mut instantiated = InstantiatedPredicates::empty();
1006 self.instantiate_into(tcx, &mut instantiated, substs);
1010 pub fn instantiate_own(
1013 substs: SubstsRef<'tcx>,
1014 ) -> InstantiatedPredicates<'tcx> {
1015 InstantiatedPredicates {
1016 predicates: self.predicates.iter().map(|(p, _)| p.subst(tcx, substs)).collect(),
1020 fn instantiate_into(
1023 instantiated: &mut InstantiatedPredicates<'tcx>,
1024 substs: SubstsRef<'tcx>,
1026 if let Some(def_id) = self.parent {
1027 tcx.predicates_of(def_id).instantiate_into(tcx, instantiated, substs);
1029 instantiated.predicates.extend(self.predicates.iter().map(|(p, _)| p.subst(tcx, substs)));
1032 pub fn instantiate_identity(&self, tcx: TyCtxt<'tcx>) -> InstantiatedPredicates<'tcx> {
1033 let mut instantiated = InstantiatedPredicates::empty();
1034 self.instantiate_identity_into(tcx, &mut instantiated);
1038 fn instantiate_identity_into(
1041 instantiated: &mut InstantiatedPredicates<'tcx>,
1043 if let Some(def_id) = self.parent {
1044 tcx.predicates_of(def_id).instantiate_identity_into(tcx, instantiated);
1046 instantiated.predicates.extend(self.predicates.iter().map(|&(p, _)| p))
1049 pub fn instantiate_supertrait(
1052 poly_trait_ref: &ty::PolyTraitRef<'tcx>,
1053 ) -> InstantiatedPredicates<'tcx> {
1054 assert_eq!(self.parent, None);
1055 InstantiatedPredicates {
1059 .map(|(pred, _)| pred.subst_supertrait(tcx, poly_trait_ref))
1065 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1066 #[derive(HashStable, TypeFoldable)]
1067 pub enum Predicate<'tcx> {
1068 /// Corresponds to `where Foo: Bar<A, B, C>`. `Foo` here would be
1069 /// the `Self` type of the trait reference and `A`, `B`, and `C`
1070 /// would be the type parameters.
1071 Trait(PolyTraitPredicate<'tcx>),
1074 RegionOutlives(PolyRegionOutlivesPredicate<'tcx>),
1077 TypeOutlives(PolyTypeOutlivesPredicate<'tcx>),
1079 /// `where <T as TraitRef>::Name == X`, approximately.
1080 /// See the `ProjectionPredicate` struct for details.
1081 Projection(PolyProjectionPredicate<'tcx>),
1083 /// No syntax: `T` well-formed.
1084 WellFormed(Ty<'tcx>),
1086 /// Trait must be object-safe.
1089 /// No direct syntax. May be thought of as `where T: FnFoo<...>`
1090 /// for some substitutions `...` and `T` being a closure type.
1091 /// Satisfied (or refuted) once we know the closure's kind.
1092 ClosureKind(DefId, SubstsRef<'tcx>, ClosureKind),
1095 Subtype(PolySubtypePredicate<'tcx>),
1097 /// Constant initializer must evaluate successfully.
1098 ConstEvaluatable(DefId, SubstsRef<'tcx>),
1101 /// The crate outlives map is computed during typeck and contains the
1102 /// outlives of every item in the local crate. You should not use it
1103 /// directly, because to do so will make your pass dependent on the
1104 /// HIR of every item in the local crate. Instead, use
1105 /// `tcx.inferred_outlives_of()` to get the outlives for a *particular*
1107 #[derive(HashStable)]
1108 pub struct CratePredicatesMap<'tcx> {
1109 /// For each struct with outlive bounds, maps to a vector of the
1110 /// predicate of its outlive bounds. If an item has no outlives
1111 /// bounds, it will have no entry.
1112 pub predicates: FxHashMap<DefId, &'tcx [(ty::Predicate<'tcx>, Span)]>,
1115 impl<'tcx> AsRef<Predicate<'tcx>> for Predicate<'tcx> {
1116 fn as_ref(&self) -> &Predicate<'tcx> {
1121 impl<'tcx> Predicate<'tcx> {
1122 /// Performs a substitution suitable for going from a
1123 /// poly-trait-ref to supertraits that must hold if that
1124 /// poly-trait-ref holds. This is slightly different from a normal
1125 /// substitution in terms of what happens with bound regions. See
1126 /// lengthy comment below for details.
1127 pub fn subst_supertrait(
1130 trait_ref: &ty::PolyTraitRef<'tcx>,
1131 ) -> ty::Predicate<'tcx> {
1132 // The interaction between HRTB and supertraits is not entirely
1133 // obvious. Let me walk you (and myself) through an example.
1135 // Let's start with an easy case. Consider two traits:
1137 // trait Foo<'a>: Bar<'a,'a> { }
1138 // trait Bar<'b,'c> { }
1140 // Now, if we have a trait reference `for<'x> T: Foo<'x>`, then
1141 // we can deduce that `for<'x> T: Bar<'x,'x>`. Basically, if we
1142 // knew that `Foo<'x>` (for any 'x) then we also know that
1143 // `Bar<'x,'x>` (for any 'x). This more-or-less falls out from
1144 // normal substitution.
1146 // In terms of why this is sound, the idea is that whenever there
1147 // is an impl of `T:Foo<'a>`, it must show that `T:Bar<'a,'a>`
1148 // holds. So if there is an impl of `T:Foo<'a>` that applies to
1149 // all `'a`, then we must know that `T:Bar<'a,'a>` holds for all
1152 // Another example to be careful of is this:
1154 // trait Foo1<'a>: for<'b> Bar1<'a,'b> { }
1155 // trait Bar1<'b,'c> { }
1157 // Here, if we have `for<'x> T: Foo1<'x>`, then what do we know?
1158 // The answer is that we know `for<'x,'b> T: Bar1<'x,'b>`. The
1159 // reason is similar to the previous example: any impl of
1160 // `T:Foo1<'x>` must show that `for<'b> T: Bar1<'x, 'b>`. So
1161 // basically we would want to collapse the bound lifetimes from
1162 // the input (`trait_ref`) and the supertraits.
1164 // To achieve this in practice is fairly straightforward. Let's
1165 // consider the more complicated scenario:
1167 // - We start out with `for<'x> T: Foo1<'x>`. In this case, `'x`
1168 // has a De Bruijn index of 1. We want to produce `for<'x,'b> T: Bar1<'x,'b>`,
1169 // where both `'x` and `'b` would have a DB index of 1.
1170 // The substitution from the input trait-ref is therefore going to be
1171 // `'a => 'x` (where `'x` has a DB index of 1).
1172 // - The super-trait-ref is `for<'b> Bar1<'a,'b>`, where `'a` is an
1173 // early-bound parameter and `'b' is a late-bound parameter with a
1175 // - If we replace `'a` with `'x` from the input, it too will have
1176 // a DB index of 1, and thus we'll have `for<'x,'b> Bar1<'x,'b>`
1177 // just as we wanted.
1179 // There is only one catch. If we just apply the substitution `'a
1180 // => 'x` to `for<'b> Bar1<'a,'b>`, the substitution code will
1181 // adjust the DB index because we substituting into a binder (it
1182 // tries to be so smart...) resulting in `for<'x> for<'b>
1183 // Bar1<'x,'b>` (we have no syntax for this, so use your
1184 // imagination). Basically the 'x will have DB index of 2 and 'b
1185 // will have DB index of 1. Not quite what we want. So we apply
1186 // the substitution to the *contents* of the trait reference,
1187 // rather than the trait reference itself (put another way, the
1188 // substitution code expects equal binding levels in the values
1189 // from the substitution and the value being substituted into, and
1190 // this trick achieves that).
1192 let substs = &trait_ref.skip_binder().substs;
1194 Predicate::Trait(ref binder) => {
1195 Predicate::Trait(binder.map_bound(|data| data.subst(tcx, substs)))
1197 Predicate::Subtype(ref binder) => {
1198 Predicate::Subtype(binder.map_bound(|data| data.subst(tcx, substs)))
1200 Predicate::RegionOutlives(ref binder) => {
1201 Predicate::RegionOutlives(binder.map_bound(|data| data.subst(tcx, substs)))
1203 Predicate::TypeOutlives(ref binder) => {
1204 Predicate::TypeOutlives(binder.map_bound(|data| data.subst(tcx, substs)))
1206 Predicate::Projection(ref binder) => {
1207 Predicate::Projection(binder.map_bound(|data| data.subst(tcx, substs)))
1209 Predicate::WellFormed(data) => Predicate::WellFormed(data.subst(tcx, substs)),
1210 Predicate::ObjectSafe(trait_def_id) => Predicate::ObjectSafe(trait_def_id),
1211 Predicate::ClosureKind(closure_def_id, closure_substs, kind) => {
1212 Predicate::ClosureKind(closure_def_id, closure_substs.subst(tcx, substs), kind)
1214 Predicate::ConstEvaluatable(def_id, const_substs) => {
1215 Predicate::ConstEvaluatable(def_id, const_substs.subst(tcx, substs))
1221 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1222 #[derive(HashStable, TypeFoldable)]
1223 pub struct TraitPredicate<'tcx> {
1224 pub trait_ref: TraitRef<'tcx>,
1227 pub type PolyTraitPredicate<'tcx> = ty::Binder<TraitPredicate<'tcx>>;
1229 impl<'tcx> TraitPredicate<'tcx> {
1230 pub fn def_id(&self) -> DefId {
1231 self.trait_ref.def_id
1234 pub fn input_types<'a>(&'a self) -> impl DoubleEndedIterator<Item = Ty<'tcx>> + 'a {
1235 self.trait_ref.input_types()
1238 pub fn self_ty(&self) -> Ty<'tcx> {
1239 self.trait_ref.self_ty()
1243 impl<'tcx> PolyTraitPredicate<'tcx> {
1244 pub fn def_id(&self) -> DefId {
1245 // Ok to skip binder since trait `DefId` does not care about regions.
1246 self.skip_binder().def_id()
1250 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, RustcEncodable, RustcDecodable)]
1251 #[derive(HashStable, TypeFoldable)]
1252 pub struct OutlivesPredicate<A, B>(pub A, pub B); // `A: B`
1253 pub type PolyOutlivesPredicate<A, B> = ty::Binder<OutlivesPredicate<A, B>>;
1254 pub type RegionOutlivesPredicate<'tcx> = OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>;
1255 pub type TypeOutlivesPredicate<'tcx> = OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>;
1256 pub type PolyRegionOutlivesPredicate<'tcx> = ty::Binder<RegionOutlivesPredicate<'tcx>>;
1257 pub type PolyTypeOutlivesPredicate<'tcx> = ty::Binder<TypeOutlivesPredicate<'tcx>>;
1259 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
1260 #[derive(HashStable, TypeFoldable)]
1261 pub struct SubtypePredicate<'tcx> {
1262 pub a_is_expected: bool,
1266 pub type PolySubtypePredicate<'tcx> = ty::Binder<SubtypePredicate<'tcx>>;
1268 /// This kind of predicate has no *direct* correspondent in the
1269 /// syntax, but it roughly corresponds to the syntactic forms:
1271 /// 1. `T: TraitRef<..., Item = Type>`
1272 /// 2. `<T as TraitRef<...>>::Item == Type` (NYI)
1274 /// In particular, form #1 is "desugared" to the combination of a
1275 /// normal trait predicate (`T: TraitRef<...>`) and one of these
1276 /// predicates. Form #2 is a broader form in that it also permits
1277 /// equality between arbitrary types. Processing an instance of
1278 /// Form #2 eventually yields one of these `ProjectionPredicate`
1279 /// instances to normalize the LHS.
1280 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1281 #[derive(HashStable, TypeFoldable)]
1282 pub struct ProjectionPredicate<'tcx> {
1283 pub projection_ty: ProjectionTy<'tcx>,
1287 pub type PolyProjectionPredicate<'tcx> = Binder<ProjectionPredicate<'tcx>>;
1289 impl<'tcx> PolyProjectionPredicate<'tcx> {
1290 /// Returns the `DefId` of the associated item being projected.
1291 pub fn item_def_id(&self) -> DefId {
1292 self.skip_binder().projection_ty.item_def_id
1296 pub fn to_poly_trait_ref(&self, tcx: TyCtxt<'tcx>) -> PolyTraitRef<'tcx> {
1297 // Note: unlike with `TraitRef::to_poly_trait_ref()`,
1298 // `self.0.trait_ref` is permitted to have escaping regions.
1299 // This is because here `self` has a `Binder` and so does our
1300 // return value, so we are preserving the number of binding
1302 self.map_bound(|predicate| predicate.projection_ty.trait_ref(tcx))
1305 pub fn ty(&self) -> Binder<Ty<'tcx>> {
1306 self.map_bound(|predicate| predicate.ty)
1309 /// The `DefId` of the `TraitItem` for the associated type.
1311 /// Note that this is not the `DefId` of the `TraitRef` containing this
1312 /// associated type, which is in `tcx.associated_item(projection_def_id()).container`.
1313 pub fn projection_def_id(&self) -> DefId {
1314 // Ok to skip binder since trait `DefId` does not care about regions.
1315 self.skip_binder().projection_ty.item_def_id
1319 pub trait ToPolyTraitRef<'tcx> {
1320 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx>;
1323 impl<'tcx> ToPolyTraitRef<'tcx> for TraitRef<'tcx> {
1324 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
1325 ty::Binder::dummy(self.clone())
1329 impl<'tcx> ToPolyTraitRef<'tcx> for PolyTraitPredicate<'tcx> {
1330 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
1331 self.map_bound_ref(|trait_pred| trait_pred.trait_ref)
1335 pub trait ToPredicate<'tcx> {
1336 fn to_predicate(&self) -> Predicate<'tcx>;
1339 impl<'tcx> ToPredicate<'tcx> for TraitRef<'tcx> {
1340 fn to_predicate(&self) -> Predicate<'tcx> {
1341 ty::Predicate::Trait(ty::Binder::dummy(ty::TraitPredicate { trait_ref: self.clone() }))
1345 impl<'tcx> ToPredicate<'tcx> for PolyTraitRef<'tcx> {
1346 fn to_predicate(&self) -> Predicate<'tcx> {
1347 ty::Predicate::Trait(self.to_poly_trait_predicate())
1351 impl<'tcx> ToPredicate<'tcx> for PolyRegionOutlivesPredicate<'tcx> {
1352 fn to_predicate(&self) -> Predicate<'tcx> {
1353 Predicate::RegionOutlives(self.clone())
1357 impl<'tcx> ToPredicate<'tcx> for PolyTypeOutlivesPredicate<'tcx> {
1358 fn to_predicate(&self) -> Predicate<'tcx> {
1359 Predicate::TypeOutlives(self.clone())
1363 impl<'tcx> ToPredicate<'tcx> for PolyProjectionPredicate<'tcx> {
1364 fn to_predicate(&self) -> Predicate<'tcx> {
1365 Predicate::Projection(self.clone())
1369 // A custom iterator used by `Predicate::walk_tys`.
1370 enum WalkTysIter<'tcx, I, J, K>
1372 I: Iterator<Item = Ty<'tcx>>,
1373 J: Iterator<Item = Ty<'tcx>>,
1374 K: Iterator<Item = Ty<'tcx>>,
1378 Two(Ty<'tcx>, Ty<'tcx>),
1384 impl<'tcx, I, J, K> Iterator for WalkTysIter<'tcx, I, J, K>
1386 I: Iterator<Item = Ty<'tcx>>,
1387 J: Iterator<Item = Ty<'tcx>>,
1388 K: Iterator<Item = Ty<'tcx>>,
1390 type Item = Ty<'tcx>;
1392 fn next(&mut self) -> Option<Ty<'tcx>> {
1394 WalkTysIter::None => None,
1395 WalkTysIter::One(item) => {
1396 *self = WalkTysIter::None;
1399 WalkTysIter::Two(item1, item2) => {
1400 *self = WalkTysIter::One(item2);
1403 WalkTysIter::Types(ref mut iter) => iter.next(),
1404 WalkTysIter::InputTypes(ref mut iter) => iter.next(),
1405 WalkTysIter::ProjectionTypes(ref mut iter) => iter.next(),
1410 impl<'tcx> Predicate<'tcx> {
1411 /// Iterates over the types in this predicate. Note that in all
1412 /// cases this is skipping over a binder, so late-bound regions
1413 /// with depth 0 are bound by the predicate.
1414 pub fn walk_tys(&'a self) -> impl Iterator<Item = Ty<'tcx>> + 'a {
1416 ty::Predicate::Trait(ref data) => {
1417 WalkTysIter::InputTypes(data.skip_binder().input_types())
1419 ty::Predicate::Subtype(binder) => {
1420 let SubtypePredicate { a, b, a_is_expected: _ } = binder.skip_binder();
1421 WalkTysIter::Two(a, b)
1423 ty::Predicate::TypeOutlives(binder) => WalkTysIter::One(binder.skip_binder().0),
1424 ty::Predicate::RegionOutlives(..) => WalkTysIter::None,
1425 ty::Predicate::Projection(ref data) => {
1426 let inner = data.skip_binder();
1427 WalkTysIter::ProjectionTypes(
1428 inner.projection_ty.substs.types().chain(Some(inner.ty)),
1431 ty::Predicate::WellFormed(data) => WalkTysIter::One(data),
1432 ty::Predicate::ObjectSafe(_trait_def_id) => WalkTysIter::None,
1433 ty::Predicate::ClosureKind(_closure_def_id, closure_substs, _kind) => {
1434 WalkTysIter::Types(closure_substs.types())
1436 ty::Predicate::ConstEvaluatable(_, substs) => WalkTysIter::Types(substs.types()),
1440 pub fn to_opt_poly_trait_ref(&self) -> Option<PolyTraitRef<'tcx>> {
1442 Predicate::Trait(ref t) => Some(t.to_poly_trait_ref()),
1443 Predicate::Projection(..)
1444 | Predicate::Subtype(..)
1445 | Predicate::RegionOutlives(..)
1446 | Predicate::WellFormed(..)
1447 | Predicate::ObjectSafe(..)
1448 | Predicate::ClosureKind(..)
1449 | Predicate::TypeOutlives(..)
1450 | Predicate::ConstEvaluatable(..) => None,
1454 pub fn to_opt_type_outlives(&self) -> Option<PolyTypeOutlivesPredicate<'tcx>> {
1456 Predicate::TypeOutlives(data) => Some(data),
1457 Predicate::Trait(..)
1458 | Predicate::Projection(..)
1459 | Predicate::Subtype(..)
1460 | Predicate::RegionOutlives(..)
1461 | Predicate::WellFormed(..)
1462 | Predicate::ObjectSafe(..)
1463 | Predicate::ClosureKind(..)
1464 | Predicate::ConstEvaluatable(..) => None,
1469 /// Represents the bounds declared on a particular set of type
1470 /// parameters. Should eventually be generalized into a flag list of
1471 /// where-clauses. You can obtain a `InstantiatedPredicates` list from a
1472 /// `GenericPredicates` by using the `instantiate` method. Note that this method
1473 /// reflects an important semantic invariant of `InstantiatedPredicates`: while
1474 /// the `GenericPredicates` are expressed in terms of the bound type
1475 /// parameters of the impl/trait/whatever, an `InstantiatedPredicates` instance
1476 /// represented a set of bounds for some particular instantiation,
1477 /// meaning that the generic parameters have been substituted with
1482 /// struct Foo<T, U: Bar<T>> { ... }
1484 /// Here, the `GenericPredicates` for `Foo` would contain a list of bounds like
1485 /// `[[], [U:Bar<T>]]`. Now if there were some particular reference
1486 /// like `Foo<isize,usize>`, then the `InstantiatedPredicates` would be `[[],
1487 /// [usize:Bar<isize>]]`.
1488 #[derive(Clone, Debug, TypeFoldable)]
1489 pub struct InstantiatedPredicates<'tcx> {
1490 pub predicates: Vec<Predicate<'tcx>>,
1493 impl<'tcx> InstantiatedPredicates<'tcx> {
1494 pub fn empty() -> InstantiatedPredicates<'tcx> {
1495 InstantiatedPredicates { predicates: vec![] }
1498 pub fn is_empty(&self) -> bool {
1499 self.predicates.is_empty()
1503 rustc_index::newtype_index! {
1504 /// "Universes" are used during type- and trait-checking in the
1505 /// presence of `for<..>` binders to control what sets of names are
1506 /// visible. Universes are arranged into a tree: the root universe
1507 /// contains names that are always visible. Each child then adds a new
1508 /// set of names that are visible, in addition to those of its parent.
1509 /// We say that the child universe "extends" the parent universe with
1512 /// To make this more concrete, consider this program:
1516 /// fn bar<T>(x: T) {
1517 /// let y: for<'a> fn(&'a u8, Foo) = ...;
1521 /// The struct name `Foo` is in the root universe U0. But the type
1522 /// parameter `T`, introduced on `bar`, is in an extended universe U1
1523 /// -- i.e., within `bar`, we can name both `T` and `Foo`, but outside
1524 /// of `bar`, we cannot name `T`. Then, within the type of `y`, the
1525 /// region `'a` is in a universe U2 that extends U1, because we can
1526 /// name it inside the fn type but not outside.
1528 /// Universes are used to do type- and trait-checking around these
1529 /// "forall" binders (also called **universal quantification**). The
1530 /// idea is that when, in the body of `bar`, we refer to `T` as a
1531 /// type, we aren't referring to any type in particular, but rather a
1532 /// kind of "fresh" type that is distinct from all other types we have
1533 /// actually declared. This is called a **placeholder** type, and we
1534 /// use universes to talk about this. In other words, a type name in
1535 /// universe 0 always corresponds to some "ground" type that the user
1536 /// declared, but a type name in a non-zero universe is a placeholder
1537 /// type -- an idealized representative of "types in general" that we
1538 /// use for checking generic functions.
1539 pub struct UniverseIndex {
1541 DEBUG_FORMAT = "U{}",
1545 impl UniverseIndex {
1546 pub const ROOT: UniverseIndex = UniverseIndex::from_u32_const(0);
1548 /// Returns the "next" universe index in order -- this new index
1549 /// is considered to extend all previous universes. This
1550 /// corresponds to entering a `forall` quantifier. So, for
1551 /// example, suppose we have this type in universe `U`:
1554 /// for<'a> fn(&'a u32)
1557 /// Once we "enter" into this `for<'a>` quantifier, we are in a
1558 /// new universe that extends `U` -- in this new universe, we can
1559 /// name the region `'a`, but that region was not nameable from
1560 /// `U` because it was not in scope there.
1561 pub fn next_universe(self) -> UniverseIndex {
1562 UniverseIndex::from_u32(self.private.checked_add(1).unwrap())
1565 /// Returns `true` if `self` can name a name from `other` -- in other words,
1566 /// if the set of names in `self` is a superset of those in
1567 /// `other` (`self >= other`).
1568 pub fn can_name(self, other: UniverseIndex) -> bool {
1569 self.private >= other.private
1572 /// Returns `true` if `self` cannot name some names from `other` -- in other
1573 /// words, if the set of names in `self` is a strict subset of
1574 /// those in `other` (`self < other`).
1575 pub fn cannot_name(self, other: UniverseIndex) -> bool {
1576 self.private < other.private
1580 /// The "placeholder index" fully defines a placeholder region.
1581 /// Placeholder regions are identified by both a **universe** as well
1582 /// as a "bound-region" within that universe. The `bound_region` is
1583 /// basically a name -- distinct bound regions within the same
1584 /// universe are just two regions with an unknown relationship to one
1586 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, PartialOrd, Ord)]
1587 pub struct Placeholder<T> {
1588 pub universe: UniverseIndex,
1592 impl<'a, T> HashStable<StableHashingContext<'a>> for Placeholder<T>
1594 T: HashStable<StableHashingContext<'a>>,
1596 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
1597 self.universe.hash_stable(hcx, hasher);
1598 self.name.hash_stable(hcx, hasher);
1602 pub type PlaceholderRegion = Placeholder<BoundRegion>;
1604 pub type PlaceholderType = Placeholder<BoundVar>;
1606 pub type PlaceholderConst = Placeholder<BoundVar>;
1608 /// When type checking, we use the `ParamEnv` to track
1609 /// details about the set of where-clauses that are in scope at this
1610 /// particular point.
1611 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable, TypeFoldable)]
1612 pub struct ParamEnv<'tcx> {
1613 /// `Obligation`s that the caller must satisfy. This is basically
1614 /// the set of bounds on the in-scope type parameters, translated
1615 /// into `Obligation`s, and elaborated and normalized.
1616 pub caller_bounds: &'tcx List<ty::Predicate<'tcx>>,
1618 /// Typically, this is `Reveal::UserFacing`, but during codegen we
1619 /// want `Reveal::All` -- note that this is always paired with an
1620 /// empty environment. To get that, use `ParamEnv::reveal()`.
1621 pub reveal: traits::Reveal,
1623 /// If this `ParamEnv` comes from a call to `tcx.param_env(def_id)`,
1624 /// register that `def_id` (useful for transitioning to the chalk trait
1626 pub def_id: Option<DefId>,
1629 impl<'tcx> ParamEnv<'tcx> {
1630 /// Construct a trait environment suitable for contexts where
1631 /// there are no where-clauses in scope. Hidden types (like `impl
1632 /// Trait`) are left hidden, so this is suitable for ordinary
1635 pub fn empty() -> Self {
1636 Self::new(List::empty(), Reveal::UserFacing, None)
1639 /// Construct a trait environment with no where-clauses in scope
1640 /// where the values of all `impl Trait` and other hidden types
1641 /// are revealed. This is suitable for monomorphized, post-typeck
1642 /// environments like codegen or doing optimizations.
1644 /// N.B., if you want to have predicates in scope, use `ParamEnv::new`,
1645 /// or invoke `param_env.with_reveal_all()`.
1647 pub fn reveal_all() -> Self {
1648 Self::new(List::empty(), Reveal::All, None)
1651 /// Construct a trait environment with the given set of predicates.
1654 caller_bounds: &'tcx List<ty::Predicate<'tcx>>,
1656 def_id: Option<DefId>,
1658 ty::ParamEnv { caller_bounds, reveal, def_id }
1661 /// Returns a new parameter environment with the same clauses, but
1662 /// which "reveals" the true results of projections in all cases
1663 /// (even for associated types that are specializable). This is
1664 /// the desired behavior during codegen and certain other special
1665 /// contexts; normally though we want to use `Reveal::UserFacing`,
1666 /// which is the default.
1667 pub fn with_reveal_all(self) -> Self {
1668 ty::ParamEnv { reveal: Reveal::All, ..self }
1671 /// Returns this same environment but with no caller bounds.
1672 pub fn without_caller_bounds(self) -> Self {
1673 ty::ParamEnv { caller_bounds: List::empty(), ..self }
1676 /// Creates a suitable environment in which to perform trait
1677 /// queries on the given value. When type-checking, this is simply
1678 /// the pair of the environment plus value. But when reveal is set to
1679 /// All, then if `value` does not reference any type parameters, we will
1680 /// pair it with the empty environment. This improves caching and is generally
1683 /// N.B., we preserve the environment when type-checking because it
1684 /// is possible for the user to have wacky where-clauses like
1685 /// `where Box<u32>: Copy`, which are clearly never
1686 /// satisfiable. We generally want to behave as if they were true,
1687 /// although the surrounding function is never reachable.
1688 pub fn and<T: TypeFoldable<'tcx>>(self, value: T) -> ParamEnvAnd<'tcx, T> {
1690 Reveal::UserFacing => ParamEnvAnd { param_env: self, value },
1693 if value.has_placeholders() || value.needs_infer() || value.has_param_types() {
1694 ParamEnvAnd { param_env: self, value }
1696 ParamEnvAnd { param_env: self.without_caller_bounds(), value }
1703 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TypeFoldable)]
1704 pub struct ParamEnvAnd<'tcx, T> {
1705 pub param_env: ParamEnv<'tcx>,
1709 impl<'tcx, T> ParamEnvAnd<'tcx, T> {
1710 pub fn into_parts(self) -> (ParamEnv<'tcx>, T) {
1711 (self.param_env, self.value)
1715 impl<'a, 'tcx, T> HashStable<StableHashingContext<'a>> for ParamEnvAnd<'tcx, T>
1717 T: HashStable<StableHashingContext<'a>>,
1719 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
1720 let ParamEnvAnd { ref param_env, ref value } = *self;
1722 param_env.hash_stable(hcx, hasher);
1723 value.hash_stable(hcx, hasher);
1727 #[derive(Copy, Clone, Debug, HashStable)]
1728 pub struct Destructor {
1729 /// The `DefId` of the destructor method
1734 #[derive(HashStable)]
1735 pub struct AdtFlags: u32 {
1736 const NO_ADT_FLAGS = 0;
1737 /// Indicates whether the ADT is an enum.
1738 const IS_ENUM = 1 << 0;
1739 /// Indicates whether the ADT is a union.
1740 const IS_UNION = 1 << 1;
1741 /// Indicates whether the ADT is a struct.
1742 const IS_STRUCT = 1 << 2;
1743 /// Indicates whether the ADT is a struct and has a constructor.
1744 const HAS_CTOR = 1 << 3;
1745 /// Indicates whether the type is a `PhantomData`.
1746 const IS_PHANTOM_DATA = 1 << 4;
1747 /// Indicates whether the type has a `#[fundamental]` attribute.
1748 const IS_FUNDAMENTAL = 1 << 5;
1749 /// Indicates whether the type is a `Box`.
1750 const IS_BOX = 1 << 6;
1751 /// Indicates whether the type is an `Arc`.
1752 const IS_ARC = 1 << 7;
1753 /// Indicates whether the type is an `Rc`.
1754 const IS_RC = 1 << 8;
1755 /// Indicates whether the variant list of this ADT is `#[non_exhaustive]`.
1756 /// (i.e., this flag is never set unless this ADT is an enum).
1757 const IS_VARIANT_LIST_NON_EXHAUSTIVE = 1 << 9;
1762 #[derive(HashStable)]
1763 pub struct VariantFlags: u32 {
1764 const NO_VARIANT_FLAGS = 0;
1765 /// Indicates whether the field list of this variant is `#[non_exhaustive]`.
1766 const IS_FIELD_LIST_NON_EXHAUSTIVE = 1 << 0;
1770 /// Definition of a variant -- a struct's fields or a enum variant.
1771 #[derive(Debug, HashStable)]
1772 pub struct VariantDef {
1773 /// `DefId` that identifies the variant itself.
1774 /// If this variant belongs to a struct or union, then this is a copy of its `DefId`.
1776 /// `DefId` that identifies the variant's constructor.
1777 /// If this variant is a struct variant, then this is `None`.
1778 pub ctor_def_id: Option<DefId>,
1779 /// Variant or struct name.
1780 #[stable_hasher(project(name))]
1782 /// Discriminant of this variant.
1783 pub discr: VariantDiscr,
1784 /// Fields of this variant.
1785 pub fields: Vec<FieldDef>,
1786 /// Type of constructor of variant.
1787 pub ctor_kind: CtorKind,
1788 /// Flags of the variant (e.g. is field list non-exhaustive)?
1789 flags: VariantFlags,
1790 /// Variant is obtained as part of recovering from a syntactic error.
1791 /// May be incomplete or bogus.
1792 pub recovered: bool,
1795 impl<'tcx> VariantDef {
1796 /// Creates a new `VariantDef`.
1798 /// `variant_did` is the `DefId` that identifies the enum variant (if this `VariantDef`
1799 /// represents an enum variant).
1801 /// `ctor_did` is the `DefId` that identifies the constructor of unit or
1802 /// tuple-variants/structs. If this is a `struct`-variant then this should be `None`.
1804 /// `parent_did` is the `DefId` of the `AdtDef` representing the enum or struct that
1805 /// owns this variant. It is used for checking if a struct has `#[non_exhaustive]` w/out having
1806 /// to go through the redirect of checking the ctor's attributes - but compiling a small crate
1807 /// requires loading the `AdtDef`s for all the structs in the universe (e.g., coherence for any
1808 /// built-in trait), and we do not want to load attributes twice.
1810 /// If someone speeds up attribute loading to not be a performance concern, they can
1811 /// remove this hack and use the constructor `DefId` everywhere.
1815 variant_did: Option<DefId>,
1816 ctor_def_id: Option<DefId>,
1817 discr: VariantDiscr,
1818 fields: Vec<FieldDef>,
1819 ctor_kind: CtorKind,
1825 "VariantDef::new(ident = {:?}, variant_did = {:?}, ctor_def_id = {:?}, discr = {:?},
1826 fields = {:?}, ctor_kind = {:?}, adt_kind = {:?}, parent_did = {:?})",
1827 ident, variant_did, ctor_def_id, discr, fields, ctor_kind, adt_kind, parent_did,
1830 let mut flags = VariantFlags::NO_VARIANT_FLAGS;
1831 if adt_kind == AdtKind::Struct && tcx.has_attr(parent_did, sym::non_exhaustive) {
1832 debug!("found non-exhaustive field list for {:?}", parent_did);
1833 flags = flags | VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE;
1834 } else if let Some(variant_did) = variant_did {
1835 if tcx.has_attr(variant_did, sym::non_exhaustive) {
1836 debug!("found non-exhaustive field list for {:?}", variant_did);
1837 flags = flags | VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE;
1842 def_id: variant_did.unwrap_or(parent_did),
1853 /// Is this field list non-exhaustive?
1855 pub fn is_field_list_non_exhaustive(&self) -> bool {
1856 self.flags.intersects(VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE)
1860 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
1861 pub enum VariantDiscr {
1862 /// Explicit value for this variant, i.e., `X = 123`.
1863 /// The `DefId` corresponds to the embedded constant.
1866 /// The previous variant's discriminant plus one.
1867 /// For efficiency reasons, the distance from the
1868 /// last `Explicit` discriminant is being stored,
1869 /// or `0` for the first variant, if it has none.
1873 #[derive(Debug, HashStable)]
1874 pub struct FieldDef {
1876 #[stable_hasher(project(name))]
1878 pub vis: Visibility,
1881 /// The definition of a user-defined type, e.g., a `struct`, `enum`, or `union`.
1883 /// These are all interned (by `intern_adt_def`) into the `adt_defs` table.
1885 /// The initialism *ADT* stands for an [*algebraic data type (ADT)*][adt].
1886 /// This is slightly wrong because `union`s are not ADTs.
1887 /// Moreover, Rust only allows recursive data types through indirection.
1889 /// [adt]: https://en.wikipedia.org/wiki/Algebraic_data_type
1891 /// The `DefId` of the struct, enum or union item.
1893 /// Variants of the ADT. If this is a struct or union, then there will be a single variant.
1894 pub variants: IndexVec<self::layout::VariantIdx, VariantDef>,
1895 /// Flags of the ADT (e.g., is this a struct? is this non-exhaustive?).
1897 /// Repr options provided by the user.
1898 pub repr: ReprOptions,
1901 impl PartialOrd for AdtDef {
1902 fn partial_cmp(&self, other: &AdtDef) -> Option<Ordering> {
1903 Some(self.cmp(&other))
1907 /// There should be only one AdtDef for each `did`, therefore
1908 /// it is fine to implement `Ord` only based on `did`.
1909 impl Ord for AdtDef {
1910 fn cmp(&self, other: &AdtDef) -> Ordering {
1911 self.did.cmp(&other.did)
1915 impl PartialEq for AdtDef {
1916 // `AdtDef`s are always interned, and this is part of `TyS` equality.
1918 fn eq(&self, other: &Self) -> bool {
1919 ptr::eq(self, other)
1923 impl Eq for AdtDef {}
1925 impl Hash for AdtDef {
1927 fn hash<H: Hasher>(&self, s: &mut H) {
1928 (self as *const AdtDef).hash(s)
1932 impl<'tcx> rustc_serialize::UseSpecializedEncodable for &'tcx AdtDef {
1933 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1938 impl<'tcx> rustc_serialize::UseSpecializedDecodable for &'tcx AdtDef {}
1940 impl<'a> HashStable<StableHashingContext<'a>> for AdtDef {
1941 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
1943 static CACHE: RefCell<FxHashMap<usize, Fingerprint>> = Default::default();
1946 let hash: Fingerprint = CACHE.with(|cache| {
1947 let addr = self as *const AdtDef as usize;
1948 *cache.borrow_mut().entry(addr).or_insert_with(|| {
1949 let ty::AdtDef { did, ref variants, ref flags, ref repr } = *self;
1951 let mut hasher = StableHasher::new();
1952 did.hash_stable(hcx, &mut hasher);
1953 variants.hash_stable(hcx, &mut hasher);
1954 flags.hash_stable(hcx, &mut hasher);
1955 repr.hash_stable(hcx, &mut hasher);
1961 hash.hash_stable(hcx, hasher);
1965 #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
1972 impl Into<DataTypeKind> for AdtKind {
1973 fn into(self) -> DataTypeKind {
1975 AdtKind::Struct => DataTypeKind::Struct,
1976 AdtKind::Union => DataTypeKind::Union,
1977 AdtKind::Enum => DataTypeKind::Enum,
1983 #[derive(RustcEncodable, RustcDecodable, Default, HashStable)]
1984 pub struct ReprFlags: u8 {
1985 const IS_C = 1 << 0;
1986 const IS_SIMD = 1 << 1;
1987 const IS_TRANSPARENT = 1 << 2;
1988 // Internal only for now. If true, don't reorder fields.
1989 const IS_LINEAR = 1 << 3;
1991 // Any of these flags being set prevent field reordering optimisation.
1992 const IS_UNOPTIMISABLE = ReprFlags::IS_C.bits |
1993 ReprFlags::IS_SIMD.bits |
1994 ReprFlags::IS_LINEAR.bits;
1998 /// Represents the repr options provided by the user,
1999 #[derive(Copy, Clone, Debug, Eq, PartialEq, RustcEncodable, RustcDecodable, Default, HashStable)]
2000 pub struct ReprOptions {
2001 pub int: Option<attr::IntType>,
2002 pub align: Option<Align>,
2003 pub pack: Option<Align>,
2004 pub flags: ReprFlags,
2008 pub fn new(tcx: TyCtxt<'_>, did: DefId) -> ReprOptions {
2009 let mut flags = ReprFlags::empty();
2010 let mut size = None;
2011 let mut max_align: Option<Align> = None;
2012 let mut min_pack: Option<Align> = None;
2013 for attr in tcx.get_attrs(did).iter() {
2014 for r in attr::find_repr_attrs(&tcx.sess.parse_sess, attr) {
2015 flags.insert(match r {
2016 attr::ReprC => ReprFlags::IS_C,
2017 attr::ReprPacked(pack) => {
2018 let pack = Align::from_bytes(pack as u64).unwrap();
2019 min_pack = Some(if let Some(min_pack) = min_pack {
2026 attr::ReprTransparent => ReprFlags::IS_TRANSPARENT,
2027 attr::ReprSimd => ReprFlags::IS_SIMD,
2028 attr::ReprInt(i) => {
2032 attr::ReprAlign(align) => {
2033 max_align = max_align.max(Some(Align::from_bytes(align as u64).unwrap()));
2040 // This is here instead of layout because the choice must make it into metadata.
2041 if !tcx.consider_optimizing(|| format!("Reorder fields of {:?}", tcx.def_path_str(did))) {
2042 flags.insert(ReprFlags::IS_LINEAR);
2044 ReprOptions { int: size, align: max_align, pack: min_pack, flags: flags }
2048 pub fn simd(&self) -> bool {
2049 self.flags.contains(ReprFlags::IS_SIMD)
2052 pub fn c(&self) -> bool {
2053 self.flags.contains(ReprFlags::IS_C)
2056 pub fn packed(&self) -> bool {
2060 pub fn transparent(&self) -> bool {
2061 self.flags.contains(ReprFlags::IS_TRANSPARENT)
2064 pub fn linear(&self) -> bool {
2065 self.flags.contains(ReprFlags::IS_LINEAR)
2068 pub fn discr_type(&self) -> attr::IntType {
2069 self.int.unwrap_or(attr::SignedInt(ast::IntTy::Isize))
2072 /// Returns `true` if this `#[repr()]` should inhabit "smart enum
2073 /// layout" optimizations, such as representing `Foo<&T>` as a
2075 pub fn inhibit_enum_layout_opt(&self) -> bool {
2076 self.c() || self.int.is_some()
2079 /// Returns `true` if this `#[repr()]` should inhibit struct field reordering
2080 /// optimizations, such as with `repr(C)`, `repr(packed(1))`, or `repr(<int>)`.
2081 pub fn inhibit_struct_field_reordering_opt(&self) -> bool {
2082 if let Some(pack) = self.pack {
2083 if pack.bytes() == 1 {
2087 self.flags.intersects(ReprFlags::IS_UNOPTIMISABLE) || self.int.is_some()
2090 /// Returns `true` if this `#[repr()]` should inhibit union ABI optimisations.
2091 pub fn inhibit_union_abi_opt(&self) -> bool {
2097 /// Creates a new `AdtDef`.
2102 variants: IndexVec<VariantIdx, VariantDef>,
2105 debug!("AdtDef::new({:?}, {:?}, {:?}, {:?})", did, kind, variants, repr);
2106 let mut flags = AdtFlags::NO_ADT_FLAGS;
2108 if kind == AdtKind::Enum && tcx.has_attr(did, sym::non_exhaustive) {
2109 debug!("found non-exhaustive variant list for {:?}", did);
2110 flags = flags | AdtFlags::IS_VARIANT_LIST_NON_EXHAUSTIVE;
2113 flags |= match kind {
2114 AdtKind::Enum => AdtFlags::IS_ENUM,
2115 AdtKind::Union => AdtFlags::IS_UNION,
2116 AdtKind::Struct => AdtFlags::IS_STRUCT,
2119 if kind == AdtKind::Struct && variants[VariantIdx::new(0)].ctor_def_id.is_some() {
2120 flags |= AdtFlags::HAS_CTOR;
2123 let attrs = tcx.get_attrs(did);
2124 if attr::contains_name(&attrs, sym::fundamental) {
2125 flags |= AdtFlags::IS_FUNDAMENTAL;
2127 if Some(did) == tcx.lang_items().phantom_data() {
2128 flags |= AdtFlags::IS_PHANTOM_DATA;
2130 if Some(did) == tcx.lang_items().owned_box() {
2131 flags |= AdtFlags::IS_BOX;
2133 if Some(did) == tcx.lang_items().arc() {
2134 flags |= AdtFlags::IS_ARC;
2136 if Some(did) == tcx.lang_items().rc() {
2137 flags |= AdtFlags::IS_RC;
2140 AdtDef { did, variants, flags, repr }
2143 /// Returns `true` if this is a struct.
2145 pub fn is_struct(&self) -> bool {
2146 self.flags.contains(AdtFlags::IS_STRUCT)
2149 /// Returns `true` if this is a union.
2151 pub fn is_union(&self) -> bool {
2152 self.flags.contains(AdtFlags::IS_UNION)
2155 /// Returns `true` if this is a enum.
2157 pub fn is_enum(&self) -> bool {
2158 self.flags.contains(AdtFlags::IS_ENUM)
2161 /// Returns `true` if the variant list of this ADT is `#[non_exhaustive]`.
2163 pub fn is_variant_list_non_exhaustive(&self) -> bool {
2164 self.flags.contains(AdtFlags::IS_VARIANT_LIST_NON_EXHAUSTIVE)
2167 /// Returns the kind of the ADT.
2169 pub fn adt_kind(&self) -> AdtKind {
2172 } else if self.is_union() {
2179 /// Returns a description of this abstract data type.
2180 pub fn descr(&self) -> &'static str {
2181 match self.adt_kind() {
2182 AdtKind::Struct => "struct",
2183 AdtKind::Union => "union",
2184 AdtKind::Enum => "enum",
2188 /// Returns a description of a variant of this abstract data type.
2190 pub fn variant_descr(&self) -> &'static str {
2191 match self.adt_kind() {
2192 AdtKind::Struct => "struct",
2193 AdtKind::Union => "union",
2194 AdtKind::Enum => "variant",
2198 /// If this function returns `true`, it implies that `is_struct` must return `true`.
2200 pub fn has_ctor(&self) -> bool {
2201 self.flags.contains(AdtFlags::HAS_CTOR)
2204 /// Returns `true` if this type is `#[fundamental]` for the purposes
2205 /// of coherence checking.
2207 pub fn is_fundamental(&self) -> bool {
2208 self.flags.contains(AdtFlags::IS_FUNDAMENTAL)
2211 /// Returns `true` if this is `PhantomData<T>`.
2213 pub fn is_phantom_data(&self) -> bool {
2214 self.flags.contains(AdtFlags::IS_PHANTOM_DATA)
2217 /// Returns `true` if this is `Arc<T>`.
2218 pub fn is_arc(&self) -> bool {
2219 self.flags.contains(AdtFlags::IS_ARC)
2222 /// Returns `true` if this is `Rc<T>`.
2223 pub fn is_rc(&self) -> bool {
2224 self.flags.contains(AdtFlags::IS_RC)
2227 /// Returns `true` if this is Box<T>.
2229 pub fn is_box(&self) -> bool {
2230 self.flags.contains(AdtFlags::IS_BOX)
2233 /// Returns `true` if this type has a destructor.
2234 pub fn has_dtor(&self, tcx: TyCtxt<'tcx>) -> bool {
2235 self.destructor(tcx).is_some()
2238 /// Asserts this is a struct or union and returns its unique variant.
2239 pub fn non_enum_variant(&self) -> &VariantDef {
2240 assert!(self.is_struct() || self.is_union());
2241 &self.variants[VariantIdx::new(0)]
2245 pub fn predicates(&self, tcx: TyCtxt<'tcx>) -> GenericPredicates<'tcx> {
2246 tcx.predicates_of(self.did)
2249 /// Returns an iterator over all fields contained
2252 pub fn all_fields(&self) -> impl Iterator<Item = &FieldDef> + Clone {
2253 self.variants.iter().flat_map(|v| v.fields.iter())
2256 pub fn is_payloadfree(&self) -> bool {
2257 !self.variants.is_empty() && self.variants.iter().all(|v| v.fields.is_empty())
2260 /// Return a `VariantDef` given a variant id.
2261 pub fn variant_with_id(&self, vid: DefId) -> &VariantDef {
2262 self.variants.iter().find(|v| v.def_id == vid).expect("variant_with_id: unknown variant")
2265 /// Return a `VariantDef` given a constructor id.
2266 pub fn variant_with_ctor_id(&self, cid: DefId) -> &VariantDef {
2269 .find(|v| v.ctor_def_id == Some(cid))
2270 .expect("variant_with_ctor_id: unknown variant")
2273 /// Return the index of `VariantDef` given a variant id.
2274 pub fn variant_index_with_id(&self, vid: DefId) -> VariantIdx {
2277 .find(|(_, v)| v.def_id == vid)
2278 .expect("variant_index_with_id: unknown variant")
2282 /// Return the index of `VariantDef` given a constructor id.
2283 pub fn variant_index_with_ctor_id(&self, cid: DefId) -> VariantIdx {
2286 .find(|(_, v)| v.ctor_def_id == Some(cid))
2287 .expect("variant_index_with_ctor_id: unknown variant")
2291 pub fn variant_of_res(&self, res: Res) -> &VariantDef {
2293 Res::Def(DefKind::Variant, vid) => self.variant_with_id(vid),
2294 Res::Def(DefKind::Ctor(..), cid) => self.variant_with_ctor_id(cid),
2295 Res::Def(DefKind::Struct, _)
2296 | Res::Def(DefKind::Union, _)
2297 | Res::Def(DefKind::TyAlias, _)
2298 | Res::Def(DefKind::AssocTy, _)
2300 | Res::SelfCtor(..) => self.non_enum_variant(),
2301 _ => bug!("unexpected res {:?} in variant_of_res", res),
2306 pub fn eval_explicit_discr(&self, tcx: TyCtxt<'tcx>, expr_did: DefId) -> Option<Discr<'tcx>> {
2307 let param_env = tcx.param_env(expr_did);
2308 let repr_type = self.repr.discr_type();
2309 match tcx.const_eval_poly(expr_did) {
2311 // FIXME: Find the right type and use it instead of `val.ty` here
2312 if let Some(b) = val.try_eval_bits(tcx, param_env, val.ty) {
2313 trace!("discriminants: {} ({:?})", b, repr_type);
2314 Some(Discr { val: b, ty: val.ty })
2316 info!("invalid enum discriminant: {:#?}", val);
2317 crate::mir::interpret::struct_error(
2318 tcx.at(tcx.def_span(expr_did)),
2319 "constant evaluation of enum discriminant resulted in non-integer",
2325 Err(ErrorHandled::Reported) => {
2326 if !expr_did.is_local() {
2328 tcx.def_span(expr_did),
2329 "variant discriminant evaluation succeeded \
2330 in its crate but failed locally"
2335 Err(ErrorHandled::TooGeneric) => {
2336 span_bug!(tcx.def_span(expr_did), "enum discriminant depends on generic arguments",)
2342 pub fn discriminants(
2345 ) -> impl Iterator<Item = (VariantIdx, Discr<'tcx>)> + Captures<'tcx> {
2346 let repr_type = self.repr.discr_type();
2347 let initial = repr_type.initial_discriminant(tcx);
2348 let mut prev_discr = None::<Discr<'tcx>>;
2349 self.variants.iter_enumerated().map(move |(i, v)| {
2350 let mut discr = prev_discr.map_or(initial, |d| d.wrap_incr(tcx));
2351 if let VariantDiscr::Explicit(expr_did) = v.discr {
2352 if let Some(new_discr) = self.eval_explicit_discr(tcx, expr_did) {
2356 prev_discr = Some(discr);
2363 pub fn variant_range(&self) -> Range<VariantIdx> {
2364 (VariantIdx::new(0)..VariantIdx::new(self.variants.len()))
2367 /// Computes the discriminant value used by a specific variant.
2368 /// Unlike `discriminants`, this is (amortized) constant-time,
2369 /// only doing at most one query for evaluating an explicit
2370 /// discriminant (the last one before the requested variant),
2371 /// assuming there are no constant-evaluation errors there.
2373 pub fn discriminant_for_variant(
2376 variant_index: VariantIdx,
2378 let (val, offset) = self.discriminant_def_for_variant(variant_index);
2379 let explicit_value = val
2380 .and_then(|expr_did| self.eval_explicit_discr(tcx, expr_did))
2381 .unwrap_or_else(|| self.repr.discr_type().initial_discriminant(tcx));
2382 explicit_value.checked_add(tcx, offset as u128).0
2385 /// Yields a `DefId` for the discriminant and an offset to add to it
2386 /// Alternatively, if there is no explicit discriminant, returns the
2387 /// inferred discriminant directly.
2388 pub fn discriminant_def_for_variant(&self, variant_index: VariantIdx) -> (Option<DefId>, u32) {
2389 let mut explicit_index = variant_index.as_u32();
2392 match self.variants[VariantIdx::from_u32(explicit_index)].discr {
2393 ty::VariantDiscr::Relative(0) => {
2397 ty::VariantDiscr::Relative(distance) => {
2398 explicit_index -= distance;
2400 ty::VariantDiscr::Explicit(did) => {
2401 expr_did = Some(did);
2406 (expr_did, variant_index.as_u32() - explicit_index)
2409 pub fn destructor(&self, tcx: TyCtxt<'tcx>) -> Option<Destructor> {
2410 tcx.adt_destructor(self.did)
2413 /// Returns a list of types such that `Self: Sized` if and only
2414 /// if that type is `Sized`, or `TyErr` if this type is recursive.
2416 /// Oddly enough, checking that the sized-constraint is `Sized` is
2417 /// actually more expressive than checking all members:
2418 /// the `Sized` trait is inductive, so an associated type that references
2419 /// `Self` would prevent its containing ADT from being `Sized`.
2421 /// Due to normalization being eager, this applies even if
2422 /// the associated type is behind a pointer (e.g., issue #31299).
2423 pub fn sized_constraint(&self, tcx: TyCtxt<'tcx>) -> &'tcx [Ty<'tcx>] {
2424 tcx.adt_sized_constraint(self.did).0
2428 impl<'tcx> FieldDef {
2429 /// Returns the type of this field. The `subst` is typically obtained
2430 /// via the second field of `TyKind::AdtDef`.
2431 pub fn ty(&self, tcx: TyCtxt<'tcx>, subst: SubstsRef<'tcx>) -> Ty<'tcx> {
2432 tcx.type_of(self.did).subst(tcx, subst)
2436 /// Represents the various closure traits in the language. This
2437 /// will determine the type of the environment (`self`, in the
2438 /// desugaring) argument that the closure expects.
2440 /// You can get the environment type of a closure using
2441 /// `tcx.closure_env_ty()`.
2455 pub enum ClosureKind {
2456 // Warning: Ordering is significant here! The ordering is chosen
2457 // because the trait Fn is a subtrait of FnMut and so in turn, and
2458 // hence we order it so that Fn < FnMut < FnOnce.
2464 impl<'tcx> ClosureKind {
2465 // This is the initial value used when doing upvar inference.
2466 pub const LATTICE_BOTTOM: ClosureKind = ClosureKind::Fn;
2468 pub fn trait_did(&self, tcx: TyCtxt<'tcx>) -> DefId {
2470 ClosureKind::Fn => tcx.require_lang_item(FnTraitLangItem, None),
2471 ClosureKind::FnMut => tcx.require_lang_item(FnMutTraitLangItem, None),
2472 ClosureKind::FnOnce => tcx.require_lang_item(FnOnceTraitLangItem, None),
2476 /// Returns `true` if this a type that impls this closure kind
2477 /// must also implement `other`.
2478 pub fn extends(self, other: ty::ClosureKind) -> bool {
2479 match (self, other) {
2480 (ClosureKind::Fn, ClosureKind::Fn) => true,
2481 (ClosureKind::Fn, ClosureKind::FnMut) => true,
2482 (ClosureKind::Fn, ClosureKind::FnOnce) => true,
2483 (ClosureKind::FnMut, ClosureKind::FnMut) => true,
2484 (ClosureKind::FnMut, ClosureKind::FnOnce) => true,
2485 (ClosureKind::FnOnce, ClosureKind::FnOnce) => true,
2490 /// Returns the representative scalar type for this closure kind.
2491 /// See `TyS::to_opt_closure_kind` for more details.
2492 pub fn to_ty(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
2494 ty::ClosureKind::Fn => tcx.types.i8,
2495 ty::ClosureKind::FnMut => tcx.types.i16,
2496 ty::ClosureKind::FnOnce => tcx.types.i32,
2501 impl<'tcx> TyS<'tcx> {
2502 /// Iterator that walks `self` and any types reachable from
2503 /// `self`, in depth-first order. Note that just walks the types
2504 /// that appear in `self`, it does not descend into the fields of
2505 /// structs or variants. For example:
2508 /// isize => { isize }
2509 /// Foo<Bar<isize>> => { Foo<Bar<isize>>, Bar<isize>, isize }
2510 /// [isize] => { [isize], isize }
2512 pub fn walk(&'tcx self) -> TypeWalker<'tcx> {
2513 TypeWalker::new(self)
2516 /// Iterator that walks the immediate children of `self`. Hence
2517 /// `Foo<Bar<i32>, u32>` yields the sequence `[Bar<i32>, u32]`
2518 /// (but not `i32`, like `walk`).
2519 pub fn walk_shallow(&'tcx self) -> smallvec::IntoIter<walk::TypeWalkerArray<'tcx>> {
2520 walk::walk_shallow(self)
2523 /// Walks `ty` and any types appearing within `ty`, invoking the
2524 /// callback `f` on each type. If the callback returns `false`, then the
2525 /// children of the current type are ignored.
2527 /// Note: prefer `ty.walk()` where possible.
2528 pub fn maybe_walk<F>(&'tcx self, mut f: F)
2530 F: FnMut(Ty<'tcx>) -> bool,
2532 let mut walker = self.walk();
2533 while let Some(ty) = walker.next() {
2535 walker.skip_current_subtree();
2542 pub fn from_mutbl(m: hir::Mutability) -> BorrowKind {
2544 hir::Mutability::Mut => MutBorrow,
2545 hir::Mutability::Not => ImmBorrow,
2549 /// Returns a mutability `m` such that an `&m T` pointer could be used to obtain this borrow
2550 /// kind. Because borrow kinds are richer than mutabilities, we sometimes have to pick a
2551 /// mutability that is stronger than necessary so that it at least *would permit* the borrow in
2553 pub fn to_mutbl_lossy(self) -> hir::Mutability {
2555 MutBorrow => hir::Mutability::Mut,
2556 ImmBorrow => hir::Mutability::Not,
2558 // We have no type corresponding to a unique imm borrow, so
2559 // use `&mut`. It gives all the capabilities of an `&uniq`
2560 // and hence is a safe "over approximation".
2561 UniqueImmBorrow => hir::Mutability::Mut,
2565 pub fn to_user_str(&self) -> &'static str {
2567 MutBorrow => "mutable",
2568 ImmBorrow => "immutable",
2569 UniqueImmBorrow => "uniquely immutable",
2574 #[derive(Debug, Clone)]
2575 pub enum Attributes<'tcx> {
2576 Owned(Lrc<[ast::Attribute]>),
2577 Borrowed(&'tcx [ast::Attribute]),
2580 impl<'tcx> ::std::ops::Deref for Attributes<'tcx> {
2581 type Target = [ast::Attribute];
2583 fn deref(&self) -> &[ast::Attribute] {
2585 &Attributes::Owned(ref data) => &data,
2586 &Attributes::Borrowed(data) => data,
2591 #[derive(Debug, PartialEq, Eq)]
2592 pub enum ImplOverlapKind {
2593 /// These impls are always allowed to overlap.
2595 /// Whether or not the impl is permitted due to the trait being
2596 /// a marker trait (a trait with #[marker], or a trait with
2597 /// no associated items and #![feature(overlapping_marker_traits)] enabled)
2600 /// These impls are allowed to overlap, but that raises
2601 /// an issue #33140 future-compatibility warning.
2603 /// Some background: in Rust 1.0, the trait-object types `Send + Sync` (today's
2604 /// `dyn Send + Sync`) and `Sync + Send` (now `dyn Sync + Send`) were different.
2606 /// The widely-used version 0.1.0 of the crate `traitobject` had accidentally relied
2607 /// that difference, making what reduces to the following set of impls:
2611 /// impl Trait for dyn Send + Sync {}
2612 /// impl Trait for dyn Sync + Send {}
2615 /// Obviously, once we made these types be identical, that code causes a coherence
2616 /// error and a fairly big headache for us. However, luckily for us, the trait
2617 /// `Trait` used in this case is basically a marker trait, and therefore having
2618 /// overlapping impls for it is sound.
2620 /// To handle this, we basically regard the trait as a marker trait, with an additional
2621 /// future-compatibility warning. To avoid accidentally "stabilizing" this feature,
2622 /// it has the following restrictions:
2624 /// 1. The trait must indeed be a marker-like trait (i.e., no items), and must be
2626 /// 2. The trait-ref of both impls must be equal.
2627 /// 3. The trait-ref of both impls must be a trait object type consisting only of
2629 /// 4. Neither of the impls can have any where-clauses.
2631 /// Once `traitobject` 0.1.0 is no longer an active concern, this hack can be removed.
2635 impl<'tcx> TyCtxt<'tcx> {
2636 pub fn body_tables(self, body: hir::BodyId) -> &'tcx TypeckTables<'tcx> {
2637 self.typeck_tables_of(self.hir().body_owner_def_id(body))
2640 /// Returns an iterator of the `DefId`s for all body-owners in this
2641 /// crate. If you would prefer to iterate over the bodies
2642 /// themselves, you can do `self.hir().krate().body_ids.iter()`.
2643 pub fn body_owners(self) -> impl Iterator<Item = DefId> + Captures<'tcx> + 'tcx {
2648 .map(move |&body_id| self.hir().body_owner_def_id(body_id))
2651 pub fn par_body_owners<F: Fn(DefId) + sync::Sync + sync::Send>(self, f: F) {
2652 par_iter(&self.hir().krate().body_ids)
2653 .for_each(|&body_id| f(self.hir().body_owner_def_id(body_id)));
2656 pub fn provided_trait_methods(self, id: DefId) -> Vec<AssocItem> {
2657 self.associated_items(id)
2658 .filter(|item| item.kind == AssocKind::Method && item.defaultness.has_value())
2662 pub fn trait_relevant_for_never(self, did: DefId) -> bool {
2663 self.associated_items(did).any(|item| item.relevant_for_never())
2666 pub fn opt_item_name(self, def_id: DefId) -> Option<Ident> {
2667 self.hir().as_local_hir_id(def_id).and_then(|hir_id| self.hir().get(hir_id).ident())
2670 pub fn opt_associated_item(self, def_id: DefId) -> Option<AssocItem> {
2671 let is_associated_item = if let Some(hir_id) = self.hir().as_local_hir_id(def_id) {
2672 match self.hir().get(hir_id) {
2673 Node::TraitItem(_) | Node::ImplItem(_) => true,
2677 match self.def_kind(def_id).expect("no def for `DefId`") {
2678 DefKind::AssocConst | DefKind::Method | DefKind::AssocTy => true,
2683 is_associated_item.then(|| self.associated_item(def_id))
2686 pub fn field_index(self, hir_id: hir::HirId, tables: &TypeckTables<'_>) -> usize {
2687 tables.field_indices().get(hir_id).cloned().expect("no index for a field")
2690 pub fn find_field_index(self, ident: Ident, variant: &VariantDef) -> Option<usize> {
2691 variant.fields.iter().position(|field| self.hygienic_eq(ident, field.ident, variant.def_id))
2694 pub fn associated_items(self, def_id: DefId) -> AssocItemsIterator<'tcx> {
2695 // Ideally, we would use `-> impl Iterator` here, but it falls
2696 // afoul of the conservative "capture [restrictions]" we put
2697 // in place, so we use a hand-written iterator.
2699 // [restrictions]: https://github.com/rust-lang/rust/issues/34511#issuecomment-373423999
2700 AssocItemsIterator {
2702 def_ids: self.associated_item_def_ids(def_id),
2707 /// Returns `true` if the impls are the same polarity and the trait either
2708 /// has no items or is annotated #[marker] and prevents item overrides.
2709 pub fn impls_are_allowed_to_overlap(
2713 ) -> Option<ImplOverlapKind> {
2714 // If either trait impl references an error, they're allowed to overlap,
2715 // as one of them essentially doesn't exist.
2716 if self.impl_trait_ref(def_id1).map_or(false, |tr| tr.references_error())
2717 || self.impl_trait_ref(def_id2).map_or(false, |tr| tr.references_error())
2719 return Some(ImplOverlapKind::Permitted { marker: false });
2722 match (self.impl_polarity(def_id1), self.impl_polarity(def_id2)) {
2723 (ImplPolarity::Reservation, _) | (_, ImplPolarity::Reservation) => {
2724 // `#[rustc_reservation_impl]` impls don't overlap with anything
2726 "impls_are_allowed_to_overlap({:?}, {:?}) = Some(Permitted) (reservations)",
2729 return Some(ImplOverlapKind::Permitted { marker: false });
2731 (ImplPolarity::Positive, ImplPolarity::Negative)
2732 | (ImplPolarity::Negative, ImplPolarity::Positive) => {
2733 // `impl AutoTrait for Type` + `impl !AutoTrait for Type`
2735 "impls_are_allowed_to_overlap({:?}, {:?}) - None (differing polarities)",
2740 (ImplPolarity::Positive, ImplPolarity::Positive)
2741 | (ImplPolarity::Negative, ImplPolarity::Negative) => {}
2744 let is_marker_overlap = if self.features().overlapping_marker_traits {
2745 let trait1_is_empty = self.impl_trait_ref(def_id1).map_or(false, |trait_ref| {
2746 self.associated_item_def_ids(trait_ref.def_id).is_empty()
2748 let trait2_is_empty = self.impl_trait_ref(def_id2).map_or(false, |trait_ref| {
2749 self.associated_item_def_ids(trait_ref.def_id).is_empty()
2751 trait1_is_empty && trait2_is_empty
2753 let is_marker_impl = |def_id: DefId| -> bool {
2754 let trait_ref = self.impl_trait_ref(def_id);
2755 trait_ref.map_or(false, |tr| self.trait_def(tr.def_id).is_marker)
2757 is_marker_impl(def_id1) && is_marker_impl(def_id2)
2760 if is_marker_overlap {
2762 "impls_are_allowed_to_overlap({:?}, {:?}) = Some(Permitted) (marker overlap)",
2765 Some(ImplOverlapKind::Permitted { marker: true })
2767 if let Some(self_ty1) = self.issue33140_self_ty(def_id1) {
2768 if let Some(self_ty2) = self.issue33140_self_ty(def_id2) {
2769 if self_ty1 == self_ty2 {
2771 "impls_are_allowed_to_overlap({:?}, {:?}) - issue #33140 HACK",
2774 return Some(ImplOverlapKind::Issue33140);
2777 "impls_are_allowed_to_overlap({:?}, {:?}) - found {:?} != {:?}",
2778 def_id1, def_id2, self_ty1, self_ty2
2784 debug!("impls_are_allowed_to_overlap({:?}, {:?}) = None", def_id1, def_id2);
2789 /// Returns `ty::VariantDef` if `res` refers to a struct,
2790 /// or variant or their constructors, panics otherwise.
2791 pub fn expect_variant_res(self, res: Res) -> &'tcx VariantDef {
2793 Res::Def(DefKind::Variant, did) => {
2794 let enum_did = self.parent(did).unwrap();
2795 self.adt_def(enum_did).variant_with_id(did)
2797 Res::Def(DefKind::Struct, did) | Res::Def(DefKind::Union, did) => {
2798 self.adt_def(did).non_enum_variant()
2800 Res::Def(DefKind::Ctor(CtorOf::Variant, ..), variant_ctor_did) => {
2801 let variant_did = self.parent(variant_ctor_did).unwrap();
2802 let enum_did = self.parent(variant_did).unwrap();
2803 self.adt_def(enum_did).variant_with_ctor_id(variant_ctor_did)
2805 Res::Def(DefKind::Ctor(CtorOf::Struct, ..), ctor_did) => {
2806 let struct_did = self.parent(ctor_did).expect("struct ctor has no parent");
2807 self.adt_def(struct_did).non_enum_variant()
2809 _ => bug!("expect_variant_res used with unexpected res {:?}", res),
2813 pub fn item_name(self, id: DefId) -> Symbol {
2814 if id.index == CRATE_DEF_INDEX {
2815 self.original_crate_name(id.krate)
2817 let def_key = self.def_key(id);
2818 match def_key.disambiguated_data.data {
2819 // The name of a constructor is that of its parent.
2820 hir_map::DefPathData::Ctor => {
2821 self.item_name(DefId { krate: id.krate, index: def_key.parent.unwrap() })
2823 _ => def_key.disambiguated_data.data.get_opt_name().unwrap_or_else(|| {
2824 bug!("item_name: no name for {:?}", self.def_path(id));
2830 /// Returns the possibly-auto-generated MIR of a `(DefId, Subst)` pair.
2831 pub fn instance_mir(self, instance: ty::InstanceDef<'tcx>) -> ReadOnlyBodyAndCache<'tcx, 'tcx> {
2833 ty::InstanceDef::Item(did) => self.optimized_mir(did).unwrap_read_only(),
2834 ty::InstanceDef::VtableShim(..)
2835 | ty::InstanceDef::ReifyShim(..)
2836 | ty::InstanceDef::Intrinsic(..)
2837 | ty::InstanceDef::FnPtrShim(..)
2838 | ty::InstanceDef::Virtual(..)
2839 | ty::InstanceDef::ClosureOnceShim { .. }
2840 | ty::InstanceDef::DropGlue(..)
2841 | ty::InstanceDef::CloneShim(..) => self.mir_shims(instance).unwrap_read_only(),
2845 /// Gets the attributes of a definition.
2846 pub fn get_attrs(self, did: DefId) -> Attributes<'tcx> {
2847 if let Some(id) = self.hir().as_local_hir_id(did) {
2848 Attributes::Borrowed(self.hir().attrs(id))
2850 Attributes::Owned(self.item_attrs(did))
2854 /// Determines whether an item is annotated with an attribute.
2855 pub fn has_attr(self, did: DefId, attr: Symbol) -> bool {
2856 attr::contains_name(&self.get_attrs(did), attr)
2859 /// Returns `true` if this is an `auto trait`.
2860 pub fn trait_is_auto(self, trait_def_id: DefId) -> bool {
2861 self.trait_def(trait_def_id).has_auto_impl
2864 pub fn generator_layout(self, def_id: DefId) -> &'tcx GeneratorLayout<'tcx> {
2865 self.optimized_mir(def_id).generator_layout.as_ref().unwrap()
2868 /// Given the `DefId` of an impl, returns the `DefId` of the trait it implements.
2869 /// If it implements no trait, returns `None`.
2870 pub fn trait_id_of_impl(self, def_id: DefId) -> Option<DefId> {
2871 self.impl_trait_ref(def_id).map(|tr| tr.def_id)
2874 /// If the given defid describes a method belonging to an impl, returns the
2875 /// `DefId` of the impl that the method belongs to; otherwise, returns `None`.
2876 pub fn impl_of_method(self, def_id: DefId) -> Option<DefId> {
2877 let item = if def_id.krate != LOCAL_CRATE {
2878 if let Some(DefKind::Method) = self.def_kind(def_id) {
2879 Some(self.associated_item(def_id))
2884 self.opt_associated_item(def_id)
2887 item.and_then(|trait_item| match trait_item.container {
2888 TraitContainer(_) => None,
2889 ImplContainer(def_id) => Some(def_id),
2893 /// Looks up the span of `impl_did` if the impl is local; otherwise returns `Err`
2894 /// with the name of the crate containing the impl.
2895 pub fn span_of_impl(self, impl_did: DefId) -> Result<Span, Symbol> {
2896 if impl_did.is_local() {
2897 let hir_id = self.hir().as_local_hir_id(impl_did).unwrap();
2898 Ok(self.hir().span(hir_id))
2900 Err(self.crate_name(impl_did.krate))
2904 /// Hygienically compares a use-site name (`use_name`) for a field or an associated item with
2905 /// its supposed definition name (`def_name`). The method also needs `DefId` of the supposed
2906 /// definition's parent/scope to perform comparison.
2907 pub fn hygienic_eq(self, use_name: Ident, def_name: Ident, def_parent_def_id: DefId) -> bool {
2908 // We could use `Ident::eq` here, but we deliberately don't. The name
2909 // comparison fails frequently, and we want to avoid the expensive
2910 // `modern()` calls required for the span comparison whenever possible.
2911 use_name.name == def_name.name
2915 .hygienic_eq(def_name.span.ctxt(), self.expansion_that_defined(def_parent_def_id))
2918 fn expansion_that_defined(self, scope: DefId) -> ExpnId {
2920 LOCAL_CRATE => self.hir().definitions().expansion_that_defined(scope.index),
2921 _ => ExpnId::root(),
2925 pub fn adjust_ident(self, mut ident: Ident, scope: DefId) -> Ident {
2926 ident.span.modernize_and_adjust(self.expansion_that_defined(scope));
2930 pub fn adjust_ident_and_get_scope(
2935 ) -> (Ident, DefId) {
2936 let scope = match ident.span.modernize_and_adjust(self.expansion_that_defined(scope)) {
2937 Some(actual_expansion) => {
2938 self.hir().definitions().parent_module_of_macro_def(actual_expansion)
2940 None => self.hir().get_module_parent(block),
2947 pub struct AssocItemsIterator<'tcx> {
2949 def_ids: &'tcx [DefId],
2953 impl Iterator for AssocItemsIterator<'_> {
2954 type Item = AssocItem;
2956 fn next(&mut self) -> Option<AssocItem> {
2957 let def_id = self.def_ids.get(self.next_index)?;
2958 self.next_index += 1;
2959 Some(self.tcx.associated_item(*def_id))
2963 #[derive(Clone, HashStable)]
2964 pub struct AdtSizedConstraint<'tcx>(pub &'tcx [Ty<'tcx>]);
2966 /// Yields the parent function's `DefId` if `def_id` is an `impl Trait` definition.
2967 pub fn is_impl_trait_defn(tcx: TyCtxt<'_>, def_id: DefId) -> Option<DefId> {
2968 if let Some(hir_id) = tcx.hir().as_local_hir_id(def_id) {
2969 if let Node::Item(item) = tcx.hir().get(hir_id) {
2970 if let hir::ItemKind::OpaqueTy(ref opaque_ty) = item.kind {
2971 return opaque_ty.impl_trait_fn;
2978 pub fn provide(providers: &mut ty::query::Providers<'_>) {
2979 context::provide(providers);
2980 erase_regions::provide(providers);
2981 layout::provide(providers);
2983 ty::query::Providers { trait_impls_of: trait_def::trait_impls_of_provider, ..*providers };
2986 /// A map for the local crate mapping each type to a vector of its
2987 /// inherent impls. This is not meant to be used outside of coherence;
2988 /// rather, you should request the vector for a specific type via
2989 /// `tcx.inherent_impls(def_id)` so as to minimize your dependencies
2990 /// (constructing this map requires touching the entire crate).
2991 #[derive(Clone, Debug, Default, HashStable)]
2992 pub struct CrateInherentImpls {
2993 pub inherent_impls: DefIdMap<Vec<DefId>>,
2996 #[derive(Clone, Copy, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2997 pub struct SymbolName {
2998 // FIXME: we don't rely on interning or equality here - better have
2999 // this be a `&'tcx str`.
3004 pub fn new(name: &str) -> SymbolName {
3005 SymbolName { name: Symbol::intern(name) }
3009 impl PartialOrd for SymbolName {
3010 fn partial_cmp(&self, other: &SymbolName) -> Option<Ordering> {
3011 self.name.as_str().partial_cmp(&other.name.as_str())
3015 /// Ordering must use the chars to ensure reproducible builds.
3016 impl Ord for SymbolName {
3017 fn cmp(&self, other: &SymbolName) -> Ordering {
3018 self.name.as_str().cmp(&other.name.as_str())
3022 impl fmt::Display for SymbolName {
3023 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
3024 fmt::Display::fmt(&self.name, fmt)
3028 impl fmt::Debug for SymbolName {
3029 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
3030 fmt::Display::fmt(&self.name, fmt)