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;
12 use crate::ich::Fingerprint;
13 use crate::ich::StableHashingContext;
14 use crate::infer::canonical::Canonical;
15 use crate::middle::cstore::CrateStoreDyn;
16 use crate::middle::lang_items::{FnMutTraitLangItem, FnOnceTraitLangItem, FnTraitLangItem};
17 use crate::middle::resolve_lifetime::ObjectLifetimeDefault;
18 use crate::mir::interpret::ErrorHandled;
19 use crate::mir::GeneratorLayout;
20 use crate::mir::ReadOnlyBodyAndCache;
21 use crate::traits::{self, Reveal};
23 use crate::ty::layout::VariantIdx;
24 use crate::ty::subst::{InternalSubsts, Subst, SubstsRef};
25 use crate::ty::util::{Discr, IntTypeExt};
26 use crate::ty::walk::TypeWalker;
27 use rustc_ast::ast::{self, Ident, Name};
28 use rustc_ast::node_id::{NodeId, NodeMap, NodeSet};
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_session::DataTypeKind;
44 use rustc_span::hygiene::ExpnId;
45 use rustc_span::symbol::{kw, sym, Symbol};
47 use rustc_target::abi::Align;
49 use std::cell::RefCell;
50 use std::cmp::{self, Ordering};
52 use std::hash::{Hash, Hasher};
58 pub use self::sty::BoundRegion::*;
59 pub use self::sty::InferTy::*;
60 pub use self::sty::RegionKind;
61 pub use self::sty::RegionKind::*;
62 pub use self::sty::TyKind::*;
63 pub use self::sty::{Binder, BoundTy, BoundTyKind, BoundVar, DebruijnIndex, INNERMOST};
64 pub use self::sty::{BoundRegion, EarlyBoundRegion, FreeRegion, Region};
65 pub use self::sty::{CanonicalPolyFnSig, FnSig, GenSig, PolyFnSig, PolyGenSig};
66 pub use self::sty::{ClosureSubsts, GeneratorSubsts, TypeAndMut, UpvarSubsts};
67 pub use self::sty::{Const, ConstKind, ExistentialProjection, PolyExistentialProjection};
68 pub use self::sty::{ConstVid, FloatVid, IntVid, RegionVid, TyVid};
69 pub use self::sty::{ExistentialPredicate, InferConst, InferTy, ParamConst, ParamTy, ProjectionTy};
70 pub use self::sty::{ExistentialTraitRef, PolyExistentialTraitRef};
71 pub use self::sty::{PolyTraitRef, TraitRef, TyKind};
72 pub use crate::ty::diagnostics::*;
74 pub use self::binding::BindingMode;
75 pub use self::binding::BindingMode::*;
77 pub use self::context::{keep_local, tls, FreeRegionInfo, TyCtxt};
78 pub use self::context::{
79 CanonicalUserType, CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations, ResolvedOpaqueTy,
80 UserType, UserTypeAnnotationIndex,
82 pub use self::context::{
83 CtxtInterners, GeneratorInteriorTypeCause, GlobalCtxt, Lift, TypeckTables,
86 pub use self::instance::RESOLVE_INSTANCE;
87 pub use self::instance::{Instance, InstanceDef};
89 pub use self::trait_def::TraitDef;
91 pub use self::query::queries;
104 pub mod free_region_map;
105 pub mod inhabitedness;
107 pub mod normalize_erasing_regions;
121 mod structural_impls;
126 pub struct ResolverOutputs {
127 pub definitions: hir_map::Definitions,
128 pub cstore: Box<CrateStoreDyn>,
129 pub extern_crate_map: NodeMap<CrateNum>,
130 pub trait_map: TraitMap<NodeId>,
131 pub maybe_unused_trait_imports: NodeSet,
132 pub maybe_unused_extern_crates: Vec<(NodeId, Span)>,
133 pub export_map: ExportMap<NodeId>,
134 pub glob_map: GlobMap,
135 /// Extern prelude entries. The value is `true` if the entry was introduced
136 /// via `extern crate` item and not `--extern` option or compiler built-in.
137 pub extern_prelude: FxHashMap<Name, bool>,
140 #[derive(Clone, Copy, PartialEq, Eq, Debug, HashStable)]
141 pub enum AssocItemContainer {
142 TraitContainer(DefId),
143 ImplContainer(DefId),
146 impl AssocItemContainer {
147 /// Asserts that this is the `DefId` of an associated item declared
148 /// in a trait, and returns the trait `DefId`.
149 pub fn assert_trait(&self) -> DefId {
151 TraitContainer(id) => id,
152 _ => bug!("associated item has wrong container type: {:?}", self),
156 pub fn id(&self) -> DefId {
158 TraitContainer(id) => id,
159 ImplContainer(id) => id,
164 /// The "header" of an impl is everything outside the body: a Self type, a trait
165 /// ref (in the case of a trait impl), and a set of predicates (from the
166 /// bounds / where-clauses).
167 #[derive(Clone, Debug, TypeFoldable)]
168 pub struct ImplHeader<'tcx> {
169 pub impl_def_id: DefId,
170 pub self_ty: Ty<'tcx>,
171 pub trait_ref: Option<TraitRef<'tcx>>,
172 pub predicates: Vec<Predicate<'tcx>>,
175 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable)]
176 pub enum ImplPolarity {
177 /// `impl Trait for Type`
179 /// `impl !Trait for Type`
181 /// `#[rustc_reservation_impl] impl Trait for Type`
183 /// This is a "stability hack", not a real Rust feature.
184 /// See #64631 for details.
188 #[derive(Copy, Clone, Debug, PartialEq, HashStable)]
189 pub struct AssocItem {
191 #[stable_hasher(project(name))]
195 pub defaultness: hir::Defaultness,
196 pub container: AssocItemContainer,
198 /// Whether this is a method with an explicit self
199 /// as its first argument, allowing method calls.
200 pub method_has_self_argument: bool,
203 #[derive(Copy, Clone, PartialEq, Debug, HashStable)]
212 pub fn suggestion_descr(&self) -> &'static str {
214 ty::AssocKind::Method => "method call",
215 ty::AssocKind::Type | ty::AssocKind::OpaqueTy => "associated type",
216 ty::AssocKind::Const => "associated constant",
220 pub fn namespace(&self) -> Namespace {
222 ty::AssocKind::OpaqueTy | ty::AssocKind::Type => Namespace::TypeNS,
223 ty::AssocKind::Const | ty::AssocKind::Method => Namespace::ValueNS,
229 pub fn def_kind(&self) -> DefKind {
231 AssocKind::Const => DefKind::AssocConst,
232 AssocKind::Method => DefKind::AssocFn,
233 AssocKind::Type => DefKind::AssocTy,
234 AssocKind::OpaqueTy => DefKind::AssocOpaqueTy,
238 /// Tests whether the associated item admits a non-trivial implementation
240 pub fn relevant_for_never(&self) -> bool {
242 AssocKind::OpaqueTy | AssocKind::Const | AssocKind::Type => true,
243 // FIXME(canndrew): Be more thorough here, check if any argument is uninhabited.
244 AssocKind::Method => !self.method_has_self_argument,
248 pub fn signature(&self, tcx: TyCtxt<'_>) -> String {
250 ty::AssocKind::Method => {
251 // We skip the binder here because the binder would deanonymize all
252 // late-bound regions, and we don't want method signatures to show up
253 // `as for<'r> fn(&'r MyType)`. Pretty-printing handles late-bound
254 // regions just fine, showing `fn(&MyType)`.
255 tcx.fn_sig(self.def_id).skip_binder().to_string()
257 ty::AssocKind::Type => format!("type {};", self.ident),
258 // FIXME(type_alias_impl_trait): we should print bounds here too.
259 ty::AssocKind::OpaqueTy => format!("type {};", self.ident),
260 ty::AssocKind::Const => {
261 format!("const {}: {:?};", self.ident, tcx.type_of(self.def_id))
267 /// A list of `ty::AssocItem`s in definition order that allows for efficient lookup by name.
269 /// When doing lookup by name, we try to postpone hygienic comparison for as long as possible since
270 /// it is relatively expensive. Instead, items are indexed by `Symbol` and hygienic comparison is
271 /// done only on items with the same name.
272 #[derive(Debug, Clone, PartialEq, HashStable)]
273 pub struct AssociatedItems {
274 items: SortedIndexMultiMap<u32, Symbol, ty::AssocItem>,
277 impl AssociatedItems {
278 /// Constructs an `AssociatedItems` map from a series of `ty::AssocItem`s in definition order.
279 pub fn new(items_in_def_order: impl IntoIterator<Item = ty::AssocItem>) -> Self {
280 let items = items_in_def_order.into_iter().map(|item| (item.ident.name, item)).collect();
281 AssociatedItems { items }
284 /// Returns a slice of associated items in the order they were defined.
286 /// New code should avoid relying on definition order. If you need a particular associated item
287 /// for a known trait, make that trait a lang item instead of indexing this array.
288 pub fn in_definition_order(&self) -> impl '_ + Iterator<Item = &ty::AssocItem> {
289 self.items.iter().map(|(_, v)| v)
292 /// Returns an iterator over all associated items with the given name, ignoring hygiene.
293 pub fn filter_by_name_unhygienic(
296 ) -> impl '_ + Iterator<Item = &ty::AssocItem> {
297 self.items.get_by_key(&name)
300 /// Returns an iterator over all associated items with the given name.
302 /// Multiple items may have the same name if they are in different `Namespace`s. For example,
303 /// an associated type can have the same name as a method. Use one of the `find_by_name_and_*`
304 /// methods below if you know which item you are looking for.
305 pub fn filter_by_name(
309 parent_def_id: DefId,
310 ) -> impl 'a + Iterator<Item = &'a ty::AssocItem> {
311 self.filter_by_name_unhygienic(ident.name)
312 .filter(move |item| tcx.hygienic_eq(ident, item.ident, parent_def_id))
315 /// Returns the associated item with the given name and `AssocKind`, if one exists.
316 pub fn find_by_name_and_kind(
321 parent_def_id: DefId,
322 ) -> Option<&ty::AssocItem> {
323 self.filter_by_name_unhygienic(ident.name)
324 .filter(|item| item.kind == kind)
325 .find(|item| tcx.hygienic_eq(ident, item.ident, parent_def_id))
328 /// Returns the associated item with the given name in the given `Namespace`, if one exists.
329 pub fn find_by_name_and_namespace(
334 parent_def_id: DefId,
335 ) -> Option<&ty::AssocItem> {
336 self.filter_by_name_unhygienic(ident.name)
337 .filter(|item| item.kind.namespace() == ns)
338 .find(|item| tcx.hygienic_eq(ident, item.ident, parent_def_id))
342 #[derive(Clone, Debug, PartialEq, Eq, Copy, RustcEncodable, RustcDecodable, HashStable)]
343 pub enum Visibility {
344 /// Visible everywhere (including in other crates).
346 /// Visible only in the given crate-local module.
348 /// Not visible anywhere in the local crate. This is the visibility of private external items.
352 pub trait DefIdTree: Copy {
353 fn parent(self, id: DefId) -> Option<DefId>;
355 fn is_descendant_of(self, mut descendant: DefId, ancestor: DefId) -> bool {
356 if descendant.krate != ancestor.krate {
360 while descendant != ancestor {
361 match self.parent(descendant) {
362 Some(parent) => descendant = parent,
363 None => return false,
370 impl<'tcx> DefIdTree for TyCtxt<'tcx> {
371 fn parent(self, id: DefId) -> Option<DefId> {
372 self.def_key(id).parent.map(|index| DefId { index, ..id })
377 pub fn from_hir(visibility: &hir::Visibility<'_>, id: hir::HirId, tcx: TyCtxt<'_>) -> Self {
378 match visibility.node {
379 hir::VisibilityKind::Public => Visibility::Public,
380 hir::VisibilityKind::Crate(_) => Visibility::Restricted(DefId::local(CRATE_DEF_INDEX)),
381 hir::VisibilityKind::Restricted { ref path, .. } => match path.res {
382 // If there is no resolution, `resolve` will have already reported an error, so
383 // assume that the visibility is public to avoid reporting more privacy errors.
384 Res::Err => Visibility::Public,
385 def => Visibility::Restricted(def.def_id()),
387 hir::VisibilityKind::Inherited => {
388 Visibility::Restricted(tcx.parent_module(id).to_def_id())
393 /// Returns `true` if an item with this visibility is accessible from the given block.
394 pub fn is_accessible_from<T: DefIdTree>(self, module: DefId, tree: T) -> bool {
395 let restriction = match self {
396 // Public items are visible everywhere.
397 Visibility::Public => return true,
398 // Private items from other crates are visible nowhere.
399 Visibility::Invisible => return false,
400 // Restricted items are visible in an arbitrary local module.
401 Visibility::Restricted(other) if other.krate != module.krate => return false,
402 Visibility::Restricted(module) => module,
405 tree.is_descendant_of(module, restriction)
408 /// Returns `true` if this visibility is at least as accessible as the given visibility
409 pub fn is_at_least<T: DefIdTree>(self, vis: Visibility, tree: T) -> bool {
410 let vis_restriction = match vis {
411 Visibility::Public => return self == Visibility::Public,
412 Visibility::Invisible => return true,
413 Visibility::Restricted(module) => module,
416 self.is_accessible_from(vis_restriction, tree)
419 // Returns `true` if this item is visible anywhere in the local crate.
420 pub fn is_visible_locally(self) -> bool {
422 Visibility::Public => true,
423 Visibility::Restricted(def_id) => def_id.is_local(),
424 Visibility::Invisible => false,
429 #[derive(Copy, Clone, PartialEq, RustcDecodable, RustcEncodable, HashStable)]
431 Covariant, // T<A> <: T<B> iff A <: B -- e.g., function return type
432 Invariant, // T<A> <: T<B> iff B == A -- e.g., type of mutable cell
433 Contravariant, // T<A> <: T<B> iff B <: A -- e.g., function param type
434 Bivariant, // T<A> <: T<B> -- e.g., unused type parameter
437 /// The crate variances map is computed during typeck and contains the
438 /// variance of every item in the local crate. You should not use it
439 /// directly, because to do so will make your pass dependent on the
440 /// HIR of every item in the local crate. Instead, use
441 /// `tcx.variances_of()` to get the variance for a *particular*
443 #[derive(HashStable)]
444 pub struct CrateVariancesMap<'tcx> {
445 /// For each item with generics, maps to a vector of the variance
446 /// of its generics. If an item has no generics, it will have no
448 pub variances: FxHashMap<DefId, &'tcx [ty::Variance]>,
452 /// `a.xform(b)` combines the variance of a context with the
453 /// variance of a type with the following meaning. If we are in a
454 /// context with variance `a`, and we encounter a type argument in
455 /// a position with variance `b`, then `a.xform(b)` is the new
456 /// variance with which the argument appears.
462 /// Here, the "ambient" variance starts as covariant. `*mut T` is
463 /// invariant with respect to `T`, so the variance in which the
464 /// `Vec<i32>` appears is `Covariant.xform(Invariant)`, which
465 /// yields `Invariant`. Now, the type `Vec<T>` is covariant with
466 /// respect to its type argument `T`, and hence the variance of
467 /// the `i32` here is `Invariant.xform(Covariant)`, which results
468 /// (again) in `Invariant`.
472 /// fn(*const Vec<i32>, *mut Vec<i32)
474 /// The ambient variance is covariant. A `fn` type is
475 /// contravariant with respect to its parameters, so the variance
476 /// within which both pointer types appear is
477 /// `Covariant.xform(Contravariant)`, or `Contravariant`. `*const
478 /// T` is covariant with respect to `T`, so the variance within
479 /// which the first `Vec<i32>` appears is
480 /// `Contravariant.xform(Covariant)` or `Contravariant`. The same
481 /// is true for its `i32` argument. In the `*mut T` case, the
482 /// variance of `Vec<i32>` is `Contravariant.xform(Invariant)`,
483 /// and hence the outermost type is `Invariant` with respect to
484 /// `Vec<i32>` (and its `i32` argument).
486 /// Source: Figure 1 of "Taming the Wildcards:
487 /// Combining Definition- and Use-Site Variance" published in PLDI'11.
488 pub fn xform(self, v: ty::Variance) -> ty::Variance {
490 // Figure 1, column 1.
491 (ty::Covariant, ty::Covariant) => ty::Covariant,
492 (ty::Covariant, ty::Contravariant) => ty::Contravariant,
493 (ty::Covariant, ty::Invariant) => ty::Invariant,
494 (ty::Covariant, ty::Bivariant) => ty::Bivariant,
496 // Figure 1, column 2.
497 (ty::Contravariant, ty::Covariant) => ty::Contravariant,
498 (ty::Contravariant, ty::Contravariant) => ty::Covariant,
499 (ty::Contravariant, ty::Invariant) => ty::Invariant,
500 (ty::Contravariant, ty::Bivariant) => ty::Bivariant,
502 // Figure 1, column 3.
503 (ty::Invariant, _) => ty::Invariant,
505 // Figure 1, column 4.
506 (ty::Bivariant, _) => ty::Bivariant,
511 // Contains information needed to resolve types and (in the future) look up
512 // the types of AST nodes.
513 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
514 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 check
522 /// whether the type has various kinds of types in it without recursing
523 /// over the type itself.
524 pub struct TypeFlags: u32 {
525 // Does this have parameters? Used to determine whether substitution is
527 /// Does this have [Param]?
528 const HAS_TY_PARAM = 1 << 0;
529 /// Does this have [ReEarlyBound]?
530 const HAS_RE_PARAM = 1 << 1;
531 /// Does this have [ConstKind::Param]?
532 const HAS_CT_PARAM = 1 << 2;
534 const NEEDS_SUBST = TypeFlags::HAS_TY_PARAM.bits
535 | TypeFlags::HAS_RE_PARAM.bits
536 | TypeFlags::HAS_CT_PARAM.bits;
538 /// Does this have [Infer]?
539 const HAS_TY_INFER = 1 << 3;
540 /// Does this have [ReVar]?
541 const HAS_RE_INFER = 1 << 4;
542 /// Does this have [ConstKind::Infer]?
543 const HAS_CT_INFER = 1 << 5;
545 /// Does this have inference variables? Used to determine whether
546 /// inference is required.
547 const NEEDS_INFER = TypeFlags::HAS_TY_INFER.bits
548 | TypeFlags::HAS_RE_INFER.bits
549 | TypeFlags::HAS_CT_INFER.bits;
551 /// Does this have [Placeholder]?
552 const HAS_TY_PLACEHOLDER = 1 << 6;
553 /// Does this have [RePlaceholder]?
554 const HAS_RE_PLACEHOLDER = 1 << 7;
555 /// Does this have [ConstKind::Placeholder]?
556 const HAS_CT_PLACEHOLDER = 1 << 8;
558 /// `true` if there are "names" of regions and so forth
559 /// that are local to a particular fn/inferctxt
560 const HAS_FREE_LOCAL_REGIONS = 1 << 9;
562 /// `true` if there are "names" of types and regions and so forth
563 /// that are local to a particular fn
564 const HAS_FREE_LOCAL_NAMES = TypeFlags::HAS_TY_PARAM.bits
565 | TypeFlags::HAS_CT_PARAM.bits
566 | TypeFlags::HAS_TY_INFER.bits
567 | TypeFlags::HAS_CT_INFER.bits
568 | TypeFlags::HAS_TY_PLACEHOLDER.bits
569 | TypeFlags::HAS_CT_PLACEHOLDER.bits
570 | TypeFlags::HAS_FREE_LOCAL_REGIONS.bits;
572 /// Does this have [Projection] or [UnnormalizedProjection]?
573 const HAS_TY_PROJECTION = 1 << 10;
574 /// Does this have [Opaque]?
575 const HAS_TY_OPAQUE = 1 << 11;
576 /// Does this have [ConstKind::Unevaluated]?
577 const HAS_CT_PROJECTION = 1 << 12;
579 /// Could this type be normalized further?
580 const HAS_PROJECTION = TypeFlags::HAS_TY_PROJECTION.bits
581 | TypeFlags::HAS_TY_OPAQUE.bits
582 | TypeFlags::HAS_CT_PROJECTION.bits;
584 /// Present if the type belongs in a local type context.
585 /// Set for placeholders and inference variables that are not "Fresh".
586 const KEEP_IN_LOCAL_TCX = 1 << 13;
588 /// Is an error type reachable?
589 const HAS_TY_ERR = 1 << 14;
591 /// Does this have any region that "appears free" in the type?
592 /// Basically anything but [ReLateBound] and [ReErased].
593 const HAS_FREE_REGIONS = 1 << 15;
595 /// Does this have any [ReLateBound] regions? Used to check
596 /// if a global bound is safe to evaluate.
597 const HAS_RE_LATE_BOUND = 1 << 16;
599 /// Does this have any [ReErased] regions?
600 const HAS_RE_ERASED = 1 << 17;
602 /// Flags representing the nominal content of a type,
603 /// computed by FlagsComputation. If you add a new nominal
604 /// flag, it should be added here too.
605 const NOMINAL_FLAGS = TypeFlags::HAS_TY_PARAM.bits
606 | TypeFlags::HAS_RE_PARAM.bits
607 | TypeFlags::HAS_CT_PARAM.bits
608 | TypeFlags::HAS_TY_INFER.bits
609 | TypeFlags::HAS_RE_INFER.bits
610 | TypeFlags::HAS_CT_INFER.bits
611 | TypeFlags::HAS_TY_PLACEHOLDER.bits
612 | TypeFlags::HAS_RE_PLACEHOLDER.bits
613 | TypeFlags::HAS_CT_PLACEHOLDER.bits
614 | TypeFlags::HAS_FREE_LOCAL_REGIONS.bits
615 | TypeFlags::HAS_TY_PROJECTION.bits
616 | TypeFlags::HAS_TY_OPAQUE.bits
617 | TypeFlags::HAS_CT_PROJECTION.bits
618 | TypeFlags::KEEP_IN_LOCAL_TCX.bits
619 | TypeFlags::HAS_TY_ERR.bits
620 | TypeFlags::HAS_FREE_REGIONS.bits
621 | TypeFlags::HAS_RE_LATE_BOUND.bits
622 | TypeFlags::HAS_RE_ERASED.bits;
626 #[allow(rustc::usage_of_ty_tykind)]
627 pub struct TyS<'tcx> {
628 pub kind: TyKind<'tcx>,
629 pub flags: TypeFlags,
631 /// This is a kind of confusing thing: it stores the smallest
634 /// (a) the binder itself captures nothing but
635 /// (b) all the late-bound things within the type are captured
636 /// by some sub-binder.
638 /// So, for a type without any late-bound things, like `u32`, this
639 /// will be *innermost*, because that is the innermost binder that
640 /// captures nothing. But for a type `&'D u32`, where `'D` is a
641 /// late-bound region with De Bruijn index `D`, this would be `D + 1`
642 /// -- the binder itself does not capture `D`, but `D` is captured
643 /// by an inner binder.
645 /// We call this concept an "exclusive" binder `D` because all
646 /// De Bruijn indices within the type are contained within `0..D`
648 outer_exclusive_binder: ty::DebruijnIndex,
651 // `TyS` is used a lot. Make sure it doesn't unintentionally get bigger.
652 #[cfg(target_arch = "x86_64")]
653 static_assert_size!(TyS<'_>, 32);
655 impl<'tcx> Ord for TyS<'tcx> {
656 fn cmp(&self, other: &TyS<'tcx>) -> Ordering {
657 self.kind.cmp(&other.kind)
661 impl<'tcx> PartialOrd for TyS<'tcx> {
662 fn partial_cmp(&self, other: &TyS<'tcx>) -> Option<Ordering> {
663 Some(self.kind.cmp(&other.kind))
667 impl<'tcx> PartialEq for TyS<'tcx> {
669 fn eq(&self, other: &TyS<'tcx>) -> bool {
673 impl<'tcx> Eq for TyS<'tcx> {}
675 impl<'tcx> Hash for TyS<'tcx> {
676 fn hash<H: Hasher>(&self, s: &mut H) {
677 (self as *const TyS<'_>).hash(s)
681 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for ty::TyS<'tcx> {
682 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
686 // The other fields just provide fast access to information that is
687 // also contained in `kind`, so no need to hash them.
690 outer_exclusive_binder: _,
693 kind.hash_stable(hcx, hasher);
697 #[rustc_diagnostic_item = "Ty"]
698 pub type Ty<'tcx> = &'tcx TyS<'tcx>;
700 impl<'tcx> rustc_serialize::UseSpecializedEncodable for Ty<'tcx> {}
701 impl<'tcx> rustc_serialize::UseSpecializedDecodable for Ty<'tcx> {}
703 pub type CanonicalTy<'tcx> = Canonical<'tcx, Ty<'tcx>>;
706 /// A dummy type used to force `List` to be unsized while not requiring references to it be wide
708 type OpaqueListContents;
711 /// A wrapper for slices with the additional invariant
712 /// that the slice is interned and no other slice with
713 /// the same contents can exist in the same context.
714 /// This means we can use pointer for both
715 /// equality comparisons and hashing.
716 /// Note: `Slice` was already taken by the `Ty`.
721 opaque: OpaqueListContents,
724 unsafe impl<T: Sync> Sync for List<T> {}
726 impl<T: Copy> List<T> {
728 fn from_arena<'tcx>(arena: &'tcx Arena<'tcx>, slice: &[T]) -> &'tcx List<T> {
729 assert!(!mem::needs_drop::<T>());
730 assert!(mem::size_of::<T>() != 0);
731 assert!(!slice.is_empty());
733 // Align up the size of the len (usize) field
734 let align = mem::align_of::<T>();
735 let align_mask = align - 1;
736 let offset = mem::size_of::<usize>();
737 let offset = (offset + align_mask) & !align_mask;
739 let size = offset + slice.len() * mem::size_of::<T>();
743 .alloc_raw(size, cmp::max(mem::align_of::<T>(), mem::align_of::<usize>()));
745 let result = &mut *(mem.as_mut_ptr() as *mut List<T>);
747 result.len = slice.len();
749 // Write the elements
750 let arena_slice = slice::from_raw_parts_mut(result.data.as_mut_ptr(), result.len);
751 arena_slice.copy_from_slice(slice);
758 impl<T: fmt::Debug> fmt::Debug for List<T> {
759 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
764 impl<T: Encodable> Encodable for List<T> {
766 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
771 impl<T> Ord for List<T>
775 fn cmp(&self, other: &List<T>) -> Ordering {
776 if self == other { Ordering::Equal } else { <[T] as Ord>::cmp(&**self, &**other) }
780 impl<T> PartialOrd for List<T>
784 fn partial_cmp(&self, other: &List<T>) -> Option<Ordering> {
786 Some(Ordering::Equal)
788 <[T] as PartialOrd>::partial_cmp(&**self, &**other)
793 impl<T: PartialEq> PartialEq for List<T> {
795 fn eq(&self, other: &List<T>) -> bool {
799 impl<T: Eq> Eq for List<T> {}
801 impl<T> Hash for List<T> {
803 fn hash<H: Hasher>(&self, s: &mut H) {
804 (self as *const List<T>).hash(s)
808 impl<T> Deref for List<T> {
811 fn deref(&self) -> &[T] {
816 impl<T> AsRef<[T]> for List<T> {
818 fn as_ref(&self) -> &[T] {
819 unsafe { slice::from_raw_parts(self.data.as_ptr(), self.len) }
823 impl<'a, T> IntoIterator for &'a List<T> {
825 type IntoIter = <&'a [T] as IntoIterator>::IntoIter;
827 fn into_iter(self) -> Self::IntoIter {
832 impl<'tcx> rustc_serialize::UseSpecializedDecodable for &'tcx List<Ty<'tcx>> {}
836 pub fn empty<'a>() -> &'a List<T> {
837 #[repr(align(64), C)]
838 struct EmptySlice([u8; 64]);
839 static EMPTY_SLICE: EmptySlice = EmptySlice([0; 64]);
840 assert!(mem::align_of::<T>() <= 64);
841 unsafe { &*(&EMPTY_SLICE as *const _ as *const List<T>) }
845 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
846 pub struct UpvarPath {
847 pub hir_id: hir::HirId,
850 /// Upvars do not get their own `NodeId`. Instead, we use the pair of
851 /// the original var ID (that is, the root variable that is referenced
852 /// by the upvar) and the ID of the closure expression.
853 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
855 pub var_path: UpvarPath,
856 pub closure_expr_id: LocalDefId,
859 #[derive(Clone, PartialEq, Debug, RustcEncodable, RustcDecodable, Copy, HashStable)]
860 pub enum BorrowKind {
861 /// Data must be immutable and is aliasable.
864 /// Data must be immutable but not aliasable. This kind of borrow
865 /// cannot currently be expressed by the user and is used only in
866 /// implicit closure bindings. It is needed when the closure
867 /// is borrowing or mutating a mutable referent, e.g.:
869 /// let x: &mut isize = ...;
870 /// let y = || *x += 5;
872 /// If we were to try to translate this closure into a more explicit
873 /// form, we'd encounter an error with the code as written:
875 /// struct Env { x: & &mut isize }
876 /// let x: &mut isize = ...;
877 /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
878 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
880 /// This is then illegal because you cannot mutate a `&mut` found
881 /// in an aliasable location. To solve, you'd have to translate with
882 /// an `&mut` borrow:
884 /// struct Env { x: & &mut isize }
885 /// let x: &mut isize = ...;
886 /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
887 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
889 /// Now the assignment to `**env.x` is legal, but creating a
890 /// mutable pointer to `x` is not because `x` is not mutable. We
891 /// could fix this by declaring `x` as `let mut x`. This is ok in
892 /// user code, if awkward, but extra weird for closures, since the
893 /// borrow is hidden.
895 /// So we introduce a "unique imm" borrow -- the referent is
896 /// immutable, but not aliasable. This solves the problem. For
897 /// simplicity, we don't give users the way to express this
898 /// borrow, it's just used when translating closures.
901 /// Data is mutable and not aliasable.
905 /// Information describing the capture of an upvar. This is computed
906 /// during `typeck`, specifically by `regionck`.
907 #[derive(PartialEq, Clone, Debug, Copy, RustcEncodable, RustcDecodable, HashStable)]
908 pub enum UpvarCapture<'tcx> {
909 /// Upvar is captured by value. This is always true when the
910 /// closure is labeled `move`, but can also be true in other cases
911 /// depending on inference.
914 /// Upvar is captured by reference.
915 ByRef(UpvarBorrow<'tcx>),
918 #[derive(PartialEq, Clone, Copy, RustcEncodable, RustcDecodable, HashStable)]
919 pub struct UpvarBorrow<'tcx> {
920 /// The kind of borrow: by-ref upvars have access to shared
921 /// immutable borrows, which are not part of the normal language
923 pub kind: BorrowKind,
925 /// Region of the resulting reference.
926 pub region: ty::Region<'tcx>,
929 pub type UpvarListMap = FxHashMap<DefId, FxIndexMap<hir::HirId, UpvarId>>;
930 pub type UpvarCaptureMap<'tcx> = FxHashMap<UpvarId, UpvarCapture<'tcx>>;
932 #[derive(Clone, Copy, PartialEq, Eq)]
933 pub enum IntVarValue {
935 UintType(ast::UintTy),
938 #[derive(Clone, Copy, PartialEq, Eq)]
939 pub struct FloatVarValue(pub ast::FloatTy);
941 impl ty::EarlyBoundRegion {
942 pub fn to_bound_region(&self) -> ty::BoundRegion {
943 ty::BoundRegion::BrNamed(self.def_id, self.name)
946 /// Does this early bound region have a name? Early bound regions normally
947 /// always have names except when using anonymous lifetimes (`'_`).
948 pub fn has_name(&self) -> bool {
949 self.name != kw::UnderscoreLifetime
953 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
954 pub enum GenericParamDefKind {
958 object_lifetime_default: ObjectLifetimeDefault,
959 synthetic: Option<hir::SyntheticTyParamKind>,
964 impl GenericParamDefKind {
965 pub fn descr(&self) -> &'static str {
967 GenericParamDefKind::Lifetime => "lifetime",
968 GenericParamDefKind::Type { .. } => "type",
969 GenericParamDefKind::Const => "constant",
974 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
975 pub struct GenericParamDef {
980 /// `pure_wrt_drop`, set by the (unsafe) `#[may_dangle]` attribute
981 /// on generic parameter `'a`/`T`, asserts data behind the parameter
982 /// `'a`/`T` won't be accessed during the parent type's `Drop` impl.
983 pub pure_wrt_drop: bool,
985 pub kind: GenericParamDefKind,
988 impl GenericParamDef {
989 pub fn to_early_bound_region_data(&self) -> ty::EarlyBoundRegion {
990 if let GenericParamDefKind::Lifetime = self.kind {
991 ty::EarlyBoundRegion { def_id: self.def_id, index: self.index, name: self.name }
993 bug!("cannot convert a non-lifetime parameter def to an early bound region")
997 pub fn to_bound_region(&self) -> ty::BoundRegion {
998 if let GenericParamDefKind::Lifetime = self.kind {
999 self.to_early_bound_region_data().to_bound_region()
1001 bug!("cannot convert a non-lifetime parameter def to an early bound region")
1007 pub struct GenericParamCount {
1008 pub lifetimes: usize,
1013 /// Information about the formal type/lifetime parameters associated
1014 /// with an item or method. Analogous to `hir::Generics`.
1016 /// The ordering of parameters is the same as in `Subst` (excluding child generics):
1017 /// `Self` (optionally), `Lifetime` params..., `Type` params...
1018 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
1019 pub struct Generics {
1020 pub parent: Option<DefId>,
1021 pub parent_count: usize,
1022 pub params: Vec<GenericParamDef>,
1024 /// Reverse map to the `index` field of each `GenericParamDef`.
1025 #[stable_hasher(ignore)]
1026 pub param_def_id_to_index: FxHashMap<DefId, u32>,
1029 pub has_late_bound_regions: Option<Span>,
1032 impl<'tcx> Generics {
1033 pub fn count(&self) -> usize {
1034 self.parent_count + self.params.len()
1037 pub fn own_counts(&self) -> GenericParamCount {
1038 // We could cache this as a property of `GenericParamCount`, but
1039 // the aim is to refactor this away entirely eventually and the
1040 // presence of this method will be a constant reminder.
1041 let mut own_counts: GenericParamCount = Default::default();
1043 for param in &self.params {
1045 GenericParamDefKind::Lifetime => own_counts.lifetimes += 1,
1046 GenericParamDefKind::Type { .. } => own_counts.types += 1,
1047 GenericParamDefKind::Const => own_counts.consts += 1,
1054 pub fn requires_monomorphization(&self, tcx: TyCtxt<'tcx>) -> bool {
1055 if self.own_requires_monomorphization() {
1059 if let Some(parent_def_id) = self.parent {
1060 let parent = tcx.generics_of(parent_def_id);
1061 parent.requires_monomorphization(tcx)
1067 pub fn own_requires_monomorphization(&self) -> bool {
1068 for param in &self.params {
1070 GenericParamDefKind::Type { .. } | GenericParamDefKind::Const => return true,
1071 GenericParamDefKind::Lifetime => {}
1077 pub fn region_param(
1079 param: &EarlyBoundRegion,
1081 ) -> &'tcx GenericParamDef {
1082 if let Some(index) = param.index.checked_sub(self.parent_count as u32) {
1083 let param = &self.params[index as usize];
1085 GenericParamDefKind::Lifetime => param,
1086 _ => bug!("expected lifetime parameter, but found another generic parameter"),
1089 tcx.generics_of(self.parent.expect("parent_count > 0 but no parent?"))
1090 .region_param(param, tcx)
1094 /// Returns the `GenericParamDef` associated with this `ParamTy`.
1095 pub fn type_param(&'tcx self, param: &ParamTy, tcx: TyCtxt<'tcx>) -> &'tcx GenericParamDef {
1096 if let Some(index) = param.index.checked_sub(self.parent_count as u32) {
1097 let param = &self.params[index as usize];
1099 GenericParamDefKind::Type { .. } => param,
1100 _ => bug!("expected type parameter, but found another generic parameter"),
1103 tcx.generics_of(self.parent.expect("parent_count > 0 but no parent?"))
1104 .type_param(param, tcx)
1108 /// Returns the `ConstParameterDef` associated with this `ParamConst`.
1109 pub fn const_param(&'tcx self, param: &ParamConst, tcx: TyCtxt<'tcx>) -> &GenericParamDef {
1110 if let Some(index) = param.index.checked_sub(self.parent_count as u32) {
1111 let param = &self.params[index as usize];
1113 GenericParamDefKind::Const => param,
1114 _ => bug!("expected const parameter, but found another generic parameter"),
1117 tcx.generics_of(self.parent.expect("parent_count>0 but no parent?"))
1118 .const_param(param, tcx)
1123 /// Bounds on generics.
1124 #[derive(Copy, Clone, Default, Debug, RustcEncodable, RustcDecodable, HashStable)]
1125 pub struct GenericPredicates<'tcx> {
1126 pub parent: Option<DefId>,
1127 pub predicates: &'tcx [(Predicate<'tcx>, Span)],
1130 impl<'tcx> GenericPredicates<'tcx> {
1134 substs: SubstsRef<'tcx>,
1135 ) -> InstantiatedPredicates<'tcx> {
1136 let mut instantiated = InstantiatedPredicates::empty();
1137 self.instantiate_into(tcx, &mut instantiated, substs);
1141 pub fn instantiate_own(
1144 substs: SubstsRef<'tcx>,
1145 ) -> InstantiatedPredicates<'tcx> {
1146 InstantiatedPredicates {
1147 predicates: self.predicates.iter().map(|(p, _)| p.subst(tcx, substs)).collect(),
1148 spans: self.predicates.iter().map(|(_, sp)| *sp).collect(),
1152 fn instantiate_into(
1155 instantiated: &mut InstantiatedPredicates<'tcx>,
1156 substs: SubstsRef<'tcx>,
1158 if let Some(def_id) = self.parent {
1159 tcx.predicates_of(def_id).instantiate_into(tcx, instantiated, substs);
1161 instantiated.predicates.extend(self.predicates.iter().map(|(p, _)| p.subst(tcx, substs)));
1162 instantiated.spans.extend(self.predicates.iter().map(|(_, sp)| *sp));
1165 pub fn instantiate_identity(&self, tcx: TyCtxt<'tcx>) -> InstantiatedPredicates<'tcx> {
1166 let mut instantiated = InstantiatedPredicates::empty();
1167 self.instantiate_identity_into(tcx, &mut instantiated);
1171 fn instantiate_identity_into(
1174 instantiated: &mut InstantiatedPredicates<'tcx>,
1176 if let Some(def_id) = self.parent {
1177 tcx.predicates_of(def_id).instantiate_identity_into(tcx, instantiated);
1179 instantiated.predicates.extend(self.predicates.iter().map(|(p, _)| p));
1180 instantiated.spans.extend(self.predicates.iter().map(|(_, s)| s));
1183 pub fn instantiate_supertrait(
1186 poly_trait_ref: &ty::PolyTraitRef<'tcx>,
1187 ) -> InstantiatedPredicates<'tcx> {
1188 assert_eq!(self.parent, None);
1189 InstantiatedPredicates {
1193 .map(|(pred, _)| pred.subst_supertrait(tcx, poly_trait_ref))
1195 spans: self.predicates.iter().map(|(_, sp)| *sp).collect(),
1200 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1201 #[derive(HashStable, TypeFoldable)]
1202 pub enum Predicate<'tcx> {
1203 /// Corresponds to `where Foo: Bar<A, B, C>`. `Foo` here would be
1204 /// the `Self` type of the trait reference and `A`, `B`, and `C`
1205 /// would be the type parameters.
1207 /// A trait predicate will have `Constness::Const` if it originates
1208 /// from a bound on a `const fn` without the `?const` opt-out (e.g.,
1209 /// `const fn foobar<Foo: Bar>() {}`).
1210 Trait(PolyTraitPredicate<'tcx>, Constness),
1213 RegionOutlives(PolyRegionOutlivesPredicate<'tcx>),
1216 TypeOutlives(PolyTypeOutlivesPredicate<'tcx>),
1218 /// `where <T as TraitRef>::Name == X`, approximately.
1219 /// See the `ProjectionPredicate` struct for details.
1220 Projection(PolyProjectionPredicate<'tcx>),
1222 /// No syntax: `T` well-formed.
1223 WellFormed(Ty<'tcx>),
1225 /// Trait must be object-safe.
1228 /// No direct syntax. May be thought of as `where T: FnFoo<...>`
1229 /// for some substitutions `...` and `T` being a closure type.
1230 /// Satisfied (or refuted) once we know the closure's kind.
1231 ClosureKind(DefId, SubstsRef<'tcx>, ClosureKind),
1234 Subtype(PolySubtypePredicate<'tcx>),
1236 /// Constant initializer must evaluate successfully.
1237 ConstEvaluatable(DefId, SubstsRef<'tcx>),
1240 /// The crate outlives map is computed during typeck and contains the
1241 /// outlives of every item in the local crate. You should not use it
1242 /// directly, because to do so will make your pass dependent on the
1243 /// HIR of every item in the local crate. Instead, use
1244 /// `tcx.inferred_outlives_of()` to get the outlives for a *particular*
1246 #[derive(HashStable)]
1247 pub struct CratePredicatesMap<'tcx> {
1248 /// For each struct with outlive bounds, maps to a vector of the
1249 /// predicate of its outlive bounds. If an item has no outlives
1250 /// bounds, it will have no entry.
1251 pub predicates: FxHashMap<DefId, &'tcx [(ty::Predicate<'tcx>, Span)]>,
1254 impl<'tcx> AsRef<Predicate<'tcx>> for Predicate<'tcx> {
1255 fn as_ref(&self) -> &Predicate<'tcx> {
1260 impl<'tcx> Predicate<'tcx> {
1261 /// Performs a substitution suitable for going from a
1262 /// poly-trait-ref to supertraits that must hold if that
1263 /// poly-trait-ref holds. This is slightly different from a normal
1264 /// substitution in terms of what happens with bound regions. See
1265 /// lengthy comment below for details.
1266 pub fn subst_supertrait(
1269 trait_ref: &ty::PolyTraitRef<'tcx>,
1270 ) -> ty::Predicate<'tcx> {
1271 // The interaction between HRTB and supertraits is not entirely
1272 // obvious. Let me walk you (and myself) through an example.
1274 // Let's start with an easy case. Consider two traits:
1276 // trait Foo<'a>: Bar<'a,'a> { }
1277 // trait Bar<'b,'c> { }
1279 // Now, if we have a trait reference `for<'x> T: Foo<'x>`, then
1280 // we can deduce that `for<'x> T: Bar<'x,'x>`. Basically, if we
1281 // knew that `Foo<'x>` (for any 'x) then we also know that
1282 // `Bar<'x,'x>` (for any 'x). This more-or-less falls out from
1283 // normal substitution.
1285 // In terms of why this is sound, the idea is that whenever there
1286 // is an impl of `T:Foo<'a>`, it must show that `T:Bar<'a,'a>`
1287 // holds. So if there is an impl of `T:Foo<'a>` that applies to
1288 // all `'a`, then we must know that `T:Bar<'a,'a>` holds for all
1291 // Another example to be careful of is this:
1293 // trait Foo1<'a>: for<'b> Bar1<'a,'b> { }
1294 // trait Bar1<'b,'c> { }
1296 // Here, if we have `for<'x> T: Foo1<'x>`, then what do we know?
1297 // The answer is that we know `for<'x,'b> T: Bar1<'x,'b>`. The
1298 // reason is similar to the previous example: any impl of
1299 // `T:Foo1<'x>` must show that `for<'b> T: Bar1<'x, 'b>`. So
1300 // basically we would want to collapse the bound lifetimes from
1301 // the input (`trait_ref`) and the supertraits.
1303 // To achieve this in practice is fairly straightforward. Let's
1304 // consider the more complicated scenario:
1306 // - We start out with `for<'x> T: Foo1<'x>`. In this case, `'x`
1307 // has a De Bruijn index of 1. We want to produce `for<'x,'b> T: Bar1<'x,'b>`,
1308 // where both `'x` and `'b` would have a DB index of 1.
1309 // The substitution from the input trait-ref is therefore going to be
1310 // `'a => 'x` (where `'x` has a DB index of 1).
1311 // - The super-trait-ref is `for<'b> Bar1<'a,'b>`, where `'a` is an
1312 // early-bound parameter and `'b' is a late-bound parameter with a
1314 // - If we replace `'a` with `'x` from the input, it too will have
1315 // a DB index of 1, and thus we'll have `for<'x,'b> Bar1<'x,'b>`
1316 // just as we wanted.
1318 // There is only one catch. If we just apply the substitution `'a
1319 // => 'x` to `for<'b> Bar1<'a,'b>`, the substitution code will
1320 // adjust the DB index because we substituting into a binder (it
1321 // tries to be so smart...) resulting in `for<'x> for<'b>
1322 // Bar1<'x,'b>` (we have no syntax for this, so use your
1323 // imagination). Basically the 'x will have DB index of 2 and 'b
1324 // will have DB index of 1. Not quite what we want. So we apply
1325 // the substitution to the *contents* of the trait reference,
1326 // rather than the trait reference itself (put another way, the
1327 // substitution code expects equal binding levels in the values
1328 // from the substitution and the value being substituted into, and
1329 // this trick achieves that).
1331 let substs = &trait_ref.skip_binder().substs;
1333 Predicate::Trait(ref binder, constness) => {
1334 Predicate::Trait(binder.map_bound(|data| data.subst(tcx, substs)), constness)
1336 Predicate::Subtype(ref binder) => {
1337 Predicate::Subtype(binder.map_bound(|data| data.subst(tcx, substs)))
1339 Predicate::RegionOutlives(ref binder) => {
1340 Predicate::RegionOutlives(binder.map_bound(|data| data.subst(tcx, substs)))
1342 Predicate::TypeOutlives(ref binder) => {
1343 Predicate::TypeOutlives(binder.map_bound(|data| data.subst(tcx, substs)))
1345 Predicate::Projection(ref binder) => {
1346 Predicate::Projection(binder.map_bound(|data| data.subst(tcx, substs)))
1348 Predicate::WellFormed(data) => Predicate::WellFormed(data.subst(tcx, substs)),
1349 Predicate::ObjectSafe(trait_def_id) => Predicate::ObjectSafe(trait_def_id),
1350 Predicate::ClosureKind(closure_def_id, closure_substs, kind) => {
1351 Predicate::ClosureKind(closure_def_id, closure_substs.subst(tcx, substs), kind)
1353 Predicate::ConstEvaluatable(def_id, const_substs) => {
1354 Predicate::ConstEvaluatable(def_id, const_substs.subst(tcx, substs))
1360 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1361 #[derive(HashStable, TypeFoldable)]
1362 pub struct TraitPredicate<'tcx> {
1363 pub trait_ref: TraitRef<'tcx>,
1366 pub type PolyTraitPredicate<'tcx> = ty::Binder<TraitPredicate<'tcx>>;
1368 impl<'tcx> TraitPredicate<'tcx> {
1369 pub fn def_id(&self) -> DefId {
1370 self.trait_ref.def_id
1373 pub fn input_types<'a>(&'a self) -> impl DoubleEndedIterator<Item = Ty<'tcx>> + 'a {
1374 self.trait_ref.input_types()
1377 pub fn self_ty(&self) -> Ty<'tcx> {
1378 self.trait_ref.self_ty()
1382 impl<'tcx> PolyTraitPredicate<'tcx> {
1383 pub fn def_id(&self) -> DefId {
1384 // Ok to skip binder since trait `DefId` does not care about regions.
1385 self.skip_binder().def_id()
1389 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, RustcEncodable, RustcDecodable)]
1390 #[derive(HashStable, TypeFoldable)]
1391 pub struct OutlivesPredicate<A, B>(pub A, pub B); // `A: B`
1392 pub type PolyOutlivesPredicate<A, B> = ty::Binder<OutlivesPredicate<A, B>>;
1393 pub type RegionOutlivesPredicate<'tcx> = OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>;
1394 pub type TypeOutlivesPredicate<'tcx> = OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>;
1395 pub type PolyRegionOutlivesPredicate<'tcx> = ty::Binder<RegionOutlivesPredicate<'tcx>>;
1396 pub type PolyTypeOutlivesPredicate<'tcx> = ty::Binder<TypeOutlivesPredicate<'tcx>>;
1398 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
1399 #[derive(HashStable, TypeFoldable)]
1400 pub struct SubtypePredicate<'tcx> {
1401 pub a_is_expected: bool,
1405 pub type PolySubtypePredicate<'tcx> = ty::Binder<SubtypePredicate<'tcx>>;
1407 /// This kind of predicate has no *direct* correspondent in the
1408 /// syntax, but it roughly corresponds to the syntactic forms:
1410 /// 1. `T: TraitRef<..., Item = Type>`
1411 /// 2. `<T as TraitRef<...>>::Item == Type` (NYI)
1413 /// In particular, form #1 is "desugared" to the combination of a
1414 /// normal trait predicate (`T: TraitRef<...>`) and one of these
1415 /// predicates. Form #2 is a broader form in that it also permits
1416 /// equality between arbitrary types. Processing an instance of
1417 /// Form #2 eventually yields one of these `ProjectionPredicate`
1418 /// instances to normalize the LHS.
1419 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1420 #[derive(HashStable, TypeFoldable)]
1421 pub struct ProjectionPredicate<'tcx> {
1422 pub projection_ty: ProjectionTy<'tcx>,
1426 pub type PolyProjectionPredicate<'tcx> = Binder<ProjectionPredicate<'tcx>>;
1428 impl<'tcx> PolyProjectionPredicate<'tcx> {
1429 /// Returns the `DefId` of the associated item being projected.
1430 pub fn item_def_id(&self) -> DefId {
1431 self.skip_binder().projection_ty.item_def_id
1435 pub fn to_poly_trait_ref(&self, tcx: TyCtxt<'tcx>) -> PolyTraitRef<'tcx> {
1436 // Note: unlike with `TraitRef::to_poly_trait_ref()`,
1437 // `self.0.trait_ref` is permitted to have escaping regions.
1438 // This is because here `self` has a `Binder` and so does our
1439 // return value, so we are preserving the number of binding
1441 self.map_bound(|predicate| predicate.projection_ty.trait_ref(tcx))
1444 pub fn ty(&self) -> Binder<Ty<'tcx>> {
1445 self.map_bound(|predicate| predicate.ty)
1448 /// The `DefId` of the `TraitItem` for the associated type.
1450 /// Note that this is not the `DefId` of the `TraitRef` containing this
1451 /// associated type, which is in `tcx.associated_item(projection_def_id()).container`.
1452 pub fn projection_def_id(&self) -> DefId {
1453 // Ok to skip binder since trait `DefId` does not care about regions.
1454 self.skip_binder().projection_ty.item_def_id
1458 pub trait ToPolyTraitRef<'tcx> {
1459 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx>;
1462 impl<'tcx> ToPolyTraitRef<'tcx> for TraitRef<'tcx> {
1463 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
1464 ty::Binder::dummy(*self)
1468 impl<'tcx> ToPolyTraitRef<'tcx> for PolyTraitPredicate<'tcx> {
1469 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
1470 self.map_bound_ref(|trait_pred| trait_pred.trait_ref)
1474 pub trait ToPredicate<'tcx> {
1475 fn to_predicate(&self) -> Predicate<'tcx>;
1478 impl<'tcx> ToPredicate<'tcx> for ConstnessAnd<TraitRef<'tcx>> {
1479 fn to_predicate(&self) -> Predicate<'tcx> {
1480 ty::Predicate::Trait(
1481 ty::Binder::dummy(ty::TraitPredicate { trait_ref: self.value }),
1487 impl<'tcx> ToPredicate<'tcx> for ConstnessAnd<&TraitRef<'tcx>> {
1488 fn to_predicate(&self) -> Predicate<'tcx> {
1489 ty::Predicate::Trait(
1490 ty::Binder::dummy(ty::TraitPredicate { trait_ref: *self.value }),
1496 impl<'tcx> ToPredicate<'tcx> for ConstnessAnd<PolyTraitRef<'tcx>> {
1497 fn to_predicate(&self) -> Predicate<'tcx> {
1498 ty::Predicate::Trait(self.value.to_poly_trait_predicate(), self.constness)
1502 impl<'tcx> ToPredicate<'tcx> for ConstnessAnd<&PolyTraitRef<'tcx>> {
1503 fn to_predicate(&self) -> Predicate<'tcx> {
1504 ty::Predicate::Trait(self.value.to_poly_trait_predicate(), self.constness)
1508 impl<'tcx> ToPredicate<'tcx> for PolyRegionOutlivesPredicate<'tcx> {
1509 fn to_predicate(&self) -> Predicate<'tcx> {
1510 Predicate::RegionOutlives(*self)
1514 impl<'tcx> ToPredicate<'tcx> for PolyTypeOutlivesPredicate<'tcx> {
1515 fn to_predicate(&self) -> Predicate<'tcx> {
1516 Predicate::TypeOutlives(*self)
1520 impl<'tcx> ToPredicate<'tcx> for PolyProjectionPredicate<'tcx> {
1521 fn to_predicate(&self) -> Predicate<'tcx> {
1522 Predicate::Projection(*self)
1526 // A custom iterator used by `Predicate::walk_tys`.
1527 enum WalkTysIter<'tcx, I, J, K>
1529 I: Iterator<Item = Ty<'tcx>>,
1530 J: Iterator<Item = Ty<'tcx>>,
1531 K: Iterator<Item = Ty<'tcx>>,
1535 Two(Ty<'tcx>, Ty<'tcx>),
1541 impl<'tcx, I, J, K> Iterator for WalkTysIter<'tcx, I, J, K>
1543 I: Iterator<Item = Ty<'tcx>>,
1544 J: Iterator<Item = Ty<'tcx>>,
1545 K: Iterator<Item = Ty<'tcx>>,
1547 type Item = Ty<'tcx>;
1549 fn next(&mut self) -> Option<Ty<'tcx>> {
1551 WalkTysIter::None => None,
1552 WalkTysIter::One(item) => {
1553 *self = WalkTysIter::None;
1556 WalkTysIter::Two(item1, item2) => {
1557 *self = WalkTysIter::One(item2);
1560 WalkTysIter::Types(ref mut iter) => iter.next(),
1561 WalkTysIter::InputTypes(ref mut iter) => iter.next(),
1562 WalkTysIter::ProjectionTypes(ref mut iter) => iter.next(),
1567 impl<'tcx> Predicate<'tcx> {
1568 /// Iterates over the types in this predicate. Note that in all
1569 /// cases this is skipping over a binder, so late-bound regions
1570 /// with depth 0 are bound by the predicate.
1571 pub fn walk_tys(&'a self) -> impl Iterator<Item = Ty<'tcx>> + 'a {
1573 ty::Predicate::Trait(ref data, _) => {
1574 WalkTysIter::InputTypes(data.skip_binder().input_types())
1576 ty::Predicate::Subtype(binder) => {
1577 let SubtypePredicate { a, b, a_is_expected: _ } = binder.skip_binder();
1578 WalkTysIter::Two(a, b)
1580 ty::Predicate::TypeOutlives(binder) => WalkTysIter::One(binder.skip_binder().0),
1581 ty::Predicate::RegionOutlives(..) => WalkTysIter::None,
1582 ty::Predicate::Projection(ref data) => {
1583 let inner = data.skip_binder();
1584 WalkTysIter::ProjectionTypes(
1585 inner.projection_ty.substs.types().chain(Some(inner.ty)),
1588 ty::Predicate::WellFormed(data) => WalkTysIter::One(data),
1589 ty::Predicate::ObjectSafe(_trait_def_id) => WalkTysIter::None,
1590 ty::Predicate::ClosureKind(_closure_def_id, closure_substs, _kind) => {
1591 WalkTysIter::Types(closure_substs.types())
1593 ty::Predicate::ConstEvaluatable(_, substs) => WalkTysIter::Types(substs.types()),
1597 pub fn to_opt_poly_trait_ref(&self) -> Option<PolyTraitRef<'tcx>> {
1599 Predicate::Trait(ref t, _) => Some(t.to_poly_trait_ref()),
1600 Predicate::Projection(..)
1601 | Predicate::Subtype(..)
1602 | Predicate::RegionOutlives(..)
1603 | Predicate::WellFormed(..)
1604 | Predicate::ObjectSafe(..)
1605 | Predicate::ClosureKind(..)
1606 | Predicate::TypeOutlives(..)
1607 | Predicate::ConstEvaluatable(..) => None,
1611 pub fn to_opt_type_outlives(&self) -> Option<PolyTypeOutlivesPredicate<'tcx>> {
1613 Predicate::TypeOutlives(data) => Some(data),
1614 Predicate::Trait(..)
1615 | Predicate::Projection(..)
1616 | Predicate::Subtype(..)
1617 | Predicate::RegionOutlives(..)
1618 | Predicate::WellFormed(..)
1619 | Predicate::ObjectSafe(..)
1620 | Predicate::ClosureKind(..)
1621 | Predicate::ConstEvaluatable(..) => None,
1626 /// Represents the bounds declared on a particular set of type
1627 /// parameters. Should eventually be generalized into a flag list of
1628 /// where-clauses. You can obtain a `InstantiatedPredicates` list from a
1629 /// `GenericPredicates` by using the `instantiate` method. Note that this method
1630 /// reflects an important semantic invariant of `InstantiatedPredicates`: while
1631 /// the `GenericPredicates` are expressed in terms of the bound type
1632 /// parameters of the impl/trait/whatever, an `InstantiatedPredicates` instance
1633 /// represented a set of bounds for some particular instantiation,
1634 /// meaning that the generic parameters have been substituted with
1639 /// struct Foo<T, U: Bar<T>> { ... }
1641 /// Here, the `GenericPredicates` for `Foo` would contain a list of bounds like
1642 /// `[[], [U:Bar<T>]]`. Now if there were some particular reference
1643 /// like `Foo<isize,usize>`, then the `InstantiatedPredicates` would be `[[],
1644 /// [usize:Bar<isize>]]`.
1645 #[derive(Clone, Debug, TypeFoldable)]
1646 pub struct InstantiatedPredicates<'tcx> {
1647 pub predicates: Vec<Predicate<'tcx>>,
1648 pub spans: Vec<Span>,
1651 impl<'tcx> InstantiatedPredicates<'tcx> {
1652 pub fn empty() -> InstantiatedPredicates<'tcx> {
1653 InstantiatedPredicates { predicates: vec![], spans: vec![] }
1656 pub fn is_empty(&self) -> bool {
1657 self.predicates.is_empty()
1661 rustc_index::newtype_index! {
1662 /// "Universes" are used during type- and trait-checking in the
1663 /// presence of `for<..>` binders to control what sets of names are
1664 /// visible. Universes are arranged into a tree: the root universe
1665 /// contains names that are always visible. Each child then adds a new
1666 /// set of names that are visible, in addition to those of its parent.
1667 /// We say that the child universe "extends" the parent universe with
1670 /// To make this more concrete, consider this program:
1674 /// fn bar<T>(x: T) {
1675 /// let y: for<'a> fn(&'a u8, Foo) = ...;
1679 /// The struct name `Foo` is in the root universe U0. But the type
1680 /// parameter `T`, introduced on `bar`, is in an extended universe U1
1681 /// -- i.e., within `bar`, we can name both `T` and `Foo`, but outside
1682 /// of `bar`, we cannot name `T`. Then, within the type of `y`, the
1683 /// region `'a` is in a universe U2 that extends U1, because we can
1684 /// name it inside the fn type but not outside.
1686 /// Universes are used to do type- and trait-checking around these
1687 /// "forall" binders (also called **universal quantification**). The
1688 /// idea is that when, in the body of `bar`, we refer to `T` as a
1689 /// type, we aren't referring to any type in particular, but rather a
1690 /// kind of "fresh" type that is distinct from all other types we have
1691 /// actually declared. This is called a **placeholder** type, and we
1692 /// use universes to talk about this. In other words, a type name in
1693 /// universe 0 always corresponds to some "ground" type that the user
1694 /// declared, but a type name in a non-zero universe is a placeholder
1695 /// type -- an idealized representative of "types in general" that we
1696 /// use for checking generic functions.
1697 pub struct UniverseIndex {
1699 DEBUG_FORMAT = "U{}",
1703 impl UniverseIndex {
1704 pub const ROOT: UniverseIndex = UniverseIndex::from_u32(0);
1706 /// Returns the "next" universe index in order -- this new index
1707 /// is considered to extend all previous universes. This
1708 /// corresponds to entering a `forall` quantifier. So, for
1709 /// example, suppose we have this type in universe `U`:
1712 /// for<'a> fn(&'a u32)
1715 /// Once we "enter" into this `for<'a>` quantifier, we are in a
1716 /// new universe that extends `U` -- in this new universe, we can
1717 /// name the region `'a`, but that region was not nameable from
1718 /// `U` because it was not in scope there.
1719 pub fn next_universe(self) -> UniverseIndex {
1720 UniverseIndex::from_u32(self.private.checked_add(1).unwrap())
1723 /// Returns `true` if `self` can name a name from `other` -- in other words,
1724 /// if the set of names in `self` is a superset of those in
1725 /// `other` (`self >= other`).
1726 pub fn can_name(self, other: UniverseIndex) -> bool {
1727 self.private >= other.private
1730 /// Returns `true` if `self` cannot name some names from `other` -- in other
1731 /// words, if the set of names in `self` is a strict subset of
1732 /// those in `other` (`self < other`).
1733 pub fn cannot_name(self, other: UniverseIndex) -> bool {
1734 self.private < other.private
1738 /// The "placeholder index" fully defines a placeholder region.
1739 /// Placeholder regions are identified by both a **universe** as well
1740 /// as a "bound-region" within that universe. The `bound_region` is
1741 /// basically a name -- distinct bound regions within the same
1742 /// universe are just two regions with an unknown relationship to one
1744 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, PartialOrd, Ord)]
1745 pub struct Placeholder<T> {
1746 pub universe: UniverseIndex,
1750 impl<'a, T> HashStable<StableHashingContext<'a>> for Placeholder<T>
1752 T: HashStable<StableHashingContext<'a>>,
1754 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
1755 self.universe.hash_stable(hcx, hasher);
1756 self.name.hash_stable(hcx, hasher);
1760 pub type PlaceholderRegion = Placeholder<BoundRegion>;
1762 pub type PlaceholderType = Placeholder<BoundVar>;
1764 pub type PlaceholderConst = Placeholder<BoundVar>;
1766 /// When type checking, we use the `ParamEnv` to track
1767 /// details about the set of where-clauses that are in scope at this
1768 /// particular point.
1769 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable, TypeFoldable)]
1770 pub struct ParamEnv<'tcx> {
1771 /// `Obligation`s that the caller must satisfy. This is basically
1772 /// the set of bounds on the in-scope type parameters, translated
1773 /// into `Obligation`s, and elaborated and normalized.
1774 pub caller_bounds: &'tcx List<ty::Predicate<'tcx>>,
1776 /// Typically, this is `Reveal::UserFacing`, but during codegen we
1777 /// want `Reveal::All` -- note that this is always paired with an
1778 /// empty environment. To get that, use `ParamEnv::reveal()`.
1779 pub reveal: traits::Reveal,
1781 /// If this `ParamEnv` comes from a call to `tcx.param_env(def_id)`,
1782 /// register that `def_id` (useful for transitioning to the chalk trait
1784 pub def_id: Option<DefId>,
1787 impl<'tcx> ParamEnv<'tcx> {
1788 /// Construct a trait environment suitable for contexts where
1789 /// there are no where-clauses in scope. Hidden types (like `impl
1790 /// Trait`) are left hidden, so this is suitable for ordinary
1793 pub fn empty() -> Self {
1794 Self::new(List::empty(), Reveal::UserFacing, None)
1797 /// Construct a trait environment with no where-clauses in scope
1798 /// where the values of all `impl Trait` and other hidden types
1799 /// are revealed. This is suitable for monomorphized, post-typeck
1800 /// environments like codegen or doing optimizations.
1802 /// N.B., if you want to have predicates in scope, use `ParamEnv::new`,
1803 /// or invoke `param_env.with_reveal_all()`.
1805 pub fn reveal_all() -> Self {
1806 Self::new(List::empty(), Reveal::All, None)
1809 /// Construct a trait environment with the given set of predicates.
1812 caller_bounds: &'tcx List<ty::Predicate<'tcx>>,
1814 def_id: Option<DefId>,
1816 ty::ParamEnv { caller_bounds, reveal, def_id }
1819 /// Returns a new parameter environment with the same clauses, but
1820 /// which "reveals" the true results of projections in all cases
1821 /// (even for associated types that are specializable). This is
1822 /// the desired behavior during codegen and certain other special
1823 /// contexts; normally though we want to use `Reveal::UserFacing`,
1824 /// which is the default.
1825 pub fn with_reveal_all(self) -> Self {
1826 ty::ParamEnv { reveal: Reveal::All, ..self }
1829 /// Returns this same environment but with no caller bounds.
1830 pub fn without_caller_bounds(self) -> Self {
1831 ty::ParamEnv { caller_bounds: List::empty(), ..self }
1834 /// Creates a suitable environment in which to perform trait
1835 /// queries on the given value. When type-checking, this is simply
1836 /// the pair of the environment plus value. But when reveal is set to
1837 /// All, then if `value` does not reference any type parameters, we will
1838 /// pair it with the empty environment. This improves caching and is generally
1841 /// N.B., we preserve the environment when type-checking because it
1842 /// is possible for the user to have wacky where-clauses like
1843 /// `where Box<u32>: Copy`, which are clearly never
1844 /// satisfiable. We generally want to behave as if they were true,
1845 /// although the surrounding function is never reachable.
1846 pub fn and<T: TypeFoldable<'tcx>>(self, value: T) -> ParamEnvAnd<'tcx, T> {
1848 Reveal::UserFacing => ParamEnvAnd { param_env: self, value },
1851 if value.is_global() {
1852 ParamEnvAnd { param_env: self.without_caller_bounds(), value }
1854 ParamEnvAnd { param_env: self, value }
1861 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1862 pub struct ConstnessAnd<T> {
1863 pub constness: Constness,
1867 // FIXME(ecstaticmorse): Audit all occurrences of `without_const().to_predicate()` to ensure that
1868 // the constness of trait bounds is being propagated correctly.
1869 pub trait WithConstness: Sized {
1871 fn with_constness(self, constness: Constness) -> ConstnessAnd<Self> {
1872 ConstnessAnd { constness, value: self }
1876 fn with_const(self) -> ConstnessAnd<Self> {
1877 self.with_constness(Constness::Const)
1881 fn without_const(self) -> ConstnessAnd<Self> {
1882 self.with_constness(Constness::NotConst)
1886 impl<T> WithConstness for T {}
1888 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TypeFoldable)]
1889 pub struct ParamEnvAnd<'tcx, T> {
1890 pub param_env: ParamEnv<'tcx>,
1894 impl<'tcx, T> ParamEnvAnd<'tcx, T> {
1895 pub fn into_parts(self) -> (ParamEnv<'tcx>, T) {
1896 (self.param_env, self.value)
1900 impl<'a, 'tcx, T> HashStable<StableHashingContext<'a>> for ParamEnvAnd<'tcx, T>
1902 T: HashStable<StableHashingContext<'a>>,
1904 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
1905 let ParamEnvAnd { ref param_env, ref value } = *self;
1907 param_env.hash_stable(hcx, hasher);
1908 value.hash_stable(hcx, hasher);
1912 #[derive(Copy, Clone, Debug, HashStable)]
1913 pub struct Destructor {
1914 /// The `DefId` of the destructor method
1919 #[derive(HashStable)]
1920 pub struct AdtFlags: u32 {
1921 const NO_ADT_FLAGS = 0;
1922 /// Indicates whether the ADT is an enum.
1923 const IS_ENUM = 1 << 0;
1924 /// Indicates whether the ADT is a union.
1925 const IS_UNION = 1 << 1;
1926 /// Indicates whether the ADT is a struct.
1927 const IS_STRUCT = 1 << 2;
1928 /// Indicates whether the ADT is a struct and has a constructor.
1929 const HAS_CTOR = 1 << 3;
1930 /// Indicates whether the type is `PhantomData`.
1931 const IS_PHANTOM_DATA = 1 << 4;
1932 /// Indicates whether the type has a `#[fundamental]` attribute.
1933 const IS_FUNDAMENTAL = 1 << 5;
1934 /// Indicates whether the type is `Box`.
1935 const IS_BOX = 1 << 6;
1936 /// Indicates whether the type is `ManuallyDrop`.
1937 const IS_MANUALLY_DROP = 1 << 7;
1938 // FIXME(matthewjasper) replace these with diagnostic items
1939 /// Indicates whether the type is an `Arc`.
1940 const IS_ARC = 1 << 8;
1941 /// Indicates whether the type is an `Rc`.
1942 const IS_RC = 1 << 9;
1943 /// Indicates whether the variant list of this ADT is `#[non_exhaustive]`.
1944 /// (i.e., this flag is never set unless this ADT is an enum).
1945 const IS_VARIANT_LIST_NON_EXHAUSTIVE = 1 << 10;
1950 #[derive(HashStable)]
1951 pub struct VariantFlags: u32 {
1952 const NO_VARIANT_FLAGS = 0;
1953 /// Indicates whether the field list of this variant is `#[non_exhaustive]`.
1954 const IS_FIELD_LIST_NON_EXHAUSTIVE = 1 << 0;
1958 /// Definition of a variant -- a struct's fields or a enum variant.
1959 #[derive(Debug, HashStable)]
1960 pub struct VariantDef {
1961 /// `DefId` that identifies the variant itself.
1962 /// If this variant belongs to a struct or union, then this is a copy of its `DefId`.
1964 /// `DefId` that identifies the variant's constructor.
1965 /// If this variant is a struct variant, then this is `None`.
1966 pub ctor_def_id: Option<DefId>,
1967 /// Variant or struct name.
1968 #[stable_hasher(project(name))]
1970 /// Discriminant of this variant.
1971 pub discr: VariantDiscr,
1972 /// Fields of this variant.
1973 pub fields: Vec<FieldDef>,
1974 /// Type of constructor of variant.
1975 pub ctor_kind: CtorKind,
1976 /// Flags of the variant (e.g. is field list non-exhaustive)?
1977 flags: VariantFlags,
1978 /// Variant is obtained as part of recovering from a syntactic error.
1979 /// May be incomplete or bogus.
1980 pub recovered: bool,
1983 impl<'tcx> VariantDef {
1984 /// Creates a new `VariantDef`.
1986 /// `variant_did` is the `DefId` that identifies the enum variant (if this `VariantDef`
1987 /// represents an enum variant).
1989 /// `ctor_did` is the `DefId` that identifies the constructor of unit or
1990 /// tuple-variants/structs. If this is a `struct`-variant then this should be `None`.
1992 /// `parent_did` is the `DefId` of the `AdtDef` representing the enum or struct that
1993 /// owns this variant. It is used for checking if a struct has `#[non_exhaustive]` w/out having
1994 /// to go through the redirect of checking the ctor's attributes - but compiling a small crate
1995 /// requires loading the `AdtDef`s for all the structs in the universe (e.g., coherence for any
1996 /// built-in trait), and we do not want to load attributes twice.
1998 /// If someone speeds up attribute loading to not be a performance concern, they can
1999 /// remove this hack and use the constructor `DefId` everywhere.
2003 variant_did: Option<DefId>,
2004 ctor_def_id: Option<DefId>,
2005 discr: VariantDiscr,
2006 fields: Vec<FieldDef>,
2007 ctor_kind: CtorKind,
2013 "VariantDef::new(ident = {:?}, variant_did = {:?}, ctor_def_id = {:?}, discr = {:?},
2014 fields = {:?}, ctor_kind = {:?}, adt_kind = {:?}, parent_did = {:?})",
2015 ident, variant_did, ctor_def_id, discr, fields, ctor_kind, adt_kind, parent_did,
2018 let mut flags = VariantFlags::NO_VARIANT_FLAGS;
2019 if adt_kind == AdtKind::Struct && tcx.has_attr(parent_did, sym::non_exhaustive) {
2020 debug!("found non-exhaustive field list for {:?}", parent_did);
2021 flags = flags | VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE;
2022 } else if let Some(variant_did) = variant_did {
2023 if tcx.has_attr(variant_did, sym::non_exhaustive) {
2024 debug!("found non-exhaustive field list for {:?}", variant_did);
2025 flags = flags | VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE;
2030 def_id: variant_did.unwrap_or(parent_did),
2041 /// Is this field list non-exhaustive?
2043 pub fn is_field_list_non_exhaustive(&self) -> bool {
2044 self.flags.intersects(VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE)
2048 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2049 pub enum VariantDiscr {
2050 /// Explicit value for this variant, i.e., `X = 123`.
2051 /// The `DefId` corresponds to the embedded constant.
2054 /// The previous variant's discriminant plus one.
2055 /// For efficiency reasons, the distance from the
2056 /// last `Explicit` discriminant is being stored,
2057 /// or `0` for the first variant, if it has none.
2061 #[derive(Debug, HashStable)]
2062 pub struct FieldDef {
2064 #[stable_hasher(project(name))]
2066 pub vis: Visibility,
2069 /// The definition of a user-defined type, e.g., a `struct`, `enum`, or `union`.
2071 /// These are all interned (by `intern_adt_def`) into the `adt_defs` table.
2073 /// The initialism *ADT* stands for an [*algebraic data type (ADT)*][adt].
2074 /// This is slightly wrong because `union`s are not ADTs.
2075 /// Moreover, Rust only allows recursive data types through indirection.
2077 /// [adt]: https://en.wikipedia.org/wiki/Algebraic_data_type
2079 /// The `DefId` of the struct, enum or union item.
2081 /// Variants of the ADT. If this is a struct or union, then there will be a single variant.
2082 pub variants: IndexVec<self::layout::VariantIdx, VariantDef>,
2083 /// Flags of the ADT (e.g., is this a struct? is this non-exhaustive?).
2085 /// Repr options provided by the user.
2086 pub repr: ReprOptions,
2089 impl PartialOrd for AdtDef {
2090 fn partial_cmp(&self, other: &AdtDef) -> Option<Ordering> {
2091 Some(self.cmp(&other))
2095 /// There should be only one AdtDef for each `did`, therefore
2096 /// it is fine to implement `Ord` only based on `did`.
2097 impl Ord for AdtDef {
2098 fn cmp(&self, other: &AdtDef) -> Ordering {
2099 self.did.cmp(&other.did)
2103 impl PartialEq for AdtDef {
2104 // `AdtDef`s are always interned, and this is part of `TyS` equality.
2106 fn eq(&self, other: &Self) -> bool {
2107 ptr::eq(self, other)
2111 impl Eq for AdtDef {}
2113 impl Hash for AdtDef {
2115 fn hash<H: Hasher>(&self, s: &mut H) {
2116 (self as *const AdtDef).hash(s)
2120 impl<'tcx> rustc_serialize::UseSpecializedEncodable for &'tcx AdtDef {
2121 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
2126 impl<'tcx> rustc_serialize::UseSpecializedDecodable for &'tcx AdtDef {}
2128 impl<'a> HashStable<StableHashingContext<'a>> for AdtDef {
2129 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
2131 static CACHE: RefCell<FxHashMap<usize, Fingerprint>> = Default::default();
2134 let hash: Fingerprint = CACHE.with(|cache| {
2135 let addr = self as *const AdtDef as usize;
2136 *cache.borrow_mut().entry(addr).or_insert_with(|| {
2137 let ty::AdtDef { did, ref variants, ref flags, ref repr } = *self;
2139 let mut hasher = StableHasher::new();
2140 did.hash_stable(hcx, &mut hasher);
2141 variants.hash_stable(hcx, &mut hasher);
2142 flags.hash_stable(hcx, &mut hasher);
2143 repr.hash_stable(hcx, &mut hasher);
2149 hash.hash_stable(hcx, hasher);
2153 #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
2160 impl Into<DataTypeKind> for AdtKind {
2161 fn into(self) -> DataTypeKind {
2163 AdtKind::Struct => DataTypeKind::Struct,
2164 AdtKind::Union => DataTypeKind::Union,
2165 AdtKind::Enum => DataTypeKind::Enum,
2171 #[derive(RustcEncodable, RustcDecodable, Default, HashStable)]
2172 pub struct ReprFlags: u8 {
2173 const IS_C = 1 << 0;
2174 const IS_SIMD = 1 << 1;
2175 const IS_TRANSPARENT = 1 << 2;
2176 // Internal only for now. If true, don't reorder fields.
2177 const IS_LINEAR = 1 << 3;
2178 // If true, don't expose any niche to type's context.
2179 const HIDE_NICHE = 1 << 4;
2180 // Any of these flags being set prevent field reordering optimisation.
2181 const IS_UNOPTIMISABLE = ReprFlags::IS_C.bits |
2182 ReprFlags::IS_SIMD.bits |
2183 ReprFlags::IS_LINEAR.bits;
2187 /// Represents the repr options provided by the user,
2188 #[derive(Copy, Clone, Debug, Eq, PartialEq, RustcEncodable, RustcDecodable, Default, HashStable)]
2189 pub struct ReprOptions {
2190 pub int: Option<attr::IntType>,
2191 pub align: Option<Align>,
2192 pub pack: Option<Align>,
2193 pub flags: ReprFlags,
2197 pub fn new(tcx: TyCtxt<'_>, did: DefId) -> ReprOptions {
2198 let mut flags = ReprFlags::empty();
2199 let mut size = None;
2200 let mut max_align: Option<Align> = None;
2201 let mut min_pack: Option<Align> = None;
2202 for attr in tcx.get_attrs(did).iter() {
2203 for r in attr::find_repr_attrs(&tcx.sess.parse_sess, attr) {
2204 flags.insert(match r {
2205 attr::ReprC => ReprFlags::IS_C,
2206 attr::ReprPacked(pack) => {
2207 let pack = Align::from_bytes(pack as u64).unwrap();
2208 min_pack = Some(if let Some(min_pack) = min_pack {
2215 attr::ReprTransparent => ReprFlags::IS_TRANSPARENT,
2216 attr::ReprNoNiche => ReprFlags::HIDE_NICHE,
2217 attr::ReprSimd => ReprFlags::IS_SIMD,
2218 attr::ReprInt(i) => {
2222 attr::ReprAlign(align) => {
2223 max_align = max_align.max(Some(Align::from_bytes(align as u64).unwrap()));
2230 // This is here instead of layout because the choice must make it into metadata.
2231 if !tcx.consider_optimizing(|| format!("Reorder fields of {:?}", tcx.def_path_str(did))) {
2232 flags.insert(ReprFlags::IS_LINEAR);
2234 ReprOptions { int: size, align: max_align, pack: min_pack, flags }
2238 pub fn simd(&self) -> bool {
2239 self.flags.contains(ReprFlags::IS_SIMD)
2242 pub fn c(&self) -> bool {
2243 self.flags.contains(ReprFlags::IS_C)
2246 pub fn packed(&self) -> bool {
2250 pub fn transparent(&self) -> bool {
2251 self.flags.contains(ReprFlags::IS_TRANSPARENT)
2254 pub fn linear(&self) -> bool {
2255 self.flags.contains(ReprFlags::IS_LINEAR)
2258 pub fn hide_niche(&self) -> bool {
2259 self.flags.contains(ReprFlags::HIDE_NICHE)
2262 pub fn discr_type(&self) -> attr::IntType {
2263 self.int.unwrap_or(attr::SignedInt(ast::IntTy::Isize))
2266 /// Returns `true` if this `#[repr()]` should inhabit "smart enum
2267 /// layout" optimizations, such as representing `Foo<&T>` as a
2269 pub fn inhibit_enum_layout_opt(&self) -> bool {
2270 self.c() || self.int.is_some()
2273 /// Returns `true` if this `#[repr()]` should inhibit struct field reordering
2274 /// optimizations, such as with `repr(C)`, `repr(packed(1))`, or `repr(<int>)`.
2275 pub fn inhibit_struct_field_reordering_opt(&self) -> bool {
2276 if let Some(pack) = self.pack {
2277 if pack.bytes() == 1 {
2281 self.flags.intersects(ReprFlags::IS_UNOPTIMISABLE) || self.int.is_some()
2284 /// Returns `true` if this `#[repr()]` should inhibit union ABI optimisations.
2285 pub fn inhibit_union_abi_opt(&self) -> bool {
2291 /// Creates a new `AdtDef`.
2296 variants: IndexVec<VariantIdx, VariantDef>,
2299 debug!("AdtDef::new({:?}, {:?}, {:?}, {:?})", did, kind, variants, repr);
2300 let mut flags = AdtFlags::NO_ADT_FLAGS;
2302 if kind == AdtKind::Enum && tcx.has_attr(did, sym::non_exhaustive) {
2303 debug!("found non-exhaustive variant list for {:?}", did);
2304 flags = flags | AdtFlags::IS_VARIANT_LIST_NON_EXHAUSTIVE;
2307 flags |= match kind {
2308 AdtKind::Enum => AdtFlags::IS_ENUM,
2309 AdtKind::Union => AdtFlags::IS_UNION,
2310 AdtKind::Struct => AdtFlags::IS_STRUCT,
2313 if kind == AdtKind::Struct && variants[VariantIdx::new(0)].ctor_def_id.is_some() {
2314 flags |= AdtFlags::HAS_CTOR;
2317 let attrs = tcx.get_attrs(did);
2318 if attr::contains_name(&attrs, sym::fundamental) {
2319 flags |= AdtFlags::IS_FUNDAMENTAL;
2321 if Some(did) == tcx.lang_items().phantom_data() {
2322 flags |= AdtFlags::IS_PHANTOM_DATA;
2324 if Some(did) == tcx.lang_items().owned_box() {
2325 flags |= AdtFlags::IS_BOX;
2327 if Some(did) == tcx.lang_items().manually_drop() {
2328 flags |= AdtFlags::IS_MANUALLY_DROP;
2330 if Some(did) == tcx.lang_items().arc() {
2331 flags |= AdtFlags::IS_ARC;
2333 if Some(did) == tcx.lang_items().rc() {
2334 flags |= AdtFlags::IS_RC;
2337 AdtDef { did, variants, flags, repr }
2340 /// Returns `true` if this is a struct.
2342 pub fn is_struct(&self) -> bool {
2343 self.flags.contains(AdtFlags::IS_STRUCT)
2346 /// Returns `true` if this is a union.
2348 pub fn is_union(&self) -> bool {
2349 self.flags.contains(AdtFlags::IS_UNION)
2352 /// Returns `true` if this is a enum.
2354 pub fn is_enum(&self) -> bool {
2355 self.flags.contains(AdtFlags::IS_ENUM)
2358 /// Returns `true` if the variant list of this ADT is `#[non_exhaustive]`.
2360 pub fn is_variant_list_non_exhaustive(&self) -> bool {
2361 self.flags.contains(AdtFlags::IS_VARIANT_LIST_NON_EXHAUSTIVE)
2364 /// Returns the kind of the ADT.
2366 pub fn adt_kind(&self) -> AdtKind {
2369 } else if self.is_union() {
2376 /// Returns a description of this abstract data type.
2377 pub fn descr(&self) -> &'static str {
2378 match self.adt_kind() {
2379 AdtKind::Struct => "struct",
2380 AdtKind::Union => "union",
2381 AdtKind::Enum => "enum",
2385 /// Returns a description of a variant of this abstract data type.
2387 pub fn variant_descr(&self) -> &'static str {
2388 match self.adt_kind() {
2389 AdtKind::Struct => "struct",
2390 AdtKind::Union => "union",
2391 AdtKind::Enum => "variant",
2395 /// If this function returns `true`, it implies that `is_struct` must return `true`.
2397 pub fn has_ctor(&self) -> bool {
2398 self.flags.contains(AdtFlags::HAS_CTOR)
2401 /// Returns `true` if this type is `#[fundamental]` for the purposes
2402 /// of coherence checking.
2404 pub fn is_fundamental(&self) -> bool {
2405 self.flags.contains(AdtFlags::IS_FUNDAMENTAL)
2408 /// Returns `true` if this is `PhantomData<T>`.
2410 pub fn is_phantom_data(&self) -> bool {
2411 self.flags.contains(AdtFlags::IS_PHANTOM_DATA)
2414 /// Returns `true` if this is `Arc<T>`.
2415 pub fn is_arc(&self) -> bool {
2416 self.flags.contains(AdtFlags::IS_ARC)
2419 /// Returns `true` if this is `Rc<T>`.
2420 pub fn is_rc(&self) -> bool {
2421 self.flags.contains(AdtFlags::IS_RC)
2424 /// Returns `true` if this is Box<T>.
2426 pub fn is_box(&self) -> bool {
2427 self.flags.contains(AdtFlags::IS_BOX)
2430 /// Returns `true` if this is `ManuallyDrop<T>`.
2432 pub fn is_manually_drop(&self) -> bool {
2433 self.flags.contains(AdtFlags::IS_MANUALLY_DROP)
2436 /// Returns `true` if this type has a destructor.
2437 pub fn has_dtor(&self, tcx: TyCtxt<'tcx>) -> bool {
2438 self.destructor(tcx).is_some()
2441 /// Asserts this is a struct or union and returns its unique variant.
2442 pub fn non_enum_variant(&self) -> &VariantDef {
2443 assert!(self.is_struct() || self.is_union());
2444 &self.variants[VariantIdx::new(0)]
2448 pub fn predicates(&self, tcx: TyCtxt<'tcx>) -> GenericPredicates<'tcx> {
2449 tcx.predicates_of(self.did)
2452 /// Returns an iterator over all fields contained
2455 pub fn all_fields(&self) -> impl Iterator<Item = &FieldDef> + Clone {
2456 self.variants.iter().flat_map(|v| v.fields.iter())
2459 pub fn is_payloadfree(&self) -> bool {
2460 !self.variants.is_empty() && self.variants.iter().all(|v| v.fields.is_empty())
2463 /// Return a `VariantDef` given a variant id.
2464 pub fn variant_with_id(&self, vid: DefId) -> &VariantDef {
2465 self.variants.iter().find(|v| v.def_id == vid).expect("variant_with_id: unknown variant")
2468 /// Return a `VariantDef` given a constructor id.
2469 pub fn variant_with_ctor_id(&self, cid: DefId) -> &VariantDef {
2472 .find(|v| v.ctor_def_id == Some(cid))
2473 .expect("variant_with_ctor_id: unknown variant")
2476 /// Return the index of `VariantDef` given a variant id.
2477 pub fn variant_index_with_id(&self, vid: DefId) -> VariantIdx {
2480 .find(|(_, v)| v.def_id == vid)
2481 .expect("variant_index_with_id: unknown variant")
2485 /// Return the index of `VariantDef` given a constructor id.
2486 pub fn variant_index_with_ctor_id(&self, cid: DefId) -> VariantIdx {
2489 .find(|(_, v)| v.ctor_def_id == Some(cid))
2490 .expect("variant_index_with_ctor_id: unknown variant")
2494 pub fn variant_of_res(&self, res: Res) -> &VariantDef {
2496 Res::Def(DefKind::Variant, vid) => self.variant_with_id(vid),
2497 Res::Def(DefKind::Ctor(..), cid) => self.variant_with_ctor_id(cid),
2498 Res::Def(DefKind::Struct, _)
2499 | Res::Def(DefKind::Union, _)
2500 | Res::Def(DefKind::TyAlias, _)
2501 | Res::Def(DefKind::AssocTy, _)
2503 | Res::SelfCtor(..) => self.non_enum_variant(),
2504 _ => bug!("unexpected res {:?} in variant_of_res", res),
2509 pub fn eval_explicit_discr(&self, tcx: TyCtxt<'tcx>, expr_did: DefId) -> Option<Discr<'tcx>> {
2510 let param_env = tcx.param_env(expr_did);
2511 let repr_type = self.repr.discr_type();
2512 match tcx.const_eval_poly(expr_did) {
2514 let ty = repr_type.to_ty(tcx);
2515 if let Some(b) = val.try_to_bits_for_ty(tcx, param_env, ty) {
2516 trace!("discriminants: {} ({:?})", b, repr_type);
2517 Some(Discr { val: b, ty })
2519 info!("invalid enum discriminant: {:#?}", val);
2520 crate::mir::interpret::struct_error(
2521 tcx.at(tcx.def_span(expr_did)),
2522 "constant evaluation of enum discriminant resulted in non-integer",
2528 Err(ErrorHandled::Reported) => {
2529 if !expr_did.is_local() {
2531 tcx.def_span(expr_did),
2532 "variant discriminant evaluation succeeded \
2533 in its crate but failed locally"
2538 Err(ErrorHandled::TooGeneric) => {
2539 span_bug!(tcx.def_span(expr_did), "enum discriminant depends on generic arguments",)
2545 pub fn discriminants(
2548 ) -> impl Iterator<Item = (VariantIdx, Discr<'tcx>)> + Captures<'tcx> {
2549 let repr_type = self.repr.discr_type();
2550 let initial = repr_type.initial_discriminant(tcx);
2551 let mut prev_discr = None::<Discr<'tcx>>;
2552 self.variants.iter_enumerated().map(move |(i, v)| {
2553 let mut discr = prev_discr.map_or(initial, |d| d.wrap_incr(tcx));
2554 if let VariantDiscr::Explicit(expr_did) = v.discr {
2555 if let Some(new_discr) = self.eval_explicit_discr(tcx, expr_did) {
2559 prev_discr = Some(discr);
2566 pub fn variant_range(&self) -> Range<VariantIdx> {
2567 VariantIdx::new(0)..VariantIdx::new(self.variants.len())
2570 /// Computes the discriminant value used by a specific variant.
2571 /// Unlike `discriminants`, this is (amortized) constant-time,
2572 /// only doing at most one query for evaluating an explicit
2573 /// discriminant (the last one before the requested variant),
2574 /// assuming there are no constant-evaluation errors there.
2576 pub fn discriminant_for_variant(
2579 variant_index: VariantIdx,
2581 let (val, offset) = self.discriminant_def_for_variant(variant_index);
2582 let explicit_value = val
2583 .and_then(|expr_did| self.eval_explicit_discr(tcx, expr_did))
2584 .unwrap_or_else(|| self.repr.discr_type().initial_discriminant(tcx));
2585 explicit_value.checked_add(tcx, offset as u128).0
2588 /// Yields a `DefId` for the discriminant and an offset to add to it
2589 /// Alternatively, if there is no explicit discriminant, returns the
2590 /// inferred discriminant directly.
2591 pub fn discriminant_def_for_variant(&self, variant_index: VariantIdx) -> (Option<DefId>, u32) {
2592 let mut explicit_index = variant_index.as_u32();
2595 match self.variants[VariantIdx::from_u32(explicit_index)].discr {
2596 ty::VariantDiscr::Relative(0) => {
2600 ty::VariantDiscr::Relative(distance) => {
2601 explicit_index -= distance;
2603 ty::VariantDiscr::Explicit(did) => {
2604 expr_did = Some(did);
2609 (expr_did, variant_index.as_u32() - explicit_index)
2612 pub fn destructor(&self, tcx: TyCtxt<'tcx>) -> Option<Destructor> {
2613 tcx.adt_destructor(self.did)
2616 /// Returns a list of types such that `Self: Sized` if and only
2617 /// if that type is `Sized`, or `TyErr` if this type is recursive.
2619 /// Oddly enough, checking that the sized-constraint is `Sized` is
2620 /// actually more expressive than checking all members:
2621 /// the `Sized` trait is inductive, so an associated type that references
2622 /// `Self` would prevent its containing ADT from being `Sized`.
2624 /// Due to normalization being eager, this applies even if
2625 /// the associated type is behind a pointer (e.g., issue #31299).
2626 pub fn sized_constraint(&self, tcx: TyCtxt<'tcx>) -> &'tcx [Ty<'tcx>] {
2627 tcx.adt_sized_constraint(self.did).0
2631 impl<'tcx> FieldDef {
2632 /// Returns the type of this field. The `subst` is typically obtained
2633 /// via the second field of `TyKind::AdtDef`.
2634 pub fn ty(&self, tcx: TyCtxt<'tcx>, subst: SubstsRef<'tcx>) -> Ty<'tcx> {
2635 tcx.type_of(self.did).subst(tcx, subst)
2639 /// Represents the various closure traits in the language. This
2640 /// will determine the type of the environment (`self`, in the
2641 /// desugaring) argument that the closure expects.
2643 /// You can get the environment type of a closure using
2644 /// `tcx.closure_env_ty()`.
2658 pub enum ClosureKind {
2659 // Warning: Ordering is significant here! The ordering is chosen
2660 // because the trait Fn is a subtrait of FnMut and so in turn, and
2661 // hence we order it so that Fn < FnMut < FnOnce.
2667 impl<'tcx> ClosureKind {
2668 // This is the initial value used when doing upvar inference.
2669 pub const LATTICE_BOTTOM: ClosureKind = ClosureKind::Fn;
2671 pub fn trait_did(&self, tcx: TyCtxt<'tcx>) -> DefId {
2673 ClosureKind::Fn => tcx.require_lang_item(FnTraitLangItem, None),
2674 ClosureKind::FnMut => tcx.require_lang_item(FnMutTraitLangItem, None),
2675 ClosureKind::FnOnce => tcx.require_lang_item(FnOnceTraitLangItem, None),
2679 /// Returns `true` if this a type that impls this closure kind
2680 /// must also implement `other`.
2681 pub fn extends(self, other: ty::ClosureKind) -> bool {
2682 match (self, other) {
2683 (ClosureKind::Fn, ClosureKind::Fn) => true,
2684 (ClosureKind::Fn, ClosureKind::FnMut) => true,
2685 (ClosureKind::Fn, ClosureKind::FnOnce) => true,
2686 (ClosureKind::FnMut, ClosureKind::FnMut) => true,
2687 (ClosureKind::FnMut, ClosureKind::FnOnce) => true,
2688 (ClosureKind::FnOnce, ClosureKind::FnOnce) => true,
2693 /// Returns the representative scalar type for this closure kind.
2694 /// See `TyS::to_opt_closure_kind` for more details.
2695 pub fn to_ty(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
2697 ty::ClosureKind::Fn => tcx.types.i8,
2698 ty::ClosureKind::FnMut => tcx.types.i16,
2699 ty::ClosureKind::FnOnce => tcx.types.i32,
2704 impl<'tcx> TyS<'tcx> {
2705 /// Iterator that walks `self` and any types reachable from
2706 /// `self`, in depth-first order. Note that just walks the types
2707 /// that appear in `self`, it does not descend into the fields of
2708 /// structs or variants. For example:
2711 /// isize => { isize }
2712 /// Foo<Bar<isize>> => { Foo<Bar<isize>>, Bar<isize>, isize }
2713 /// [isize] => { [isize], isize }
2715 pub fn walk(&'tcx self) -> TypeWalker<'tcx> {
2716 TypeWalker::new(self)
2719 /// Iterator that walks the immediate children of `self`. Hence
2720 /// `Foo<Bar<i32>, u32>` yields the sequence `[Bar<i32>, u32]`
2721 /// (but not `i32`, like `walk`).
2722 pub fn walk_shallow(&'tcx self) -> smallvec::IntoIter<walk::TypeWalkerArray<'tcx>> {
2723 walk::walk_shallow(self)
2726 /// Walks `ty` and any types appearing within `ty`, invoking the
2727 /// callback `f` on each type. If the callback returns `false`, then the
2728 /// children of the current type are ignored.
2730 /// Note: prefer `ty.walk()` where possible.
2731 pub fn maybe_walk<F>(&'tcx self, mut f: F)
2733 F: FnMut(Ty<'tcx>) -> bool,
2735 let mut walker = self.walk();
2736 while let Some(ty) = walker.next() {
2738 walker.skip_current_subtree();
2745 pub fn from_mutbl(m: hir::Mutability) -> BorrowKind {
2747 hir::Mutability::Mut => MutBorrow,
2748 hir::Mutability::Not => ImmBorrow,
2752 /// Returns a mutability `m` such that an `&m T` pointer could be used to obtain this borrow
2753 /// kind. Because borrow kinds are richer than mutabilities, we sometimes have to pick a
2754 /// mutability that is stronger than necessary so that it at least *would permit* the borrow in
2756 pub fn to_mutbl_lossy(self) -> hir::Mutability {
2758 MutBorrow => hir::Mutability::Mut,
2759 ImmBorrow => hir::Mutability::Not,
2761 // We have no type corresponding to a unique imm borrow, so
2762 // use `&mut`. It gives all the capabilities of an `&uniq`
2763 // and hence is a safe "over approximation".
2764 UniqueImmBorrow => hir::Mutability::Mut,
2768 pub fn to_user_str(&self) -> &'static str {
2770 MutBorrow => "mutable",
2771 ImmBorrow => "immutable",
2772 UniqueImmBorrow => "uniquely immutable",
2777 #[derive(Debug, Clone)]
2778 pub enum Attributes<'tcx> {
2779 Owned(Lrc<[ast::Attribute]>),
2780 Borrowed(&'tcx [ast::Attribute]),
2783 impl<'tcx> ::std::ops::Deref for Attributes<'tcx> {
2784 type Target = [ast::Attribute];
2786 fn deref(&self) -> &[ast::Attribute] {
2788 &Attributes::Owned(ref data) => &data,
2789 &Attributes::Borrowed(data) => data,
2794 #[derive(Debug, PartialEq, Eq)]
2795 pub enum ImplOverlapKind {
2796 /// These impls are always allowed to overlap.
2798 /// Whether or not the impl is permitted due to the trait being a `#[marker]` trait
2801 /// These impls are allowed to overlap, but that raises
2802 /// an issue #33140 future-compatibility warning.
2804 /// Some background: in Rust 1.0, the trait-object types `Send + Sync` (today's
2805 /// `dyn Send + Sync`) and `Sync + Send` (now `dyn Sync + Send`) were different.
2807 /// The widely-used version 0.1.0 of the crate `traitobject` had accidentally relied
2808 /// that difference, making what reduces to the following set of impls:
2812 /// impl Trait for dyn Send + Sync {}
2813 /// impl Trait for dyn Sync + Send {}
2816 /// Obviously, once we made these types be identical, that code causes a coherence
2817 /// error and a fairly big headache for us. However, luckily for us, the trait
2818 /// `Trait` used in this case is basically a marker trait, and therefore having
2819 /// overlapping impls for it is sound.
2821 /// To handle this, we basically regard the trait as a marker trait, with an additional
2822 /// future-compatibility warning. To avoid accidentally "stabilizing" this feature,
2823 /// it has the following restrictions:
2825 /// 1. The trait must indeed be a marker-like trait (i.e., no items), and must be
2827 /// 2. The trait-ref of both impls must be equal.
2828 /// 3. The trait-ref of both impls must be a trait object type consisting only of
2830 /// 4. Neither of the impls can have any where-clauses.
2832 /// Once `traitobject` 0.1.0 is no longer an active concern, this hack can be removed.
2836 impl<'tcx> TyCtxt<'tcx> {
2837 pub fn body_tables(self, body: hir::BodyId) -> &'tcx TypeckTables<'tcx> {
2838 self.typeck_tables_of(self.hir().body_owner_def_id(body))
2841 /// Returns an iterator of the `DefId`s for all body-owners in this
2842 /// crate. If you would prefer to iterate over the bodies
2843 /// themselves, you can do `self.hir().krate().body_ids.iter()`.
2844 pub fn body_owners(self) -> impl Iterator<Item = DefId> + Captures<'tcx> + 'tcx {
2849 .map(move |&body_id| self.hir().body_owner_def_id(body_id))
2852 pub fn par_body_owners<F: Fn(DefId) + sync::Sync + sync::Send>(self, f: F) {
2853 par_iter(&self.hir().krate().body_ids)
2854 .for_each(|&body_id| f(self.hir().body_owner_def_id(body_id)));
2857 pub fn provided_trait_methods(self, id: DefId) -> impl 'tcx + Iterator<Item = &'tcx AssocItem> {
2858 self.associated_items(id)
2859 .in_definition_order()
2860 .filter(|item| item.kind == AssocKind::Method && item.defaultness.has_value())
2863 pub fn trait_relevant_for_never(self, did: DefId) -> bool {
2864 self.associated_items(did).in_definition_order().any(|item| item.relevant_for_never())
2867 pub fn opt_item_name(self, def_id: DefId) -> Option<Ident> {
2868 self.hir().as_local_hir_id(def_id).and_then(|hir_id| self.hir().get(hir_id).ident())
2871 pub fn opt_associated_item(self, def_id: DefId) -> Option<AssocItem> {
2872 let is_associated_item = if let Some(hir_id) = self.hir().as_local_hir_id(def_id) {
2873 match self.hir().get(hir_id) {
2874 Node::TraitItem(_) | Node::ImplItem(_) => true,
2878 match self.def_kind(def_id).expect("no def for `DefId`") {
2879 DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy => true,
2884 is_associated_item.then(|| self.associated_item(def_id))
2887 pub fn field_index(self, hir_id: hir::HirId, tables: &TypeckTables<'_>) -> usize {
2888 tables.field_indices().get(hir_id).cloned().expect("no index for a field")
2891 pub fn find_field_index(self, ident: Ident, variant: &VariantDef) -> Option<usize> {
2892 variant.fields.iter().position(|field| self.hygienic_eq(ident, field.ident, variant.def_id))
2895 /// Returns `true` if the impls are the same polarity and the trait either
2896 /// has no items or is annotated #[marker] and prevents item overrides.
2897 pub fn impls_are_allowed_to_overlap(
2901 ) -> Option<ImplOverlapKind> {
2902 // If either trait impl references an error, they're allowed to overlap,
2903 // as one of them essentially doesn't exist.
2904 if self.impl_trait_ref(def_id1).map_or(false, |tr| tr.references_error())
2905 || self.impl_trait_ref(def_id2).map_or(false, |tr| tr.references_error())
2907 return Some(ImplOverlapKind::Permitted { marker: false });
2910 match (self.impl_polarity(def_id1), self.impl_polarity(def_id2)) {
2911 (ImplPolarity::Reservation, _) | (_, ImplPolarity::Reservation) => {
2912 // `#[rustc_reservation_impl]` impls don't overlap with anything
2914 "impls_are_allowed_to_overlap({:?}, {:?}) = Some(Permitted) (reservations)",
2917 return Some(ImplOverlapKind::Permitted { marker: false });
2919 (ImplPolarity::Positive, ImplPolarity::Negative)
2920 | (ImplPolarity::Negative, ImplPolarity::Positive) => {
2921 // `impl AutoTrait for Type` + `impl !AutoTrait for Type`
2923 "impls_are_allowed_to_overlap({:?}, {:?}) - None (differing polarities)",
2928 (ImplPolarity::Positive, ImplPolarity::Positive)
2929 | (ImplPolarity::Negative, ImplPolarity::Negative) => {}
2932 let is_marker_overlap = {
2933 let is_marker_impl = |def_id: DefId| -> bool {
2934 let trait_ref = self.impl_trait_ref(def_id);
2935 trait_ref.map_or(false, |tr| self.trait_def(tr.def_id).is_marker)
2937 is_marker_impl(def_id1) && is_marker_impl(def_id2)
2940 if is_marker_overlap {
2942 "impls_are_allowed_to_overlap({:?}, {:?}) = Some(Permitted) (marker overlap)",
2945 Some(ImplOverlapKind::Permitted { marker: true })
2947 if let Some(self_ty1) = self.issue33140_self_ty(def_id1) {
2948 if let Some(self_ty2) = self.issue33140_self_ty(def_id2) {
2949 if self_ty1 == self_ty2 {
2951 "impls_are_allowed_to_overlap({:?}, {:?}) - issue #33140 HACK",
2954 return Some(ImplOverlapKind::Issue33140);
2957 "impls_are_allowed_to_overlap({:?}, {:?}) - found {:?} != {:?}",
2958 def_id1, def_id2, self_ty1, self_ty2
2964 debug!("impls_are_allowed_to_overlap({:?}, {:?}) = None", def_id1, def_id2);
2969 /// Returns `ty::VariantDef` if `res` refers to a struct,
2970 /// or variant or their constructors, panics otherwise.
2971 pub fn expect_variant_res(self, res: Res) -> &'tcx VariantDef {
2973 Res::Def(DefKind::Variant, did) => {
2974 let enum_did = self.parent(did).unwrap();
2975 self.adt_def(enum_did).variant_with_id(did)
2977 Res::Def(DefKind::Struct, did) | Res::Def(DefKind::Union, did) => {
2978 self.adt_def(did).non_enum_variant()
2980 Res::Def(DefKind::Ctor(CtorOf::Variant, ..), variant_ctor_did) => {
2981 let variant_did = self.parent(variant_ctor_did).unwrap();
2982 let enum_did = self.parent(variant_did).unwrap();
2983 self.adt_def(enum_did).variant_with_ctor_id(variant_ctor_did)
2985 Res::Def(DefKind::Ctor(CtorOf::Struct, ..), ctor_did) => {
2986 let struct_did = self.parent(ctor_did).expect("struct ctor has no parent");
2987 self.adt_def(struct_did).non_enum_variant()
2989 _ => bug!("expect_variant_res used with unexpected res {:?}", res),
2993 pub fn item_name(self, id: DefId) -> Symbol {
2994 if id.index == CRATE_DEF_INDEX {
2995 self.original_crate_name(id.krate)
2997 let def_key = self.def_key(id);
2998 match def_key.disambiguated_data.data {
2999 // The name of a constructor is that of its parent.
3000 hir_map::DefPathData::Ctor => {
3001 self.item_name(DefId { krate: id.krate, index: def_key.parent.unwrap() })
3003 _ => def_key.disambiguated_data.data.get_opt_name().unwrap_or_else(|| {
3004 bug!("item_name: no name for {:?}", self.def_path(id));
3010 /// Returns the possibly-auto-generated MIR of a `(DefId, Subst)` pair.
3011 pub fn instance_mir(self, instance: ty::InstanceDef<'tcx>) -> ReadOnlyBodyAndCache<'tcx, 'tcx> {
3013 ty::InstanceDef::Item(did) => self.optimized_mir(did).unwrap_read_only(),
3014 ty::InstanceDef::VtableShim(..)
3015 | ty::InstanceDef::ReifyShim(..)
3016 | ty::InstanceDef::Intrinsic(..)
3017 | ty::InstanceDef::FnPtrShim(..)
3018 | ty::InstanceDef::Virtual(..)
3019 | ty::InstanceDef::ClosureOnceShim { .. }
3020 | ty::InstanceDef::DropGlue(..)
3021 | ty::InstanceDef::CloneShim(..) => self.mir_shims(instance).unwrap_read_only(),
3025 /// Gets the attributes of a definition.
3026 pub fn get_attrs(self, did: DefId) -> Attributes<'tcx> {
3027 if let Some(id) = self.hir().as_local_hir_id(did) {
3028 Attributes::Borrowed(self.hir().attrs(id))
3030 Attributes::Owned(self.item_attrs(did))
3034 /// Determines whether an item is annotated with an attribute.
3035 pub fn has_attr(self, did: DefId, attr: Symbol) -> bool {
3036 attr::contains_name(&self.get_attrs(did), attr)
3039 /// Returns `true` if this is an `auto trait`.
3040 pub fn trait_is_auto(self, trait_def_id: DefId) -> bool {
3041 self.trait_def(trait_def_id).has_auto_impl
3044 pub fn generator_layout(self, def_id: DefId) -> &'tcx GeneratorLayout<'tcx> {
3045 self.optimized_mir(def_id).generator_layout.as_ref().unwrap()
3048 /// Given the `DefId` of an impl, returns the `DefId` of the trait it implements.
3049 /// If it implements no trait, returns `None`.
3050 pub fn trait_id_of_impl(self, def_id: DefId) -> Option<DefId> {
3051 self.impl_trait_ref(def_id).map(|tr| tr.def_id)
3054 /// If the given defid describes a method belonging to an impl, returns the
3055 /// `DefId` of the impl that the method belongs to; otherwise, returns `None`.
3056 pub fn impl_of_method(self, def_id: DefId) -> Option<DefId> {
3057 let item = if def_id.krate != LOCAL_CRATE {
3058 if let Some(DefKind::AssocFn) = self.def_kind(def_id) {
3059 Some(self.associated_item(def_id))
3064 self.opt_associated_item(def_id)
3067 item.and_then(|trait_item| match trait_item.container {
3068 TraitContainer(_) => None,
3069 ImplContainer(def_id) => Some(def_id),
3073 /// Looks up the span of `impl_did` if the impl is local; otherwise returns `Err`
3074 /// with the name of the crate containing the impl.
3075 pub fn span_of_impl(self, impl_did: DefId) -> Result<Span, Symbol> {
3076 if impl_did.is_local() {
3077 let hir_id = self.hir().as_local_hir_id(impl_did).unwrap();
3078 Ok(self.hir().span(hir_id))
3080 Err(self.crate_name(impl_did.krate))
3084 /// Hygienically compares a use-site name (`use_name`) for a field or an associated item with
3085 /// its supposed definition name (`def_name`). The method also needs `DefId` of the supposed
3086 /// definition's parent/scope to perform comparison.
3087 pub fn hygienic_eq(self, use_name: Ident, def_name: Ident, def_parent_def_id: DefId) -> bool {
3088 // We could use `Ident::eq` here, but we deliberately don't. The name
3089 // comparison fails frequently, and we want to avoid the expensive
3090 // `normalize_to_macros_2_0()` calls required for the span comparison whenever possible.
3091 use_name.name == def_name.name
3095 .hygienic_eq(def_name.span.ctxt(), self.expansion_that_defined(def_parent_def_id))
3098 fn expansion_that_defined(self, scope: DefId) -> ExpnId {
3099 match scope.as_local() {
3100 Some(scope) => self.hir().definitions().expansion_that_defined(scope),
3101 None => ExpnId::root(),
3105 pub fn adjust_ident(self, mut ident: Ident, scope: DefId) -> Ident {
3106 ident.span.normalize_to_macros_2_0_and_adjust(self.expansion_that_defined(scope));
3110 pub fn adjust_ident_and_get_scope(
3115 ) -> (Ident, DefId) {
3117 match ident.span.normalize_to_macros_2_0_and_adjust(self.expansion_that_defined(scope))
3119 Some(actual_expansion) => {
3120 self.hir().definitions().parent_module_of_macro_def(actual_expansion)
3122 None => self.parent_module(block).to_def_id(),
3127 pub fn is_object_safe(self, key: DefId) -> bool {
3128 self.object_safety_violations(key).is_empty()
3132 #[derive(Clone, HashStable)]
3133 pub struct AdtSizedConstraint<'tcx>(pub &'tcx [Ty<'tcx>]);
3135 /// Yields the parent function's `DefId` if `def_id` is an `impl Trait` definition.
3136 pub fn is_impl_trait_defn(tcx: TyCtxt<'_>, def_id: DefId) -> Option<DefId> {
3137 if let Some(hir_id) = tcx.hir().as_local_hir_id(def_id) {
3138 if let Node::Item(item) = tcx.hir().get(hir_id) {
3139 if let hir::ItemKind::OpaqueTy(ref opaque_ty) = item.kind {
3140 return opaque_ty.impl_trait_fn;
3147 pub fn provide(providers: &mut ty::query::Providers<'_>) {
3148 context::provide(providers);
3149 erase_regions::provide(providers);
3150 layout::provide(providers);
3151 *providers = ty::query::Providers {
3152 trait_impls_of: trait_def::trait_impls_of_provider,
3153 all_local_trait_impls: trait_def::all_local_trait_impls,
3158 /// A map for the local crate mapping each type to a vector of its
3159 /// inherent impls. This is not meant to be used outside of coherence;
3160 /// rather, you should request the vector for a specific type via
3161 /// `tcx.inherent_impls(def_id)` so as to minimize your dependencies
3162 /// (constructing this map requires touching the entire crate).
3163 #[derive(Clone, Debug, Default, HashStable)]
3164 pub struct CrateInherentImpls {
3165 pub inherent_impls: DefIdMap<Vec<DefId>>,
3168 #[derive(Clone, Copy, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
3169 pub struct SymbolName {
3170 // FIXME: we don't rely on interning or equality here - better have
3171 // this be a `&'tcx str`.
3176 pub fn new(name: &str) -> SymbolName {
3177 SymbolName { name: Symbol::intern(name) }
3181 impl PartialOrd for SymbolName {
3182 fn partial_cmp(&self, other: &SymbolName) -> Option<Ordering> {
3183 self.name.as_str().partial_cmp(&other.name.as_str())
3187 /// Ordering must use the chars to ensure reproducible builds.
3188 impl Ord for SymbolName {
3189 fn cmp(&self, other: &SymbolName) -> Ordering {
3190 self.name.as_str().cmp(&other.name.as_str())
3194 impl fmt::Display for SymbolName {
3195 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
3196 fmt::Display::fmt(&self.name, fmt)
3200 impl fmt::Debug for SymbolName {
3201 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
3202 fmt::Display::fmt(&self.name, fmt)