1 pub use self::Variance::*;
2 pub use self::AssociatedItemContainer::*;
3 pub use self::BorrowKind::*;
4 pub use self::IntVarValue::*;
5 pub use self::fold::TypeFoldable;
7 use crate::hir::{map as hir_map, FreevarMap, GlobMap, TraitMap};
9 use crate::hir::def::{Def, CtorKind, ExportMap};
10 use crate::hir::def_id::{CrateNum, DefId, LocalDefId, CRATE_DEF_INDEX, LOCAL_CRATE};
11 use crate::hir::map::DefPathData;
12 use rustc_data_structures::svh::Svh;
13 use crate::ich::Fingerprint;
14 use crate::ich::StableHashingContext;
15 use crate::infer::canonical::Canonical;
16 use crate::middle::lang_items::{FnTraitLangItem, FnMutTraitLangItem, FnOnceTraitLangItem};
17 use crate::middle::resolve_lifetime::ObjectLifetimeDefault;
19 use crate::mir::interpret::{GlobalId, ErrorHandled};
20 use crate::mir::GeneratorLayout;
21 use crate::session::CrateDisambiguator;
22 use crate::traits::{self, Reveal};
24 use crate::ty::layout::VariantIdx;
25 use crate::ty::subst::{Subst, InternalSubsts, SubstsRef};
26 use crate::ty::util::{IntTypeExt, Discr};
27 use crate::ty::walk::TypeWalker;
28 use crate::util::captures::Captures;
29 use crate::util::nodemap::{NodeSet, DefIdMap, FxHashMap};
30 use arena::SyncDroplessArena;
31 use crate::session::DataTypeKind;
33 use serialize::{self, Encodable, Encoder};
34 use std::cell::RefCell;
35 use std::cmp::{self, Ordering};
37 use std::hash::{Hash, Hasher};
39 use rustc_data_structures::sync::{self, Lrc, ParallelIterator, par_iter};
42 use syntax::ast::{self, Name, Ident, NodeId};
44 use syntax::ext::hygiene::Mark;
45 use syntax::symbol::{keywords, Symbol, LocalInternedString, InternedString};
49 use rustc_data_structures::indexed_vec::{Idx, IndexVec};
50 use rustc_data_structures::stable_hasher::{StableHasher, StableHasherResult,
55 pub use self::sty::{Binder, BoundTy, BoundTyKind, BoundVar, DebruijnIndex, INNERMOST};
56 pub use self::sty::{FnSig, GenSig, CanonicalPolyFnSig, PolyFnSig, PolyGenSig};
57 pub use self::sty::{InferTy, ParamTy, ProjectionTy, ExistentialPredicate};
58 pub use self::sty::{ClosureSubsts, GeneratorSubsts, UpvarSubsts, TypeAndMut};
59 pub use self::sty::{TraitRef, TyKind, PolyTraitRef};
60 pub use self::sty::{ExistentialTraitRef, PolyExistentialTraitRef};
61 pub use self::sty::{ExistentialProjection, PolyExistentialProjection, Const, LazyConst};
62 pub use self::sty::{BoundRegion, EarlyBoundRegion, FreeRegion, Region};
63 pub use self::sty::RegionKind;
64 pub use self::sty::{TyVid, IntVid, FloatVid, RegionVid};
65 pub use self::sty::BoundRegion::*;
66 pub use self::sty::InferTy::*;
67 pub use self::sty::RegionKind::*;
68 pub use self::sty::TyKind::*;
70 pub use self::binding::BindingMode;
71 pub use self::binding::BindingMode::*;
73 pub use self::context::{TyCtxt, FreeRegionInfo, GlobalArenas, AllArenas, tls, keep_local};
74 pub use self::context::{Lift, TypeckTables, CtxtInterners};
75 pub use self::context::{
76 UserTypeAnnotationIndex, UserType, CanonicalUserType,
77 CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations, ResolvedOpaqueTy,
80 pub use self::instance::{Instance, InstanceDef};
82 pub use self::trait_def::TraitDef;
84 pub use self::query::queries;
96 pub mod inhabitedness;
113 mod structural_impls;
119 pub struct Resolutions {
120 pub freevars: FreevarMap,
121 pub trait_map: TraitMap,
122 pub maybe_unused_trait_imports: NodeSet,
123 pub maybe_unused_extern_crates: Vec<(NodeId, Span)>,
124 pub export_map: ExportMap,
125 pub glob_map: GlobMap,
126 /// Extern prelude entries. The value is `true` if the entry was introduced
127 /// via `extern crate` item and not `--extern` option or compiler built-in.
128 pub extern_prelude: FxHashMap<Name, bool>,
131 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
132 pub enum AssociatedItemContainer {
133 TraitContainer(DefId),
134 ImplContainer(DefId),
137 impl AssociatedItemContainer {
138 /// Asserts that this is the `DefId` of an associated item declared
139 /// in a trait, and returns the trait `DefId`.
140 pub fn assert_trait(&self) -> DefId {
142 TraitContainer(id) => id,
143 _ => bug!("associated item has wrong container type: {:?}", self)
147 pub fn id(&self) -> DefId {
149 TraitContainer(id) => id,
150 ImplContainer(id) => id,
155 /// The "header" of an impl is everything outside the body: a Self type, a trait
156 /// ref (in the case of a trait impl), and a set of predicates (from the
157 /// bounds / where-clauses).
158 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
159 pub struct ImplHeader<'tcx> {
160 pub impl_def_id: DefId,
161 pub self_ty: Ty<'tcx>,
162 pub trait_ref: Option<TraitRef<'tcx>>,
163 pub predicates: Vec<Predicate<'tcx>>,
166 #[derive(Copy, Clone, Debug, PartialEq)]
167 pub struct AssociatedItem {
170 pub kind: AssociatedKind,
172 pub defaultness: hir::Defaultness,
173 pub container: AssociatedItemContainer,
175 /// Whether this is a method with an explicit self
176 /// as its first argument, allowing method calls.
177 pub method_has_self_argument: bool,
180 #[derive(Copy, Clone, PartialEq, Eq, Debug, Hash, RustcEncodable, RustcDecodable)]
181 pub enum AssociatedKind {
188 impl AssociatedItem {
189 pub fn def(&self) -> Def {
191 AssociatedKind::Const => Def::AssociatedConst(self.def_id),
192 AssociatedKind::Method => Def::Method(self.def_id),
193 AssociatedKind::Type => Def::AssociatedTy(self.def_id),
194 AssociatedKind::Existential => Def::AssociatedExistential(self.def_id),
198 /// Tests whether the associated item admits a non-trivial implementation
200 pub fn relevant_for_never<'tcx>(&self) -> bool {
202 AssociatedKind::Existential |
203 AssociatedKind::Const |
204 AssociatedKind::Type => true,
205 // FIXME(canndrew): Be more thorough here, check if any argument is uninhabited.
206 AssociatedKind::Method => !self.method_has_self_argument,
210 pub fn signature<'a, 'tcx>(&self, tcx: &TyCtxt<'a, 'tcx, 'tcx>) -> String {
212 ty::AssociatedKind::Method => {
213 // We skip the binder here because the binder would deanonymize all
214 // late-bound regions, and we don't want method signatures to show up
215 // `as for<'r> fn(&'r MyType)`. Pretty-printing handles late-bound
216 // regions just fine, showing `fn(&MyType)`.
217 tcx.fn_sig(self.def_id).skip_binder().to_string()
219 ty::AssociatedKind::Type => format!("type {};", self.ident),
220 ty::AssociatedKind::Existential => format!("existential type {};", self.ident),
221 ty::AssociatedKind::Const => {
222 format!("const {}: {:?};", self.ident, tcx.type_of(self.def_id))
228 #[derive(Clone, Debug, PartialEq, Eq, Copy, RustcEncodable, RustcDecodable)]
229 pub enum Visibility {
230 /// Visible everywhere (including in other crates).
232 /// Visible only in the given crate-local module.
234 /// Not visible anywhere in the local crate. This is the visibility of private external items.
238 pub trait DefIdTree: Copy {
239 fn parent(self, id: DefId) -> Option<DefId>;
241 fn is_descendant_of(self, mut descendant: DefId, ancestor: DefId) -> bool {
242 if descendant.krate != ancestor.krate {
246 while descendant != ancestor {
247 match self.parent(descendant) {
248 Some(parent) => descendant = parent,
249 None => return false,
256 impl<'a, 'gcx, 'tcx> DefIdTree for TyCtxt<'a, 'gcx, 'tcx> {
257 fn parent(self, id: DefId) -> Option<DefId> {
258 self.def_key(id).parent.map(|index| DefId { index: index, ..id })
263 pub fn from_hir(visibility: &hir::Visibility, id: NodeId, tcx: TyCtxt<'_, '_, '_>) -> Self {
264 match visibility.node {
265 hir::VisibilityKind::Public => Visibility::Public,
266 hir::VisibilityKind::Crate(_) => Visibility::Restricted(DefId::local(CRATE_DEF_INDEX)),
267 hir::VisibilityKind::Restricted { ref path, .. } => match path.def {
268 // If there is no resolution, `resolve` will have already reported an error, so
269 // assume that the visibility is public to avoid reporting more privacy errors.
270 Def::Err => Visibility::Public,
271 def => Visibility::Restricted(def.def_id()),
273 hir::VisibilityKind::Inherited => {
274 Visibility::Restricted(tcx.hir().get_module_parent(id))
279 /// Returns `true` if an item with this visibility is accessible from the given block.
280 pub fn is_accessible_from<T: DefIdTree>(self, module: DefId, tree: T) -> bool {
281 let restriction = match self {
282 // Public items are visible everywhere.
283 Visibility::Public => return true,
284 // Private items from other crates are visible nowhere.
285 Visibility::Invisible => return false,
286 // Restricted items are visible in an arbitrary local module.
287 Visibility::Restricted(other) if other.krate != module.krate => return false,
288 Visibility::Restricted(module) => module,
291 tree.is_descendant_of(module, restriction)
294 /// Returns `true` if this visibility is at least as accessible as the given visibility
295 pub fn is_at_least<T: DefIdTree>(self, vis: Visibility, tree: T) -> bool {
296 let vis_restriction = match vis {
297 Visibility::Public => return self == Visibility::Public,
298 Visibility::Invisible => return true,
299 Visibility::Restricted(module) => module,
302 self.is_accessible_from(vis_restriction, tree)
305 // Returns `true` if this item is visible anywhere in the local crate.
306 pub fn is_visible_locally(self) -> bool {
308 Visibility::Public => true,
309 Visibility::Restricted(def_id) => def_id.is_local(),
310 Visibility::Invisible => false,
315 #[derive(Copy, Clone, PartialEq, Eq, RustcDecodable, RustcEncodable, Hash)]
317 Covariant, // T<A> <: T<B> iff A <: B -- e.g., function return type
318 Invariant, // T<A> <: T<B> iff B == A -- e.g., type of mutable cell
319 Contravariant, // T<A> <: T<B> iff B <: A -- e.g., function param type
320 Bivariant, // T<A> <: T<B> -- e.g., unused type parameter
323 /// The crate variances map is computed during typeck and contains the
324 /// variance of every item in the local crate. You should not use it
325 /// directly, because to do so will make your pass dependent on the
326 /// HIR of every item in the local crate. Instead, use
327 /// `tcx.variances_of()` to get the variance for a *particular*
329 pub struct CrateVariancesMap {
330 /// For each item with generics, maps to a vector of the variance
331 /// of its generics. If an item has no generics, it will have no
333 pub variances: FxHashMap<DefId, Lrc<Vec<ty::Variance>>>,
335 /// An empty vector, useful for cloning.
336 pub empty_variance: Lrc<Vec<ty::Variance>>,
340 /// `a.xform(b)` combines the variance of a context with the
341 /// variance of a type with the following meaning. If we are in a
342 /// context with variance `a`, and we encounter a type argument in
343 /// a position with variance `b`, then `a.xform(b)` is the new
344 /// variance with which the argument appears.
350 /// Here, the "ambient" variance starts as covariant. `*mut T` is
351 /// invariant with respect to `T`, so the variance in which the
352 /// `Vec<i32>` appears is `Covariant.xform(Invariant)`, which
353 /// yields `Invariant`. Now, the type `Vec<T>` is covariant with
354 /// respect to its type argument `T`, and hence the variance of
355 /// the `i32` here is `Invariant.xform(Covariant)`, which results
356 /// (again) in `Invariant`.
360 /// fn(*const Vec<i32>, *mut Vec<i32)
362 /// The ambient variance is covariant. A `fn` type is
363 /// contravariant with respect to its parameters, so the variance
364 /// within which both pointer types appear is
365 /// `Covariant.xform(Contravariant)`, or `Contravariant`. `*const
366 /// T` is covariant with respect to `T`, so the variance within
367 /// which the first `Vec<i32>` appears is
368 /// `Contravariant.xform(Covariant)` or `Contravariant`. The same
369 /// is true for its `i32` argument. In the `*mut T` case, the
370 /// variance of `Vec<i32>` is `Contravariant.xform(Invariant)`,
371 /// and hence the outermost type is `Invariant` with respect to
372 /// `Vec<i32>` (and its `i32` argument).
374 /// Source: Figure 1 of "Taming the Wildcards:
375 /// Combining Definition- and Use-Site Variance" published in PLDI'11.
376 pub fn xform(self, v: ty::Variance) -> ty::Variance {
378 // Figure 1, column 1.
379 (ty::Covariant, ty::Covariant) => ty::Covariant,
380 (ty::Covariant, ty::Contravariant) => ty::Contravariant,
381 (ty::Covariant, ty::Invariant) => ty::Invariant,
382 (ty::Covariant, ty::Bivariant) => ty::Bivariant,
384 // Figure 1, column 2.
385 (ty::Contravariant, ty::Covariant) => ty::Contravariant,
386 (ty::Contravariant, ty::Contravariant) => ty::Covariant,
387 (ty::Contravariant, ty::Invariant) => ty::Invariant,
388 (ty::Contravariant, ty::Bivariant) => ty::Bivariant,
390 // Figure 1, column 3.
391 (ty::Invariant, _) => ty::Invariant,
393 // Figure 1, column 4.
394 (ty::Bivariant, _) => ty::Bivariant,
399 // Contains information needed to resolve types and (in the future) look up
400 // the types of AST nodes.
401 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
402 pub struct CReaderCacheKey {
407 // Flags that we track on types. These flags are propagated upwards
408 // through the type during type construction, so that we can quickly
409 // check whether the type has various kinds of types in it without
410 // recursing over the type itself.
412 pub struct TypeFlags: u32 {
413 const HAS_PARAMS = 1 << 0;
414 const HAS_SELF = 1 << 1;
415 const HAS_TY_INFER = 1 << 2;
416 const HAS_RE_INFER = 1 << 3;
417 const HAS_RE_PLACEHOLDER = 1 << 4;
419 /// Does this have any `ReEarlyBound` regions? Used to
420 /// determine whether substitition is required, since those
421 /// represent regions that are bound in a `ty::Generics` and
422 /// hence may be substituted.
423 const HAS_RE_EARLY_BOUND = 1 << 5;
425 /// Does this have any region that "appears free" in the type?
426 /// Basically anything but `ReLateBound` and `ReErased`.
427 const HAS_FREE_REGIONS = 1 << 6;
429 /// Is an error type reachable?
430 const HAS_TY_ERR = 1 << 7;
431 const HAS_PROJECTION = 1 << 8;
433 // FIXME: Rename this to the actual property since it's used for generators too
434 const HAS_TY_CLOSURE = 1 << 9;
436 // `true` if there are "names" of types and regions and so forth
437 // that are local to a particular fn
438 const HAS_FREE_LOCAL_NAMES = 1 << 10;
440 // Present if the type belongs in a local type context.
441 // Only set for Infer other than Fresh.
442 const KEEP_IN_LOCAL_TCX = 1 << 11;
444 // Is there a projection that does not involve a bound region?
445 // Currently we can't normalize projections w/ bound regions.
446 const HAS_NORMALIZABLE_PROJECTION = 1 << 12;
448 /// Does this have any `ReLateBound` regions? Used to check
449 /// if a global bound is safe to evaluate.
450 const HAS_RE_LATE_BOUND = 1 << 13;
452 const HAS_TY_PLACEHOLDER = 1 << 14;
454 const NEEDS_SUBST = TypeFlags::HAS_PARAMS.bits |
455 TypeFlags::HAS_SELF.bits |
456 TypeFlags::HAS_RE_EARLY_BOUND.bits;
458 // Flags representing the nominal content of a type,
459 // computed by FlagsComputation. If you add a new nominal
460 // flag, it should be added here too.
461 const NOMINAL_FLAGS = TypeFlags::HAS_PARAMS.bits |
462 TypeFlags::HAS_SELF.bits |
463 TypeFlags::HAS_TY_INFER.bits |
464 TypeFlags::HAS_RE_INFER.bits |
465 TypeFlags::HAS_RE_PLACEHOLDER.bits |
466 TypeFlags::HAS_RE_EARLY_BOUND.bits |
467 TypeFlags::HAS_FREE_REGIONS.bits |
468 TypeFlags::HAS_TY_ERR.bits |
469 TypeFlags::HAS_PROJECTION.bits |
470 TypeFlags::HAS_TY_CLOSURE.bits |
471 TypeFlags::HAS_FREE_LOCAL_NAMES.bits |
472 TypeFlags::KEEP_IN_LOCAL_TCX.bits |
473 TypeFlags::HAS_RE_LATE_BOUND.bits |
474 TypeFlags::HAS_TY_PLACEHOLDER.bits;
478 pub struct TyS<'tcx> {
479 pub sty: TyKind<'tcx>,
480 pub flags: TypeFlags,
482 /// This is a kind of confusing thing: it stores the smallest
485 /// (a) the binder itself captures nothing but
486 /// (b) all the late-bound things within the type are captured
487 /// by some sub-binder.
489 /// So, for a type without any late-bound things, like `u32`, this
490 /// will be *innermost*, because that is the innermost binder that
491 /// captures nothing. But for a type `&'D u32`, where `'D` is a
492 /// late-bound region with De Bruijn index `D`, this would be `D + 1`
493 /// -- the binder itself does not capture `D`, but `D` is captured
494 /// by an inner binder.
496 /// We call this concept an "exclusive" binder `D` because all
497 /// De Bruijn indices within the type are contained within `0..D`
499 outer_exclusive_binder: ty::DebruijnIndex,
502 // `TyS` is used a lot. Make sure it doesn't unintentionally get bigger.
503 #[cfg(target_arch = "x86_64")]
504 static_assert!(MEM_SIZE_OF_TY_S: ::std::mem::size_of::<TyS<'_>>() == 32);
506 impl<'tcx> Ord for TyS<'tcx> {
507 fn cmp(&self, other: &TyS<'tcx>) -> Ordering {
508 self.sty.cmp(&other.sty)
512 impl<'tcx> PartialOrd for TyS<'tcx> {
513 fn partial_cmp(&self, other: &TyS<'tcx>) -> Option<Ordering> {
514 Some(self.sty.cmp(&other.sty))
518 impl<'tcx> PartialEq for TyS<'tcx> {
520 fn eq(&self, other: &TyS<'tcx>) -> bool {
524 impl<'tcx> Eq for TyS<'tcx> {}
526 impl<'tcx> Hash for TyS<'tcx> {
527 fn hash<H: Hasher>(&self, s: &mut H) {
528 (self as *const TyS<'_>).hash(s)
532 impl<'tcx> TyS<'tcx> {
533 pub fn is_primitive_ty(&self) -> bool {
540 TyKind::Infer(InferTy::IntVar(_)) |
541 TyKind::Infer(InferTy::FloatVar(_)) |
542 TyKind::Infer(InferTy::FreshIntTy(_)) |
543 TyKind::Infer(InferTy::FreshFloatTy(_)) => true,
544 TyKind::Ref(_, x, _) => x.is_primitive_ty(),
549 pub fn is_suggestable(&self) -> bool {
554 TyKind::Dynamic(..) |
555 TyKind::Closure(..) |
557 TyKind::Projection(..) => false,
563 impl<'a, 'gcx> HashStable<StableHashingContext<'a>> for ty::TyS<'gcx> {
564 fn hash_stable<W: StableHasherResult>(&self,
565 hcx: &mut StableHashingContext<'a>,
566 hasher: &mut StableHasher<W>) {
570 // The other fields just provide fast access to information that is
571 // also contained in `sty`, so no need to hash them.
574 outer_exclusive_binder: _,
577 sty.hash_stable(hcx, hasher);
581 pub type Ty<'tcx> = &'tcx TyS<'tcx>;
583 impl<'tcx> serialize::UseSpecializedEncodable for Ty<'tcx> {}
584 impl<'tcx> serialize::UseSpecializedDecodable for Ty<'tcx> {}
586 pub type CanonicalTy<'gcx> = Canonical<'gcx, Ty<'gcx>>;
589 /// A dummy type used to force List to by unsized without requiring fat pointers
590 type OpaqueListContents;
593 /// A wrapper for slices with the additional invariant
594 /// that the slice is interned and no other slice with
595 /// the same contents can exist in the same context.
596 /// This means we can use pointer for both
597 /// equality comparisons and hashing.
598 /// Note: `Slice` was already taken by the `Ty`.
603 opaque: OpaqueListContents,
606 unsafe impl<T: Sync> Sync for List<T> {}
608 impl<T: Copy> List<T> {
610 fn from_arena<'tcx>(arena: &'tcx SyncDroplessArena, slice: &[T]) -> &'tcx List<T> {
611 assert!(!mem::needs_drop::<T>());
612 assert!(mem::size_of::<T>() != 0);
613 assert!(slice.len() != 0);
615 // Align up the size of the len (usize) field
616 let align = mem::align_of::<T>();
617 let align_mask = align - 1;
618 let offset = mem::size_of::<usize>();
619 let offset = (offset + align_mask) & !align_mask;
621 let size = offset + slice.len() * mem::size_of::<T>();
623 let mem = arena.alloc_raw(
625 cmp::max(mem::align_of::<T>(), mem::align_of::<usize>()));
627 let result = &mut *(mem.as_mut_ptr() as *mut List<T>);
629 result.len = slice.len();
631 // Write the elements
632 let arena_slice = slice::from_raw_parts_mut(result.data.as_mut_ptr(), result.len);
633 arena_slice.copy_from_slice(slice);
640 impl<T: fmt::Debug> fmt::Debug for List<T> {
641 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
646 impl<T: Encodable> Encodable for List<T> {
648 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
653 impl<T> Ord for List<T> where T: Ord {
654 fn cmp(&self, other: &List<T>) -> Ordering {
655 if self == other { Ordering::Equal } else {
656 <[T] as Ord>::cmp(&**self, &**other)
661 impl<T> PartialOrd for List<T> where T: PartialOrd {
662 fn partial_cmp(&self, other: &List<T>) -> Option<Ordering> {
663 if self == other { Some(Ordering::Equal) } else {
664 <[T] as PartialOrd>::partial_cmp(&**self, &**other)
669 impl<T: PartialEq> PartialEq for List<T> {
671 fn eq(&self, other: &List<T>) -> bool {
675 impl<T: Eq> Eq for List<T> {}
677 impl<T> Hash for List<T> {
679 fn hash<H: Hasher>(&self, s: &mut H) {
680 (self as *const List<T>).hash(s)
684 impl<T> Deref for List<T> {
687 fn deref(&self) -> &[T] {
689 slice::from_raw_parts(self.data.as_ptr(), self.len)
694 impl<'a, T> IntoIterator for &'a List<T> {
696 type IntoIter = <&'a [T] as IntoIterator>::IntoIter;
698 fn into_iter(self) -> Self::IntoIter {
703 impl<'tcx> serialize::UseSpecializedDecodable for &'tcx List<Ty<'tcx>> {}
707 pub fn empty<'a>() -> &'a List<T> {
708 #[repr(align(64), C)]
709 struct EmptySlice([u8; 64]);
710 static EMPTY_SLICE: EmptySlice = EmptySlice([0; 64]);
711 assert!(mem::align_of::<T>() <= 64);
713 &*(&EMPTY_SLICE as *const _ as *const List<T>)
718 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
719 pub struct UpvarPath {
720 pub hir_id: hir::HirId,
723 /// Upvars do not get their own `NodeId`. Instead, we use the pair of
724 /// the original var ID (that is, the root variable that is referenced
725 /// by the upvar) and the ID of the closure expression.
726 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
728 pub var_path: UpvarPath,
729 pub closure_expr_id: LocalDefId,
732 #[derive(Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable, Copy)]
733 pub enum BorrowKind {
734 /// Data must be immutable and is aliasable.
737 /// Data must be immutable but not aliasable. This kind of borrow
738 /// cannot currently be expressed by the user and is used only in
739 /// implicit closure bindings. It is needed when the closure
740 /// is borrowing or mutating a mutable referent, e.g.:
742 /// let x: &mut isize = ...;
743 /// let y = || *x += 5;
745 /// If we were to try to translate this closure into a more explicit
746 /// form, we'd encounter an error with the code as written:
748 /// struct Env { x: & &mut isize }
749 /// let x: &mut isize = ...;
750 /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
751 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
753 /// This is then illegal because you cannot mutate a `&mut` found
754 /// in an aliasable location. To solve, you'd have to translate with
755 /// an `&mut` borrow:
757 /// struct Env { x: & &mut isize }
758 /// let x: &mut isize = ...;
759 /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
760 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
762 /// Now the assignment to `**env.x` is legal, but creating a
763 /// mutable pointer to `x` is not because `x` is not mutable. We
764 /// could fix this by declaring `x` as `let mut x`. This is ok in
765 /// user code, if awkward, but extra weird for closures, since the
766 /// borrow is hidden.
768 /// So we introduce a "unique imm" borrow -- the referent is
769 /// immutable, but not aliasable. This solves the problem. For
770 /// simplicity, we don't give users the way to express this
771 /// borrow, it's just used when translating closures.
774 /// Data is mutable and not aliasable.
778 /// Information describing the capture of an upvar. This is computed
779 /// during `typeck`, specifically by `regionck`.
780 #[derive(PartialEq, Clone, Debug, Copy, RustcEncodable, RustcDecodable)]
781 pub enum UpvarCapture<'tcx> {
782 /// Upvar is captured by value. This is always true when the
783 /// closure is labeled `move`, but can also be true in other cases
784 /// depending on inference.
787 /// Upvar is captured by reference.
788 ByRef(UpvarBorrow<'tcx>),
791 #[derive(PartialEq, Clone, Copy, RustcEncodable, RustcDecodable)]
792 pub struct UpvarBorrow<'tcx> {
793 /// The kind of borrow: by-ref upvars have access to shared
794 /// immutable borrows, which are not part of the normal language
796 pub kind: BorrowKind,
798 /// Region of the resulting reference.
799 pub region: ty::Region<'tcx>,
802 pub type UpvarListMap = FxHashMap<DefId, Vec<UpvarId>>;
803 pub type UpvarCaptureMap<'tcx> = FxHashMap<UpvarId, UpvarCapture<'tcx>>;
805 #[derive(Copy, Clone)]
806 pub struct ClosureUpvar<'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 != keywords::UnderscoreLifetime.name().as_interned_str()
833 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
834 pub enum GenericParamDefKind {
838 object_lifetime_default: ObjectLifetimeDefault,
839 synthetic: Option<hir::SyntheticTyParamKind>,
843 #[derive(Clone, RustcEncodable, RustcDecodable)]
844 pub struct GenericParamDef {
845 pub name: InternedString,
849 /// `pure_wrt_drop`, set by the (unsafe) `#[may_dangle]` attribute
850 /// on generic parameter `'a`/`T`, asserts data behind the parameter
851 /// `'a`/`T` won't be accessed during the parent type's `Drop` impl.
852 pub pure_wrt_drop: bool,
854 pub kind: GenericParamDefKind,
857 impl GenericParamDef {
858 pub fn to_early_bound_region_data(&self) -> ty::EarlyBoundRegion {
859 if let GenericParamDefKind::Lifetime = self.kind {
860 ty::EarlyBoundRegion {
866 bug!("cannot convert a non-lifetime parameter def to an early bound region")
870 pub fn to_bound_region(&self) -> ty::BoundRegion {
871 if let GenericParamDefKind::Lifetime = self.kind {
872 self.to_early_bound_region_data().to_bound_region()
874 bug!("cannot convert a non-lifetime parameter def to an early bound region")
880 pub struct GenericParamCount {
881 pub lifetimes: usize,
885 /// Information about the formal type/lifetime parameters associated
886 /// with an item or method. Analogous to `hir::Generics`.
888 /// The ordering of parameters is the same as in `Subst` (excluding child generics):
889 /// `Self` (optionally), `Lifetime` params..., `Type` params...
890 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
891 pub struct Generics {
892 pub parent: Option<DefId>,
893 pub parent_count: usize,
894 pub params: Vec<GenericParamDef>,
896 /// Reverse map to the `index` field of each `GenericParamDef`
897 pub param_def_id_to_index: FxHashMap<DefId, u32>,
900 pub has_late_bound_regions: Option<Span>,
903 impl<'a, 'gcx, 'tcx> Generics {
904 pub fn count(&self) -> usize {
905 self.parent_count + self.params.len()
908 pub fn own_counts(&self) -> GenericParamCount {
909 // We could cache this as a property of `GenericParamCount`, but
910 // the aim is to refactor this away entirely eventually and the
911 // presence of this method will be a constant reminder.
912 let mut own_counts: GenericParamCount = Default::default();
914 for param in &self.params {
916 GenericParamDefKind::Lifetime => own_counts.lifetimes += 1,
917 GenericParamDefKind::Type { .. } => own_counts.types += 1,
924 pub fn requires_monomorphization(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> bool {
925 for param in &self.params {
927 GenericParamDefKind::Type { .. } => return true,
928 GenericParamDefKind::Lifetime => {}
931 if let Some(parent_def_id) = self.parent {
932 let parent = tcx.generics_of(parent_def_id);
933 parent.requires_monomorphization(tcx)
939 pub fn region_param(&'tcx self,
940 param: &EarlyBoundRegion,
941 tcx: TyCtxt<'a, 'gcx, 'tcx>)
942 -> &'tcx GenericParamDef
944 if let Some(index) = param.index.checked_sub(self.parent_count as u32) {
945 let param = &self.params[index as usize];
947 ty::GenericParamDefKind::Lifetime => param,
948 _ => bug!("expected lifetime parameter, but found another generic parameter")
951 tcx.generics_of(self.parent.expect("parent_count > 0 but no parent?"))
952 .region_param(param, tcx)
956 /// Returns the `GenericParamDef` associated with this `ParamTy`.
957 pub fn type_param(&'tcx self,
959 tcx: TyCtxt<'a, 'gcx, 'tcx>)
960 -> &'tcx GenericParamDef {
961 if let Some(index) = param.idx.checked_sub(self.parent_count as u32) {
962 let param = &self.params[index as usize];
964 ty::GenericParamDefKind::Type {..} => param,
965 _ => bug!("expected type parameter, but found another generic parameter")
968 tcx.generics_of(self.parent.expect("parent_count > 0 but no parent?"))
969 .type_param(param, tcx)
974 /// Bounds on generics.
975 #[derive(Clone, Default)]
976 pub struct GenericPredicates<'tcx> {
977 pub parent: Option<DefId>,
978 pub predicates: Vec<(Predicate<'tcx>, Span)>,
981 impl<'tcx> serialize::UseSpecializedEncodable for GenericPredicates<'tcx> {}
982 impl<'tcx> serialize::UseSpecializedDecodable for GenericPredicates<'tcx> {}
984 impl<'a, 'gcx, 'tcx> GenericPredicates<'tcx> {
985 pub fn instantiate(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, substs: SubstsRef<'tcx>)
986 -> InstantiatedPredicates<'tcx> {
987 let mut instantiated = InstantiatedPredicates::empty();
988 self.instantiate_into(tcx, &mut instantiated, substs);
992 pub fn instantiate_own(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, substs: SubstsRef<'tcx>)
993 -> InstantiatedPredicates<'tcx> {
994 InstantiatedPredicates {
995 predicates: self.predicates.iter().map(|(p, _)| p.subst(tcx, substs)).collect(),
999 fn instantiate_into(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
1000 instantiated: &mut InstantiatedPredicates<'tcx>,
1001 substs: SubstsRef<'tcx>) {
1002 if let Some(def_id) = self.parent {
1003 tcx.predicates_of(def_id).instantiate_into(tcx, instantiated, substs);
1005 instantiated.predicates.extend(
1006 self.predicates.iter().map(|(p, _)| p.subst(tcx, substs)),
1010 pub fn instantiate_identity(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>)
1011 -> InstantiatedPredicates<'tcx> {
1012 let mut instantiated = InstantiatedPredicates::empty();
1013 self.instantiate_identity_into(tcx, &mut instantiated);
1017 fn instantiate_identity_into(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
1018 instantiated: &mut InstantiatedPredicates<'tcx>) {
1019 if let Some(def_id) = self.parent {
1020 tcx.predicates_of(def_id).instantiate_identity_into(tcx, instantiated);
1022 instantiated.predicates.extend(self.predicates.iter().map(|&(p, _)| p))
1025 pub fn instantiate_supertrait(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
1026 poly_trait_ref: &ty::PolyTraitRef<'tcx>)
1027 -> InstantiatedPredicates<'tcx>
1029 assert_eq!(self.parent, None);
1030 InstantiatedPredicates {
1031 predicates: self.predicates.iter().map(|(pred, _)| {
1032 pred.subst_supertrait(tcx, poly_trait_ref)
1038 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1039 pub enum Predicate<'tcx> {
1040 /// Corresponds to `where Foo: Bar<A,B,C>`. `Foo` here would be
1041 /// the `Self` type of the trait reference and `A`, `B`, and `C`
1042 /// would be the type parameters.
1043 Trait(PolyTraitPredicate<'tcx>),
1046 RegionOutlives(PolyRegionOutlivesPredicate<'tcx>),
1049 TypeOutlives(PolyTypeOutlivesPredicate<'tcx>),
1051 /// where `<T as TraitRef>::Name == X`, approximately.
1052 /// See the `ProjectionPredicate` struct for details.
1053 Projection(PolyProjectionPredicate<'tcx>),
1055 /// no syntax: `T` well-formed
1056 WellFormed(Ty<'tcx>),
1058 /// trait must be object-safe
1061 /// No direct syntax. May be thought of as `where T: FnFoo<...>`
1062 /// for some substitutions `...` and `T` being a closure type.
1063 /// Satisfied (or refuted) once we know the closure's kind.
1064 ClosureKind(DefId, ClosureSubsts<'tcx>, ClosureKind),
1067 Subtype(PolySubtypePredicate<'tcx>),
1069 /// Constant initializer must evaluate successfully.
1070 ConstEvaluatable(DefId, SubstsRef<'tcx>),
1073 /// The crate outlives map is computed during typeck and contains the
1074 /// outlives of every item in the local crate. You should not use it
1075 /// directly, because to do so will make your pass dependent on the
1076 /// HIR of every item in the local crate. Instead, use
1077 /// `tcx.inferred_outlives_of()` to get the outlives for a *particular*
1079 pub struct CratePredicatesMap<'tcx> {
1080 /// For each struct with outlive bounds, maps to a vector of the
1081 /// predicate of its outlive bounds. If an item has no outlives
1082 /// bounds, it will have no entry.
1083 pub predicates: FxHashMap<DefId, Lrc<Vec<ty::Predicate<'tcx>>>>,
1085 /// An empty vector, useful for cloning.
1086 pub empty_predicate: Lrc<Vec<ty::Predicate<'tcx>>>,
1089 impl<'tcx> AsRef<Predicate<'tcx>> for Predicate<'tcx> {
1090 fn as_ref(&self) -> &Predicate<'tcx> {
1095 impl<'a, 'gcx, 'tcx> Predicate<'tcx> {
1096 /// Performs a substitution suitable for going from a
1097 /// poly-trait-ref to supertraits that must hold if that
1098 /// poly-trait-ref holds. This is slightly different from a normal
1099 /// substitution in terms of what happens with bound regions. See
1100 /// lengthy comment below for details.
1101 pub fn subst_supertrait(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
1102 trait_ref: &ty::PolyTraitRef<'tcx>)
1103 -> ty::Predicate<'tcx>
1105 // The interaction between HRTB and supertraits is not entirely
1106 // obvious. Let me walk you (and myself) through an example.
1108 // Let's start with an easy case. Consider two traits:
1110 // trait Foo<'a>: Bar<'a,'a> { }
1111 // trait Bar<'b,'c> { }
1113 // Now, if we have a trait reference `for<'x> T: Foo<'x>`, then
1114 // we can deduce that `for<'x> T: Bar<'x,'x>`. Basically, if we
1115 // knew that `Foo<'x>` (for any 'x) then we also know that
1116 // `Bar<'x,'x>` (for any 'x). This more-or-less falls out from
1117 // normal substitution.
1119 // In terms of why this is sound, the idea is that whenever there
1120 // is an impl of `T:Foo<'a>`, it must show that `T:Bar<'a,'a>`
1121 // holds. So if there is an impl of `T:Foo<'a>` that applies to
1122 // all `'a`, then we must know that `T:Bar<'a,'a>` holds for all
1125 // Another example to be careful of is this:
1127 // trait Foo1<'a>: for<'b> Bar1<'a,'b> { }
1128 // trait Bar1<'b,'c> { }
1130 // Here, if we have `for<'x> T: Foo1<'x>`, then what do we know?
1131 // The answer is that we know `for<'x,'b> T: Bar1<'x,'b>`. The
1132 // reason is similar to the previous example: any impl of
1133 // `T:Foo1<'x>` must show that `for<'b> T: Bar1<'x, 'b>`. So
1134 // basically we would want to collapse the bound lifetimes from
1135 // the input (`trait_ref`) and the supertraits.
1137 // To achieve this in practice is fairly straightforward. Let's
1138 // consider the more complicated scenario:
1140 // - We start out with `for<'x> T: Foo1<'x>`. In this case, `'x`
1141 // has a De Bruijn index of 1. We want to produce `for<'x,'b> T: Bar1<'x,'b>`,
1142 // where both `'x` and `'b` would have a DB index of 1.
1143 // The substitution from the input trait-ref is therefore going to be
1144 // `'a => 'x` (where `'x` has a DB index of 1).
1145 // - The super-trait-ref is `for<'b> Bar1<'a,'b>`, where `'a` is an
1146 // early-bound parameter and `'b' is a late-bound parameter with a
1148 // - If we replace `'a` with `'x` from the input, it too will have
1149 // a DB index of 1, and thus we'll have `for<'x,'b> Bar1<'x,'b>`
1150 // just as we wanted.
1152 // There is only one catch. If we just apply the substitution `'a
1153 // => 'x` to `for<'b> Bar1<'a,'b>`, the substitution code will
1154 // adjust the DB index because we substituting into a binder (it
1155 // tries to be so smart...) resulting in `for<'x> for<'b>
1156 // Bar1<'x,'b>` (we have no syntax for this, so use your
1157 // imagination). Basically the 'x will have DB index of 2 and 'b
1158 // will have DB index of 1. Not quite what we want. So we apply
1159 // the substitution to the *contents* of the trait reference,
1160 // rather than the trait reference itself (put another way, the
1161 // substitution code expects equal binding levels in the values
1162 // from the substitution and the value being substituted into, and
1163 // this trick achieves that).
1165 let substs = &trait_ref.skip_binder().substs;
1167 Predicate::Trait(ref binder) =>
1168 Predicate::Trait(binder.map_bound(|data| data.subst(tcx, substs))),
1169 Predicate::Subtype(ref binder) =>
1170 Predicate::Subtype(binder.map_bound(|data| data.subst(tcx, substs))),
1171 Predicate::RegionOutlives(ref binder) =>
1172 Predicate::RegionOutlives(binder.map_bound(|data| data.subst(tcx, substs))),
1173 Predicate::TypeOutlives(ref binder) =>
1174 Predicate::TypeOutlives(binder.map_bound(|data| data.subst(tcx, substs))),
1175 Predicate::Projection(ref binder) =>
1176 Predicate::Projection(binder.map_bound(|data| data.subst(tcx, substs))),
1177 Predicate::WellFormed(data) =>
1178 Predicate::WellFormed(data.subst(tcx, substs)),
1179 Predicate::ObjectSafe(trait_def_id) =>
1180 Predicate::ObjectSafe(trait_def_id),
1181 Predicate::ClosureKind(closure_def_id, closure_substs, kind) =>
1182 Predicate::ClosureKind(closure_def_id, closure_substs.subst(tcx, substs), kind),
1183 Predicate::ConstEvaluatable(def_id, const_substs) =>
1184 Predicate::ConstEvaluatable(def_id, const_substs.subst(tcx, substs)),
1189 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1190 pub struct TraitPredicate<'tcx> {
1191 pub trait_ref: TraitRef<'tcx>
1194 pub type PolyTraitPredicate<'tcx> = ty::Binder<TraitPredicate<'tcx>>;
1196 impl<'tcx> TraitPredicate<'tcx> {
1197 pub fn def_id(&self) -> DefId {
1198 self.trait_ref.def_id
1201 pub fn input_types<'a>(&'a self) -> impl DoubleEndedIterator<Item=Ty<'tcx>> + 'a {
1202 self.trait_ref.input_types()
1205 pub fn self_ty(&self) -> Ty<'tcx> {
1206 self.trait_ref.self_ty()
1210 impl<'tcx> PolyTraitPredicate<'tcx> {
1211 pub fn def_id(&self) -> DefId {
1212 // ok to skip binder since trait def-id does not care about regions
1213 self.skip_binder().def_id()
1217 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, RustcEncodable, RustcDecodable)]
1218 pub struct OutlivesPredicate<A,B>(pub A, pub B); // `A: B`
1219 pub type PolyOutlivesPredicate<A,B> = ty::Binder<OutlivesPredicate<A,B>>;
1220 pub type RegionOutlivesPredicate<'tcx> = OutlivesPredicate<ty::Region<'tcx>,
1222 pub type TypeOutlivesPredicate<'tcx> = OutlivesPredicate<Ty<'tcx>,
1224 pub type PolyRegionOutlivesPredicate<'tcx> = ty::Binder<RegionOutlivesPredicate<'tcx>>;
1225 pub type PolyTypeOutlivesPredicate<'tcx> = ty::Binder<TypeOutlivesPredicate<'tcx>>;
1227 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
1228 pub struct SubtypePredicate<'tcx> {
1229 pub a_is_expected: bool,
1233 pub type PolySubtypePredicate<'tcx> = ty::Binder<SubtypePredicate<'tcx>>;
1235 /// This kind of predicate has no *direct* correspondent in the
1236 /// syntax, but it roughly corresponds to the syntactic forms:
1238 /// 1. `T: TraitRef<..., Item = Type>`
1239 /// 2. `<T as TraitRef<...>>::Item == Type` (NYI)
1241 /// In particular, form #1 is "desugared" to the combination of a
1242 /// normal trait predicate (`T: TraitRef<...>`) and one of these
1243 /// predicates. Form #2 is a broader form in that it also permits
1244 /// equality between arbitrary types. Processing an instance of
1245 /// Form #2 eventually yields one of these `ProjectionPredicate`
1246 /// instances to normalize the LHS.
1247 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1248 pub struct ProjectionPredicate<'tcx> {
1249 pub projection_ty: ProjectionTy<'tcx>,
1253 pub type PolyProjectionPredicate<'tcx> = Binder<ProjectionPredicate<'tcx>>;
1255 impl<'tcx> PolyProjectionPredicate<'tcx> {
1256 /// Returns the `DefId` of the associated item being projected.
1257 pub fn item_def_id(&self) -> DefId {
1258 self.skip_binder().projection_ty.item_def_id
1262 pub fn to_poly_trait_ref(&self, tcx: TyCtxt<'_, '_, '_>) -> PolyTraitRef<'tcx> {
1263 // Note: unlike with `TraitRef::to_poly_trait_ref()`,
1264 // `self.0.trait_ref` is permitted to have escaping regions.
1265 // This is because here `self` has a `Binder` and so does our
1266 // return value, so we are preserving the number of binding
1268 self.map_bound(|predicate| predicate.projection_ty.trait_ref(tcx))
1271 pub fn ty(&self) -> Binder<Ty<'tcx>> {
1272 self.map_bound(|predicate| predicate.ty)
1275 /// The `DefId` of the `TraitItem` for the associated type.
1277 /// Note that this is not the `DefId` of the `TraitRef` containing this
1278 /// associated type, which is in `tcx.associated_item(projection_def_id()).container`.
1279 pub fn projection_def_id(&self) -> DefId {
1280 // okay to skip binder since trait def-id does not care about regions
1281 self.skip_binder().projection_ty.item_def_id
1285 pub trait ToPolyTraitRef<'tcx> {
1286 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx>;
1289 impl<'tcx> ToPolyTraitRef<'tcx> for TraitRef<'tcx> {
1290 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
1291 ty::Binder::dummy(self.clone())
1295 impl<'tcx> ToPolyTraitRef<'tcx> for PolyTraitPredicate<'tcx> {
1296 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
1297 self.map_bound_ref(|trait_pred| trait_pred.trait_ref)
1301 pub trait ToPredicate<'tcx> {
1302 fn to_predicate(&self) -> Predicate<'tcx>;
1305 impl<'tcx> ToPredicate<'tcx> for TraitRef<'tcx> {
1306 fn to_predicate(&self) -> Predicate<'tcx> {
1307 ty::Predicate::Trait(ty::Binder::dummy(ty::TraitPredicate {
1308 trait_ref: self.clone()
1313 impl<'tcx> ToPredicate<'tcx> for PolyTraitRef<'tcx> {
1314 fn to_predicate(&self) -> Predicate<'tcx> {
1315 ty::Predicate::Trait(self.to_poly_trait_predicate())
1319 impl<'tcx> ToPredicate<'tcx> for PolyRegionOutlivesPredicate<'tcx> {
1320 fn to_predicate(&self) -> Predicate<'tcx> {
1321 Predicate::RegionOutlives(self.clone())
1325 impl<'tcx> ToPredicate<'tcx> for PolyTypeOutlivesPredicate<'tcx> {
1326 fn to_predicate(&self) -> Predicate<'tcx> {
1327 Predicate::TypeOutlives(self.clone())
1331 impl<'tcx> ToPredicate<'tcx> for PolyProjectionPredicate<'tcx> {
1332 fn to_predicate(&self) -> Predicate<'tcx> {
1333 Predicate::Projection(self.clone())
1337 // A custom iterator used by Predicate::walk_tys.
1338 enum WalkTysIter<'tcx, I, J, K>
1339 where I: Iterator<Item = Ty<'tcx>>,
1340 J: Iterator<Item = Ty<'tcx>>,
1341 K: Iterator<Item = Ty<'tcx>>
1345 Two(Ty<'tcx>, Ty<'tcx>),
1351 impl<'tcx, I, J, K> Iterator for WalkTysIter<'tcx, I, J, K>
1352 where I: Iterator<Item = Ty<'tcx>>,
1353 J: Iterator<Item = Ty<'tcx>>,
1354 K: Iterator<Item = Ty<'tcx>>
1356 type Item = Ty<'tcx>;
1358 fn next(&mut self) -> Option<Ty<'tcx>> {
1360 WalkTysIter::None => None,
1361 WalkTysIter::One(item) => {
1362 *self = WalkTysIter::None;
1365 WalkTysIter::Two(item1, item2) => {
1366 *self = WalkTysIter::One(item2);
1369 WalkTysIter::Types(ref mut iter) => {
1372 WalkTysIter::InputTypes(ref mut iter) => {
1375 WalkTysIter::ProjectionTypes(ref mut iter) => {
1382 impl<'tcx> Predicate<'tcx> {
1383 /// Iterates over the types in this predicate. Note that in all
1384 /// cases this is skipping over a binder, so late-bound regions
1385 /// with depth 0 are bound by the predicate.
1386 pub fn walk_tys(&'a self) -> impl Iterator<Item = Ty<'tcx>> + 'a {
1388 ty::Predicate::Trait(ref data) => {
1389 WalkTysIter::InputTypes(data.skip_binder().input_types())
1391 ty::Predicate::Subtype(binder) => {
1392 let SubtypePredicate { a, b, a_is_expected: _ } = binder.skip_binder();
1393 WalkTysIter::Two(a, b)
1395 ty::Predicate::TypeOutlives(binder) => {
1396 WalkTysIter::One(binder.skip_binder().0)
1398 ty::Predicate::RegionOutlives(..) => {
1401 ty::Predicate::Projection(ref data) => {
1402 let inner = data.skip_binder();
1403 WalkTysIter::ProjectionTypes(
1404 inner.projection_ty.substs.types().chain(Some(inner.ty)))
1406 ty::Predicate::WellFormed(data) => {
1407 WalkTysIter::One(data)
1409 ty::Predicate::ObjectSafe(_trait_def_id) => {
1412 ty::Predicate::ClosureKind(_closure_def_id, closure_substs, _kind) => {
1413 WalkTysIter::Types(closure_substs.substs.types())
1415 ty::Predicate::ConstEvaluatable(_, substs) => {
1416 WalkTysIter::Types(substs.types())
1421 pub fn to_opt_poly_trait_ref(&self) -> Option<PolyTraitRef<'tcx>> {
1423 Predicate::Trait(ref t) => {
1424 Some(t.to_poly_trait_ref())
1426 Predicate::Projection(..) |
1427 Predicate::Subtype(..) |
1428 Predicate::RegionOutlives(..) |
1429 Predicate::WellFormed(..) |
1430 Predicate::ObjectSafe(..) |
1431 Predicate::ClosureKind(..) |
1432 Predicate::TypeOutlives(..) |
1433 Predicate::ConstEvaluatable(..) => {
1439 pub fn to_opt_type_outlives(&self) -> Option<PolyTypeOutlivesPredicate<'tcx>> {
1441 Predicate::TypeOutlives(data) => {
1444 Predicate::Trait(..) |
1445 Predicate::Projection(..) |
1446 Predicate::Subtype(..) |
1447 Predicate::RegionOutlives(..) |
1448 Predicate::WellFormed(..) |
1449 Predicate::ObjectSafe(..) |
1450 Predicate::ClosureKind(..) |
1451 Predicate::ConstEvaluatable(..) => {
1458 /// Represents the bounds declared on a particular set of type
1459 /// parameters. Should eventually be generalized into a flag list of
1460 /// where-clauses. You can obtain a `InstantiatedPredicates` list from a
1461 /// `GenericPredicates` by using the `instantiate` method. Note that this method
1462 /// reflects an important semantic invariant of `InstantiatedPredicates`: while
1463 /// the `GenericPredicates` are expressed in terms of the bound type
1464 /// parameters of the impl/trait/whatever, an `InstantiatedPredicates` instance
1465 /// represented a set of bounds for some particular instantiation,
1466 /// meaning that the generic parameters have been substituted with
1471 /// struct Foo<T,U:Bar<T>> { ... }
1473 /// Here, the `GenericPredicates` for `Foo` would contain a list of bounds like
1474 /// `[[], [U:Bar<T>]]`. Now if there were some particular reference
1475 /// like `Foo<isize,usize>`, then the `InstantiatedPredicates` would be `[[],
1476 /// [usize:Bar<isize>]]`.
1478 pub struct InstantiatedPredicates<'tcx> {
1479 pub predicates: Vec<Predicate<'tcx>>,
1482 impl<'tcx> InstantiatedPredicates<'tcx> {
1483 pub fn empty() -> InstantiatedPredicates<'tcx> {
1484 InstantiatedPredicates { predicates: vec![] }
1487 pub fn is_empty(&self) -> bool {
1488 self.predicates.is_empty()
1492 /// "Universes" are used during type- and trait-checking in the
1493 /// presence of `for<..>` binders to control what sets of names are
1494 /// visible. Universes are arranged into a tree: the root universe
1495 /// contains names that are always visible. Each child then adds a new
1496 /// set of names that are visible, in addition to those of its parent.
1497 /// We say that the child universe "extends" the parent universe with
1500 /// To make this more concrete, consider this program:
1504 /// fn bar<T>(x: T) {
1505 /// let y: for<'a> fn(&'a u8, Foo) = ...;
1509 /// The struct name `Foo` is in the root universe U0. But the type
1510 /// parameter `T`, introduced on `bar`, is in an extended universe U1
1511 /// -- i.e., within `bar`, we can name both `T` and `Foo`, but outside
1512 /// of `bar`, we cannot name `T`. Then, within the type of `y`, the
1513 /// region `'a` is in a universe U2 that extends U1, because we can
1514 /// name it inside the fn type but not outside.
1516 /// Universes are used to do type- and trait-checking around these
1517 /// "forall" binders (also called **universal quantification**). The
1518 /// idea is that when, in the body of `bar`, we refer to `T` as a
1519 /// type, we aren't referring to any type in particular, but rather a
1520 /// kind of "fresh" type that is distinct from all other types we have
1521 /// actually declared. This is called a **placeholder** type, and we
1522 /// use universes to talk about this. In other words, a type name in
1523 /// universe 0 always corresponds to some "ground" type that the user
1524 /// declared, but a type name in a non-zero universe is a placeholder
1525 /// type -- an idealized representative of "types in general" that we
1526 /// use for checking generic functions.
1528 pub struct UniverseIndex {
1529 DEBUG_FORMAT = "U{}",
1533 impl_stable_hash_for!(struct UniverseIndex { private });
1535 impl UniverseIndex {
1536 pub const ROOT: UniverseIndex = UniverseIndex::from_u32_const(0);
1538 /// Returns the "next" universe index in order -- this new index
1539 /// is considered to extend all previous universes. This
1540 /// corresponds to entering a `forall` quantifier. So, for
1541 /// example, suppose we have this type in universe `U`:
1544 /// for<'a> fn(&'a u32)
1547 /// Once we "enter" into this `for<'a>` quantifier, we are in a
1548 /// new universe that extends `U` -- in this new universe, we can
1549 /// name the region `'a`, but that region was not nameable from
1550 /// `U` because it was not in scope there.
1551 pub fn next_universe(self) -> UniverseIndex {
1552 UniverseIndex::from_u32(self.private.checked_add(1).unwrap())
1555 /// Returns `true` if `self` can name a name from `other` -- in other words,
1556 /// if the set of names in `self` is a superset of those in
1557 /// `other` (`self >= other`).
1558 pub fn can_name(self, other: UniverseIndex) -> bool {
1559 self.private >= other.private
1562 /// Returns `true` if `self` cannot name some names from `other` -- in other
1563 /// words, if the set of names in `self` is a strict subset of
1564 /// those in `other` (`self < other`).
1565 pub fn cannot_name(self, other: UniverseIndex) -> bool {
1566 self.private < other.private
1570 /// The "placeholder index" fully defines a placeholder region.
1571 /// Placeholder regions are identified by both a **universe** as well
1572 /// as a "bound-region" within that universe. The `bound_region` is
1573 /// basically a name -- distinct bound regions within the same
1574 /// universe are just two regions with an unknown relationship to one
1576 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, PartialOrd, Ord)]
1577 pub struct Placeholder<T> {
1578 pub universe: UniverseIndex,
1582 impl<'a, 'gcx, T> HashStable<StableHashingContext<'a>> for Placeholder<T>
1583 where T: HashStable<StableHashingContext<'a>>
1585 fn hash_stable<W: StableHasherResult>(
1587 hcx: &mut StableHashingContext<'a>,
1588 hasher: &mut StableHasher<W>
1590 self.universe.hash_stable(hcx, hasher);
1591 self.name.hash_stable(hcx, hasher);
1595 pub type PlaceholderRegion = Placeholder<BoundRegion>;
1597 pub type PlaceholderType = Placeholder<BoundVar>;
1599 /// When type checking, we use the `ParamEnv` to track
1600 /// details about the set of where-clauses that are in scope at this
1601 /// particular point.
1602 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1603 pub struct ParamEnv<'tcx> {
1604 /// Obligations that the caller must satisfy. This is basically
1605 /// the set of bounds on the in-scope type parameters, translated
1606 /// into Obligations, and elaborated and normalized.
1607 pub caller_bounds: &'tcx List<ty::Predicate<'tcx>>,
1609 /// Typically, this is `Reveal::UserFacing`, but during codegen we
1610 /// want `Reveal::All` -- note that this is always paired with an
1611 /// empty environment. To get that, use `ParamEnv::reveal()`.
1612 pub reveal: traits::Reveal,
1614 /// If this `ParamEnv` comes from a call to `tcx.param_env(def_id)`,
1615 /// register that `def_id` (useful for transitioning to the chalk trait
1617 pub def_id: Option<DefId>,
1620 impl<'tcx> ParamEnv<'tcx> {
1621 /// Construct a trait environment suitable for contexts where
1622 /// there are no where-clauses in scope. Hidden types (like `impl
1623 /// Trait`) are left hidden, so this is suitable for ordinary
1626 pub fn empty() -> Self {
1627 Self::new(List::empty(), Reveal::UserFacing, None)
1630 /// Construct a trait environment with no where-clauses in scope
1631 /// where the values of all `impl Trait` and other hidden types
1632 /// are revealed. This is suitable for monomorphized, post-typeck
1633 /// environments like codegen or doing optimizations.
1635 /// N.B., if you want to have predicates in scope, use `ParamEnv::new`,
1636 /// or invoke `param_env.with_reveal_all()`.
1638 pub fn reveal_all() -> Self {
1639 Self::new(List::empty(), Reveal::All, None)
1642 /// Construct a trait environment with the given set of predicates.
1645 caller_bounds: &'tcx List<ty::Predicate<'tcx>>,
1647 def_id: Option<DefId>
1649 ty::ParamEnv { caller_bounds, reveal, def_id }
1652 /// Returns a new parameter environment with the same clauses, but
1653 /// which "reveals" the true results of projections in all cases
1654 /// (even for associated types that are specializable). This is
1655 /// the desired behavior during codegen and certain other special
1656 /// contexts; normally though we want to use `Reveal::UserFacing`,
1657 /// which is the default.
1658 pub fn with_reveal_all(self) -> Self {
1659 ty::ParamEnv { reveal: Reveal::All, ..self }
1662 /// Returns this same environment but with no caller bounds.
1663 pub fn without_caller_bounds(self) -> Self {
1664 ty::ParamEnv { caller_bounds: List::empty(), ..self }
1667 /// Creates a suitable environment in which to perform trait
1668 /// queries on the given value. When type-checking, this is simply
1669 /// the pair of the environment plus value. But when reveal is set to
1670 /// All, then if `value` does not reference any type parameters, we will
1671 /// pair it with the empty environment. This improves caching and is generally
1674 /// N.B., we preserve the environment when type-checking because it
1675 /// is possible for the user to have wacky where-clauses like
1676 /// `where Box<u32>: Copy`, which are clearly never
1677 /// satisfiable. We generally want to behave as if they were true,
1678 /// although the surrounding function is never reachable.
1679 pub fn and<T: TypeFoldable<'tcx>>(self, value: T) -> ParamEnvAnd<'tcx, T> {
1681 Reveal::UserFacing => {
1689 if value.has_placeholders()
1690 || value.needs_infer()
1691 || value.has_param_types()
1692 || value.has_self_ty()
1700 param_env: self.without_caller_bounds(),
1709 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1710 pub struct ParamEnvAnd<'tcx, T> {
1711 pub param_env: ParamEnv<'tcx>,
1715 impl<'tcx, T> ParamEnvAnd<'tcx, T> {
1716 pub fn into_parts(self) -> (ParamEnv<'tcx>, T) {
1717 (self.param_env, self.value)
1721 impl<'a, 'gcx, T> HashStable<StableHashingContext<'a>> for ParamEnvAnd<'gcx, T>
1722 where T: HashStable<StableHashingContext<'a>>
1724 fn hash_stable<W: StableHasherResult>(&self,
1725 hcx: &mut StableHashingContext<'a>,
1726 hasher: &mut StableHasher<W>) {
1732 param_env.hash_stable(hcx, hasher);
1733 value.hash_stable(hcx, hasher);
1737 #[derive(Copy, Clone, Debug)]
1738 pub struct Destructor {
1739 /// The `DefId` of the destructor method
1744 pub struct AdtFlags: u32 {
1745 const NO_ADT_FLAGS = 0;
1746 const IS_ENUM = 1 << 0;
1747 const IS_UNION = 1 << 1;
1748 const IS_STRUCT = 1 << 2;
1749 const HAS_CTOR = 1 << 3;
1750 const IS_PHANTOM_DATA = 1 << 4;
1751 const IS_FUNDAMENTAL = 1 << 5;
1752 const IS_BOX = 1 << 6;
1753 /// Indicates whether the type is an `Arc`.
1754 const IS_ARC = 1 << 7;
1755 /// Indicates whether the type is an `Rc`.
1756 const IS_RC = 1 << 8;
1757 /// Indicates whether the variant list of this ADT is `#[non_exhaustive]`.
1758 /// (i.e., this flag is never set unless this ADT is an enum).
1759 const IS_VARIANT_LIST_NON_EXHAUSTIVE = 1 << 9;
1764 pub struct VariantFlags: u32 {
1765 const NO_VARIANT_FLAGS = 0;
1766 /// Indicates whether the field list of this variant is `#[non_exhaustive]`.
1767 const IS_FIELD_LIST_NON_EXHAUSTIVE = 1 << 0;
1772 pub struct VariantDef {
1773 /// The variant's `DefId`. If this is a tuple-like struct,
1774 /// this is the `DefId` of the struct's ctor.
1776 pub ident: Ident, // struct's name if this is a struct
1777 pub discr: VariantDiscr,
1778 pub fields: Vec<FieldDef>,
1779 pub ctor_kind: CtorKind,
1780 flags: VariantFlags,
1783 impl<'a, 'gcx, 'tcx> VariantDef {
1784 /// Creates a new `VariantDef`.
1786 /// - `did` is the `DefId` used for the variant.
1787 /// This is the constructor `DefId` for tuple stucts, and the variant `DefId` for everything
1789 /// - `attribute_def_id` is the DefId that has the variant's attributes.
1790 /// This is the struct `DefId` for structs, and the variant `DefId` for variants.
1792 /// Note that we *could* use the constructor `DefId`, because the constructor attributes
1793 /// redirect to the base attributes, but compiling a small crate requires
1794 /// loading the `AdtDef`s for all the structs in the universe (e.g., coherence for any
1795 /// built-in trait), and we do not want to load attributes twice.
1797 /// If someone speeds up attribute loading to not be a performance concern, they can
1798 /// remove this hack and use the constructor `DefId` everywhere.
1799 pub fn new(tcx: TyCtxt<'a, 'gcx, 'tcx>,
1802 discr: VariantDiscr,
1803 fields: Vec<FieldDef>,
1805 ctor_kind: CtorKind,
1806 attribute_def_id: DefId)
1809 debug!("VariantDef::new({:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?})", did, ident, discr,
1810 fields, adt_kind, ctor_kind, attribute_def_id);
1811 let mut flags = VariantFlags::NO_VARIANT_FLAGS;
1812 if adt_kind == AdtKind::Struct && tcx.has_attr(attribute_def_id, "non_exhaustive") {
1813 debug!("found non-exhaustive field list for {:?}", did);
1814 flags = flags | VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE;
1827 pub fn is_field_list_non_exhaustive(&self) -> bool {
1828 self.flags.intersects(VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE)
1832 impl_stable_hash_for!(struct VariantDef {
1834 ident -> (ident.name),
1841 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
1842 pub enum VariantDiscr {
1843 /// Explicit value for this variant, i.e., `X = 123`.
1844 /// The `DefId` corresponds to the embedded constant.
1847 /// The previous variant's discriminant plus one.
1848 /// For efficiency reasons, the distance from the
1849 /// last `Explicit` discriminant is being stored,
1850 /// or `0` for the first variant, if it has none.
1855 pub struct FieldDef {
1858 pub vis: Visibility,
1861 /// The definition of an abstract data type -- a struct or enum.
1863 /// These are all interned (by `intern_adt_def`) into the `adt_defs`
1867 pub variants: IndexVec<self::layout::VariantIdx, VariantDef>,
1869 pub repr: ReprOptions,
1872 impl PartialOrd for AdtDef {
1873 fn partial_cmp(&self, other: &AdtDef) -> Option<Ordering> {
1874 Some(self.cmp(&other))
1878 /// There should be only one AdtDef for each `did`, therefore
1879 /// it is fine to implement `Ord` only based on `did`.
1880 impl Ord for AdtDef {
1881 fn cmp(&self, other: &AdtDef) -> Ordering {
1882 self.did.cmp(&other.did)
1886 impl PartialEq for AdtDef {
1887 // AdtDef are always interned and this is part of TyS equality
1889 fn eq(&self, other: &Self) -> bool { ptr::eq(self, other) }
1892 impl Eq for AdtDef {}
1894 impl Hash for AdtDef {
1896 fn hash<H: Hasher>(&self, s: &mut H) {
1897 (self as *const AdtDef).hash(s)
1901 impl<'tcx> serialize::UseSpecializedEncodable for &'tcx AdtDef {
1902 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1907 impl<'tcx> serialize::UseSpecializedDecodable for &'tcx AdtDef {}
1910 impl<'a> HashStable<StableHashingContext<'a>> for AdtDef {
1911 fn hash_stable<W: StableHasherResult>(&self,
1912 hcx: &mut StableHashingContext<'a>,
1913 hasher: &mut StableHasher<W>) {
1915 static CACHE: RefCell<FxHashMap<usize, Fingerprint>> = Default::default();
1918 let hash: Fingerprint = CACHE.with(|cache| {
1919 let addr = self as *const AdtDef as usize;
1920 *cache.borrow_mut().entry(addr).or_insert_with(|| {
1928 let mut hasher = StableHasher::new();
1929 did.hash_stable(hcx, &mut hasher);
1930 variants.hash_stable(hcx, &mut hasher);
1931 flags.hash_stable(hcx, &mut hasher);
1932 repr.hash_stable(hcx, &mut hasher);
1938 hash.hash_stable(hcx, hasher);
1942 #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
1943 pub enum AdtKind { Struct, Union, Enum }
1945 impl Into<DataTypeKind> for AdtKind {
1946 fn into(self) -> DataTypeKind {
1948 AdtKind::Struct => DataTypeKind::Struct,
1949 AdtKind::Union => DataTypeKind::Union,
1950 AdtKind::Enum => DataTypeKind::Enum,
1956 #[derive(RustcEncodable, RustcDecodable, Default)]
1957 pub struct ReprFlags: u8 {
1958 const IS_C = 1 << 0;
1959 const IS_SIMD = 1 << 1;
1960 const IS_TRANSPARENT = 1 << 2;
1961 // Internal only for now. If true, don't reorder fields.
1962 const IS_LINEAR = 1 << 3;
1964 // Any of these flags being set prevent field reordering optimisation.
1965 const IS_UNOPTIMISABLE = ReprFlags::IS_C.bits |
1966 ReprFlags::IS_SIMD.bits |
1967 ReprFlags::IS_LINEAR.bits;
1971 impl_stable_hash_for!(struct ReprFlags {
1975 /// Represents the repr options provided by the user,
1976 #[derive(Copy, Clone, Debug, Eq, PartialEq, RustcEncodable, RustcDecodable, Default)]
1977 pub struct ReprOptions {
1978 pub int: Option<attr::IntType>,
1981 pub flags: ReprFlags,
1984 impl_stable_hash_for!(struct ReprOptions {
1992 pub fn new(tcx: TyCtxt<'_, '_, '_>, did: DefId) -> ReprOptions {
1993 let mut flags = ReprFlags::empty();
1994 let mut size = None;
1995 let mut max_align = 0;
1996 let mut min_pack = 0;
1997 for attr in tcx.get_attrs(did).iter() {
1998 for r in attr::find_repr_attrs(&tcx.sess.parse_sess, attr) {
1999 flags.insert(match r {
2000 attr::ReprC => ReprFlags::IS_C,
2001 attr::ReprPacked(pack) => {
2002 min_pack = if min_pack > 0 {
2003 cmp::min(pack, min_pack)
2009 attr::ReprTransparent => ReprFlags::IS_TRANSPARENT,
2010 attr::ReprSimd => ReprFlags::IS_SIMD,
2011 attr::ReprInt(i) => {
2015 attr::ReprAlign(align) => {
2016 max_align = cmp::max(align, max_align);
2023 // This is here instead of layout because the choice must make it into metadata.
2024 if !tcx.consider_optimizing(|| format!("Reorder fields of {:?}", tcx.item_path_str(did))) {
2025 flags.insert(ReprFlags::IS_LINEAR);
2027 ReprOptions { int: size, align: max_align, pack: min_pack, flags: flags }
2031 pub fn simd(&self) -> bool { self.flags.contains(ReprFlags::IS_SIMD) }
2033 pub fn c(&self) -> bool { self.flags.contains(ReprFlags::IS_C) }
2035 pub fn packed(&self) -> bool { self.pack > 0 }
2037 pub fn transparent(&self) -> bool { self.flags.contains(ReprFlags::IS_TRANSPARENT) }
2039 pub fn linear(&self) -> bool { self.flags.contains(ReprFlags::IS_LINEAR) }
2041 pub fn discr_type(&self) -> attr::IntType {
2042 self.int.unwrap_or(attr::SignedInt(ast::IntTy::Isize))
2045 /// Returns `true` if this `#[repr()]` should inhabit "smart enum
2046 /// layout" optimizations, such as representing `Foo<&T>` as a
2048 pub fn inhibit_enum_layout_opt(&self) -> bool {
2049 self.c() || self.int.is_some()
2052 /// Returns `true` if this `#[repr()]` should inhibit struct field reordering
2053 /// optimizations, such as with `repr(C)`, `repr(packed(1))`, or `repr(<int>)`.
2054 pub fn inhibit_struct_field_reordering_opt(&self) -> bool {
2055 self.flags.intersects(ReprFlags::IS_UNOPTIMISABLE) || self.pack == 1 ||
2059 /// Returns `true` if this `#[repr()]` should inhibit union ABI optimisations.
2060 pub fn inhibit_union_abi_opt(&self) -> bool {
2066 impl<'a, 'gcx, 'tcx> AdtDef {
2067 fn new(tcx: TyCtxt<'_, '_, '_>,
2070 variants: IndexVec<VariantIdx, VariantDef>,
2071 repr: ReprOptions) -> Self {
2072 debug!("AdtDef::new({:?}, {:?}, {:?}, {:?})", did, kind, variants, repr);
2073 let mut flags = AdtFlags::NO_ADT_FLAGS;
2075 if kind == AdtKind::Enum && tcx.has_attr(did, "non_exhaustive") {
2076 debug!("found non-exhaustive variant list for {:?}", did);
2077 flags = flags | AdtFlags::IS_VARIANT_LIST_NON_EXHAUSTIVE;
2079 flags |= match kind {
2080 AdtKind::Enum => AdtFlags::IS_ENUM,
2081 AdtKind::Union => AdtFlags::IS_UNION,
2082 AdtKind::Struct => AdtFlags::IS_STRUCT,
2085 if let AdtKind::Struct = kind {
2086 let variant_def = &variants[VariantIdx::new(0)];
2087 let def_key = tcx.def_key(variant_def.did);
2088 match def_key.disambiguated_data.data {
2089 DefPathData::StructCtor => flags |= AdtFlags::HAS_CTOR,
2094 let attrs = tcx.get_attrs(did);
2095 if attr::contains_name(&attrs, "fundamental") {
2096 flags |= AdtFlags::IS_FUNDAMENTAL;
2098 if Some(did) == tcx.lang_items().phantom_data() {
2099 flags |= AdtFlags::IS_PHANTOM_DATA;
2101 if Some(did) == tcx.lang_items().owned_box() {
2102 flags |= AdtFlags::IS_BOX;
2104 if Some(did) == tcx.lang_items().arc() {
2105 flags |= AdtFlags::IS_ARC;
2107 if Some(did) == tcx.lang_items().rc() {
2108 flags |= AdtFlags::IS_RC;
2120 pub fn is_struct(&self) -> bool {
2121 self.flags.contains(AdtFlags::IS_STRUCT)
2125 pub fn is_union(&self) -> bool {
2126 self.flags.contains(AdtFlags::IS_UNION)
2130 pub fn is_enum(&self) -> bool {
2131 self.flags.contains(AdtFlags::IS_ENUM)
2135 pub fn is_variant_list_non_exhaustive(&self) -> bool {
2136 self.flags.contains(AdtFlags::IS_VARIANT_LIST_NON_EXHAUSTIVE)
2139 /// Returns the kind of the ADT.
2141 pub fn adt_kind(&self) -> AdtKind {
2144 } else if self.is_union() {
2151 pub fn descr(&self) -> &'static str {
2152 match self.adt_kind() {
2153 AdtKind::Struct => "struct",
2154 AdtKind::Union => "union",
2155 AdtKind::Enum => "enum",
2160 pub fn variant_descr(&self) -> &'static str {
2161 match self.adt_kind() {
2162 AdtKind::Struct => "struct",
2163 AdtKind::Union => "union",
2164 AdtKind::Enum => "variant",
2168 /// If this function returns `true`, it implies that `is_struct` must return `true`.
2170 pub fn has_ctor(&self) -> bool {
2171 self.flags.contains(AdtFlags::HAS_CTOR)
2174 /// Returns `true` if this type is `#[fundamental]` for the purposes
2175 /// of coherence checking.
2177 pub fn is_fundamental(&self) -> bool {
2178 self.flags.contains(AdtFlags::IS_FUNDAMENTAL)
2181 /// Returns `true` if this is `PhantomData<T>`.
2183 pub fn is_phantom_data(&self) -> bool {
2184 self.flags.contains(AdtFlags::IS_PHANTOM_DATA)
2187 /// Returns `true` if this is `Arc<T>`.
2188 pub fn is_arc(&self) -> bool {
2189 self.flags.contains(AdtFlags::IS_ARC)
2192 /// Returns `true` if this is `Rc<T>`.
2193 pub fn is_rc(&self) -> bool {
2194 self.flags.contains(AdtFlags::IS_RC)
2197 /// Returns `true` if this is Box<T>.
2199 pub fn is_box(&self) -> bool {
2200 self.flags.contains(AdtFlags::IS_BOX)
2203 /// Returns `true` if this type has a destructor.
2204 pub fn has_dtor(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> bool {
2205 self.destructor(tcx).is_some()
2208 /// Asserts this is a struct or union and returns its unique variant.
2209 pub fn non_enum_variant(&self) -> &VariantDef {
2210 assert!(self.is_struct() || self.is_union());
2211 &self.variants[VariantIdx::new(0)]
2215 pub fn predicates(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Lrc<GenericPredicates<'gcx>> {
2216 tcx.predicates_of(self.did)
2219 /// Returns an iterator over all fields contained
2222 pub fn all_fields<'s>(&'s self) -> impl Iterator<Item = &'s FieldDef> {
2223 self.variants.iter().flat_map(|v| v.fields.iter())
2226 pub fn is_payloadfree(&self) -> bool {
2227 !self.variants.is_empty() &&
2228 self.variants.iter().all(|v| v.fields.is_empty())
2231 pub fn variant_with_id(&self, vid: DefId) -> &VariantDef {
2234 .find(|v| v.did == vid)
2235 .expect("variant_with_id: unknown variant")
2238 pub fn variant_index_with_id(&self, vid: DefId) -> VariantIdx {
2241 .find(|(_, v)| v.did == vid)
2242 .expect("variant_index_with_id: unknown variant")
2246 pub fn variant_of_def(&self, def: Def) -> &VariantDef {
2248 Def::Variant(vid) | Def::VariantCtor(vid, ..) => self.variant_with_id(vid),
2249 Def::Struct(..) | Def::StructCtor(..) | Def::Union(..) |
2250 Def::TyAlias(..) | Def::AssociatedTy(..) | Def::SelfTy(..) |
2251 Def::SelfCtor(..) => self.non_enum_variant(),
2252 _ => bug!("unexpected def {:?} in variant_of_def", def)
2257 pub fn eval_explicit_discr(
2259 tcx: TyCtxt<'a, 'gcx, 'tcx>,
2261 ) -> Option<Discr<'tcx>> {
2262 let param_env = ParamEnv::empty();
2263 let repr_type = self.repr.discr_type();
2264 let substs = InternalSubsts::identity_for_item(tcx.global_tcx(), expr_did);
2265 let instance = ty::Instance::new(expr_did, substs);
2266 let cid = GlobalId {
2270 match tcx.const_eval(param_env.and(cid)) {
2272 // FIXME: Find the right type and use it instead of `val.ty` here
2273 if let Some(b) = val.assert_bits(tcx.global_tcx(), param_env.and(val.ty)) {
2274 trace!("discriminants: {} ({:?})", b, repr_type);
2280 info!("invalid enum discriminant: {:#?}", val);
2281 crate::mir::interpret::struct_error(
2282 tcx.at(tcx.def_span(expr_did)),
2283 "constant evaluation of enum discriminant resulted in non-integer",
2288 Err(ErrorHandled::Reported) => {
2289 if !expr_did.is_local() {
2290 span_bug!(tcx.def_span(expr_did),
2291 "variant discriminant evaluation succeeded \
2292 in its crate but failed locally");
2296 Err(ErrorHandled::TooGeneric) => span_bug!(
2297 tcx.def_span(expr_did),
2298 "enum discriminant depends on generic arguments",
2304 pub fn discriminants(
2306 tcx: TyCtxt<'a, 'gcx, 'tcx>,
2307 ) -> impl Iterator<Item=(VariantIdx, Discr<'tcx>)> + Captures<'gcx> + 'a {
2308 let repr_type = self.repr.discr_type();
2309 let initial = repr_type.initial_discriminant(tcx.global_tcx());
2310 let mut prev_discr = None::<Discr<'tcx>>;
2311 self.variants.iter_enumerated().map(move |(i, v)| {
2312 let mut discr = prev_discr.map_or(initial, |d| d.wrap_incr(tcx));
2313 if let VariantDiscr::Explicit(expr_did) = v.discr {
2314 if let Some(new_discr) = self.eval_explicit_discr(tcx, expr_did) {
2318 prev_discr = Some(discr);
2324 /// Computes the discriminant value used by a specific variant.
2325 /// Unlike `discriminants`, this is (amortized) constant-time,
2326 /// only doing at most one query for evaluating an explicit
2327 /// discriminant (the last one before the requested variant),
2328 /// assuming there are no constant-evaluation errors there.
2329 pub fn discriminant_for_variant(&self,
2330 tcx: TyCtxt<'a, 'gcx, 'tcx>,
2331 variant_index: VariantIdx)
2333 let (val, offset) = self.discriminant_def_for_variant(variant_index);
2334 let explicit_value = val
2335 .and_then(|expr_did| self.eval_explicit_discr(tcx, expr_did))
2336 .unwrap_or_else(|| self.repr.discr_type().initial_discriminant(tcx.global_tcx()));
2337 explicit_value.checked_add(tcx, offset as u128).0
2340 /// Yields a `DefId` for the discriminant and an offset to add to it
2341 /// Alternatively, if there is no explicit discriminant, returns the
2342 /// inferred discriminant directly.
2343 pub fn discriminant_def_for_variant(
2345 variant_index: VariantIdx,
2346 ) -> (Option<DefId>, u32) {
2347 let mut explicit_index = variant_index.as_u32();
2350 match self.variants[VariantIdx::from_u32(explicit_index)].discr {
2351 ty::VariantDiscr::Relative(0) => {
2355 ty::VariantDiscr::Relative(distance) => {
2356 explicit_index -= distance;
2358 ty::VariantDiscr::Explicit(did) => {
2359 expr_did = Some(did);
2364 (expr_did, variant_index.as_u32() - explicit_index)
2367 pub fn destructor(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Option<Destructor> {
2368 tcx.adt_destructor(self.did)
2371 /// Returns a list of types such that `Self: Sized` if and only
2372 /// if that type is `Sized`, or `TyErr` if this type is recursive.
2374 /// Oddly enough, checking that the sized-constraint is `Sized` is
2375 /// actually more expressive than checking all members:
2376 /// the `Sized` trait is inductive, so an associated type that references
2377 /// `Self` would prevent its containing ADT from being `Sized`.
2379 /// Due to normalization being eager, this applies even if
2380 /// the associated type is behind a pointer (e.g., issue #31299).
2381 pub fn sized_constraint(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> &'tcx [Ty<'tcx>] {
2382 tcx.adt_sized_constraint(self.did).0
2385 fn sized_constraint_for_ty(&self,
2386 tcx: TyCtxt<'a, 'tcx, 'tcx>,
2389 let result = match ty.sty {
2390 Bool | Char | Int(..) | Uint(..) | Float(..) |
2391 RawPtr(..) | Ref(..) | FnDef(..) | FnPtr(_) |
2392 Array(..) | Closure(..) | Generator(..) | Never => {
2401 GeneratorWitness(..) => {
2402 // these are never sized - return the target type
2409 Some(ty) => self.sized_constraint_for_ty(tcx, ty)
2413 Adt(adt, substs) => {
2415 let adt_tys = adt.sized_constraint(tcx);
2416 debug!("sized_constraint_for_ty({:?}) intermediate = {:?}",
2419 .map(|ty| ty.subst(tcx, substs))
2420 .flat_map(|ty| self.sized_constraint_for_ty(tcx, ty))
2424 Projection(..) | Opaque(..) => {
2425 // must calculate explicitly.
2426 // FIXME: consider special-casing always-Sized projections
2430 UnnormalizedProjection(..) => bug!("only used with chalk-engine"),
2433 // perf hack: if there is a `T: Sized` bound, then
2434 // we know that `T` is Sized and do not need to check
2437 let sized_trait = match tcx.lang_items().sized_trait() {
2439 _ => return vec![ty]
2441 let sized_predicate = Binder::dummy(TraitRef {
2442 def_id: sized_trait,
2443 substs: tcx.mk_substs_trait(ty, &[])
2445 let predicates = &tcx.predicates_of(self.did).predicates;
2446 if predicates.iter().any(|(p, _)| *p == sized_predicate) {
2456 bug!("unexpected type `{:?}` in sized_constraint_for_ty",
2460 debug!("sized_constraint_for_ty({:?}) = {:?}", ty, result);
2465 impl<'a, 'gcx, 'tcx> FieldDef {
2466 pub fn ty(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, subst: SubstsRef<'tcx>) -> Ty<'tcx> {
2467 tcx.type_of(self.did).subst(tcx, subst)
2471 /// Represents the various closure traits in the language. This
2472 /// will determine the type of the environment (`self`, in the
2473 /// desugaring) argument that the closure expects.
2475 /// You can get the environment type of a closure using
2476 /// `tcx.closure_env_ty()`.
2477 #[derive(Clone, Copy, PartialOrd, Ord, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
2478 pub enum ClosureKind {
2479 // Warning: Ordering is significant here! The ordering is chosen
2480 // because the trait Fn is a subtrait of FnMut and so in turn, and
2481 // hence we order it so that Fn < FnMut < FnOnce.
2487 impl<'a, 'tcx> ClosureKind {
2488 // This is the initial value used when doing upvar inference.
2489 pub const LATTICE_BOTTOM: ClosureKind = ClosureKind::Fn;
2491 pub fn trait_did(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> DefId {
2493 ClosureKind::Fn => tcx.require_lang_item(FnTraitLangItem),
2494 ClosureKind::FnMut => {
2495 tcx.require_lang_item(FnMutTraitLangItem)
2497 ClosureKind::FnOnce => {
2498 tcx.require_lang_item(FnOnceTraitLangItem)
2503 /// Returns `true` if this a type that impls this closure kind
2504 /// must also implement `other`.
2505 pub fn extends(self, other: ty::ClosureKind) -> bool {
2506 match (self, other) {
2507 (ClosureKind::Fn, ClosureKind::Fn) => true,
2508 (ClosureKind::Fn, ClosureKind::FnMut) => true,
2509 (ClosureKind::Fn, ClosureKind::FnOnce) => true,
2510 (ClosureKind::FnMut, ClosureKind::FnMut) => true,
2511 (ClosureKind::FnMut, ClosureKind::FnOnce) => true,
2512 (ClosureKind::FnOnce, ClosureKind::FnOnce) => true,
2517 /// Returns the representative scalar type for this closure kind.
2518 /// See `TyS::to_opt_closure_kind` for more details.
2519 pub fn to_ty(self, tcx: TyCtxt<'_, '_, 'tcx>) -> Ty<'tcx> {
2521 ty::ClosureKind::Fn => tcx.types.i8,
2522 ty::ClosureKind::FnMut => tcx.types.i16,
2523 ty::ClosureKind::FnOnce => tcx.types.i32,
2528 impl<'tcx> TyS<'tcx> {
2529 /// Iterator that walks `self` and any types reachable from
2530 /// `self`, in depth-first order. Note that just walks the types
2531 /// that appear in `self`, it does not descend into the fields of
2532 /// structs or variants. For example:
2535 /// isize => { isize }
2536 /// Foo<Bar<isize>> => { Foo<Bar<isize>>, Bar<isize>, isize }
2537 /// [isize] => { [isize], isize }
2539 pub fn walk(&'tcx self) -> TypeWalker<'tcx> {
2540 TypeWalker::new(self)
2543 /// Iterator that walks the immediate children of `self`. Hence
2544 /// `Foo<Bar<i32>, u32>` yields the sequence `[Bar<i32>, u32]`
2545 /// (but not `i32`, like `walk`).
2546 pub fn walk_shallow(&'tcx self) -> smallvec::IntoIter<walk::TypeWalkerArray<'tcx>> {
2547 walk::walk_shallow(self)
2550 /// Walks `ty` and any types appearing within `ty`, invoking the
2551 /// callback `f` on each type. If the callback returns `false`, then the
2552 /// children of the current type are ignored.
2554 /// Note: prefer `ty.walk()` where possible.
2555 pub fn maybe_walk<F>(&'tcx self, mut f: F)
2556 where F: FnMut(Ty<'tcx>) -> bool
2558 let mut walker = self.walk();
2559 while let Some(ty) = walker.next() {
2561 walker.skip_current_subtree();
2568 pub fn from_mutbl(m: hir::Mutability) -> BorrowKind {
2570 hir::MutMutable => MutBorrow,
2571 hir::MutImmutable => ImmBorrow,
2575 /// Returns a mutability `m` such that an `&m T` pointer could be used to obtain this borrow
2576 /// kind. Because borrow kinds are richer than mutabilities, we sometimes have to pick a
2577 /// mutability that is stronger than necessary so that it at least *would permit* the borrow in
2579 pub fn to_mutbl_lossy(self) -> hir::Mutability {
2581 MutBorrow => hir::MutMutable,
2582 ImmBorrow => hir::MutImmutable,
2584 // We have no type corresponding to a unique imm borrow, so
2585 // use `&mut`. It gives all the capabilities of an `&uniq`
2586 // and hence is a safe "over approximation".
2587 UniqueImmBorrow => hir::MutMutable,
2591 pub fn to_user_str(&self) -> &'static str {
2593 MutBorrow => "mutable",
2594 ImmBorrow => "immutable",
2595 UniqueImmBorrow => "uniquely immutable",
2600 #[derive(Debug, Clone)]
2601 pub enum Attributes<'gcx> {
2602 Owned(Lrc<[ast::Attribute]>),
2603 Borrowed(&'gcx [ast::Attribute])
2606 impl<'gcx> ::std::ops::Deref for Attributes<'gcx> {
2607 type Target = [ast::Attribute];
2609 fn deref(&self) -> &[ast::Attribute] {
2611 &Attributes::Owned(ref data) => &data,
2612 &Attributes::Borrowed(data) => data
2617 #[derive(Debug, PartialEq, Eq)]
2618 pub enum ImplOverlapKind {
2619 /// These impls are always allowed to overlap.
2621 /// These impls are allowed to overlap, but that raises
2622 /// an issue #33140 future-compatibility warning.
2624 /// Some background: in Rust 1.0, the trait-object types `Send + Sync` (today's
2625 /// `dyn Send + Sync`) and `Sync + Send` (now `dyn Sync + Send`) were different.
2627 /// The widely-used version 0.1.0 of the crate `traitobject` had accidentally relied
2628 /// that difference, making what reduces to the following set of impls:
2632 /// impl Trait for dyn Send + Sync {}
2633 /// impl Trait for dyn Sync + Send {}
2636 /// Obviously, once we made these types be identical, that code causes a coherence
2637 /// error and a fairly big headache for us. However, luckily for us, the trait
2638 /// `Trait` used in this case is basically a marker trait, and therefore having
2639 /// overlapping impls for it is sound.
2641 /// To handle this, we basically regard the trait as a marker trait, with an additional
2642 /// future-compatibility warning. To avoid accidentally "stabilizing" this feature,
2643 /// it has the following restrictions:
2645 /// 1. The trait must indeed be a marker-like trait (i.e., no items), and must be
2647 /// 2. The trait-ref of both impls must be equal.
2648 /// 3. The trait-ref of both impls must be a trait object type consisting only of
2650 /// 4. Neither of the impls can have any where-clauses.
2652 /// Once `traitobject` 0.1.0 is no longer an active concern, this hack can be removed.
2656 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
2657 pub fn body_tables(self, body: hir::BodyId) -> &'gcx TypeckTables<'gcx> {
2658 self.typeck_tables_of(self.hir().body_owner_def_id(body))
2661 /// Returns an iterator of the `DefId`s for all body-owners in this
2662 /// crate. If you would prefer to iterate over the bodies
2663 /// themselves, you can do `self.hir().krate().body_ids.iter()`.
2666 ) -> impl Iterator<Item = DefId> + Captures<'tcx> + Captures<'gcx> + 'a {
2670 .map(move |&body_id| self.hir().body_owner_def_id(body_id))
2673 pub fn par_body_owners<F: Fn(DefId) + sync::Sync + sync::Send>(self, f: F) {
2674 par_iter(&self.hir().krate().body_ids).for_each(|&body_id| {
2675 f(self.hir().body_owner_def_id(body_id))
2679 pub fn expr_span(self, id: NodeId) -> Span {
2680 match self.hir().find(id) {
2681 Some(Node::Expr(e)) => {
2685 bug!("Node id {} is not an expr: {:?}", id, f);
2688 bug!("Node id {} is not present in the node map", id);
2693 pub fn provided_trait_methods(self, id: DefId) -> Vec<AssociatedItem> {
2694 self.associated_items(id)
2695 .filter(|item| item.kind == AssociatedKind::Method && item.defaultness.has_value())
2699 pub fn trait_relevant_for_never(self, did: DefId) -> bool {
2700 self.associated_items(did).any(|item| {
2701 item.relevant_for_never()
2705 pub fn opt_associated_item(self, def_id: DefId) -> Option<AssociatedItem> {
2706 let is_associated_item = if let Some(node_id) = self.hir().as_local_node_id(def_id) {
2707 match self.hir().get(node_id) {
2708 Node::TraitItem(_) | Node::ImplItem(_) => true,
2712 match self.describe_def(def_id).expect("no def for def-id") {
2713 Def::AssociatedConst(_) | Def::Method(_) | Def::AssociatedTy(_) => true,
2718 if is_associated_item {
2719 Some(self.associated_item(def_id))
2725 fn associated_item_from_trait_item_ref(self,
2726 parent_def_id: DefId,
2727 parent_vis: &hir::Visibility,
2728 trait_item_ref: &hir::TraitItemRef)
2730 let def_id = self.hir().local_def_id(trait_item_ref.id.node_id);
2731 let (kind, has_self) = match trait_item_ref.kind {
2732 hir::AssociatedItemKind::Const => (ty::AssociatedKind::Const, false),
2733 hir::AssociatedItemKind::Method { has_self } => {
2734 (ty::AssociatedKind::Method, has_self)
2736 hir::AssociatedItemKind::Type => (ty::AssociatedKind::Type, false),
2737 hir::AssociatedItemKind::Existential => bug!("only impls can have existentials"),
2741 ident: trait_item_ref.ident,
2743 // Visibility of trait items is inherited from their traits.
2744 vis: Visibility::from_hir(parent_vis, trait_item_ref.id.node_id, self),
2745 defaultness: trait_item_ref.defaultness,
2747 container: TraitContainer(parent_def_id),
2748 method_has_self_argument: has_self
2752 fn associated_item_from_impl_item_ref(self,
2753 parent_def_id: DefId,
2754 impl_item_ref: &hir::ImplItemRef)
2756 let def_id = self.hir().local_def_id(impl_item_ref.id.node_id);
2757 let (kind, has_self) = match impl_item_ref.kind {
2758 hir::AssociatedItemKind::Const => (ty::AssociatedKind::Const, false),
2759 hir::AssociatedItemKind::Method { has_self } => {
2760 (ty::AssociatedKind::Method, has_self)
2762 hir::AssociatedItemKind::Type => (ty::AssociatedKind::Type, false),
2763 hir::AssociatedItemKind::Existential => (ty::AssociatedKind::Existential, false),
2767 ident: impl_item_ref.ident,
2769 // Visibility of trait impl items doesn't matter.
2770 vis: ty::Visibility::from_hir(&impl_item_ref.vis, impl_item_ref.id.node_id, self),
2771 defaultness: impl_item_ref.defaultness,
2773 container: ImplContainer(parent_def_id),
2774 method_has_self_argument: has_self
2778 pub fn field_index(self, hir_id: hir::HirId, tables: &TypeckTables<'_>) -> usize {
2779 tables.field_indices().get(hir_id).cloned().expect("no index for a field")
2782 pub fn find_field_index(self, ident: Ident, variant: &VariantDef) -> Option<usize> {
2783 variant.fields.iter().position(|field| {
2784 self.adjust_ident(ident, variant.did, hir::DUMMY_HIR_ID).0 == field.ident.modern()
2788 pub fn associated_items(
2791 ) -> AssociatedItemsIterator<'a, 'gcx, 'tcx> {
2792 // Ideally, we would use `-> impl Iterator` here, but it falls
2793 // afoul of the conservative "capture [restrictions]" we put
2794 // in place, so we use a hand-written iterator.
2796 // [restrictions]: https://github.com/rust-lang/rust/issues/34511#issuecomment-373423999
2797 AssociatedItemsIterator {
2799 def_ids: self.associated_item_def_ids(def_id),
2804 /// Returns `true` if the impls are the same polarity and the trait either
2805 /// has no items or is annotated #[marker] and prevents item overrides.
2806 pub fn impls_are_allowed_to_overlap(self, def_id1: DefId, def_id2: DefId)
2807 -> Option<ImplOverlapKind>
2809 let is_legit = if self.features().overlapping_marker_traits {
2810 let trait1_is_empty = self.impl_trait_ref(def_id1)
2811 .map_or(false, |trait_ref| {
2812 self.associated_item_def_ids(trait_ref.def_id).is_empty()
2814 let trait2_is_empty = self.impl_trait_ref(def_id2)
2815 .map_or(false, |trait_ref| {
2816 self.associated_item_def_ids(trait_ref.def_id).is_empty()
2818 self.impl_polarity(def_id1) == self.impl_polarity(def_id2)
2822 let is_marker_impl = |def_id: DefId| -> bool {
2823 let trait_ref = self.impl_trait_ref(def_id);
2824 trait_ref.map_or(false, |tr| self.trait_def(tr.def_id).is_marker)
2826 self.impl_polarity(def_id1) == self.impl_polarity(def_id2)
2827 && is_marker_impl(def_id1)
2828 && is_marker_impl(def_id2)
2832 debug!("impls_are_allowed_to_overlap({:?}, {:?}) = Some(Permitted)",
2834 Some(ImplOverlapKind::Permitted)
2836 if let Some(self_ty1) = self.issue33140_self_ty(def_id1) {
2837 if let Some(self_ty2) = self.issue33140_self_ty(def_id2) {
2838 if self_ty1 == self_ty2 {
2839 debug!("impls_are_allowed_to_overlap({:?}, {:?}) - issue #33140 HACK",
2841 return Some(ImplOverlapKind::Issue33140);
2843 debug!("impls_are_allowed_to_overlap({:?}, {:?}) - found {:?} != {:?}",
2844 def_id1, def_id2, self_ty1, self_ty2);
2849 debug!("impls_are_allowed_to_overlap({:?}, {:?}) = None",
2855 // Returns `ty::VariantDef` if `def` refers to a struct,
2856 // or variant or their constructors, panics otherwise.
2857 pub fn expect_variant_def(self, def: Def) -> &'tcx VariantDef {
2859 Def::Variant(did) | Def::VariantCtor(did, ..) => {
2860 let enum_did = self.parent_def_id(did).unwrap();
2861 self.adt_def(enum_did).variant_with_id(did)
2863 Def::Struct(did) | Def::Union(did) => {
2864 self.adt_def(did).non_enum_variant()
2866 Def::StructCtor(ctor_did, ..) => {
2867 let did = self.parent_def_id(ctor_did).expect("struct ctor has no parent");
2868 self.adt_def(did).non_enum_variant()
2870 _ => bug!("expect_variant_def used with unexpected def {:?}", def)
2874 /// Given a `VariantDef`, returns the def-id of the `AdtDef` of which it is a part.
2875 pub fn adt_def_id_of_variant(self, variant_def: &'tcx VariantDef) -> DefId {
2876 let def_key = self.def_key(variant_def.did);
2877 match def_key.disambiguated_data.data {
2878 // for enum variants and tuple structs, the def-id of the ADT itself
2879 // is the *parent* of the variant
2880 DefPathData::EnumVariant(..) | DefPathData::StructCtor =>
2881 DefId { krate: variant_def.did.krate, index: def_key.parent.unwrap() },
2883 // otherwise, for structs and unions, they share a def-id
2884 _ => variant_def.did,
2888 pub fn item_name(self, id: DefId) -> InternedString {
2889 if id.index == CRATE_DEF_INDEX {
2890 self.original_crate_name(id.krate).as_interned_str()
2892 let def_key = self.def_key(id);
2893 // The name of a StructCtor is that of its struct parent.
2894 if let hir_map::DefPathData::StructCtor = def_key.disambiguated_data.data {
2895 self.item_name(DefId {
2897 index: def_key.parent.unwrap()
2900 def_key.disambiguated_data.data.get_opt_name().unwrap_or_else(|| {
2901 bug!("item_name: no name for {:?}", self.def_path(id));
2907 /// Returns the possibly-auto-generated MIR of a `(DefId, Subst)` pair.
2908 pub fn instance_mir(self, instance: ty::InstanceDef<'gcx>)
2912 ty::InstanceDef::Item(did) => {
2913 self.optimized_mir(did)
2915 ty::InstanceDef::VtableShim(..) |
2916 ty::InstanceDef::Intrinsic(..) |
2917 ty::InstanceDef::FnPtrShim(..) |
2918 ty::InstanceDef::Virtual(..) |
2919 ty::InstanceDef::ClosureOnceShim { .. } |
2920 ty::InstanceDef::DropGlue(..) |
2921 ty::InstanceDef::CloneShim(..) => {
2922 self.mir_shims(instance)
2927 /// Gets the attributes of a definition.
2928 pub fn get_attrs(self, did: DefId) -> Attributes<'gcx> {
2929 if let Some(id) = self.hir().as_local_hir_id(did) {
2930 Attributes::Borrowed(self.hir().attrs_by_hir_id(id))
2932 Attributes::Owned(self.item_attrs(did))
2936 /// Determines whether an item is annotated with an attribute.
2937 pub fn has_attr(self, did: DefId, attr: &str) -> bool {
2938 attr::contains_name(&self.get_attrs(did), attr)
2941 /// Returns `true` if this is an `auto trait`.
2942 pub fn trait_is_auto(self, trait_def_id: DefId) -> bool {
2943 self.trait_def(trait_def_id).has_auto_impl
2946 pub fn generator_layout(self, def_id: DefId) -> &'tcx GeneratorLayout<'tcx> {
2947 self.optimized_mir(def_id).generator_layout.as_ref().unwrap()
2950 /// Given the `DefId` of an impl, returns the `DefId` of the trait it implements.
2951 /// If it implements no trait, returns `None`.
2952 pub fn trait_id_of_impl(self, def_id: DefId) -> Option<DefId> {
2953 self.impl_trait_ref(def_id).map(|tr| tr.def_id)
2956 /// If the given defid describes a method belonging to an impl, returns the
2957 /// `DefId` of the impl that the method belongs to; otherwise, returns `None`.
2958 pub fn impl_of_method(self, def_id: DefId) -> Option<DefId> {
2959 let item = if def_id.krate != LOCAL_CRATE {
2960 if let Some(Def::Method(_)) = self.describe_def(def_id) {
2961 Some(self.associated_item(def_id))
2966 self.opt_associated_item(def_id)
2969 item.and_then(|trait_item|
2970 match trait_item.container {
2971 TraitContainer(_) => None,
2972 ImplContainer(def_id) => Some(def_id),
2977 /// Looks up the span of `impl_did` if the impl is local; otherwise returns `Err`
2978 /// with the name of the crate containing the impl.
2979 pub fn span_of_impl(self, impl_did: DefId) -> Result<Span, Symbol> {
2980 if impl_did.is_local() {
2981 let hir_id = self.hir().as_local_hir_id(impl_did).unwrap();
2982 Ok(self.hir().span_by_hir_id(hir_id))
2984 Err(self.crate_name(impl_did.krate))
2988 /// Hygienically compares a use-site name (`use_name`) for a field or an associated item with
2989 /// its supposed definition name (`def_name`). The method also needs `DefId` of the supposed
2990 /// definition's parent/scope to perform comparison.
2991 pub fn hygienic_eq(self, use_name: Ident, def_name: Ident, def_parent_def_id: DefId) -> bool {
2992 self.adjust_ident(use_name, def_parent_def_id, hir::DUMMY_HIR_ID).0 == def_name.modern()
2995 pub fn adjust_ident(self, mut ident: Ident, scope: DefId, block: hir::HirId) -> (Ident, DefId) {
2996 ident = ident.modern();
2997 let target_expansion = match scope.krate {
2998 LOCAL_CRATE => self.hir().definitions().expansion_that_defined(scope.index),
3001 let scope = match ident.span.adjust(target_expansion) {
3002 Some(actual_expansion) =>
3003 self.hir().definitions().parent_module_of_macro_def(actual_expansion),
3004 None if block == hir::DUMMY_HIR_ID => DefId::local(CRATE_DEF_INDEX), // Dummy DefId
3005 None => self.hir().get_module_parent_by_hir_id(block),
3011 pub struct AssociatedItemsIterator<'a, 'gcx: 'tcx, 'tcx: 'a> {
3012 tcx: TyCtxt<'a, 'gcx, 'tcx>,
3013 def_ids: Lrc<Vec<DefId>>,
3017 impl Iterator for AssociatedItemsIterator<'_, '_, '_> {
3018 type Item = AssociatedItem;
3020 fn next(&mut self) -> Option<AssociatedItem> {
3021 let def_id = self.def_ids.get(self.next_index)?;
3022 self.next_index += 1;
3023 Some(self.tcx.associated_item(*def_id))
3027 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
3028 pub fn with_freevars<T, F>(self, fid: NodeId, f: F) -> T where
3029 F: FnOnce(&[hir::Freevar]) -> T,
3031 let def_id = self.hir().local_def_id(fid);
3032 match self.freevars(def_id) {
3039 fn associated_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> AssociatedItem {
3040 let id = tcx.hir().as_local_node_id(def_id).unwrap();
3041 let parent_id = tcx.hir().get_parent(id);
3042 let parent_def_id = tcx.hir().local_def_id(parent_id);
3043 let parent_item = tcx.hir().expect_item(parent_id);
3044 match parent_item.node {
3045 hir::ItemKind::Impl(.., ref impl_item_refs) => {
3046 if let Some(impl_item_ref) = impl_item_refs.iter().find(|i| i.id.node_id == id) {
3047 let assoc_item = tcx.associated_item_from_impl_item_ref(parent_def_id,
3049 debug_assert_eq!(assoc_item.def_id, def_id);
3054 hir::ItemKind::Trait(.., ref trait_item_refs) => {
3055 if let Some(trait_item_ref) = trait_item_refs.iter().find(|i| i.id.node_id == id) {
3056 let assoc_item = tcx.associated_item_from_trait_item_ref(parent_def_id,
3059 debug_assert_eq!(assoc_item.def_id, def_id);
3067 span_bug!(parent_item.span,
3068 "unexpected parent of trait or impl item or item not found: {:?}",
3073 pub struct AdtSizedConstraint<'tcx>(pub &'tcx [Ty<'tcx>]);
3075 /// Calculates the `Sized` constraint.
3077 /// In fact, there are only a few options for the types in the constraint:
3078 /// - an obviously-unsized type
3079 /// - a type parameter or projection whose Sizedness can't be known
3080 /// - a tuple of type parameters or projections, if there are multiple
3082 /// - a Error, if a type contained itself. The representability
3083 /// check should catch this case.
3084 fn adt_sized_constraint<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
3086 -> AdtSizedConstraint<'tcx> {
3087 let def = tcx.adt_def(def_id);
3089 let result = tcx.mk_type_list(def.variants.iter().flat_map(|v| {
3092 def.sized_constraint_for_ty(tcx, tcx.type_of(f.did))
3095 debug!("adt_sized_constraint: {:?} => {:?}", def, result);
3097 AdtSizedConstraint(result)
3100 fn associated_item_def_ids<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
3102 -> Lrc<Vec<DefId>> {
3103 let id = tcx.hir().as_local_hir_id(def_id).unwrap();
3104 let item = tcx.hir().expect_item_by_hir_id(id);
3105 let vec: Vec<_> = match item.node {
3106 hir::ItemKind::Trait(.., ref trait_item_refs) => {
3107 trait_item_refs.iter()
3108 .map(|trait_item_ref| trait_item_ref.id)
3109 .map(|id| tcx.hir().local_def_id(id.node_id))
3112 hir::ItemKind::Impl(.., ref impl_item_refs) => {
3113 impl_item_refs.iter()
3114 .map(|impl_item_ref| impl_item_ref.id)
3115 .map(|id| tcx.hir().local_def_id(id.node_id))
3118 hir::ItemKind::TraitAlias(..) => vec![],
3119 _ => span_bug!(item.span, "associated_item_def_ids: not impl or trait")
3124 fn def_span<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> Span {
3125 tcx.hir().span_if_local(def_id).unwrap()
3128 /// If the given `DefId` describes an item belonging to a trait,
3129 /// returns the `DefId` of the trait that the trait item belongs to;
3130 /// otherwise, returns `None`.
3131 fn trait_of_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> Option<DefId> {
3132 tcx.opt_associated_item(def_id)
3133 .and_then(|associated_item| {
3134 match associated_item.container {
3135 TraitContainer(def_id) => Some(def_id),
3136 ImplContainer(_) => None
3141 /// Yields the parent function's `DefId` if `def_id` is an `impl Trait` definition.
3142 pub fn is_impl_trait_defn(tcx: TyCtxt<'_, '_, '_>, def_id: DefId) -> Option<DefId> {
3143 if let Some(node_id) = tcx.hir().as_local_node_id(def_id) {
3144 if let Node::Item(item) = tcx.hir().get(node_id) {
3145 if let hir::ItemKind::Existential(ref exist_ty) = item.node {
3146 return exist_ty.impl_trait_fn;
3153 /// See `ParamEnv` struct definition for details.
3154 fn param_env<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
3158 // The param_env of an impl Trait type is its defining function's param_env
3159 if let Some(parent) = is_impl_trait_defn(tcx, def_id) {
3160 return param_env(tcx, parent);
3162 // Compute the bounds on Self and the type parameters.
3164 let InstantiatedPredicates { predicates } =
3165 tcx.predicates_of(def_id).instantiate_identity(tcx);
3167 // Finally, we have to normalize the bounds in the environment, in
3168 // case they contain any associated type projections. This process
3169 // can yield errors if the put in illegal associated types, like
3170 // `<i32 as Foo>::Bar` where `i32` does not implement `Foo`. We
3171 // report these errors right here; this doesn't actually feel
3172 // right to me, because constructing the environment feels like a
3173 // kind of a "idempotent" action, but I'm not sure where would be
3174 // a better place. In practice, we construct environments for
3175 // every fn once during type checking, and we'll abort if there
3176 // are any errors at that point, so after type checking you can be
3177 // sure that this will succeed without errors anyway.
3179 let unnormalized_env = ty::ParamEnv::new(
3180 tcx.intern_predicates(&predicates),
3181 traits::Reveal::UserFacing,
3182 if tcx.sess.opts.debugging_opts.chalk { Some(def_id) } else { None }
3185 let body_id = tcx.hir().as_local_hir_id(def_id).map_or(hir::DUMMY_HIR_ID, |id| {
3186 tcx.hir().maybe_body_owned_by_by_hir_id(id).map_or(id, |body| body.hir_id)
3188 let cause = traits::ObligationCause::misc(tcx.def_span(def_id), body_id);
3189 traits::normalize_param_env_or_error(tcx, def_id, unnormalized_env, cause)
3192 fn crate_disambiguator<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
3193 crate_num: CrateNum) -> CrateDisambiguator {
3194 assert_eq!(crate_num, LOCAL_CRATE);
3195 tcx.sess.local_crate_disambiguator()
3198 fn original_crate_name<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
3199 crate_num: CrateNum) -> Symbol {
3200 assert_eq!(crate_num, LOCAL_CRATE);
3201 tcx.crate_name.clone()
3204 fn crate_hash<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
3205 crate_num: CrateNum)
3207 assert_eq!(crate_num, LOCAL_CRATE);
3208 tcx.hir().crate_hash
3211 fn instance_def_size_estimate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
3212 instance_def: InstanceDef<'tcx>)
3214 match instance_def {
3215 InstanceDef::Item(..) |
3216 InstanceDef::DropGlue(..) => {
3217 let mir = tcx.instance_mir(instance_def);
3218 mir.basic_blocks().iter().map(|bb| bb.statements.len()).sum()
3220 // Estimate the size of other compiler-generated shims to be 1.
3225 /// If `def_id` is an issue 33140 hack impl, returns its self type; otherwise, returns `None`.
3227 /// See [`ImplOverlapKind::Issue33140`] for more details.
3228 fn issue33140_self_ty<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
3232 debug!("issue33140_self_ty({:?})", def_id);
3234 let trait_ref = tcx.impl_trait_ref(def_id).unwrap_or_else(|| {
3235 bug!("issue33140_self_ty called on inherent impl {:?}", def_id)
3238 debug!("issue33140_self_ty({:?}), trait-ref={:?}", def_id, trait_ref);
3240 let is_marker_like =
3241 tcx.impl_polarity(def_id) == hir::ImplPolarity::Positive &&
3242 tcx.associated_item_def_ids(trait_ref.def_id).is_empty();
3244 // Check whether these impls would be ok for a marker trait.
3245 if !is_marker_like {
3246 debug!("issue33140_self_ty - not marker-like!");
3250 // impl must be `impl Trait for dyn Marker1 + Marker2 + ...`
3251 if trait_ref.substs.len() != 1 {
3252 debug!("issue33140_self_ty - impl has substs!");
3256 let predicates = tcx.predicates_of(def_id);
3257 if predicates.parent.is_some() || !predicates.predicates.is_empty() {
3258 debug!("issue33140_self_ty - impl has predicates {:?}!", predicates);
3262 let self_ty = trait_ref.self_ty();
3263 let self_ty_matches = match self_ty.sty {
3264 ty::Dynamic(ref data, ty::ReStatic) => data.principal().is_none(),
3268 if self_ty_matches {
3269 debug!("issue33140_self_ty - MATCHES!");
3272 debug!("issue33140_self_ty - non-matching self type");
3277 pub fn provide(providers: &mut ty::query::Providers<'_>) {
3278 context::provide(providers);
3279 erase_regions::provide(providers);
3280 layout::provide(providers);
3281 util::provide(providers);
3282 constness::provide(providers);
3283 *providers = ty::query::Providers {
3285 associated_item_def_ids,
3286 adt_sized_constraint,
3290 crate_disambiguator,
3291 original_crate_name,
3293 trait_impls_of: trait_def::trait_impls_of_provider,
3294 instance_def_size_estimate,
3300 /// A map for the local crate mapping each type to a vector of its
3301 /// inherent impls. This is not meant to be used outside of coherence;
3302 /// rather, you should request the vector for a specific type via
3303 /// `tcx.inherent_impls(def_id)` so as to minimize your dependencies
3304 /// (constructing this map requires touching the entire crate).
3305 #[derive(Clone, Debug, Default)]
3306 pub struct CrateInherentImpls {
3307 pub inherent_impls: DefIdMap<Lrc<Vec<DefId>>>,
3310 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable)]
3311 pub struct SymbolName {
3312 // FIXME: we don't rely on interning or equality here - better have
3313 // this be a `&'tcx str`.
3314 pub name: InternedString
3317 impl_stable_hash_for!(struct self::SymbolName {
3322 pub fn new(name: &str) -> SymbolName {
3324 name: Symbol::intern(name).as_interned_str()
3328 pub fn as_str(&self) -> LocalInternedString {
3333 impl fmt::Display for SymbolName {
3334 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
3335 fmt::Display::fmt(&self.name, fmt)
3339 impl fmt::Debug for SymbolName {
3340 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
3341 fmt::Display::fmt(&self.name, fmt)