1 // ignore-tidy-filelength
3 pub use self::fold::{TypeFoldable, TypeVisitor};
4 pub use self::AssocItemContainer::*;
5 pub use self::BorrowKind::*;
6 pub use self::IntVarValue::*;
7 pub use self::Variance::*;
9 use crate::hir::exports::ExportMap;
10 use crate::hir::map as hir_map;
12 use crate::ich::Fingerprint;
13 use crate::ich::StableHashingContext;
14 use crate::infer::canonical::Canonical;
15 use crate::middle::cstore::CrateStoreDyn;
16 use crate::middle::lang_items::{FnMutTraitLangItem, FnOnceTraitLangItem, FnTraitLangItem};
17 use crate::middle::resolve_lifetime::ObjectLifetimeDefault;
18 use crate::mir::interpret::ErrorHandled;
19 use crate::mir::GeneratorLayout;
20 use crate::mir::ReadOnlyBodyAndCache;
21 use crate::session::CrateDisambiguator;
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 crate::util::captures::Captures;
30 use arena::SyncDroplessArena;
31 use rustc_data_structures::fx::FxHashMap;
32 use rustc_data_structures::fx::FxIndexMap;
33 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
34 use rustc_data_structures::svh::Svh;
35 use rustc_data_structures::sync::{self, par_iter, Lrc, ParallelIterator};
37 use rustc_hir::def::{CtorKind, CtorOf, DefKind, Res};
38 use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, LocalDefId, CRATE_DEF_INDEX, LOCAL_CRATE};
39 use rustc_hir::{GlobMap, Node, TraitMap};
40 use rustc_index::vec::{Idx, IndexVec};
41 use rustc_macros::HashStable;
42 use rustc_serialize::{self, Encodable, Encoder};
43 use rustc_session::node_id::{NodeMap, NodeSet};
44 use rustc_span::hygiene::ExpnId;
45 use rustc_span::symbol::{kw, sym, Symbol};
47 use rustc_target::abi::Align;
49 use std::cell::RefCell;
50 use std::cmp::{self, Ordering};
52 use std::hash::{Hash, Hasher};
57 use syntax::ast::{self, Ident, Name, NodeId};
60 pub use self::sty::BoundRegion::*;
61 pub use self::sty::InferTy::*;
62 pub use self::sty::RegionKind;
63 pub use self::sty::RegionKind::*;
64 pub use self::sty::TyKind::*;
65 pub use self::sty::{Binder, BoundTy, BoundTyKind, BoundVar, DebruijnIndex, INNERMOST};
66 pub use self::sty::{BoundRegion, EarlyBoundRegion, FreeRegion, Region};
67 pub use self::sty::{CanonicalPolyFnSig, FnSig, GenSig, PolyFnSig, PolyGenSig};
68 pub use self::sty::{ClosureSubsts, GeneratorSubsts, TypeAndMut, UpvarSubsts};
69 pub use self::sty::{Const, ConstKind, ExistentialProjection, PolyExistentialProjection};
70 pub use self::sty::{ConstVid, FloatVid, IntVid, RegionVid, TyVid};
71 pub use self::sty::{ExistentialPredicate, InferConst, InferTy, ParamConst, ParamTy, ProjectionTy};
72 pub use self::sty::{ExistentialTraitRef, PolyExistentialTraitRef};
73 pub use self::sty::{PolyTraitRef, TraitRef, TyKind};
74 pub use crate::ty::diagnostics::*;
76 pub use self::binding::BindingMode;
77 pub use self::binding::BindingMode::*;
79 pub use self::context::{keep_local, tls, AllArenas, FreeRegionInfo, TyCtxt};
80 pub use self::context::{
81 CanonicalUserType, CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations, ResolvedOpaqueTy,
82 UserType, UserTypeAnnotationIndex,
84 pub use self::context::{
85 CtxtInterners, GeneratorInteriorTypeCause, GlobalCtxt, Lift, TypeckTables,
88 pub use self::instance::{Instance, InstanceDef};
90 pub use self::trait_def::TraitDef;
92 pub use self::query::queries;
105 pub mod free_region_map;
106 pub mod inhabitedness;
108 pub mod normalize_erasing_regions;
122 mod structural_impls;
127 pub struct ResolverOutputs {
128 pub definitions: hir_map::Definitions,
129 pub cstore: Box<CrateStoreDyn>,
130 pub extern_crate_map: NodeMap<CrateNum>,
131 pub trait_map: TraitMap,
132 pub maybe_unused_trait_imports: NodeSet,
133 pub maybe_unused_extern_crates: Vec<(NodeId, Span)>,
134 pub export_map: ExportMap<NodeId>,
135 pub glob_map: GlobMap,
136 /// Extern prelude entries. The value is `true` if the entry was introduced
137 /// via `extern crate` item and not `--extern` option or compiler built-in.
138 pub extern_prelude: FxHashMap<Name, bool>,
141 #[derive(Clone, Copy, PartialEq, Eq, Debug, HashStable)]
142 pub enum AssocItemContainer {
143 TraitContainer(DefId),
144 ImplContainer(DefId),
147 impl AssocItemContainer {
148 /// Asserts that this is the `DefId` of an associated item declared
149 /// in a trait, and returns the trait `DefId`.
150 pub fn assert_trait(&self) -> DefId {
152 TraitContainer(id) => id,
153 _ => bug!("associated item has wrong container type: {:?}", self),
157 pub fn id(&self) -> DefId {
159 TraitContainer(id) => id,
160 ImplContainer(id) => id,
165 /// The "header" of an impl is everything outside the body: a Self type, a trait
166 /// ref (in the case of a trait impl), and a set of predicates (from the
167 /// bounds / where-clauses).
168 #[derive(Clone, Debug, TypeFoldable)]
169 pub struct ImplHeader<'tcx> {
170 pub impl_def_id: DefId,
171 pub self_ty: Ty<'tcx>,
172 pub trait_ref: Option<TraitRef<'tcx>>,
173 pub predicates: Vec<Predicate<'tcx>>,
176 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable)]
177 pub enum ImplPolarity {
178 /// `impl Trait for Type`
180 /// `impl !Trait for Type`
182 /// `#[rustc_reservation_impl] impl Trait for Type`
184 /// This is a "stability hack", not a real Rust feature.
185 /// See #64631 for details.
189 #[derive(Copy, Clone, Debug, PartialEq, HashStable)]
190 pub struct AssocItem {
192 #[stable_hasher(project(name))]
196 pub defaultness: hir::Defaultness,
197 pub container: AssocItemContainer,
199 /// Whether this is a method with an explicit self
200 /// as its first argument, allowing method calls.
201 pub method_has_self_argument: bool,
204 #[derive(Copy, Clone, PartialEq, Debug, HashStable)]
213 pub fn suggestion_descr(&self) -> &'static str {
215 ty::AssocKind::Method => "method call",
216 ty::AssocKind::Type | ty::AssocKind::OpaqueTy => "associated type",
217 ty::AssocKind::Const => "associated constant",
223 pub fn def_kind(&self) -> DefKind {
225 AssocKind::Const => DefKind::AssocConst,
226 AssocKind::Method => DefKind::Method,
227 AssocKind::Type => DefKind::AssocTy,
228 AssocKind::OpaqueTy => DefKind::AssocOpaqueTy,
232 /// Tests whether the associated item admits a non-trivial implementation
234 pub fn relevant_for_never(&self) -> bool {
236 AssocKind::OpaqueTy | AssocKind::Const | AssocKind::Type => true,
237 // FIXME(canndrew): Be more thorough here, check if any argument is uninhabited.
238 AssocKind::Method => !self.method_has_self_argument,
242 pub fn signature(&self, tcx: TyCtxt<'_>) -> String {
244 ty::AssocKind::Method => {
245 // We skip the binder here because the binder would deanonymize all
246 // late-bound regions, and we don't want method signatures to show up
247 // `as for<'r> fn(&'r MyType)`. Pretty-printing handles late-bound
248 // regions just fine, showing `fn(&MyType)`.
249 tcx.fn_sig(self.def_id).skip_binder().to_string()
251 ty::AssocKind::Type => format!("type {};", self.ident),
252 // FIXME(type_alias_impl_trait): we should print bounds here too.
253 ty::AssocKind::OpaqueTy => format!("type {};", self.ident),
254 ty::AssocKind::Const => {
255 format!("const {}: {:?};", self.ident, tcx.type_of(self.def_id))
261 #[derive(Clone, Debug, PartialEq, Eq, Copy, RustcEncodable, RustcDecodable, HashStable)]
262 pub enum Visibility {
263 /// Visible everywhere (including in other crates).
265 /// Visible only in the given crate-local module.
267 /// Not visible anywhere in the local crate. This is the visibility of private external items.
271 pub trait DefIdTree: Copy {
272 fn parent(self, id: DefId) -> Option<DefId>;
274 fn is_descendant_of(self, mut descendant: DefId, ancestor: DefId) -> bool {
275 if descendant.krate != ancestor.krate {
279 while descendant != ancestor {
280 match self.parent(descendant) {
281 Some(parent) => descendant = parent,
282 None => return false,
289 impl<'tcx> DefIdTree for TyCtxt<'tcx> {
290 fn parent(self, id: DefId) -> Option<DefId> {
291 self.def_key(id).parent.map(|index| DefId { index: index, ..id })
296 pub fn from_hir(visibility: &hir::Visibility<'_>, id: hir::HirId, tcx: TyCtxt<'_>) -> Self {
297 match visibility.node {
298 hir::VisibilityKind::Public => Visibility::Public,
299 hir::VisibilityKind::Crate(_) => Visibility::Restricted(DefId::local(CRATE_DEF_INDEX)),
300 hir::VisibilityKind::Restricted { ref path, .. } => match path.res {
301 // If there is no resolution, `resolve` will have already reported an error, so
302 // assume that the visibility is public to avoid reporting more privacy errors.
303 Res::Err => Visibility::Public,
304 def => Visibility::Restricted(def.def_id()),
306 hir::VisibilityKind::Inherited => {
307 Visibility::Restricted(tcx.hir().get_module_parent(id))
312 /// Returns `true` if an item with this visibility is accessible from the given block.
313 pub fn is_accessible_from<T: DefIdTree>(self, module: DefId, tree: T) -> bool {
314 let restriction = match self {
315 // Public items are visible everywhere.
316 Visibility::Public => return true,
317 // Private items from other crates are visible nowhere.
318 Visibility::Invisible => return false,
319 // Restricted items are visible in an arbitrary local module.
320 Visibility::Restricted(other) if other.krate != module.krate => return false,
321 Visibility::Restricted(module) => module,
324 tree.is_descendant_of(module, restriction)
327 /// Returns `true` if this visibility is at least as accessible as the given visibility
328 pub fn is_at_least<T: DefIdTree>(self, vis: Visibility, tree: T) -> bool {
329 let vis_restriction = match vis {
330 Visibility::Public => return self == Visibility::Public,
331 Visibility::Invisible => return true,
332 Visibility::Restricted(module) => module,
335 self.is_accessible_from(vis_restriction, tree)
338 // Returns `true` if this item is visible anywhere in the local crate.
339 pub fn is_visible_locally(self) -> bool {
341 Visibility::Public => true,
342 Visibility::Restricted(def_id) => def_id.is_local(),
343 Visibility::Invisible => false,
348 #[derive(Copy, Clone, PartialEq, RustcDecodable, RustcEncodable, HashStable)]
350 Covariant, // T<A> <: T<B> iff A <: B -- e.g., function return type
351 Invariant, // T<A> <: T<B> iff B == A -- e.g., type of mutable cell
352 Contravariant, // T<A> <: T<B> iff B <: A -- e.g., function param type
353 Bivariant, // T<A> <: T<B> -- e.g., unused type parameter
356 /// The crate variances map is computed during typeck and contains the
357 /// variance of every item in the local crate. You should not use it
358 /// directly, because to do so will make your pass dependent on the
359 /// HIR of every item in the local crate. Instead, use
360 /// `tcx.variances_of()` to get the variance for a *particular*
362 #[derive(HashStable)]
363 pub struct CrateVariancesMap<'tcx> {
364 /// For each item with generics, maps to a vector of the variance
365 /// of its generics. If an item has no generics, it will have no
367 pub variances: FxHashMap<DefId, &'tcx [ty::Variance]>,
371 /// `a.xform(b)` combines the variance of a context with the
372 /// variance of a type with the following meaning. If we are in a
373 /// context with variance `a`, and we encounter a type argument in
374 /// a position with variance `b`, then `a.xform(b)` is the new
375 /// variance with which the argument appears.
381 /// Here, the "ambient" variance starts as covariant. `*mut T` is
382 /// invariant with respect to `T`, so the variance in which the
383 /// `Vec<i32>` appears is `Covariant.xform(Invariant)`, which
384 /// yields `Invariant`. Now, the type `Vec<T>` is covariant with
385 /// respect to its type argument `T`, and hence the variance of
386 /// the `i32` here is `Invariant.xform(Covariant)`, which results
387 /// (again) in `Invariant`.
391 /// fn(*const Vec<i32>, *mut Vec<i32)
393 /// The ambient variance is covariant. A `fn` type is
394 /// contravariant with respect to its parameters, so the variance
395 /// within which both pointer types appear is
396 /// `Covariant.xform(Contravariant)`, or `Contravariant`. `*const
397 /// T` is covariant with respect to `T`, so the variance within
398 /// which the first `Vec<i32>` appears is
399 /// `Contravariant.xform(Covariant)` or `Contravariant`. The same
400 /// is true for its `i32` argument. In the `*mut T` case, the
401 /// variance of `Vec<i32>` is `Contravariant.xform(Invariant)`,
402 /// and hence the outermost type is `Invariant` with respect to
403 /// `Vec<i32>` (and its `i32` argument).
405 /// Source: Figure 1 of "Taming the Wildcards:
406 /// Combining Definition- and Use-Site Variance" published in PLDI'11.
407 pub fn xform(self, v: ty::Variance) -> ty::Variance {
409 // Figure 1, column 1.
410 (ty::Covariant, ty::Covariant) => ty::Covariant,
411 (ty::Covariant, ty::Contravariant) => ty::Contravariant,
412 (ty::Covariant, ty::Invariant) => ty::Invariant,
413 (ty::Covariant, ty::Bivariant) => ty::Bivariant,
415 // Figure 1, column 2.
416 (ty::Contravariant, ty::Covariant) => ty::Contravariant,
417 (ty::Contravariant, ty::Contravariant) => ty::Covariant,
418 (ty::Contravariant, ty::Invariant) => ty::Invariant,
419 (ty::Contravariant, ty::Bivariant) => ty::Bivariant,
421 // Figure 1, column 3.
422 (ty::Invariant, _) => ty::Invariant,
424 // Figure 1, column 4.
425 (ty::Bivariant, _) => ty::Bivariant,
430 // Contains information needed to resolve types and (in the future) look up
431 // the types of AST nodes.
432 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
433 pub struct CReaderCacheKey {
438 // Flags that we track on types. These flags are propagated upwards
439 // through the type during type construction, so that we can quickly
440 // check whether the type has various kinds of types in it without
441 // recursing over the type itself.
443 pub struct TypeFlags: u32 {
444 const HAS_PARAMS = 1 << 0;
445 const HAS_TY_INFER = 1 << 1;
446 const HAS_RE_INFER = 1 << 2;
447 const HAS_RE_PLACEHOLDER = 1 << 3;
449 /// Does this have any `ReEarlyBound` regions? Used to
450 /// determine whether substitition is required, since those
451 /// represent regions that are bound in a `ty::Generics` and
452 /// hence may be substituted.
453 const HAS_RE_EARLY_BOUND = 1 << 4;
455 /// Does this have any region that "appears free" in the type?
456 /// Basically anything but `ReLateBound` and `ReErased`.
457 const HAS_FREE_REGIONS = 1 << 5;
459 /// Is an error type reachable?
460 const HAS_TY_ERR = 1 << 6;
461 const HAS_PROJECTION = 1 << 7;
463 // FIXME: Rename this to the actual property since it's used for generators too
464 const HAS_TY_CLOSURE = 1 << 8;
466 /// `true` if there are "names" of types and regions and so forth
467 /// that are local to a particular fn
468 const HAS_FREE_LOCAL_NAMES = 1 << 9;
470 /// Present if the type belongs in a local type context.
471 /// Only set for Infer other than Fresh.
472 const KEEP_IN_LOCAL_TCX = 1 << 10;
474 /// Does this have any `ReLateBound` regions? Used to check
475 /// if a global bound is safe to evaluate.
476 const HAS_RE_LATE_BOUND = 1 << 11;
478 const HAS_TY_PLACEHOLDER = 1 << 12;
480 const HAS_CT_INFER = 1 << 13;
481 const HAS_CT_PLACEHOLDER = 1 << 14;
483 const NEEDS_SUBST = TypeFlags::HAS_PARAMS.bits |
484 TypeFlags::HAS_RE_EARLY_BOUND.bits;
486 /// Flags representing the nominal content of a type,
487 /// computed by FlagsComputation. If you add a new nominal
488 /// flag, it should be added here too.
489 const NOMINAL_FLAGS = TypeFlags::HAS_PARAMS.bits |
490 TypeFlags::HAS_TY_INFER.bits |
491 TypeFlags::HAS_RE_INFER.bits |
492 TypeFlags::HAS_RE_PLACEHOLDER.bits |
493 TypeFlags::HAS_RE_EARLY_BOUND.bits |
494 TypeFlags::HAS_FREE_REGIONS.bits |
495 TypeFlags::HAS_TY_ERR.bits |
496 TypeFlags::HAS_PROJECTION.bits |
497 TypeFlags::HAS_TY_CLOSURE.bits |
498 TypeFlags::HAS_FREE_LOCAL_NAMES.bits |
499 TypeFlags::KEEP_IN_LOCAL_TCX.bits |
500 TypeFlags::HAS_RE_LATE_BOUND.bits |
501 TypeFlags::HAS_TY_PLACEHOLDER.bits |
502 TypeFlags::HAS_CT_INFER.bits |
503 TypeFlags::HAS_CT_PLACEHOLDER.bits;
507 #[allow(rustc::usage_of_ty_tykind)]
508 pub struct TyS<'tcx> {
509 pub kind: TyKind<'tcx>,
510 pub flags: TypeFlags,
512 /// This is a kind of confusing thing: it stores the smallest
515 /// (a) the binder itself captures nothing but
516 /// (b) all the late-bound things within the type are captured
517 /// by some sub-binder.
519 /// So, for a type without any late-bound things, like `u32`, this
520 /// will be *innermost*, because that is the innermost binder that
521 /// captures nothing. But for a type `&'D u32`, where `'D` is a
522 /// late-bound region with De Bruijn index `D`, this would be `D + 1`
523 /// -- the binder itself does not capture `D`, but `D` is captured
524 /// by an inner binder.
526 /// We call this concept an "exclusive" binder `D` because all
527 /// De Bruijn indices within the type are contained within `0..D`
529 outer_exclusive_binder: ty::DebruijnIndex,
532 // `TyS` is used a lot. Make sure it doesn't unintentionally get bigger.
533 #[cfg(target_arch = "x86_64")]
534 static_assert_size!(TyS<'_>, 32);
536 impl<'tcx> Ord for TyS<'tcx> {
537 fn cmp(&self, other: &TyS<'tcx>) -> Ordering {
538 self.kind.cmp(&other.kind)
542 impl<'tcx> PartialOrd for TyS<'tcx> {
543 fn partial_cmp(&self, other: &TyS<'tcx>) -> Option<Ordering> {
544 Some(self.kind.cmp(&other.kind))
548 impl<'tcx> PartialEq for TyS<'tcx> {
550 fn eq(&self, other: &TyS<'tcx>) -> bool {
554 impl<'tcx> Eq for TyS<'tcx> {}
556 impl<'tcx> Hash for TyS<'tcx> {
557 fn hash<H: Hasher>(&self, s: &mut H) {
558 (self as *const TyS<'_>).hash(s)
562 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for ty::TyS<'tcx> {
563 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
567 // The other fields just provide fast access to information that is
568 // also contained in `kind`, so no need to hash them.
571 outer_exclusive_binder: _,
574 kind.hash_stable(hcx, hasher);
578 #[rustc_diagnostic_item = "Ty"]
579 pub type Ty<'tcx> = &'tcx TyS<'tcx>;
581 impl<'tcx> rustc_serialize::UseSpecializedEncodable for Ty<'tcx> {}
582 impl<'tcx> rustc_serialize::UseSpecializedDecodable for Ty<'tcx> {}
584 pub type CanonicalTy<'tcx> = Canonical<'tcx, Ty<'tcx>>;
587 /// A dummy type used to force `List` to be unsized while not requiring references to it be wide
589 type OpaqueListContents;
592 /// A wrapper for slices with the additional invariant
593 /// that the slice is interned and no other slice with
594 /// the same contents can exist in the same context.
595 /// This means we can use pointer for both
596 /// equality comparisons and hashing.
597 /// Note: `Slice` was already taken by the `Ty`.
602 opaque: OpaqueListContents,
605 unsafe impl<T: Sync> Sync for List<T> {}
607 impl<T: Copy> List<T> {
609 fn from_arena<'tcx>(arena: &'tcx SyncDroplessArena, slice: &[T]) -> &'tcx List<T> {
610 assert!(!mem::needs_drop::<T>());
611 assert!(mem::size_of::<T>() != 0);
612 assert!(slice.len() != 0);
614 // Align up the size of the len (usize) field
615 let align = mem::align_of::<T>();
616 let align_mask = align - 1;
617 let offset = mem::size_of::<usize>();
618 let offset = (offset + align_mask) & !align_mask;
620 let size = offset + slice.len() * mem::size_of::<T>();
622 let mem = arena.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(Copy, Clone, TypeFoldable)]
812 pub struct ClosureUpvar<'tcx> {
818 #[derive(Clone, Copy, PartialEq, Eq)]
819 pub enum IntVarValue {
821 UintType(ast::UintTy),
824 #[derive(Clone, Copy, PartialEq, Eq)]
825 pub struct FloatVarValue(pub ast::FloatTy);
827 impl ty::EarlyBoundRegion {
828 pub fn to_bound_region(&self) -> ty::BoundRegion {
829 ty::BoundRegion::BrNamed(self.def_id, self.name)
832 /// Does this early bound region have a name? Early bound regions normally
833 /// always have names except when using anonymous lifetimes (`'_`).
834 pub fn has_name(&self) -> bool {
835 self.name != kw::UnderscoreLifetime
839 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
840 pub enum GenericParamDefKind {
844 object_lifetime_default: ObjectLifetimeDefault,
845 synthetic: Option<hir::SyntheticTyParamKind>,
850 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable)]
851 pub struct GenericParamDef {
856 /// `pure_wrt_drop`, set by the (unsafe) `#[may_dangle]` attribute
857 /// on generic parameter `'a`/`T`, asserts data behind the parameter
858 /// `'a`/`T` won't be accessed during the parent type's `Drop` impl.
859 pub pure_wrt_drop: bool,
861 pub kind: GenericParamDefKind,
864 impl GenericParamDef {
865 pub fn to_early_bound_region_data(&self) -> ty::EarlyBoundRegion {
866 if let GenericParamDefKind::Lifetime = self.kind {
867 ty::EarlyBoundRegion { def_id: self.def_id, index: self.index, name: self.name }
869 bug!("cannot convert a non-lifetime parameter def to an early bound region")
873 pub fn to_bound_region(&self) -> ty::BoundRegion {
874 if let GenericParamDefKind::Lifetime = self.kind {
875 self.to_early_bound_region_data().to_bound_region()
877 bug!("cannot convert a non-lifetime parameter def to an early bound region")
883 pub struct GenericParamCount {
884 pub lifetimes: usize,
889 /// Information about the formal type/lifetime parameters associated
890 /// with an item or method. Analogous to `hir::Generics`.
892 /// The ordering of parameters is the same as in `Subst` (excluding child generics):
893 /// `Self` (optionally), `Lifetime` params..., `Type` params...
894 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
895 pub struct Generics {
896 pub parent: Option<DefId>,
897 pub parent_count: usize,
898 pub params: Vec<GenericParamDef>,
900 /// Reverse map to the `index` field of each `GenericParamDef`.
901 #[stable_hasher(ignore)]
902 pub param_def_id_to_index: FxHashMap<DefId, u32>,
905 pub has_late_bound_regions: Option<Span>,
908 impl<'tcx> Generics {
909 pub fn count(&self) -> usize {
910 self.parent_count + self.params.len()
913 pub fn own_counts(&self) -> GenericParamCount {
914 // We could cache this as a property of `GenericParamCount`, but
915 // the aim is to refactor this away entirely eventually and the
916 // presence of this method will be a constant reminder.
917 let mut own_counts: GenericParamCount = Default::default();
919 for param in &self.params {
921 GenericParamDefKind::Lifetime => own_counts.lifetimes += 1,
922 GenericParamDefKind::Type { .. } => own_counts.types += 1,
923 GenericParamDefKind::Const => own_counts.consts += 1,
930 pub fn requires_monomorphization(&self, tcx: TyCtxt<'tcx>) -> bool {
931 if self.own_requires_monomorphization() {
935 if let Some(parent_def_id) = self.parent {
936 let parent = tcx.generics_of(parent_def_id);
937 parent.requires_monomorphization(tcx)
943 pub fn own_requires_monomorphization(&self) -> bool {
944 for param in &self.params {
946 GenericParamDefKind::Type { .. } | GenericParamDefKind::Const => return true,
947 GenericParamDefKind::Lifetime => {}
955 param: &EarlyBoundRegion,
957 ) -> &'tcx GenericParamDef {
958 if let Some(index) = param.index.checked_sub(self.parent_count as u32) {
959 let param = &self.params[index as usize];
961 GenericParamDefKind::Lifetime => param,
962 _ => bug!("expected lifetime parameter, but found another generic parameter"),
965 tcx.generics_of(self.parent.expect("parent_count > 0 but no parent?"))
966 .region_param(param, tcx)
970 /// Returns the `GenericParamDef` associated with this `ParamTy`.
971 pub fn type_param(&'tcx self, param: &ParamTy, tcx: TyCtxt<'tcx>) -> &'tcx GenericParamDef {
972 if let Some(index) = param.index.checked_sub(self.parent_count as u32) {
973 let param = &self.params[index as usize];
975 GenericParamDefKind::Type { .. } => param,
976 _ => bug!("expected type parameter, but found another generic parameter"),
979 tcx.generics_of(self.parent.expect("parent_count > 0 but no parent?"))
980 .type_param(param, tcx)
984 /// Returns the `ConstParameterDef` associated with this `ParamConst`.
985 pub fn const_param(&'tcx self, param: &ParamConst, tcx: TyCtxt<'tcx>) -> &GenericParamDef {
986 if let Some(index) = param.index.checked_sub(self.parent_count as u32) {
987 let param = &self.params[index as usize];
989 GenericParamDefKind::Const => param,
990 _ => bug!("expected const parameter, but found another generic parameter"),
993 tcx.generics_of(self.parent.expect("parent_count>0 but no parent?"))
994 .const_param(param, tcx)
999 /// Bounds on generics.
1000 #[derive(Copy, Clone, Default, Debug, RustcEncodable, RustcDecodable, HashStable)]
1001 pub struct GenericPredicates<'tcx> {
1002 pub parent: Option<DefId>,
1003 pub predicates: &'tcx [(Predicate<'tcx>, Span)],
1006 impl<'tcx> GenericPredicates<'tcx> {
1010 substs: SubstsRef<'tcx>,
1011 ) -> InstantiatedPredicates<'tcx> {
1012 let mut instantiated = InstantiatedPredicates::empty();
1013 self.instantiate_into(tcx, &mut instantiated, substs);
1017 pub fn instantiate_own(
1020 substs: SubstsRef<'tcx>,
1021 ) -> InstantiatedPredicates<'tcx> {
1022 InstantiatedPredicates {
1023 predicates: self.predicates.iter().map(|(p, _)| p.subst(tcx, substs)).collect(),
1027 fn instantiate_into(
1030 instantiated: &mut InstantiatedPredicates<'tcx>,
1031 substs: SubstsRef<'tcx>,
1033 if let Some(def_id) = self.parent {
1034 tcx.predicates_of(def_id).instantiate_into(tcx, instantiated, substs);
1036 instantiated.predicates.extend(self.predicates.iter().map(|(p, _)| p.subst(tcx, substs)));
1039 pub fn instantiate_identity(&self, tcx: TyCtxt<'tcx>) -> InstantiatedPredicates<'tcx> {
1040 let mut instantiated = InstantiatedPredicates::empty();
1041 self.instantiate_identity_into(tcx, &mut instantiated);
1045 fn instantiate_identity_into(
1048 instantiated: &mut InstantiatedPredicates<'tcx>,
1050 if let Some(def_id) = self.parent {
1051 tcx.predicates_of(def_id).instantiate_identity_into(tcx, instantiated);
1053 instantiated.predicates.extend(self.predicates.iter().map(|&(p, _)| p))
1056 pub fn instantiate_supertrait(
1059 poly_trait_ref: &ty::PolyTraitRef<'tcx>,
1060 ) -> InstantiatedPredicates<'tcx> {
1061 assert_eq!(self.parent, None);
1062 InstantiatedPredicates {
1066 .map(|(pred, _)| pred.subst_supertrait(tcx, poly_trait_ref))
1072 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1073 #[derive(HashStable, TypeFoldable)]
1074 pub enum Predicate<'tcx> {
1075 /// Corresponds to `where Foo: Bar<A, B, C>`. `Foo` here would be
1076 /// the `Self` type of the trait reference and `A`, `B`, and `C`
1077 /// would be the type parameters.
1078 Trait(PolyTraitPredicate<'tcx>),
1081 RegionOutlives(PolyRegionOutlivesPredicate<'tcx>),
1084 TypeOutlives(PolyTypeOutlivesPredicate<'tcx>),
1086 /// `where <T as TraitRef>::Name == X`, approximately.
1087 /// See the `ProjectionPredicate` struct for details.
1088 Projection(PolyProjectionPredicate<'tcx>),
1090 /// No syntax: `T` well-formed.
1091 WellFormed(Ty<'tcx>),
1093 /// Trait must be object-safe.
1096 /// No direct syntax. May be thought of as `where T: FnFoo<...>`
1097 /// for some substitutions `...` and `T` being a closure type.
1098 /// Satisfied (or refuted) once we know the closure's kind.
1099 ClosureKind(DefId, SubstsRef<'tcx>, ClosureKind),
1102 Subtype(PolySubtypePredicate<'tcx>),
1104 /// Constant initializer must evaluate successfully.
1105 ConstEvaluatable(DefId, SubstsRef<'tcx>),
1108 /// The crate outlives map is computed during typeck and contains the
1109 /// outlives of every item in the local crate. You should not use it
1110 /// directly, because to do so will make your pass dependent on the
1111 /// HIR of every item in the local crate. Instead, use
1112 /// `tcx.inferred_outlives_of()` to get the outlives for a *particular*
1114 #[derive(HashStable)]
1115 pub struct CratePredicatesMap<'tcx> {
1116 /// For each struct with outlive bounds, maps to a vector of the
1117 /// predicate of its outlive bounds. If an item has no outlives
1118 /// bounds, it will have no entry.
1119 pub predicates: FxHashMap<DefId, &'tcx [(ty::Predicate<'tcx>, Span)]>,
1122 impl<'tcx> AsRef<Predicate<'tcx>> for Predicate<'tcx> {
1123 fn as_ref(&self) -> &Predicate<'tcx> {
1128 impl<'tcx> Predicate<'tcx> {
1129 /// Performs a substitution suitable for going from a
1130 /// poly-trait-ref to supertraits that must hold if that
1131 /// poly-trait-ref holds. This is slightly different from a normal
1132 /// substitution in terms of what happens with bound regions. See
1133 /// lengthy comment below for details.
1134 pub fn subst_supertrait(
1137 trait_ref: &ty::PolyTraitRef<'tcx>,
1138 ) -> ty::Predicate<'tcx> {
1139 // The interaction between HRTB and supertraits is not entirely
1140 // obvious. Let me walk you (and myself) through an example.
1142 // Let's start with an easy case. Consider two traits:
1144 // trait Foo<'a>: Bar<'a,'a> { }
1145 // trait Bar<'b,'c> { }
1147 // Now, if we have a trait reference `for<'x> T: Foo<'x>`, then
1148 // we can deduce that `for<'x> T: Bar<'x,'x>`. Basically, if we
1149 // knew that `Foo<'x>` (for any 'x) then we also know that
1150 // `Bar<'x,'x>` (for any 'x). This more-or-less falls out from
1151 // normal substitution.
1153 // In terms of why this is sound, the idea is that whenever there
1154 // is an impl of `T:Foo<'a>`, it must show that `T:Bar<'a,'a>`
1155 // holds. So if there is an impl of `T:Foo<'a>` that applies to
1156 // all `'a`, then we must know that `T:Bar<'a,'a>` holds for all
1159 // Another example to be careful of is this:
1161 // trait Foo1<'a>: for<'b> Bar1<'a,'b> { }
1162 // trait Bar1<'b,'c> { }
1164 // Here, if we have `for<'x> T: Foo1<'x>`, then what do we know?
1165 // The answer is that we know `for<'x,'b> T: Bar1<'x,'b>`. The
1166 // reason is similar to the previous example: any impl of
1167 // `T:Foo1<'x>` must show that `for<'b> T: Bar1<'x, 'b>`. So
1168 // basically we would want to collapse the bound lifetimes from
1169 // the input (`trait_ref`) and the supertraits.
1171 // To achieve this in practice is fairly straightforward. Let's
1172 // consider the more complicated scenario:
1174 // - We start out with `for<'x> T: Foo1<'x>`. In this case, `'x`
1175 // has a De Bruijn index of 1. We want to produce `for<'x,'b> T: Bar1<'x,'b>`,
1176 // where both `'x` and `'b` would have a DB index of 1.
1177 // The substitution from the input trait-ref is therefore going to be
1178 // `'a => 'x` (where `'x` has a DB index of 1).
1179 // - The super-trait-ref is `for<'b> Bar1<'a,'b>`, where `'a` is an
1180 // early-bound parameter and `'b' is a late-bound parameter with a
1182 // - If we replace `'a` with `'x` from the input, it too will have
1183 // a DB index of 1, and thus we'll have `for<'x,'b> Bar1<'x,'b>`
1184 // just as we wanted.
1186 // There is only one catch. If we just apply the substitution `'a
1187 // => 'x` to `for<'b> Bar1<'a,'b>`, the substitution code will
1188 // adjust the DB index because we substituting into a binder (it
1189 // tries to be so smart...) resulting in `for<'x> for<'b>
1190 // Bar1<'x,'b>` (we have no syntax for this, so use your
1191 // imagination). Basically the 'x will have DB index of 2 and 'b
1192 // will have DB index of 1. Not quite what we want. So we apply
1193 // the substitution to the *contents* of the trait reference,
1194 // rather than the trait reference itself (put another way, the
1195 // substitution code expects equal binding levels in the values
1196 // from the substitution and the value being substituted into, and
1197 // this trick achieves that).
1199 let substs = &trait_ref.skip_binder().substs;
1201 Predicate::Trait(ref binder) => {
1202 Predicate::Trait(binder.map_bound(|data| data.subst(tcx, substs)))
1204 Predicate::Subtype(ref binder) => {
1205 Predicate::Subtype(binder.map_bound(|data| data.subst(tcx, substs)))
1207 Predicate::RegionOutlives(ref binder) => {
1208 Predicate::RegionOutlives(binder.map_bound(|data| data.subst(tcx, substs)))
1210 Predicate::TypeOutlives(ref binder) => {
1211 Predicate::TypeOutlives(binder.map_bound(|data| data.subst(tcx, substs)))
1213 Predicate::Projection(ref binder) => {
1214 Predicate::Projection(binder.map_bound(|data| data.subst(tcx, substs)))
1216 Predicate::WellFormed(data) => Predicate::WellFormed(data.subst(tcx, substs)),
1217 Predicate::ObjectSafe(trait_def_id) => Predicate::ObjectSafe(trait_def_id),
1218 Predicate::ClosureKind(closure_def_id, closure_substs, kind) => {
1219 Predicate::ClosureKind(closure_def_id, closure_substs.subst(tcx, substs), kind)
1221 Predicate::ConstEvaluatable(def_id, const_substs) => {
1222 Predicate::ConstEvaluatable(def_id, const_substs.subst(tcx, substs))
1228 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1229 #[derive(HashStable, TypeFoldable)]
1230 pub struct TraitPredicate<'tcx> {
1231 pub trait_ref: TraitRef<'tcx>,
1234 pub type PolyTraitPredicate<'tcx> = ty::Binder<TraitPredicate<'tcx>>;
1236 impl<'tcx> TraitPredicate<'tcx> {
1237 pub fn def_id(&self) -> DefId {
1238 self.trait_ref.def_id
1241 pub fn input_types<'a>(&'a self) -> impl DoubleEndedIterator<Item = Ty<'tcx>> + 'a {
1242 self.trait_ref.input_types()
1245 pub fn self_ty(&self) -> Ty<'tcx> {
1246 self.trait_ref.self_ty()
1250 impl<'tcx> PolyTraitPredicate<'tcx> {
1251 pub fn def_id(&self) -> DefId {
1252 // Ok to skip binder since trait `DefId` does not care about regions.
1253 self.skip_binder().def_id()
1257 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, RustcEncodable, RustcDecodable)]
1258 #[derive(HashStable, TypeFoldable)]
1259 pub struct OutlivesPredicate<A, B>(pub A, pub B); // `A: B`
1260 pub type PolyOutlivesPredicate<A, B> = ty::Binder<OutlivesPredicate<A, B>>;
1261 pub type RegionOutlivesPredicate<'tcx> = OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>;
1262 pub type TypeOutlivesPredicate<'tcx> = OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>;
1263 pub type PolyRegionOutlivesPredicate<'tcx> = ty::Binder<RegionOutlivesPredicate<'tcx>>;
1264 pub type PolyTypeOutlivesPredicate<'tcx> = ty::Binder<TypeOutlivesPredicate<'tcx>>;
1266 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
1267 #[derive(HashStable, TypeFoldable)]
1268 pub struct SubtypePredicate<'tcx> {
1269 pub a_is_expected: bool,
1273 pub type PolySubtypePredicate<'tcx> = ty::Binder<SubtypePredicate<'tcx>>;
1275 /// This kind of predicate has no *direct* correspondent in the
1276 /// syntax, but it roughly corresponds to the syntactic forms:
1278 /// 1. `T: TraitRef<..., Item = Type>`
1279 /// 2. `<T as TraitRef<...>>::Item == Type` (NYI)
1281 /// In particular, form #1 is "desugared" to the combination of a
1282 /// normal trait predicate (`T: TraitRef<...>`) and one of these
1283 /// predicates. Form #2 is a broader form in that it also permits
1284 /// equality between arbitrary types. Processing an instance of
1285 /// Form #2 eventually yields one of these `ProjectionPredicate`
1286 /// instances to normalize the LHS.
1287 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1288 #[derive(HashStable, TypeFoldable)]
1289 pub struct ProjectionPredicate<'tcx> {
1290 pub projection_ty: ProjectionTy<'tcx>,
1294 pub type PolyProjectionPredicate<'tcx> = Binder<ProjectionPredicate<'tcx>>;
1296 impl<'tcx> PolyProjectionPredicate<'tcx> {
1297 /// Returns the `DefId` of the associated item being projected.
1298 pub fn item_def_id(&self) -> DefId {
1299 self.skip_binder().projection_ty.item_def_id
1303 pub fn to_poly_trait_ref(&self, tcx: TyCtxt<'tcx>) -> PolyTraitRef<'tcx> {
1304 // Note: unlike with `TraitRef::to_poly_trait_ref()`,
1305 // `self.0.trait_ref` is permitted to have escaping regions.
1306 // This is because here `self` has a `Binder` and so does our
1307 // return value, so we are preserving the number of binding
1309 self.map_bound(|predicate| predicate.projection_ty.trait_ref(tcx))
1312 pub fn ty(&self) -> Binder<Ty<'tcx>> {
1313 self.map_bound(|predicate| predicate.ty)
1316 /// The `DefId` of the `TraitItem` for the associated type.
1318 /// Note that this is not the `DefId` of the `TraitRef` containing this
1319 /// associated type, which is in `tcx.associated_item(projection_def_id()).container`.
1320 pub fn projection_def_id(&self) -> DefId {
1321 // Ok to skip binder since trait `DefId` does not care about regions.
1322 self.skip_binder().projection_ty.item_def_id
1326 pub trait ToPolyTraitRef<'tcx> {
1327 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx>;
1330 impl<'tcx> ToPolyTraitRef<'tcx> for TraitRef<'tcx> {
1331 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
1332 ty::Binder::dummy(self.clone())
1336 impl<'tcx> ToPolyTraitRef<'tcx> for PolyTraitPredicate<'tcx> {
1337 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
1338 self.map_bound_ref(|trait_pred| trait_pred.trait_ref)
1342 pub trait ToPredicate<'tcx> {
1343 fn to_predicate(&self) -> Predicate<'tcx>;
1346 impl<'tcx> ToPredicate<'tcx> for TraitRef<'tcx> {
1347 fn to_predicate(&self) -> Predicate<'tcx> {
1348 ty::Predicate::Trait(ty::Binder::dummy(ty::TraitPredicate { trait_ref: self.clone() }))
1352 impl<'tcx> ToPredicate<'tcx> for PolyTraitRef<'tcx> {
1353 fn to_predicate(&self) -> Predicate<'tcx> {
1354 ty::Predicate::Trait(self.to_poly_trait_predicate())
1358 impl<'tcx> ToPredicate<'tcx> for PolyRegionOutlivesPredicate<'tcx> {
1359 fn to_predicate(&self) -> Predicate<'tcx> {
1360 Predicate::RegionOutlives(self.clone())
1364 impl<'tcx> ToPredicate<'tcx> for PolyTypeOutlivesPredicate<'tcx> {
1365 fn to_predicate(&self) -> Predicate<'tcx> {
1366 Predicate::TypeOutlives(self.clone())
1370 impl<'tcx> ToPredicate<'tcx> for PolyProjectionPredicate<'tcx> {
1371 fn to_predicate(&self) -> Predicate<'tcx> {
1372 Predicate::Projection(self.clone())
1376 // A custom iterator used by `Predicate::walk_tys`.
1377 enum WalkTysIter<'tcx, I, J, K>
1379 I: Iterator<Item = Ty<'tcx>>,
1380 J: Iterator<Item = Ty<'tcx>>,
1381 K: Iterator<Item = Ty<'tcx>>,
1385 Two(Ty<'tcx>, Ty<'tcx>),
1391 impl<'tcx, I, J, K> Iterator for WalkTysIter<'tcx, I, J, K>
1393 I: Iterator<Item = Ty<'tcx>>,
1394 J: Iterator<Item = Ty<'tcx>>,
1395 K: Iterator<Item = Ty<'tcx>>,
1397 type Item = Ty<'tcx>;
1399 fn next(&mut self) -> Option<Ty<'tcx>> {
1401 WalkTysIter::None => None,
1402 WalkTysIter::One(item) => {
1403 *self = WalkTysIter::None;
1406 WalkTysIter::Two(item1, item2) => {
1407 *self = WalkTysIter::One(item2);
1410 WalkTysIter::Types(ref mut iter) => iter.next(),
1411 WalkTysIter::InputTypes(ref mut iter) => iter.next(),
1412 WalkTysIter::ProjectionTypes(ref mut iter) => iter.next(),
1417 impl<'tcx> Predicate<'tcx> {
1418 /// Iterates over the types in this predicate. Note that in all
1419 /// cases this is skipping over a binder, so late-bound regions
1420 /// with depth 0 are bound by the predicate.
1421 pub fn walk_tys(&'a self) -> impl Iterator<Item = Ty<'tcx>> + 'a {
1423 ty::Predicate::Trait(ref data) => {
1424 WalkTysIter::InputTypes(data.skip_binder().input_types())
1426 ty::Predicate::Subtype(binder) => {
1427 let SubtypePredicate { a, b, a_is_expected: _ } = binder.skip_binder();
1428 WalkTysIter::Two(a, b)
1430 ty::Predicate::TypeOutlives(binder) => WalkTysIter::One(binder.skip_binder().0),
1431 ty::Predicate::RegionOutlives(..) => WalkTysIter::None,
1432 ty::Predicate::Projection(ref data) => {
1433 let inner = data.skip_binder();
1434 WalkTysIter::ProjectionTypes(
1435 inner.projection_ty.substs.types().chain(Some(inner.ty)),
1438 ty::Predicate::WellFormed(data) => WalkTysIter::One(data),
1439 ty::Predicate::ObjectSafe(_trait_def_id) => WalkTysIter::None,
1440 ty::Predicate::ClosureKind(_closure_def_id, closure_substs, _kind) => {
1441 WalkTysIter::Types(closure_substs.types())
1443 ty::Predicate::ConstEvaluatable(_, substs) => WalkTysIter::Types(substs.types()),
1447 pub fn to_opt_poly_trait_ref(&self) -> Option<PolyTraitRef<'tcx>> {
1449 Predicate::Trait(ref t) => Some(t.to_poly_trait_ref()),
1450 Predicate::Projection(..)
1451 | Predicate::Subtype(..)
1452 | Predicate::RegionOutlives(..)
1453 | Predicate::WellFormed(..)
1454 | Predicate::ObjectSafe(..)
1455 | Predicate::ClosureKind(..)
1456 | Predicate::TypeOutlives(..)
1457 | Predicate::ConstEvaluatable(..) => None,
1461 pub fn to_opt_type_outlives(&self) -> Option<PolyTypeOutlivesPredicate<'tcx>> {
1463 Predicate::TypeOutlives(data) => Some(data),
1464 Predicate::Trait(..)
1465 | Predicate::Projection(..)
1466 | Predicate::Subtype(..)
1467 | Predicate::RegionOutlives(..)
1468 | Predicate::WellFormed(..)
1469 | Predicate::ObjectSafe(..)
1470 | Predicate::ClosureKind(..)
1471 | Predicate::ConstEvaluatable(..) => None,
1476 /// Represents the bounds declared on a particular set of type
1477 /// parameters. Should eventually be generalized into a flag list of
1478 /// where-clauses. You can obtain a `InstantiatedPredicates` list from a
1479 /// `GenericPredicates` by using the `instantiate` method. Note that this method
1480 /// reflects an important semantic invariant of `InstantiatedPredicates`: while
1481 /// the `GenericPredicates` are expressed in terms of the bound type
1482 /// parameters of the impl/trait/whatever, an `InstantiatedPredicates` instance
1483 /// represented a set of bounds for some particular instantiation,
1484 /// meaning that the generic parameters have been substituted with
1489 /// struct Foo<T, U: Bar<T>> { ... }
1491 /// Here, the `GenericPredicates` for `Foo` would contain a list of bounds like
1492 /// `[[], [U:Bar<T>]]`. Now if there were some particular reference
1493 /// like `Foo<isize,usize>`, then the `InstantiatedPredicates` would be `[[],
1494 /// [usize:Bar<isize>]]`.
1495 #[derive(Clone, Debug, TypeFoldable)]
1496 pub struct InstantiatedPredicates<'tcx> {
1497 pub predicates: Vec<Predicate<'tcx>>,
1500 impl<'tcx> InstantiatedPredicates<'tcx> {
1501 pub fn empty() -> InstantiatedPredicates<'tcx> {
1502 InstantiatedPredicates { predicates: vec![] }
1505 pub fn is_empty(&self) -> bool {
1506 self.predicates.is_empty()
1510 rustc_index::newtype_index! {
1511 /// "Universes" are used during type- and trait-checking in the
1512 /// presence of `for<..>` binders to control what sets of names are
1513 /// visible. Universes are arranged into a tree: the root universe
1514 /// contains names that are always visible. Each child then adds a new
1515 /// set of names that are visible, in addition to those of its parent.
1516 /// We say that the child universe "extends" the parent universe with
1519 /// To make this more concrete, consider this program:
1523 /// fn bar<T>(x: T) {
1524 /// let y: for<'a> fn(&'a u8, Foo) = ...;
1528 /// The struct name `Foo` is in the root universe U0. But the type
1529 /// parameter `T`, introduced on `bar`, is in an extended universe U1
1530 /// -- i.e., within `bar`, we can name both `T` and `Foo`, but outside
1531 /// of `bar`, we cannot name `T`. Then, within the type of `y`, the
1532 /// region `'a` is in a universe U2 that extends U1, because we can
1533 /// name it inside the fn type but not outside.
1535 /// Universes are used to do type- and trait-checking around these
1536 /// "forall" binders (also called **universal quantification**). The
1537 /// idea is that when, in the body of `bar`, we refer to `T` as a
1538 /// type, we aren't referring to any type in particular, but rather a
1539 /// kind of "fresh" type that is distinct from all other types we have
1540 /// actually declared. This is called a **placeholder** type, and we
1541 /// use universes to talk about this. In other words, a type name in
1542 /// universe 0 always corresponds to some "ground" type that the user
1543 /// declared, but a type name in a non-zero universe is a placeholder
1544 /// type -- an idealized representative of "types in general" that we
1545 /// use for checking generic functions.
1546 pub struct UniverseIndex {
1548 DEBUG_FORMAT = "U{}",
1552 impl UniverseIndex {
1553 pub const ROOT: UniverseIndex = UniverseIndex::from_u32_const(0);
1555 /// Returns the "next" universe index in order -- this new index
1556 /// is considered to extend all previous universes. This
1557 /// corresponds to entering a `forall` quantifier. So, for
1558 /// example, suppose we have this type in universe `U`:
1561 /// for<'a> fn(&'a u32)
1564 /// Once we "enter" into this `for<'a>` quantifier, we are in a
1565 /// new universe that extends `U` -- in this new universe, we can
1566 /// name the region `'a`, but that region was not nameable from
1567 /// `U` because it was not in scope there.
1568 pub fn next_universe(self) -> UniverseIndex {
1569 UniverseIndex::from_u32(self.private.checked_add(1).unwrap())
1572 /// Returns `true` if `self` can name a name from `other` -- in other words,
1573 /// if the set of names in `self` is a superset of those in
1574 /// `other` (`self >= other`).
1575 pub fn can_name(self, other: UniverseIndex) -> bool {
1576 self.private >= other.private
1579 /// Returns `true` if `self` cannot name some names from `other` -- in other
1580 /// words, if the set of names in `self` is a strict subset of
1581 /// those in `other` (`self < other`).
1582 pub fn cannot_name(self, other: UniverseIndex) -> bool {
1583 self.private < other.private
1587 /// The "placeholder index" fully defines a placeholder region.
1588 /// Placeholder regions are identified by both a **universe** as well
1589 /// as a "bound-region" within that universe. The `bound_region` is
1590 /// basically a name -- distinct bound regions within the same
1591 /// universe are just two regions with an unknown relationship to one
1593 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, PartialOrd, Ord)]
1594 pub struct Placeholder<T> {
1595 pub universe: UniverseIndex,
1599 impl<'a, T> HashStable<StableHashingContext<'a>> for Placeholder<T>
1601 T: HashStable<StableHashingContext<'a>>,
1603 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
1604 self.universe.hash_stable(hcx, hasher);
1605 self.name.hash_stable(hcx, hasher);
1609 pub type PlaceholderRegion = Placeholder<BoundRegion>;
1611 pub type PlaceholderType = Placeholder<BoundVar>;
1613 pub type PlaceholderConst = Placeholder<BoundVar>;
1615 /// When type checking, we use the `ParamEnv` to track
1616 /// details about the set of where-clauses that are in scope at this
1617 /// particular point.
1618 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable, TypeFoldable)]
1619 pub struct ParamEnv<'tcx> {
1620 /// `Obligation`s that the caller must satisfy. This is basically
1621 /// the set of bounds on the in-scope type parameters, translated
1622 /// into `Obligation`s, and elaborated and normalized.
1623 pub caller_bounds: &'tcx List<ty::Predicate<'tcx>>,
1625 /// Typically, this is `Reveal::UserFacing`, but during codegen we
1626 /// want `Reveal::All` -- note that this is always paired with an
1627 /// empty environment. To get that, use `ParamEnv::reveal()`.
1628 pub reveal: traits::Reveal,
1630 /// If this `ParamEnv` comes from a call to `tcx.param_env(def_id)`,
1631 /// register that `def_id` (useful for transitioning to the chalk trait
1633 pub def_id: Option<DefId>,
1636 impl<'tcx> ParamEnv<'tcx> {
1637 /// Construct a trait environment suitable for contexts where
1638 /// there are no where-clauses in scope. Hidden types (like `impl
1639 /// Trait`) are left hidden, so this is suitable for ordinary
1642 pub fn empty() -> Self {
1643 Self::new(List::empty(), Reveal::UserFacing, None)
1646 /// Construct a trait environment with no where-clauses in scope
1647 /// where the values of all `impl Trait` and other hidden types
1648 /// are revealed. This is suitable for monomorphized, post-typeck
1649 /// environments like codegen or doing optimizations.
1651 /// N.B., if you want to have predicates in scope, use `ParamEnv::new`,
1652 /// or invoke `param_env.with_reveal_all()`.
1654 pub fn reveal_all() -> Self {
1655 Self::new(List::empty(), Reveal::All, None)
1658 /// Construct a trait environment with the given set of predicates.
1661 caller_bounds: &'tcx List<ty::Predicate<'tcx>>,
1663 def_id: Option<DefId>,
1665 ty::ParamEnv { caller_bounds, reveal, def_id }
1668 /// Returns a new parameter environment with the same clauses, but
1669 /// which "reveals" the true results of projections in all cases
1670 /// (even for associated types that are specializable). This is
1671 /// the desired behavior during codegen and certain other special
1672 /// contexts; normally though we want to use `Reveal::UserFacing`,
1673 /// which is the default.
1674 pub fn with_reveal_all(self) -> Self {
1675 ty::ParamEnv { reveal: Reveal::All, ..self }
1678 /// Returns this same environment but with no caller bounds.
1679 pub fn without_caller_bounds(self) -> Self {
1680 ty::ParamEnv { caller_bounds: List::empty(), ..self }
1683 /// Creates a suitable environment in which to perform trait
1684 /// queries on the given value. When type-checking, this is simply
1685 /// the pair of the environment plus value. But when reveal is set to
1686 /// All, then if `value` does not reference any type parameters, we will
1687 /// pair it with the empty environment. This improves caching and is generally
1690 /// N.B., we preserve the environment when type-checking because it
1691 /// is possible for the user to have wacky where-clauses like
1692 /// `where Box<u32>: Copy`, which are clearly never
1693 /// satisfiable. We generally want to behave as if they were true,
1694 /// although the surrounding function is never reachable.
1695 pub fn and<T: TypeFoldable<'tcx>>(self, value: T) -> ParamEnvAnd<'tcx, T> {
1697 Reveal::UserFacing => ParamEnvAnd { param_env: self, value },
1700 if value.has_placeholders() || value.needs_infer() || value.has_param_types() {
1701 ParamEnvAnd { param_env: self, value }
1703 ParamEnvAnd { param_env: self.without_caller_bounds(), value }
1710 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TypeFoldable)]
1711 pub struct ParamEnvAnd<'tcx, T> {
1712 pub param_env: ParamEnv<'tcx>,
1716 impl<'tcx, T> ParamEnvAnd<'tcx, T> {
1717 pub fn into_parts(self) -> (ParamEnv<'tcx>, T) {
1718 (self.param_env, self.value)
1722 impl<'a, 'tcx, T> HashStable<StableHashingContext<'a>> for ParamEnvAnd<'tcx, T>
1724 T: HashStable<StableHashingContext<'a>>,
1726 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
1727 let ParamEnvAnd { ref param_env, ref value } = *self;
1729 param_env.hash_stable(hcx, hasher);
1730 value.hash_stable(hcx, hasher);
1734 #[derive(Copy, Clone, Debug, HashStable)]
1735 pub struct Destructor {
1736 /// The `DefId` of the destructor method
1741 #[derive(HashStable)]
1742 pub struct AdtFlags: u32 {
1743 const NO_ADT_FLAGS = 0;
1744 /// Indicates whether the ADT is an enum.
1745 const IS_ENUM = 1 << 0;
1746 /// Indicates whether the ADT is a union.
1747 const IS_UNION = 1 << 1;
1748 /// Indicates whether the ADT is a struct.
1749 const IS_STRUCT = 1 << 2;
1750 /// Indicates whether the ADT is a struct and has a constructor.
1751 const HAS_CTOR = 1 << 3;
1752 /// Indicates whether the type is a `PhantomData`.
1753 const IS_PHANTOM_DATA = 1 << 4;
1754 /// Indicates whether the type has a `#[fundamental]` attribute.
1755 const IS_FUNDAMENTAL = 1 << 5;
1756 /// Indicates whether the type is a `Box`.
1757 const IS_BOX = 1 << 6;
1758 /// Indicates whether the type is an `Arc`.
1759 const IS_ARC = 1 << 7;
1760 /// Indicates whether the type is an `Rc`.
1761 const IS_RC = 1 << 8;
1762 /// Indicates whether the variant list of this ADT is `#[non_exhaustive]`.
1763 /// (i.e., this flag is never set unless this ADT is an enum).
1764 const IS_VARIANT_LIST_NON_EXHAUSTIVE = 1 << 9;
1769 #[derive(HashStable)]
1770 pub struct VariantFlags: u32 {
1771 const NO_VARIANT_FLAGS = 0;
1772 /// Indicates whether the field list of this variant is `#[non_exhaustive]`.
1773 const IS_FIELD_LIST_NON_EXHAUSTIVE = 1 << 0;
1777 /// Definition of a variant -- a struct's fields or a enum variant.
1778 #[derive(Debug, HashStable)]
1779 pub struct VariantDef {
1780 /// `DefId` that identifies the variant itself.
1781 /// If this variant belongs to a struct or union, then this is a copy of its `DefId`.
1783 /// `DefId` that identifies the variant's constructor.
1784 /// If this variant is a struct variant, then this is `None`.
1785 pub ctor_def_id: Option<DefId>,
1786 /// Variant or struct name.
1787 #[stable_hasher(project(name))]
1789 /// Discriminant of this variant.
1790 pub discr: VariantDiscr,
1791 /// Fields of this variant.
1792 pub fields: Vec<FieldDef>,
1793 /// Type of constructor of variant.
1794 pub ctor_kind: CtorKind,
1795 /// Flags of the variant (e.g. is field list non-exhaustive)?
1796 flags: VariantFlags,
1797 /// Variant is obtained as part of recovering from a syntactic error.
1798 /// May be incomplete or bogus.
1799 pub recovered: bool,
1802 impl<'tcx> VariantDef {
1803 /// Creates a new `VariantDef`.
1805 /// `variant_did` is the `DefId` that identifies the enum variant (if this `VariantDef`
1806 /// represents an enum variant).
1808 /// `ctor_did` is the `DefId` that identifies the constructor of unit or
1809 /// tuple-variants/structs. If this is a `struct`-variant then this should be `None`.
1811 /// `parent_did` is the `DefId` of the `AdtDef` representing the enum or struct that
1812 /// owns this variant. It is used for checking if a struct has `#[non_exhaustive]` w/out having
1813 /// to go through the redirect of checking the ctor's attributes - but compiling a small crate
1814 /// requires loading the `AdtDef`s for all the structs in the universe (e.g., coherence for any
1815 /// built-in trait), and we do not want to load attributes twice.
1817 /// If someone speeds up attribute loading to not be a performance concern, they can
1818 /// remove this hack and use the constructor `DefId` everywhere.
1822 variant_did: Option<DefId>,
1823 ctor_def_id: Option<DefId>,
1824 discr: VariantDiscr,
1825 fields: Vec<FieldDef>,
1826 ctor_kind: CtorKind,
1832 "VariantDef::new(ident = {:?}, variant_did = {:?}, ctor_def_id = {:?}, discr = {:?},
1833 fields = {:?}, ctor_kind = {:?}, adt_kind = {:?}, parent_did = {:?})",
1834 ident, variant_did, ctor_def_id, discr, fields, ctor_kind, adt_kind, parent_did,
1837 let mut flags = VariantFlags::NO_VARIANT_FLAGS;
1838 if adt_kind == AdtKind::Struct && tcx.has_attr(parent_did, sym::non_exhaustive) {
1839 debug!("found non-exhaustive field list for {:?}", parent_did);
1840 flags = flags | VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE;
1841 } else if let Some(variant_did) = variant_did {
1842 if tcx.has_attr(variant_did, sym::non_exhaustive) {
1843 debug!("found non-exhaustive field list for {:?}", variant_did);
1844 flags = flags | VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE;
1849 def_id: variant_did.unwrap_or(parent_did),
1860 /// Is this field list non-exhaustive?
1862 pub fn is_field_list_non_exhaustive(&self) -> bool {
1863 self.flags.intersects(VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE)
1867 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
1868 pub enum VariantDiscr {
1869 /// Explicit value for this variant, i.e., `X = 123`.
1870 /// The `DefId` corresponds to the embedded constant.
1873 /// The previous variant's discriminant plus one.
1874 /// For efficiency reasons, the distance from the
1875 /// last `Explicit` discriminant is being stored,
1876 /// or `0` for the first variant, if it has none.
1880 #[derive(Debug, HashStable)]
1881 pub struct FieldDef {
1883 #[stable_hasher(project(name))]
1885 pub vis: Visibility,
1888 /// The definition of a user-defined type, e.g., a `struct`, `enum`, or `union`.
1890 /// These are all interned (by `intern_adt_def`) into the `adt_defs` table.
1892 /// The initialism *ADT* stands for an [*algebraic data type (ADT)*][adt].
1893 /// This is slightly wrong because `union`s are not ADTs.
1894 /// Moreover, Rust only allows recursive data types through indirection.
1896 /// [adt]: https://en.wikipedia.org/wiki/Algebraic_data_type
1898 /// The `DefId` of the struct, enum or union item.
1900 /// Variants of the ADT. If this is a struct or union, then there will be a single variant.
1901 pub variants: IndexVec<self::layout::VariantIdx, VariantDef>,
1902 /// Flags of the ADT (e.g., is this a struct? is this non-exhaustive?).
1904 /// Repr options provided by the user.
1905 pub repr: ReprOptions,
1908 impl PartialOrd for AdtDef {
1909 fn partial_cmp(&self, other: &AdtDef) -> Option<Ordering> {
1910 Some(self.cmp(&other))
1914 /// There should be only one AdtDef for each `did`, therefore
1915 /// it is fine to implement `Ord` only based on `did`.
1916 impl Ord for AdtDef {
1917 fn cmp(&self, other: &AdtDef) -> Ordering {
1918 self.did.cmp(&other.did)
1922 impl PartialEq for AdtDef {
1923 // `AdtDef`s are always interned, and this is part of `TyS` equality.
1925 fn eq(&self, other: &Self) -> bool {
1926 ptr::eq(self, other)
1930 impl Eq for AdtDef {}
1932 impl Hash for AdtDef {
1934 fn hash<H: Hasher>(&self, s: &mut H) {
1935 (self as *const AdtDef).hash(s)
1939 impl<'tcx> rustc_serialize::UseSpecializedEncodable for &'tcx AdtDef {
1940 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1945 impl<'tcx> rustc_serialize::UseSpecializedDecodable for &'tcx AdtDef {}
1947 impl<'a> HashStable<StableHashingContext<'a>> for AdtDef {
1948 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
1950 static CACHE: RefCell<FxHashMap<usize, Fingerprint>> = Default::default();
1953 let hash: Fingerprint = CACHE.with(|cache| {
1954 let addr = self as *const AdtDef as usize;
1955 *cache.borrow_mut().entry(addr).or_insert_with(|| {
1956 let ty::AdtDef { did, ref variants, ref flags, ref repr } = *self;
1958 let mut hasher = StableHasher::new();
1959 did.hash_stable(hcx, &mut hasher);
1960 variants.hash_stable(hcx, &mut hasher);
1961 flags.hash_stable(hcx, &mut hasher);
1962 repr.hash_stable(hcx, &mut hasher);
1968 hash.hash_stable(hcx, hasher);
1972 #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
1979 impl Into<DataTypeKind> for AdtKind {
1980 fn into(self) -> DataTypeKind {
1982 AdtKind::Struct => DataTypeKind::Struct,
1983 AdtKind::Union => DataTypeKind::Union,
1984 AdtKind::Enum => DataTypeKind::Enum,
1990 #[derive(RustcEncodable, RustcDecodable, Default, HashStable)]
1991 pub struct ReprFlags: u8 {
1992 const IS_C = 1 << 0;
1993 const IS_SIMD = 1 << 1;
1994 const IS_TRANSPARENT = 1 << 2;
1995 // Internal only for now. If true, don't reorder fields.
1996 const IS_LINEAR = 1 << 3;
1998 // Any of these flags being set prevent field reordering optimisation.
1999 const IS_UNOPTIMISABLE = ReprFlags::IS_C.bits |
2000 ReprFlags::IS_SIMD.bits |
2001 ReprFlags::IS_LINEAR.bits;
2005 /// Represents the repr options provided by the user,
2006 #[derive(Copy, Clone, Debug, Eq, PartialEq, RustcEncodable, RustcDecodable, Default, HashStable)]
2007 pub struct ReprOptions {
2008 pub int: Option<attr::IntType>,
2009 pub align: Option<Align>,
2010 pub pack: Option<Align>,
2011 pub flags: ReprFlags,
2015 pub fn new(tcx: TyCtxt<'_>, did: DefId) -> ReprOptions {
2016 let mut flags = ReprFlags::empty();
2017 let mut size = None;
2018 let mut max_align: Option<Align> = None;
2019 let mut min_pack: Option<Align> = None;
2020 for attr in tcx.get_attrs(did).iter() {
2021 for r in attr::find_repr_attrs(&tcx.sess.parse_sess, attr) {
2022 flags.insert(match r {
2023 attr::ReprC => ReprFlags::IS_C,
2024 attr::ReprPacked(pack) => {
2025 let pack = Align::from_bytes(pack as u64).unwrap();
2026 min_pack = Some(if let Some(min_pack) = min_pack {
2033 attr::ReprTransparent => ReprFlags::IS_TRANSPARENT,
2034 attr::ReprSimd => ReprFlags::IS_SIMD,
2035 attr::ReprInt(i) => {
2039 attr::ReprAlign(align) => {
2040 max_align = max_align.max(Some(Align::from_bytes(align as u64).unwrap()));
2047 // This is here instead of layout because the choice must make it into metadata.
2048 if !tcx.consider_optimizing(|| format!("Reorder fields of {:?}", tcx.def_path_str(did))) {
2049 flags.insert(ReprFlags::IS_LINEAR);
2051 ReprOptions { int: size, align: max_align, pack: min_pack, flags: flags }
2055 pub fn simd(&self) -> bool {
2056 self.flags.contains(ReprFlags::IS_SIMD)
2059 pub fn c(&self) -> bool {
2060 self.flags.contains(ReprFlags::IS_C)
2063 pub fn packed(&self) -> bool {
2067 pub fn transparent(&self) -> bool {
2068 self.flags.contains(ReprFlags::IS_TRANSPARENT)
2071 pub fn linear(&self) -> bool {
2072 self.flags.contains(ReprFlags::IS_LINEAR)
2075 pub fn discr_type(&self) -> attr::IntType {
2076 self.int.unwrap_or(attr::SignedInt(ast::IntTy::Isize))
2079 /// Returns `true` if this `#[repr()]` should inhabit "smart enum
2080 /// layout" optimizations, such as representing `Foo<&T>` as a
2082 pub fn inhibit_enum_layout_opt(&self) -> bool {
2083 self.c() || self.int.is_some()
2086 /// Returns `true` if this `#[repr()]` should inhibit struct field reordering
2087 /// optimizations, such as with `repr(C)`, `repr(packed(1))`, or `repr(<int>)`.
2088 pub fn inhibit_struct_field_reordering_opt(&self) -> bool {
2089 if let Some(pack) = self.pack {
2090 if pack.bytes() == 1 {
2094 self.flags.intersects(ReprFlags::IS_UNOPTIMISABLE) || self.int.is_some()
2097 /// Returns `true` if this `#[repr()]` should inhibit union ABI optimisations.
2098 pub fn inhibit_union_abi_opt(&self) -> bool {
2104 /// Creates a new `AdtDef`.
2109 variants: IndexVec<VariantIdx, VariantDef>,
2112 debug!("AdtDef::new({:?}, {:?}, {:?}, {:?})", did, kind, variants, repr);
2113 let mut flags = AdtFlags::NO_ADT_FLAGS;
2115 if kind == AdtKind::Enum && tcx.has_attr(did, sym::non_exhaustive) {
2116 debug!("found non-exhaustive variant list for {:?}", did);
2117 flags = flags | AdtFlags::IS_VARIANT_LIST_NON_EXHAUSTIVE;
2120 flags |= match kind {
2121 AdtKind::Enum => AdtFlags::IS_ENUM,
2122 AdtKind::Union => AdtFlags::IS_UNION,
2123 AdtKind::Struct => AdtFlags::IS_STRUCT,
2126 if kind == AdtKind::Struct && variants[VariantIdx::new(0)].ctor_def_id.is_some() {
2127 flags |= AdtFlags::HAS_CTOR;
2130 let attrs = tcx.get_attrs(did);
2131 if attr::contains_name(&attrs, sym::fundamental) {
2132 flags |= AdtFlags::IS_FUNDAMENTAL;
2134 if Some(did) == tcx.lang_items().phantom_data() {
2135 flags |= AdtFlags::IS_PHANTOM_DATA;
2137 if Some(did) == tcx.lang_items().owned_box() {
2138 flags |= AdtFlags::IS_BOX;
2140 if Some(did) == tcx.lang_items().arc() {
2141 flags |= AdtFlags::IS_ARC;
2143 if Some(did) == tcx.lang_items().rc() {
2144 flags |= AdtFlags::IS_RC;
2147 AdtDef { did, variants, flags, repr }
2150 /// Returns `true` if this is a struct.
2152 pub fn is_struct(&self) -> bool {
2153 self.flags.contains(AdtFlags::IS_STRUCT)
2156 /// Returns `true` if this is a union.
2158 pub fn is_union(&self) -> bool {
2159 self.flags.contains(AdtFlags::IS_UNION)
2162 /// Returns `true` if this is a enum.
2164 pub fn is_enum(&self) -> bool {
2165 self.flags.contains(AdtFlags::IS_ENUM)
2168 /// Returns `true` if the variant list of this ADT is `#[non_exhaustive]`.
2170 pub fn is_variant_list_non_exhaustive(&self) -> bool {
2171 self.flags.contains(AdtFlags::IS_VARIANT_LIST_NON_EXHAUSTIVE)
2174 /// Returns the kind of the ADT.
2176 pub fn adt_kind(&self) -> AdtKind {
2179 } else if self.is_union() {
2186 /// Returns a description of this abstract data type.
2187 pub fn descr(&self) -> &'static str {
2188 match self.adt_kind() {
2189 AdtKind::Struct => "struct",
2190 AdtKind::Union => "union",
2191 AdtKind::Enum => "enum",
2195 /// Returns a description of a variant of this abstract data type.
2197 pub fn variant_descr(&self) -> &'static str {
2198 match self.adt_kind() {
2199 AdtKind::Struct => "struct",
2200 AdtKind::Union => "union",
2201 AdtKind::Enum => "variant",
2205 /// If this function returns `true`, it implies that `is_struct` must return `true`.
2207 pub fn has_ctor(&self) -> bool {
2208 self.flags.contains(AdtFlags::HAS_CTOR)
2211 /// Returns `true` if this type is `#[fundamental]` for the purposes
2212 /// of coherence checking.
2214 pub fn is_fundamental(&self) -> bool {
2215 self.flags.contains(AdtFlags::IS_FUNDAMENTAL)
2218 /// Returns `true` if this is `PhantomData<T>`.
2220 pub fn is_phantom_data(&self) -> bool {
2221 self.flags.contains(AdtFlags::IS_PHANTOM_DATA)
2224 /// Returns `true` if this is `Arc<T>`.
2225 pub fn is_arc(&self) -> bool {
2226 self.flags.contains(AdtFlags::IS_ARC)
2229 /// Returns `true` if this is `Rc<T>`.
2230 pub fn is_rc(&self) -> bool {
2231 self.flags.contains(AdtFlags::IS_RC)
2234 /// Returns `true` if this is Box<T>.
2236 pub fn is_box(&self) -> bool {
2237 self.flags.contains(AdtFlags::IS_BOX)
2240 /// Returns `true` if this type has a destructor.
2241 pub fn has_dtor(&self, tcx: TyCtxt<'tcx>) -> bool {
2242 self.destructor(tcx).is_some()
2245 /// Asserts this is a struct or union and returns its unique variant.
2246 pub fn non_enum_variant(&self) -> &VariantDef {
2247 assert!(self.is_struct() || self.is_union());
2248 &self.variants[VariantIdx::new(0)]
2252 pub fn predicates(&self, tcx: TyCtxt<'tcx>) -> GenericPredicates<'tcx> {
2253 tcx.predicates_of(self.did)
2256 /// Returns an iterator over all fields contained
2259 pub fn all_fields(&self) -> impl Iterator<Item = &FieldDef> + Clone {
2260 self.variants.iter().flat_map(|v| v.fields.iter())
2263 pub fn is_payloadfree(&self) -> bool {
2264 !self.variants.is_empty() && self.variants.iter().all(|v| v.fields.is_empty())
2267 /// Return a `VariantDef` given a variant id.
2268 pub fn variant_with_id(&self, vid: DefId) -> &VariantDef {
2269 self.variants.iter().find(|v| v.def_id == vid).expect("variant_with_id: unknown variant")
2272 /// Return a `VariantDef` given a constructor id.
2273 pub fn variant_with_ctor_id(&self, cid: DefId) -> &VariantDef {
2276 .find(|v| v.ctor_def_id == Some(cid))
2277 .expect("variant_with_ctor_id: unknown variant")
2280 /// Return the index of `VariantDef` given a variant id.
2281 pub fn variant_index_with_id(&self, vid: DefId) -> VariantIdx {
2284 .find(|(_, v)| v.def_id == vid)
2285 .expect("variant_index_with_id: unknown variant")
2289 /// Return the index of `VariantDef` given a constructor id.
2290 pub fn variant_index_with_ctor_id(&self, cid: DefId) -> VariantIdx {
2293 .find(|(_, v)| v.ctor_def_id == Some(cid))
2294 .expect("variant_index_with_ctor_id: unknown variant")
2298 pub fn variant_of_res(&self, res: Res) -> &VariantDef {
2300 Res::Def(DefKind::Variant, vid) => self.variant_with_id(vid),
2301 Res::Def(DefKind::Ctor(..), cid) => self.variant_with_ctor_id(cid),
2302 Res::Def(DefKind::Struct, _)
2303 | Res::Def(DefKind::Union, _)
2304 | Res::Def(DefKind::TyAlias, _)
2305 | Res::Def(DefKind::AssocTy, _)
2307 | Res::SelfCtor(..) => self.non_enum_variant(),
2308 _ => bug!("unexpected res {:?} in variant_of_res", res),
2313 pub fn eval_explicit_discr(&self, tcx: TyCtxt<'tcx>, expr_did: DefId) -> Option<Discr<'tcx>> {
2314 let param_env = tcx.param_env(expr_did);
2315 let repr_type = self.repr.discr_type();
2316 match tcx.const_eval_poly(expr_did) {
2318 // FIXME: Find the right type and use it instead of `val.ty` here
2319 if let Some(b) = val.try_eval_bits(tcx, param_env, val.ty) {
2320 trace!("discriminants: {} ({:?})", b, repr_type);
2321 Some(Discr { val: b, ty: val.ty })
2323 info!("invalid enum discriminant: {:#?}", val);
2324 crate::mir::interpret::struct_error(
2325 tcx.at(tcx.def_span(expr_did)),
2326 "constant evaluation of enum discriminant resulted in non-integer",
2332 Err(ErrorHandled::Reported) => {
2333 if !expr_did.is_local() {
2335 tcx.def_span(expr_did),
2336 "variant discriminant evaluation succeeded \
2337 in its crate but failed locally"
2342 Err(ErrorHandled::TooGeneric) => {
2343 span_bug!(tcx.def_span(expr_did), "enum discriminant depends on generic arguments",)
2349 pub fn discriminants(
2352 ) -> impl Iterator<Item = (VariantIdx, Discr<'tcx>)> + Captures<'tcx> {
2353 let repr_type = self.repr.discr_type();
2354 let initial = repr_type.initial_discriminant(tcx);
2355 let mut prev_discr = None::<Discr<'tcx>>;
2356 self.variants.iter_enumerated().map(move |(i, v)| {
2357 let mut discr = prev_discr.map_or(initial, |d| d.wrap_incr(tcx));
2358 if let VariantDiscr::Explicit(expr_did) = v.discr {
2359 if let Some(new_discr) = self.eval_explicit_discr(tcx, expr_did) {
2363 prev_discr = Some(discr);
2370 pub fn variant_range(&self) -> Range<VariantIdx> {
2371 (VariantIdx::new(0)..VariantIdx::new(self.variants.len()))
2374 /// Computes the discriminant value used by a specific variant.
2375 /// Unlike `discriminants`, this is (amortized) constant-time,
2376 /// only doing at most one query for evaluating an explicit
2377 /// discriminant (the last one before the requested variant),
2378 /// assuming there are no constant-evaluation errors there.
2380 pub fn discriminant_for_variant(
2383 variant_index: VariantIdx,
2385 let (val, offset) = self.discriminant_def_for_variant(variant_index);
2386 let explicit_value = val
2387 .and_then(|expr_did| self.eval_explicit_discr(tcx, expr_did))
2388 .unwrap_or_else(|| self.repr.discr_type().initial_discriminant(tcx));
2389 explicit_value.checked_add(tcx, offset as u128).0
2392 /// Yields a `DefId` for the discriminant and an offset to add to it
2393 /// Alternatively, if there is no explicit discriminant, returns the
2394 /// inferred discriminant directly.
2395 pub fn discriminant_def_for_variant(&self, variant_index: VariantIdx) -> (Option<DefId>, u32) {
2396 let mut explicit_index = variant_index.as_u32();
2399 match self.variants[VariantIdx::from_u32(explicit_index)].discr {
2400 ty::VariantDiscr::Relative(0) => {
2404 ty::VariantDiscr::Relative(distance) => {
2405 explicit_index -= distance;
2407 ty::VariantDiscr::Explicit(did) => {
2408 expr_did = Some(did);
2413 (expr_did, variant_index.as_u32() - explicit_index)
2416 pub fn destructor(&self, tcx: TyCtxt<'tcx>) -> Option<Destructor> {
2417 tcx.adt_destructor(self.did)
2420 /// Returns a list of types such that `Self: Sized` if and only
2421 /// if that type is `Sized`, or `TyErr` if this type is recursive.
2423 /// Oddly enough, checking that the sized-constraint is `Sized` is
2424 /// actually more expressive than checking all members:
2425 /// the `Sized` trait is inductive, so an associated type that references
2426 /// `Self` would prevent its containing ADT from being `Sized`.
2428 /// Due to normalization being eager, this applies even if
2429 /// the associated type is behind a pointer (e.g., issue #31299).
2430 pub fn sized_constraint(&self, tcx: TyCtxt<'tcx>) -> &'tcx [Ty<'tcx>] {
2431 tcx.adt_sized_constraint(self.did).0
2434 fn sized_constraint_for_ty(&self, tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Vec<Ty<'tcx>> {
2435 let result = match ty.kind {
2436 Bool | Char | Int(..) | Uint(..) | Float(..) | RawPtr(..) | Ref(..) | FnDef(..)
2437 | FnPtr(_) | Array(..) | Closure(..) | Generator(..) | Never => vec![],
2439 Str | Dynamic(..) | Slice(_) | Foreign(..) | Error | GeneratorWitness(..) => {
2440 // these are never sized - return the target type
2444 Tuple(ref tys) => match tys.last() {
2446 Some(ty) => self.sized_constraint_for_ty(tcx, ty.expect_ty()),
2449 Adt(adt, substs) => {
2451 let adt_tys = adt.sized_constraint(tcx);
2452 debug!("sized_constraint_for_ty({:?}) intermediate = {:?}", ty, adt_tys);
2455 .map(|ty| ty.subst(tcx, substs))
2456 .flat_map(|ty| self.sized_constraint_for_ty(tcx, ty))
2460 Projection(..) | Opaque(..) => {
2461 // must calculate explicitly.
2462 // FIXME: consider special-casing always-Sized projections
2466 UnnormalizedProjection(..) => bug!("only used with chalk-engine"),
2469 // perf hack: if there is a `T: Sized` bound, then
2470 // we know that `T` is Sized and do not need to check
2473 let sized_trait = match tcx.lang_items().sized_trait() {
2475 _ => return vec![ty],
2477 let sized_predicate = Binder::dummy(TraitRef {
2478 def_id: sized_trait,
2479 substs: tcx.mk_substs_trait(ty, &[]),
2482 let predicates = tcx.predicates_of(self.did).predicates;
2483 if predicates.iter().any(|(p, _)| *p == sized_predicate) {
2490 Placeholder(..) | Bound(..) | Infer(..) => {
2491 bug!("unexpected type `{:?}` in sized_constraint_for_ty", ty)
2494 debug!("sized_constraint_for_ty({:?}) = {:?}", ty, result);
2499 impl<'tcx> FieldDef {
2500 /// Returns the type of this field. The `subst` is typically obtained
2501 /// via the second field of `TyKind::AdtDef`.
2502 pub fn ty(&self, tcx: TyCtxt<'tcx>, subst: SubstsRef<'tcx>) -> Ty<'tcx> {
2503 tcx.type_of(self.did).subst(tcx, subst)
2507 /// Represents the various closure traits in the language. This
2508 /// will determine the type of the environment (`self`, in the
2509 /// desugaring) argument that the closure expects.
2511 /// You can get the environment type of a closure using
2512 /// `tcx.closure_env_ty()`.
2526 pub enum ClosureKind {
2527 // Warning: Ordering is significant here! The ordering is chosen
2528 // because the trait Fn is a subtrait of FnMut and so in turn, and
2529 // hence we order it so that Fn < FnMut < FnOnce.
2535 impl<'tcx> ClosureKind {
2536 // This is the initial value used when doing upvar inference.
2537 pub const LATTICE_BOTTOM: ClosureKind = ClosureKind::Fn;
2539 pub fn trait_did(&self, tcx: TyCtxt<'tcx>) -> DefId {
2541 ClosureKind::Fn => tcx.require_lang_item(FnTraitLangItem, None),
2542 ClosureKind::FnMut => tcx.require_lang_item(FnMutTraitLangItem, None),
2543 ClosureKind::FnOnce => tcx.require_lang_item(FnOnceTraitLangItem, None),
2547 /// Returns `true` if this a type that impls this closure kind
2548 /// must also implement `other`.
2549 pub fn extends(self, other: ty::ClosureKind) -> bool {
2550 match (self, other) {
2551 (ClosureKind::Fn, ClosureKind::Fn) => true,
2552 (ClosureKind::Fn, ClosureKind::FnMut) => true,
2553 (ClosureKind::Fn, ClosureKind::FnOnce) => true,
2554 (ClosureKind::FnMut, ClosureKind::FnMut) => true,
2555 (ClosureKind::FnMut, ClosureKind::FnOnce) => true,
2556 (ClosureKind::FnOnce, ClosureKind::FnOnce) => true,
2561 /// Returns the representative scalar type for this closure kind.
2562 /// See `TyS::to_opt_closure_kind` for more details.
2563 pub fn to_ty(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
2565 ty::ClosureKind::Fn => tcx.types.i8,
2566 ty::ClosureKind::FnMut => tcx.types.i16,
2567 ty::ClosureKind::FnOnce => tcx.types.i32,
2572 impl<'tcx> TyS<'tcx> {
2573 /// Iterator that walks `self` and any types reachable from
2574 /// `self`, in depth-first order. Note that just walks the types
2575 /// that appear in `self`, it does not descend into the fields of
2576 /// structs or variants. For example:
2579 /// isize => { isize }
2580 /// Foo<Bar<isize>> => { Foo<Bar<isize>>, Bar<isize>, isize }
2581 /// [isize] => { [isize], isize }
2583 pub fn walk(&'tcx self) -> TypeWalker<'tcx> {
2584 TypeWalker::new(self)
2587 /// Iterator that walks the immediate children of `self`. Hence
2588 /// `Foo<Bar<i32>, u32>` yields the sequence `[Bar<i32>, u32]`
2589 /// (but not `i32`, like `walk`).
2590 pub fn walk_shallow(&'tcx self) -> smallvec::IntoIter<walk::TypeWalkerArray<'tcx>> {
2591 walk::walk_shallow(self)
2594 /// Walks `ty` and any types appearing within `ty`, invoking the
2595 /// callback `f` on each type. If the callback returns `false`, then the
2596 /// children of the current type are ignored.
2598 /// Note: prefer `ty.walk()` where possible.
2599 pub fn maybe_walk<F>(&'tcx self, mut f: F)
2601 F: FnMut(Ty<'tcx>) -> bool,
2603 let mut walker = self.walk();
2604 while let Some(ty) = walker.next() {
2606 walker.skip_current_subtree();
2613 pub fn from_mutbl(m: hir::Mutability) -> BorrowKind {
2615 hir::Mutability::Mut => MutBorrow,
2616 hir::Mutability::Not => ImmBorrow,
2620 /// Returns a mutability `m` such that an `&m T` pointer could be used to obtain this borrow
2621 /// kind. Because borrow kinds are richer than mutabilities, we sometimes have to pick a
2622 /// mutability that is stronger than necessary so that it at least *would permit* the borrow in
2624 pub fn to_mutbl_lossy(self) -> hir::Mutability {
2626 MutBorrow => hir::Mutability::Mut,
2627 ImmBorrow => hir::Mutability::Not,
2629 // We have no type corresponding to a unique imm borrow, so
2630 // use `&mut`. It gives all the capabilities of an `&uniq`
2631 // and hence is a safe "over approximation".
2632 UniqueImmBorrow => hir::Mutability::Mut,
2636 pub fn to_user_str(&self) -> &'static str {
2638 MutBorrow => "mutable",
2639 ImmBorrow => "immutable",
2640 UniqueImmBorrow => "uniquely immutable",
2645 #[derive(Debug, Clone)]
2646 pub enum Attributes<'tcx> {
2647 Owned(Lrc<[ast::Attribute]>),
2648 Borrowed(&'tcx [ast::Attribute]),
2651 impl<'tcx> ::std::ops::Deref for Attributes<'tcx> {
2652 type Target = [ast::Attribute];
2654 fn deref(&self) -> &[ast::Attribute] {
2656 &Attributes::Owned(ref data) => &data,
2657 &Attributes::Borrowed(data) => data,
2662 #[derive(Debug, PartialEq, Eq)]
2663 pub enum ImplOverlapKind {
2664 /// These impls are always allowed to overlap.
2666 /// These impls are allowed to overlap, but that raises
2667 /// an issue #33140 future-compatibility warning.
2669 /// Some background: in Rust 1.0, the trait-object types `Send + Sync` (today's
2670 /// `dyn Send + Sync`) and `Sync + Send` (now `dyn Sync + Send`) were different.
2672 /// The widely-used version 0.1.0 of the crate `traitobject` had accidentally relied
2673 /// that difference, making what reduces to the following set of impls:
2677 /// impl Trait for dyn Send + Sync {}
2678 /// impl Trait for dyn Sync + Send {}
2681 /// Obviously, once we made these types be identical, that code causes a coherence
2682 /// error and a fairly big headache for us. However, luckily for us, the trait
2683 /// `Trait` used in this case is basically a marker trait, and therefore having
2684 /// overlapping impls for it is sound.
2686 /// To handle this, we basically regard the trait as a marker trait, with an additional
2687 /// future-compatibility warning. To avoid accidentally "stabilizing" this feature,
2688 /// it has the following restrictions:
2690 /// 1. The trait must indeed be a marker-like trait (i.e., no items), and must be
2692 /// 2. The trait-ref of both impls must be equal.
2693 /// 3. The trait-ref of both impls must be a trait object type consisting only of
2695 /// 4. Neither of the impls can have any where-clauses.
2697 /// Once `traitobject` 0.1.0 is no longer an active concern, this hack can be removed.
2701 impl<'tcx> TyCtxt<'tcx> {
2702 pub fn body_tables(self, body: hir::BodyId) -> &'tcx TypeckTables<'tcx> {
2703 self.typeck_tables_of(self.hir().body_owner_def_id(body))
2706 /// Returns an iterator of the `DefId`s for all body-owners in this
2707 /// crate. If you would prefer to iterate over the bodies
2708 /// themselves, you can do `self.hir().krate().body_ids.iter()`.
2709 pub fn body_owners(self) -> impl Iterator<Item = DefId> + Captures<'tcx> + 'tcx {
2714 .map(move |&body_id| self.hir().body_owner_def_id(body_id))
2717 pub fn par_body_owners<F: Fn(DefId) + sync::Sync + sync::Send>(self, f: F) {
2718 par_iter(&self.hir().krate().body_ids)
2719 .for_each(|&body_id| f(self.hir().body_owner_def_id(body_id)));
2722 pub fn provided_trait_methods(self, id: DefId) -> Vec<AssocItem> {
2723 self.associated_items(id)
2724 .filter(|item| item.kind == AssocKind::Method && item.defaultness.has_value())
2728 pub fn trait_relevant_for_never(self, did: DefId) -> bool {
2729 self.associated_items(did).any(|item| item.relevant_for_never())
2732 pub fn opt_item_name(self, def_id: DefId) -> Option<Ident> {
2733 self.hir().as_local_hir_id(def_id).and_then(|hir_id| self.hir().get(hir_id).ident())
2736 pub fn opt_associated_item(self, def_id: DefId) -> Option<AssocItem> {
2737 let is_associated_item = if let Some(hir_id) = self.hir().as_local_hir_id(def_id) {
2738 match self.hir().get(hir_id) {
2739 Node::TraitItem(_) | Node::ImplItem(_) => true,
2743 match self.def_kind(def_id).expect("no def for `DefId`") {
2744 DefKind::AssocConst | DefKind::Method | DefKind::AssocTy => true,
2749 is_associated_item.then(|| self.associated_item(def_id))
2752 fn associated_item_from_trait_item_ref(
2754 parent_def_id: DefId,
2755 parent_vis: &hir::Visibility<'_>,
2756 trait_item_ref: &hir::TraitItemRef,
2758 let def_id = self.hir().local_def_id(trait_item_ref.id.hir_id);
2759 let (kind, has_self) = match trait_item_ref.kind {
2760 hir::AssocItemKind::Const => (ty::AssocKind::Const, false),
2761 hir::AssocItemKind::Method { has_self } => (ty::AssocKind::Method, has_self),
2762 hir::AssocItemKind::Type => (ty::AssocKind::Type, false),
2763 hir::AssocItemKind::OpaqueTy => bug!("only impls can have opaque types"),
2767 ident: trait_item_ref.ident,
2769 // Visibility of trait items is inherited from their traits.
2770 vis: Visibility::from_hir(parent_vis, trait_item_ref.id.hir_id, self),
2771 defaultness: trait_item_ref.defaultness,
2773 container: TraitContainer(parent_def_id),
2774 method_has_self_argument: has_self,
2778 fn associated_item_from_impl_item_ref(
2780 parent_def_id: DefId,
2781 impl_item_ref: &hir::ImplItemRef<'_>,
2783 let def_id = self.hir().local_def_id(impl_item_ref.id.hir_id);
2784 let (kind, has_self) = match impl_item_ref.kind {
2785 hir::AssocItemKind::Const => (ty::AssocKind::Const, false),
2786 hir::AssocItemKind::Method { has_self } => (ty::AssocKind::Method, has_self),
2787 hir::AssocItemKind::Type => (ty::AssocKind::Type, false),
2788 hir::AssocItemKind::OpaqueTy => (ty::AssocKind::OpaqueTy, false),
2792 ident: impl_item_ref.ident,
2794 // Visibility of trait impl items doesn't matter.
2795 vis: ty::Visibility::from_hir(&impl_item_ref.vis, impl_item_ref.id.hir_id, self),
2796 defaultness: impl_item_ref.defaultness,
2798 container: ImplContainer(parent_def_id),
2799 method_has_self_argument: has_self,
2803 pub fn field_index(self, hir_id: hir::HirId, tables: &TypeckTables<'_>) -> usize {
2804 tables.field_indices().get(hir_id).cloned().expect("no index for a field")
2807 pub fn find_field_index(self, ident: Ident, variant: &VariantDef) -> Option<usize> {
2808 variant.fields.iter().position(|field| self.hygienic_eq(ident, field.ident, variant.def_id))
2811 pub fn associated_items(self, def_id: DefId) -> AssocItemsIterator<'tcx> {
2812 // Ideally, we would use `-> impl Iterator` here, but it falls
2813 // afoul of the conservative "capture [restrictions]" we put
2814 // in place, so we use a hand-written iterator.
2816 // [restrictions]: https://github.com/rust-lang/rust/issues/34511#issuecomment-373423999
2817 AssocItemsIterator {
2819 def_ids: self.associated_item_def_ids(def_id),
2824 /// Returns `true` if the impls are the same polarity and the trait either
2825 /// has no items or is annotated #[marker] and prevents item overrides.
2826 pub fn impls_are_allowed_to_overlap(
2830 ) -> Option<ImplOverlapKind> {
2831 // If either trait impl references an error, they're allowed to overlap,
2832 // as one of them essentially doesn't exist.
2833 if self.impl_trait_ref(def_id1).map_or(false, |tr| tr.references_error())
2834 || self.impl_trait_ref(def_id2).map_or(false, |tr| tr.references_error())
2836 return Some(ImplOverlapKind::Permitted);
2839 match (self.impl_polarity(def_id1), self.impl_polarity(def_id2)) {
2840 (ImplPolarity::Reservation, _) | (_, ImplPolarity::Reservation) => {
2841 // `#[rustc_reservation_impl]` impls don't overlap with anything
2843 "impls_are_allowed_to_overlap({:?}, {:?}) = Some(Permitted) (reservations)",
2846 return Some(ImplOverlapKind::Permitted);
2848 (ImplPolarity::Positive, ImplPolarity::Negative)
2849 | (ImplPolarity::Negative, ImplPolarity::Positive) => {
2850 // `impl AutoTrait for Type` + `impl !AutoTrait for Type`
2852 "impls_are_allowed_to_overlap({:?}, {:?}) - None (differing polarities)",
2857 (ImplPolarity::Positive, ImplPolarity::Positive)
2858 | (ImplPolarity::Negative, ImplPolarity::Negative) => {}
2861 let is_marker_overlap = if self.features().overlapping_marker_traits {
2862 let trait1_is_empty = self.impl_trait_ref(def_id1).map_or(false, |trait_ref| {
2863 self.associated_item_def_ids(trait_ref.def_id).is_empty()
2865 let trait2_is_empty = self.impl_trait_ref(def_id2).map_or(false, |trait_ref| {
2866 self.associated_item_def_ids(trait_ref.def_id).is_empty()
2868 trait1_is_empty && trait2_is_empty
2870 let is_marker_impl = |def_id: DefId| -> bool {
2871 let trait_ref = self.impl_trait_ref(def_id);
2872 trait_ref.map_or(false, |tr| self.trait_def(tr.def_id).is_marker)
2874 is_marker_impl(def_id1) && is_marker_impl(def_id2)
2877 if is_marker_overlap {
2879 "impls_are_allowed_to_overlap({:?}, {:?}) = Some(Permitted) (marker overlap)",
2882 Some(ImplOverlapKind::Permitted)
2884 if let Some(self_ty1) = self.issue33140_self_ty(def_id1) {
2885 if let Some(self_ty2) = self.issue33140_self_ty(def_id2) {
2886 if self_ty1 == self_ty2 {
2888 "impls_are_allowed_to_overlap({:?}, {:?}) - issue #33140 HACK",
2891 return Some(ImplOverlapKind::Issue33140);
2894 "impls_are_allowed_to_overlap({:?}, {:?}) - found {:?} != {:?}",
2895 def_id1, def_id2, self_ty1, self_ty2
2901 debug!("impls_are_allowed_to_overlap({:?}, {:?}) = None", def_id1, def_id2);
2906 /// Returns `ty::VariantDef` if `res` refers to a struct,
2907 /// or variant or their constructors, panics otherwise.
2908 pub fn expect_variant_res(self, res: Res) -> &'tcx VariantDef {
2910 Res::Def(DefKind::Variant, did) => {
2911 let enum_did = self.parent(did).unwrap();
2912 self.adt_def(enum_did).variant_with_id(did)
2914 Res::Def(DefKind::Struct, did) | Res::Def(DefKind::Union, did) => {
2915 self.adt_def(did).non_enum_variant()
2917 Res::Def(DefKind::Ctor(CtorOf::Variant, ..), variant_ctor_did) => {
2918 let variant_did = self.parent(variant_ctor_did).unwrap();
2919 let enum_did = self.parent(variant_did).unwrap();
2920 self.adt_def(enum_did).variant_with_ctor_id(variant_ctor_did)
2922 Res::Def(DefKind::Ctor(CtorOf::Struct, ..), ctor_did) => {
2923 let struct_did = self.parent(ctor_did).expect("struct ctor has no parent");
2924 self.adt_def(struct_did).non_enum_variant()
2926 _ => bug!("expect_variant_res used with unexpected res {:?}", res),
2930 pub fn item_name(self, id: DefId) -> Symbol {
2931 if id.index == CRATE_DEF_INDEX {
2932 self.original_crate_name(id.krate)
2934 let def_key = self.def_key(id);
2935 match def_key.disambiguated_data.data {
2936 // The name of a constructor is that of its parent.
2937 hir_map::DefPathData::Ctor => {
2938 self.item_name(DefId { krate: id.krate, index: def_key.parent.unwrap() })
2940 _ => def_key.disambiguated_data.data.get_opt_name().unwrap_or_else(|| {
2941 bug!("item_name: no name for {:?}", self.def_path(id));
2947 /// Returns the possibly-auto-generated MIR of a `(DefId, Subst)` pair.
2948 pub fn instance_mir(self, instance: ty::InstanceDef<'tcx>) -> ReadOnlyBodyAndCache<'tcx, 'tcx> {
2950 ty::InstanceDef::Item(did) => self.optimized_mir(did).unwrap_read_only(),
2951 ty::InstanceDef::VtableShim(..)
2952 | ty::InstanceDef::ReifyShim(..)
2953 | ty::InstanceDef::Intrinsic(..)
2954 | ty::InstanceDef::FnPtrShim(..)
2955 | ty::InstanceDef::Virtual(..)
2956 | ty::InstanceDef::ClosureOnceShim { .. }
2957 | ty::InstanceDef::DropGlue(..)
2958 | ty::InstanceDef::CloneShim(..) => self.mir_shims(instance).unwrap_read_only(),
2962 /// Gets the attributes of a definition.
2963 pub fn get_attrs(self, did: DefId) -> Attributes<'tcx> {
2964 if let Some(id) = self.hir().as_local_hir_id(did) {
2965 Attributes::Borrowed(self.hir().attrs(id))
2967 Attributes::Owned(self.item_attrs(did))
2971 /// Determines whether an item is annotated with an attribute.
2972 pub fn has_attr(self, did: DefId, attr: Symbol) -> bool {
2973 attr::contains_name(&self.get_attrs(did), attr)
2976 /// Returns `true` if this is an `auto trait`.
2977 pub fn trait_is_auto(self, trait_def_id: DefId) -> bool {
2978 self.trait_def(trait_def_id).has_auto_impl
2981 pub fn generator_layout(self, def_id: DefId) -> &'tcx GeneratorLayout<'tcx> {
2982 self.optimized_mir(def_id).generator_layout.as_ref().unwrap()
2985 /// Given the `DefId` of an impl, returns the `DefId` of the trait it implements.
2986 /// If it implements no trait, returns `None`.
2987 pub fn trait_id_of_impl(self, def_id: DefId) -> Option<DefId> {
2988 self.impl_trait_ref(def_id).map(|tr| tr.def_id)
2991 /// If the given defid describes a method belonging to an impl, returns the
2992 /// `DefId` of the impl that the method belongs to; otherwise, returns `None`.
2993 pub fn impl_of_method(self, def_id: DefId) -> Option<DefId> {
2994 let item = if def_id.krate != LOCAL_CRATE {
2995 if let Some(DefKind::Method) = self.def_kind(def_id) {
2996 Some(self.associated_item(def_id))
3001 self.opt_associated_item(def_id)
3004 item.and_then(|trait_item| match trait_item.container {
3005 TraitContainer(_) => None,
3006 ImplContainer(def_id) => Some(def_id),
3010 /// Looks up the span of `impl_did` if the impl is local; otherwise returns `Err`
3011 /// with the name of the crate containing the impl.
3012 pub fn span_of_impl(self, impl_did: DefId) -> Result<Span, Symbol> {
3013 if impl_did.is_local() {
3014 let hir_id = self.hir().as_local_hir_id(impl_did).unwrap();
3015 Ok(self.hir().span(hir_id))
3017 Err(self.crate_name(impl_did.krate))
3021 /// Hygienically compares a use-site name (`use_name`) for a field or an associated item with
3022 /// its supposed definition name (`def_name`). The method also needs `DefId` of the supposed
3023 /// definition's parent/scope to perform comparison.
3024 pub fn hygienic_eq(self, use_name: Ident, def_name: Ident, def_parent_def_id: DefId) -> bool {
3025 // We could use `Ident::eq` here, but we deliberately don't. The name
3026 // comparison fails frequently, and we want to avoid the expensive
3027 // `modern()` calls required for the span comparison whenever possible.
3028 use_name.name == def_name.name
3032 .hygienic_eq(def_name.span.ctxt(), self.expansion_that_defined(def_parent_def_id))
3035 fn expansion_that_defined(self, scope: DefId) -> ExpnId {
3037 LOCAL_CRATE => self.hir().definitions().expansion_that_defined(scope.index),
3038 _ => ExpnId::root(),
3042 pub fn adjust_ident(self, mut ident: Ident, scope: DefId) -> Ident {
3043 ident.span.modernize_and_adjust(self.expansion_that_defined(scope));
3047 pub fn adjust_ident_and_get_scope(
3052 ) -> (Ident, DefId) {
3053 let scope = match ident.span.modernize_and_adjust(self.expansion_that_defined(scope)) {
3054 Some(actual_expansion) => {
3055 self.hir().definitions().parent_module_of_macro_def(actual_expansion)
3057 None => self.hir().get_module_parent(block),
3064 pub struct AssocItemsIterator<'tcx> {
3066 def_ids: &'tcx [DefId],
3070 impl Iterator for AssocItemsIterator<'_> {
3071 type Item = AssocItem;
3073 fn next(&mut self) -> Option<AssocItem> {
3074 let def_id = self.def_ids.get(self.next_index)?;
3075 self.next_index += 1;
3076 Some(self.tcx.associated_item(*def_id))
3080 fn associated_item(tcx: TyCtxt<'_>, def_id: DefId) -> AssocItem {
3081 let id = tcx.hir().as_local_hir_id(def_id).unwrap();
3082 let parent_id = tcx.hir().get_parent_item(id);
3083 let parent_def_id = tcx.hir().local_def_id(parent_id);
3084 let parent_item = tcx.hir().expect_item(parent_id);
3085 match parent_item.kind {
3086 hir::ItemKind::Impl(.., ref impl_item_refs) => {
3087 if let Some(impl_item_ref) = impl_item_refs.iter().find(|i| i.id.hir_id == id) {
3089 tcx.associated_item_from_impl_item_ref(parent_def_id, impl_item_ref);
3090 debug_assert_eq!(assoc_item.def_id, def_id);
3095 hir::ItemKind::Trait(.., ref trait_item_refs) => {
3096 if let Some(trait_item_ref) = trait_item_refs.iter().find(|i| i.id.hir_id == id) {
3097 let assoc_item = tcx.associated_item_from_trait_item_ref(
3102 debug_assert_eq!(assoc_item.def_id, def_id);
3112 "unexpected parent of trait or impl item or item not found: {:?}",
3117 #[derive(Clone, HashStable)]
3118 pub struct AdtSizedConstraint<'tcx>(pub &'tcx [Ty<'tcx>]);
3120 /// Calculates the `Sized` constraint.
3122 /// In fact, there are only a few options for the types in the constraint:
3123 /// - an obviously-unsized type
3124 /// - a type parameter or projection whose Sizedness can't be known
3125 /// - a tuple of type parameters or projections, if there are multiple
3127 /// - a Error, if a type contained itself. The representability
3128 /// check should catch this case.
3129 fn adt_sized_constraint(tcx: TyCtxt<'_>, def_id: DefId) -> AdtSizedConstraint<'_> {
3130 let def = tcx.adt_def(def_id);
3132 let result = tcx.mk_type_list(
3135 .flat_map(|v| v.fields.last())
3136 .flat_map(|f| def.sized_constraint_for_ty(tcx, tcx.type_of(f.did))),
3139 debug!("adt_sized_constraint: {:?} => {:?}", def, result);
3141 AdtSizedConstraint(result)
3144 fn associated_item_def_ids(tcx: TyCtxt<'_>, def_id: DefId) -> &[DefId] {
3145 let id = tcx.hir().as_local_hir_id(def_id).unwrap();
3146 let item = tcx.hir().expect_item(id);
3148 hir::ItemKind::Trait(.., ref trait_item_refs) => tcx.arena.alloc_from_iter(
3151 .map(|trait_item_ref| trait_item_ref.id)
3152 .map(|id| tcx.hir().local_def_id(id.hir_id)),
3154 hir::ItemKind::Impl(.., ref impl_item_refs) => tcx.arena.alloc_from_iter(
3157 .map(|impl_item_ref| impl_item_ref.id)
3158 .map(|id| tcx.hir().local_def_id(id.hir_id)),
3160 hir::ItemKind::TraitAlias(..) => &[],
3161 _ => span_bug!(item.span, "associated_item_def_ids: not impl or trait"),
3165 fn def_span(tcx: TyCtxt<'_>, def_id: DefId) -> Span {
3166 tcx.hir().span_if_local(def_id).unwrap()
3169 /// If the given `DefId` describes an item belonging to a trait,
3170 /// returns the `DefId` of the trait that the trait item belongs to;
3171 /// otherwise, returns `None`.
3172 fn trait_of_item(tcx: TyCtxt<'_>, def_id: DefId) -> Option<DefId> {
3173 tcx.opt_associated_item(def_id).and_then(|associated_item| match associated_item.container {
3174 TraitContainer(def_id) => Some(def_id),
3175 ImplContainer(_) => None,
3179 /// Yields the parent function's `DefId` if `def_id` is an `impl Trait` definition.
3180 pub fn is_impl_trait_defn(tcx: TyCtxt<'_>, def_id: DefId) -> Option<DefId> {
3181 if let Some(hir_id) = tcx.hir().as_local_hir_id(def_id) {
3182 if let Node::Item(item) = tcx.hir().get(hir_id) {
3183 if let hir::ItemKind::OpaqueTy(ref opaque_ty) = item.kind {
3184 return opaque_ty.impl_trait_fn;
3191 /// See `ParamEnv` struct definition for details.
3192 fn param_env(tcx: TyCtxt<'_>, def_id: DefId) -> ParamEnv<'_> {
3193 // The param_env of an impl Trait type is its defining function's param_env
3194 if let Some(parent) = is_impl_trait_defn(tcx, def_id) {
3195 return param_env(tcx, parent);
3197 // Compute the bounds on Self and the type parameters.
3199 let InstantiatedPredicates { predicates } = tcx.predicates_of(def_id).instantiate_identity(tcx);
3201 // Finally, we have to normalize the bounds in the environment, in
3202 // case they contain any associated type projections. This process
3203 // can yield errors if the put in illegal associated types, like
3204 // `<i32 as Foo>::Bar` where `i32` does not implement `Foo`. We
3205 // report these errors right here; this doesn't actually feel
3206 // right to me, because constructing the environment feels like a
3207 // kind of a "idempotent" action, but I'm not sure where would be
3208 // a better place. In practice, we construct environments for
3209 // every fn once during type checking, and we'll abort if there
3210 // are any errors at that point, so after type checking you can be
3211 // sure that this will succeed without errors anyway.
3213 let unnormalized_env = ty::ParamEnv::new(
3214 tcx.intern_predicates(&predicates),
3215 traits::Reveal::UserFacing,
3216 tcx.sess.opts.debugging_opts.chalk.then_some(def_id),
3219 let body_id = tcx.hir().as_local_hir_id(def_id).map_or(hir::DUMMY_HIR_ID, |id| {
3220 tcx.hir().maybe_body_owned_by(id).map_or(id, |body| body.hir_id)
3222 let cause = traits::ObligationCause::misc(tcx.def_span(def_id), body_id);
3223 traits::normalize_param_env_or_error(tcx, def_id, unnormalized_env, cause)
3226 fn crate_disambiguator(tcx: TyCtxt<'_>, crate_num: CrateNum) -> CrateDisambiguator {
3227 assert_eq!(crate_num, LOCAL_CRATE);
3228 tcx.sess.local_crate_disambiguator()
3231 fn original_crate_name(tcx: TyCtxt<'_>, crate_num: CrateNum) -> Symbol {
3232 assert_eq!(crate_num, LOCAL_CRATE);
3233 tcx.crate_name.clone()
3236 fn crate_hash(tcx: TyCtxt<'_>, crate_num: CrateNum) -> Svh {
3237 assert_eq!(crate_num, LOCAL_CRATE);
3238 tcx.hir().crate_hash
3241 fn instance_def_size_estimate<'tcx>(tcx: TyCtxt<'tcx>, instance_def: InstanceDef<'tcx>) -> usize {
3242 match instance_def {
3243 InstanceDef::Item(..) | InstanceDef::DropGlue(..) => {
3244 let mir = tcx.instance_mir(instance_def);
3245 mir.basic_blocks().iter().map(|bb| bb.statements.len()).sum()
3247 // Estimate the size of other compiler-generated shims to be 1.
3252 /// If `def_id` is an issue 33140 hack impl, returns its self type; otherwise, returns `None`.
3254 /// See [`ImplOverlapKind::Issue33140`] for more details.
3255 fn issue33140_self_ty(tcx: TyCtxt<'_>, def_id: DefId) -> Option<Ty<'_>> {
3256 debug!("issue33140_self_ty({:?})", def_id);
3259 .impl_trait_ref(def_id)
3260 .unwrap_or_else(|| bug!("issue33140_self_ty called on inherent impl {:?}", def_id));
3262 debug!("issue33140_self_ty({:?}), trait-ref={:?}", def_id, trait_ref);
3264 let is_marker_like = tcx.impl_polarity(def_id) == ty::ImplPolarity::Positive
3265 && tcx.associated_item_def_ids(trait_ref.def_id).is_empty();
3267 // Check whether these impls would be ok for a marker trait.
3268 if !is_marker_like {
3269 debug!("issue33140_self_ty - not marker-like!");
3273 // impl must be `impl Trait for dyn Marker1 + Marker2 + ...`
3274 if trait_ref.substs.len() != 1 {
3275 debug!("issue33140_self_ty - impl has substs!");
3279 let predicates = tcx.predicates_of(def_id);
3280 if predicates.parent.is_some() || !predicates.predicates.is_empty() {
3281 debug!("issue33140_self_ty - impl has predicates {:?}!", predicates);
3285 let self_ty = trait_ref.self_ty();
3286 let self_ty_matches = match self_ty.kind {
3287 ty::Dynamic(ref data, ty::ReStatic) => data.principal().is_none(),
3291 if self_ty_matches {
3292 debug!("issue33140_self_ty - MATCHES!");
3295 debug!("issue33140_self_ty - non-matching self type");
3300 /// Check if a function is async.
3301 fn asyncness(tcx: TyCtxt<'_>, def_id: DefId) -> hir::IsAsync {
3304 .as_local_hir_id(def_id)
3305 .unwrap_or_else(|| bug!("asyncness: expected local `DefId`, got `{:?}`", def_id));
3307 let node = tcx.hir().get(hir_id);
3309 let fn_like = hir_map::blocks::FnLikeNode::from_node(node).unwrap_or_else(|| {
3310 bug!("asyncness: expected fn-like node but got `{:?}`", def_id);
3316 pub fn provide(providers: &mut ty::query::Providers<'_>) {
3317 context::provide(providers);
3318 erase_regions::provide(providers);
3319 layout::provide(providers);
3320 *providers = ty::query::Providers {
3323 associated_item_def_ids,
3324 adt_sized_constraint,
3328 crate_disambiguator,
3329 original_crate_name,
3331 trait_impls_of: trait_def::trait_impls_of_provider,
3332 instance_def_size_estimate,
3338 /// A map for the local crate mapping each type to a vector of its
3339 /// inherent impls. This is not meant to be used outside of coherence;
3340 /// rather, you should request the vector for a specific type via
3341 /// `tcx.inherent_impls(def_id)` so as to minimize your dependencies
3342 /// (constructing this map requires touching the entire crate).
3343 #[derive(Clone, Debug, Default, HashStable)]
3344 pub struct CrateInherentImpls {
3345 pub inherent_impls: DefIdMap<Vec<DefId>>,
3348 #[derive(Clone, Copy, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
3349 pub struct SymbolName {
3350 // FIXME: we don't rely on interning or equality here - better have
3351 // this be a `&'tcx str`.
3356 pub fn new(name: &str) -> SymbolName {
3357 SymbolName { name: Symbol::intern(name) }
3361 impl PartialOrd for SymbolName {
3362 fn partial_cmp(&self, other: &SymbolName) -> Option<Ordering> {
3363 self.name.as_str().partial_cmp(&other.name.as_str())
3367 /// Ordering must use the chars to ensure reproducible builds.
3368 impl Ord for SymbolName {
3369 fn cmp(&self, other: &SymbolName) -> Ordering {
3370 self.name.as_str().cmp(&other.name.as_str())
3374 impl fmt::Display for SymbolName {
3375 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
3376 fmt::Display::fmt(&self.name, fmt)
3380 impl fmt::Debug for SymbolName {
3381 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
3382 fmt::Display::fmt(&self.name, fmt)