1 // ignore-tidy-filelength
3 pub use self::fold::{TypeFoldable, TypeVisitor};
4 pub use self::AssocItemContainer::*;
5 pub use self::BorrowKind::*;
6 pub use self::IntVarValue::*;
7 pub use self::Variance::*;
9 use crate::arena::Arena;
10 use crate::hir::exports::ExportMap;
11 use crate::hir::map as hir_map;
13 use crate::ich::Fingerprint;
14 use crate::ich::StableHashingContext;
15 use crate::infer::canonical::Canonical;
16 use crate::middle::cstore::CrateStoreDyn;
17 use crate::middle::lang_items::{FnMutTraitLangItem, FnOnceTraitLangItem, FnTraitLangItem};
18 use crate::middle::resolve_lifetime::ObjectLifetimeDefault;
19 use crate::mir::interpret::ErrorHandled;
20 use crate::mir::GeneratorLayout;
21 use crate::mir::ReadOnlyBodyAndCache;
22 use crate::session::DataTypeKind;
23 use crate::traits::{self, Reveal};
25 use crate::ty::layout::VariantIdx;
26 use crate::ty::subst::{InternalSubsts, Subst, SubstsRef};
27 use crate::ty::util::{Discr, IntTypeExt};
28 use crate::ty::walk::TypeWalker;
29 use rustc_attr as attr;
30 use rustc_data_structures::captures::Captures;
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::sync::{self, par_iter, Lrc, ParallelIterator};
36 use rustc_hir::def::{CtorKind, CtorOf, DefKind, Res};
37 use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, LocalDefId, CRATE_DEF_INDEX, LOCAL_CRATE};
38 use rustc_hir::{GlobMap, Node, TraitMap};
39 use rustc_index::vec::{Idx, IndexVec};
40 use rustc_macros::HashStable;
41 use rustc_serialize::{self, Encodable, Encoder};
42 use rustc_span::hygiene::ExpnId;
43 use rustc_span::symbol::{kw, sym, Symbol};
45 use rustc_target::abi::Align;
46 use syntax::ast::{self, Constness, Ident, Name};
47 use syntax::node_id::{NodeId, NodeMap, NodeSet};
50 use std::cell::RefCell;
51 use std::cmp::{self, Ordering};
53 use std::hash::{Hash, Hasher};
59 pub use self::sty::BoundRegion::*;
60 pub use self::sty::InferTy::*;
61 pub use self::sty::RegionKind;
62 pub use self::sty::RegionKind::*;
63 pub use self::sty::TyKind::*;
64 pub use self::sty::{Binder, BoundTy, BoundTyKind, BoundVar, DebruijnIndex, INNERMOST};
65 pub use self::sty::{BoundRegion, EarlyBoundRegion, FreeRegion, Region};
66 pub use self::sty::{CanonicalPolyFnSig, FnSig, GenSig, PolyFnSig, PolyGenSig};
67 pub use self::sty::{ClosureSubsts, GeneratorSubsts, TypeAndMut, UpvarSubsts};
68 pub use self::sty::{Const, ConstKind, ExistentialProjection, PolyExistentialProjection};
69 pub use self::sty::{ConstVid, FloatVid, IntVid, RegionVid, TyVid};
70 pub use self::sty::{ExistentialPredicate, InferConst, InferTy, ParamConst, ParamTy, ProjectionTy};
71 pub use self::sty::{ExistentialTraitRef, PolyExistentialTraitRef};
72 pub use self::sty::{PolyTraitRef, TraitRef, TyKind};
73 pub use crate::ty::diagnostics::*;
75 pub use self::binding::BindingMode;
76 pub use self::binding::BindingMode::*;
78 pub use self::context::{keep_local, tls, FreeRegionInfo, TyCtxt};
79 pub use self::context::{
80 CanonicalUserType, CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations, ResolvedOpaqueTy,
81 UserType, UserTypeAnnotationIndex,
83 pub use self::context::{
84 CtxtInterners, GeneratorInteriorTypeCause, GlobalCtxt, Lift, TypeckTables,
87 pub use self::instance::{Instance, InstanceDef};
89 pub use self::trait_def::TraitDef;
91 pub use self::query::queries;
104 pub mod free_region_map;
105 pub mod inhabitedness;
107 pub mod normalize_erasing_regions;
121 mod structural_impls;
126 pub struct ResolverOutputs {
127 pub definitions: hir_map::Definitions,
128 pub cstore: Box<CrateStoreDyn>,
129 pub extern_crate_map: NodeMap<CrateNum>,
130 pub trait_map: TraitMap,
131 pub maybe_unused_trait_imports: NodeSet,
132 pub maybe_unused_extern_crates: Vec<(NodeId, Span)>,
133 pub export_map: ExportMap<NodeId>,
134 pub glob_map: GlobMap,
135 /// Extern prelude entries. The value is `true` if the entry was introduced
136 /// via `extern crate` item and not `--extern` option or compiler built-in.
137 pub extern_prelude: FxHashMap<Name, bool>,
140 #[derive(Clone, Copy, PartialEq, Eq, Debug, HashStable)]
141 pub enum AssocItemContainer {
142 TraitContainer(DefId),
143 ImplContainer(DefId),
146 impl AssocItemContainer {
147 /// Asserts that this is the `DefId` of an associated item declared
148 /// in a trait, and returns the trait `DefId`.
149 pub fn assert_trait(&self) -> DefId {
151 TraitContainer(id) => id,
152 _ => bug!("associated item has wrong container type: {:?}", self),
156 pub fn id(&self) -> DefId {
158 TraitContainer(id) => id,
159 ImplContainer(id) => id,
164 /// The "header" of an impl is everything outside the body: a Self type, a trait
165 /// ref (in the case of a trait impl), and a set of predicates (from the
166 /// bounds / where-clauses).
167 #[derive(Clone, Debug, TypeFoldable)]
168 pub struct ImplHeader<'tcx> {
169 pub impl_def_id: DefId,
170 pub self_ty: Ty<'tcx>,
171 pub trait_ref: Option<TraitRef<'tcx>>,
172 pub predicates: Vec<Predicate<'tcx>>,
175 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable)]
176 pub enum ImplPolarity {
177 /// `impl Trait for Type`
179 /// `impl !Trait for Type`
181 /// `#[rustc_reservation_impl] impl Trait for Type`
183 /// This is a "stability hack", not a real Rust feature.
184 /// See #64631 for details.
188 #[derive(Copy, Clone, Debug, PartialEq, HashStable)]
189 pub struct AssocItem {
191 #[stable_hasher(project(name))]
195 pub defaultness: hir::Defaultness,
196 pub container: AssocItemContainer,
198 /// Whether this is a method with an explicit self
199 /// as its first argument, allowing method calls.
200 pub method_has_self_argument: bool,
203 #[derive(Copy, Clone, PartialEq, Debug, HashStable)]
212 pub fn suggestion_descr(&self) -> &'static str {
214 ty::AssocKind::Method => "method call",
215 ty::AssocKind::Type | ty::AssocKind::OpaqueTy => "associated type",
216 ty::AssocKind::Const => "associated constant",
222 pub fn def_kind(&self) -> DefKind {
224 AssocKind::Const => DefKind::AssocConst,
225 AssocKind::Method => DefKind::Method,
226 AssocKind::Type => DefKind::AssocTy,
227 AssocKind::OpaqueTy => DefKind::AssocOpaqueTy,
231 /// Tests whether the associated item admits a non-trivial implementation
233 pub fn relevant_for_never(&self) -> bool {
235 AssocKind::OpaqueTy | AssocKind::Const | AssocKind::Type => true,
236 // FIXME(canndrew): Be more thorough here, check if any argument is uninhabited.
237 AssocKind::Method => !self.method_has_self_argument,
241 pub fn signature(&self, tcx: TyCtxt<'_>) -> String {
243 ty::AssocKind::Method => {
244 // We skip the binder here because the binder would deanonymize all
245 // late-bound regions, and we don't want method signatures to show up
246 // `as for<'r> fn(&'r MyType)`. Pretty-printing handles late-bound
247 // regions just fine, showing `fn(&MyType)`.
248 tcx.fn_sig(self.def_id).skip_binder().to_string()
250 ty::AssocKind::Type => format!("type {};", self.ident),
251 // FIXME(type_alias_impl_trait): we should print bounds here too.
252 ty::AssocKind::OpaqueTy => format!("type {};", self.ident),
253 ty::AssocKind::Const => {
254 format!("const {}: {:?};", self.ident, tcx.type_of(self.def_id))
260 #[derive(Clone, Debug, PartialEq, Eq, Copy, RustcEncodable, RustcDecodable, HashStable)]
261 pub enum Visibility {
262 /// Visible everywhere (including in other crates).
264 /// Visible only in the given crate-local module.
266 /// Not visible anywhere in the local crate. This is the visibility of private external items.
270 pub trait DefIdTree: Copy {
271 fn parent(self, id: DefId) -> Option<DefId>;
273 fn is_descendant_of(self, mut descendant: DefId, ancestor: DefId) -> bool {
274 if descendant.krate != ancestor.krate {
278 while descendant != ancestor {
279 match self.parent(descendant) {
280 Some(parent) => descendant = parent,
281 None => return false,
288 impl<'tcx> DefIdTree for TyCtxt<'tcx> {
289 fn parent(self, id: DefId) -> Option<DefId> {
290 self.def_key(id).parent.map(|index| DefId { index: index, ..id })
295 pub fn from_hir(visibility: &hir::Visibility<'_>, id: hir::HirId, tcx: TyCtxt<'_>) -> Self {
296 match visibility.node {
297 hir::VisibilityKind::Public => Visibility::Public,
298 hir::VisibilityKind::Crate(_) => Visibility::Restricted(DefId::local(CRATE_DEF_INDEX)),
299 hir::VisibilityKind::Restricted { ref path, .. } => match path.res {
300 // If there is no resolution, `resolve` will have already reported an error, so
301 // assume that the visibility is public to avoid reporting more privacy errors.
302 Res::Err => Visibility::Public,
303 def => Visibility::Restricted(def.def_id()),
305 hir::VisibilityKind::Inherited => {
306 Visibility::Restricted(tcx.hir().get_module_parent(id))
311 /// Returns `true` if an item with this visibility is accessible from the given block.
312 pub fn is_accessible_from<T: DefIdTree>(self, module: DefId, tree: T) -> bool {
313 let restriction = match self {
314 // Public items are visible everywhere.
315 Visibility::Public => return true,
316 // Private items from other crates are visible nowhere.
317 Visibility::Invisible => return false,
318 // Restricted items are visible in an arbitrary local module.
319 Visibility::Restricted(other) if other.krate != module.krate => return false,
320 Visibility::Restricted(module) => module,
323 tree.is_descendant_of(module, restriction)
326 /// Returns `true` if this visibility is at least as accessible as the given visibility
327 pub fn is_at_least<T: DefIdTree>(self, vis: Visibility, tree: T) -> bool {
328 let vis_restriction = match vis {
329 Visibility::Public => return self == Visibility::Public,
330 Visibility::Invisible => return true,
331 Visibility::Restricted(module) => module,
334 self.is_accessible_from(vis_restriction, tree)
337 // Returns `true` if this item is visible anywhere in the local crate.
338 pub fn is_visible_locally(self) -> bool {
340 Visibility::Public => true,
341 Visibility::Restricted(def_id) => def_id.is_local(),
342 Visibility::Invisible => false,
347 #[derive(Copy, Clone, PartialEq, RustcDecodable, RustcEncodable, HashStable)]
349 Covariant, // T<A> <: T<B> iff A <: B -- e.g., function return type
350 Invariant, // T<A> <: T<B> iff B == A -- e.g., type of mutable cell
351 Contravariant, // T<A> <: T<B> iff B <: A -- e.g., function param type
352 Bivariant, // T<A> <: T<B> -- e.g., unused type parameter
355 /// The crate variances map is computed during typeck and contains the
356 /// variance of every item in the local crate. You should not use it
357 /// directly, because to do so will make your pass dependent on the
358 /// HIR of every item in the local crate. Instead, use
359 /// `tcx.variances_of()` to get the variance for a *particular*
361 #[derive(HashStable)]
362 pub struct CrateVariancesMap<'tcx> {
363 /// For each item with generics, maps to a vector of the variance
364 /// of its generics. If an item has no generics, it will have no
366 pub variances: FxHashMap<DefId, &'tcx [ty::Variance]>,
370 /// `a.xform(b)` combines the variance of a context with the
371 /// variance of a type with the following meaning. If we are in a
372 /// context with variance `a`, and we encounter a type argument in
373 /// a position with variance `b`, then `a.xform(b)` is the new
374 /// variance with which the argument appears.
380 /// Here, the "ambient" variance starts as covariant. `*mut T` is
381 /// invariant with respect to `T`, so the variance in which the
382 /// `Vec<i32>` appears is `Covariant.xform(Invariant)`, which
383 /// yields `Invariant`. Now, the type `Vec<T>` is covariant with
384 /// respect to its type argument `T`, and hence the variance of
385 /// the `i32` here is `Invariant.xform(Covariant)`, which results
386 /// (again) in `Invariant`.
390 /// fn(*const Vec<i32>, *mut Vec<i32)
392 /// The ambient variance is covariant. A `fn` type is
393 /// contravariant with respect to its parameters, so the variance
394 /// within which both pointer types appear is
395 /// `Covariant.xform(Contravariant)`, or `Contravariant`. `*const
396 /// T` is covariant with respect to `T`, so the variance within
397 /// which the first `Vec<i32>` appears is
398 /// `Contravariant.xform(Covariant)` or `Contravariant`. The same
399 /// is true for its `i32` argument. In the `*mut T` case, the
400 /// variance of `Vec<i32>` is `Contravariant.xform(Invariant)`,
401 /// and hence the outermost type is `Invariant` with respect to
402 /// `Vec<i32>` (and its `i32` argument).
404 /// Source: Figure 1 of "Taming the Wildcards:
405 /// Combining Definition- and Use-Site Variance" published in PLDI'11.
406 pub fn xform(self, v: ty::Variance) -> ty::Variance {
408 // Figure 1, column 1.
409 (ty::Covariant, ty::Covariant) => ty::Covariant,
410 (ty::Covariant, ty::Contravariant) => ty::Contravariant,
411 (ty::Covariant, ty::Invariant) => ty::Invariant,
412 (ty::Covariant, ty::Bivariant) => ty::Bivariant,
414 // Figure 1, column 2.
415 (ty::Contravariant, ty::Covariant) => ty::Contravariant,
416 (ty::Contravariant, ty::Contravariant) => ty::Covariant,
417 (ty::Contravariant, ty::Invariant) => ty::Invariant,
418 (ty::Contravariant, ty::Bivariant) => ty::Bivariant,
420 // Figure 1, column 3.
421 (ty::Invariant, _) => ty::Invariant,
423 // Figure 1, column 4.
424 (ty::Bivariant, _) => ty::Bivariant,
429 // Contains information needed to resolve types and (in the future) look up
430 // the types of AST nodes.
431 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
432 pub struct CReaderCacheKey {
437 // Flags that we track on types. These flags are propagated upwards
438 // through the type during type construction, so that we can quickly
439 // check whether the type has various kinds of types in it without
440 // recursing over the type itself.
442 pub struct TypeFlags: u32 {
443 const HAS_PARAMS = 1 << 0;
444 const HAS_TY_INFER = 1 << 1;
445 const HAS_RE_INFER = 1 << 2;
446 const HAS_RE_PLACEHOLDER = 1 << 3;
448 /// Does this have any `ReEarlyBound` regions? Used to
449 /// determine whether substitition is required, since those
450 /// represent regions that are bound in a `ty::Generics` and
451 /// hence may be substituted.
452 const HAS_RE_EARLY_BOUND = 1 << 4;
454 /// Does this have any region that "appears free" in the type?
455 /// Basically anything but `ReLateBound` and `ReErased`.
456 const HAS_FREE_REGIONS = 1 << 5;
458 /// Is an error type reachable?
459 const HAS_TY_ERR = 1 << 6;
460 const HAS_PROJECTION = 1 << 7;
462 // FIXME: Rename this to the actual property since it's used for generators too
463 const HAS_TY_CLOSURE = 1 << 8;
465 /// `true` if there are "names" of types and regions and so forth
466 /// that are local to a particular fn
467 const HAS_FREE_LOCAL_NAMES = 1 << 9;
469 /// Present if the type belongs in a local type context.
470 /// Only set for Infer other than Fresh.
471 const KEEP_IN_LOCAL_TCX = 1 << 10;
473 /// Does this have any `ReLateBound` regions? Used to check
474 /// if a global bound is safe to evaluate.
475 const HAS_RE_LATE_BOUND = 1 << 11;
477 const HAS_TY_PLACEHOLDER = 1 << 12;
479 const HAS_CT_INFER = 1 << 13;
480 const HAS_CT_PLACEHOLDER = 1 << 14;
482 const NEEDS_SUBST = TypeFlags::HAS_PARAMS.bits |
483 TypeFlags::HAS_RE_EARLY_BOUND.bits;
485 /// Flags representing the nominal content of a type,
486 /// computed by FlagsComputation. If you add a new nominal
487 /// flag, it should be added here too.
488 const NOMINAL_FLAGS = TypeFlags::HAS_PARAMS.bits |
489 TypeFlags::HAS_TY_INFER.bits |
490 TypeFlags::HAS_RE_INFER.bits |
491 TypeFlags::HAS_RE_PLACEHOLDER.bits |
492 TypeFlags::HAS_RE_EARLY_BOUND.bits |
493 TypeFlags::HAS_FREE_REGIONS.bits |
494 TypeFlags::HAS_TY_ERR.bits |
495 TypeFlags::HAS_PROJECTION.bits |
496 TypeFlags::HAS_TY_CLOSURE.bits |
497 TypeFlags::HAS_FREE_LOCAL_NAMES.bits |
498 TypeFlags::KEEP_IN_LOCAL_TCX.bits |
499 TypeFlags::HAS_RE_LATE_BOUND.bits |
500 TypeFlags::HAS_TY_PLACEHOLDER.bits |
501 TypeFlags::HAS_CT_INFER.bits |
502 TypeFlags::HAS_CT_PLACEHOLDER.bits;
506 #[allow(rustc::usage_of_ty_tykind)]
507 pub struct TyS<'tcx> {
508 pub kind: TyKind<'tcx>,
509 pub flags: TypeFlags,
511 /// This is a kind of confusing thing: it stores the smallest
514 /// (a) the binder itself captures nothing but
515 /// (b) all the late-bound things within the type are captured
516 /// by some sub-binder.
518 /// So, for a type without any late-bound things, like `u32`, this
519 /// will be *innermost*, because that is the innermost binder that
520 /// captures nothing. But for a type `&'D u32`, where `'D` is a
521 /// late-bound region with De Bruijn index `D`, this would be `D + 1`
522 /// -- the binder itself does not capture `D`, but `D` is captured
523 /// by an inner binder.
525 /// We call this concept an "exclusive" binder `D` because all
526 /// De Bruijn indices within the type are contained within `0..D`
528 outer_exclusive_binder: ty::DebruijnIndex,
531 // `TyS` is used a lot. Make sure it doesn't unintentionally get bigger.
532 #[cfg(target_arch = "x86_64")]
533 static_assert_size!(TyS<'_>, 32);
535 impl<'tcx> Ord for TyS<'tcx> {
536 fn cmp(&self, other: &TyS<'tcx>) -> Ordering {
537 self.kind.cmp(&other.kind)
541 impl<'tcx> PartialOrd for TyS<'tcx> {
542 fn partial_cmp(&self, other: &TyS<'tcx>) -> Option<Ordering> {
543 Some(self.kind.cmp(&other.kind))
547 impl<'tcx> PartialEq for TyS<'tcx> {
549 fn eq(&self, other: &TyS<'tcx>) -> bool {
553 impl<'tcx> Eq for TyS<'tcx> {}
555 impl<'tcx> Hash for TyS<'tcx> {
556 fn hash<H: Hasher>(&self, s: &mut H) {
557 (self as *const TyS<'_>).hash(s)
561 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for ty::TyS<'tcx> {
562 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
566 // The other fields just provide fast access to information that is
567 // also contained in `kind`, so no need to hash them.
570 outer_exclusive_binder: _,
573 kind.hash_stable(hcx, hasher);
577 #[rustc_diagnostic_item = "Ty"]
578 pub type Ty<'tcx> = &'tcx TyS<'tcx>;
580 impl<'tcx> rustc_serialize::UseSpecializedEncodable for Ty<'tcx> {}
581 impl<'tcx> rustc_serialize::UseSpecializedDecodable for Ty<'tcx> {}
583 pub type CanonicalTy<'tcx> = Canonical<'tcx, Ty<'tcx>>;
586 /// A dummy type used to force `List` to be unsized while not requiring references to it be wide
588 type OpaqueListContents;
591 /// A wrapper for slices with the additional invariant
592 /// that the slice is interned and no other slice with
593 /// the same contents can exist in the same context.
594 /// This means we can use pointer for both
595 /// equality comparisons and hashing.
596 /// Note: `Slice` was already taken by the `Ty`.
601 opaque: OpaqueListContents,
604 unsafe impl<T: Sync> Sync for List<T> {}
606 impl<T: Copy> List<T> {
608 fn from_arena<'tcx>(arena: &'tcx Arena<'tcx>, slice: &[T]) -> &'tcx List<T> {
609 assert!(!mem::needs_drop::<T>());
610 assert!(mem::size_of::<T>() != 0);
611 assert!(slice.len() != 0);
613 // Align up the size of the len (usize) field
614 let align = mem::align_of::<T>();
615 let align_mask = align - 1;
616 let offset = mem::size_of::<usize>();
617 let offset = (offset + align_mask) & !align_mask;
619 let size = offset + slice.len() * mem::size_of::<T>();
623 .alloc_raw(size, cmp::max(mem::align_of::<T>(), mem::align_of::<usize>()));
625 let result = &mut *(mem.as_mut_ptr() as *mut List<T>);
627 result.len = slice.len();
629 // Write the elements
630 let arena_slice = slice::from_raw_parts_mut(result.data.as_mut_ptr(), result.len);
631 arena_slice.copy_from_slice(slice);
638 impl<T: fmt::Debug> fmt::Debug for List<T> {
639 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
644 impl<T: Encodable> Encodable for List<T> {
646 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
651 impl<T> Ord for List<T>
655 fn cmp(&self, other: &List<T>) -> Ordering {
656 if self == other { Ordering::Equal } else { <[T] as Ord>::cmp(&**self, &**other) }
660 impl<T> PartialOrd for List<T>
664 fn partial_cmp(&self, other: &List<T>) -> Option<Ordering> {
666 Some(Ordering::Equal)
668 <[T] as PartialOrd>::partial_cmp(&**self, &**other)
673 impl<T: PartialEq> PartialEq for List<T> {
675 fn eq(&self, other: &List<T>) -> bool {
679 impl<T: Eq> Eq for List<T> {}
681 impl<T> Hash for List<T> {
683 fn hash<H: Hasher>(&self, s: &mut H) {
684 (self as *const List<T>).hash(s)
688 impl<T> Deref for List<T> {
691 fn deref(&self) -> &[T] {
696 impl<T> AsRef<[T]> for List<T> {
698 fn as_ref(&self) -> &[T] {
699 unsafe { slice::from_raw_parts(self.data.as_ptr(), self.len) }
703 impl<'a, T> IntoIterator for &'a List<T> {
705 type IntoIter = <&'a [T] as IntoIterator>::IntoIter;
707 fn into_iter(self) -> Self::IntoIter {
712 impl<'tcx> rustc_serialize::UseSpecializedDecodable for &'tcx List<Ty<'tcx>> {}
716 pub fn empty<'a>() -> &'a List<T> {
717 #[repr(align(64), C)]
718 struct EmptySlice([u8; 64]);
719 static EMPTY_SLICE: EmptySlice = EmptySlice([0; 64]);
720 assert!(mem::align_of::<T>() <= 64);
721 unsafe { &*(&EMPTY_SLICE as *const _ as *const List<T>) }
725 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
726 pub struct UpvarPath {
727 pub hir_id: hir::HirId,
730 /// Upvars do not get their own `NodeId`. Instead, we use the pair of
731 /// the original var ID (that is, the root variable that is referenced
732 /// by the upvar) and the ID of the closure expression.
733 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
735 pub var_path: UpvarPath,
736 pub closure_expr_id: LocalDefId,
739 #[derive(Clone, PartialEq, Debug, RustcEncodable, RustcDecodable, Copy, HashStable)]
740 pub enum BorrowKind {
741 /// Data must be immutable and is aliasable.
744 /// Data must be immutable but not aliasable. This kind of borrow
745 /// cannot currently be expressed by the user and is used only in
746 /// implicit closure bindings. It is needed when the closure
747 /// is borrowing or mutating a mutable referent, e.g.:
749 /// let x: &mut isize = ...;
750 /// let y = || *x += 5;
752 /// If we were to try to translate this closure into a more explicit
753 /// form, we'd encounter an error with the code as written:
755 /// struct Env { x: & &mut isize }
756 /// let x: &mut isize = ...;
757 /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
758 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
760 /// This is then illegal because you cannot mutate a `&mut` found
761 /// in an aliasable location. To solve, you'd have to translate with
762 /// an `&mut` borrow:
764 /// struct Env { x: & &mut isize }
765 /// let x: &mut isize = ...;
766 /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
767 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
769 /// Now the assignment to `**env.x` is legal, but creating a
770 /// mutable pointer to `x` is not because `x` is not mutable. We
771 /// could fix this by declaring `x` as `let mut x`. This is ok in
772 /// user code, if awkward, but extra weird for closures, since the
773 /// borrow is hidden.
775 /// So we introduce a "unique imm" borrow -- the referent is
776 /// immutable, but not aliasable. This solves the problem. For
777 /// simplicity, we don't give users the way to express this
778 /// borrow, it's just used when translating closures.
781 /// Data is mutable and not aliasable.
785 /// Information describing the capture of an upvar. This is computed
786 /// during `typeck`, specifically by `regionck`.
787 #[derive(PartialEq, Clone, Debug, Copy, RustcEncodable, RustcDecodable, HashStable)]
788 pub enum UpvarCapture<'tcx> {
789 /// Upvar is captured by value. This is always true when the
790 /// closure is labeled `move`, but can also be true in other cases
791 /// depending on inference.
794 /// Upvar is captured by reference.
795 ByRef(UpvarBorrow<'tcx>),
798 #[derive(PartialEq, Clone, Copy, RustcEncodable, RustcDecodable, HashStable)]
799 pub struct UpvarBorrow<'tcx> {
800 /// The kind of borrow: by-ref upvars have access to shared
801 /// immutable borrows, which are not part of the normal language
803 pub kind: BorrowKind,
805 /// Region of the resulting reference.
806 pub region: ty::Region<'tcx>,
809 pub type UpvarListMap = FxHashMap<DefId, FxIndexMap<hir::HirId, UpvarId>>;
810 pub type UpvarCaptureMap<'tcx> = FxHashMap<UpvarId, UpvarCapture<'tcx>>;
812 #[derive(Clone, Copy, PartialEq, Eq)]
813 pub enum IntVarValue {
815 UintType(ast::UintTy),
818 #[derive(Clone, Copy, PartialEq, Eq)]
819 pub struct FloatVarValue(pub ast::FloatTy);
821 impl ty::EarlyBoundRegion {
822 pub fn to_bound_region(&self) -> ty::BoundRegion {
823 ty::BoundRegion::BrNamed(self.def_id, self.name)
826 /// Does this early bound region have a name? Early bound regions normally
827 /// always have names except when using anonymous lifetimes (`'_`).
828 pub fn has_name(&self) -> bool {
829 self.name != kw::UnderscoreLifetime
833 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
834 pub enum GenericParamDefKind {
838 object_lifetime_default: ObjectLifetimeDefault,
839 synthetic: Option<hir::SyntheticTyParamKind>,
844 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable)]
845 pub struct GenericParamDef {
850 /// `pure_wrt_drop`, set by the (unsafe) `#[may_dangle]` attribute
851 /// on generic parameter `'a`/`T`, asserts data behind the parameter
852 /// `'a`/`T` won't be accessed during the parent type's `Drop` impl.
853 pub pure_wrt_drop: bool,
855 pub kind: GenericParamDefKind,
858 impl GenericParamDef {
859 pub fn to_early_bound_region_data(&self) -> ty::EarlyBoundRegion {
860 if let GenericParamDefKind::Lifetime = self.kind {
861 ty::EarlyBoundRegion { def_id: self.def_id, index: self.index, name: self.name }
863 bug!("cannot convert a non-lifetime parameter def to an early bound region")
867 pub fn to_bound_region(&self) -> ty::BoundRegion {
868 if let GenericParamDefKind::Lifetime = self.kind {
869 self.to_early_bound_region_data().to_bound_region()
871 bug!("cannot convert a non-lifetime parameter def to an early bound region")
877 pub struct GenericParamCount {
878 pub lifetimes: usize,
883 /// Information about the formal type/lifetime parameters associated
884 /// with an item or method. Analogous to `hir::Generics`.
886 /// The ordering of parameters is the same as in `Subst` (excluding child generics):
887 /// `Self` (optionally), `Lifetime` params..., `Type` params...
888 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
889 pub struct Generics {
890 pub parent: Option<DefId>,
891 pub parent_count: usize,
892 pub params: Vec<GenericParamDef>,
894 /// Reverse map to the `index` field of each `GenericParamDef`.
895 #[stable_hasher(ignore)]
896 pub param_def_id_to_index: FxHashMap<DefId, u32>,
899 pub has_late_bound_regions: Option<Span>,
902 impl<'tcx> Generics {
903 pub fn count(&self) -> usize {
904 self.parent_count + self.params.len()
907 pub fn own_counts(&self) -> GenericParamCount {
908 // We could cache this as a property of `GenericParamCount`, but
909 // the aim is to refactor this away entirely eventually and the
910 // presence of this method will be a constant reminder.
911 let mut own_counts: GenericParamCount = Default::default();
913 for param in &self.params {
915 GenericParamDefKind::Lifetime => own_counts.lifetimes += 1,
916 GenericParamDefKind::Type { .. } => own_counts.types += 1,
917 GenericParamDefKind::Const => own_counts.consts += 1,
924 pub fn requires_monomorphization(&self, tcx: TyCtxt<'tcx>) -> bool {
925 if self.own_requires_monomorphization() {
929 if let Some(parent_def_id) = self.parent {
930 let parent = tcx.generics_of(parent_def_id);
931 parent.requires_monomorphization(tcx)
937 pub fn own_requires_monomorphization(&self) -> bool {
938 for param in &self.params {
940 GenericParamDefKind::Type { .. } | GenericParamDefKind::Const => return true,
941 GenericParamDefKind::Lifetime => {}
949 param: &EarlyBoundRegion,
951 ) -> &'tcx GenericParamDef {
952 if let Some(index) = param.index.checked_sub(self.parent_count as u32) {
953 let param = &self.params[index as usize];
955 GenericParamDefKind::Lifetime => param,
956 _ => bug!("expected lifetime parameter, but found another generic parameter"),
959 tcx.generics_of(self.parent.expect("parent_count > 0 but no parent?"))
960 .region_param(param, tcx)
964 /// Returns the `GenericParamDef` associated with this `ParamTy`.
965 pub fn type_param(&'tcx self, param: &ParamTy, tcx: TyCtxt<'tcx>) -> &'tcx GenericParamDef {
966 if let Some(index) = param.index.checked_sub(self.parent_count as u32) {
967 let param = &self.params[index as usize];
969 GenericParamDefKind::Type { .. } => param,
970 _ => bug!("expected type parameter, but found another generic parameter"),
973 tcx.generics_of(self.parent.expect("parent_count > 0 but no parent?"))
974 .type_param(param, tcx)
978 /// Returns the `ConstParameterDef` associated with this `ParamConst`.
979 pub fn const_param(&'tcx self, param: &ParamConst, tcx: TyCtxt<'tcx>) -> &GenericParamDef {
980 if let Some(index) = param.index.checked_sub(self.parent_count as u32) {
981 let param = &self.params[index as usize];
983 GenericParamDefKind::Const => param,
984 _ => bug!("expected const parameter, but found another generic parameter"),
987 tcx.generics_of(self.parent.expect("parent_count>0 but no parent?"))
988 .const_param(param, tcx)
993 /// Bounds on generics.
994 #[derive(Copy, Clone, Default, Debug, RustcEncodable, RustcDecodable, HashStable)]
995 pub struct GenericPredicates<'tcx> {
996 pub parent: Option<DefId>,
997 pub predicates: &'tcx [(Predicate<'tcx>, Span)],
1000 impl<'tcx> GenericPredicates<'tcx> {
1004 substs: SubstsRef<'tcx>,
1005 ) -> InstantiatedPredicates<'tcx> {
1006 let mut instantiated = InstantiatedPredicates::empty();
1007 self.instantiate_into(tcx, &mut instantiated, substs);
1011 pub fn instantiate_own(
1014 substs: SubstsRef<'tcx>,
1015 ) -> InstantiatedPredicates<'tcx> {
1016 InstantiatedPredicates {
1017 predicates: self.predicates.iter().map(|(p, _)| p.subst(tcx, substs)).collect(),
1021 fn instantiate_into(
1024 instantiated: &mut InstantiatedPredicates<'tcx>,
1025 substs: SubstsRef<'tcx>,
1027 if let Some(def_id) = self.parent {
1028 tcx.predicates_of(def_id).instantiate_into(tcx, instantiated, substs);
1030 instantiated.predicates.extend(self.predicates.iter().map(|(p, _)| p.subst(tcx, substs)));
1033 pub fn instantiate_identity(&self, tcx: TyCtxt<'tcx>) -> InstantiatedPredicates<'tcx> {
1034 let mut instantiated = InstantiatedPredicates::empty();
1035 self.instantiate_identity_into(tcx, &mut instantiated);
1039 fn instantiate_identity_into(
1042 instantiated: &mut InstantiatedPredicates<'tcx>,
1044 if let Some(def_id) = self.parent {
1045 tcx.predicates_of(def_id).instantiate_identity_into(tcx, instantiated);
1047 instantiated.predicates.extend(self.predicates.iter().map(|&(p, _)| p))
1050 pub fn instantiate_supertrait(
1053 poly_trait_ref: &ty::PolyTraitRef<'tcx>,
1054 ) -> InstantiatedPredicates<'tcx> {
1055 assert_eq!(self.parent, None);
1056 InstantiatedPredicates {
1060 .map(|(pred, _)| pred.subst_supertrait(tcx, poly_trait_ref))
1066 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1067 #[derive(HashStable, TypeFoldable)]
1068 pub enum Predicate<'tcx> {
1069 /// Corresponds to `where Foo: Bar<A, B, C>`. `Foo` here would be
1070 /// the `Self` type of the trait reference and `A`, `B`, and `C`
1071 /// would be the type parameters.
1073 /// A trait predicate will have `Constness::Const` if it originates
1074 /// from a bound on a `const fn` without the `?const` opt-out (e.g.,
1075 /// `const fn foobar<Foo: Bar>() {}`).
1076 Trait(PolyTraitPredicate<'tcx>, Constness),
1079 RegionOutlives(PolyRegionOutlivesPredicate<'tcx>),
1082 TypeOutlives(PolyTypeOutlivesPredicate<'tcx>),
1084 /// `where <T as TraitRef>::Name == X`, approximately.
1085 /// See the `ProjectionPredicate` struct for details.
1086 Projection(PolyProjectionPredicate<'tcx>),
1088 /// No syntax: `T` well-formed.
1089 WellFormed(Ty<'tcx>),
1091 /// Trait must be object-safe.
1094 /// No direct syntax. May be thought of as `where T: FnFoo<...>`
1095 /// for some substitutions `...` and `T` being a closure type.
1096 /// Satisfied (or refuted) once we know the closure's kind.
1097 ClosureKind(DefId, SubstsRef<'tcx>, ClosureKind),
1100 Subtype(PolySubtypePredicate<'tcx>),
1102 /// Constant initializer must evaluate successfully.
1103 ConstEvaluatable(DefId, SubstsRef<'tcx>),
1106 /// The crate outlives map is computed during typeck and contains the
1107 /// outlives of every item in the local crate. You should not use it
1108 /// directly, because to do so will make your pass dependent on the
1109 /// HIR of every item in the local crate. Instead, use
1110 /// `tcx.inferred_outlives_of()` to get the outlives for a *particular*
1112 #[derive(HashStable)]
1113 pub struct CratePredicatesMap<'tcx> {
1114 /// For each struct with outlive bounds, maps to a vector of the
1115 /// predicate of its outlive bounds. If an item has no outlives
1116 /// bounds, it will have no entry.
1117 pub predicates: FxHashMap<DefId, &'tcx [(ty::Predicate<'tcx>, Span)]>,
1120 impl<'tcx> AsRef<Predicate<'tcx>> for Predicate<'tcx> {
1121 fn as_ref(&self) -> &Predicate<'tcx> {
1126 impl<'tcx> Predicate<'tcx> {
1127 /// Performs a substitution suitable for going from a
1128 /// poly-trait-ref to supertraits that must hold if that
1129 /// poly-trait-ref holds. This is slightly different from a normal
1130 /// substitution in terms of what happens with bound regions. See
1131 /// lengthy comment below for details.
1132 pub fn subst_supertrait(
1135 trait_ref: &ty::PolyTraitRef<'tcx>,
1136 ) -> ty::Predicate<'tcx> {
1137 // The interaction between HRTB and supertraits is not entirely
1138 // obvious. Let me walk you (and myself) through an example.
1140 // Let's start with an easy case. Consider two traits:
1142 // trait Foo<'a>: Bar<'a,'a> { }
1143 // trait Bar<'b,'c> { }
1145 // Now, if we have a trait reference `for<'x> T: Foo<'x>`, then
1146 // we can deduce that `for<'x> T: Bar<'x,'x>`. Basically, if we
1147 // knew that `Foo<'x>` (for any 'x) then we also know that
1148 // `Bar<'x,'x>` (for any 'x). This more-or-less falls out from
1149 // normal substitution.
1151 // In terms of why this is sound, the idea is that whenever there
1152 // is an impl of `T:Foo<'a>`, it must show that `T:Bar<'a,'a>`
1153 // holds. So if there is an impl of `T:Foo<'a>` that applies to
1154 // all `'a`, then we must know that `T:Bar<'a,'a>` holds for all
1157 // Another example to be careful of is this:
1159 // trait Foo1<'a>: for<'b> Bar1<'a,'b> { }
1160 // trait Bar1<'b,'c> { }
1162 // Here, if we have `for<'x> T: Foo1<'x>`, then what do we know?
1163 // The answer is that we know `for<'x,'b> T: Bar1<'x,'b>`. The
1164 // reason is similar to the previous example: any impl of
1165 // `T:Foo1<'x>` must show that `for<'b> T: Bar1<'x, 'b>`. So
1166 // basically we would want to collapse the bound lifetimes from
1167 // the input (`trait_ref`) and the supertraits.
1169 // To achieve this in practice is fairly straightforward. Let's
1170 // consider the more complicated scenario:
1172 // - We start out with `for<'x> T: Foo1<'x>`. In this case, `'x`
1173 // has a De Bruijn index of 1. We want to produce `for<'x,'b> T: Bar1<'x,'b>`,
1174 // where both `'x` and `'b` would have a DB index of 1.
1175 // The substitution from the input trait-ref is therefore going to be
1176 // `'a => 'x` (where `'x` has a DB index of 1).
1177 // - The super-trait-ref is `for<'b> Bar1<'a,'b>`, where `'a` is an
1178 // early-bound parameter and `'b' is a late-bound parameter with a
1180 // - If we replace `'a` with `'x` from the input, it too will have
1181 // a DB index of 1, and thus we'll have `for<'x,'b> Bar1<'x,'b>`
1182 // just as we wanted.
1184 // There is only one catch. If we just apply the substitution `'a
1185 // => 'x` to `for<'b> Bar1<'a,'b>`, the substitution code will
1186 // adjust the DB index because we substituting into a binder (it
1187 // tries to be so smart...) resulting in `for<'x> for<'b>
1188 // Bar1<'x,'b>` (we have no syntax for this, so use your
1189 // imagination). Basically the 'x will have DB index of 2 and 'b
1190 // will have DB index of 1. Not quite what we want. So we apply
1191 // the substitution to the *contents* of the trait reference,
1192 // rather than the trait reference itself (put another way, the
1193 // substitution code expects equal binding levels in the values
1194 // from the substitution and the value being substituted into, and
1195 // this trick achieves that).
1197 let substs = &trait_ref.skip_binder().substs;
1199 Predicate::Trait(ref binder, constness) => {
1200 Predicate::Trait(binder.map_bound(|data| data.subst(tcx, substs)), constness)
1202 Predicate::Subtype(ref binder) => {
1203 Predicate::Subtype(binder.map_bound(|data| data.subst(tcx, substs)))
1205 Predicate::RegionOutlives(ref binder) => {
1206 Predicate::RegionOutlives(binder.map_bound(|data| data.subst(tcx, substs)))
1208 Predicate::TypeOutlives(ref binder) => {
1209 Predicate::TypeOutlives(binder.map_bound(|data| data.subst(tcx, substs)))
1211 Predicate::Projection(ref binder) => {
1212 Predicate::Projection(binder.map_bound(|data| data.subst(tcx, substs)))
1214 Predicate::WellFormed(data) => Predicate::WellFormed(data.subst(tcx, substs)),
1215 Predicate::ObjectSafe(trait_def_id) => Predicate::ObjectSafe(trait_def_id),
1216 Predicate::ClosureKind(closure_def_id, closure_substs, kind) => {
1217 Predicate::ClosureKind(closure_def_id, closure_substs.subst(tcx, substs), kind)
1219 Predicate::ConstEvaluatable(def_id, const_substs) => {
1220 Predicate::ConstEvaluatable(def_id, const_substs.subst(tcx, substs))
1226 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1227 #[derive(HashStable, TypeFoldable)]
1228 pub struct TraitPredicate<'tcx> {
1229 pub trait_ref: TraitRef<'tcx>,
1232 pub type PolyTraitPredicate<'tcx> = ty::Binder<TraitPredicate<'tcx>>;
1234 impl<'tcx> TraitPredicate<'tcx> {
1235 pub fn def_id(&self) -> DefId {
1236 self.trait_ref.def_id
1239 pub fn input_types<'a>(&'a self) -> impl DoubleEndedIterator<Item = Ty<'tcx>> + 'a {
1240 self.trait_ref.input_types()
1243 pub fn self_ty(&self) -> Ty<'tcx> {
1244 self.trait_ref.self_ty()
1248 impl<'tcx> PolyTraitPredicate<'tcx> {
1249 pub fn def_id(&self) -> DefId {
1250 // Ok to skip binder since trait `DefId` does not care about regions.
1251 self.skip_binder().def_id()
1255 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, RustcEncodable, RustcDecodable)]
1256 #[derive(HashStable, TypeFoldable)]
1257 pub struct OutlivesPredicate<A, B>(pub A, pub B); // `A: B`
1258 pub type PolyOutlivesPredicate<A, B> = ty::Binder<OutlivesPredicate<A, B>>;
1259 pub type RegionOutlivesPredicate<'tcx> = OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>;
1260 pub type TypeOutlivesPredicate<'tcx> = OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>;
1261 pub type PolyRegionOutlivesPredicate<'tcx> = ty::Binder<RegionOutlivesPredicate<'tcx>>;
1262 pub type PolyTypeOutlivesPredicate<'tcx> = ty::Binder<TypeOutlivesPredicate<'tcx>>;
1264 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
1265 #[derive(HashStable, TypeFoldable)]
1266 pub struct SubtypePredicate<'tcx> {
1267 pub a_is_expected: bool,
1271 pub type PolySubtypePredicate<'tcx> = ty::Binder<SubtypePredicate<'tcx>>;
1273 /// This kind of predicate has no *direct* correspondent in the
1274 /// syntax, but it roughly corresponds to the syntactic forms:
1276 /// 1. `T: TraitRef<..., Item = Type>`
1277 /// 2. `<T as TraitRef<...>>::Item == Type` (NYI)
1279 /// In particular, form #1 is "desugared" to the combination of a
1280 /// normal trait predicate (`T: TraitRef<...>`) and one of these
1281 /// predicates. Form #2 is a broader form in that it also permits
1282 /// equality between arbitrary types. Processing an instance of
1283 /// Form #2 eventually yields one of these `ProjectionPredicate`
1284 /// instances to normalize the LHS.
1285 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1286 #[derive(HashStable, TypeFoldable)]
1287 pub struct ProjectionPredicate<'tcx> {
1288 pub projection_ty: ProjectionTy<'tcx>,
1292 pub type PolyProjectionPredicate<'tcx> = Binder<ProjectionPredicate<'tcx>>;
1294 impl<'tcx> PolyProjectionPredicate<'tcx> {
1295 /// Returns the `DefId` of the associated item being projected.
1296 pub fn item_def_id(&self) -> DefId {
1297 self.skip_binder().projection_ty.item_def_id
1301 pub fn to_poly_trait_ref(&self, tcx: TyCtxt<'tcx>) -> PolyTraitRef<'tcx> {
1302 // Note: unlike with `TraitRef::to_poly_trait_ref()`,
1303 // `self.0.trait_ref` is permitted to have escaping regions.
1304 // This is because here `self` has a `Binder` and so does our
1305 // return value, so we are preserving the number of binding
1307 self.map_bound(|predicate| predicate.projection_ty.trait_ref(tcx))
1310 pub fn ty(&self) -> Binder<Ty<'tcx>> {
1311 self.map_bound(|predicate| predicate.ty)
1314 /// The `DefId` of the `TraitItem` for the associated type.
1316 /// Note that this is not the `DefId` of the `TraitRef` containing this
1317 /// associated type, which is in `tcx.associated_item(projection_def_id()).container`.
1318 pub fn projection_def_id(&self) -> DefId {
1319 // Ok to skip binder since trait `DefId` does not care about regions.
1320 self.skip_binder().projection_ty.item_def_id
1324 pub trait ToPolyTraitRef<'tcx> {
1325 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx>;
1328 impl<'tcx> ToPolyTraitRef<'tcx> for TraitRef<'tcx> {
1329 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
1330 ty::Binder::dummy(*self)
1334 impl<'tcx> ToPolyTraitRef<'tcx> for PolyTraitPredicate<'tcx> {
1335 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
1336 self.map_bound_ref(|trait_pred| trait_pred.trait_ref)
1340 pub trait ToPredicate<'tcx> {
1341 fn to_predicate(&self) -> Predicate<'tcx>;
1344 impl<'tcx> ToPredicate<'tcx> for ConstnessAnd<TraitRef<'tcx>> {
1345 fn to_predicate(&self) -> Predicate<'tcx> {
1346 ty::Predicate::Trait(
1347 ty::Binder::dummy(ty::TraitPredicate { trait_ref: self.value }),
1353 impl<'tcx> ToPredicate<'tcx> for ConstnessAnd<&TraitRef<'tcx>> {
1354 fn to_predicate(&self) -> Predicate<'tcx> {
1355 ty::Predicate::Trait(
1356 ty::Binder::dummy(ty::TraitPredicate { trait_ref: self.value.clone() }),
1362 impl<'tcx> ToPredicate<'tcx> for ConstnessAnd<PolyTraitRef<'tcx>> {
1363 fn to_predicate(&self) -> Predicate<'tcx> {
1364 ty::Predicate::Trait(self.value.to_poly_trait_predicate(), self.constness)
1368 impl<'tcx> ToPredicate<'tcx> for ConstnessAnd<&PolyTraitRef<'tcx>> {
1369 fn to_predicate(&self) -> Predicate<'tcx> {
1370 ty::Predicate::Trait(self.value.to_poly_trait_predicate(), self.constness)
1374 impl<'tcx> ToPredicate<'tcx> for PolyRegionOutlivesPredicate<'tcx> {
1375 fn to_predicate(&self) -> Predicate<'tcx> {
1376 Predicate::RegionOutlives(*self)
1380 impl<'tcx> ToPredicate<'tcx> for PolyTypeOutlivesPredicate<'tcx> {
1381 fn to_predicate(&self) -> Predicate<'tcx> {
1382 Predicate::TypeOutlives(*self)
1386 impl<'tcx> ToPredicate<'tcx> for PolyProjectionPredicate<'tcx> {
1387 fn to_predicate(&self) -> Predicate<'tcx> {
1388 Predicate::Projection(*self)
1392 // A custom iterator used by `Predicate::walk_tys`.
1393 enum WalkTysIter<'tcx, I, J, K>
1395 I: Iterator<Item = Ty<'tcx>>,
1396 J: Iterator<Item = Ty<'tcx>>,
1397 K: Iterator<Item = Ty<'tcx>>,
1401 Two(Ty<'tcx>, Ty<'tcx>),
1407 impl<'tcx, I, J, K> Iterator for WalkTysIter<'tcx, I, J, K>
1409 I: Iterator<Item = Ty<'tcx>>,
1410 J: Iterator<Item = Ty<'tcx>>,
1411 K: Iterator<Item = Ty<'tcx>>,
1413 type Item = Ty<'tcx>;
1415 fn next(&mut self) -> Option<Ty<'tcx>> {
1417 WalkTysIter::None => None,
1418 WalkTysIter::One(item) => {
1419 *self = WalkTysIter::None;
1422 WalkTysIter::Two(item1, item2) => {
1423 *self = WalkTysIter::One(item2);
1426 WalkTysIter::Types(ref mut iter) => iter.next(),
1427 WalkTysIter::InputTypes(ref mut iter) => iter.next(),
1428 WalkTysIter::ProjectionTypes(ref mut iter) => iter.next(),
1433 impl<'tcx> Predicate<'tcx> {
1434 /// Iterates over the types in this predicate. Note that in all
1435 /// cases this is skipping over a binder, so late-bound regions
1436 /// with depth 0 are bound by the predicate.
1437 pub fn walk_tys(&'a self) -> impl Iterator<Item = Ty<'tcx>> + 'a {
1439 ty::Predicate::Trait(ref data, _) => {
1440 WalkTysIter::InputTypes(data.skip_binder().input_types())
1442 ty::Predicate::Subtype(binder) => {
1443 let SubtypePredicate { a, b, a_is_expected: _ } = binder.skip_binder();
1444 WalkTysIter::Two(a, b)
1446 ty::Predicate::TypeOutlives(binder) => WalkTysIter::One(binder.skip_binder().0),
1447 ty::Predicate::RegionOutlives(..) => WalkTysIter::None,
1448 ty::Predicate::Projection(ref data) => {
1449 let inner = data.skip_binder();
1450 WalkTysIter::ProjectionTypes(
1451 inner.projection_ty.substs.types().chain(Some(inner.ty)),
1454 ty::Predicate::WellFormed(data) => WalkTysIter::One(data),
1455 ty::Predicate::ObjectSafe(_trait_def_id) => WalkTysIter::None,
1456 ty::Predicate::ClosureKind(_closure_def_id, closure_substs, _kind) => {
1457 WalkTysIter::Types(closure_substs.types())
1459 ty::Predicate::ConstEvaluatable(_, substs) => WalkTysIter::Types(substs.types()),
1463 pub fn to_opt_poly_trait_ref(&self) -> Option<PolyTraitRef<'tcx>> {
1465 Predicate::Trait(ref t, _) => Some(t.to_poly_trait_ref()),
1466 Predicate::Projection(..)
1467 | Predicate::Subtype(..)
1468 | Predicate::RegionOutlives(..)
1469 | Predicate::WellFormed(..)
1470 | Predicate::ObjectSafe(..)
1471 | Predicate::ClosureKind(..)
1472 | Predicate::TypeOutlives(..)
1473 | Predicate::ConstEvaluatable(..) => None,
1477 pub fn to_opt_type_outlives(&self) -> Option<PolyTypeOutlivesPredicate<'tcx>> {
1479 Predicate::TypeOutlives(data) => Some(data),
1480 Predicate::Trait(..)
1481 | Predicate::Projection(..)
1482 | Predicate::Subtype(..)
1483 | Predicate::RegionOutlives(..)
1484 | Predicate::WellFormed(..)
1485 | Predicate::ObjectSafe(..)
1486 | Predicate::ClosureKind(..)
1487 | Predicate::ConstEvaluatable(..) => None,
1492 /// Represents the bounds declared on a particular set of type
1493 /// parameters. Should eventually be generalized into a flag list of
1494 /// where-clauses. You can obtain a `InstantiatedPredicates` list from a
1495 /// `GenericPredicates` by using the `instantiate` method. Note that this method
1496 /// reflects an important semantic invariant of `InstantiatedPredicates`: while
1497 /// the `GenericPredicates` are expressed in terms of the bound type
1498 /// parameters of the impl/trait/whatever, an `InstantiatedPredicates` instance
1499 /// represented a set of bounds for some particular instantiation,
1500 /// meaning that the generic parameters have been substituted with
1505 /// struct Foo<T, U: Bar<T>> { ... }
1507 /// Here, the `GenericPredicates` for `Foo` would contain a list of bounds like
1508 /// `[[], [U:Bar<T>]]`. Now if there were some particular reference
1509 /// like `Foo<isize,usize>`, then the `InstantiatedPredicates` would be `[[],
1510 /// [usize:Bar<isize>]]`.
1511 #[derive(Clone, Debug, TypeFoldable)]
1512 pub struct InstantiatedPredicates<'tcx> {
1513 pub predicates: Vec<Predicate<'tcx>>,
1516 impl<'tcx> InstantiatedPredicates<'tcx> {
1517 pub fn empty() -> InstantiatedPredicates<'tcx> {
1518 InstantiatedPredicates { predicates: vec![] }
1521 pub fn is_empty(&self) -> bool {
1522 self.predicates.is_empty()
1526 rustc_index::newtype_index! {
1527 /// "Universes" are used during type- and trait-checking in the
1528 /// presence of `for<..>` binders to control what sets of names are
1529 /// visible. Universes are arranged into a tree: the root universe
1530 /// contains names that are always visible. Each child then adds a new
1531 /// set of names that are visible, in addition to those of its parent.
1532 /// We say that the child universe "extends" the parent universe with
1535 /// To make this more concrete, consider this program:
1539 /// fn bar<T>(x: T) {
1540 /// let y: for<'a> fn(&'a u8, Foo) = ...;
1544 /// The struct name `Foo` is in the root universe U0. But the type
1545 /// parameter `T`, introduced on `bar`, is in an extended universe U1
1546 /// -- i.e., within `bar`, we can name both `T` and `Foo`, but outside
1547 /// of `bar`, we cannot name `T`. Then, within the type of `y`, the
1548 /// region `'a` is in a universe U2 that extends U1, because we can
1549 /// name it inside the fn type but not outside.
1551 /// Universes are used to do type- and trait-checking around these
1552 /// "forall" binders (also called **universal quantification**). The
1553 /// idea is that when, in the body of `bar`, we refer to `T` as a
1554 /// type, we aren't referring to any type in particular, but rather a
1555 /// kind of "fresh" type that is distinct from all other types we have
1556 /// actually declared. This is called a **placeholder** type, and we
1557 /// use universes to talk about this. In other words, a type name in
1558 /// universe 0 always corresponds to some "ground" type that the user
1559 /// declared, but a type name in a non-zero universe is a placeholder
1560 /// type -- an idealized representative of "types in general" that we
1561 /// use for checking generic functions.
1562 pub struct UniverseIndex {
1564 DEBUG_FORMAT = "U{}",
1568 impl UniverseIndex {
1569 pub const ROOT: UniverseIndex = UniverseIndex::from_u32_const(0);
1571 /// Returns the "next" universe index in order -- this new index
1572 /// is considered to extend all previous universes. This
1573 /// corresponds to entering a `forall` quantifier. So, for
1574 /// example, suppose we have this type in universe `U`:
1577 /// for<'a> fn(&'a u32)
1580 /// Once we "enter" into this `for<'a>` quantifier, we are in a
1581 /// new universe that extends `U` -- in this new universe, we can
1582 /// name the region `'a`, but that region was not nameable from
1583 /// `U` because it was not in scope there.
1584 pub fn next_universe(self) -> UniverseIndex {
1585 UniverseIndex::from_u32(self.private.checked_add(1).unwrap())
1588 /// Returns `true` if `self` can name a name from `other` -- in other words,
1589 /// if the set of names in `self` is a superset of those in
1590 /// `other` (`self >= other`).
1591 pub fn can_name(self, other: UniverseIndex) -> bool {
1592 self.private >= other.private
1595 /// Returns `true` if `self` cannot name some names from `other` -- in other
1596 /// words, if the set of names in `self` is a strict subset of
1597 /// those in `other` (`self < other`).
1598 pub fn cannot_name(self, other: UniverseIndex) -> bool {
1599 self.private < other.private
1603 /// The "placeholder index" fully defines a placeholder region.
1604 /// Placeholder regions are identified by both a **universe** as well
1605 /// as a "bound-region" within that universe. The `bound_region` is
1606 /// basically a name -- distinct bound regions within the same
1607 /// universe are just two regions with an unknown relationship to one
1609 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, PartialOrd, Ord)]
1610 pub struct Placeholder<T> {
1611 pub universe: UniverseIndex,
1615 impl<'a, T> HashStable<StableHashingContext<'a>> for Placeholder<T>
1617 T: HashStable<StableHashingContext<'a>>,
1619 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
1620 self.universe.hash_stable(hcx, hasher);
1621 self.name.hash_stable(hcx, hasher);
1625 pub type PlaceholderRegion = Placeholder<BoundRegion>;
1627 pub type PlaceholderType = Placeholder<BoundVar>;
1629 pub type PlaceholderConst = Placeholder<BoundVar>;
1631 /// When type checking, we use the `ParamEnv` to track
1632 /// details about the set of where-clauses that are in scope at this
1633 /// particular point.
1634 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable, TypeFoldable)]
1635 pub struct ParamEnv<'tcx> {
1636 /// `Obligation`s that the caller must satisfy. This is basically
1637 /// the set of bounds on the in-scope type parameters, translated
1638 /// into `Obligation`s, and elaborated and normalized.
1639 pub caller_bounds: &'tcx List<ty::Predicate<'tcx>>,
1641 /// Typically, this is `Reveal::UserFacing`, but during codegen we
1642 /// want `Reveal::All` -- note that this is always paired with an
1643 /// empty environment. To get that, use `ParamEnv::reveal()`.
1644 pub reveal: traits::Reveal,
1646 /// If this `ParamEnv` comes from a call to `tcx.param_env(def_id)`,
1647 /// register that `def_id` (useful for transitioning to the chalk trait
1649 pub def_id: Option<DefId>,
1652 impl<'tcx> ParamEnv<'tcx> {
1653 /// Construct a trait environment suitable for contexts where
1654 /// there are no where-clauses in scope. Hidden types (like `impl
1655 /// Trait`) are left hidden, so this is suitable for ordinary
1658 pub fn empty() -> Self {
1659 Self::new(List::empty(), Reveal::UserFacing, None)
1662 /// Construct a trait environment with no where-clauses in scope
1663 /// where the values of all `impl Trait` and other hidden types
1664 /// are revealed. This is suitable for monomorphized, post-typeck
1665 /// environments like codegen or doing optimizations.
1667 /// N.B., if you want to have predicates in scope, use `ParamEnv::new`,
1668 /// or invoke `param_env.with_reveal_all()`.
1670 pub fn reveal_all() -> Self {
1671 Self::new(List::empty(), Reveal::All, None)
1674 /// Construct a trait environment with the given set of predicates.
1677 caller_bounds: &'tcx List<ty::Predicate<'tcx>>,
1679 def_id: Option<DefId>,
1681 ty::ParamEnv { caller_bounds, reveal, def_id }
1684 /// Returns a new parameter environment with the same clauses, but
1685 /// which "reveals" the true results of projections in all cases
1686 /// (even for associated types that are specializable). This is
1687 /// the desired behavior during codegen and certain other special
1688 /// contexts; normally though we want to use `Reveal::UserFacing`,
1689 /// which is the default.
1690 pub fn with_reveal_all(self) -> Self {
1691 ty::ParamEnv { reveal: Reveal::All, ..self }
1694 /// Returns this same environment but with no caller bounds.
1695 pub fn without_caller_bounds(self) -> Self {
1696 ty::ParamEnv { caller_bounds: List::empty(), ..self }
1699 /// Creates a suitable environment in which to perform trait
1700 /// queries on the given value. When type-checking, this is simply
1701 /// the pair of the environment plus value. But when reveal is set to
1702 /// All, then if `value` does not reference any type parameters, we will
1703 /// pair it with the empty environment. This improves caching and is generally
1706 /// N.B., we preserve the environment when type-checking because it
1707 /// is possible for the user to have wacky where-clauses like
1708 /// `where Box<u32>: Copy`, which are clearly never
1709 /// satisfiable. We generally want to behave as if they were true,
1710 /// although the surrounding function is never reachable.
1711 pub fn and<T: TypeFoldable<'tcx>>(self, value: T) -> ParamEnvAnd<'tcx, T> {
1713 Reveal::UserFacing => ParamEnvAnd { param_env: self, value },
1716 if value.has_placeholders() || value.needs_infer() || value.has_param_types() {
1717 ParamEnvAnd { param_env: self, value }
1719 ParamEnvAnd { param_env: self.without_caller_bounds(), value }
1726 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1727 pub struct ConstnessAnd<T> {
1728 pub constness: Constness,
1732 // FIXME(ecstaticmorse): Audit all occurrences of `without_const().to_predicate()` to ensure that
1733 // the constness of trait bounds is being propagated correctly.
1734 pub trait WithConstness: Sized {
1736 fn with_constness(self, constness: Constness) -> ConstnessAnd<Self> {
1737 ConstnessAnd { constness, value: self }
1741 fn with_const(self) -> ConstnessAnd<Self> {
1742 self.with_constness(Constness::Const)
1746 fn without_const(self) -> ConstnessAnd<Self> {
1747 self.with_constness(Constness::NotConst)
1751 impl<T> WithConstness for T {}
1753 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TypeFoldable)]
1754 pub struct ParamEnvAnd<'tcx, T> {
1755 pub param_env: ParamEnv<'tcx>,
1759 impl<'tcx, T> ParamEnvAnd<'tcx, T> {
1760 pub fn into_parts(self) -> (ParamEnv<'tcx>, T) {
1761 (self.param_env, self.value)
1765 impl<'a, 'tcx, T> HashStable<StableHashingContext<'a>> for ParamEnvAnd<'tcx, T>
1767 T: HashStable<StableHashingContext<'a>>,
1769 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
1770 let ParamEnvAnd { ref param_env, ref value } = *self;
1772 param_env.hash_stable(hcx, hasher);
1773 value.hash_stable(hcx, hasher);
1777 #[derive(Copy, Clone, Debug, HashStable)]
1778 pub struct Destructor {
1779 /// The `DefId` of the destructor method
1784 #[derive(HashStable)]
1785 pub struct AdtFlags: u32 {
1786 const NO_ADT_FLAGS = 0;
1787 /// Indicates whether the ADT is an enum.
1788 const IS_ENUM = 1 << 0;
1789 /// Indicates whether the ADT is a union.
1790 const IS_UNION = 1 << 1;
1791 /// Indicates whether the ADT is a struct.
1792 const IS_STRUCT = 1 << 2;
1793 /// Indicates whether the ADT is a struct and has a constructor.
1794 const HAS_CTOR = 1 << 3;
1795 /// Indicates whether the type is a `PhantomData`.
1796 const IS_PHANTOM_DATA = 1 << 4;
1797 /// Indicates whether the type has a `#[fundamental]` attribute.
1798 const IS_FUNDAMENTAL = 1 << 5;
1799 /// Indicates whether the type is a `Box`.
1800 const IS_BOX = 1 << 6;
1801 /// Indicates whether the type is an `Arc`.
1802 const IS_ARC = 1 << 7;
1803 /// Indicates whether the type is an `Rc`.
1804 const IS_RC = 1 << 8;
1805 /// Indicates whether the variant list of this ADT is `#[non_exhaustive]`.
1806 /// (i.e., this flag is never set unless this ADT is an enum).
1807 const IS_VARIANT_LIST_NON_EXHAUSTIVE = 1 << 9;
1812 #[derive(HashStable)]
1813 pub struct VariantFlags: u32 {
1814 const NO_VARIANT_FLAGS = 0;
1815 /// Indicates whether the field list of this variant is `#[non_exhaustive]`.
1816 const IS_FIELD_LIST_NON_EXHAUSTIVE = 1 << 0;
1820 /// Definition of a variant -- a struct's fields or a enum variant.
1821 #[derive(Debug, HashStable)]
1822 pub struct VariantDef {
1823 /// `DefId` that identifies the variant itself.
1824 /// If this variant belongs to a struct or union, then this is a copy of its `DefId`.
1826 /// `DefId` that identifies the variant's constructor.
1827 /// If this variant is a struct variant, then this is `None`.
1828 pub ctor_def_id: Option<DefId>,
1829 /// Variant or struct name.
1830 #[stable_hasher(project(name))]
1832 /// Discriminant of this variant.
1833 pub discr: VariantDiscr,
1834 /// Fields of this variant.
1835 pub fields: Vec<FieldDef>,
1836 /// Type of constructor of variant.
1837 pub ctor_kind: CtorKind,
1838 /// Flags of the variant (e.g. is field list non-exhaustive)?
1839 flags: VariantFlags,
1840 /// Variant is obtained as part of recovering from a syntactic error.
1841 /// May be incomplete or bogus.
1842 pub recovered: bool,
1845 impl<'tcx> VariantDef {
1846 /// Creates a new `VariantDef`.
1848 /// `variant_did` is the `DefId` that identifies the enum variant (if this `VariantDef`
1849 /// represents an enum variant).
1851 /// `ctor_did` is the `DefId` that identifies the constructor of unit or
1852 /// tuple-variants/structs. If this is a `struct`-variant then this should be `None`.
1854 /// `parent_did` is the `DefId` of the `AdtDef` representing the enum or struct that
1855 /// owns this variant. It is used for checking if a struct has `#[non_exhaustive]` w/out having
1856 /// to go through the redirect of checking the ctor's attributes - but compiling a small crate
1857 /// requires loading the `AdtDef`s for all the structs in the universe (e.g., coherence for any
1858 /// built-in trait), and we do not want to load attributes twice.
1860 /// If someone speeds up attribute loading to not be a performance concern, they can
1861 /// remove this hack and use the constructor `DefId` everywhere.
1865 variant_did: Option<DefId>,
1866 ctor_def_id: Option<DefId>,
1867 discr: VariantDiscr,
1868 fields: Vec<FieldDef>,
1869 ctor_kind: CtorKind,
1875 "VariantDef::new(ident = {:?}, variant_did = {:?}, ctor_def_id = {:?}, discr = {:?},
1876 fields = {:?}, ctor_kind = {:?}, adt_kind = {:?}, parent_did = {:?})",
1877 ident, variant_did, ctor_def_id, discr, fields, ctor_kind, adt_kind, parent_did,
1880 let mut flags = VariantFlags::NO_VARIANT_FLAGS;
1881 if adt_kind == AdtKind::Struct && tcx.has_attr(parent_did, sym::non_exhaustive) {
1882 debug!("found non-exhaustive field list for {:?}", parent_did);
1883 flags = flags | VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE;
1884 } else if let Some(variant_did) = variant_did {
1885 if tcx.has_attr(variant_did, sym::non_exhaustive) {
1886 debug!("found non-exhaustive field list for {:?}", variant_did);
1887 flags = flags | VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE;
1892 def_id: variant_did.unwrap_or(parent_did),
1903 /// Is this field list non-exhaustive?
1905 pub fn is_field_list_non_exhaustive(&self) -> bool {
1906 self.flags.intersects(VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE)
1910 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
1911 pub enum VariantDiscr {
1912 /// Explicit value for this variant, i.e., `X = 123`.
1913 /// The `DefId` corresponds to the embedded constant.
1916 /// The previous variant's discriminant plus one.
1917 /// For efficiency reasons, the distance from the
1918 /// last `Explicit` discriminant is being stored,
1919 /// or `0` for the first variant, if it has none.
1923 #[derive(Debug, HashStable)]
1924 pub struct FieldDef {
1926 #[stable_hasher(project(name))]
1928 pub vis: Visibility,
1931 /// The definition of a user-defined type, e.g., a `struct`, `enum`, or `union`.
1933 /// These are all interned (by `intern_adt_def`) into the `adt_defs` table.
1935 /// The initialism *ADT* stands for an [*algebraic data type (ADT)*][adt].
1936 /// This is slightly wrong because `union`s are not ADTs.
1937 /// Moreover, Rust only allows recursive data types through indirection.
1939 /// [adt]: https://en.wikipedia.org/wiki/Algebraic_data_type
1941 /// The `DefId` of the struct, enum or union item.
1943 /// Variants of the ADT. If this is a struct or union, then there will be a single variant.
1944 pub variants: IndexVec<self::layout::VariantIdx, VariantDef>,
1945 /// Flags of the ADT (e.g., is this a struct? is this non-exhaustive?).
1947 /// Repr options provided by the user.
1948 pub repr: ReprOptions,
1951 impl PartialOrd for AdtDef {
1952 fn partial_cmp(&self, other: &AdtDef) -> Option<Ordering> {
1953 Some(self.cmp(&other))
1957 /// There should be only one AdtDef for each `did`, therefore
1958 /// it is fine to implement `Ord` only based on `did`.
1959 impl Ord for AdtDef {
1960 fn cmp(&self, other: &AdtDef) -> Ordering {
1961 self.did.cmp(&other.did)
1965 impl PartialEq for AdtDef {
1966 // `AdtDef`s are always interned, and this is part of `TyS` equality.
1968 fn eq(&self, other: &Self) -> bool {
1969 ptr::eq(self, other)
1973 impl Eq for AdtDef {}
1975 impl Hash for AdtDef {
1977 fn hash<H: Hasher>(&self, s: &mut H) {
1978 (self as *const AdtDef).hash(s)
1982 impl<'tcx> rustc_serialize::UseSpecializedEncodable for &'tcx AdtDef {
1983 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1988 impl<'tcx> rustc_serialize::UseSpecializedDecodable for &'tcx AdtDef {}
1990 impl<'a> HashStable<StableHashingContext<'a>> for AdtDef {
1991 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
1993 static CACHE: RefCell<FxHashMap<usize, Fingerprint>> = Default::default();
1996 let hash: Fingerprint = CACHE.with(|cache| {
1997 let addr = self as *const AdtDef as usize;
1998 *cache.borrow_mut().entry(addr).or_insert_with(|| {
1999 let ty::AdtDef { did, ref variants, ref flags, ref repr } = *self;
2001 let mut hasher = StableHasher::new();
2002 did.hash_stable(hcx, &mut hasher);
2003 variants.hash_stable(hcx, &mut hasher);
2004 flags.hash_stable(hcx, &mut hasher);
2005 repr.hash_stable(hcx, &mut hasher);
2011 hash.hash_stable(hcx, hasher);
2015 #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
2022 impl Into<DataTypeKind> for AdtKind {
2023 fn into(self) -> DataTypeKind {
2025 AdtKind::Struct => DataTypeKind::Struct,
2026 AdtKind::Union => DataTypeKind::Union,
2027 AdtKind::Enum => DataTypeKind::Enum,
2033 #[derive(RustcEncodable, RustcDecodable, Default, HashStable)]
2034 pub struct ReprFlags: u8 {
2035 const IS_C = 1 << 0;
2036 const IS_SIMD = 1 << 1;
2037 const IS_TRANSPARENT = 1 << 2;
2038 // Internal only for now. If true, don't reorder fields.
2039 const IS_LINEAR = 1 << 3;
2041 // Any of these flags being set prevent field reordering optimisation.
2042 const IS_UNOPTIMISABLE = ReprFlags::IS_C.bits |
2043 ReprFlags::IS_SIMD.bits |
2044 ReprFlags::IS_LINEAR.bits;
2048 /// Represents the repr options provided by the user,
2049 #[derive(Copy, Clone, Debug, Eq, PartialEq, RustcEncodable, RustcDecodable, Default, HashStable)]
2050 pub struct ReprOptions {
2051 pub int: Option<attr::IntType>,
2052 pub align: Option<Align>,
2053 pub pack: Option<Align>,
2054 pub flags: ReprFlags,
2058 pub fn new(tcx: TyCtxt<'_>, did: DefId) -> ReprOptions {
2059 let mut flags = ReprFlags::empty();
2060 let mut size = None;
2061 let mut max_align: Option<Align> = None;
2062 let mut min_pack: Option<Align> = None;
2063 for attr in tcx.get_attrs(did).iter() {
2064 for r in attr::find_repr_attrs(&tcx.sess.parse_sess, attr) {
2065 flags.insert(match r {
2066 attr::ReprC => ReprFlags::IS_C,
2067 attr::ReprPacked(pack) => {
2068 let pack = Align::from_bytes(pack as u64).unwrap();
2069 min_pack = Some(if let Some(min_pack) = min_pack {
2076 attr::ReprTransparent => ReprFlags::IS_TRANSPARENT,
2077 attr::ReprSimd => ReprFlags::IS_SIMD,
2078 attr::ReprInt(i) => {
2082 attr::ReprAlign(align) => {
2083 max_align = max_align.max(Some(Align::from_bytes(align as u64).unwrap()));
2090 // This is here instead of layout because the choice must make it into metadata.
2091 if !tcx.consider_optimizing(|| format!("Reorder fields of {:?}", tcx.def_path_str(did))) {
2092 flags.insert(ReprFlags::IS_LINEAR);
2094 ReprOptions { int: size, align: max_align, pack: min_pack, flags: flags }
2098 pub fn simd(&self) -> bool {
2099 self.flags.contains(ReprFlags::IS_SIMD)
2102 pub fn c(&self) -> bool {
2103 self.flags.contains(ReprFlags::IS_C)
2106 pub fn packed(&self) -> bool {
2110 pub fn transparent(&self) -> bool {
2111 self.flags.contains(ReprFlags::IS_TRANSPARENT)
2114 pub fn linear(&self) -> bool {
2115 self.flags.contains(ReprFlags::IS_LINEAR)
2118 pub fn discr_type(&self) -> attr::IntType {
2119 self.int.unwrap_or(attr::SignedInt(ast::IntTy::Isize))
2122 /// Returns `true` if this `#[repr()]` should inhabit "smart enum
2123 /// layout" optimizations, such as representing `Foo<&T>` as a
2125 pub fn inhibit_enum_layout_opt(&self) -> bool {
2126 self.c() || self.int.is_some()
2129 /// Returns `true` if this `#[repr()]` should inhibit struct field reordering
2130 /// optimizations, such as with `repr(C)`, `repr(packed(1))`, or `repr(<int>)`.
2131 pub fn inhibit_struct_field_reordering_opt(&self) -> bool {
2132 if let Some(pack) = self.pack {
2133 if pack.bytes() == 1 {
2137 self.flags.intersects(ReprFlags::IS_UNOPTIMISABLE) || self.int.is_some()
2140 /// Returns `true` if this `#[repr()]` should inhibit union ABI optimisations.
2141 pub fn inhibit_union_abi_opt(&self) -> bool {
2147 /// Creates a new `AdtDef`.
2152 variants: IndexVec<VariantIdx, VariantDef>,
2155 debug!("AdtDef::new({:?}, {:?}, {:?}, {:?})", did, kind, variants, repr);
2156 let mut flags = AdtFlags::NO_ADT_FLAGS;
2158 if kind == AdtKind::Enum && tcx.has_attr(did, sym::non_exhaustive) {
2159 debug!("found non-exhaustive variant list for {:?}", did);
2160 flags = flags | AdtFlags::IS_VARIANT_LIST_NON_EXHAUSTIVE;
2163 flags |= match kind {
2164 AdtKind::Enum => AdtFlags::IS_ENUM,
2165 AdtKind::Union => AdtFlags::IS_UNION,
2166 AdtKind::Struct => AdtFlags::IS_STRUCT,
2169 if kind == AdtKind::Struct && variants[VariantIdx::new(0)].ctor_def_id.is_some() {
2170 flags |= AdtFlags::HAS_CTOR;
2173 let attrs = tcx.get_attrs(did);
2174 if attr::contains_name(&attrs, sym::fundamental) {
2175 flags |= AdtFlags::IS_FUNDAMENTAL;
2177 if Some(did) == tcx.lang_items().phantom_data() {
2178 flags |= AdtFlags::IS_PHANTOM_DATA;
2180 if Some(did) == tcx.lang_items().owned_box() {
2181 flags |= AdtFlags::IS_BOX;
2183 if Some(did) == tcx.lang_items().arc() {
2184 flags |= AdtFlags::IS_ARC;
2186 if Some(did) == tcx.lang_items().rc() {
2187 flags |= AdtFlags::IS_RC;
2190 AdtDef { did, variants, flags, repr }
2193 /// Returns `true` if this is a struct.
2195 pub fn is_struct(&self) -> bool {
2196 self.flags.contains(AdtFlags::IS_STRUCT)
2199 /// Returns `true` if this is a union.
2201 pub fn is_union(&self) -> bool {
2202 self.flags.contains(AdtFlags::IS_UNION)
2205 /// Returns `true` if this is a enum.
2207 pub fn is_enum(&self) -> bool {
2208 self.flags.contains(AdtFlags::IS_ENUM)
2211 /// Returns `true` if the variant list of this ADT is `#[non_exhaustive]`.
2213 pub fn is_variant_list_non_exhaustive(&self) -> bool {
2214 self.flags.contains(AdtFlags::IS_VARIANT_LIST_NON_EXHAUSTIVE)
2217 /// Returns the kind of the ADT.
2219 pub fn adt_kind(&self) -> AdtKind {
2222 } else if self.is_union() {
2229 /// Returns a description of this abstract data type.
2230 pub fn descr(&self) -> &'static str {
2231 match self.adt_kind() {
2232 AdtKind::Struct => "struct",
2233 AdtKind::Union => "union",
2234 AdtKind::Enum => "enum",
2238 /// Returns a description of a variant of this abstract data type.
2240 pub fn variant_descr(&self) -> &'static str {
2241 match self.adt_kind() {
2242 AdtKind::Struct => "struct",
2243 AdtKind::Union => "union",
2244 AdtKind::Enum => "variant",
2248 /// If this function returns `true`, it implies that `is_struct` must return `true`.
2250 pub fn has_ctor(&self) -> bool {
2251 self.flags.contains(AdtFlags::HAS_CTOR)
2254 /// Returns `true` if this type is `#[fundamental]` for the purposes
2255 /// of coherence checking.
2257 pub fn is_fundamental(&self) -> bool {
2258 self.flags.contains(AdtFlags::IS_FUNDAMENTAL)
2261 /// Returns `true` if this is `PhantomData<T>`.
2263 pub fn is_phantom_data(&self) -> bool {
2264 self.flags.contains(AdtFlags::IS_PHANTOM_DATA)
2267 /// Returns `true` if this is `Arc<T>`.
2268 pub fn is_arc(&self) -> bool {
2269 self.flags.contains(AdtFlags::IS_ARC)
2272 /// Returns `true` if this is `Rc<T>`.
2273 pub fn is_rc(&self) -> bool {
2274 self.flags.contains(AdtFlags::IS_RC)
2277 /// Returns `true` if this is Box<T>.
2279 pub fn is_box(&self) -> bool {
2280 self.flags.contains(AdtFlags::IS_BOX)
2283 /// Returns `true` if this type has a destructor.
2284 pub fn has_dtor(&self, tcx: TyCtxt<'tcx>) -> bool {
2285 self.destructor(tcx).is_some()
2288 /// Asserts this is a struct or union and returns its unique variant.
2289 pub fn non_enum_variant(&self) -> &VariantDef {
2290 assert!(self.is_struct() || self.is_union());
2291 &self.variants[VariantIdx::new(0)]
2295 pub fn predicates(&self, tcx: TyCtxt<'tcx>) -> GenericPredicates<'tcx> {
2296 tcx.predicates_of(self.did)
2299 /// Returns an iterator over all fields contained
2302 pub fn all_fields(&self) -> impl Iterator<Item = &FieldDef> + Clone {
2303 self.variants.iter().flat_map(|v| v.fields.iter())
2306 pub fn is_payloadfree(&self) -> bool {
2307 !self.variants.is_empty() && self.variants.iter().all(|v| v.fields.is_empty())
2310 /// Return a `VariantDef` given a variant id.
2311 pub fn variant_with_id(&self, vid: DefId) -> &VariantDef {
2312 self.variants.iter().find(|v| v.def_id == vid).expect("variant_with_id: unknown variant")
2315 /// Return a `VariantDef` given a constructor id.
2316 pub fn variant_with_ctor_id(&self, cid: DefId) -> &VariantDef {
2319 .find(|v| v.ctor_def_id == Some(cid))
2320 .expect("variant_with_ctor_id: unknown variant")
2323 /// Return the index of `VariantDef` given a variant id.
2324 pub fn variant_index_with_id(&self, vid: DefId) -> VariantIdx {
2327 .find(|(_, v)| v.def_id == vid)
2328 .expect("variant_index_with_id: unknown variant")
2332 /// Return the index of `VariantDef` given a constructor id.
2333 pub fn variant_index_with_ctor_id(&self, cid: DefId) -> VariantIdx {
2336 .find(|(_, v)| v.ctor_def_id == Some(cid))
2337 .expect("variant_index_with_ctor_id: unknown variant")
2341 pub fn variant_of_res(&self, res: Res) -> &VariantDef {
2343 Res::Def(DefKind::Variant, vid) => self.variant_with_id(vid),
2344 Res::Def(DefKind::Ctor(..), cid) => self.variant_with_ctor_id(cid),
2345 Res::Def(DefKind::Struct, _)
2346 | Res::Def(DefKind::Union, _)
2347 | Res::Def(DefKind::TyAlias, _)
2348 | Res::Def(DefKind::AssocTy, _)
2350 | Res::SelfCtor(..) => self.non_enum_variant(),
2351 _ => bug!("unexpected res {:?} in variant_of_res", res),
2356 pub fn eval_explicit_discr(&self, tcx: TyCtxt<'tcx>, expr_did: DefId) -> Option<Discr<'tcx>> {
2357 let param_env = tcx.param_env(expr_did);
2358 let repr_type = self.repr.discr_type();
2359 match tcx.const_eval_poly(expr_did) {
2361 // FIXME: Find the right type and use it instead of `val.ty` here
2362 if let Some(b) = val.try_eval_bits(tcx, param_env, val.ty) {
2363 trace!("discriminants: {} ({:?})", b, repr_type);
2364 Some(Discr { val: b, ty: val.ty })
2366 info!("invalid enum discriminant: {:#?}", val);
2367 crate::mir::interpret::struct_error(
2368 tcx.at(tcx.def_span(expr_did)),
2369 "constant evaluation of enum discriminant resulted in non-integer",
2375 Err(ErrorHandled::Reported) => {
2376 if !expr_did.is_local() {
2378 tcx.def_span(expr_did),
2379 "variant discriminant evaluation succeeded \
2380 in its crate but failed locally"
2385 Err(ErrorHandled::TooGeneric) => {
2386 span_bug!(tcx.def_span(expr_did), "enum discriminant depends on generic arguments",)
2392 pub fn discriminants(
2395 ) -> impl Iterator<Item = (VariantIdx, Discr<'tcx>)> + Captures<'tcx> {
2396 let repr_type = self.repr.discr_type();
2397 let initial = repr_type.initial_discriminant(tcx);
2398 let mut prev_discr = None::<Discr<'tcx>>;
2399 self.variants.iter_enumerated().map(move |(i, v)| {
2400 let mut discr = prev_discr.map_or(initial, |d| d.wrap_incr(tcx));
2401 if let VariantDiscr::Explicit(expr_did) = v.discr {
2402 if let Some(new_discr) = self.eval_explicit_discr(tcx, expr_did) {
2406 prev_discr = Some(discr);
2413 pub fn variant_range(&self) -> Range<VariantIdx> {
2414 VariantIdx::new(0)..VariantIdx::new(self.variants.len())
2417 /// Computes the discriminant value used by a specific variant.
2418 /// Unlike `discriminants`, this is (amortized) constant-time,
2419 /// only doing at most one query for evaluating an explicit
2420 /// discriminant (the last one before the requested variant),
2421 /// assuming there are no constant-evaluation errors there.
2423 pub fn discriminant_for_variant(
2426 variant_index: VariantIdx,
2428 let (val, offset) = self.discriminant_def_for_variant(variant_index);
2429 let explicit_value = val
2430 .and_then(|expr_did| self.eval_explicit_discr(tcx, expr_did))
2431 .unwrap_or_else(|| self.repr.discr_type().initial_discriminant(tcx));
2432 explicit_value.checked_add(tcx, offset as u128).0
2435 /// Yields a `DefId` for the discriminant and an offset to add to it
2436 /// Alternatively, if there is no explicit discriminant, returns the
2437 /// inferred discriminant directly.
2438 pub fn discriminant_def_for_variant(&self, variant_index: VariantIdx) -> (Option<DefId>, u32) {
2439 let mut explicit_index = variant_index.as_u32();
2442 match self.variants[VariantIdx::from_u32(explicit_index)].discr {
2443 ty::VariantDiscr::Relative(0) => {
2447 ty::VariantDiscr::Relative(distance) => {
2448 explicit_index -= distance;
2450 ty::VariantDiscr::Explicit(did) => {
2451 expr_did = Some(did);
2456 (expr_did, variant_index.as_u32() - explicit_index)
2459 pub fn destructor(&self, tcx: TyCtxt<'tcx>) -> Option<Destructor> {
2460 tcx.adt_destructor(self.did)
2463 /// Returns a list of types such that `Self: Sized` if and only
2464 /// if that type is `Sized`, or `TyErr` if this type is recursive.
2466 /// Oddly enough, checking that the sized-constraint is `Sized` is
2467 /// actually more expressive than checking all members:
2468 /// the `Sized` trait is inductive, so an associated type that references
2469 /// `Self` would prevent its containing ADT from being `Sized`.
2471 /// Due to normalization being eager, this applies even if
2472 /// the associated type is behind a pointer (e.g., issue #31299).
2473 pub fn sized_constraint(&self, tcx: TyCtxt<'tcx>) -> &'tcx [Ty<'tcx>] {
2474 tcx.adt_sized_constraint(self.did).0
2478 impl<'tcx> FieldDef {
2479 /// Returns the type of this field. The `subst` is typically obtained
2480 /// via the second field of `TyKind::AdtDef`.
2481 pub fn ty(&self, tcx: TyCtxt<'tcx>, subst: SubstsRef<'tcx>) -> Ty<'tcx> {
2482 tcx.type_of(self.did).subst(tcx, subst)
2486 /// Represents the various closure traits in the language. This
2487 /// will determine the type of the environment (`self`, in the
2488 /// desugaring) argument that the closure expects.
2490 /// You can get the environment type of a closure using
2491 /// `tcx.closure_env_ty()`.
2505 pub enum ClosureKind {
2506 // Warning: Ordering is significant here! The ordering is chosen
2507 // because the trait Fn is a subtrait of FnMut and so in turn, and
2508 // hence we order it so that Fn < FnMut < FnOnce.
2514 impl<'tcx> ClosureKind {
2515 // This is the initial value used when doing upvar inference.
2516 pub const LATTICE_BOTTOM: ClosureKind = ClosureKind::Fn;
2518 pub fn trait_did(&self, tcx: TyCtxt<'tcx>) -> DefId {
2520 ClosureKind::Fn => tcx.require_lang_item(FnTraitLangItem, None),
2521 ClosureKind::FnMut => tcx.require_lang_item(FnMutTraitLangItem, None),
2522 ClosureKind::FnOnce => tcx.require_lang_item(FnOnceTraitLangItem, None),
2526 /// Returns `true` if this a type that impls this closure kind
2527 /// must also implement `other`.
2528 pub fn extends(self, other: ty::ClosureKind) -> bool {
2529 match (self, other) {
2530 (ClosureKind::Fn, ClosureKind::Fn) => true,
2531 (ClosureKind::Fn, ClosureKind::FnMut) => true,
2532 (ClosureKind::Fn, ClosureKind::FnOnce) => true,
2533 (ClosureKind::FnMut, ClosureKind::FnMut) => true,
2534 (ClosureKind::FnMut, ClosureKind::FnOnce) => true,
2535 (ClosureKind::FnOnce, ClosureKind::FnOnce) => true,
2540 /// Returns the representative scalar type for this closure kind.
2541 /// See `TyS::to_opt_closure_kind` for more details.
2542 pub fn to_ty(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
2544 ty::ClosureKind::Fn => tcx.types.i8,
2545 ty::ClosureKind::FnMut => tcx.types.i16,
2546 ty::ClosureKind::FnOnce => tcx.types.i32,
2551 impl<'tcx> TyS<'tcx> {
2552 /// Iterator that walks `self` and any types reachable from
2553 /// `self`, in depth-first order. Note that just walks the types
2554 /// that appear in `self`, it does not descend into the fields of
2555 /// structs or variants. For example:
2558 /// isize => { isize }
2559 /// Foo<Bar<isize>> => { Foo<Bar<isize>>, Bar<isize>, isize }
2560 /// [isize] => { [isize], isize }
2562 pub fn walk(&'tcx self) -> TypeWalker<'tcx> {
2563 TypeWalker::new(self)
2566 /// Iterator that walks the immediate children of `self`. Hence
2567 /// `Foo<Bar<i32>, u32>` yields the sequence `[Bar<i32>, u32]`
2568 /// (but not `i32`, like `walk`).
2569 pub fn walk_shallow(&'tcx self) -> smallvec::IntoIter<walk::TypeWalkerArray<'tcx>> {
2570 walk::walk_shallow(self)
2573 /// Walks `ty` and any types appearing within `ty`, invoking the
2574 /// callback `f` on each type. If the callback returns `false`, then the
2575 /// children of the current type are ignored.
2577 /// Note: prefer `ty.walk()` where possible.
2578 pub fn maybe_walk<F>(&'tcx self, mut f: F)
2580 F: FnMut(Ty<'tcx>) -> bool,
2582 let mut walker = self.walk();
2583 while let Some(ty) = walker.next() {
2585 walker.skip_current_subtree();
2592 pub fn from_mutbl(m: hir::Mutability) -> BorrowKind {
2594 hir::Mutability::Mut => MutBorrow,
2595 hir::Mutability::Not => ImmBorrow,
2599 /// Returns a mutability `m` such that an `&m T` pointer could be used to obtain this borrow
2600 /// kind. Because borrow kinds are richer than mutabilities, we sometimes have to pick a
2601 /// mutability that is stronger than necessary so that it at least *would permit* the borrow in
2603 pub fn to_mutbl_lossy(self) -> hir::Mutability {
2605 MutBorrow => hir::Mutability::Mut,
2606 ImmBorrow => hir::Mutability::Not,
2608 // We have no type corresponding to a unique imm borrow, so
2609 // use `&mut`. It gives all the capabilities of an `&uniq`
2610 // and hence is a safe "over approximation".
2611 UniqueImmBorrow => hir::Mutability::Mut,
2615 pub fn to_user_str(&self) -> &'static str {
2617 MutBorrow => "mutable",
2618 ImmBorrow => "immutable",
2619 UniqueImmBorrow => "uniquely immutable",
2624 #[derive(Debug, Clone)]
2625 pub enum Attributes<'tcx> {
2626 Owned(Lrc<[ast::Attribute]>),
2627 Borrowed(&'tcx [ast::Attribute]),
2630 impl<'tcx> ::std::ops::Deref for Attributes<'tcx> {
2631 type Target = [ast::Attribute];
2633 fn deref(&self) -> &[ast::Attribute] {
2635 &Attributes::Owned(ref data) => &data,
2636 &Attributes::Borrowed(data) => data,
2641 #[derive(Debug, PartialEq, Eq)]
2642 pub enum ImplOverlapKind {
2643 /// These impls are always allowed to overlap.
2645 /// Whether or not the impl is permitted due to the trait being
2646 /// a marker trait (a trait with #[marker], or a trait with
2647 /// no associated items and #![feature(overlapping_marker_traits)] enabled)
2650 /// These impls are allowed to overlap, but that raises
2651 /// an issue #33140 future-compatibility warning.
2653 /// Some background: in Rust 1.0, the trait-object types `Send + Sync` (today's
2654 /// `dyn Send + Sync`) and `Sync + Send` (now `dyn Sync + Send`) were different.
2656 /// The widely-used version 0.1.0 of the crate `traitobject` had accidentally relied
2657 /// that difference, making what reduces to the following set of impls:
2661 /// impl Trait for dyn Send + Sync {}
2662 /// impl Trait for dyn Sync + Send {}
2665 /// Obviously, once we made these types be identical, that code causes a coherence
2666 /// error and a fairly big headache for us. However, luckily for us, the trait
2667 /// `Trait` used in this case is basically a marker trait, and therefore having
2668 /// overlapping impls for it is sound.
2670 /// To handle this, we basically regard the trait as a marker trait, with an additional
2671 /// future-compatibility warning. To avoid accidentally "stabilizing" this feature,
2672 /// it has the following restrictions:
2674 /// 1. The trait must indeed be a marker-like trait (i.e., no items), and must be
2676 /// 2. The trait-ref of both impls must be equal.
2677 /// 3. The trait-ref of both impls must be a trait object type consisting only of
2679 /// 4. Neither of the impls can have any where-clauses.
2681 /// Once `traitobject` 0.1.0 is no longer an active concern, this hack can be removed.
2685 impl<'tcx> TyCtxt<'tcx> {
2686 pub fn body_tables(self, body: hir::BodyId) -> &'tcx TypeckTables<'tcx> {
2687 self.typeck_tables_of(self.hir().body_owner_def_id(body))
2690 /// Returns an iterator of the `DefId`s for all body-owners in this
2691 /// crate. If you would prefer to iterate over the bodies
2692 /// themselves, you can do `self.hir().krate().body_ids.iter()`.
2693 pub fn body_owners(self) -> impl Iterator<Item = DefId> + Captures<'tcx> + 'tcx {
2698 .map(move |&body_id| self.hir().body_owner_def_id(body_id))
2701 pub fn par_body_owners<F: Fn(DefId) + sync::Sync + sync::Send>(self, f: F) {
2702 par_iter(&self.hir().krate().body_ids)
2703 .for_each(|&body_id| f(self.hir().body_owner_def_id(body_id)));
2706 pub fn provided_trait_methods(self, id: DefId) -> Vec<AssocItem> {
2707 self.associated_items(id)
2708 .filter(|item| item.kind == AssocKind::Method && item.defaultness.has_value())
2712 pub fn trait_relevant_for_never(self, did: DefId) -> bool {
2713 self.associated_items(did).any(|item| item.relevant_for_never())
2716 pub fn opt_item_name(self, def_id: DefId) -> Option<Ident> {
2717 self.hir().as_local_hir_id(def_id).and_then(|hir_id| self.hir().get(hir_id).ident())
2720 pub fn opt_associated_item(self, def_id: DefId) -> Option<AssocItem> {
2721 let is_associated_item = if let Some(hir_id) = self.hir().as_local_hir_id(def_id) {
2722 match self.hir().get(hir_id) {
2723 Node::TraitItem(_) | Node::ImplItem(_) => true,
2727 match self.def_kind(def_id).expect("no def for `DefId`") {
2728 DefKind::AssocConst | DefKind::Method | DefKind::AssocTy => true,
2733 is_associated_item.then(|| self.associated_item(def_id))
2736 pub fn field_index(self, hir_id: hir::HirId, tables: &TypeckTables<'_>) -> usize {
2737 tables.field_indices().get(hir_id).cloned().expect("no index for a field")
2740 pub fn find_field_index(self, ident: Ident, variant: &VariantDef) -> Option<usize> {
2741 variant.fields.iter().position(|field| self.hygienic_eq(ident, field.ident, variant.def_id))
2744 pub fn associated_items(self, def_id: DefId) -> AssocItemsIterator<'tcx> {
2745 // Ideally, we would use `-> impl Iterator` here, but it falls
2746 // afoul of the conservative "capture [restrictions]" we put
2747 // in place, so we use a hand-written iterator.
2749 // [restrictions]: https://github.com/rust-lang/rust/issues/34511#issuecomment-373423999
2750 AssocItemsIterator {
2752 def_ids: self.associated_item_def_ids(def_id),
2757 /// Returns `true` if the impls are the same polarity and the trait either
2758 /// has no items or is annotated #[marker] and prevents item overrides.
2759 pub fn impls_are_allowed_to_overlap(
2763 ) -> Option<ImplOverlapKind> {
2764 // If either trait impl references an error, they're allowed to overlap,
2765 // as one of them essentially doesn't exist.
2766 if self.impl_trait_ref(def_id1).map_or(false, |tr| tr.references_error())
2767 || self.impl_trait_ref(def_id2).map_or(false, |tr| tr.references_error())
2769 return Some(ImplOverlapKind::Permitted { marker: false });
2772 match (self.impl_polarity(def_id1), self.impl_polarity(def_id2)) {
2773 (ImplPolarity::Reservation, _) | (_, ImplPolarity::Reservation) => {
2774 // `#[rustc_reservation_impl]` impls don't overlap with anything
2776 "impls_are_allowed_to_overlap({:?}, {:?}) = Some(Permitted) (reservations)",
2779 return Some(ImplOverlapKind::Permitted { marker: false });
2781 (ImplPolarity::Positive, ImplPolarity::Negative)
2782 | (ImplPolarity::Negative, ImplPolarity::Positive) => {
2783 // `impl AutoTrait for Type` + `impl !AutoTrait for Type`
2785 "impls_are_allowed_to_overlap({:?}, {:?}) - None (differing polarities)",
2790 (ImplPolarity::Positive, ImplPolarity::Positive)
2791 | (ImplPolarity::Negative, ImplPolarity::Negative) => {}
2794 let is_marker_overlap = if self.features().overlapping_marker_traits {
2795 let trait1_is_empty = self.impl_trait_ref(def_id1).map_or(false, |trait_ref| {
2796 self.associated_item_def_ids(trait_ref.def_id).is_empty()
2798 let trait2_is_empty = self.impl_trait_ref(def_id2).map_or(false, |trait_ref| {
2799 self.associated_item_def_ids(trait_ref.def_id).is_empty()
2801 trait1_is_empty && trait2_is_empty
2803 let is_marker_impl = |def_id: DefId| -> bool {
2804 let trait_ref = self.impl_trait_ref(def_id);
2805 trait_ref.map_or(false, |tr| self.trait_def(tr.def_id).is_marker)
2807 is_marker_impl(def_id1) && is_marker_impl(def_id2)
2810 if is_marker_overlap {
2812 "impls_are_allowed_to_overlap({:?}, {:?}) = Some(Permitted) (marker overlap)",
2815 Some(ImplOverlapKind::Permitted { marker: true })
2817 if let Some(self_ty1) = self.issue33140_self_ty(def_id1) {
2818 if let Some(self_ty2) = self.issue33140_self_ty(def_id2) {
2819 if self_ty1 == self_ty2 {
2821 "impls_are_allowed_to_overlap({:?}, {:?}) - issue #33140 HACK",
2824 return Some(ImplOverlapKind::Issue33140);
2827 "impls_are_allowed_to_overlap({:?}, {:?}) - found {:?} != {:?}",
2828 def_id1, def_id2, self_ty1, self_ty2
2834 debug!("impls_are_allowed_to_overlap({:?}, {:?}) = None", def_id1, def_id2);
2839 /// Returns `ty::VariantDef` if `res` refers to a struct,
2840 /// or variant or their constructors, panics otherwise.
2841 pub fn expect_variant_res(self, res: Res) -> &'tcx VariantDef {
2843 Res::Def(DefKind::Variant, did) => {
2844 let enum_did = self.parent(did).unwrap();
2845 self.adt_def(enum_did).variant_with_id(did)
2847 Res::Def(DefKind::Struct, did) | Res::Def(DefKind::Union, did) => {
2848 self.adt_def(did).non_enum_variant()
2850 Res::Def(DefKind::Ctor(CtorOf::Variant, ..), variant_ctor_did) => {
2851 let variant_did = self.parent(variant_ctor_did).unwrap();
2852 let enum_did = self.parent(variant_did).unwrap();
2853 self.adt_def(enum_did).variant_with_ctor_id(variant_ctor_did)
2855 Res::Def(DefKind::Ctor(CtorOf::Struct, ..), ctor_did) => {
2856 let struct_did = self.parent(ctor_did).expect("struct ctor has no parent");
2857 self.adt_def(struct_did).non_enum_variant()
2859 _ => bug!("expect_variant_res used with unexpected res {:?}", res),
2863 pub fn item_name(self, id: DefId) -> Symbol {
2864 if id.index == CRATE_DEF_INDEX {
2865 self.original_crate_name(id.krate)
2867 let def_key = self.def_key(id);
2868 match def_key.disambiguated_data.data {
2869 // The name of a constructor is that of its parent.
2870 hir_map::DefPathData::Ctor => {
2871 self.item_name(DefId { krate: id.krate, index: def_key.parent.unwrap() })
2873 _ => def_key.disambiguated_data.data.get_opt_name().unwrap_or_else(|| {
2874 bug!("item_name: no name for {:?}", self.def_path(id));
2880 /// Returns the possibly-auto-generated MIR of a `(DefId, Subst)` pair.
2881 pub fn instance_mir(self, instance: ty::InstanceDef<'tcx>) -> ReadOnlyBodyAndCache<'tcx, 'tcx> {
2883 ty::InstanceDef::Item(did) => self.optimized_mir(did).unwrap_read_only(),
2884 ty::InstanceDef::VtableShim(..)
2885 | ty::InstanceDef::ReifyShim(..)
2886 | ty::InstanceDef::Intrinsic(..)
2887 | ty::InstanceDef::FnPtrShim(..)
2888 | ty::InstanceDef::Virtual(..)
2889 | ty::InstanceDef::ClosureOnceShim { .. }
2890 | ty::InstanceDef::DropGlue(..)
2891 | ty::InstanceDef::CloneShim(..) => self.mir_shims(instance).unwrap_read_only(),
2895 /// Gets the attributes of a definition.
2896 pub fn get_attrs(self, did: DefId) -> Attributes<'tcx> {
2897 if let Some(id) = self.hir().as_local_hir_id(did) {
2898 Attributes::Borrowed(self.hir().attrs(id))
2900 Attributes::Owned(self.item_attrs(did))
2904 /// Determines whether an item is annotated with an attribute.
2905 pub fn has_attr(self, did: DefId, attr: Symbol) -> bool {
2906 attr::contains_name(&self.get_attrs(did), attr)
2909 /// Returns `true` if this is an `auto trait`.
2910 pub fn trait_is_auto(self, trait_def_id: DefId) -> bool {
2911 self.trait_def(trait_def_id).has_auto_impl
2914 pub fn generator_layout(self, def_id: DefId) -> &'tcx GeneratorLayout<'tcx> {
2915 self.optimized_mir(def_id).generator_layout.as_ref().unwrap()
2918 /// Given the `DefId` of an impl, returns the `DefId` of the trait it implements.
2919 /// If it implements no trait, returns `None`.
2920 pub fn trait_id_of_impl(self, def_id: DefId) -> Option<DefId> {
2921 self.impl_trait_ref(def_id).map(|tr| tr.def_id)
2924 /// If the given defid describes a method belonging to an impl, returns the
2925 /// `DefId` of the impl that the method belongs to; otherwise, returns `None`.
2926 pub fn impl_of_method(self, def_id: DefId) -> Option<DefId> {
2927 let item = if def_id.krate != LOCAL_CRATE {
2928 if let Some(DefKind::Method) = self.def_kind(def_id) {
2929 Some(self.associated_item(def_id))
2934 self.opt_associated_item(def_id)
2937 item.and_then(|trait_item| match trait_item.container {
2938 TraitContainer(_) => None,
2939 ImplContainer(def_id) => Some(def_id),
2943 /// Looks up the span of `impl_did` if the impl is local; otherwise returns `Err`
2944 /// with the name of the crate containing the impl.
2945 pub fn span_of_impl(self, impl_did: DefId) -> Result<Span, Symbol> {
2946 if impl_did.is_local() {
2947 let hir_id = self.hir().as_local_hir_id(impl_did).unwrap();
2948 Ok(self.hir().span(hir_id))
2950 Err(self.crate_name(impl_did.krate))
2954 /// Hygienically compares a use-site name (`use_name`) for a field or an associated item with
2955 /// its supposed definition name (`def_name`). The method also needs `DefId` of the supposed
2956 /// definition's parent/scope to perform comparison.
2957 pub fn hygienic_eq(self, use_name: Ident, def_name: Ident, def_parent_def_id: DefId) -> bool {
2958 // We could use `Ident::eq` here, but we deliberately don't. The name
2959 // comparison fails frequently, and we want to avoid the expensive
2960 // `modern()` calls required for the span comparison whenever possible.
2961 use_name.name == def_name.name
2965 .hygienic_eq(def_name.span.ctxt(), self.expansion_that_defined(def_parent_def_id))
2968 fn expansion_that_defined(self, scope: DefId) -> ExpnId {
2970 LOCAL_CRATE => self.hir().definitions().expansion_that_defined(scope.index),
2971 _ => ExpnId::root(),
2975 pub fn adjust_ident(self, mut ident: Ident, scope: DefId) -> Ident {
2976 ident.span.modernize_and_adjust(self.expansion_that_defined(scope));
2980 pub fn adjust_ident_and_get_scope(
2985 ) -> (Ident, DefId) {
2986 let scope = match ident.span.modernize_and_adjust(self.expansion_that_defined(scope)) {
2987 Some(actual_expansion) => {
2988 self.hir().definitions().parent_module_of_macro_def(actual_expansion)
2990 None => self.hir().get_module_parent(block),
2997 pub struct AssocItemsIterator<'tcx> {
2999 def_ids: &'tcx [DefId],
3003 impl Iterator for AssocItemsIterator<'_> {
3004 type Item = AssocItem;
3006 fn next(&mut self) -> Option<AssocItem> {
3007 let def_id = self.def_ids.get(self.next_index)?;
3008 self.next_index += 1;
3009 Some(self.tcx.associated_item(*def_id))
3013 #[derive(Clone, HashStable)]
3014 pub struct AdtSizedConstraint<'tcx>(pub &'tcx [Ty<'tcx>]);
3016 /// Yields the parent function's `DefId` if `def_id` is an `impl Trait` definition.
3017 pub fn is_impl_trait_defn(tcx: TyCtxt<'_>, def_id: DefId) -> Option<DefId> {
3018 if let Some(hir_id) = tcx.hir().as_local_hir_id(def_id) {
3019 if let Node::Item(item) = tcx.hir().get(hir_id) {
3020 if let hir::ItemKind::OpaqueTy(ref opaque_ty) = item.kind {
3021 return opaque_ty.impl_trait_fn;
3028 pub fn provide(providers: &mut ty::query::Providers<'_>) {
3029 context::provide(providers);
3030 erase_regions::provide(providers);
3031 layout::provide(providers);
3033 ty::query::Providers { trait_impls_of: trait_def::trait_impls_of_provider, ..*providers };
3036 /// A map for the local crate mapping each type to a vector of its
3037 /// inherent impls. This is not meant to be used outside of coherence;
3038 /// rather, you should request the vector for a specific type via
3039 /// `tcx.inherent_impls(def_id)` so as to minimize your dependencies
3040 /// (constructing this map requires touching the entire crate).
3041 #[derive(Clone, Debug, Default, HashStable)]
3042 pub struct CrateInherentImpls {
3043 pub inherent_impls: DefIdMap<Vec<DefId>>,
3046 #[derive(Clone, Copy, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
3047 pub struct SymbolName {
3048 // FIXME: we don't rely on interning or equality here - better have
3049 // this be a `&'tcx str`.
3054 pub fn new(name: &str) -> SymbolName {
3055 SymbolName { name: Symbol::intern(name) }
3059 impl PartialOrd for SymbolName {
3060 fn partial_cmp(&self, other: &SymbolName) -> Option<Ordering> {
3061 self.name.as_str().partial_cmp(&other.name.as_str())
3065 /// Ordering must use the chars to ensure reproducible builds.
3066 impl Ord for SymbolName {
3067 fn cmp(&self, other: &SymbolName) -> Ordering {
3068 self.name.as_str().cmp(&other.name.as_str())
3072 impl fmt::Display for SymbolName {
3073 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
3074 fmt::Display::fmt(&self.name, fmt)
3078 impl fmt::Debug for SymbolName {
3079 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
3080 fmt::Display::fmt(&self.name, fmt)