1 // ignore-tidy-filelength
3 pub use self::fold::{TypeFoldable, TypeVisitor};
4 pub use self::AssocItemContainer::*;
5 pub use self::BorrowKind::*;
6 pub use self::IntVarValue::*;
7 pub use self::Variance::*;
9 use crate::arena::Arena;
10 use crate::hir::exports::ExportMap;
11 use crate::hir::map as hir_map;
13 use crate::ich::Fingerprint;
14 use crate::ich::StableHashingContext;
15 use crate::infer::canonical::Canonical;
16 use crate::middle::cstore::CrateStoreDyn;
17 use crate::middle::lang_items::{FnMutTraitLangItem, FnOnceTraitLangItem, FnTraitLangItem};
18 use crate::middle::resolve_lifetime::ObjectLifetimeDefault;
19 use crate::mir::interpret::ErrorHandled;
20 use crate::mir::GeneratorLayout;
21 use crate::mir::ReadOnlyBodyAndCache;
22 use crate::session::DataTypeKind;
23 use crate::traits::{self, Reveal};
25 use crate::ty::layout::VariantIdx;
26 use crate::ty::subst::{InternalSubsts, Subst, SubstsRef};
27 use crate::ty::util::{Discr, IntTypeExt};
28 use crate::ty::walk::TypeWalker;
29 use rustc_attr as attr;
30 use rustc_data_structures::captures::Captures;
31 use rustc_data_structures::fx::FxHashMap;
32 use rustc_data_structures::fx::FxIndexMap;
33 use rustc_data_structures::sorted_map::SortedIndexMultiMap;
34 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
35 use rustc_data_structures::sync::{self, par_iter, Lrc, ParallelIterator};
37 use rustc_hir::def::{CtorKind, CtorOf, DefKind, Namespace, Res};
38 use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, LocalDefId, CRATE_DEF_INDEX, LOCAL_CRATE};
39 use rustc_hir::{Constness, GlobMap, Node, TraitMap};
40 use rustc_index::vec::{Idx, IndexVec};
41 use rustc_macros::HashStable;
42 use rustc_serialize::{self, Encodable, Encoder};
43 use rustc_span::hygiene::ExpnId;
44 use rustc_span::symbol::{kw, sym, Symbol};
46 use rustc_target::abi::Align;
47 use syntax::ast::{self, Ident, Name};
48 use syntax::node_id::{NodeId, NodeMap, NodeSet};
50 use std::cell::RefCell;
51 use std::cmp::{self, Ordering};
53 use std::hash::{Hash, Hasher};
59 pub use self::sty::BoundRegion::*;
60 pub use self::sty::InferTy::*;
61 pub use self::sty::RegionKind;
62 pub use self::sty::RegionKind::*;
63 pub use self::sty::TyKind::*;
64 pub use self::sty::{Binder, BoundTy, BoundTyKind, BoundVar, DebruijnIndex, INNERMOST};
65 pub use self::sty::{BoundRegion, EarlyBoundRegion, FreeRegion, Region};
66 pub use self::sty::{CanonicalPolyFnSig, FnSig, GenSig, PolyFnSig, PolyGenSig};
67 pub use self::sty::{ClosureSubsts, GeneratorSubsts, TypeAndMut, UpvarSubsts};
68 pub use self::sty::{Const, ConstKind, ExistentialProjection, PolyExistentialProjection};
69 pub use self::sty::{ConstVid, FloatVid, IntVid, RegionVid, TyVid};
70 pub use self::sty::{ExistentialPredicate, InferConst, InferTy, ParamConst, ParamTy, ProjectionTy};
71 pub use self::sty::{ExistentialTraitRef, PolyExistentialTraitRef};
72 pub use self::sty::{PolyTraitRef, TraitRef, TyKind};
73 pub use crate::ty::diagnostics::*;
75 pub use self::binding::BindingMode;
76 pub use self::binding::BindingMode::*;
78 pub use self::context::{keep_local, tls, FreeRegionInfo, TyCtxt};
79 pub use self::context::{
80 CanonicalUserType, CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations, ResolvedOpaqueTy,
81 UserType, UserTypeAnnotationIndex,
83 pub use self::context::{
84 CtxtInterners, GeneratorInteriorTypeCause, GlobalCtxt, Lift, TypeckTables,
87 pub use self::instance::RESOLVE_INSTANCE;
88 pub use self::instance::{Instance, InstanceDef};
90 pub use self::trait_def::TraitDef;
92 pub use self::query::queries;
105 pub mod free_region_map;
106 pub mod inhabitedness;
108 pub mod normalize_erasing_regions;
122 mod structural_impls;
127 pub struct ResolverOutputs {
128 pub definitions: hir_map::Definitions,
129 pub cstore: Box<CrateStoreDyn>,
130 pub extern_crate_map: NodeMap<CrateNum>,
131 pub trait_map: TraitMap<NodeId>,
132 pub maybe_unused_trait_imports: NodeSet,
133 pub maybe_unused_extern_crates: Vec<(NodeId, Span)>,
134 pub export_map: ExportMap<NodeId>,
135 pub glob_map: GlobMap,
136 /// Extern prelude entries. The value is `true` if the entry was introduced
137 /// via `extern crate` item and not `--extern` option or compiler built-in.
138 pub extern_prelude: FxHashMap<Name, bool>,
141 #[derive(Clone, Copy, PartialEq, Eq, Debug, HashStable)]
142 pub enum AssocItemContainer {
143 TraitContainer(DefId),
144 ImplContainer(DefId),
147 impl AssocItemContainer {
148 /// Asserts that this is the `DefId` of an associated item declared
149 /// in a trait, and returns the trait `DefId`.
150 pub fn assert_trait(&self) -> DefId {
152 TraitContainer(id) => id,
153 _ => bug!("associated item has wrong container type: {:?}", self),
157 pub fn id(&self) -> DefId {
159 TraitContainer(id) => id,
160 ImplContainer(id) => id,
165 /// The "header" of an impl is everything outside the body: a Self type, a trait
166 /// ref (in the case of a trait impl), and a set of predicates (from the
167 /// bounds / where-clauses).
168 #[derive(Clone, Debug, TypeFoldable)]
169 pub struct ImplHeader<'tcx> {
170 pub impl_def_id: DefId,
171 pub self_ty: Ty<'tcx>,
172 pub trait_ref: Option<TraitRef<'tcx>>,
173 pub predicates: Vec<Predicate<'tcx>>,
176 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable)]
177 pub enum ImplPolarity {
178 /// `impl Trait for Type`
180 /// `impl !Trait for Type`
182 /// `#[rustc_reservation_impl] impl Trait for Type`
184 /// This is a "stability hack", not a real Rust feature.
185 /// See #64631 for details.
189 #[derive(Copy, Clone, Debug, PartialEq, HashStable)]
190 pub struct AssocItem {
192 #[stable_hasher(project(name))]
196 pub defaultness: hir::Defaultness,
197 pub container: AssocItemContainer,
199 /// Whether this is a method with an explicit self
200 /// as its first argument, allowing method calls.
201 pub method_has_self_argument: bool,
204 #[derive(Copy, Clone, PartialEq, Debug, HashStable)]
213 pub fn suggestion_descr(&self) -> &'static str {
215 ty::AssocKind::Method => "method call",
216 ty::AssocKind::Type | ty::AssocKind::OpaqueTy => "associated type",
217 ty::AssocKind::Const => "associated constant",
221 pub fn namespace(&self) -> Namespace {
223 ty::AssocKind::OpaqueTy | ty::AssocKind::Type => Namespace::TypeNS,
224 ty::AssocKind::Const | ty::AssocKind::Method => Namespace::ValueNS,
230 pub fn def_kind(&self) -> DefKind {
232 AssocKind::Const => DefKind::AssocConst,
233 AssocKind::Method => DefKind::Method,
234 AssocKind::Type => DefKind::AssocTy,
235 AssocKind::OpaqueTy => DefKind::AssocOpaqueTy,
239 /// Tests whether the associated item admits a non-trivial implementation
241 pub fn relevant_for_never(&self) -> bool {
243 AssocKind::OpaqueTy | AssocKind::Const | AssocKind::Type => true,
244 // FIXME(canndrew): Be more thorough here, check if any argument is uninhabited.
245 AssocKind::Method => !self.method_has_self_argument,
249 pub fn signature(&self, tcx: TyCtxt<'_>) -> String {
251 ty::AssocKind::Method => {
252 // We skip the binder here because the binder would deanonymize all
253 // late-bound regions, and we don't want method signatures to show up
254 // `as for<'r> fn(&'r MyType)`. Pretty-printing handles late-bound
255 // regions just fine, showing `fn(&MyType)`.
256 tcx.fn_sig(self.def_id).skip_binder().to_string()
258 ty::AssocKind::Type => format!("type {};", self.ident),
259 // FIXME(type_alias_impl_trait): we should print bounds here too.
260 ty::AssocKind::OpaqueTy => format!("type {};", self.ident),
261 ty::AssocKind::Const => {
262 format!("const {}: {:?};", self.ident, tcx.type_of(self.def_id))
268 /// A list of `ty::AssocItem`s in definition order that allows for efficient lookup by name.
270 /// When doing lookup by name, we try to postpone hygienic comparison for as long as possible since
271 /// it is relatively expensive. Instead, items are indexed by `Symbol` and hygienic comparison is
272 /// done only on items with the same name.
273 #[derive(Debug, Clone, PartialEq, HashStable)]
274 pub struct AssociatedItems {
275 items: SortedIndexMultiMap<u32, Symbol, ty::AssocItem>,
278 impl AssociatedItems {
279 /// Constructs an `AssociatedItems` map from a series of `ty::AssocItem`s in definition order.
280 pub fn new(items_in_def_order: impl IntoIterator<Item = ty::AssocItem>) -> Self {
281 let items = items_in_def_order.into_iter().map(|item| (item.ident.name, item)).collect();
282 AssociatedItems { items }
285 /// Returns a slice of associated items in the order they were defined.
287 /// New code should avoid relying on definition order. If you need a particular associated item
288 /// for a known trait, make that trait a lang item instead of indexing this array.
289 pub fn in_definition_order(&self) -> impl '_ + Iterator<Item = &ty::AssocItem> {
290 self.items.iter().map(|(_, v)| v)
293 /// Returns an iterator over all associated items with the given name, ignoring hygiene.
294 pub fn filter_by_name_unhygienic(
297 ) -> impl '_ + Iterator<Item = &ty::AssocItem> {
298 self.items.get_by_key(&name)
301 /// Returns an iterator over all associated items with the given name.
303 /// Multiple items may have the same name if they are in different `Namespace`s. For example,
304 /// an associated type can have the same name as a method. Use one of the `find_by_name_and_*`
305 /// methods below if you know which item you are looking for.
306 pub fn filter_by_name(
310 parent_def_id: DefId,
311 ) -> impl 'a + Iterator<Item = &'a ty::AssocItem> {
312 self.filter_by_name_unhygienic(ident.name)
313 .filter(move |item| tcx.hygienic_eq(ident, item.ident, parent_def_id))
316 /// Returns the associated item with the given name and `AssocKind`, if one exists.
317 pub fn find_by_name_and_kind(
322 parent_def_id: DefId,
323 ) -> Option<&ty::AssocItem> {
324 self.filter_by_name_unhygienic(ident.name)
325 .filter(|item| item.kind == kind)
326 .find(|item| tcx.hygienic_eq(ident, item.ident, parent_def_id))
329 /// Returns the associated item with the given name in the given `Namespace`, if one exists.
330 pub fn find_by_name_and_namespace(
335 parent_def_id: DefId,
336 ) -> Option<&ty::AssocItem> {
337 self.filter_by_name_unhygienic(ident.name)
338 .filter(|item| item.kind.namespace() == ns)
339 .find(|item| tcx.hygienic_eq(ident, item.ident, parent_def_id))
343 #[derive(Clone, Debug, PartialEq, Eq, Copy, RustcEncodable, RustcDecodable, HashStable)]
344 pub enum Visibility {
345 /// Visible everywhere (including in other crates).
347 /// Visible only in the given crate-local module.
349 /// Not visible anywhere in the local crate. This is the visibility of private external items.
353 pub trait DefIdTree: Copy {
354 fn parent(self, id: DefId) -> Option<DefId>;
356 fn is_descendant_of(self, mut descendant: DefId, ancestor: DefId) -> bool {
357 if descendant.krate != ancestor.krate {
361 while descendant != ancestor {
362 match self.parent(descendant) {
363 Some(parent) => descendant = parent,
364 None => return false,
371 impl<'tcx> DefIdTree for TyCtxt<'tcx> {
372 fn parent(self, id: DefId) -> Option<DefId> {
373 self.def_key(id).parent.map(|index| DefId { index: index, ..id })
378 pub fn from_hir(visibility: &hir::Visibility<'_>, id: hir::HirId, tcx: TyCtxt<'_>) -> Self {
379 match visibility.node {
380 hir::VisibilityKind::Public => Visibility::Public,
381 hir::VisibilityKind::Crate(_) => Visibility::Restricted(DefId::local(CRATE_DEF_INDEX)),
382 hir::VisibilityKind::Restricted { ref path, .. } => match path.res {
383 // If there is no resolution, `resolve` will have already reported an error, so
384 // assume that the visibility is public to avoid reporting more privacy errors.
385 Res::Err => Visibility::Public,
386 def => Visibility::Restricted(def.def_id()),
388 hir::VisibilityKind::Inherited => {
389 Visibility::Restricted(tcx.hir().get_module_parent(id))
394 /// Returns `true` if an item with this visibility is accessible from the given block.
395 pub fn is_accessible_from<T: DefIdTree>(self, module: DefId, tree: T) -> bool {
396 let restriction = match self {
397 // Public items are visible everywhere.
398 Visibility::Public => return true,
399 // Private items from other crates are visible nowhere.
400 Visibility::Invisible => return false,
401 // Restricted items are visible in an arbitrary local module.
402 Visibility::Restricted(other) if other.krate != module.krate => return false,
403 Visibility::Restricted(module) => module,
406 tree.is_descendant_of(module, restriction)
409 /// Returns `true` if this visibility is at least as accessible as the given visibility
410 pub fn is_at_least<T: DefIdTree>(self, vis: Visibility, tree: T) -> bool {
411 let vis_restriction = match vis {
412 Visibility::Public => return self == Visibility::Public,
413 Visibility::Invisible => return true,
414 Visibility::Restricted(module) => module,
417 self.is_accessible_from(vis_restriction, tree)
420 // Returns `true` if this item is visible anywhere in the local crate.
421 pub fn is_visible_locally(self) -> bool {
423 Visibility::Public => true,
424 Visibility::Restricted(def_id) => def_id.is_local(),
425 Visibility::Invisible => false,
430 #[derive(Copy, Clone, PartialEq, RustcDecodable, RustcEncodable, HashStable)]
432 Covariant, // T<A> <: T<B> iff A <: B -- e.g., function return type
433 Invariant, // T<A> <: T<B> iff B == A -- e.g., type of mutable cell
434 Contravariant, // T<A> <: T<B> iff B <: A -- e.g., function param type
435 Bivariant, // T<A> <: T<B> -- e.g., unused type parameter
438 /// The crate variances map is computed during typeck and contains the
439 /// variance of every item in the local crate. You should not use it
440 /// directly, because to do so will make your pass dependent on the
441 /// HIR of every item in the local crate. Instead, use
442 /// `tcx.variances_of()` to get the variance for a *particular*
444 #[derive(HashStable)]
445 pub struct CrateVariancesMap<'tcx> {
446 /// For each item with generics, maps to a vector of the variance
447 /// of its generics. If an item has no generics, it will have no
449 pub variances: FxHashMap<DefId, &'tcx [ty::Variance]>,
453 /// `a.xform(b)` combines the variance of a context with the
454 /// variance of a type with the following meaning. If we are in a
455 /// context with variance `a`, and we encounter a type argument in
456 /// a position with variance `b`, then `a.xform(b)` is the new
457 /// variance with which the argument appears.
463 /// Here, the "ambient" variance starts as covariant. `*mut T` is
464 /// invariant with respect to `T`, so the variance in which the
465 /// `Vec<i32>` appears is `Covariant.xform(Invariant)`, which
466 /// yields `Invariant`. Now, the type `Vec<T>` is covariant with
467 /// respect to its type argument `T`, and hence the variance of
468 /// the `i32` here is `Invariant.xform(Covariant)`, which results
469 /// (again) in `Invariant`.
473 /// fn(*const Vec<i32>, *mut Vec<i32)
475 /// The ambient variance is covariant. A `fn` type is
476 /// contravariant with respect to its parameters, so the variance
477 /// within which both pointer types appear is
478 /// `Covariant.xform(Contravariant)`, or `Contravariant`. `*const
479 /// T` is covariant with respect to `T`, so the variance within
480 /// which the first `Vec<i32>` appears is
481 /// `Contravariant.xform(Covariant)` or `Contravariant`. The same
482 /// is true for its `i32` argument. In the `*mut T` case, the
483 /// variance of `Vec<i32>` is `Contravariant.xform(Invariant)`,
484 /// and hence the outermost type is `Invariant` with respect to
485 /// `Vec<i32>` (and its `i32` argument).
487 /// Source: Figure 1 of "Taming the Wildcards:
488 /// Combining Definition- and Use-Site Variance" published in PLDI'11.
489 pub fn xform(self, v: ty::Variance) -> ty::Variance {
491 // Figure 1, column 1.
492 (ty::Covariant, ty::Covariant) => ty::Covariant,
493 (ty::Covariant, ty::Contravariant) => ty::Contravariant,
494 (ty::Covariant, ty::Invariant) => ty::Invariant,
495 (ty::Covariant, ty::Bivariant) => ty::Bivariant,
497 // Figure 1, column 2.
498 (ty::Contravariant, ty::Covariant) => ty::Contravariant,
499 (ty::Contravariant, ty::Contravariant) => ty::Covariant,
500 (ty::Contravariant, ty::Invariant) => ty::Invariant,
501 (ty::Contravariant, ty::Bivariant) => ty::Bivariant,
503 // Figure 1, column 3.
504 (ty::Invariant, _) => ty::Invariant,
506 // Figure 1, column 4.
507 (ty::Bivariant, _) => ty::Bivariant,
512 // Contains information needed to resolve types and (in the future) look up
513 // the types of AST nodes.
514 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
515 pub struct CReaderCacheKey {
520 // Flags that we track on types. These flags are propagated upwards
521 // through the type during type construction, so that we can quickly
522 // check whether the type has various kinds of types in it without
523 // recursing over the type itself.
525 pub struct TypeFlags: u32 {
526 const HAS_PARAMS = 1 << 0;
527 const HAS_TY_INFER = 1 << 1;
528 const HAS_RE_INFER = 1 << 2;
529 const HAS_RE_PLACEHOLDER = 1 << 3;
531 /// Does this have any `ReEarlyBound` regions? Used to
532 /// determine whether substitition is required, since those
533 /// represent regions that are bound in a `ty::Generics` and
534 /// hence may be substituted.
535 const HAS_RE_EARLY_BOUND = 1 << 4;
537 /// Does this have any region that "appears free" in the type?
538 /// Basically anything but `ReLateBound` and `ReErased`.
539 const HAS_FREE_REGIONS = 1 << 5;
541 /// Is an error type reachable?
542 const HAS_TY_ERR = 1 << 6;
543 const HAS_PROJECTION = 1 << 7;
545 // FIXME: Rename this to the actual property since it's used for generators too
546 const HAS_TY_CLOSURE = 1 << 8;
548 /// `true` if there are "names" of types and regions and so forth
549 /// that are local to a particular fn
550 const HAS_FREE_LOCAL_NAMES = 1 << 9;
552 /// Present if the type belongs in a local type context.
553 /// Only set for Infer other than Fresh.
554 const KEEP_IN_LOCAL_TCX = 1 << 10;
556 /// Does this have any `ReLateBound` regions? Used to check
557 /// if a global bound is safe to evaluate.
558 const HAS_RE_LATE_BOUND = 1 << 11;
560 /// Does this have any `ReErased` regions?
561 const HAS_RE_ERASED = 1 << 12;
563 const HAS_TY_PLACEHOLDER = 1 << 13;
565 const HAS_CT_INFER = 1 << 14;
566 const HAS_CT_PLACEHOLDER = 1 << 15;
567 /// Does this have any [Opaque] types.
568 const HAS_TY_OPAQUE = 1 << 16;
570 const NEEDS_SUBST = TypeFlags::HAS_PARAMS.bits |
571 TypeFlags::HAS_RE_EARLY_BOUND.bits;
573 /// Flags representing the nominal content of a type,
574 /// computed by FlagsComputation. If you add a new nominal
575 /// flag, it should be added here too.
576 const NOMINAL_FLAGS = TypeFlags::HAS_PARAMS.bits |
577 TypeFlags::HAS_TY_INFER.bits |
578 TypeFlags::HAS_RE_INFER.bits |
579 TypeFlags::HAS_RE_PLACEHOLDER.bits |
580 TypeFlags::HAS_RE_EARLY_BOUND.bits |
581 TypeFlags::HAS_FREE_REGIONS.bits |
582 TypeFlags::HAS_TY_ERR.bits |
583 TypeFlags::HAS_PROJECTION.bits |
584 TypeFlags::HAS_TY_CLOSURE.bits |
585 TypeFlags::HAS_FREE_LOCAL_NAMES.bits |
586 TypeFlags::KEEP_IN_LOCAL_TCX.bits |
587 TypeFlags::HAS_RE_LATE_BOUND.bits |
588 TypeFlags::HAS_RE_ERASED.bits |
589 TypeFlags::HAS_TY_PLACEHOLDER.bits |
590 TypeFlags::HAS_CT_INFER.bits |
591 TypeFlags::HAS_CT_PLACEHOLDER.bits |
592 TypeFlags::HAS_TY_OPAQUE.bits;
596 #[allow(rustc::usage_of_ty_tykind)]
597 pub struct TyS<'tcx> {
598 pub kind: TyKind<'tcx>,
599 pub flags: TypeFlags,
601 /// This is a kind of confusing thing: it stores the smallest
604 /// (a) the binder itself captures nothing but
605 /// (b) all the late-bound things within the type are captured
606 /// by some sub-binder.
608 /// So, for a type without any late-bound things, like `u32`, this
609 /// will be *innermost*, because that is the innermost binder that
610 /// captures nothing. But for a type `&'D u32`, where `'D` is a
611 /// late-bound region with De Bruijn index `D`, this would be `D + 1`
612 /// -- the binder itself does not capture `D`, but `D` is captured
613 /// by an inner binder.
615 /// We call this concept an "exclusive" binder `D` because all
616 /// De Bruijn indices within the type are contained within `0..D`
618 outer_exclusive_binder: ty::DebruijnIndex,
621 // `TyS` is used a lot. Make sure it doesn't unintentionally get bigger.
622 #[cfg(target_arch = "x86_64")]
623 static_assert_size!(TyS<'_>, 32);
625 impl<'tcx> Ord for TyS<'tcx> {
626 fn cmp(&self, other: &TyS<'tcx>) -> Ordering {
627 self.kind.cmp(&other.kind)
631 impl<'tcx> PartialOrd for TyS<'tcx> {
632 fn partial_cmp(&self, other: &TyS<'tcx>) -> Option<Ordering> {
633 Some(self.kind.cmp(&other.kind))
637 impl<'tcx> PartialEq for TyS<'tcx> {
639 fn eq(&self, other: &TyS<'tcx>) -> bool {
643 impl<'tcx> Eq for TyS<'tcx> {}
645 impl<'tcx> Hash for TyS<'tcx> {
646 fn hash<H: Hasher>(&self, s: &mut H) {
647 (self as *const TyS<'_>).hash(s)
651 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for ty::TyS<'tcx> {
652 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
656 // The other fields just provide fast access to information that is
657 // also contained in `kind`, so no need to hash them.
660 outer_exclusive_binder: _,
663 kind.hash_stable(hcx, hasher);
667 #[rustc_diagnostic_item = "Ty"]
668 pub type Ty<'tcx> = &'tcx TyS<'tcx>;
670 impl<'tcx> rustc_serialize::UseSpecializedEncodable for Ty<'tcx> {}
671 impl<'tcx> rustc_serialize::UseSpecializedDecodable for Ty<'tcx> {}
673 pub type CanonicalTy<'tcx> = Canonical<'tcx, Ty<'tcx>>;
676 /// A dummy type used to force `List` to be unsized while not requiring references to it be wide
678 type OpaqueListContents;
681 /// A wrapper for slices with the additional invariant
682 /// that the slice is interned and no other slice with
683 /// the same contents can exist in the same context.
684 /// This means we can use pointer for both
685 /// equality comparisons and hashing.
686 /// Note: `Slice` was already taken by the `Ty`.
691 opaque: OpaqueListContents,
694 unsafe impl<T: Sync> Sync for List<T> {}
696 impl<T: Copy> List<T> {
698 fn from_arena<'tcx>(arena: &'tcx Arena<'tcx>, slice: &[T]) -> &'tcx List<T> {
699 assert!(!mem::needs_drop::<T>());
700 assert!(mem::size_of::<T>() != 0);
701 assert!(slice.len() != 0);
703 // Align up the size of the len (usize) field
704 let align = mem::align_of::<T>();
705 let align_mask = align - 1;
706 let offset = mem::size_of::<usize>();
707 let offset = (offset + align_mask) & !align_mask;
709 let size = offset + slice.len() * mem::size_of::<T>();
713 .alloc_raw(size, cmp::max(mem::align_of::<T>(), mem::align_of::<usize>()));
715 let result = &mut *(mem.as_mut_ptr() as *mut List<T>);
717 result.len = slice.len();
719 // Write the elements
720 let arena_slice = slice::from_raw_parts_mut(result.data.as_mut_ptr(), result.len);
721 arena_slice.copy_from_slice(slice);
728 impl<T: fmt::Debug> fmt::Debug for List<T> {
729 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
734 impl<T: Encodable> Encodable for List<T> {
736 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
741 impl<T> Ord for List<T>
745 fn cmp(&self, other: &List<T>) -> Ordering {
746 if self == other { Ordering::Equal } else { <[T] as Ord>::cmp(&**self, &**other) }
750 impl<T> PartialOrd for List<T>
754 fn partial_cmp(&self, other: &List<T>) -> Option<Ordering> {
756 Some(Ordering::Equal)
758 <[T] as PartialOrd>::partial_cmp(&**self, &**other)
763 impl<T: PartialEq> PartialEq for List<T> {
765 fn eq(&self, other: &List<T>) -> bool {
769 impl<T: Eq> Eq for List<T> {}
771 impl<T> Hash for List<T> {
773 fn hash<H: Hasher>(&self, s: &mut H) {
774 (self as *const List<T>).hash(s)
778 impl<T> Deref for List<T> {
781 fn deref(&self) -> &[T] {
786 impl<T> AsRef<[T]> for List<T> {
788 fn as_ref(&self) -> &[T] {
789 unsafe { slice::from_raw_parts(self.data.as_ptr(), self.len) }
793 impl<'a, T> IntoIterator for &'a List<T> {
795 type IntoIter = <&'a [T] as IntoIterator>::IntoIter;
797 fn into_iter(self) -> Self::IntoIter {
802 impl<'tcx> rustc_serialize::UseSpecializedDecodable for &'tcx List<Ty<'tcx>> {}
806 pub fn empty<'a>() -> &'a List<T> {
807 #[repr(align(64), C)]
808 struct EmptySlice([u8; 64]);
809 static EMPTY_SLICE: EmptySlice = EmptySlice([0; 64]);
810 assert!(mem::align_of::<T>() <= 64);
811 unsafe { &*(&EMPTY_SLICE as *const _ as *const List<T>) }
815 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
816 pub struct UpvarPath {
817 pub hir_id: hir::HirId,
820 /// Upvars do not get their own `NodeId`. Instead, we use the pair of
821 /// the original var ID (that is, the root variable that is referenced
822 /// by the upvar) and the ID of the closure expression.
823 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
825 pub var_path: UpvarPath,
826 pub closure_expr_id: LocalDefId,
829 #[derive(Clone, PartialEq, Debug, RustcEncodable, RustcDecodable, Copy, HashStable)]
830 pub enum BorrowKind {
831 /// Data must be immutable and is aliasable.
834 /// Data must be immutable but not aliasable. This kind of borrow
835 /// cannot currently be expressed by the user and is used only in
836 /// implicit closure bindings. It is needed when the closure
837 /// is borrowing or mutating a mutable referent, e.g.:
839 /// let x: &mut isize = ...;
840 /// let y = || *x += 5;
842 /// If we were to try to translate this closure into a more explicit
843 /// form, we'd encounter an error with the code as written:
845 /// struct Env { x: & &mut isize }
846 /// let x: &mut isize = ...;
847 /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
848 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
850 /// This is then illegal because you cannot mutate a `&mut` found
851 /// in an aliasable location. To solve, you'd have to translate with
852 /// an `&mut` borrow:
854 /// struct Env { x: & &mut isize }
855 /// let x: &mut isize = ...;
856 /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
857 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
859 /// Now the assignment to `**env.x` is legal, but creating a
860 /// mutable pointer to `x` is not because `x` is not mutable. We
861 /// could fix this by declaring `x` as `let mut x`. This is ok in
862 /// user code, if awkward, but extra weird for closures, since the
863 /// borrow is hidden.
865 /// So we introduce a "unique imm" borrow -- the referent is
866 /// immutable, but not aliasable. This solves the problem. For
867 /// simplicity, we don't give users the way to express this
868 /// borrow, it's just used when translating closures.
871 /// Data is mutable and not aliasable.
875 /// Information describing the capture of an upvar. This is computed
876 /// during `typeck`, specifically by `regionck`.
877 #[derive(PartialEq, Clone, Debug, Copy, RustcEncodable, RustcDecodable, HashStable)]
878 pub enum UpvarCapture<'tcx> {
879 /// Upvar is captured by value. This is always true when the
880 /// closure is labeled `move`, but can also be true in other cases
881 /// depending on inference.
884 /// Upvar is captured by reference.
885 ByRef(UpvarBorrow<'tcx>),
888 #[derive(PartialEq, Clone, Copy, RustcEncodable, RustcDecodable, HashStable)]
889 pub struct UpvarBorrow<'tcx> {
890 /// The kind of borrow: by-ref upvars have access to shared
891 /// immutable borrows, which are not part of the normal language
893 pub kind: BorrowKind,
895 /// Region of the resulting reference.
896 pub region: ty::Region<'tcx>,
899 pub type UpvarListMap = FxHashMap<DefId, FxIndexMap<hir::HirId, UpvarId>>;
900 pub type UpvarCaptureMap<'tcx> = FxHashMap<UpvarId, UpvarCapture<'tcx>>;
902 #[derive(Clone, Copy, PartialEq, Eq)]
903 pub enum IntVarValue {
905 UintType(ast::UintTy),
908 #[derive(Clone, Copy, PartialEq, Eq)]
909 pub struct FloatVarValue(pub ast::FloatTy);
911 impl ty::EarlyBoundRegion {
912 pub fn to_bound_region(&self) -> ty::BoundRegion {
913 ty::BoundRegion::BrNamed(self.def_id, self.name)
916 /// Does this early bound region have a name? Early bound regions normally
917 /// always have names except when using anonymous lifetimes (`'_`).
918 pub fn has_name(&self) -> bool {
919 self.name != kw::UnderscoreLifetime
923 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
924 pub enum GenericParamDefKind {
928 object_lifetime_default: ObjectLifetimeDefault,
929 synthetic: Option<hir::SyntheticTyParamKind>,
934 impl GenericParamDefKind {
935 pub fn descr(&self) -> &'static str {
937 GenericParamDefKind::Lifetime => "lifetime",
938 GenericParamDefKind::Type { .. } => "type",
939 GenericParamDefKind::Const => "constant",
944 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
945 pub struct GenericParamDef {
950 /// `pure_wrt_drop`, set by the (unsafe) `#[may_dangle]` attribute
951 /// on generic parameter `'a`/`T`, asserts data behind the parameter
952 /// `'a`/`T` won't be accessed during the parent type's `Drop` impl.
953 pub pure_wrt_drop: bool,
955 pub kind: GenericParamDefKind,
958 impl GenericParamDef {
959 pub fn to_early_bound_region_data(&self) -> ty::EarlyBoundRegion {
960 if let GenericParamDefKind::Lifetime = self.kind {
961 ty::EarlyBoundRegion { def_id: self.def_id, index: self.index, name: self.name }
963 bug!("cannot convert a non-lifetime parameter def to an early bound region")
967 pub fn to_bound_region(&self) -> ty::BoundRegion {
968 if let GenericParamDefKind::Lifetime = self.kind {
969 self.to_early_bound_region_data().to_bound_region()
971 bug!("cannot convert a non-lifetime parameter def to an early bound region")
977 pub struct GenericParamCount {
978 pub lifetimes: usize,
983 /// Information about the formal type/lifetime parameters associated
984 /// with an item or method. Analogous to `hir::Generics`.
986 /// The ordering of parameters is the same as in `Subst` (excluding child generics):
987 /// `Self` (optionally), `Lifetime` params..., `Type` params...
988 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
989 pub struct Generics {
990 pub parent: Option<DefId>,
991 pub parent_count: usize,
992 pub params: Vec<GenericParamDef>,
994 /// Reverse map to the `index` field of each `GenericParamDef`.
995 #[stable_hasher(ignore)]
996 pub param_def_id_to_index: FxHashMap<DefId, u32>,
999 pub has_late_bound_regions: Option<Span>,
1002 impl<'tcx> Generics {
1003 pub fn count(&self) -> usize {
1004 self.parent_count + self.params.len()
1007 pub fn own_counts(&self) -> GenericParamCount {
1008 // We could cache this as a property of `GenericParamCount`, but
1009 // the aim is to refactor this away entirely eventually and the
1010 // presence of this method will be a constant reminder.
1011 let mut own_counts: GenericParamCount = Default::default();
1013 for param in &self.params {
1015 GenericParamDefKind::Lifetime => own_counts.lifetimes += 1,
1016 GenericParamDefKind::Type { .. } => own_counts.types += 1,
1017 GenericParamDefKind::Const => own_counts.consts += 1,
1024 pub fn requires_monomorphization(&self, tcx: TyCtxt<'tcx>) -> bool {
1025 if self.own_requires_monomorphization() {
1029 if let Some(parent_def_id) = self.parent {
1030 let parent = tcx.generics_of(parent_def_id);
1031 parent.requires_monomorphization(tcx)
1037 pub fn own_requires_monomorphization(&self) -> bool {
1038 for param in &self.params {
1040 GenericParamDefKind::Type { .. } | GenericParamDefKind::Const => return true,
1041 GenericParamDefKind::Lifetime => {}
1047 pub fn region_param(
1049 param: &EarlyBoundRegion,
1051 ) -> &'tcx GenericParamDef {
1052 if let Some(index) = param.index.checked_sub(self.parent_count as u32) {
1053 let param = &self.params[index as usize];
1055 GenericParamDefKind::Lifetime => param,
1056 _ => bug!("expected lifetime parameter, but found another generic parameter"),
1059 tcx.generics_of(self.parent.expect("parent_count > 0 but no parent?"))
1060 .region_param(param, tcx)
1064 /// Returns the `GenericParamDef` associated with this `ParamTy`.
1065 pub fn type_param(&'tcx self, param: &ParamTy, tcx: TyCtxt<'tcx>) -> &'tcx GenericParamDef {
1066 if let Some(index) = param.index.checked_sub(self.parent_count as u32) {
1067 let param = &self.params[index as usize];
1069 GenericParamDefKind::Type { .. } => param,
1070 _ => bug!("expected type parameter, but found another generic parameter"),
1073 tcx.generics_of(self.parent.expect("parent_count > 0 but no parent?"))
1074 .type_param(param, tcx)
1078 /// Returns the `ConstParameterDef` associated with this `ParamConst`.
1079 pub fn const_param(&'tcx self, param: &ParamConst, tcx: TyCtxt<'tcx>) -> &GenericParamDef {
1080 if let Some(index) = param.index.checked_sub(self.parent_count as u32) {
1081 let param = &self.params[index as usize];
1083 GenericParamDefKind::Const => param,
1084 _ => bug!("expected const parameter, but found another generic parameter"),
1087 tcx.generics_of(self.parent.expect("parent_count>0 but no parent?"))
1088 .const_param(param, tcx)
1093 /// Bounds on generics.
1094 #[derive(Copy, Clone, Default, Debug, RustcEncodable, RustcDecodable, HashStable)]
1095 pub struct GenericPredicates<'tcx> {
1096 pub parent: Option<DefId>,
1097 pub predicates: &'tcx [(Predicate<'tcx>, Span)],
1100 impl<'tcx> GenericPredicates<'tcx> {
1104 substs: SubstsRef<'tcx>,
1105 ) -> InstantiatedPredicates<'tcx> {
1106 let mut instantiated = InstantiatedPredicates::empty();
1107 self.instantiate_into(tcx, &mut instantiated, substs);
1111 pub fn instantiate_own(
1114 substs: SubstsRef<'tcx>,
1115 ) -> InstantiatedPredicates<'tcx> {
1116 InstantiatedPredicates {
1117 predicates: self.predicates.iter().map(|(p, _)| p.subst(tcx, substs)).collect(),
1118 spans: self.predicates.iter().map(|(_, sp)| *sp).collect(),
1122 fn instantiate_into(
1125 instantiated: &mut InstantiatedPredicates<'tcx>,
1126 substs: SubstsRef<'tcx>,
1128 if let Some(def_id) = self.parent {
1129 tcx.predicates_of(def_id).instantiate_into(tcx, instantiated, substs);
1131 instantiated.predicates.extend(self.predicates.iter().map(|(p, _)| p.subst(tcx, substs)));
1132 instantiated.spans.extend(self.predicates.iter().map(|(_, sp)| *sp));
1135 pub fn instantiate_identity(&self, tcx: TyCtxt<'tcx>) -> InstantiatedPredicates<'tcx> {
1136 let mut instantiated = InstantiatedPredicates::empty();
1137 self.instantiate_identity_into(tcx, &mut instantiated);
1141 fn instantiate_identity_into(
1144 instantiated: &mut InstantiatedPredicates<'tcx>,
1146 if let Some(def_id) = self.parent {
1147 tcx.predicates_of(def_id).instantiate_identity_into(tcx, instantiated);
1149 instantiated.predicates.extend(self.predicates.iter().map(|(p, _)| p));
1150 instantiated.spans.extend(self.predicates.iter().map(|(_, s)| s));
1153 pub fn instantiate_supertrait(
1156 poly_trait_ref: &ty::PolyTraitRef<'tcx>,
1157 ) -> InstantiatedPredicates<'tcx> {
1158 assert_eq!(self.parent, None);
1159 InstantiatedPredicates {
1163 .map(|(pred, _)| pred.subst_supertrait(tcx, poly_trait_ref))
1165 spans: self.predicates.iter().map(|(_, sp)| *sp).collect(),
1170 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1171 #[derive(HashStable, TypeFoldable)]
1172 pub enum Predicate<'tcx> {
1173 /// Corresponds to `where Foo: Bar<A, B, C>`. `Foo` here would be
1174 /// the `Self` type of the trait reference and `A`, `B`, and `C`
1175 /// would be the type parameters.
1177 /// A trait predicate will have `Constness::Const` if it originates
1178 /// from a bound on a `const fn` without the `?const` opt-out (e.g.,
1179 /// `const fn foobar<Foo: Bar>() {}`).
1180 Trait(PolyTraitPredicate<'tcx>, Constness),
1183 RegionOutlives(PolyRegionOutlivesPredicate<'tcx>),
1186 TypeOutlives(PolyTypeOutlivesPredicate<'tcx>),
1188 /// `where <T as TraitRef>::Name == X`, approximately.
1189 /// See the `ProjectionPredicate` struct for details.
1190 Projection(PolyProjectionPredicate<'tcx>),
1192 /// No syntax: `T` well-formed.
1193 WellFormed(Ty<'tcx>),
1195 /// Trait must be object-safe.
1198 /// No direct syntax. May be thought of as `where T: FnFoo<...>`
1199 /// for some substitutions `...` and `T` being a closure type.
1200 /// Satisfied (or refuted) once we know the closure's kind.
1201 ClosureKind(DefId, SubstsRef<'tcx>, ClosureKind),
1204 Subtype(PolySubtypePredicate<'tcx>),
1206 /// Constant initializer must evaluate successfully.
1207 ConstEvaluatable(DefId, SubstsRef<'tcx>),
1210 /// The crate outlives map is computed during typeck and contains the
1211 /// outlives of every item in the local crate. You should not use it
1212 /// directly, because to do so will make your pass dependent on the
1213 /// HIR of every item in the local crate. Instead, use
1214 /// `tcx.inferred_outlives_of()` to get the outlives for a *particular*
1216 #[derive(HashStable)]
1217 pub struct CratePredicatesMap<'tcx> {
1218 /// For each struct with outlive bounds, maps to a vector of the
1219 /// predicate of its outlive bounds. If an item has no outlives
1220 /// bounds, it will have no entry.
1221 pub predicates: FxHashMap<DefId, &'tcx [(ty::Predicate<'tcx>, Span)]>,
1224 impl<'tcx> AsRef<Predicate<'tcx>> for Predicate<'tcx> {
1225 fn as_ref(&self) -> &Predicate<'tcx> {
1230 impl<'tcx> Predicate<'tcx> {
1231 /// Performs a substitution suitable for going from a
1232 /// poly-trait-ref to supertraits that must hold if that
1233 /// poly-trait-ref holds. This is slightly different from a normal
1234 /// substitution in terms of what happens with bound regions. See
1235 /// lengthy comment below for details.
1236 pub fn subst_supertrait(
1239 trait_ref: &ty::PolyTraitRef<'tcx>,
1240 ) -> ty::Predicate<'tcx> {
1241 // The interaction between HRTB and supertraits is not entirely
1242 // obvious. Let me walk you (and myself) through an example.
1244 // Let's start with an easy case. Consider two traits:
1246 // trait Foo<'a>: Bar<'a,'a> { }
1247 // trait Bar<'b,'c> { }
1249 // Now, if we have a trait reference `for<'x> T: Foo<'x>`, then
1250 // we can deduce that `for<'x> T: Bar<'x,'x>`. Basically, if we
1251 // knew that `Foo<'x>` (for any 'x) then we also know that
1252 // `Bar<'x,'x>` (for any 'x). This more-or-less falls out from
1253 // normal substitution.
1255 // In terms of why this is sound, the idea is that whenever there
1256 // is an impl of `T:Foo<'a>`, it must show that `T:Bar<'a,'a>`
1257 // holds. So if there is an impl of `T:Foo<'a>` that applies to
1258 // all `'a`, then we must know that `T:Bar<'a,'a>` holds for all
1261 // Another example to be careful of is this:
1263 // trait Foo1<'a>: for<'b> Bar1<'a,'b> { }
1264 // trait Bar1<'b,'c> { }
1266 // Here, if we have `for<'x> T: Foo1<'x>`, then what do we know?
1267 // The answer is that we know `for<'x,'b> T: Bar1<'x,'b>`. The
1268 // reason is similar to the previous example: any impl of
1269 // `T:Foo1<'x>` must show that `for<'b> T: Bar1<'x, 'b>`. So
1270 // basically we would want to collapse the bound lifetimes from
1271 // the input (`trait_ref`) and the supertraits.
1273 // To achieve this in practice is fairly straightforward. Let's
1274 // consider the more complicated scenario:
1276 // - We start out with `for<'x> T: Foo1<'x>`. In this case, `'x`
1277 // has a De Bruijn index of 1. We want to produce `for<'x,'b> T: Bar1<'x,'b>`,
1278 // where both `'x` and `'b` would have a DB index of 1.
1279 // The substitution from the input trait-ref is therefore going to be
1280 // `'a => 'x` (where `'x` has a DB index of 1).
1281 // - The super-trait-ref is `for<'b> Bar1<'a,'b>`, where `'a` is an
1282 // early-bound parameter and `'b' is a late-bound parameter with a
1284 // - If we replace `'a` with `'x` from the input, it too will have
1285 // a DB index of 1, and thus we'll have `for<'x,'b> Bar1<'x,'b>`
1286 // just as we wanted.
1288 // There is only one catch. If we just apply the substitution `'a
1289 // => 'x` to `for<'b> Bar1<'a,'b>`, the substitution code will
1290 // adjust the DB index because we substituting into a binder (it
1291 // tries to be so smart...) resulting in `for<'x> for<'b>
1292 // Bar1<'x,'b>` (we have no syntax for this, so use your
1293 // imagination). Basically the 'x will have DB index of 2 and 'b
1294 // will have DB index of 1. Not quite what we want. So we apply
1295 // the substitution to the *contents* of the trait reference,
1296 // rather than the trait reference itself (put another way, the
1297 // substitution code expects equal binding levels in the values
1298 // from the substitution and the value being substituted into, and
1299 // this trick achieves that).
1301 let substs = &trait_ref.skip_binder().substs;
1303 Predicate::Trait(ref binder, constness) => {
1304 Predicate::Trait(binder.map_bound(|data| data.subst(tcx, substs)), constness)
1306 Predicate::Subtype(ref binder) => {
1307 Predicate::Subtype(binder.map_bound(|data| data.subst(tcx, substs)))
1309 Predicate::RegionOutlives(ref binder) => {
1310 Predicate::RegionOutlives(binder.map_bound(|data| data.subst(tcx, substs)))
1312 Predicate::TypeOutlives(ref binder) => {
1313 Predicate::TypeOutlives(binder.map_bound(|data| data.subst(tcx, substs)))
1315 Predicate::Projection(ref binder) => {
1316 Predicate::Projection(binder.map_bound(|data| data.subst(tcx, substs)))
1318 Predicate::WellFormed(data) => Predicate::WellFormed(data.subst(tcx, substs)),
1319 Predicate::ObjectSafe(trait_def_id) => Predicate::ObjectSafe(trait_def_id),
1320 Predicate::ClosureKind(closure_def_id, closure_substs, kind) => {
1321 Predicate::ClosureKind(closure_def_id, closure_substs.subst(tcx, substs), kind)
1323 Predicate::ConstEvaluatable(def_id, const_substs) => {
1324 Predicate::ConstEvaluatable(def_id, const_substs.subst(tcx, substs))
1330 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1331 #[derive(HashStable, TypeFoldable)]
1332 pub struct TraitPredicate<'tcx> {
1333 pub trait_ref: TraitRef<'tcx>,
1336 pub type PolyTraitPredicate<'tcx> = ty::Binder<TraitPredicate<'tcx>>;
1338 impl<'tcx> TraitPredicate<'tcx> {
1339 pub fn def_id(&self) -> DefId {
1340 self.trait_ref.def_id
1343 pub fn input_types<'a>(&'a self) -> impl DoubleEndedIterator<Item = Ty<'tcx>> + 'a {
1344 self.trait_ref.input_types()
1347 pub fn self_ty(&self) -> Ty<'tcx> {
1348 self.trait_ref.self_ty()
1352 impl<'tcx> PolyTraitPredicate<'tcx> {
1353 pub fn def_id(&self) -> DefId {
1354 // Ok to skip binder since trait `DefId` does not care about regions.
1355 self.skip_binder().def_id()
1359 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, RustcEncodable, RustcDecodable)]
1360 #[derive(HashStable, TypeFoldable)]
1361 pub struct OutlivesPredicate<A, B>(pub A, pub B); // `A: B`
1362 pub type PolyOutlivesPredicate<A, B> = ty::Binder<OutlivesPredicate<A, B>>;
1363 pub type RegionOutlivesPredicate<'tcx> = OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>;
1364 pub type TypeOutlivesPredicate<'tcx> = OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>;
1365 pub type PolyRegionOutlivesPredicate<'tcx> = ty::Binder<RegionOutlivesPredicate<'tcx>>;
1366 pub type PolyTypeOutlivesPredicate<'tcx> = ty::Binder<TypeOutlivesPredicate<'tcx>>;
1368 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
1369 #[derive(HashStable, TypeFoldable)]
1370 pub struct SubtypePredicate<'tcx> {
1371 pub a_is_expected: bool,
1375 pub type PolySubtypePredicate<'tcx> = ty::Binder<SubtypePredicate<'tcx>>;
1377 /// This kind of predicate has no *direct* correspondent in the
1378 /// syntax, but it roughly corresponds to the syntactic forms:
1380 /// 1. `T: TraitRef<..., Item = Type>`
1381 /// 2. `<T as TraitRef<...>>::Item == Type` (NYI)
1383 /// In particular, form #1 is "desugared" to the combination of a
1384 /// normal trait predicate (`T: TraitRef<...>`) and one of these
1385 /// predicates. Form #2 is a broader form in that it also permits
1386 /// equality between arbitrary types. Processing an instance of
1387 /// Form #2 eventually yields one of these `ProjectionPredicate`
1388 /// instances to normalize the LHS.
1389 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1390 #[derive(HashStable, TypeFoldable)]
1391 pub struct ProjectionPredicate<'tcx> {
1392 pub projection_ty: ProjectionTy<'tcx>,
1396 pub type PolyProjectionPredicate<'tcx> = Binder<ProjectionPredicate<'tcx>>;
1398 impl<'tcx> PolyProjectionPredicate<'tcx> {
1399 /// Returns the `DefId` of the associated item being projected.
1400 pub fn item_def_id(&self) -> DefId {
1401 self.skip_binder().projection_ty.item_def_id
1405 pub fn to_poly_trait_ref(&self, tcx: TyCtxt<'tcx>) -> PolyTraitRef<'tcx> {
1406 // Note: unlike with `TraitRef::to_poly_trait_ref()`,
1407 // `self.0.trait_ref` is permitted to have escaping regions.
1408 // This is because here `self` has a `Binder` and so does our
1409 // return value, so we are preserving the number of binding
1411 self.map_bound(|predicate| predicate.projection_ty.trait_ref(tcx))
1414 pub fn ty(&self) -> Binder<Ty<'tcx>> {
1415 self.map_bound(|predicate| predicate.ty)
1418 /// The `DefId` of the `TraitItem` for the associated type.
1420 /// Note that this is not the `DefId` of the `TraitRef` containing this
1421 /// associated type, which is in `tcx.associated_item(projection_def_id()).container`.
1422 pub fn projection_def_id(&self) -> DefId {
1423 // Ok to skip binder since trait `DefId` does not care about regions.
1424 self.skip_binder().projection_ty.item_def_id
1428 pub trait ToPolyTraitRef<'tcx> {
1429 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx>;
1432 impl<'tcx> ToPolyTraitRef<'tcx> for TraitRef<'tcx> {
1433 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
1434 ty::Binder::dummy(*self)
1438 impl<'tcx> ToPolyTraitRef<'tcx> for PolyTraitPredicate<'tcx> {
1439 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
1440 self.map_bound_ref(|trait_pred| trait_pred.trait_ref)
1444 pub trait ToPredicate<'tcx> {
1445 fn to_predicate(&self) -> Predicate<'tcx>;
1448 impl<'tcx> ToPredicate<'tcx> for ConstnessAnd<TraitRef<'tcx>> {
1449 fn to_predicate(&self) -> Predicate<'tcx> {
1450 ty::Predicate::Trait(
1451 ty::Binder::dummy(ty::TraitPredicate { trait_ref: self.value }),
1457 impl<'tcx> ToPredicate<'tcx> for ConstnessAnd<&TraitRef<'tcx>> {
1458 fn to_predicate(&self) -> Predicate<'tcx> {
1459 ty::Predicate::Trait(
1460 ty::Binder::dummy(ty::TraitPredicate { trait_ref: self.value.clone() }),
1466 impl<'tcx> ToPredicate<'tcx> for ConstnessAnd<PolyTraitRef<'tcx>> {
1467 fn to_predicate(&self) -> Predicate<'tcx> {
1468 ty::Predicate::Trait(self.value.to_poly_trait_predicate(), self.constness)
1472 impl<'tcx> ToPredicate<'tcx> for ConstnessAnd<&PolyTraitRef<'tcx>> {
1473 fn to_predicate(&self) -> Predicate<'tcx> {
1474 ty::Predicate::Trait(self.value.to_poly_trait_predicate(), self.constness)
1478 impl<'tcx> ToPredicate<'tcx> for PolyRegionOutlivesPredicate<'tcx> {
1479 fn to_predicate(&self) -> Predicate<'tcx> {
1480 Predicate::RegionOutlives(*self)
1484 impl<'tcx> ToPredicate<'tcx> for PolyTypeOutlivesPredicate<'tcx> {
1485 fn to_predicate(&self) -> Predicate<'tcx> {
1486 Predicate::TypeOutlives(*self)
1490 impl<'tcx> ToPredicate<'tcx> for PolyProjectionPredicate<'tcx> {
1491 fn to_predicate(&self) -> Predicate<'tcx> {
1492 Predicate::Projection(*self)
1496 // A custom iterator used by `Predicate::walk_tys`.
1497 enum WalkTysIter<'tcx, I, J, K>
1499 I: Iterator<Item = Ty<'tcx>>,
1500 J: Iterator<Item = Ty<'tcx>>,
1501 K: Iterator<Item = Ty<'tcx>>,
1505 Two(Ty<'tcx>, Ty<'tcx>),
1511 impl<'tcx, I, J, K> Iterator for WalkTysIter<'tcx, I, J, K>
1513 I: Iterator<Item = Ty<'tcx>>,
1514 J: Iterator<Item = Ty<'tcx>>,
1515 K: Iterator<Item = Ty<'tcx>>,
1517 type Item = Ty<'tcx>;
1519 fn next(&mut self) -> Option<Ty<'tcx>> {
1521 WalkTysIter::None => None,
1522 WalkTysIter::One(item) => {
1523 *self = WalkTysIter::None;
1526 WalkTysIter::Two(item1, item2) => {
1527 *self = WalkTysIter::One(item2);
1530 WalkTysIter::Types(ref mut iter) => iter.next(),
1531 WalkTysIter::InputTypes(ref mut iter) => iter.next(),
1532 WalkTysIter::ProjectionTypes(ref mut iter) => iter.next(),
1537 impl<'tcx> Predicate<'tcx> {
1538 /// Iterates over the types in this predicate. Note that in all
1539 /// cases this is skipping over a binder, so late-bound regions
1540 /// with depth 0 are bound by the predicate.
1541 pub fn walk_tys(&'a self) -> impl Iterator<Item = Ty<'tcx>> + 'a {
1543 ty::Predicate::Trait(ref data, _) => {
1544 WalkTysIter::InputTypes(data.skip_binder().input_types())
1546 ty::Predicate::Subtype(binder) => {
1547 let SubtypePredicate { a, b, a_is_expected: _ } = binder.skip_binder();
1548 WalkTysIter::Two(a, b)
1550 ty::Predicate::TypeOutlives(binder) => WalkTysIter::One(binder.skip_binder().0),
1551 ty::Predicate::RegionOutlives(..) => WalkTysIter::None,
1552 ty::Predicate::Projection(ref data) => {
1553 let inner = data.skip_binder();
1554 WalkTysIter::ProjectionTypes(
1555 inner.projection_ty.substs.types().chain(Some(inner.ty)),
1558 ty::Predicate::WellFormed(data) => WalkTysIter::One(data),
1559 ty::Predicate::ObjectSafe(_trait_def_id) => WalkTysIter::None,
1560 ty::Predicate::ClosureKind(_closure_def_id, closure_substs, _kind) => {
1561 WalkTysIter::Types(closure_substs.types())
1563 ty::Predicate::ConstEvaluatable(_, substs) => WalkTysIter::Types(substs.types()),
1567 pub fn to_opt_poly_trait_ref(&self) -> Option<PolyTraitRef<'tcx>> {
1569 Predicate::Trait(ref t, _) => Some(t.to_poly_trait_ref()),
1570 Predicate::Projection(..)
1571 | Predicate::Subtype(..)
1572 | Predicate::RegionOutlives(..)
1573 | Predicate::WellFormed(..)
1574 | Predicate::ObjectSafe(..)
1575 | Predicate::ClosureKind(..)
1576 | Predicate::TypeOutlives(..)
1577 | Predicate::ConstEvaluatable(..) => None,
1581 pub fn to_opt_type_outlives(&self) -> Option<PolyTypeOutlivesPredicate<'tcx>> {
1583 Predicate::TypeOutlives(data) => Some(data),
1584 Predicate::Trait(..)
1585 | Predicate::Projection(..)
1586 | Predicate::Subtype(..)
1587 | Predicate::RegionOutlives(..)
1588 | Predicate::WellFormed(..)
1589 | Predicate::ObjectSafe(..)
1590 | Predicate::ClosureKind(..)
1591 | Predicate::ConstEvaluatable(..) => None,
1596 /// Represents the bounds declared on a particular set of type
1597 /// parameters. Should eventually be generalized into a flag list of
1598 /// where-clauses. You can obtain a `InstantiatedPredicates` list from a
1599 /// `GenericPredicates` by using the `instantiate` method. Note that this method
1600 /// reflects an important semantic invariant of `InstantiatedPredicates`: while
1601 /// the `GenericPredicates` are expressed in terms of the bound type
1602 /// parameters of the impl/trait/whatever, an `InstantiatedPredicates` instance
1603 /// represented a set of bounds for some particular instantiation,
1604 /// meaning that the generic parameters have been substituted with
1609 /// struct Foo<T, U: Bar<T>> { ... }
1611 /// Here, the `GenericPredicates` for `Foo` would contain a list of bounds like
1612 /// `[[], [U:Bar<T>]]`. Now if there were some particular reference
1613 /// like `Foo<isize,usize>`, then the `InstantiatedPredicates` would be `[[],
1614 /// [usize:Bar<isize>]]`.
1615 #[derive(Clone, Debug, TypeFoldable)]
1616 pub struct InstantiatedPredicates<'tcx> {
1617 pub predicates: Vec<Predicate<'tcx>>,
1618 pub spans: Vec<Span>,
1621 impl<'tcx> InstantiatedPredicates<'tcx> {
1622 pub fn empty() -> InstantiatedPredicates<'tcx> {
1623 InstantiatedPredicates { predicates: vec![], spans: vec![] }
1626 pub fn is_empty(&self) -> bool {
1627 self.predicates.is_empty()
1631 rustc_index::newtype_index! {
1632 /// "Universes" are used during type- and trait-checking in the
1633 /// presence of `for<..>` binders to control what sets of names are
1634 /// visible. Universes are arranged into a tree: the root universe
1635 /// contains names that are always visible. Each child then adds a new
1636 /// set of names that are visible, in addition to those of its parent.
1637 /// We say that the child universe "extends" the parent universe with
1640 /// To make this more concrete, consider this program:
1644 /// fn bar<T>(x: T) {
1645 /// let y: for<'a> fn(&'a u8, Foo) = ...;
1649 /// The struct name `Foo` is in the root universe U0. But the type
1650 /// parameter `T`, introduced on `bar`, is in an extended universe U1
1651 /// -- i.e., within `bar`, we can name both `T` and `Foo`, but outside
1652 /// of `bar`, we cannot name `T`. Then, within the type of `y`, the
1653 /// region `'a` is in a universe U2 that extends U1, because we can
1654 /// name it inside the fn type but not outside.
1656 /// Universes are used to do type- and trait-checking around these
1657 /// "forall" binders (also called **universal quantification**). The
1658 /// idea is that when, in the body of `bar`, we refer to `T` as a
1659 /// type, we aren't referring to any type in particular, but rather a
1660 /// kind of "fresh" type that is distinct from all other types we have
1661 /// actually declared. This is called a **placeholder** type, and we
1662 /// use universes to talk about this. In other words, a type name in
1663 /// universe 0 always corresponds to some "ground" type that the user
1664 /// declared, but a type name in a non-zero universe is a placeholder
1665 /// type -- an idealized representative of "types in general" that we
1666 /// use for checking generic functions.
1667 pub struct UniverseIndex {
1669 DEBUG_FORMAT = "U{}",
1673 impl UniverseIndex {
1674 pub const ROOT: UniverseIndex = UniverseIndex::from_u32_const(0);
1676 /// Returns the "next" universe index in order -- this new index
1677 /// is considered to extend all previous universes. This
1678 /// corresponds to entering a `forall` quantifier. So, for
1679 /// example, suppose we have this type in universe `U`:
1682 /// for<'a> fn(&'a u32)
1685 /// Once we "enter" into this `for<'a>` quantifier, we are in a
1686 /// new universe that extends `U` -- in this new universe, we can
1687 /// name the region `'a`, but that region was not nameable from
1688 /// `U` because it was not in scope there.
1689 pub fn next_universe(self) -> UniverseIndex {
1690 UniverseIndex::from_u32(self.private.checked_add(1).unwrap())
1693 /// Returns `true` if `self` can name a name from `other` -- in other words,
1694 /// if the set of names in `self` is a superset of those in
1695 /// `other` (`self >= other`).
1696 pub fn can_name(self, other: UniverseIndex) -> bool {
1697 self.private >= other.private
1700 /// Returns `true` if `self` cannot name some names from `other` -- in other
1701 /// words, if the set of names in `self` is a strict subset of
1702 /// those in `other` (`self < other`).
1703 pub fn cannot_name(self, other: UniverseIndex) -> bool {
1704 self.private < other.private
1708 /// The "placeholder index" fully defines a placeholder region.
1709 /// Placeholder regions are identified by both a **universe** as well
1710 /// as a "bound-region" within that universe. The `bound_region` is
1711 /// basically a name -- distinct bound regions within the same
1712 /// universe are just two regions with an unknown relationship to one
1714 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, PartialOrd, Ord)]
1715 pub struct Placeholder<T> {
1716 pub universe: UniverseIndex,
1720 impl<'a, T> HashStable<StableHashingContext<'a>> for Placeholder<T>
1722 T: HashStable<StableHashingContext<'a>>,
1724 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
1725 self.universe.hash_stable(hcx, hasher);
1726 self.name.hash_stable(hcx, hasher);
1730 pub type PlaceholderRegion = Placeholder<BoundRegion>;
1732 pub type PlaceholderType = Placeholder<BoundVar>;
1734 pub type PlaceholderConst = Placeholder<BoundVar>;
1736 /// When type checking, we use the `ParamEnv` to track
1737 /// details about the set of where-clauses that are in scope at this
1738 /// particular point.
1739 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable, TypeFoldable)]
1740 pub struct ParamEnv<'tcx> {
1741 /// `Obligation`s that the caller must satisfy. This is basically
1742 /// the set of bounds on the in-scope type parameters, translated
1743 /// into `Obligation`s, and elaborated and normalized.
1744 pub caller_bounds: &'tcx List<ty::Predicate<'tcx>>,
1746 /// Typically, this is `Reveal::UserFacing`, but during codegen we
1747 /// want `Reveal::All` -- note that this is always paired with an
1748 /// empty environment. To get that, use `ParamEnv::reveal()`.
1749 pub reveal: traits::Reveal,
1751 /// If this `ParamEnv` comes from a call to `tcx.param_env(def_id)`,
1752 /// register that `def_id` (useful for transitioning to the chalk trait
1754 pub def_id: Option<DefId>,
1757 impl<'tcx> ParamEnv<'tcx> {
1758 /// Construct a trait environment suitable for contexts where
1759 /// there are no where-clauses in scope. Hidden types (like `impl
1760 /// Trait`) are left hidden, so this is suitable for ordinary
1763 pub fn empty() -> Self {
1764 Self::new(List::empty(), Reveal::UserFacing, None)
1767 /// Construct a trait environment with no where-clauses in scope
1768 /// where the values of all `impl Trait` and other hidden types
1769 /// are revealed. This is suitable for monomorphized, post-typeck
1770 /// environments like codegen or doing optimizations.
1772 /// N.B., if you want to have predicates in scope, use `ParamEnv::new`,
1773 /// or invoke `param_env.with_reveal_all()`.
1775 pub fn reveal_all() -> Self {
1776 Self::new(List::empty(), Reveal::All, None)
1779 /// Construct a trait environment with the given set of predicates.
1782 caller_bounds: &'tcx List<ty::Predicate<'tcx>>,
1784 def_id: Option<DefId>,
1786 ty::ParamEnv { caller_bounds, reveal, def_id }
1789 /// Returns a new parameter environment with the same clauses, but
1790 /// which "reveals" the true results of projections in all cases
1791 /// (even for associated types that are specializable). This is
1792 /// the desired behavior during codegen and certain other special
1793 /// contexts; normally though we want to use `Reveal::UserFacing`,
1794 /// which is the default.
1795 pub fn with_reveal_all(self) -> Self {
1796 ty::ParamEnv { reveal: Reveal::All, ..self }
1799 /// Returns this same environment but with no caller bounds.
1800 pub fn without_caller_bounds(self) -> Self {
1801 ty::ParamEnv { caller_bounds: List::empty(), ..self }
1804 /// Creates a suitable environment in which to perform trait
1805 /// queries on the given value. When type-checking, this is simply
1806 /// the pair of the environment plus value. But when reveal is set to
1807 /// All, then if `value` does not reference any type parameters, we will
1808 /// pair it with the empty environment. This improves caching and is generally
1811 /// N.B., we preserve the environment when type-checking because it
1812 /// is possible for the user to have wacky where-clauses like
1813 /// `where Box<u32>: Copy`, which are clearly never
1814 /// satisfiable. We generally want to behave as if they were true,
1815 /// although the surrounding function is never reachable.
1816 pub fn and<T: TypeFoldable<'tcx>>(self, value: T) -> ParamEnvAnd<'tcx, T> {
1818 Reveal::UserFacing => ParamEnvAnd { param_env: self, value },
1821 if value.has_placeholders() || value.needs_infer() || value.has_param_types() {
1822 ParamEnvAnd { param_env: self, value }
1824 ParamEnvAnd { param_env: self.without_caller_bounds(), value }
1831 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1832 pub struct ConstnessAnd<T> {
1833 pub constness: Constness,
1837 // FIXME(ecstaticmorse): Audit all occurrences of `without_const().to_predicate()` to ensure that
1838 // the constness of trait bounds is being propagated correctly.
1839 pub trait WithConstness: Sized {
1841 fn with_constness(self, constness: Constness) -> ConstnessAnd<Self> {
1842 ConstnessAnd { constness, value: self }
1846 fn with_const(self) -> ConstnessAnd<Self> {
1847 self.with_constness(Constness::Const)
1851 fn without_const(self) -> ConstnessAnd<Self> {
1852 self.with_constness(Constness::NotConst)
1856 impl<T> WithConstness for T {}
1858 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TypeFoldable)]
1859 pub struct ParamEnvAnd<'tcx, T> {
1860 pub param_env: ParamEnv<'tcx>,
1864 impl<'tcx, T> ParamEnvAnd<'tcx, T> {
1865 pub fn into_parts(self) -> (ParamEnv<'tcx>, T) {
1866 (self.param_env, self.value)
1870 impl<'a, 'tcx, T> HashStable<StableHashingContext<'a>> for ParamEnvAnd<'tcx, T>
1872 T: HashStable<StableHashingContext<'a>>,
1874 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
1875 let ParamEnvAnd { ref param_env, ref value } = *self;
1877 param_env.hash_stable(hcx, hasher);
1878 value.hash_stable(hcx, hasher);
1882 #[derive(Copy, Clone, Debug, HashStable)]
1883 pub struct Destructor {
1884 /// The `DefId` of the destructor method
1889 #[derive(HashStable)]
1890 pub struct AdtFlags: u32 {
1891 const NO_ADT_FLAGS = 0;
1892 /// Indicates whether the ADT is an enum.
1893 const IS_ENUM = 1 << 0;
1894 /// Indicates whether the ADT is a union.
1895 const IS_UNION = 1 << 1;
1896 /// Indicates whether the ADT is a struct.
1897 const IS_STRUCT = 1 << 2;
1898 /// Indicates whether the ADT is a struct and has a constructor.
1899 const HAS_CTOR = 1 << 3;
1900 /// Indicates whether the type is `PhantomData`.
1901 const IS_PHANTOM_DATA = 1 << 4;
1902 /// Indicates whether the type has a `#[fundamental]` attribute.
1903 const IS_FUNDAMENTAL = 1 << 5;
1904 /// Indicates whether the type is `Box`.
1905 const IS_BOX = 1 << 6;
1906 /// Indicates whether the type is `ManuallyDrop`.
1907 const IS_MANUALLY_DROP = 1 << 7;
1908 // FIXME(matthewjasper) replace these with diagnostic items
1909 /// Indicates whether the type is an `Arc`.
1910 const IS_ARC = 1 << 8;
1911 /// Indicates whether the type is an `Rc`.
1912 const IS_RC = 1 << 9;
1913 /// Indicates whether the variant list of this ADT is `#[non_exhaustive]`.
1914 /// (i.e., this flag is never set unless this ADT is an enum).
1915 const IS_VARIANT_LIST_NON_EXHAUSTIVE = 1 << 10;
1920 #[derive(HashStable)]
1921 pub struct VariantFlags: u32 {
1922 const NO_VARIANT_FLAGS = 0;
1923 /// Indicates whether the field list of this variant is `#[non_exhaustive]`.
1924 const IS_FIELD_LIST_NON_EXHAUSTIVE = 1 << 0;
1928 /// Definition of a variant -- a struct's fields or a enum variant.
1929 #[derive(Debug, HashStable)]
1930 pub struct VariantDef {
1931 /// `DefId` that identifies the variant itself.
1932 /// If this variant belongs to a struct or union, then this is a copy of its `DefId`.
1934 /// `DefId` that identifies the variant's constructor.
1935 /// If this variant is a struct variant, then this is `None`.
1936 pub ctor_def_id: Option<DefId>,
1937 /// Variant or struct name.
1938 #[stable_hasher(project(name))]
1940 /// Discriminant of this variant.
1941 pub discr: VariantDiscr,
1942 /// Fields of this variant.
1943 pub fields: Vec<FieldDef>,
1944 /// Type of constructor of variant.
1945 pub ctor_kind: CtorKind,
1946 /// Flags of the variant (e.g. is field list non-exhaustive)?
1947 flags: VariantFlags,
1948 /// Variant is obtained as part of recovering from a syntactic error.
1949 /// May be incomplete or bogus.
1950 pub recovered: bool,
1953 impl<'tcx> VariantDef {
1954 /// Creates a new `VariantDef`.
1956 /// `variant_did` is the `DefId` that identifies the enum variant (if this `VariantDef`
1957 /// represents an enum variant).
1959 /// `ctor_did` is the `DefId` that identifies the constructor of unit or
1960 /// tuple-variants/structs. If this is a `struct`-variant then this should be `None`.
1962 /// `parent_did` is the `DefId` of the `AdtDef` representing the enum or struct that
1963 /// owns this variant. It is used for checking if a struct has `#[non_exhaustive]` w/out having
1964 /// to go through the redirect of checking the ctor's attributes - but compiling a small crate
1965 /// requires loading the `AdtDef`s for all the structs in the universe (e.g., coherence for any
1966 /// built-in trait), and we do not want to load attributes twice.
1968 /// If someone speeds up attribute loading to not be a performance concern, they can
1969 /// remove this hack and use the constructor `DefId` everywhere.
1973 variant_did: Option<DefId>,
1974 ctor_def_id: Option<DefId>,
1975 discr: VariantDiscr,
1976 fields: Vec<FieldDef>,
1977 ctor_kind: CtorKind,
1983 "VariantDef::new(ident = {:?}, variant_did = {:?}, ctor_def_id = {:?}, discr = {:?},
1984 fields = {:?}, ctor_kind = {:?}, adt_kind = {:?}, parent_did = {:?})",
1985 ident, variant_did, ctor_def_id, discr, fields, ctor_kind, adt_kind, parent_did,
1988 let mut flags = VariantFlags::NO_VARIANT_FLAGS;
1989 if adt_kind == AdtKind::Struct && tcx.has_attr(parent_did, sym::non_exhaustive) {
1990 debug!("found non-exhaustive field list for {:?}", parent_did);
1991 flags = flags | VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE;
1992 } else if let Some(variant_did) = variant_did {
1993 if tcx.has_attr(variant_did, sym::non_exhaustive) {
1994 debug!("found non-exhaustive field list for {:?}", variant_did);
1995 flags = flags | VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE;
2000 def_id: variant_did.unwrap_or(parent_did),
2011 /// Is this field list non-exhaustive?
2013 pub fn is_field_list_non_exhaustive(&self) -> bool {
2014 self.flags.intersects(VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE)
2018 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2019 pub enum VariantDiscr {
2020 /// Explicit value for this variant, i.e., `X = 123`.
2021 /// The `DefId` corresponds to the embedded constant.
2024 /// The previous variant's discriminant plus one.
2025 /// For efficiency reasons, the distance from the
2026 /// last `Explicit` discriminant is being stored,
2027 /// or `0` for the first variant, if it has none.
2031 #[derive(Debug, HashStable)]
2032 pub struct FieldDef {
2034 #[stable_hasher(project(name))]
2036 pub vis: Visibility,
2039 /// The definition of a user-defined type, e.g., a `struct`, `enum`, or `union`.
2041 /// These are all interned (by `intern_adt_def`) into the `adt_defs` table.
2043 /// The initialism *ADT* stands for an [*algebraic data type (ADT)*][adt].
2044 /// This is slightly wrong because `union`s are not ADTs.
2045 /// Moreover, Rust only allows recursive data types through indirection.
2047 /// [adt]: https://en.wikipedia.org/wiki/Algebraic_data_type
2049 /// The `DefId` of the struct, enum or union item.
2051 /// Variants of the ADT. If this is a struct or union, then there will be a single variant.
2052 pub variants: IndexVec<self::layout::VariantIdx, VariantDef>,
2053 /// Flags of the ADT (e.g., is this a struct? is this non-exhaustive?).
2055 /// Repr options provided by the user.
2056 pub repr: ReprOptions,
2059 impl PartialOrd for AdtDef {
2060 fn partial_cmp(&self, other: &AdtDef) -> Option<Ordering> {
2061 Some(self.cmp(&other))
2065 /// There should be only one AdtDef for each `did`, therefore
2066 /// it is fine to implement `Ord` only based on `did`.
2067 impl Ord for AdtDef {
2068 fn cmp(&self, other: &AdtDef) -> Ordering {
2069 self.did.cmp(&other.did)
2073 impl PartialEq for AdtDef {
2074 // `AdtDef`s are always interned, and this is part of `TyS` equality.
2076 fn eq(&self, other: &Self) -> bool {
2077 ptr::eq(self, other)
2081 impl Eq for AdtDef {}
2083 impl Hash for AdtDef {
2085 fn hash<H: Hasher>(&self, s: &mut H) {
2086 (self as *const AdtDef).hash(s)
2090 impl<'tcx> rustc_serialize::UseSpecializedEncodable for &'tcx AdtDef {
2091 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
2096 impl<'tcx> rustc_serialize::UseSpecializedDecodable for &'tcx AdtDef {}
2098 impl<'a> HashStable<StableHashingContext<'a>> for AdtDef {
2099 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
2101 static CACHE: RefCell<FxHashMap<usize, Fingerprint>> = Default::default();
2104 let hash: Fingerprint = CACHE.with(|cache| {
2105 let addr = self as *const AdtDef as usize;
2106 *cache.borrow_mut().entry(addr).or_insert_with(|| {
2107 let ty::AdtDef { did, ref variants, ref flags, ref repr } = *self;
2109 let mut hasher = StableHasher::new();
2110 did.hash_stable(hcx, &mut hasher);
2111 variants.hash_stable(hcx, &mut hasher);
2112 flags.hash_stable(hcx, &mut hasher);
2113 repr.hash_stable(hcx, &mut hasher);
2119 hash.hash_stable(hcx, hasher);
2123 #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
2130 impl Into<DataTypeKind> for AdtKind {
2131 fn into(self) -> DataTypeKind {
2133 AdtKind::Struct => DataTypeKind::Struct,
2134 AdtKind::Union => DataTypeKind::Union,
2135 AdtKind::Enum => DataTypeKind::Enum,
2141 #[derive(RustcEncodable, RustcDecodable, Default, HashStable)]
2142 pub struct ReprFlags: u8 {
2143 const IS_C = 1 << 0;
2144 const IS_SIMD = 1 << 1;
2145 const IS_TRANSPARENT = 1 << 2;
2146 // Internal only for now. If true, don't reorder fields.
2147 const IS_LINEAR = 1 << 3;
2148 // If true, don't expose any niche to type's context.
2149 const HIDE_NICHE = 1 << 4;
2150 // Any of these flags being set prevent field reordering optimisation.
2151 const IS_UNOPTIMISABLE = ReprFlags::IS_C.bits |
2152 ReprFlags::IS_SIMD.bits |
2153 ReprFlags::IS_LINEAR.bits;
2157 /// Represents the repr options provided by the user,
2158 #[derive(Copy, Clone, Debug, Eq, PartialEq, RustcEncodable, RustcDecodable, Default, HashStable)]
2159 pub struct ReprOptions {
2160 pub int: Option<attr::IntType>,
2161 pub align: Option<Align>,
2162 pub pack: Option<Align>,
2163 pub flags: ReprFlags,
2167 pub fn new(tcx: TyCtxt<'_>, did: DefId) -> ReprOptions {
2168 let mut flags = ReprFlags::empty();
2169 let mut size = None;
2170 let mut max_align: Option<Align> = None;
2171 let mut min_pack: Option<Align> = None;
2172 for attr in tcx.get_attrs(did).iter() {
2173 for r in attr::find_repr_attrs(&tcx.sess.parse_sess, attr) {
2174 flags.insert(match r {
2175 attr::ReprC => ReprFlags::IS_C,
2176 attr::ReprPacked(pack) => {
2177 let pack = Align::from_bytes(pack as u64).unwrap();
2178 min_pack = Some(if let Some(min_pack) = min_pack {
2185 attr::ReprTransparent => ReprFlags::IS_TRANSPARENT,
2186 attr::ReprNoNiche => ReprFlags::HIDE_NICHE,
2187 attr::ReprSimd => ReprFlags::IS_SIMD,
2188 attr::ReprInt(i) => {
2192 attr::ReprAlign(align) => {
2193 max_align = max_align.max(Some(Align::from_bytes(align as u64).unwrap()));
2200 // This is here instead of layout because the choice must make it into metadata.
2201 if !tcx.consider_optimizing(|| format!("Reorder fields of {:?}", tcx.def_path_str(did))) {
2202 flags.insert(ReprFlags::IS_LINEAR);
2204 ReprOptions { int: size, align: max_align, pack: min_pack, flags: flags }
2208 pub fn simd(&self) -> bool {
2209 self.flags.contains(ReprFlags::IS_SIMD)
2212 pub fn c(&self) -> bool {
2213 self.flags.contains(ReprFlags::IS_C)
2216 pub fn packed(&self) -> bool {
2220 pub fn transparent(&self) -> bool {
2221 self.flags.contains(ReprFlags::IS_TRANSPARENT)
2224 pub fn linear(&self) -> bool {
2225 self.flags.contains(ReprFlags::IS_LINEAR)
2228 pub fn hide_niche(&self) -> bool {
2229 self.flags.contains(ReprFlags::HIDE_NICHE)
2232 pub fn discr_type(&self) -> attr::IntType {
2233 self.int.unwrap_or(attr::SignedInt(ast::IntTy::Isize))
2236 /// Returns `true` if this `#[repr()]` should inhabit "smart enum
2237 /// layout" optimizations, such as representing `Foo<&T>` as a
2239 pub fn inhibit_enum_layout_opt(&self) -> bool {
2240 self.c() || self.int.is_some()
2243 /// Returns `true` if this `#[repr()]` should inhibit struct field reordering
2244 /// optimizations, such as with `repr(C)`, `repr(packed(1))`, or `repr(<int>)`.
2245 pub fn inhibit_struct_field_reordering_opt(&self) -> bool {
2246 if let Some(pack) = self.pack {
2247 if pack.bytes() == 1 {
2251 self.flags.intersects(ReprFlags::IS_UNOPTIMISABLE) || self.int.is_some()
2254 /// Returns `true` if this `#[repr()]` should inhibit union ABI optimisations.
2255 pub fn inhibit_union_abi_opt(&self) -> bool {
2261 /// Creates a new `AdtDef`.
2266 variants: IndexVec<VariantIdx, VariantDef>,
2269 debug!("AdtDef::new({:?}, {:?}, {:?}, {:?})", did, kind, variants, repr);
2270 let mut flags = AdtFlags::NO_ADT_FLAGS;
2272 if kind == AdtKind::Enum && tcx.has_attr(did, sym::non_exhaustive) {
2273 debug!("found non-exhaustive variant list for {:?}", did);
2274 flags = flags | AdtFlags::IS_VARIANT_LIST_NON_EXHAUSTIVE;
2277 flags |= match kind {
2278 AdtKind::Enum => AdtFlags::IS_ENUM,
2279 AdtKind::Union => AdtFlags::IS_UNION,
2280 AdtKind::Struct => AdtFlags::IS_STRUCT,
2283 if kind == AdtKind::Struct && variants[VariantIdx::new(0)].ctor_def_id.is_some() {
2284 flags |= AdtFlags::HAS_CTOR;
2287 let attrs = tcx.get_attrs(did);
2288 if attr::contains_name(&attrs, sym::fundamental) {
2289 flags |= AdtFlags::IS_FUNDAMENTAL;
2291 if Some(did) == tcx.lang_items().phantom_data() {
2292 flags |= AdtFlags::IS_PHANTOM_DATA;
2294 if Some(did) == tcx.lang_items().owned_box() {
2295 flags |= AdtFlags::IS_BOX;
2297 if Some(did) == tcx.lang_items().manually_drop() {
2298 flags |= AdtFlags::IS_MANUALLY_DROP;
2300 if Some(did) == tcx.lang_items().arc() {
2301 flags |= AdtFlags::IS_ARC;
2303 if Some(did) == tcx.lang_items().rc() {
2304 flags |= AdtFlags::IS_RC;
2307 AdtDef { did, variants, flags, repr }
2310 /// Returns `true` if this is a struct.
2312 pub fn is_struct(&self) -> bool {
2313 self.flags.contains(AdtFlags::IS_STRUCT)
2316 /// Returns `true` if this is a union.
2318 pub fn is_union(&self) -> bool {
2319 self.flags.contains(AdtFlags::IS_UNION)
2322 /// Returns `true` if this is a enum.
2324 pub fn is_enum(&self) -> bool {
2325 self.flags.contains(AdtFlags::IS_ENUM)
2328 /// Returns `true` if the variant list of this ADT is `#[non_exhaustive]`.
2330 pub fn is_variant_list_non_exhaustive(&self) -> bool {
2331 self.flags.contains(AdtFlags::IS_VARIANT_LIST_NON_EXHAUSTIVE)
2334 /// Returns the kind of the ADT.
2336 pub fn adt_kind(&self) -> AdtKind {
2339 } else if self.is_union() {
2346 /// Returns a description of this abstract data type.
2347 pub fn descr(&self) -> &'static str {
2348 match self.adt_kind() {
2349 AdtKind::Struct => "struct",
2350 AdtKind::Union => "union",
2351 AdtKind::Enum => "enum",
2355 /// Returns a description of a variant of this abstract data type.
2357 pub fn variant_descr(&self) -> &'static str {
2358 match self.adt_kind() {
2359 AdtKind::Struct => "struct",
2360 AdtKind::Union => "union",
2361 AdtKind::Enum => "variant",
2365 /// If this function returns `true`, it implies that `is_struct` must return `true`.
2367 pub fn has_ctor(&self) -> bool {
2368 self.flags.contains(AdtFlags::HAS_CTOR)
2371 /// Returns `true` if this type is `#[fundamental]` for the purposes
2372 /// of coherence checking.
2374 pub fn is_fundamental(&self) -> bool {
2375 self.flags.contains(AdtFlags::IS_FUNDAMENTAL)
2378 /// Returns `true` if this is `PhantomData<T>`.
2380 pub fn is_phantom_data(&self) -> bool {
2381 self.flags.contains(AdtFlags::IS_PHANTOM_DATA)
2384 /// Returns `true` if this is `Arc<T>`.
2385 pub fn is_arc(&self) -> bool {
2386 self.flags.contains(AdtFlags::IS_ARC)
2389 /// Returns `true` if this is `Rc<T>`.
2390 pub fn is_rc(&self) -> bool {
2391 self.flags.contains(AdtFlags::IS_RC)
2394 /// Returns `true` if this is Box<T>.
2396 pub fn is_box(&self) -> bool {
2397 self.flags.contains(AdtFlags::IS_BOX)
2400 /// Returns `true` if this is `ManuallyDrop<T>`.
2402 pub fn is_manually_drop(&self) -> bool {
2403 self.flags.contains(AdtFlags::IS_MANUALLY_DROP)
2406 /// Returns `true` if this type has a destructor.
2407 pub fn has_dtor(&self, tcx: TyCtxt<'tcx>) -> bool {
2408 self.destructor(tcx).is_some()
2411 /// Asserts this is a struct or union and returns its unique variant.
2412 pub fn non_enum_variant(&self) -> &VariantDef {
2413 assert!(self.is_struct() || self.is_union());
2414 &self.variants[VariantIdx::new(0)]
2418 pub fn predicates(&self, tcx: TyCtxt<'tcx>) -> GenericPredicates<'tcx> {
2419 tcx.predicates_of(self.did)
2422 /// Returns an iterator over all fields contained
2425 pub fn all_fields(&self) -> impl Iterator<Item = &FieldDef> + Clone {
2426 self.variants.iter().flat_map(|v| v.fields.iter())
2429 pub fn is_payloadfree(&self) -> bool {
2430 !self.variants.is_empty() && self.variants.iter().all(|v| v.fields.is_empty())
2433 /// Return a `VariantDef` given a variant id.
2434 pub fn variant_with_id(&self, vid: DefId) -> &VariantDef {
2435 self.variants.iter().find(|v| v.def_id == vid).expect("variant_with_id: unknown variant")
2438 /// Return a `VariantDef` given a constructor id.
2439 pub fn variant_with_ctor_id(&self, cid: DefId) -> &VariantDef {
2442 .find(|v| v.ctor_def_id == Some(cid))
2443 .expect("variant_with_ctor_id: unknown variant")
2446 /// Return the index of `VariantDef` given a variant id.
2447 pub fn variant_index_with_id(&self, vid: DefId) -> VariantIdx {
2450 .find(|(_, v)| v.def_id == vid)
2451 .expect("variant_index_with_id: unknown variant")
2455 /// Return the index of `VariantDef` given a constructor id.
2456 pub fn variant_index_with_ctor_id(&self, cid: DefId) -> VariantIdx {
2459 .find(|(_, v)| v.ctor_def_id == Some(cid))
2460 .expect("variant_index_with_ctor_id: unknown variant")
2464 pub fn variant_of_res(&self, res: Res) -> &VariantDef {
2466 Res::Def(DefKind::Variant, vid) => self.variant_with_id(vid),
2467 Res::Def(DefKind::Ctor(..), cid) => self.variant_with_ctor_id(cid),
2468 Res::Def(DefKind::Struct, _)
2469 | Res::Def(DefKind::Union, _)
2470 | Res::Def(DefKind::TyAlias, _)
2471 | Res::Def(DefKind::AssocTy, _)
2473 | Res::SelfCtor(..) => self.non_enum_variant(),
2474 _ => bug!("unexpected res {:?} in variant_of_res", res),
2479 pub fn eval_explicit_discr(&self, tcx: TyCtxt<'tcx>, expr_did: DefId) -> Option<Discr<'tcx>> {
2480 let param_env = tcx.param_env(expr_did);
2481 let repr_type = self.repr.discr_type();
2482 match tcx.const_eval_poly(expr_did) {
2484 let ty = repr_type.to_ty(tcx);
2485 if let Some(b) = val.try_to_bits_for_ty(tcx, param_env, ty) {
2486 trace!("discriminants: {} ({:?})", b, repr_type);
2487 Some(Discr { val: b, ty })
2489 info!("invalid enum discriminant: {:#?}", val);
2490 crate::mir::interpret::struct_error(
2491 tcx.at(tcx.def_span(expr_did)),
2492 "constant evaluation of enum discriminant resulted in non-integer",
2498 Err(ErrorHandled::Reported) => {
2499 if !expr_did.is_local() {
2501 tcx.def_span(expr_did),
2502 "variant discriminant evaluation succeeded \
2503 in its crate but failed locally"
2508 Err(ErrorHandled::TooGeneric) => {
2509 span_bug!(tcx.def_span(expr_did), "enum discriminant depends on generic arguments",)
2515 pub fn discriminants(
2518 ) -> impl Iterator<Item = (VariantIdx, Discr<'tcx>)> + Captures<'tcx> {
2519 let repr_type = self.repr.discr_type();
2520 let initial = repr_type.initial_discriminant(tcx);
2521 let mut prev_discr = None::<Discr<'tcx>>;
2522 self.variants.iter_enumerated().map(move |(i, v)| {
2523 let mut discr = prev_discr.map_or(initial, |d| d.wrap_incr(tcx));
2524 if let VariantDiscr::Explicit(expr_did) = v.discr {
2525 if let Some(new_discr) = self.eval_explicit_discr(tcx, expr_did) {
2529 prev_discr = Some(discr);
2536 pub fn variant_range(&self) -> Range<VariantIdx> {
2537 VariantIdx::new(0)..VariantIdx::new(self.variants.len())
2540 /// Computes the discriminant value used by a specific variant.
2541 /// Unlike `discriminants`, this is (amortized) constant-time,
2542 /// only doing at most one query for evaluating an explicit
2543 /// discriminant (the last one before the requested variant),
2544 /// assuming there are no constant-evaluation errors there.
2546 pub fn discriminant_for_variant(
2549 variant_index: VariantIdx,
2551 let (val, offset) = self.discriminant_def_for_variant(variant_index);
2552 let explicit_value = val
2553 .and_then(|expr_did| self.eval_explicit_discr(tcx, expr_did))
2554 .unwrap_or_else(|| self.repr.discr_type().initial_discriminant(tcx));
2555 explicit_value.checked_add(tcx, offset as u128).0
2558 /// Yields a `DefId` for the discriminant and an offset to add to it
2559 /// Alternatively, if there is no explicit discriminant, returns the
2560 /// inferred discriminant directly.
2561 pub fn discriminant_def_for_variant(&self, variant_index: VariantIdx) -> (Option<DefId>, u32) {
2562 let mut explicit_index = variant_index.as_u32();
2565 match self.variants[VariantIdx::from_u32(explicit_index)].discr {
2566 ty::VariantDiscr::Relative(0) => {
2570 ty::VariantDiscr::Relative(distance) => {
2571 explicit_index -= distance;
2573 ty::VariantDiscr::Explicit(did) => {
2574 expr_did = Some(did);
2579 (expr_did, variant_index.as_u32() - explicit_index)
2582 pub fn destructor(&self, tcx: TyCtxt<'tcx>) -> Option<Destructor> {
2583 tcx.adt_destructor(self.did)
2586 /// Returns a list of types such that `Self: Sized` if and only
2587 /// if that type is `Sized`, or `TyErr` if this type is recursive.
2589 /// Oddly enough, checking that the sized-constraint is `Sized` is
2590 /// actually more expressive than checking all members:
2591 /// the `Sized` trait is inductive, so an associated type that references
2592 /// `Self` would prevent its containing ADT from being `Sized`.
2594 /// Due to normalization being eager, this applies even if
2595 /// the associated type is behind a pointer (e.g., issue #31299).
2596 pub fn sized_constraint(&self, tcx: TyCtxt<'tcx>) -> &'tcx [Ty<'tcx>] {
2597 tcx.adt_sized_constraint(self.did).0
2601 impl<'tcx> FieldDef {
2602 /// Returns the type of this field. The `subst` is typically obtained
2603 /// via the second field of `TyKind::AdtDef`.
2604 pub fn ty(&self, tcx: TyCtxt<'tcx>, subst: SubstsRef<'tcx>) -> Ty<'tcx> {
2605 tcx.type_of(self.did).subst(tcx, subst)
2609 /// Represents the various closure traits in the language. This
2610 /// will determine the type of the environment (`self`, in the
2611 /// desugaring) argument that the closure expects.
2613 /// You can get the environment type of a closure using
2614 /// `tcx.closure_env_ty()`.
2628 pub enum ClosureKind {
2629 // Warning: Ordering is significant here! The ordering is chosen
2630 // because the trait Fn is a subtrait of FnMut and so in turn, and
2631 // hence we order it so that Fn < FnMut < FnOnce.
2637 impl<'tcx> ClosureKind {
2638 // This is the initial value used when doing upvar inference.
2639 pub const LATTICE_BOTTOM: ClosureKind = ClosureKind::Fn;
2641 pub fn trait_did(&self, tcx: TyCtxt<'tcx>) -> DefId {
2643 ClosureKind::Fn => tcx.require_lang_item(FnTraitLangItem, None),
2644 ClosureKind::FnMut => tcx.require_lang_item(FnMutTraitLangItem, None),
2645 ClosureKind::FnOnce => tcx.require_lang_item(FnOnceTraitLangItem, None),
2649 /// Returns `true` if this a type that impls this closure kind
2650 /// must also implement `other`.
2651 pub fn extends(self, other: ty::ClosureKind) -> bool {
2652 match (self, other) {
2653 (ClosureKind::Fn, ClosureKind::Fn) => true,
2654 (ClosureKind::Fn, ClosureKind::FnMut) => true,
2655 (ClosureKind::Fn, ClosureKind::FnOnce) => true,
2656 (ClosureKind::FnMut, ClosureKind::FnMut) => true,
2657 (ClosureKind::FnMut, ClosureKind::FnOnce) => true,
2658 (ClosureKind::FnOnce, ClosureKind::FnOnce) => true,
2663 /// Returns the representative scalar type for this closure kind.
2664 /// See `TyS::to_opt_closure_kind` for more details.
2665 pub fn to_ty(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
2667 ty::ClosureKind::Fn => tcx.types.i8,
2668 ty::ClosureKind::FnMut => tcx.types.i16,
2669 ty::ClosureKind::FnOnce => tcx.types.i32,
2674 impl<'tcx> TyS<'tcx> {
2675 /// Iterator that walks `self` and any types reachable from
2676 /// `self`, in depth-first order. Note that just walks the types
2677 /// that appear in `self`, it does not descend into the fields of
2678 /// structs or variants. For example:
2681 /// isize => { isize }
2682 /// Foo<Bar<isize>> => { Foo<Bar<isize>>, Bar<isize>, isize }
2683 /// [isize] => { [isize], isize }
2685 pub fn walk(&'tcx self) -> TypeWalker<'tcx> {
2686 TypeWalker::new(self)
2689 /// Iterator that walks the immediate children of `self`. Hence
2690 /// `Foo<Bar<i32>, u32>` yields the sequence `[Bar<i32>, u32]`
2691 /// (but not `i32`, like `walk`).
2692 pub fn walk_shallow(&'tcx self) -> smallvec::IntoIter<walk::TypeWalkerArray<'tcx>> {
2693 walk::walk_shallow(self)
2696 /// Walks `ty` and any types appearing within `ty`, invoking the
2697 /// callback `f` on each type. If the callback returns `false`, then the
2698 /// children of the current type are ignored.
2700 /// Note: prefer `ty.walk()` where possible.
2701 pub fn maybe_walk<F>(&'tcx self, mut f: F)
2703 F: FnMut(Ty<'tcx>) -> bool,
2705 let mut walker = self.walk();
2706 while let Some(ty) = walker.next() {
2708 walker.skip_current_subtree();
2715 pub fn from_mutbl(m: hir::Mutability) -> BorrowKind {
2717 hir::Mutability::Mut => MutBorrow,
2718 hir::Mutability::Not => ImmBorrow,
2722 /// Returns a mutability `m` such that an `&m T` pointer could be used to obtain this borrow
2723 /// kind. Because borrow kinds are richer than mutabilities, we sometimes have to pick a
2724 /// mutability that is stronger than necessary so that it at least *would permit* the borrow in
2726 pub fn to_mutbl_lossy(self) -> hir::Mutability {
2728 MutBorrow => hir::Mutability::Mut,
2729 ImmBorrow => hir::Mutability::Not,
2731 // We have no type corresponding to a unique imm borrow, so
2732 // use `&mut`. It gives all the capabilities of an `&uniq`
2733 // and hence is a safe "over approximation".
2734 UniqueImmBorrow => hir::Mutability::Mut,
2738 pub fn to_user_str(&self) -> &'static str {
2740 MutBorrow => "mutable",
2741 ImmBorrow => "immutable",
2742 UniqueImmBorrow => "uniquely immutable",
2747 #[derive(Debug, Clone)]
2748 pub enum Attributes<'tcx> {
2749 Owned(Lrc<[ast::Attribute]>),
2750 Borrowed(&'tcx [ast::Attribute]),
2753 impl<'tcx> ::std::ops::Deref for Attributes<'tcx> {
2754 type Target = [ast::Attribute];
2756 fn deref(&self) -> &[ast::Attribute] {
2758 &Attributes::Owned(ref data) => &data,
2759 &Attributes::Borrowed(data) => data,
2764 #[derive(Debug, PartialEq, Eq)]
2765 pub enum ImplOverlapKind {
2766 /// These impls are always allowed to overlap.
2768 /// Whether or not the impl is permitted due to the trait being a `#[marker]` trait
2771 /// These impls are allowed to overlap, but that raises
2772 /// an issue #33140 future-compatibility warning.
2774 /// Some background: in Rust 1.0, the trait-object types `Send + Sync` (today's
2775 /// `dyn Send + Sync`) and `Sync + Send` (now `dyn Sync + Send`) were different.
2777 /// The widely-used version 0.1.0 of the crate `traitobject` had accidentally relied
2778 /// that difference, making what reduces to the following set of impls:
2782 /// impl Trait for dyn Send + Sync {}
2783 /// impl Trait for dyn Sync + Send {}
2786 /// Obviously, once we made these types be identical, that code causes a coherence
2787 /// error and a fairly big headache for us. However, luckily for us, the trait
2788 /// `Trait` used in this case is basically a marker trait, and therefore having
2789 /// overlapping impls for it is sound.
2791 /// To handle this, we basically regard the trait as a marker trait, with an additional
2792 /// future-compatibility warning. To avoid accidentally "stabilizing" this feature,
2793 /// it has the following restrictions:
2795 /// 1. The trait must indeed be a marker-like trait (i.e., no items), and must be
2797 /// 2. The trait-ref of both impls must be equal.
2798 /// 3. The trait-ref of both impls must be a trait object type consisting only of
2800 /// 4. Neither of the impls can have any where-clauses.
2802 /// Once `traitobject` 0.1.0 is no longer an active concern, this hack can be removed.
2806 impl<'tcx> TyCtxt<'tcx> {
2807 pub fn body_tables(self, body: hir::BodyId) -> &'tcx TypeckTables<'tcx> {
2808 self.typeck_tables_of(self.hir().body_owner_def_id(body))
2811 /// Returns an iterator of the `DefId`s for all body-owners in this
2812 /// crate. If you would prefer to iterate over the bodies
2813 /// themselves, you can do `self.hir().krate().body_ids.iter()`.
2814 pub fn body_owners(self) -> impl Iterator<Item = DefId> + Captures<'tcx> + 'tcx {
2819 .map(move |&body_id| self.hir().body_owner_def_id(body_id))
2822 pub fn par_body_owners<F: Fn(DefId) + sync::Sync + sync::Send>(self, f: F) {
2823 par_iter(&self.hir().krate().body_ids)
2824 .for_each(|&body_id| f(self.hir().body_owner_def_id(body_id)));
2827 pub fn provided_trait_methods(self, id: DefId) -> impl 'tcx + Iterator<Item = &'tcx AssocItem> {
2828 self.associated_items(id)
2829 .in_definition_order()
2830 .filter(|item| item.kind == AssocKind::Method && item.defaultness.has_value())
2833 pub fn trait_relevant_for_never(self, did: DefId) -> bool {
2834 self.associated_items(did).in_definition_order().any(|item| item.relevant_for_never())
2837 pub fn opt_item_name(self, def_id: DefId) -> Option<Ident> {
2838 self.hir().as_local_hir_id(def_id).and_then(|hir_id| self.hir().get(hir_id).ident())
2841 pub fn opt_associated_item(self, def_id: DefId) -> Option<AssocItem> {
2842 let is_associated_item = if let Some(hir_id) = self.hir().as_local_hir_id(def_id) {
2843 match self.hir().get(hir_id) {
2844 Node::TraitItem(_) | Node::ImplItem(_) => true,
2848 match self.def_kind(def_id).expect("no def for `DefId`") {
2849 DefKind::AssocConst | DefKind::Method | DefKind::AssocTy => true,
2854 is_associated_item.then(|| self.associated_item(def_id))
2857 pub fn field_index(self, hir_id: hir::HirId, tables: &TypeckTables<'_>) -> usize {
2858 tables.field_indices().get(hir_id).cloned().expect("no index for a field")
2861 pub fn find_field_index(self, ident: Ident, variant: &VariantDef) -> Option<usize> {
2862 variant.fields.iter().position(|field| self.hygienic_eq(ident, field.ident, variant.def_id))
2865 /// Returns `true` if the impls are the same polarity and the trait either
2866 /// has no items or is annotated #[marker] and prevents item overrides.
2867 pub fn impls_are_allowed_to_overlap(
2871 ) -> Option<ImplOverlapKind> {
2872 // If either trait impl references an error, they're allowed to overlap,
2873 // as one of them essentially doesn't exist.
2874 if self.impl_trait_ref(def_id1).map_or(false, |tr| tr.references_error())
2875 || self.impl_trait_ref(def_id2).map_or(false, |tr| tr.references_error())
2877 return Some(ImplOverlapKind::Permitted { marker: false });
2880 match (self.impl_polarity(def_id1), self.impl_polarity(def_id2)) {
2881 (ImplPolarity::Reservation, _) | (_, ImplPolarity::Reservation) => {
2882 // `#[rustc_reservation_impl]` impls don't overlap with anything
2884 "impls_are_allowed_to_overlap({:?}, {:?}) = Some(Permitted) (reservations)",
2887 return Some(ImplOverlapKind::Permitted { marker: false });
2889 (ImplPolarity::Positive, ImplPolarity::Negative)
2890 | (ImplPolarity::Negative, ImplPolarity::Positive) => {
2891 // `impl AutoTrait for Type` + `impl !AutoTrait for Type`
2893 "impls_are_allowed_to_overlap({:?}, {:?}) - None (differing polarities)",
2898 (ImplPolarity::Positive, ImplPolarity::Positive)
2899 | (ImplPolarity::Negative, ImplPolarity::Negative) => {}
2902 let is_marker_overlap = {
2903 let is_marker_impl = |def_id: DefId| -> bool {
2904 let trait_ref = self.impl_trait_ref(def_id);
2905 trait_ref.map_or(false, |tr| self.trait_def(tr.def_id).is_marker)
2907 is_marker_impl(def_id1) && is_marker_impl(def_id2)
2910 if is_marker_overlap {
2912 "impls_are_allowed_to_overlap({:?}, {:?}) = Some(Permitted) (marker overlap)",
2915 Some(ImplOverlapKind::Permitted { marker: true })
2917 if let Some(self_ty1) = self.issue33140_self_ty(def_id1) {
2918 if let Some(self_ty2) = self.issue33140_self_ty(def_id2) {
2919 if self_ty1 == self_ty2 {
2921 "impls_are_allowed_to_overlap({:?}, {:?}) - issue #33140 HACK",
2924 return Some(ImplOverlapKind::Issue33140);
2927 "impls_are_allowed_to_overlap({:?}, {:?}) - found {:?} != {:?}",
2928 def_id1, def_id2, self_ty1, self_ty2
2934 debug!("impls_are_allowed_to_overlap({:?}, {:?}) = None", def_id1, def_id2);
2939 /// Returns `ty::VariantDef` if `res` refers to a struct,
2940 /// or variant or their constructors, panics otherwise.
2941 pub fn expect_variant_res(self, res: Res) -> &'tcx VariantDef {
2943 Res::Def(DefKind::Variant, did) => {
2944 let enum_did = self.parent(did).unwrap();
2945 self.adt_def(enum_did).variant_with_id(did)
2947 Res::Def(DefKind::Struct, did) | Res::Def(DefKind::Union, did) => {
2948 self.adt_def(did).non_enum_variant()
2950 Res::Def(DefKind::Ctor(CtorOf::Variant, ..), variant_ctor_did) => {
2951 let variant_did = self.parent(variant_ctor_did).unwrap();
2952 let enum_did = self.parent(variant_did).unwrap();
2953 self.adt_def(enum_did).variant_with_ctor_id(variant_ctor_did)
2955 Res::Def(DefKind::Ctor(CtorOf::Struct, ..), ctor_did) => {
2956 let struct_did = self.parent(ctor_did).expect("struct ctor has no parent");
2957 self.adt_def(struct_did).non_enum_variant()
2959 _ => bug!("expect_variant_res used with unexpected res {:?}", res),
2963 pub fn item_name(self, id: DefId) -> Symbol {
2964 if id.index == CRATE_DEF_INDEX {
2965 self.original_crate_name(id.krate)
2967 let def_key = self.def_key(id);
2968 match def_key.disambiguated_data.data {
2969 // The name of a constructor is that of its parent.
2970 hir_map::DefPathData::Ctor => {
2971 self.item_name(DefId { krate: id.krate, index: def_key.parent.unwrap() })
2973 _ => def_key.disambiguated_data.data.get_opt_name().unwrap_or_else(|| {
2974 bug!("item_name: no name for {:?}", self.def_path(id));
2980 /// Returns the possibly-auto-generated MIR of a `(DefId, Subst)` pair.
2981 pub fn instance_mir(self, instance: ty::InstanceDef<'tcx>) -> ReadOnlyBodyAndCache<'tcx, 'tcx> {
2983 ty::InstanceDef::Item(did) => self.optimized_mir(did).unwrap_read_only(),
2984 ty::InstanceDef::VtableShim(..)
2985 | ty::InstanceDef::ReifyShim(..)
2986 | ty::InstanceDef::Intrinsic(..)
2987 | ty::InstanceDef::FnPtrShim(..)
2988 | ty::InstanceDef::Virtual(..)
2989 | ty::InstanceDef::ClosureOnceShim { .. }
2990 | ty::InstanceDef::DropGlue(..)
2991 | ty::InstanceDef::CloneShim(..) => self.mir_shims(instance).unwrap_read_only(),
2995 /// Gets the attributes of a definition.
2996 pub fn get_attrs(self, did: DefId) -> Attributes<'tcx> {
2997 if let Some(id) = self.hir().as_local_hir_id(did) {
2998 Attributes::Borrowed(self.hir().attrs(id))
3000 Attributes::Owned(self.item_attrs(did))
3004 /// Determines whether an item is annotated with an attribute.
3005 pub fn has_attr(self, did: DefId, attr: Symbol) -> bool {
3006 attr::contains_name(&self.get_attrs(did), attr)
3009 /// Returns `true` if this is an `auto trait`.
3010 pub fn trait_is_auto(self, trait_def_id: DefId) -> bool {
3011 self.trait_def(trait_def_id).has_auto_impl
3014 pub fn generator_layout(self, def_id: DefId) -> &'tcx GeneratorLayout<'tcx> {
3015 self.optimized_mir(def_id).generator_layout.as_ref().unwrap()
3018 /// Given the `DefId` of an impl, returns the `DefId` of the trait it implements.
3019 /// If it implements no trait, returns `None`.
3020 pub fn trait_id_of_impl(self, def_id: DefId) -> Option<DefId> {
3021 self.impl_trait_ref(def_id).map(|tr| tr.def_id)
3024 /// If the given defid describes a method belonging to an impl, returns the
3025 /// `DefId` of the impl that the method belongs to; otherwise, returns `None`.
3026 pub fn impl_of_method(self, def_id: DefId) -> Option<DefId> {
3027 let item = if def_id.krate != LOCAL_CRATE {
3028 if let Some(DefKind::Method) = self.def_kind(def_id) {
3029 Some(self.associated_item(def_id))
3034 self.opt_associated_item(def_id)
3037 item.and_then(|trait_item| match trait_item.container {
3038 TraitContainer(_) => None,
3039 ImplContainer(def_id) => Some(def_id),
3043 /// Looks up the span of `impl_did` if the impl is local; otherwise returns `Err`
3044 /// with the name of the crate containing the impl.
3045 pub fn span_of_impl(self, impl_did: DefId) -> Result<Span, Symbol> {
3046 if impl_did.is_local() {
3047 let hir_id = self.hir().as_local_hir_id(impl_did).unwrap();
3048 Ok(self.hir().span(hir_id))
3050 Err(self.crate_name(impl_did.krate))
3054 /// Hygienically compares a use-site name (`use_name`) for a field or an associated item with
3055 /// its supposed definition name (`def_name`). The method also needs `DefId` of the supposed
3056 /// definition's parent/scope to perform comparison.
3057 pub fn hygienic_eq(self, use_name: Ident, def_name: Ident, def_parent_def_id: DefId) -> bool {
3058 // We could use `Ident::eq` here, but we deliberately don't. The name
3059 // comparison fails frequently, and we want to avoid the expensive
3060 // `modern()` calls required for the span comparison whenever possible.
3061 use_name.name == def_name.name
3065 .hygienic_eq(def_name.span.ctxt(), self.expansion_that_defined(def_parent_def_id))
3068 fn expansion_that_defined(self, scope: DefId) -> ExpnId {
3070 LOCAL_CRATE => self.hir().definitions().expansion_that_defined(scope.index),
3071 _ => ExpnId::root(),
3075 pub fn adjust_ident(self, mut ident: Ident, scope: DefId) -> Ident {
3076 ident.span.modernize_and_adjust(self.expansion_that_defined(scope));
3080 pub fn adjust_ident_and_get_scope(
3085 ) -> (Ident, DefId) {
3086 let scope = match ident.span.modernize_and_adjust(self.expansion_that_defined(scope)) {
3087 Some(actual_expansion) => {
3088 self.hir().definitions().parent_module_of_macro_def(actual_expansion)
3090 None => self.hir().get_module_parent(block),
3095 pub fn is_object_safe(self, key: DefId) -> bool {
3096 self.object_safety_violations(key).is_empty()
3100 #[derive(Clone, HashStable)]
3101 pub struct AdtSizedConstraint<'tcx>(pub &'tcx [Ty<'tcx>]);
3103 /// Yields the parent function's `DefId` if `def_id` is an `impl Trait` definition.
3104 pub fn is_impl_trait_defn(tcx: TyCtxt<'_>, def_id: DefId) -> Option<DefId> {
3105 if let Some(hir_id) = tcx.hir().as_local_hir_id(def_id) {
3106 if let Node::Item(item) = tcx.hir().get(hir_id) {
3107 if let hir::ItemKind::OpaqueTy(ref opaque_ty) = item.kind {
3108 return opaque_ty.impl_trait_fn;
3115 pub fn provide(providers: &mut ty::query::Providers<'_>) {
3116 context::provide(providers);
3117 erase_regions::provide(providers);
3118 layout::provide(providers);
3120 ty::query::Providers { trait_impls_of: trait_def::trait_impls_of_provider, ..*providers };
3123 /// A map for the local crate mapping each type to a vector of its
3124 /// inherent impls. This is not meant to be used outside of coherence;
3125 /// rather, you should request the vector for a specific type via
3126 /// `tcx.inherent_impls(def_id)` so as to minimize your dependencies
3127 /// (constructing this map requires touching the entire crate).
3128 #[derive(Clone, Debug, Default, HashStable)]
3129 pub struct CrateInherentImpls {
3130 pub inherent_impls: DefIdMap<Vec<DefId>>,
3133 #[derive(Clone, Copy, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
3134 pub struct SymbolName {
3135 // FIXME: we don't rely on interning or equality here - better have
3136 // this be a `&'tcx str`.
3141 pub fn new(name: &str) -> SymbolName {
3142 SymbolName { name: Symbol::intern(name) }
3146 impl PartialOrd for SymbolName {
3147 fn partial_cmp(&self, other: &SymbolName) -> Option<Ordering> {
3148 self.name.as_str().partial_cmp(&other.name.as_str())
3152 /// Ordering must use the chars to ensure reproducible builds.
3153 impl Ord for SymbolName {
3154 fn cmp(&self, other: &SymbolName) -> Ordering {
3155 self.name.as_str().cmp(&other.name.as_str())
3159 impl fmt::Display for SymbolName {
3160 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
3161 fmt::Display::fmt(&self.name, fmt)
3165 impl fmt::Debug for SymbolName {
3166 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
3167 fmt::Display::fmt(&self.name, fmt)