1 // ignore-tidy-filelength
2 pub use self::fold::{TypeFoldable, TypeVisitor};
3 pub use self::AssocItemContainer::*;
4 pub use self::BorrowKind::*;
5 pub use self::IntVarValue::*;
6 pub use self::Variance::*;
8 use crate::hir::exports::ExportMap;
9 use crate::ich::StableHashingContext;
10 use crate::infer::canonical::Canonical;
11 use crate::middle::cstore::CrateStoreDyn;
12 use crate::middle::resolve_lifetime::ObjectLifetimeDefault;
13 use crate::mir::interpret::ErrorHandled;
15 use crate::mir::GeneratorLayout;
16 use crate::traits::{self, Reveal};
18 use crate::ty::subst::{GenericArg, InternalSubsts, Subst, SubstsRef};
19 use crate::ty::util::{Discr, IntTypeExt};
21 use rustc_attr as attr;
22 use rustc_data_structures::captures::Captures;
23 use rustc_data_structures::fingerprint::Fingerprint;
24 use rustc_data_structures::fx::FxHashMap;
25 use rustc_data_structures::fx::FxHashSet;
26 use rustc_data_structures::fx::FxIndexMap;
27 use rustc_data_structures::sorted_map::SortedIndexMultiMap;
28 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
29 use rustc_data_structures::sync::{self, par_iter, ParallelIterator};
30 use rustc_errors::ErrorReported;
32 use rustc_hir::def::{CtorKind, CtorOf, DefKind, Namespace, Res};
33 use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, LocalDefId, CRATE_DEF_INDEX};
34 use rustc_hir::lang_items::{FnMutTraitLangItem, FnOnceTraitLangItem, FnTraitLangItem};
35 use rustc_hir::{Constness, Node};
36 use rustc_index::vec::{Idx, IndexVec};
37 use rustc_macros::HashStable;
38 use rustc_serialize::{self, Encodable, Encoder};
39 use rustc_session::DataTypeKind;
40 use rustc_span::hygiene::ExpnId;
41 use rustc_span::symbol::{kw, sym, Ident, Symbol};
43 use rustc_target::abi::{Align, VariantIdx};
45 use std::cell::RefCell;
46 use std::cmp::Ordering;
48 use std::hash::{Hash, Hasher};
49 use std::marker::PhantomData;
53 pub use self::sty::BoundRegion::*;
54 pub use self::sty::InferTy::*;
55 pub use self::sty::RegionKind;
56 pub use self::sty::RegionKind::*;
57 pub use self::sty::TyKind::*;
58 pub use self::sty::{Binder, BoundTy, BoundTyKind, BoundVar, DebruijnIndex, INNERMOST};
59 pub use self::sty::{BoundRegion, EarlyBoundRegion, FreeRegion, Region};
60 pub use self::sty::{CanonicalPolyFnSig, FnSig, GenSig, PolyFnSig, PolyGenSig};
61 pub use self::sty::{ClosureSubsts, GeneratorSubsts, TypeAndMut, UpvarSubsts};
62 pub use self::sty::{Const, ConstKind, ExistentialProjection, PolyExistentialProjection};
63 pub use self::sty::{ConstVid, FloatVid, IntVid, RegionVid, TyVid};
64 pub use self::sty::{ExistentialPredicate, InferConst, InferTy, ParamConst, ParamTy, ProjectionTy};
65 pub use self::sty::{ExistentialTraitRef, PolyExistentialTraitRef};
66 pub use self::sty::{PolyTraitRef, TraitRef, TyKind};
67 pub use crate::ty::diagnostics::*;
69 pub use self::binding::BindingMode;
70 pub use self::binding::BindingMode::*;
72 pub use self::context::{tls, FreeRegionInfo, TyCtxt};
73 pub use self::context::{
74 CanonicalUserType, CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations, ResolvedOpaqueTy,
75 UserType, UserTypeAnnotationIndex,
77 pub use self::context::{
78 CtxtInterners, GeneratorInteriorTypeCause, GlobalCtxt, Lift, TypeckTables,
81 pub use self::instance::{Instance, InstanceDef};
83 pub use self::list::List;
85 pub use self::trait_def::TraitDef;
87 pub use self::query::queries;
89 pub use self::consts::ConstInt;
102 pub mod inhabitedness;
104 pub mod normalize_erasing_regions;
120 mod structural_impls;
125 pub struct ResolverOutputs {
126 pub definitions: rustc_hir::definitions::Definitions,
127 pub cstore: Box<CrateStoreDyn>,
128 pub extern_crate_map: FxHashMap<LocalDefId, CrateNum>,
129 pub maybe_unused_trait_imports: FxHashSet<LocalDefId>,
130 pub maybe_unused_extern_crates: Vec<(LocalDefId, Span)>,
131 pub export_map: ExportMap<LocalDefId>,
132 pub glob_map: FxHashMap<LocalDefId, FxHashSet<Symbol>>,
133 /// Extern prelude entries. The value is `true` if the entry was introduced
134 /// via `extern crate` item and not `--extern` option or compiler built-in.
135 pub extern_prelude: FxHashMap<Symbol, bool>,
138 #[derive(Clone, Copy, PartialEq, Eq, Debug, HashStable)]
139 pub enum AssocItemContainer {
140 TraitContainer(DefId),
141 ImplContainer(DefId),
144 impl AssocItemContainer {
145 /// Asserts that this is the `DefId` of an associated item declared
146 /// in a trait, and returns the trait `DefId`.
147 pub fn assert_trait(&self) -> DefId {
149 TraitContainer(id) => id,
150 _ => bug!("associated item has wrong container type: {:?}", self),
154 pub fn id(&self) -> DefId {
156 TraitContainer(id) => id,
157 ImplContainer(id) => id,
162 /// The "header" of an impl is everything outside the body: a Self type, a trait
163 /// ref (in the case of a trait impl), and a set of predicates (from the
164 /// bounds / where-clauses).
165 #[derive(Clone, Debug, TypeFoldable)]
166 pub struct ImplHeader<'tcx> {
167 pub impl_def_id: DefId,
168 pub self_ty: Ty<'tcx>,
169 pub trait_ref: Option<TraitRef<'tcx>>,
170 pub predicates: Vec<Predicate<'tcx>>,
173 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable)]
174 pub enum ImplPolarity {
175 /// `impl Trait for Type`
177 /// `impl !Trait for Type`
179 /// `#[rustc_reservation_impl] impl Trait for Type`
181 /// This is a "stability hack", not a real Rust feature.
182 /// See #64631 for details.
186 #[derive(Copy, Clone, Debug, PartialEq, HashStable)]
187 pub struct AssocItem {
189 #[stable_hasher(project(name))]
193 pub defaultness: hir::Defaultness,
194 pub container: AssocItemContainer,
196 /// Whether this is a method with an explicit self
197 /// as its first parameter, allowing method calls.
198 pub fn_has_self_parameter: bool,
201 #[derive(Copy, Clone, PartialEq, Debug, HashStable)]
209 pub fn namespace(&self) -> Namespace {
211 ty::AssocKind::Type => Namespace::TypeNS,
212 ty::AssocKind::Const | ty::AssocKind::Fn => Namespace::ValueNS,
216 pub fn as_def_kind(&self) -> DefKind {
218 AssocKind::Const => DefKind::AssocConst,
219 AssocKind::Fn => DefKind::AssocFn,
220 AssocKind::Type => DefKind::AssocTy,
226 pub fn signature(&self, tcx: TyCtxt<'_>) -> String {
228 ty::AssocKind::Fn => {
229 // We skip the binder here because the binder would deanonymize all
230 // late-bound regions, and we don't want method signatures to show up
231 // `as for<'r> fn(&'r MyType)`. Pretty-printing handles late-bound
232 // regions just fine, showing `fn(&MyType)`.
233 tcx.fn_sig(self.def_id).skip_binder().to_string()
235 ty::AssocKind::Type => format!("type {};", self.ident),
236 ty::AssocKind::Const => {
237 format!("const {}: {:?};", self.ident, tcx.type_of(self.def_id))
243 /// A list of `ty::AssocItem`s in definition order that allows for efficient lookup by name.
245 /// When doing lookup by name, we try to postpone hygienic comparison for as long as possible since
246 /// it is relatively expensive. Instead, items are indexed by `Symbol` and hygienic comparison is
247 /// done only on items with the same name.
248 #[derive(Debug, Clone, PartialEq, HashStable)]
249 pub struct AssociatedItems<'tcx> {
250 items: SortedIndexMultiMap<u32, Symbol, &'tcx ty::AssocItem>,
253 impl<'tcx> AssociatedItems<'tcx> {
254 /// Constructs an `AssociatedItems` map from a series of `ty::AssocItem`s in definition order.
255 pub fn new(items_in_def_order: impl IntoIterator<Item = &'tcx ty::AssocItem>) -> Self {
256 let items = items_in_def_order.into_iter().map(|item| (item.ident.name, item)).collect();
257 AssociatedItems { items }
260 /// Returns a slice of associated items in the order they were defined.
262 /// New code should avoid relying on definition order. If you need a particular associated item
263 /// for a known trait, make that trait a lang item instead of indexing this array.
264 pub fn in_definition_order(&self) -> impl '_ + Iterator<Item = &ty::AssocItem> {
265 self.items.iter().map(|(_, v)| *v)
268 /// Returns an iterator over all associated items with the given name, ignoring hygiene.
269 pub fn filter_by_name_unhygienic(
272 ) -> impl '_ + Iterator<Item = &ty::AssocItem> {
273 self.items.get_by_key(&name).copied()
276 /// Returns an iterator over all associated items with the given name.
278 /// Multiple items may have the same name if they are in different `Namespace`s. For example,
279 /// an associated type can have the same name as a method. Use one of the `find_by_name_and_*`
280 /// methods below if you know which item you are looking for.
281 pub fn filter_by_name(
285 parent_def_id: DefId,
286 ) -> impl 'a + Iterator<Item = &'a ty::AssocItem> {
287 self.filter_by_name_unhygienic(ident.name)
288 .filter(move |item| tcx.hygienic_eq(ident, item.ident, parent_def_id))
291 /// Returns the associated item with the given name and `AssocKind`, if one exists.
292 pub fn find_by_name_and_kind(
297 parent_def_id: DefId,
298 ) -> Option<&ty::AssocItem> {
299 self.filter_by_name_unhygienic(ident.name)
300 .filter(|item| item.kind == kind)
301 .find(|item| tcx.hygienic_eq(ident, item.ident, parent_def_id))
304 /// Returns the associated item with the given name in the given `Namespace`, if one exists.
305 pub fn find_by_name_and_namespace(
310 parent_def_id: DefId,
311 ) -> Option<&ty::AssocItem> {
312 self.filter_by_name_unhygienic(ident.name)
313 .filter(|item| item.kind.namespace() == ns)
314 .find(|item| tcx.hygienic_eq(ident, item.ident, parent_def_id))
318 #[derive(Clone, Debug, PartialEq, Eq, Copy, RustcEncodable, RustcDecodable, HashStable)]
319 pub enum Visibility {
320 /// Visible everywhere (including in other crates).
322 /// Visible only in the given crate-local module.
324 /// Not visible anywhere in the local crate. This is the visibility of private external items.
328 pub trait DefIdTree: Copy {
329 fn parent(self, id: DefId) -> Option<DefId>;
331 fn is_descendant_of(self, mut descendant: DefId, ancestor: DefId) -> bool {
332 if descendant.krate != ancestor.krate {
336 while descendant != ancestor {
337 match self.parent(descendant) {
338 Some(parent) => descendant = parent,
339 None => return false,
346 impl<'tcx> DefIdTree for TyCtxt<'tcx> {
347 fn parent(self, id: DefId) -> Option<DefId> {
348 self.def_key(id).parent.map(|index| DefId { index, ..id })
353 pub fn from_hir(visibility: &hir::Visibility<'_>, id: hir::HirId, tcx: TyCtxt<'_>) -> Self {
354 match visibility.node {
355 hir::VisibilityKind::Public => Visibility::Public,
356 hir::VisibilityKind::Crate(_) => Visibility::Restricted(DefId::local(CRATE_DEF_INDEX)),
357 hir::VisibilityKind::Restricted { ref path, .. } => match path.res {
358 // If there is no resolution, `resolve` will have already reported an error, so
359 // assume that the visibility is public to avoid reporting more privacy errors.
360 Res::Err => Visibility::Public,
361 def => Visibility::Restricted(def.def_id()),
363 hir::VisibilityKind::Inherited => {
364 Visibility::Restricted(tcx.parent_module(id).to_def_id())
369 /// Returns `true` if an item with this visibility is accessible from the given block.
370 pub fn is_accessible_from<T: DefIdTree>(self, module: DefId, tree: T) -> bool {
371 let restriction = match self {
372 // Public items are visible everywhere.
373 Visibility::Public => return true,
374 // Private items from other crates are visible nowhere.
375 Visibility::Invisible => return false,
376 // Restricted items are visible in an arbitrary local module.
377 Visibility::Restricted(other) if other.krate != module.krate => return false,
378 Visibility::Restricted(module) => module,
381 tree.is_descendant_of(module, restriction)
384 /// Returns `true` if this visibility is at least as accessible as the given visibility
385 pub fn is_at_least<T: DefIdTree>(self, vis: Visibility, tree: T) -> bool {
386 let vis_restriction = match vis {
387 Visibility::Public => return self == Visibility::Public,
388 Visibility::Invisible => return true,
389 Visibility::Restricted(module) => module,
392 self.is_accessible_from(vis_restriction, tree)
395 // Returns `true` if this item is visible anywhere in the local crate.
396 pub fn is_visible_locally(self) -> bool {
398 Visibility::Public => true,
399 Visibility::Restricted(def_id) => def_id.is_local(),
400 Visibility::Invisible => false,
405 #[derive(Copy, Clone, PartialEq, RustcDecodable, RustcEncodable, HashStable)]
407 Covariant, // T<A> <: T<B> iff A <: B -- e.g., function return type
408 Invariant, // T<A> <: T<B> iff B == A -- e.g., type of mutable cell
409 Contravariant, // T<A> <: T<B> iff B <: A -- e.g., function param type
410 Bivariant, // T<A> <: T<B> -- e.g., unused type parameter
413 /// The crate variances map is computed during typeck and contains the
414 /// variance of every item in the local crate. You should not use it
415 /// directly, because to do so will make your pass dependent on the
416 /// HIR of every item in the local crate. Instead, use
417 /// `tcx.variances_of()` to get the variance for a *particular*
419 #[derive(HashStable)]
420 pub struct CrateVariancesMap<'tcx> {
421 /// For each item with generics, maps to a vector of the variance
422 /// of its generics. If an item has no generics, it will have no
424 pub variances: FxHashMap<DefId, &'tcx [ty::Variance]>,
428 /// `a.xform(b)` combines the variance of a context with the
429 /// variance of a type with the following meaning. If we are in a
430 /// context with variance `a`, and we encounter a type argument in
431 /// a position with variance `b`, then `a.xform(b)` is the new
432 /// variance with which the argument appears.
438 /// Here, the "ambient" variance starts as covariant. `*mut T` is
439 /// invariant with respect to `T`, so the variance in which the
440 /// `Vec<i32>` appears is `Covariant.xform(Invariant)`, which
441 /// yields `Invariant`. Now, the type `Vec<T>` is covariant with
442 /// respect to its type argument `T`, and hence the variance of
443 /// the `i32` here is `Invariant.xform(Covariant)`, which results
444 /// (again) in `Invariant`.
448 /// fn(*const Vec<i32>, *mut Vec<i32)
450 /// The ambient variance is covariant. A `fn` type is
451 /// contravariant with respect to its parameters, so the variance
452 /// within which both pointer types appear is
453 /// `Covariant.xform(Contravariant)`, or `Contravariant`. `*const
454 /// T` is covariant with respect to `T`, so the variance within
455 /// which the first `Vec<i32>` appears is
456 /// `Contravariant.xform(Covariant)` or `Contravariant`. The same
457 /// is true for its `i32` argument. In the `*mut T` case, the
458 /// variance of `Vec<i32>` is `Contravariant.xform(Invariant)`,
459 /// and hence the outermost type is `Invariant` with respect to
460 /// `Vec<i32>` (and its `i32` argument).
462 /// Source: Figure 1 of "Taming the Wildcards:
463 /// Combining Definition- and Use-Site Variance" published in PLDI'11.
464 pub fn xform(self, v: ty::Variance) -> ty::Variance {
466 // Figure 1, column 1.
467 (ty::Covariant, ty::Covariant) => ty::Covariant,
468 (ty::Covariant, ty::Contravariant) => ty::Contravariant,
469 (ty::Covariant, ty::Invariant) => ty::Invariant,
470 (ty::Covariant, ty::Bivariant) => ty::Bivariant,
472 // Figure 1, column 2.
473 (ty::Contravariant, ty::Covariant) => ty::Contravariant,
474 (ty::Contravariant, ty::Contravariant) => ty::Covariant,
475 (ty::Contravariant, ty::Invariant) => ty::Invariant,
476 (ty::Contravariant, ty::Bivariant) => ty::Bivariant,
478 // Figure 1, column 3.
479 (ty::Invariant, _) => ty::Invariant,
481 // Figure 1, column 4.
482 (ty::Bivariant, _) => ty::Bivariant,
487 // Contains information needed to resolve types and (in the future) look up
488 // the types of AST nodes.
489 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
490 pub struct CReaderCacheKey {
496 /// Flags that we track on types. These flags are propagated upwards
497 /// through the type during type construction, so that we can quickly check
498 /// whether the type has various kinds of types in it without recursing
499 /// over the type itself.
500 pub struct TypeFlags: u32 {
501 // Does this have parameters? Used to determine whether substitution is
503 /// Does this have [Param]?
504 const HAS_TY_PARAM = 1 << 0;
505 /// Does this have [ReEarlyBound]?
506 const HAS_RE_PARAM = 1 << 1;
507 /// Does this have [ConstKind::Param]?
508 const HAS_CT_PARAM = 1 << 2;
510 const NEEDS_SUBST = TypeFlags::HAS_TY_PARAM.bits
511 | TypeFlags::HAS_RE_PARAM.bits
512 | TypeFlags::HAS_CT_PARAM.bits;
514 /// Does this have [Infer]?
515 const HAS_TY_INFER = 1 << 3;
516 /// Does this have [ReVar]?
517 const HAS_RE_INFER = 1 << 4;
518 /// Does this have [ConstKind::Infer]?
519 const HAS_CT_INFER = 1 << 5;
521 /// Does this have inference variables? Used to determine whether
522 /// inference is required.
523 const NEEDS_INFER = TypeFlags::HAS_TY_INFER.bits
524 | TypeFlags::HAS_RE_INFER.bits
525 | TypeFlags::HAS_CT_INFER.bits;
527 /// Does this have [Placeholder]?
528 const HAS_TY_PLACEHOLDER = 1 << 6;
529 /// Does this have [RePlaceholder]?
530 const HAS_RE_PLACEHOLDER = 1 << 7;
531 /// Does this have [ConstKind::Placeholder]?
532 const HAS_CT_PLACEHOLDER = 1 << 8;
534 /// `true` if there are "names" of regions and so forth
535 /// that are local to a particular fn/inferctxt
536 const HAS_FREE_LOCAL_REGIONS = 1 << 9;
538 /// `true` if there are "names" of types and regions and so forth
539 /// that are local to a particular fn
540 const HAS_FREE_LOCAL_NAMES = TypeFlags::HAS_TY_PARAM.bits
541 | TypeFlags::HAS_CT_PARAM.bits
542 | TypeFlags::HAS_TY_INFER.bits
543 | TypeFlags::HAS_CT_INFER.bits
544 | TypeFlags::HAS_TY_PLACEHOLDER.bits
545 | TypeFlags::HAS_CT_PLACEHOLDER.bits
546 | TypeFlags::HAS_FREE_LOCAL_REGIONS.bits;
548 /// Does this have [Projection]?
549 const HAS_TY_PROJECTION = 1 << 10;
550 /// Does this have [Opaque]?
551 const HAS_TY_OPAQUE = 1 << 11;
552 /// Does this have [ConstKind::Unevaluated]?
553 const HAS_CT_PROJECTION = 1 << 12;
555 /// Could this type be normalized further?
556 const HAS_PROJECTION = TypeFlags::HAS_TY_PROJECTION.bits
557 | TypeFlags::HAS_TY_OPAQUE.bits
558 | TypeFlags::HAS_CT_PROJECTION.bits;
560 /// Is an error type/const reachable?
561 const HAS_ERROR = 1 << 13;
563 /// Does this have any region that "appears free" in the type?
564 /// Basically anything but [ReLateBound] and [ReErased].
565 const HAS_FREE_REGIONS = 1 << 14;
567 /// Does this have any [ReLateBound] regions? Used to check
568 /// if a global bound is safe to evaluate.
569 const HAS_RE_LATE_BOUND = 1 << 15;
571 /// Does this have any [ReErased] regions?
572 const HAS_RE_ERASED = 1 << 16;
574 /// Does this value have parameters/placeholders/inference variables which could be
575 /// replaced later, in a way that would change the results of `impl` specialization?
576 const STILL_FURTHER_SPECIALIZABLE = 1 << 17;
580 #[allow(rustc::usage_of_ty_tykind)]
581 pub struct TyS<'tcx> {
582 pub kind: TyKind<'tcx>,
583 pub flags: TypeFlags,
585 /// This is a kind of confusing thing: it stores the smallest
588 /// (a) the binder itself captures nothing but
589 /// (b) all the late-bound things within the type are captured
590 /// by some sub-binder.
592 /// So, for a type without any late-bound things, like `u32`, this
593 /// will be *innermost*, because that is the innermost binder that
594 /// captures nothing. But for a type `&'D u32`, where `'D` is a
595 /// late-bound region with De Bruijn index `D`, this would be `D + 1`
596 /// -- the binder itself does not capture `D`, but `D` is captured
597 /// by an inner binder.
599 /// We call this concept an "exclusive" binder `D` because all
600 /// De Bruijn indices within the type are contained within `0..D`
602 outer_exclusive_binder: ty::DebruijnIndex,
605 // `TyS` is used a lot. Make sure it doesn't unintentionally get bigger.
606 #[cfg(target_arch = "x86_64")]
607 static_assert_size!(TyS<'_>, 32);
609 impl<'tcx> Ord for TyS<'tcx> {
610 fn cmp(&self, other: &TyS<'tcx>) -> Ordering {
611 self.kind.cmp(&other.kind)
615 impl<'tcx> PartialOrd for TyS<'tcx> {
616 fn partial_cmp(&self, other: &TyS<'tcx>) -> Option<Ordering> {
617 Some(self.kind.cmp(&other.kind))
621 impl<'tcx> PartialEq for TyS<'tcx> {
623 fn eq(&self, other: &TyS<'tcx>) -> bool {
627 impl<'tcx> Eq for TyS<'tcx> {}
629 impl<'tcx> Hash for TyS<'tcx> {
630 fn hash<H: Hasher>(&self, s: &mut H) {
631 (self as *const TyS<'_>).hash(s)
635 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for TyS<'tcx> {
636 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
640 // The other fields just provide fast access to information that is
641 // also contained in `kind`, so no need to hash them.
644 outer_exclusive_binder: _,
647 kind.hash_stable(hcx, hasher);
651 #[rustc_diagnostic_item = "Ty"]
652 pub type Ty<'tcx> = &'tcx TyS<'tcx>;
654 impl<'tcx> rustc_serialize::UseSpecializedEncodable for Ty<'tcx> {}
655 impl<'tcx> rustc_serialize::UseSpecializedDecodable for Ty<'tcx> {}
656 impl<'tcx> rustc_serialize::UseSpecializedDecodable for &'tcx List<Ty<'tcx>> {}
658 pub type CanonicalTy<'tcx> = Canonical<'tcx, Ty<'tcx>>;
660 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
661 pub struct UpvarPath {
662 pub hir_id: hir::HirId,
665 /// Upvars do not get their own `NodeId`. Instead, we use the pair of
666 /// the original var ID (that is, the root variable that is referenced
667 /// by the upvar) and the ID of the closure expression.
668 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
670 pub var_path: UpvarPath,
671 pub closure_expr_id: LocalDefId,
674 #[derive(Clone, PartialEq, Debug, RustcEncodable, RustcDecodable, Copy, HashStable)]
675 pub enum BorrowKind {
676 /// Data must be immutable and is aliasable.
679 /// Data must be immutable but not aliasable. This kind of borrow
680 /// cannot currently be expressed by the user and is used only in
681 /// implicit closure bindings. It is needed when the closure
682 /// is borrowing or mutating a mutable referent, e.g.:
684 /// let x: &mut isize = ...;
685 /// let y = || *x += 5;
687 /// If we were to try to translate this closure into a more explicit
688 /// form, we'd encounter an error with the code as written:
690 /// struct Env { x: & &mut isize }
691 /// let x: &mut isize = ...;
692 /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
693 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
695 /// This is then illegal because you cannot mutate a `&mut` found
696 /// in an aliasable location. To solve, you'd have to translate with
697 /// an `&mut` borrow:
699 /// struct Env { x: & &mut isize }
700 /// let x: &mut isize = ...;
701 /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
702 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
704 /// Now the assignment to `**env.x` is legal, but creating a
705 /// mutable pointer to `x` is not because `x` is not mutable. We
706 /// could fix this by declaring `x` as `let mut x`. This is ok in
707 /// user code, if awkward, but extra weird for closures, since the
708 /// borrow is hidden.
710 /// So we introduce a "unique imm" borrow -- the referent is
711 /// immutable, but not aliasable. This solves the problem. For
712 /// simplicity, we don't give users the way to express this
713 /// borrow, it's just used when translating closures.
716 /// Data is mutable and not aliasable.
720 /// Information describing the capture of an upvar. This is computed
721 /// during `typeck`, specifically by `regionck`.
722 #[derive(PartialEq, Clone, Debug, Copy, RustcEncodable, RustcDecodable, HashStable)]
723 pub enum UpvarCapture<'tcx> {
724 /// Upvar is captured by value. This is always true when the
725 /// closure is labeled `move`, but can also be true in other cases
726 /// depending on inference.
729 /// Upvar is captured by reference.
730 ByRef(UpvarBorrow<'tcx>),
733 #[derive(PartialEq, Clone, Copy, RustcEncodable, RustcDecodable, HashStable)]
734 pub struct UpvarBorrow<'tcx> {
735 /// The kind of borrow: by-ref upvars have access to shared
736 /// immutable borrows, which are not part of the normal language
738 pub kind: BorrowKind,
740 /// Region of the resulting reference.
741 pub region: ty::Region<'tcx>,
744 pub type UpvarListMap = FxHashMap<DefId, FxIndexMap<hir::HirId, UpvarId>>;
745 pub type UpvarCaptureMap<'tcx> = FxHashMap<UpvarId, UpvarCapture<'tcx>>;
747 #[derive(Clone, Copy, PartialEq, Eq)]
748 pub enum IntVarValue {
750 UintType(ast::UintTy),
753 #[derive(Clone, Copy, PartialEq, Eq)]
754 pub struct FloatVarValue(pub ast::FloatTy);
756 impl ty::EarlyBoundRegion {
757 pub fn to_bound_region(&self) -> ty::BoundRegion {
758 ty::BoundRegion::BrNamed(self.def_id, self.name)
761 /// Does this early bound region have a name? Early bound regions normally
762 /// always have names except when using anonymous lifetimes (`'_`).
763 pub fn has_name(&self) -> bool {
764 self.name != kw::UnderscoreLifetime
768 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
769 pub enum GenericParamDefKind {
773 object_lifetime_default: ObjectLifetimeDefault,
774 synthetic: Option<hir::SyntheticTyParamKind>,
779 impl GenericParamDefKind {
780 pub fn descr(&self) -> &'static str {
782 GenericParamDefKind::Lifetime => "lifetime",
783 GenericParamDefKind::Type { .. } => "type",
784 GenericParamDefKind::Const => "constant",
789 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
790 pub struct GenericParamDef {
795 /// `pure_wrt_drop`, set by the (unsafe) `#[may_dangle]` attribute
796 /// on generic parameter `'a`/`T`, asserts data behind the parameter
797 /// `'a`/`T` won't be accessed during the parent type's `Drop` impl.
798 pub pure_wrt_drop: bool,
800 pub kind: GenericParamDefKind,
803 impl GenericParamDef {
804 pub fn to_early_bound_region_data(&self) -> ty::EarlyBoundRegion {
805 if let GenericParamDefKind::Lifetime = self.kind {
806 ty::EarlyBoundRegion { def_id: self.def_id, index: self.index, name: self.name }
808 bug!("cannot convert a non-lifetime parameter def to an early bound region")
812 pub fn to_bound_region(&self) -> ty::BoundRegion {
813 if let GenericParamDefKind::Lifetime = self.kind {
814 self.to_early_bound_region_data().to_bound_region()
816 bug!("cannot convert a non-lifetime parameter def to an early bound region")
822 pub struct GenericParamCount {
823 pub lifetimes: usize,
828 /// Information about the formal type/lifetime parameters associated
829 /// with an item or method. Analogous to `hir::Generics`.
831 /// The ordering of parameters is the same as in `Subst` (excluding child generics):
832 /// `Self` (optionally), `Lifetime` params..., `Type` params...
833 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
834 pub struct Generics {
835 pub parent: Option<DefId>,
836 pub parent_count: usize,
837 pub params: Vec<GenericParamDef>,
839 /// Reverse map to the `index` field of each `GenericParamDef`.
840 #[stable_hasher(ignore)]
841 pub param_def_id_to_index: FxHashMap<DefId, u32>,
844 pub has_late_bound_regions: Option<Span>,
847 impl<'tcx> Generics {
848 pub fn count(&self) -> usize {
849 self.parent_count + self.params.len()
852 pub fn own_counts(&self) -> GenericParamCount {
853 // We could cache this as a property of `GenericParamCount`, but
854 // the aim is to refactor this away entirely eventually and the
855 // presence of this method will be a constant reminder.
856 let mut own_counts: GenericParamCount = Default::default();
858 for param in &self.params {
860 GenericParamDefKind::Lifetime => own_counts.lifetimes += 1,
861 GenericParamDefKind::Type { .. } => own_counts.types += 1,
862 GenericParamDefKind::Const => own_counts.consts += 1,
869 pub fn requires_monomorphization(&self, tcx: TyCtxt<'tcx>) -> bool {
870 if self.own_requires_monomorphization() {
874 if let Some(parent_def_id) = self.parent {
875 let parent = tcx.generics_of(parent_def_id);
876 parent.requires_monomorphization(tcx)
882 pub fn own_requires_monomorphization(&self) -> bool {
883 for param in &self.params {
885 GenericParamDefKind::Type { .. } | GenericParamDefKind::Const => return true,
886 GenericParamDefKind::Lifetime => {}
892 pub fn param_at(&'tcx self, param_index: usize, tcx: TyCtxt<'tcx>) -> &'tcx GenericParamDef {
893 if let Some(index) = param_index.checked_sub(self.parent_count) {
896 tcx.generics_of(self.parent.expect("parent_count > 0 but no parent?"))
897 .param_at(param_index, tcx)
903 param: &EarlyBoundRegion,
905 ) -> &'tcx GenericParamDef {
906 let param = self.param_at(param.index as usize, tcx);
908 GenericParamDefKind::Lifetime => param,
909 _ => bug!("expected lifetime parameter, but found another generic parameter"),
913 /// Returns the `GenericParamDef` associated with this `ParamTy`.
914 pub fn type_param(&'tcx self, param: &ParamTy, tcx: TyCtxt<'tcx>) -> &'tcx GenericParamDef {
915 let param = self.param_at(param.index as usize, tcx);
917 GenericParamDefKind::Type { .. } => param,
918 _ => bug!("expected type parameter, but found another generic parameter"),
922 /// Returns the `ConstParameterDef` associated with this `ParamConst`.
923 pub fn const_param(&'tcx self, param: &ParamConst, tcx: TyCtxt<'tcx>) -> &GenericParamDef {
924 let param = self.param_at(param.index as usize, tcx);
926 GenericParamDefKind::Const => param,
927 _ => bug!("expected const parameter, but found another generic parameter"),
932 /// Bounds on generics.
933 #[derive(Copy, Clone, Default, Debug, RustcEncodable, RustcDecodable, HashStable)]
934 pub struct GenericPredicates<'tcx> {
935 pub parent: Option<DefId>,
936 pub predicates: &'tcx [(Predicate<'tcx>, Span)],
939 impl<'tcx> GenericPredicates<'tcx> {
943 substs: SubstsRef<'tcx>,
944 ) -> InstantiatedPredicates<'tcx> {
945 let mut instantiated = InstantiatedPredicates::empty();
946 self.instantiate_into(tcx, &mut instantiated, substs);
950 pub fn instantiate_own(
953 substs: SubstsRef<'tcx>,
954 ) -> InstantiatedPredicates<'tcx> {
955 InstantiatedPredicates {
956 predicates: self.predicates.iter().map(|(p, _)| p.subst(tcx, substs)).collect(),
957 spans: self.predicates.iter().map(|(_, sp)| *sp).collect(),
964 instantiated: &mut InstantiatedPredicates<'tcx>,
965 substs: SubstsRef<'tcx>,
967 if let Some(def_id) = self.parent {
968 tcx.predicates_of(def_id).instantiate_into(tcx, instantiated, substs);
970 instantiated.predicates.extend(self.predicates.iter().map(|(p, _)| p.subst(tcx, substs)));
971 instantiated.spans.extend(self.predicates.iter().map(|(_, sp)| *sp));
974 pub fn instantiate_identity(&self, tcx: TyCtxt<'tcx>) -> InstantiatedPredicates<'tcx> {
975 let mut instantiated = InstantiatedPredicates::empty();
976 self.instantiate_identity_into(tcx, &mut instantiated);
980 fn instantiate_identity_into(
983 instantiated: &mut InstantiatedPredicates<'tcx>,
985 if let Some(def_id) = self.parent {
986 tcx.predicates_of(def_id).instantiate_identity_into(tcx, instantiated);
988 instantiated.predicates.extend(self.predicates.iter().map(|(p, _)| p));
989 instantiated.spans.extend(self.predicates.iter().map(|(_, s)| s));
992 pub fn instantiate_supertrait(
995 poly_trait_ref: &ty::PolyTraitRef<'tcx>,
996 ) -> InstantiatedPredicates<'tcx> {
997 assert_eq!(self.parent, None);
998 InstantiatedPredicates {
1002 .map(|(pred, _)| pred.subst_supertrait(tcx, poly_trait_ref))
1004 spans: self.predicates.iter().map(|(_, sp)| *sp).collect(),
1010 crate struct PredicateInner<'tcx> {
1011 kind: PredicateKind<'tcx>,
1013 /// See the comment for the corresponding field of [TyS].
1014 outer_exclusive_binder: ty::DebruijnIndex,
1017 #[cfg(target_arch = "x86_64")]
1018 static_assert_size!(PredicateInner<'_>, 40);
1020 #[derive(Clone, Copy, Lift)]
1021 pub struct Predicate<'tcx> {
1022 inner: &'tcx PredicateInner<'tcx>,
1025 impl rustc_serialize::UseSpecializedEncodable for Predicate<'_> {}
1026 impl rustc_serialize::UseSpecializedDecodable for Predicate<'_> {}
1028 impl<'tcx> PartialEq for Predicate<'tcx> {
1029 fn eq(&self, other: &Self) -> bool {
1030 // `self.kind` is always interned.
1031 ptr::eq(self.inner, other.inner)
1035 impl Hash for Predicate<'_> {
1036 fn hash<H: Hasher>(&self, s: &mut H) {
1037 (self.inner as *const PredicateInner<'_>).hash(s)
1041 impl<'tcx> Eq for Predicate<'tcx> {}
1043 impl<'tcx> Predicate<'tcx> {
1045 pub fn kind(self) -> &'tcx PredicateKind<'tcx> {
1050 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for Predicate<'tcx> {
1051 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
1052 let PredicateInner {
1055 // The other fields just provide fast access to information that is
1056 // also contained in `kind`, so no need to hash them.
1058 outer_exclusive_binder: _,
1061 kind.hash_stable(hcx, hasher);
1065 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1066 #[derive(HashStable, TypeFoldable)]
1067 pub enum PredicateKind<'tcx> {
1068 /// Corresponds to `where Foo: Bar<A, B, C>`. `Foo` here would be
1069 /// the `Self` type of the trait reference and `A`, `B`, and `C`
1070 /// would be the type parameters.
1072 /// A trait predicate will have `Constness::Const` if it originates
1073 /// from a bound on a `const fn` without the `?const` opt-out (e.g.,
1074 /// `const fn foobar<Foo: Bar>() {}`).
1075 Trait(PolyTraitPredicate<'tcx>, Constness),
1078 RegionOutlives(PolyRegionOutlivesPredicate<'tcx>),
1081 TypeOutlives(PolyTypeOutlivesPredicate<'tcx>),
1083 /// `where <T as TraitRef>::Name == X`, approximately.
1084 /// See the `ProjectionPredicate` struct for details.
1085 Projection(PolyProjectionPredicate<'tcx>),
1087 /// No syntax: `T` well-formed.
1088 WellFormed(GenericArg<'tcx>),
1090 /// Trait must be object-safe.
1093 /// No direct syntax. May be thought of as `where T: FnFoo<...>`
1094 /// for some substitutions `...` and `T` being a closure type.
1095 /// Satisfied (or refuted) once we know the closure's kind.
1096 ClosureKind(DefId, SubstsRef<'tcx>, ClosureKind),
1099 Subtype(PolySubtypePredicate<'tcx>),
1101 /// Constant initializer must evaluate successfully.
1102 ConstEvaluatable(ty::WithOptParam<DefId>, SubstsRef<'tcx>),
1104 /// Constants must be equal. The first component is the const that is expected.
1105 ConstEquate(&'tcx Const<'tcx>, &'tcx Const<'tcx>),
1108 /// The crate outlives map is computed during typeck and contains the
1109 /// outlives of every item in the local crate. You should not use it
1110 /// directly, because to do so will make your pass dependent on the
1111 /// HIR of every item in the local crate. Instead, use
1112 /// `tcx.inferred_outlives_of()` to get the outlives for a *particular*
1114 #[derive(HashStable)]
1115 pub struct CratePredicatesMap<'tcx> {
1116 /// For each struct with outlive bounds, maps to a vector of the
1117 /// predicate of its outlive bounds. If an item has no outlives
1118 /// bounds, it will have no entry.
1119 pub predicates: FxHashMap<DefId, &'tcx [(ty::Predicate<'tcx>, Span)]>,
1122 impl<'tcx> Predicate<'tcx> {
1123 /// Performs a substitution suitable for going from a
1124 /// poly-trait-ref to supertraits that must hold if that
1125 /// poly-trait-ref holds. This is slightly different from a normal
1126 /// substitution in terms of what happens with bound regions. See
1127 /// lengthy comment below for details.
1128 pub fn subst_supertrait(
1131 trait_ref: &ty::PolyTraitRef<'tcx>,
1132 ) -> ty::Predicate<'tcx> {
1133 // The interaction between HRTB and supertraits is not entirely
1134 // obvious. Let me walk you (and myself) through an example.
1136 // Let's start with an easy case. Consider two traits:
1138 // trait Foo<'a>: Bar<'a,'a> { }
1139 // trait Bar<'b,'c> { }
1141 // Now, if we have a trait reference `for<'x> T: Foo<'x>`, then
1142 // we can deduce that `for<'x> T: Bar<'x,'x>`. Basically, if we
1143 // knew that `Foo<'x>` (for any 'x) then we also know that
1144 // `Bar<'x,'x>` (for any 'x). This more-or-less falls out from
1145 // normal substitution.
1147 // In terms of why this is sound, the idea is that whenever there
1148 // is an impl of `T:Foo<'a>`, it must show that `T:Bar<'a,'a>`
1149 // holds. So if there is an impl of `T:Foo<'a>` that applies to
1150 // all `'a`, then we must know that `T:Bar<'a,'a>` holds for all
1153 // Another example to be careful of is this:
1155 // trait Foo1<'a>: for<'b> Bar1<'a,'b> { }
1156 // trait Bar1<'b,'c> { }
1158 // Here, if we have `for<'x> T: Foo1<'x>`, then what do we know?
1159 // The answer is that we know `for<'x,'b> T: Bar1<'x,'b>`. The
1160 // reason is similar to the previous example: any impl of
1161 // `T:Foo1<'x>` must show that `for<'b> T: Bar1<'x, 'b>`. So
1162 // basically we would want to collapse the bound lifetimes from
1163 // the input (`trait_ref`) and the supertraits.
1165 // To achieve this in practice is fairly straightforward. Let's
1166 // consider the more complicated scenario:
1168 // - We start out with `for<'x> T: Foo1<'x>`. In this case, `'x`
1169 // has a De Bruijn index of 1. We want to produce `for<'x,'b> T: Bar1<'x,'b>`,
1170 // where both `'x` and `'b` would have a DB index of 1.
1171 // The substitution from the input trait-ref is therefore going to be
1172 // `'a => 'x` (where `'x` has a DB index of 1).
1173 // - The super-trait-ref is `for<'b> Bar1<'a,'b>`, where `'a` is an
1174 // early-bound parameter and `'b' is a late-bound parameter with a
1176 // - If we replace `'a` with `'x` from the input, it too will have
1177 // a DB index of 1, and thus we'll have `for<'x,'b> Bar1<'x,'b>`
1178 // just as we wanted.
1180 // There is only one catch. If we just apply the substitution `'a
1181 // => 'x` to `for<'b> Bar1<'a,'b>`, the substitution code will
1182 // adjust the DB index because we substituting into a binder (it
1183 // tries to be so smart...) resulting in `for<'x> for<'b>
1184 // Bar1<'x,'b>` (we have no syntax for this, so use your
1185 // imagination). Basically the 'x will have DB index of 2 and 'b
1186 // will have DB index of 1. Not quite what we want. So we apply
1187 // the substitution to the *contents* of the trait reference,
1188 // rather than the trait reference itself (put another way, the
1189 // substitution code expects equal binding levels in the values
1190 // from the substitution and the value being substituted into, and
1191 // this trick achieves that).
1193 let substs = &trait_ref.skip_binder().substs;
1194 let kind = self.kind();
1195 let new = match kind {
1196 &PredicateKind::Trait(ref binder, constness) => {
1197 PredicateKind::Trait(binder.map_bound(|data| data.subst(tcx, substs)), constness)
1199 PredicateKind::Subtype(binder) => {
1200 PredicateKind::Subtype(binder.map_bound(|data| data.subst(tcx, substs)))
1202 PredicateKind::RegionOutlives(binder) => {
1203 PredicateKind::RegionOutlives(binder.map_bound(|data| data.subst(tcx, substs)))
1205 PredicateKind::TypeOutlives(binder) => {
1206 PredicateKind::TypeOutlives(binder.map_bound(|data| data.subst(tcx, substs)))
1208 PredicateKind::Projection(binder) => {
1209 PredicateKind::Projection(binder.map_bound(|data| data.subst(tcx, substs)))
1211 &PredicateKind::WellFormed(data) => PredicateKind::WellFormed(data.subst(tcx, substs)),
1212 &PredicateKind::ObjectSafe(trait_def_id) => PredicateKind::ObjectSafe(trait_def_id),
1213 &PredicateKind::ClosureKind(closure_def_id, closure_substs, kind) => {
1214 PredicateKind::ClosureKind(closure_def_id, closure_substs.subst(tcx, substs), kind)
1216 &PredicateKind::ConstEvaluatable(def_id, const_substs) => {
1217 PredicateKind::ConstEvaluatable(def_id, const_substs.subst(tcx, substs))
1219 PredicateKind::ConstEquate(c1, c2) => {
1220 PredicateKind::ConstEquate(c1.subst(tcx, substs), c2.subst(tcx, substs))
1224 if new != *kind { new.to_predicate(tcx) } else { self }
1228 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1229 #[derive(HashStable, TypeFoldable)]
1230 pub struct TraitPredicate<'tcx> {
1231 pub trait_ref: TraitRef<'tcx>,
1234 pub type PolyTraitPredicate<'tcx> = ty::Binder<TraitPredicate<'tcx>>;
1236 impl<'tcx> TraitPredicate<'tcx> {
1237 pub fn def_id(self) -> DefId {
1238 self.trait_ref.def_id
1241 pub fn self_ty(self) -> Ty<'tcx> {
1242 self.trait_ref.self_ty()
1246 impl<'tcx> PolyTraitPredicate<'tcx> {
1247 pub fn def_id(self) -> DefId {
1248 // Ok to skip binder since trait `DefId` does not care about regions.
1249 self.skip_binder().def_id()
1253 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, RustcEncodable, RustcDecodable)]
1254 #[derive(HashStable, TypeFoldable)]
1255 pub struct OutlivesPredicate<A, B>(pub A, pub B); // `A: B`
1256 pub type PolyOutlivesPredicate<A, B> = ty::Binder<OutlivesPredicate<A, B>>;
1257 pub type RegionOutlivesPredicate<'tcx> = OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>;
1258 pub type TypeOutlivesPredicate<'tcx> = OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>;
1259 pub type PolyRegionOutlivesPredicate<'tcx> = ty::Binder<RegionOutlivesPredicate<'tcx>>;
1260 pub type PolyTypeOutlivesPredicate<'tcx> = ty::Binder<TypeOutlivesPredicate<'tcx>>;
1262 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
1263 #[derive(HashStable, TypeFoldable)]
1264 pub struct SubtypePredicate<'tcx> {
1265 pub a_is_expected: bool,
1269 pub type PolySubtypePredicate<'tcx> = ty::Binder<SubtypePredicate<'tcx>>;
1271 /// This kind of predicate has no *direct* correspondent in the
1272 /// syntax, but it roughly corresponds to the syntactic forms:
1274 /// 1. `T: TraitRef<..., Item = Type>`
1275 /// 2. `<T as TraitRef<...>>::Item == Type` (NYI)
1277 /// In particular, form #1 is "desugared" to the combination of a
1278 /// normal trait predicate (`T: TraitRef<...>`) and one of these
1279 /// predicates. Form #2 is a broader form in that it also permits
1280 /// equality between arbitrary types. Processing an instance of
1281 /// Form #2 eventually yields one of these `ProjectionPredicate`
1282 /// instances to normalize the LHS.
1283 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1284 #[derive(HashStable, TypeFoldable)]
1285 pub struct ProjectionPredicate<'tcx> {
1286 pub projection_ty: ProjectionTy<'tcx>,
1290 pub type PolyProjectionPredicate<'tcx> = Binder<ProjectionPredicate<'tcx>>;
1292 impl<'tcx> PolyProjectionPredicate<'tcx> {
1293 /// Returns the `DefId` of the associated item being projected.
1294 pub fn item_def_id(&self) -> DefId {
1295 self.skip_binder().projection_ty.item_def_id
1299 pub fn to_poly_trait_ref(&self, tcx: TyCtxt<'tcx>) -> PolyTraitRef<'tcx> {
1300 // Note: unlike with `TraitRef::to_poly_trait_ref()`,
1301 // `self.0.trait_ref` is permitted to have escaping regions.
1302 // This is because here `self` has a `Binder` and so does our
1303 // return value, so we are preserving the number of binding
1305 self.map_bound(|predicate| predicate.projection_ty.trait_ref(tcx))
1308 pub fn ty(&self) -> Binder<Ty<'tcx>> {
1309 self.map_bound(|predicate| predicate.ty)
1312 /// The `DefId` of the `TraitItem` for the associated type.
1314 /// Note that this is not the `DefId` of the `TraitRef` containing this
1315 /// associated type, which is in `tcx.associated_item(projection_def_id()).container`.
1316 pub fn projection_def_id(&self) -> DefId {
1317 // Ok to skip binder since trait `DefId` does not care about regions.
1318 self.skip_binder().projection_ty.item_def_id
1322 pub trait ToPolyTraitRef<'tcx> {
1323 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx>;
1326 impl<'tcx> ToPolyTraitRef<'tcx> for TraitRef<'tcx> {
1327 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
1328 ty::Binder::dummy(*self)
1332 impl<'tcx> ToPolyTraitRef<'tcx> for PolyTraitPredicate<'tcx> {
1333 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
1334 self.map_bound_ref(|trait_pred| trait_pred.trait_ref)
1338 pub trait ToPredicate<'tcx> {
1339 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx>;
1342 impl ToPredicate<'tcx> for PredicateKind<'tcx> {
1344 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1345 tcx.mk_predicate(self)
1349 impl<'tcx> ToPredicate<'tcx> for ConstnessAnd<TraitRef<'tcx>> {
1350 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1351 ty::PredicateKind::Trait(
1352 ty::Binder::dummy(ty::TraitPredicate { trait_ref: self.value }),
1359 impl<'tcx> ToPredicate<'tcx> for ConstnessAnd<&TraitRef<'tcx>> {
1360 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1361 ty::PredicateKind::Trait(
1362 ty::Binder::dummy(ty::TraitPredicate { trait_ref: *self.value }),
1369 impl<'tcx> ToPredicate<'tcx> for ConstnessAnd<PolyTraitRef<'tcx>> {
1370 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1371 ty::PredicateKind::Trait(self.value.to_poly_trait_predicate(), self.constness)
1376 impl<'tcx> ToPredicate<'tcx> for ConstnessAnd<&PolyTraitRef<'tcx>> {
1377 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1378 ty::PredicateKind::Trait(self.value.to_poly_trait_predicate(), self.constness)
1383 impl<'tcx> ToPredicate<'tcx> for PolyRegionOutlivesPredicate<'tcx> {
1384 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1385 PredicateKind::RegionOutlives(self).to_predicate(tcx)
1389 impl<'tcx> ToPredicate<'tcx> for PolyTypeOutlivesPredicate<'tcx> {
1390 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1391 PredicateKind::TypeOutlives(self).to_predicate(tcx)
1395 impl<'tcx> ToPredicate<'tcx> for PolyProjectionPredicate<'tcx> {
1396 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1397 PredicateKind::Projection(self).to_predicate(tcx)
1401 impl<'tcx> Predicate<'tcx> {
1402 pub fn to_opt_poly_trait_ref(self) -> Option<PolyTraitRef<'tcx>> {
1404 &PredicateKind::Trait(ref t, _) => Some(t.to_poly_trait_ref()),
1405 PredicateKind::Projection(..)
1406 | PredicateKind::Subtype(..)
1407 | PredicateKind::RegionOutlives(..)
1408 | PredicateKind::WellFormed(..)
1409 | PredicateKind::ObjectSafe(..)
1410 | PredicateKind::ClosureKind(..)
1411 | PredicateKind::TypeOutlives(..)
1412 | PredicateKind::ConstEvaluatable(..)
1413 | PredicateKind::ConstEquate(..) => None,
1417 pub fn to_opt_type_outlives(self) -> Option<PolyTypeOutlivesPredicate<'tcx>> {
1419 &PredicateKind::TypeOutlives(data) => Some(data),
1420 PredicateKind::Trait(..)
1421 | PredicateKind::Projection(..)
1422 | PredicateKind::Subtype(..)
1423 | PredicateKind::RegionOutlives(..)
1424 | PredicateKind::WellFormed(..)
1425 | PredicateKind::ObjectSafe(..)
1426 | PredicateKind::ClosureKind(..)
1427 | PredicateKind::ConstEvaluatable(..)
1428 | PredicateKind::ConstEquate(..) => None,
1433 /// Represents the bounds declared on a particular set of type
1434 /// parameters. Should eventually be generalized into a flag list of
1435 /// where-clauses. You can obtain a `InstantiatedPredicates` list from a
1436 /// `GenericPredicates` by using the `instantiate` method. Note that this method
1437 /// reflects an important semantic invariant of `InstantiatedPredicates`: while
1438 /// the `GenericPredicates` are expressed in terms of the bound type
1439 /// parameters of the impl/trait/whatever, an `InstantiatedPredicates` instance
1440 /// represented a set of bounds for some particular instantiation,
1441 /// meaning that the generic parameters have been substituted with
1446 /// struct Foo<T, U: Bar<T>> { ... }
1448 /// Here, the `GenericPredicates` for `Foo` would contain a list of bounds like
1449 /// `[[], [U:Bar<T>]]`. Now if there were some particular reference
1450 /// like `Foo<isize,usize>`, then the `InstantiatedPredicates` would be `[[],
1451 /// [usize:Bar<isize>]]`.
1452 #[derive(Clone, Debug, TypeFoldable)]
1453 pub struct InstantiatedPredicates<'tcx> {
1454 pub predicates: Vec<Predicate<'tcx>>,
1455 pub spans: Vec<Span>,
1458 impl<'tcx> InstantiatedPredicates<'tcx> {
1459 pub fn empty() -> InstantiatedPredicates<'tcx> {
1460 InstantiatedPredicates { predicates: vec![], spans: vec![] }
1463 pub fn is_empty(&self) -> bool {
1464 self.predicates.is_empty()
1468 rustc_index::newtype_index! {
1469 /// "Universes" are used during type- and trait-checking in the
1470 /// presence of `for<..>` binders to control what sets of names are
1471 /// visible. Universes are arranged into a tree: the root universe
1472 /// contains names that are always visible. Each child then adds a new
1473 /// set of names that are visible, in addition to those of its parent.
1474 /// We say that the child universe "extends" the parent universe with
1477 /// To make this more concrete, consider this program:
1481 /// fn bar<T>(x: T) {
1482 /// let y: for<'a> fn(&'a u8, Foo) = ...;
1486 /// The struct name `Foo` is in the root universe U0. But the type
1487 /// parameter `T`, introduced on `bar`, is in an extended universe U1
1488 /// -- i.e., within `bar`, we can name both `T` and `Foo`, but outside
1489 /// of `bar`, we cannot name `T`. Then, within the type of `y`, the
1490 /// region `'a` is in a universe U2 that extends U1, because we can
1491 /// name it inside the fn type but not outside.
1493 /// Universes are used to do type- and trait-checking around these
1494 /// "forall" binders (also called **universal quantification**). The
1495 /// idea is that when, in the body of `bar`, we refer to `T` as a
1496 /// type, we aren't referring to any type in particular, but rather a
1497 /// kind of "fresh" type that is distinct from all other types we have
1498 /// actually declared. This is called a **placeholder** type, and we
1499 /// use universes to talk about this. In other words, a type name in
1500 /// universe 0 always corresponds to some "ground" type that the user
1501 /// declared, but a type name in a non-zero universe is a placeholder
1502 /// type -- an idealized representative of "types in general" that we
1503 /// use for checking generic functions.
1504 pub struct UniverseIndex {
1506 DEBUG_FORMAT = "U{}",
1510 impl UniverseIndex {
1511 pub const ROOT: UniverseIndex = UniverseIndex::from_u32(0);
1513 /// Returns the "next" universe index in order -- this new index
1514 /// is considered to extend all previous universes. This
1515 /// corresponds to entering a `forall` quantifier. So, for
1516 /// example, suppose we have this type in universe `U`:
1519 /// for<'a> fn(&'a u32)
1522 /// Once we "enter" into this `for<'a>` quantifier, we are in a
1523 /// new universe that extends `U` -- in this new universe, we can
1524 /// name the region `'a`, but that region was not nameable from
1525 /// `U` because it was not in scope there.
1526 pub fn next_universe(self) -> UniverseIndex {
1527 UniverseIndex::from_u32(self.private.checked_add(1).unwrap())
1530 /// Returns `true` if `self` can name a name from `other` -- in other words,
1531 /// if the set of names in `self` is a superset of those in
1532 /// `other` (`self >= other`).
1533 pub fn can_name(self, other: UniverseIndex) -> bool {
1534 self.private >= other.private
1537 /// Returns `true` if `self` cannot name some names from `other` -- in other
1538 /// words, if the set of names in `self` is a strict subset of
1539 /// those in `other` (`self < other`).
1540 pub fn cannot_name(self, other: UniverseIndex) -> bool {
1541 self.private < other.private
1545 /// The "placeholder index" fully defines a placeholder region.
1546 /// Placeholder regions are identified by both a **universe** as well
1547 /// as a "bound-region" within that universe. The `bound_region` is
1548 /// basically a name -- distinct bound regions within the same
1549 /// universe are just two regions with an unknown relationship to one
1551 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, PartialOrd, Ord)]
1552 pub struct Placeholder<T> {
1553 pub universe: UniverseIndex,
1557 impl<'a, T> HashStable<StableHashingContext<'a>> for Placeholder<T>
1559 T: HashStable<StableHashingContext<'a>>,
1561 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
1562 self.universe.hash_stable(hcx, hasher);
1563 self.name.hash_stable(hcx, hasher);
1567 pub type PlaceholderRegion = Placeholder<BoundRegion>;
1569 pub type PlaceholderType = Placeholder<BoundVar>;
1571 pub type PlaceholderConst = Placeholder<BoundVar>;
1573 /// A `DefId` which is potentially bundled with its corresponding generic parameter
1574 /// in case `did` is a const argument.
1576 /// This is used to prevent cycle errors during typeck
1577 /// as `type_of(const_arg)` depends on `typeck_tables_of(owning_body)`
1578 /// which once again requires the type of its generic arguments.
1580 /// Luckily we only need to deal with const arguments once we
1581 /// know their corresponding parameters. We (ab)use this by
1582 /// calling `type_of(param_did)` for these arguments.
1585 /// #![feature(const_generics)]
1589 /// fn foo<const N: usize>(&self) -> usize { N }
1593 /// fn foo<const N: u8>(&self) -> usize { 42 }
1601 #[derive(Copy, Clone, Debug, TypeFoldable, Lift, RustcEncodable, RustcDecodable)]
1602 #[derive(PartialEq, Eq, PartialOrd, Ord)]
1603 #[derive(Hash, HashStable)]
1604 pub struct WithOptParam<T> {
1606 /// The `DefId` of the corresponding generic paramter in case `did` is
1607 /// a const argument.
1609 /// Note that even if `did` is a const argument, this may still be `None`.
1610 /// All queries taking `WithOptParam` start by calling `tcx.opt_const_param_of(def.did)`
1611 /// to potentially update `param_did` in case it `None`.
1612 pub param_did: Option<DefId>,
1615 impl<T> WithOptParam<T> {
1616 pub fn dummy(did: T) -> WithOptParam<T> {
1617 WithOptParam { did, param_did: None }
1621 impl WithOptParam<LocalDefId> {
1622 pub fn to_global(self) -> WithOptParam<DefId> {
1623 WithOptParam { did: self.did.to_def_id(), param_did: self.param_did }
1626 pub fn ty_def_id(self) -> DefId {
1627 if let Some(did) = self.param_did { did } else { self.did.to_def_id() }
1631 impl WithOptParam<DefId> {
1632 pub fn as_local(self) -> Option<WithOptParam<LocalDefId>> {
1633 self.did.as_local().map(|did| WithOptParam { did, param_did: self.param_did })
1636 pub fn as_const_arg(self) -> Option<(LocalDefId, DefId)> {
1637 if let Some(param_did) = self.param_did {
1638 if let Some(did) = self.did.as_local() {
1639 return Some((did, param_did));
1646 pub fn expect_local(self) -> WithOptParam<LocalDefId> {
1647 self.as_local().unwrap()
1650 pub fn is_local(self) -> bool {
1654 pub fn ty_def_id(self) -> DefId {
1655 self.param_did.unwrap_or(self.did)
1659 /// When type checking, we use the `ParamEnv` to track
1660 /// details about the set of where-clauses that are in scope at this
1661 /// particular point.
1662 #[derive(Copy, Clone)]
1663 pub struct ParamEnv<'tcx> {
1664 // We pack the caller_bounds List pointer and a Reveal enum into this usize.
1665 // Specifically, the low bit represents Reveal, with 0 meaning `UserFacing`
1666 // and 1 meaning `All`. The rest is the pointer.
1668 // This relies on the List<ty::Predicate<'tcx>> type having at least 2-byte
1669 // alignment. Lists start with a usize and are repr(C) so this should be
1670 // fine; there is a debug_assert in the constructor as well.
1672 // Note that the choice of 0 for UserFacing is intentional -- since it is the
1673 // first variant in Reveal this means that joining the pointer is a simple `or`.
1676 /// `Obligation`s that the caller must satisfy. This is basically
1677 /// the set of bounds on the in-scope type parameters, translated
1678 /// into `Obligation`s, and elaborated and normalized.
1680 /// Note: This is packed into the `packed_data` usize above, use the
1681 /// `caller_bounds()` method to access it.
1682 caller_bounds: PhantomData<&'tcx List<ty::Predicate<'tcx>>>,
1684 /// Typically, this is `Reveal::UserFacing`, but during codegen we
1685 /// want `Reveal::All`.
1687 /// Note: This is packed into the caller_bounds usize above, use the reveal()
1688 /// method to access it.
1689 reveal: PhantomData<traits::Reveal>,
1691 /// If this `ParamEnv` comes from a call to `tcx.param_env(def_id)`,
1692 /// register that `def_id` (useful for transitioning to the chalk trait
1694 pub def_id: Option<DefId>,
1697 impl<'tcx> fmt::Debug for ParamEnv<'tcx> {
1698 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1699 f.debug_struct("ParamEnv")
1700 .field("caller_bounds", &self.caller_bounds())
1701 .field("reveal", &self.reveal())
1702 .field("def_id", &self.def_id)
1707 impl<'tcx> Hash for ParamEnv<'tcx> {
1708 fn hash<H: Hasher>(&self, state: &mut H) {
1709 // List hashes as the raw pointer, so we can skip splitting into the
1710 // pointer and the enum.
1711 self.packed_data.hash(state);
1712 self.def_id.hash(state);
1716 impl<'tcx> PartialEq for ParamEnv<'tcx> {
1717 fn eq(&self, other: &Self) -> bool {
1718 self.caller_bounds() == other.caller_bounds()
1719 && self.reveal() == other.reveal()
1720 && self.def_id == other.def_id
1723 impl<'tcx> Eq for ParamEnv<'tcx> {}
1725 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for ParamEnv<'tcx> {
1726 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
1727 self.caller_bounds().hash_stable(hcx, hasher);
1728 self.reveal().hash_stable(hcx, hasher);
1729 self.def_id.hash_stable(hcx, hasher);
1733 impl<'tcx> TypeFoldable<'tcx> for ParamEnv<'tcx> {
1734 fn super_fold_with<F: ty::fold::TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
1736 self.caller_bounds().fold_with(folder),
1737 self.reveal().fold_with(folder),
1738 self.def_id.fold_with(folder),
1742 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1743 self.caller_bounds().visit_with(visitor)
1744 || self.reveal().visit_with(visitor)
1745 || self.def_id.visit_with(visitor)
1749 impl<'tcx> ParamEnv<'tcx> {
1750 /// Construct a trait environment suitable for contexts where
1751 /// there are no where-clauses in scope. Hidden types (like `impl
1752 /// Trait`) are left hidden, so this is suitable for ordinary
1755 pub fn empty() -> Self {
1756 Self::new(List::empty(), Reveal::UserFacing, None)
1760 pub fn caller_bounds(self) -> &'tcx List<ty::Predicate<'tcx>> {
1761 // mask out bottom bit
1762 unsafe { &*((self.packed_data & (!1)) as *const _) }
1766 pub fn reveal(self) -> traits::Reveal {
1767 if self.packed_data & 1 == 0 { traits::Reveal::UserFacing } else { traits::Reveal::All }
1770 /// Construct a trait environment with no where-clauses in scope
1771 /// where the values of all `impl Trait` and other hidden types
1772 /// are revealed. This is suitable for monomorphized, post-typeck
1773 /// environments like codegen or doing optimizations.
1775 /// N.B., if you want to have predicates in scope, use `ParamEnv::new`,
1776 /// or invoke `param_env.with_reveal_all()`.
1778 pub fn reveal_all() -> Self {
1779 Self::new(List::empty(), Reveal::All, None)
1782 /// Construct a trait environment with the given set of predicates.
1785 caller_bounds: &'tcx List<ty::Predicate<'tcx>>,
1787 def_id: Option<DefId>,
1789 let packed_data = caller_bounds as *const _ as usize;
1790 // Check that we can pack the reveal data into the pointer.
1791 debug_assert!(packed_data & 1 == 0);
1793 packed_data: packed_data
1795 Reveal::UserFacing => 0,
1798 caller_bounds: PhantomData,
1799 reveal: PhantomData,
1804 pub fn with_user_facing(mut self) -> Self {
1806 self.packed_data &= !1;
1810 /// Returns a new parameter environment with the same clauses, but
1811 /// which "reveals" the true results of projections in all cases
1812 /// (even for associated types that are specializable). This is
1813 /// the desired behavior during codegen and certain other special
1814 /// contexts; normally though we want to use `Reveal::UserFacing`,
1815 /// which is the default.
1816 pub fn with_reveal_all(mut self) -> Self {
1817 self.packed_data |= 1;
1821 /// Returns this same environment but with no caller bounds.
1822 pub fn without_caller_bounds(self) -> Self {
1823 Self::new(List::empty(), self.reveal(), self.def_id)
1826 /// Creates a suitable environment in which to perform trait
1827 /// queries on the given value. When type-checking, this is simply
1828 /// the pair of the environment plus value. But when reveal is set to
1829 /// All, then if `value` does not reference any type parameters, we will
1830 /// pair it with the empty environment. This improves caching and is generally
1833 /// N.B., we preserve the environment when type-checking because it
1834 /// is possible for the user to have wacky where-clauses like
1835 /// `where Box<u32>: Copy`, which are clearly never
1836 /// satisfiable. We generally want to behave as if they were true,
1837 /// although the surrounding function is never reachable.
1838 pub fn and<T: TypeFoldable<'tcx>>(self, value: T) -> ParamEnvAnd<'tcx, T> {
1839 match self.reveal() {
1840 Reveal::UserFacing => ParamEnvAnd { param_env: self, value },
1843 if value.is_global() {
1844 ParamEnvAnd { param_env: self.without_caller_bounds(), value }
1846 ParamEnvAnd { param_env: self, value }
1853 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1854 pub struct ConstnessAnd<T> {
1855 pub constness: Constness,
1859 // FIXME(ecstaticmorse): Audit all occurrences of `without_const().to_predicate(tcx)` to ensure that
1860 // the constness of trait bounds is being propagated correctly.
1861 pub trait WithConstness: Sized {
1863 fn with_constness(self, constness: Constness) -> ConstnessAnd<Self> {
1864 ConstnessAnd { constness, value: self }
1868 fn with_const(self) -> ConstnessAnd<Self> {
1869 self.with_constness(Constness::Const)
1873 fn without_const(self) -> ConstnessAnd<Self> {
1874 self.with_constness(Constness::NotConst)
1878 impl<T> WithConstness for T {}
1880 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TypeFoldable)]
1881 pub struct ParamEnvAnd<'tcx, T> {
1882 pub param_env: ParamEnv<'tcx>,
1886 impl<'tcx, T> ParamEnvAnd<'tcx, T> {
1887 pub fn into_parts(self) -> (ParamEnv<'tcx>, T) {
1888 (self.param_env, self.value)
1892 impl<'a, 'tcx, T> HashStable<StableHashingContext<'a>> for ParamEnvAnd<'tcx, T>
1894 T: HashStable<StableHashingContext<'a>>,
1896 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
1897 let ParamEnvAnd { ref param_env, ref value } = *self;
1899 param_env.hash_stable(hcx, hasher);
1900 value.hash_stable(hcx, hasher);
1904 #[derive(Copy, Clone, Debug, HashStable)]
1905 pub struct Destructor {
1906 /// The `DefId` of the destructor method
1911 #[derive(HashStable)]
1912 pub struct AdtFlags: u32 {
1913 const NO_ADT_FLAGS = 0;
1914 /// Indicates whether the ADT is an enum.
1915 const IS_ENUM = 1 << 0;
1916 /// Indicates whether the ADT is a union.
1917 const IS_UNION = 1 << 1;
1918 /// Indicates whether the ADT is a struct.
1919 const IS_STRUCT = 1 << 2;
1920 /// Indicates whether the ADT is a struct and has a constructor.
1921 const HAS_CTOR = 1 << 3;
1922 /// Indicates whether the type is `PhantomData`.
1923 const IS_PHANTOM_DATA = 1 << 4;
1924 /// Indicates whether the type has a `#[fundamental]` attribute.
1925 const IS_FUNDAMENTAL = 1 << 5;
1926 /// Indicates whether the type is `Box`.
1927 const IS_BOX = 1 << 6;
1928 /// Indicates whether the type is `ManuallyDrop`.
1929 const IS_MANUALLY_DROP = 1 << 7;
1930 /// Indicates whether the variant list of this ADT is `#[non_exhaustive]`.
1931 /// (i.e., this flag is never set unless this ADT is an enum).
1932 const IS_VARIANT_LIST_NON_EXHAUSTIVE = 1 << 8;
1937 #[derive(HashStable)]
1938 pub struct VariantFlags: u32 {
1939 const NO_VARIANT_FLAGS = 0;
1940 /// Indicates whether the field list of this variant is `#[non_exhaustive]`.
1941 const IS_FIELD_LIST_NON_EXHAUSTIVE = 1 << 0;
1945 /// Definition of a variant -- a struct's fields or a enum variant.
1946 #[derive(Debug, HashStable)]
1947 pub struct VariantDef {
1948 /// `DefId` that identifies the variant itself.
1949 /// If this variant belongs to a struct or union, then this is a copy of its `DefId`.
1951 /// `DefId` that identifies the variant's constructor.
1952 /// If this variant is a struct variant, then this is `None`.
1953 pub ctor_def_id: Option<DefId>,
1954 /// Variant or struct name.
1955 #[stable_hasher(project(name))]
1957 /// Discriminant of this variant.
1958 pub discr: VariantDiscr,
1959 /// Fields of this variant.
1960 pub fields: Vec<FieldDef>,
1961 /// Type of constructor of variant.
1962 pub ctor_kind: CtorKind,
1963 /// Flags of the variant (e.g. is field list non-exhaustive)?
1964 flags: VariantFlags,
1965 /// Variant is obtained as part of recovering from a syntactic error.
1966 /// May be incomplete or bogus.
1967 pub recovered: bool,
1970 impl<'tcx> VariantDef {
1971 /// Creates a new `VariantDef`.
1973 /// `variant_did` is the `DefId` that identifies the enum variant (if this `VariantDef`
1974 /// represents an enum variant).
1976 /// `ctor_did` is the `DefId` that identifies the constructor of unit or
1977 /// tuple-variants/structs. If this is a `struct`-variant then this should be `None`.
1979 /// `parent_did` is the `DefId` of the `AdtDef` representing the enum or struct that
1980 /// owns this variant. It is used for checking if a struct has `#[non_exhaustive]` w/out having
1981 /// to go through the redirect of checking the ctor's attributes - but compiling a small crate
1982 /// requires loading the `AdtDef`s for all the structs in the universe (e.g., coherence for any
1983 /// built-in trait), and we do not want to load attributes twice.
1985 /// If someone speeds up attribute loading to not be a performance concern, they can
1986 /// remove this hack and use the constructor `DefId` everywhere.
1990 variant_did: Option<DefId>,
1991 ctor_def_id: Option<DefId>,
1992 discr: VariantDiscr,
1993 fields: Vec<FieldDef>,
1994 ctor_kind: CtorKind,
2000 "VariantDef::new(ident = {:?}, variant_did = {:?}, ctor_def_id = {:?}, discr = {:?},
2001 fields = {:?}, ctor_kind = {:?}, adt_kind = {:?}, parent_did = {:?})",
2002 ident, variant_did, ctor_def_id, discr, fields, ctor_kind, adt_kind, parent_did,
2005 let mut flags = VariantFlags::NO_VARIANT_FLAGS;
2006 if adt_kind == AdtKind::Struct && tcx.has_attr(parent_did, sym::non_exhaustive) {
2007 debug!("found non-exhaustive field list for {:?}", parent_did);
2008 flags = flags | VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE;
2009 } else if let Some(variant_did) = variant_did {
2010 if tcx.has_attr(variant_did, sym::non_exhaustive) {
2011 debug!("found non-exhaustive field list for {:?}", variant_did);
2012 flags = flags | VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE;
2017 def_id: variant_did.unwrap_or(parent_did),
2028 /// Is this field list non-exhaustive?
2030 pub fn is_field_list_non_exhaustive(&self) -> bool {
2031 self.flags.intersects(VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE)
2034 /// `repr(transparent)` structs can have a single non-ZST field, this function returns that
2036 pub fn transparent_newtype_field(&self, tcx: TyCtxt<'tcx>) -> Option<&FieldDef> {
2037 for field in &self.fields {
2038 let field_ty = field.ty(tcx, InternalSubsts::identity_for_item(tcx, self.def_id));
2039 if !field_ty.is_zst(tcx, self.def_id) {
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 `alloc_adt_def`) into the global arena.
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<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 /// Returns the discriminant type, given these `repr` options.
2263 /// This must only be called on enums!
2264 pub fn discr_type(&self) -> attr::IntType {
2265 self.int.unwrap_or(attr::SignedInt(ast::IntTy::Isize))
2268 /// Returns `true` if this `#[repr()]` should inhabit "smart enum
2269 /// layout" optimizations, such as representing `Foo<&T>` as a
2271 pub fn inhibit_enum_layout_opt(&self) -> bool {
2272 self.c() || self.int.is_some()
2275 /// Returns `true` if this `#[repr()]` should inhibit struct field reordering
2276 /// optimizations, such as with `repr(C)`, `repr(packed(1))`, or `repr(<int>)`.
2277 pub fn inhibit_struct_field_reordering_opt(&self) -> bool {
2278 if let Some(pack) = self.pack {
2279 if pack.bytes() == 1 {
2283 self.flags.intersects(ReprFlags::IS_UNOPTIMISABLE) || self.int.is_some()
2286 /// Returns `true` if this `#[repr()]` should inhibit union ABI optimisations.
2287 pub fn inhibit_union_abi_opt(&self) -> bool {
2293 /// Creates a new `AdtDef`.
2298 variants: IndexVec<VariantIdx, VariantDef>,
2301 debug!("AdtDef::new({:?}, {:?}, {:?}, {:?})", did, kind, variants, repr);
2302 let mut flags = AdtFlags::NO_ADT_FLAGS;
2304 if kind == AdtKind::Enum && tcx.has_attr(did, sym::non_exhaustive) {
2305 debug!("found non-exhaustive variant list for {:?}", did);
2306 flags = flags | AdtFlags::IS_VARIANT_LIST_NON_EXHAUSTIVE;
2309 flags |= match kind {
2310 AdtKind::Enum => AdtFlags::IS_ENUM,
2311 AdtKind::Union => AdtFlags::IS_UNION,
2312 AdtKind::Struct => AdtFlags::IS_STRUCT,
2315 if kind == AdtKind::Struct && variants[VariantIdx::new(0)].ctor_def_id.is_some() {
2316 flags |= AdtFlags::HAS_CTOR;
2319 let attrs = tcx.get_attrs(did);
2320 if attr::contains_name(&attrs, sym::fundamental) {
2321 flags |= AdtFlags::IS_FUNDAMENTAL;
2323 if Some(did) == tcx.lang_items().phantom_data() {
2324 flags |= AdtFlags::IS_PHANTOM_DATA;
2326 if Some(did) == tcx.lang_items().owned_box() {
2327 flags |= AdtFlags::IS_BOX;
2329 if Some(did) == tcx.lang_items().manually_drop() {
2330 flags |= AdtFlags::IS_MANUALLY_DROP;
2333 AdtDef { did, variants, flags, repr }
2336 /// Returns `true` if this is a struct.
2338 pub fn is_struct(&self) -> bool {
2339 self.flags.contains(AdtFlags::IS_STRUCT)
2342 /// Returns `true` if this is a union.
2344 pub fn is_union(&self) -> bool {
2345 self.flags.contains(AdtFlags::IS_UNION)
2348 /// Returns `true` if this is a enum.
2350 pub fn is_enum(&self) -> bool {
2351 self.flags.contains(AdtFlags::IS_ENUM)
2354 /// Returns `true` if the variant list of this ADT is `#[non_exhaustive]`.
2356 pub fn is_variant_list_non_exhaustive(&self) -> bool {
2357 self.flags.contains(AdtFlags::IS_VARIANT_LIST_NON_EXHAUSTIVE)
2360 /// Returns the kind of the ADT.
2362 pub fn adt_kind(&self) -> AdtKind {
2365 } else if self.is_union() {
2372 /// Returns a description of this abstract data type.
2373 pub fn descr(&self) -> &'static str {
2374 match self.adt_kind() {
2375 AdtKind::Struct => "struct",
2376 AdtKind::Union => "union",
2377 AdtKind::Enum => "enum",
2381 /// Returns a description of a variant of this abstract data type.
2383 pub fn variant_descr(&self) -> &'static str {
2384 match self.adt_kind() {
2385 AdtKind::Struct => "struct",
2386 AdtKind::Union => "union",
2387 AdtKind::Enum => "variant",
2391 /// If this function returns `true`, it implies that `is_struct` must return `true`.
2393 pub fn has_ctor(&self) -> bool {
2394 self.flags.contains(AdtFlags::HAS_CTOR)
2397 /// Returns `true` if this type is `#[fundamental]` for the purposes
2398 /// of coherence checking.
2400 pub fn is_fundamental(&self) -> bool {
2401 self.flags.contains(AdtFlags::IS_FUNDAMENTAL)
2404 /// Returns `true` if this is `PhantomData<T>`.
2406 pub fn is_phantom_data(&self) -> bool {
2407 self.flags.contains(AdtFlags::IS_PHANTOM_DATA)
2410 /// Returns `true` if this is Box<T>.
2412 pub fn is_box(&self) -> bool {
2413 self.flags.contains(AdtFlags::IS_BOX)
2416 /// Returns `true` if this is `ManuallyDrop<T>`.
2418 pub fn is_manually_drop(&self) -> bool {
2419 self.flags.contains(AdtFlags::IS_MANUALLY_DROP)
2422 /// Returns `true` if this type has a destructor.
2423 pub fn has_dtor(&self, tcx: TyCtxt<'tcx>) -> bool {
2424 self.destructor(tcx).is_some()
2427 /// Asserts this is a struct or union and returns its unique variant.
2428 pub fn non_enum_variant(&self) -> &VariantDef {
2429 assert!(self.is_struct() || self.is_union());
2430 &self.variants[VariantIdx::new(0)]
2434 pub fn predicates(&self, tcx: TyCtxt<'tcx>) -> GenericPredicates<'tcx> {
2435 tcx.predicates_of(self.did)
2438 /// Returns an iterator over all fields contained
2441 pub fn all_fields(&self) -> impl Iterator<Item = &FieldDef> + Clone {
2442 self.variants.iter().flat_map(|v| v.fields.iter())
2445 pub fn is_payloadfree(&self) -> bool {
2446 !self.variants.is_empty() && self.variants.iter().all(|v| v.fields.is_empty())
2449 /// Return a `VariantDef` given a variant id.
2450 pub fn variant_with_id(&self, vid: DefId) -> &VariantDef {
2451 self.variants.iter().find(|v| v.def_id == vid).expect("variant_with_id: unknown variant")
2454 /// Return a `VariantDef` given a constructor id.
2455 pub fn variant_with_ctor_id(&self, cid: DefId) -> &VariantDef {
2458 .find(|v| v.ctor_def_id == Some(cid))
2459 .expect("variant_with_ctor_id: unknown variant")
2462 /// Return the index of `VariantDef` given a variant id.
2463 pub fn variant_index_with_id(&self, vid: DefId) -> VariantIdx {
2466 .find(|(_, v)| v.def_id == vid)
2467 .expect("variant_index_with_id: unknown variant")
2471 /// Return the index of `VariantDef` given a constructor id.
2472 pub fn variant_index_with_ctor_id(&self, cid: DefId) -> VariantIdx {
2475 .find(|(_, v)| v.ctor_def_id == Some(cid))
2476 .expect("variant_index_with_ctor_id: unknown variant")
2480 pub fn variant_of_res(&self, res: Res) -> &VariantDef {
2482 Res::Def(DefKind::Variant, vid) => self.variant_with_id(vid),
2483 Res::Def(DefKind::Ctor(..), cid) => self.variant_with_ctor_id(cid),
2484 Res::Def(DefKind::Struct, _)
2485 | Res::Def(DefKind::Union, _)
2486 | Res::Def(DefKind::TyAlias, _)
2487 | Res::Def(DefKind::AssocTy, _)
2489 | Res::SelfCtor(..) => self.non_enum_variant(),
2490 _ => bug!("unexpected res {:?} in variant_of_res", res),
2495 pub fn eval_explicit_discr(&self, tcx: TyCtxt<'tcx>, expr_did: DefId) -> Option<Discr<'tcx>> {
2496 assert!(self.is_enum());
2497 let param_env = tcx.param_env(expr_did);
2498 let repr_type = self.repr.discr_type();
2499 match tcx.const_eval_poly(expr_did) {
2501 let ty = repr_type.to_ty(tcx);
2502 if let Some(b) = val.try_to_bits_for_ty(tcx, param_env, ty) {
2503 trace!("discriminants: {} ({:?})", b, repr_type);
2504 Some(Discr { val: b, ty })
2506 info!("invalid enum discriminant: {:#?}", val);
2507 crate::mir::interpret::struct_error(
2508 tcx.at(tcx.def_span(expr_did)),
2509 "constant evaluation of enum discriminant resulted in non-integer",
2516 let msg = match err {
2517 ErrorHandled::Reported(ErrorReported) | ErrorHandled::Linted => {
2518 "enum discriminant evaluation failed"
2520 ErrorHandled::TooGeneric => "enum discriminant depends on generics",
2522 tcx.sess.delay_span_bug(tcx.def_span(expr_did), msg);
2529 pub fn discriminants(
2532 ) -> impl Iterator<Item = (VariantIdx, Discr<'tcx>)> + Captures<'tcx> {
2533 assert!(self.is_enum());
2534 let repr_type = self.repr.discr_type();
2535 let initial = repr_type.initial_discriminant(tcx);
2536 let mut prev_discr = None::<Discr<'tcx>>;
2537 self.variants.iter_enumerated().map(move |(i, v)| {
2538 let mut discr = prev_discr.map_or(initial, |d| d.wrap_incr(tcx));
2539 if let VariantDiscr::Explicit(expr_did) = v.discr {
2540 if let Some(new_discr) = self.eval_explicit_discr(tcx, expr_did) {
2544 prev_discr = Some(discr);
2551 pub fn variant_range(&self) -> Range<VariantIdx> {
2552 VariantIdx::new(0)..VariantIdx::new(self.variants.len())
2555 /// Computes the discriminant value used by a specific variant.
2556 /// Unlike `discriminants`, this is (amortized) constant-time,
2557 /// only doing at most one query for evaluating an explicit
2558 /// discriminant (the last one before the requested variant),
2559 /// assuming there are no constant-evaluation errors there.
2561 pub fn discriminant_for_variant(
2564 variant_index: VariantIdx,
2566 assert!(self.is_enum());
2567 let (val, offset) = self.discriminant_def_for_variant(variant_index);
2568 let explicit_value = val
2569 .and_then(|expr_did| self.eval_explicit_discr(tcx, expr_did))
2570 .unwrap_or_else(|| self.repr.discr_type().initial_discriminant(tcx));
2571 explicit_value.checked_add(tcx, offset as u128).0
2574 /// Yields a `DefId` for the discriminant and an offset to add to it
2575 /// Alternatively, if there is no explicit discriminant, returns the
2576 /// inferred discriminant directly.
2577 pub fn discriminant_def_for_variant(&self, variant_index: VariantIdx) -> (Option<DefId>, u32) {
2578 assert!(!self.variants.is_empty());
2579 let mut explicit_index = variant_index.as_u32();
2582 match self.variants[VariantIdx::from_u32(explicit_index)].discr {
2583 ty::VariantDiscr::Relative(0) => {
2587 ty::VariantDiscr::Relative(distance) => {
2588 explicit_index -= distance;
2590 ty::VariantDiscr::Explicit(did) => {
2591 expr_did = Some(did);
2596 (expr_did, variant_index.as_u32() - explicit_index)
2599 pub fn destructor(&self, tcx: TyCtxt<'tcx>) -> Option<Destructor> {
2600 tcx.adt_destructor(self.did)
2603 /// Returns a list of types such that `Self: Sized` if and only
2604 /// if that type is `Sized`, or `TyErr` if this type is recursive.
2606 /// Oddly enough, checking that the sized-constraint is `Sized` is
2607 /// actually more expressive than checking all members:
2608 /// the `Sized` trait is inductive, so an associated type that references
2609 /// `Self` would prevent its containing ADT from being `Sized`.
2611 /// Due to normalization being eager, this applies even if
2612 /// the associated type is behind a pointer (e.g., issue #31299).
2613 pub fn sized_constraint(&self, tcx: TyCtxt<'tcx>) -> &'tcx [Ty<'tcx>] {
2614 tcx.adt_sized_constraint(self.did).0
2618 impl<'tcx> FieldDef {
2619 /// Returns the type of this field. The `subst` is typically obtained
2620 /// via the second field of `TyKind::AdtDef`.
2621 pub fn ty(&self, tcx: TyCtxt<'tcx>, subst: SubstsRef<'tcx>) -> Ty<'tcx> {
2622 tcx.type_of(self.did).subst(tcx, subst)
2626 /// Represents the various closure traits in the language. This
2627 /// will determine the type of the environment (`self`, in the
2628 /// desugaring) argument that the closure expects.
2630 /// You can get the environment type of a closure using
2631 /// `tcx.closure_env_ty()`.
2632 #[derive(Clone, Copy, PartialOrd, Ord, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
2633 #[derive(HashStable)]
2634 pub enum ClosureKind {
2635 // Warning: Ordering is significant here! The ordering is chosen
2636 // because the trait Fn is a subtrait of FnMut and so in turn, and
2637 // hence we order it so that Fn < FnMut < FnOnce.
2643 impl<'tcx> ClosureKind {
2644 // This is the initial value used when doing upvar inference.
2645 pub const LATTICE_BOTTOM: ClosureKind = ClosureKind::Fn;
2647 pub fn trait_did(&self, tcx: TyCtxt<'tcx>) -> DefId {
2649 ClosureKind::Fn => tcx.require_lang_item(FnTraitLangItem, None),
2650 ClosureKind::FnMut => tcx.require_lang_item(FnMutTraitLangItem, None),
2651 ClosureKind::FnOnce => tcx.require_lang_item(FnOnceTraitLangItem, None),
2655 /// Returns `true` if this a type that impls this closure kind
2656 /// must also implement `other`.
2657 pub fn extends(self, other: ty::ClosureKind) -> bool {
2658 match (self, other) {
2659 (ClosureKind::Fn, ClosureKind::Fn) => true,
2660 (ClosureKind::Fn, ClosureKind::FnMut) => true,
2661 (ClosureKind::Fn, ClosureKind::FnOnce) => true,
2662 (ClosureKind::FnMut, ClosureKind::FnMut) => true,
2663 (ClosureKind::FnMut, ClosureKind::FnOnce) => true,
2664 (ClosureKind::FnOnce, ClosureKind::FnOnce) => true,
2669 /// Returns the representative scalar type for this closure kind.
2670 /// See `TyS::to_opt_closure_kind` for more details.
2671 pub fn to_ty(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
2673 ty::ClosureKind::Fn => tcx.types.i8,
2674 ty::ClosureKind::FnMut => tcx.types.i16,
2675 ty::ClosureKind::FnOnce => tcx.types.i32,
2681 pub fn from_mutbl(m: hir::Mutability) -> BorrowKind {
2683 hir::Mutability::Mut => MutBorrow,
2684 hir::Mutability::Not => ImmBorrow,
2688 /// Returns a mutability `m` such that an `&m T` pointer could be used to obtain this borrow
2689 /// kind. Because borrow kinds are richer than mutabilities, we sometimes have to pick a
2690 /// mutability that is stronger than necessary so that it at least *would permit* the borrow in
2692 pub fn to_mutbl_lossy(self) -> hir::Mutability {
2694 MutBorrow => hir::Mutability::Mut,
2695 ImmBorrow => hir::Mutability::Not,
2697 // We have no type corresponding to a unique imm borrow, so
2698 // use `&mut`. It gives all the capabilities of an `&uniq`
2699 // and hence is a safe "over approximation".
2700 UniqueImmBorrow => hir::Mutability::Mut,
2704 pub fn to_user_str(&self) -> &'static str {
2706 MutBorrow => "mutable",
2707 ImmBorrow => "immutable",
2708 UniqueImmBorrow => "uniquely immutable",
2713 pub type Attributes<'tcx> = &'tcx [ast::Attribute];
2715 #[derive(Debug, PartialEq, Eq)]
2716 pub enum ImplOverlapKind {
2717 /// These impls are always allowed to overlap.
2719 /// Whether or not the impl is permitted due to the trait being a `#[marker]` trait
2722 /// These impls are allowed to overlap, but that raises
2723 /// an issue #33140 future-compatibility warning.
2725 /// Some background: in Rust 1.0, the trait-object types `Send + Sync` (today's
2726 /// `dyn Send + Sync`) and `Sync + Send` (now `dyn Sync + Send`) were different.
2728 /// The widely-used version 0.1.0 of the crate `traitobject` had accidentally relied
2729 /// that difference, making what reduces to the following set of impls:
2733 /// impl Trait for dyn Send + Sync {}
2734 /// impl Trait for dyn Sync + Send {}
2737 /// Obviously, once we made these types be identical, that code causes a coherence
2738 /// error and a fairly big headache for us. However, luckily for us, the trait
2739 /// `Trait` used in this case is basically a marker trait, and therefore having
2740 /// overlapping impls for it is sound.
2742 /// To handle this, we basically regard the trait as a marker trait, with an additional
2743 /// future-compatibility warning. To avoid accidentally "stabilizing" this feature,
2744 /// it has the following restrictions:
2746 /// 1. The trait must indeed be a marker-like trait (i.e., no items), and must be
2748 /// 2. The trait-ref of both impls must be equal.
2749 /// 3. The trait-ref of both impls must be a trait object type consisting only of
2751 /// 4. Neither of the impls can have any where-clauses.
2753 /// Once `traitobject` 0.1.0 is no longer an active concern, this hack can be removed.
2757 impl<'tcx> TyCtxt<'tcx> {
2758 pub fn body_tables(self, body: hir::BodyId) -> &'tcx TypeckTables<'tcx> {
2759 self.typeck_tables_of(self.hir().body_owner_def_id(body))
2762 /// Returns an iterator of the `DefId`s for all body-owners in this
2763 /// crate. If you would prefer to iterate over the bodies
2764 /// themselves, you can do `self.hir().krate().body_ids.iter()`.
2765 pub fn body_owners(self) -> impl Iterator<Item = LocalDefId> + Captures<'tcx> + 'tcx {
2770 .map(move |&body_id| self.hir().body_owner_def_id(body_id))
2773 pub fn par_body_owners<F: Fn(LocalDefId) + sync::Sync + sync::Send>(self, f: F) {
2774 par_iter(&self.hir().krate().body_ids)
2775 .for_each(|&body_id| f(self.hir().body_owner_def_id(body_id)));
2778 pub fn provided_trait_methods(self, id: DefId) -> impl 'tcx + Iterator<Item = &'tcx AssocItem> {
2779 self.associated_items(id)
2780 .in_definition_order()
2781 .filter(|item| item.kind == AssocKind::Fn && item.defaultness.has_value())
2784 pub fn opt_item_name(self, def_id: DefId) -> Option<Ident> {
2787 .and_then(|def_id| self.hir().get(self.hir().as_local_hir_id(def_id)).ident())
2790 pub fn opt_associated_item(self, def_id: DefId) -> Option<&'tcx AssocItem> {
2791 let is_associated_item = if let Some(def_id) = def_id.as_local() {
2792 match self.hir().get(self.hir().as_local_hir_id(def_id)) {
2793 Node::TraitItem(_) | Node::ImplItem(_) => true,
2797 match self.def_kind(def_id) {
2798 DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy => true,
2803 is_associated_item.then(|| self.associated_item(def_id))
2806 pub fn field_index(self, hir_id: hir::HirId, tables: &TypeckTables<'_>) -> usize {
2807 tables.field_indices().get(hir_id).cloned().expect("no index for a field")
2810 pub fn find_field_index(self, ident: Ident, variant: &VariantDef) -> Option<usize> {
2811 variant.fields.iter().position(|field| self.hygienic_eq(ident, field.ident, variant.def_id))
2814 /// Returns `true` if the impls are the same polarity and the trait either
2815 /// has no items or is annotated `#[marker]` and prevents item overrides.
2816 pub fn impls_are_allowed_to_overlap(
2820 ) -> Option<ImplOverlapKind> {
2821 // If either trait impl references an error, they're allowed to overlap,
2822 // as one of them essentially doesn't exist.
2823 if self.impl_trait_ref(def_id1).map_or(false, |tr| tr.references_error())
2824 || self.impl_trait_ref(def_id2).map_or(false, |tr| tr.references_error())
2826 return Some(ImplOverlapKind::Permitted { marker: false });
2829 match (self.impl_polarity(def_id1), self.impl_polarity(def_id2)) {
2830 (ImplPolarity::Reservation, _) | (_, ImplPolarity::Reservation) => {
2831 // `#[rustc_reservation_impl]` impls don't overlap with anything
2833 "impls_are_allowed_to_overlap({:?}, {:?}) = Some(Permitted) (reservations)",
2836 return Some(ImplOverlapKind::Permitted { marker: false });
2838 (ImplPolarity::Positive, ImplPolarity::Negative)
2839 | (ImplPolarity::Negative, ImplPolarity::Positive) => {
2840 // `impl AutoTrait for Type` + `impl !AutoTrait for Type`
2842 "impls_are_allowed_to_overlap({:?}, {:?}) - None (differing polarities)",
2847 (ImplPolarity::Positive, ImplPolarity::Positive)
2848 | (ImplPolarity::Negative, ImplPolarity::Negative) => {}
2851 let is_marker_overlap = {
2852 let is_marker_impl = |def_id: DefId| -> bool {
2853 let trait_ref = self.impl_trait_ref(def_id);
2854 trait_ref.map_or(false, |tr| self.trait_def(tr.def_id).is_marker)
2856 is_marker_impl(def_id1) && is_marker_impl(def_id2)
2859 if is_marker_overlap {
2861 "impls_are_allowed_to_overlap({:?}, {:?}) = Some(Permitted) (marker overlap)",
2864 Some(ImplOverlapKind::Permitted { marker: true })
2866 if let Some(self_ty1) = self.issue33140_self_ty(def_id1) {
2867 if let Some(self_ty2) = self.issue33140_self_ty(def_id2) {
2868 if self_ty1 == self_ty2 {
2870 "impls_are_allowed_to_overlap({:?}, {:?}) - issue #33140 HACK",
2873 return Some(ImplOverlapKind::Issue33140);
2876 "impls_are_allowed_to_overlap({:?}, {:?}) - found {:?} != {:?}",
2877 def_id1, def_id2, self_ty1, self_ty2
2883 debug!("impls_are_allowed_to_overlap({:?}, {:?}) = None", def_id1, def_id2);
2888 /// Returns `ty::VariantDef` if `res` refers to a struct,
2889 /// or variant or their constructors, panics otherwise.
2890 pub fn expect_variant_res(self, res: Res) -> &'tcx VariantDef {
2892 Res::Def(DefKind::Variant, did) => {
2893 let enum_did = self.parent(did).unwrap();
2894 self.adt_def(enum_did).variant_with_id(did)
2896 Res::Def(DefKind::Struct | DefKind::Union, did) => self.adt_def(did).non_enum_variant(),
2897 Res::Def(DefKind::Ctor(CtorOf::Variant, ..), variant_ctor_did) => {
2898 let variant_did = self.parent(variant_ctor_did).unwrap();
2899 let enum_did = self.parent(variant_did).unwrap();
2900 self.adt_def(enum_did).variant_with_ctor_id(variant_ctor_did)
2902 Res::Def(DefKind::Ctor(CtorOf::Struct, ..), ctor_did) => {
2903 let struct_did = self.parent(ctor_did).expect("struct ctor has no parent");
2904 self.adt_def(struct_did).non_enum_variant()
2906 _ => bug!("expect_variant_res used with unexpected res {:?}", res),
2910 pub fn item_name(self, id: DefId) -> Symbol {
2911 if id.index == CRATE_DEF_INDEX {
2912 self.original_crate_name(id.krate)
2914 let def_key = self.def_key(id);
2915 match def_key.disambiguated_data.data {
2916 // The name of a constructor is that of its parent.
2917 rustc_hir::definitions::DefPathData::Ctor => {
2918 self.item_name(DefId { krate: id.krate, index: def_key.parent.unwrap() })
2920 _ => def_key.disambiguated_data.data.get_opt_name().unwrap_or_else(|| {
2921 bug!("item_name: no name for {:?}", self.def_path(id));
2927 /// Returns the possibly-auto-generated MIR of a `(DefId, Subst)` pair.
2928 pub fn instance_mir(self, instance: ty::InstanceDef<'tcx>) -> &'tcx Body<'tcx> {
2930 ty::InstanceDef::Item(def) => {
2931 if let Some((did, param_did)) = def.as_const_arg() {
2932 self.optimized_mir_of_const_arg((did, param_did))
2934 self.optimized_mir(def.did)
2937 ty::InstanceDef::VtableShim(..)
2938 | ty::InstanceDef::ReifyShim(..)
2939 | ty::InstanceDef::Intrinsic(..)
2940 | ty::InstanceDef::FnPtrShim(..)
2941 | ty::InstanceDef::Virtual(..)
2942 | ty::InstanceDef::ClosureOnceShim { .. }
2943 | ty::InstanceDef::DropGlue(..)
2944 | ty::InstanceDef::CloneShim(..) => self.mir_shims(instance),
2948 /// Gets the attributes of a definition.
2949 pub fn get_attrs(self, did: DefId) -> Attributes<'tcx> {
2950 if let Some(did) = did.as_local() {
2951 self.hir().attrs(self.hir().as_local_hir_id(did))
2953 self.item_attrs(did)
2957 /// Determines whether an item is annotated with an attribute.
2958 pub fn has_attr(self, did: DefId, attr: Symbol) -> bool {
2959 attr::contains_name(&self.get_attrs(did), attr)
2962 /// Returns `true` if this is an `auto trait`.
2963 pub fn trait_is_auto(self, trait_def_id: DefId) -> bool {
2964 self.trait_def(trait_def_id).has_auto_impl
2967 pub fn generator_layout(self, def_id: DefId) -> &'tcx GeneratorLayout<'tcx> {
2968 self.optimized_mir(def_id).generator_layout.as_ref().unwrap()
2971 /// Given the `DefId` of an impl, returns the `DefId` of the trait it implements.
2972 /// If it implements no trait, returns `None`.
2973 pub fn trait_id_of_impl(self, def_id: DefId) -> Option<DefId> {
2974 self.impl_trait_ref(def_id).map(|tr| tr.def_id)
2977 /// If the given defid describes a method belonging to an impl, returns the
2978 /// `DefId` of the impl that the method belongs to; otherwise, returns `None`.
2979 pub fn impl_of_method(self, def_id: DefId) -> Option<DefId> {
2980 self.opt_associated_item(def_id).and_then(|trait_item| match trait_item.container {
2981 TraitContainer(_) => None,
2982 ImplContainer(def_id) => Some(def_id),
2986 /// Looks up the span of `impl_did` if the impl is local; otherwise returns `Err`
2987 /// with the name of the crate containing the impl.
2988 pub fn span_of_impl(self, impl_did: DefId) -> Result<Span, Symbol> {
2989 if let Some(impl_did) = impl_did.as_local() {
2990 let hir_id = self.hir().as_local_hir_id(impl_did);
2991 Ok(self.hir().span(hir_id))
2993 Err(self.crate_name(impl_did.krate))
2997 /// Hygienically compares a use-site name (`use_name`) for a field or an associated item with
2998 /// its supposed definition name (`def_name`). The method also needs `DefId` of the supposed
2999 /// definition's parent/scope to perform comparison.
3000 pub fn hygienic_eq(self, use_name: Ident, def_name: Ident, def_parent_def_id: DefId) -> bool {
3001 // We could use `Ident::eq` here, but we deliberately don't. The name
3002 // comparison fails frequently, and we want to avoid the expensive
3003 // `normalize_to_macros_2_0()` calls required for the span comparison whenever possible.
3004 use_name.name == def_name.name
3008 .hygienic_eq(def_name.span.ctxt(), self.expansion_that_defined(def_parent_def_id))
3011 fn expansion_that_defined(self, scope: DefId) -> ExpnId {
3012 match scope.as_local() {
3013 Some(scope) => self.hir().definitions().expansion_that_defined(scope),
3014 None => ExpnId::root(),
3018 pub fn adjust_ident(self, mut ident: Ident, scope: DefId) -> Ident {
3019 ident.span.normalize_to_macros_2_0_and_adjust(self.expansion_that_defined(scope));
3023 pub fn adjust_ident_and_get_scope(
3028 ) -> (Ident, DefId) {
3030 match ident.span.normalize_to_macros_2_0_and_adjust(self.expansion_that_defined(scope))
3032 Some(actual_expansion) => {
3033 self.hir().definitions().parent_module_of_macro_def(actual_expansion)
3035 None => self.parent_module(block).to_def_id(),
3040 pub fn is_object_safe(self, key: DefId) -> bool {
3041 self.object_safety_violations(key).is_empty()
3045 #[derive(Clone, HashStable)]
3046 pub struct AdtSizedConstraint<'tcx>(pub &'tcx [Ty<'tcx>]);
3048 /// Yields the parent function's `DefId` if `def_id` is an `impl Trait` definition.
3049 pub fn is_impl_trait_defn(tcx: TyCtxt<'_>, def_id: DefId) -> Option<DefId> {
3050 if let Some(def_id) = def_id.as_local() {
3051 if let Node::Item(item) = tcx.hir().get(tcx.hir().as_local_hir_id(def_id)) {
3052 if let hir::ItemKind::OpaqueTy(ref opaque_ty) = item.kind {
3053 return opaque_ty.impl_trait_fn;
3060 pub fn provide(providers: &mut ty::query::Providers) {
3061 context::provide(providers);
3062 erase_regions::provide(providers);
3063 layout::provide(providers);
3064 super::util::bug::provide(providers);
3065 *providers = ty::query::Providers {
3066 trait_impls_of: trait_def::trait_impls_of_provider,
3067 all_local_trait_impls: trait_def::all_local_trait_impls,
3072 /// A map for the local crate mapping each type to a vector of its
3073 /// inherent impls. This is not meant to be used outside of coherence;
3074 /// rather, you should request the vector for a specific type via
3075 /// `tcx.inherent_impls(def_id)` so as to minimize your dependencies
3076 /// (constructing this map requires touching the entire crate).
3077 #[derive(Clone, Debug, Default, HashStable)]
3078 pub struct CrateInherentImpls {
3079 pub inherent_impls: DefIdMap<Vec<DefId>>,
3082 #[derive(Clone, Copy, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
3083 pub struct SymbolName {
3084 // FIXME: we don't rely on interning or equality here - better have
3085 // this be a `&'tcx str`.
3090 pub fn new(name: &str) -> SymbolName {
3091 SymbolName { name: Symbol::intern(name) }
3095 impl PartialOrd for SymbolName {
3096 fn partial_cmp(&self, other: &SymbolName) -> Option<Ordering> {
3097 self.name.as_str().partial_cmp(&other.name.as_str())
3101 /// Ordering must use the chars to ensure reproducible builds.
3102 impl Ord for SymbolName {
3103 fn cmp(&self, other: &SymbolName) -> Ordering {
3104 self.name.as_str().cmp(&other.name.as_str())
3108 impl fmt::Display for SymbolName {
3109 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
3110 fmt::Display::fmt(&self.name, fmt)
3114 impl fmt::Debug for SymbolName {
3115 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
3116 fmt::Display::fmt(&self.name, fmt)