1 // ignore-tidy-filelength
2 pub use self::fold::{TypeFoldable, TypeFolder, 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::hir::place::Place as HirPlace;
10 use crate::ich::StableHashingContext;
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_data_structures::tagged_ptr::CopyTaggedPtr;
31 use rustc_errors::ErrorReported;
33 use rustc_hir::def::{CtorKind, CtorOf, DefKind, Namespace, Res};
34 use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, LocalDefId, CRATE_DEF_INDEX};
35 use rustc_hir::lang_items::LangItem;
36 use rustc_hir::{Constness, Node};
37 use rustc_index::vec::{Idx, IndexVec};
38 use rustc_macros::HashStable;
39 use rustc_serialize::{self, Encodable, Encoder};
40 use rustc_session::DataTypeKind;
41 use rustc_span::hygiene::ExpnId;
42 use rustc_span::symbol::{kw, sym, Ident, Symbol};
44 use rustc_target::abi::{Align, VariantIdx};
46 use std::cell::RefCell;
47 use std::cmp::Ordering;
49 use std::hash::{Hash, Hasher};
50 use std::ops::{ControlFlow, Range};
54 pub use self::sty::BoundRegion::*;
55 pub use self::sty::InferTy::*;
56 pub use self::sty::RegionKind;
57 pub use self::sty::RegionKind::*;
58 pub use self::sty::TyKind::*;
59 pub use self::sty::{Binder, BoundTy, BoundTyKind, BoundVar, DebruijnIndex, INNERMOST};
60 pub use self::sty::{BoundRegion, EarlyBoundRegion, FreeRegion, Region};
61 pub use self::sty::{CanonicalPolyFnSig, FnSig, GenSig, PolyFnSig, PolyGenSig};
62 pub use self::sty::{ClosureSubsts, GeneratorSubsts, TypeAndMut, UpvarSubsts};
63 pub use self::sty::{ClosureSubstsParts, GeneratorSubstsParts};
64 pub use self::sty::{ConstVid, FloatVid, IntVid, RegionVid, TyVid};
65 pub use self::sty::{ExistentialPredicate, InferTy, ParamConst, ParamTy, ProjectionTy};
66 pub use self::sty::{ExistentialProjection, PolyExistentialProjection};
67 pub use self::sty::{ExistentialTraitRef, PolyExistentialTraitRef};
68 pub use self::sty::{PolyTraitRef, TraitRef, TyKind};
69 pub use crate::ty::diagnostics::*;
71 pub use self::binding::BindingMode;
72 pub use self::binding::BindingMode::*;
74 pub use self::context::{tls, FreeRegionInfo, TyCtxt};
75 pub use self::context::{
76 CanonicalUserType, CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations,
77 DelaySpanBugEmitted, ResolvedOpaqueTy, UserType, UserTypeAnnotationIndex,
79 pub use self::context::{
80 CtxtInterners, GeneratorInteriorTypeCause, GlobalCtxt, Lift, TypeckResults,
83 pub use self::instance::{Instance, InstanceDef};
85 pub use self::list::List;
87 pub use self::trait_def::TraitDef;
89 pub use self::query::queries;
91 pub use self::consts::{Const, ConstInt, ConstKind, InferConst, ScalarInt};
103 pub mod inhabitedness;
105 pub mod normalize_erasing_regions;
121 mod structural_impls;
126 pub struct ResolverOutputs {
127 pub definitions: rustc_hir::definitions::Definitions,
128 pub cstore: Box<CrateStoreDyn>,
129 pub visibilities: FxHashMap<LocalDefId, Visibility>,
130 pub extern_crate_map: FxHashMap<LocalDefId, CrateNum>,
131 pub maybe_unused_trait_imports: FxHashSet<LocalDefId>,
132 pub maybe_unused_extern_crates: Vec<(LocalDefId, Span)>,
133 pub export_map: ExportMap<LocalDefId>,
134 pub glob_map: FxHashMap<LocalDefId, FxHashSet<Symbol>>,
135 /// Extern prelude entries. The value is `true` if the entry was introduced
136 /// via `extern crate` item and not `--extern` option or compiler built-in.
137 pub extern_prelude: FxHashMap<Symbol, bool>,
140 #[derive(Clone, Copy, PartialEq, Eq, Debug, HashStable, Hash)]
141 pub enum AssocItemContainer {
142 TraitContainer(DefId),
143 ImplContainer(DefId),
146 impl AssocItemContainer {
147 /// Asserts that this is the `DefId` of an associated item declared
148 /// in a trait, and returns the trait `DefId`.
149 pub fn assert_trait(&self) -> DefId {
151 TraitContainer(id) => id,
152 _ => bug!("associated item has wrong container type: {:?}", self),
156 pub fn id(&self) -> DefId {
158 TraitContainer(id) => id,
159 ImplContainer(id) => id,
164 /// The "header" of an impl is everything outside the body: a Self type, a trait
165 /// ref (in the case of a trait impl), and a set of predicates (from the
166 /// bounds / where-clauses).
167 #[derive(Clone, Debug, TypeFoldable)]
168 pub struct ImplHeader<'tcx> {
169 pub impl_def_id: DefId,
170 pub self_ty: Ty<'tcx>,
171 pub trait_ref: Option<TraitRef<'tcx>>,
172 pub predicates: Vec<Predicate<'tcx>>,
175 #[derive(Copy, Clone, PartialEq, TyEncodable, TyDecodable, HashStable)]
176 pub enum ImplPolarity {
177 /// `impl Trait for Type`
179 /// `impl !Trait for Type`
181 /// `#[rustc_reservation_impl] impl Trait for Type`
183 /// This is a "stability hack", not a real Rust feature.
184 /// See #64631 for details.
188 #[derive(Copy, Clone, Debug, PartialEq, HashStable, Eq, Hash)]
189 pub struct AssocItem {
191 #[stable_hasher(project(name))]
195 pub defaultness: hir::Defaultness,
196 pub container: AssocItemContainer,
198 /// Whether this is a method with an explicit self
199 /// as its first parameter, allowing method calls.
200 pub fn_has_self_parameter: bool,
203 #[derive(Copy, Clone, PartialEq, Debug, HashStable, Eq, Hash)]
211 pub fn namespace(&self) -> Namespace {
213 ty::AssocKind::Type => Namespace::TypeNS,
214 ty::AssocKind::Const | ty::AssocKind::Fn => Namespace::ValueNS,
218 pub fn as_def_kind(&self) -> DefKind {
220 AssocKind::Const => DefKind::AssocConst,
221 AssocKind::Fn => DefKind::AssocFn,
222 AssocKind::Type => DefKind::AssocTy,
228 pub fn signature(&self, tcx: TyCtxt<'_>) -> String {
230 ty::AssocKind::Fn => {
231 // We skip the binder here because the binder would deanonymize all
232 // late-bound regions, and we don't want method signatures to show up
233 // `as for<'r> fn(&'r MyType)`. Pretty-printing handles late-bound
234 // regions just fine, showing `fn(&MyType)`.
235 tcx.fn_sig(self.def_id).skip_binder().to_string()
237 ty::AssocKind::Type => format!("type {};", self.ident),
238 ty::AssocKind::Const => {
239 format!("const {}: {:?};", self.ident, tcx.type_of(self.def_id))
245 /// A list of `ty::AssocItem`s in definition order that allows for efficient lookup by name.
247 /// When doing lookup by name, we try to postpone hygienic comparison for as long as possible since
248 /// it is relatively expensive. Instead, items are indexed by `Symbol` and hygienic comparison is
249 /// done only on items with the same name.
250 #[derive(Debug, Clone, PartialEq, HashStable)]
251 pub struct AssociatedItems<'tcx> {
252 items: SortedIndexMultiMap<u32, Symbol, &'tcx ty::AssocItem>,
255 impl<'tcx> AssociatedItems<'tcx> {
256 /// Constructs an `AssociatedItems` map from a series of `ty::AssocItem`s in definition order.
257 pub fn new(items_in_def_order: impl IntoIterator<Item = &'tcx ty::AssocItem>) -> Self {
258 let items = items_in_def_order.into_iter().map(|item| (item.ident.name, item)).collect();
259 AssociatedItems { items }
262 /// Returns a slice of associated items in the order they were defined.
264 /// New code should avoid relying on definition order. If you need a particular associated item
265 /// for a known trait, make that trait a lang item instead of indexing this array.
266 pub fn in_definition_order(&self) -> impl '_ + Iterator<Item = &ty::AssocItem> {
267 self.items.iter().map(|(_, v)| *v)
270 pub fn len(&self) -> usize {
274 /// Returns an iterator over all associated items with the given name, ignoring hygiene.
275 pub fn filter_by_name_unhygienic(
278 ) -> impl '_ + Iterator<Item = &ty::AssocItem> {
279 self.items.get_by_key(&name).copied()
282 /// Returns an iterator over all associated items with the given name.
284 /// Multiple items may have the same name if they are in different `Namespace`s. For example,
285 /// an associated type can have the same name as a method. Use one of the `find_by_name_and_*`
286 /// methods below if you know which item you are looking for.
287 pub fn filter_by_name(
291 parent_def_id: DefId,
292 ) -> impl 'a + Iterator<Item = &'a ty::AssocItem> {
293 self.filter_by_name_unhygienic(ident.name)
294 .filter(move |item| tcx.hygienic_eq(ident, item.ident, parent_def_id))
297 /// Returns the associated item with the given name and `AssocKind`, if one exists.
298 pub fn find_by_name_and_kind(
303 parent_def_id: DefId,
304 ) -> Option<&ty::AssocItem> {
305 self.filter_by_name_unhygienic(ident.name)
306 .filter(|item| item.kind == kind)
307 .find(|item| tcx.hygienic_eq(ident, item.ident, parent_def_id))
310 /// Returns the associated item with the given name in the given `Namespace`, if one exists.
311 pub fn find_by_name_and_namespace(
316 parent_def_id: DefId,
317 ) -> Option<&ty::AssocItem> {
318 self.filter_by_name_unhygienic(ident.name)
319 .filter(|item| item.kind.namespace() == ns)
320 .find(|item| tcx.hygienic_eq(ident, item.ident, parent_def_id))
324 #[derive(Clone, Debug, PartialEq, Eq, Copy, Hash, TyEncodable, TyDecodable, HashStable)]
325 pub enum Visibility {
326 /// Visible everywhere (including in other crates).
328 /// Visible only in the given crate-local module.
330 /// Not visible anywhere in the local crate. This is the visibility of private external items.
334 pub trait DefIdTree: Copy {
335 fn parent(self, id: DefId) -> Option<DefId>;
337 fn is_descendant_of(self, mut descendant: DefId, ancestor: DefId) -> bool {
338 if descendant.krate != ancestor.krate {
342 while descendant != ancestor {
343 match self.parent(descendant) {
344 Some(parent) => descendant = parent,
345 None => return false,
352 impl<'tcx> DefIdTree for TyCtxt<'tcx> {
353 fn parent(self, id: DefId) -> Option<DefId> {
354 self.def_key(id).parent.map(|index| DefId { index, ..id })
359 pub fn from_hir(visibility: &hir::Visibility<'_>, id: hir::HirId, tcx: TyCtxt<'_>) -> Self {
360 match visibility.node {
361 hir::VisibilityKind::Public => Visibility::Public,
362 hir::VisibilityKind::Crate(_) => Visibility::Restricted(DefId::local(CRATE_DEF_INDEX)),
363 hir::VisibilityKind::Restricted { ref path, .. } => match path.res {
364 // If there is no resolution, `resolve` will have already reported an error, so
365 // assume that the visibility is public to avoid reporting more privacy errors.
366 Res::Err => Visibility::Public,
367 def => Visibility::Restricted(def.def_id()),
369 hir::VisibilityKind::Inherited => {
370 Visibility::Restricted(tcx.parent_module(id).to_def_id())
375 /// Returns `true` if an item with this visibility is accessible from the given block.
376 pub fn is_accessible_from<T: DefIdTree>(self, module: DefId, tree: T) -> bool {
377 let restriction = match self {
378 // Public items are visible everywhere.
379 Visibility::Public => return true,
380 // Private items from other crates are visible nowhere.
381 Visibility::Invisible => return false,
382 // Restricted items are visible in an arbitrary local module.
383 Visibility::Restricted(other) if other.krate != module.krate => return false,
384 Visibility::Restricted(module) => module,
387 tree.is_descendant_of(module, restriction)
390 /// Returns `true` if this visibility is at least as accessible as the given visibility
391 pub fn is_at_least<T: DefIdTree>(self, vis: Visibility, tree: T) -> bool {
392 let vis_restriction = match vis {
393 Visibility::Public => return self == Visibility::Public,
394 Visibility::Invisible => return true,
395 Visibility::Restricted(module) => module,
398 self.is_accessible_from(vis_restriction, tree)
401 // Returns `true` if this item is visible anywhere in the local crate.
402 pub fn is_visible_locally(self) -> bool {
404 Visibility::Public => true,
405 Visibility::Restricted(def_id) => def_id.is_local(),
406 Visibility::Invisible => false,
411 #[derive(Copy, Clone, PartialEq, TyDecodable, TyEncodable, HashStable)]
413 Covariant, // T<A> <: T<B> iff A <: B -- e.g., function return type
414 Invariant, // T<A> <: T<B> iff B == A -- e.g., type of mutable cell
415 Contravariant, // T<A> <: T<B> iff B <: A -- e.g., function param type
416 Bivariant, // T<A> <: T<B> -- e.g., unused type parameter
419 /// The crate variances map is computed during typeck and contains the
420 /// variance of every item in the local crate. You should not use it
421 /// directly, because to do so will make your pass dependent on the
422 /// HIR of every item in the local crate. Instead, use
423 /// `tcx.variances_of()` to get the variance for a *particular*
425 #[derive(HashStable)]
426 pub struct CrateVariancesMap<'tcx> {
427 /// For each item with generics, maps to a vector of the variance
428 /// of its generics. If an item has no generics, it will have no
430 pub variances: FxHashMap<DefId, &'tcx [ty::Variance]>,
434 /// `a.xform(b)` combines the variance of a context with the
435 /// variance of a type with the following meaning. If we are in a
436 /// context with variance `a`, and we encounter a type argument in
437 /// a position with variance `b`, then `a.xform(b)` is the new
438 /// variance with which the argument appears.
444 /// Here, the "ambient" variance starts as covariant. `*mut T` is
445 /// invariant with respect to `T`, so the variance in which the
446 /// `Vec<i32>` appears is `Covariant.xform(Invariant)`, which
447 /// yields `Invariant`. Now, the type `Vec<T>` is covariant with
448 /// respect to its type argument `T`, and hence the variance of
449 /// the `i32` here is `Invariant.xform(Covariant)`, which results
450 /// (again) in `Invariant`.
454 /// fn(*const Vec<i32>, *mut Vec<i32)
456 /// The ambient variance is covariant. A `fn` type is
457 /// contravariant with respect to its parameters, so the variance
458 /// within which both pointer types appear is
459 /// `Covariant.xform(Contravariant)`, or `Contravariant`. `*const
460 /// T` is covariant with respect to `T`, so the variance within
461 /// which the first `Vec<i32>` appears is
462 /// `Contravariant.xform(Covariant)` or `Contravariant`. The same
463 /// is true for its `i32` argument. In the `*mut T` case, the
464 /// variance of `Vec<i32>` is `Contravariant.xform(Invariant)`,
465 /// and hence the outermost type is `Invariant` with respect to
466 /// `Vec<i32>` (and its `i32` argument).
468 /// Source: Figure 1 of "Taming the Wildcards:
469 /// Combining Definition- and Use-Site Variance" published in PLDI'11.
470 pub fn xform(self, v: ty::Variance) -> ty::Variance {
472 // Figure 1, column 1.
473 (ty::Covariant, ty::Covariant) => ty::Covariant,
474 (ty::Covariant, ty::Contravariant) => ty::Contravariant,
475 (ty::Covariant, ty::Invariant) => ty::Invariant,
476 (ty::Covariant, ty::Bivariant) => ty::Bivariant,
478 // Figure 1, column 2.
479 (ty::Contravariant, ty::Covariant) => ty::Contravariant,
480 (ty::Contravariant, ty::Contravariant) => ty::Covariant,
481 (ty::Contravariant, ty::Invariant) => ty::Invariant,
482 (ty::Contravariant, ty::Bivariant) => ty::Bivariant,
484 // Figure 1, column 3.
485 (ty::Invariant, _) => ty::Invariant,
487 // Figure 1, column 4.
488 (ty::Bivariant, _) => ty::Bivariant,
493 // Contains information needed to resolve types and (in the future) look up
494 // the types of AST nodes.
495 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
496 pub struct CReaderCacheKey {
502 /// Flags that we track on types. These flags are propagated upwards
503 /// through the type during type construction, so that we can quickly check
504 /// whether the type has various kinds of types in it without recursing
505 /// over the type itself.
506 pub struct TypeFlags: u32 {
507 // Does this have parameters? Used to determine whether substitution is
509 /// Does this have [Param]?
510 const HAS_TY_PARAM = 1 << 0;
511 /// Does this have [ReEarlyBound]?
512 const HAS_RE_PARAM = 1 << 1;
513 /// Does this have [ConstKind::Param]?
514 const HAS_CT_PARAM = 1 << 2;
516 const NEEDS_SUBST = TypeFlags::HAS_TY_PARAM.bits
517 | TypeFlags::HAS_RE_PARAM.bits
518 | TypeFlags::HAS_CT_PARAM.bits;
520 /// Does this have [Infer]?
521 const HAS_TY_INFER = 1 << 3;
522 /// Does this have [ReVar]?
523 const HAS_RE_INFER = 1 << 4;
524 /// Does this have [ConstKind::Infer]?
525 const HAS_CT_INFER = 1 << 5;
527 /// Does this have inference variables? Used to determine whether
528 /// inference is required.
529 const NEEDS_INFER = TypeFlags::HAS_TY_INFER.bits
530 | TypeFlags::HAS_RE_INFER.bits
531 | TypeFlags::HAS_CT_INFER.bits;
533 /// Does this have [Placeholder]?
534 const HAS_TY_PLACEHOLDER = 1 << 6;
535 /// Does this have [RePlaceholder]?
536 const HAS_RE_PLACEHOLDER = 1 << 7;
537 /// Does this have [ConstKind::Placeholder]?
538 const HAS_CT_PLACEHOLDER = 1 << 8;
540 /// `true` if there are "names" of regions and so forth
541 /// that are local to a particular fn/inferctxt
542 const HAS_FREE_LOCAL_REGIONS = 1 << 9;
544 /// `true` if there are "names" of types and regions and so forth
545 /// that are local to a particular fn
546 const HAS_FREE_LOCAL_NAMES = TypeFlags::HAS_TY_PARAM.bits
547 | TypeFlags::HAS_CT_PARAM.bits
548 | TypeFlags::HAS_TY_INFER.bits
549 | TypeFlags::HAS_CT_INFER.bits
550 | TypeFlags::HAS_TY_PLACEHOLDER.bits
551 | TypeFlags::HAS_CT_PLACEHOLDER.bits
552 | TypeFlags::HAS_FREE_LOCAL_REGIONS.bits;
554 /// Does this have [Projection]?
555 const HAS_TY_PROJECTION = 1 << 10;
556 /// Does this have [Opaque]?
557 const HAS_TY_OPAQUE = 1 << 11;
558 /// Does this have [ConstKind::Unevaluated]?
559 const HAS_CT_PROJECTION = 1 << 12;
561 /// Could this type be normalized further?
562 const HAS_PROJECTION = TypeFlags::HAS_TY_PROJECTION.bits
563 | TypeFlags::HAS_TY_OPAQUE.bits
564 | TypeFlags::HAS_CT_PROJECTION.bits;
566 /// Is an error type/const reachable?
567 const HAS_ERROR = 1 << 13;
569 /// Does this have any region that "appears free" in the type?
570 /// Basically anything but [ReLateBound] and [ReErased].
571 const HAS_FREE_REGIONS = 1 << 14;
573 /// Does this have any [ReLateBound] regions? Used to check
574 /// if a global bound is safe to evaluate.
575 const HAS_RE_LATE_BOUND = 1 << 15;
577 /// Does this have any [ReErased] regions?
578 const HAS_RE_ERASED = 1 << 16;
580 /// Does this value have parameters/placeholders/inference variables which could be
581 /// replaced later, in a way that would change the results of `impl` specialization?
582 const STILL_FURTHER_SPECIALIZABLE = 1 << 17;
586 #[allow(rustc::usage_of_ty_tykind)]
587 pub struct TyS<'tcx> {
588 /// This field shouldn't be used directly and may be removed in the future.
589 /// Use `TyS::kind()` instead.
591 /// This field shouldn't be used directly and may be removed in the future.
592 /// Use `TyS::flags()` instead.
595 /// This is a kind of confusing thing: it stores the smallest
598 /// (a) the binder itself captures nothing but
599 /// (b) all the late-bound things within the type are captured
600 /// by some sub-binder.
602 /// So, for a type without any late-bound things, like `u32`, this
603 /// will be *innermost*, because that is the innermost binder that
604 /// captures nothing. But for a type `&'D u32`, where `'D` is a
605 /// late-bound region with De Bruijn index `D`, this would be `D + 1`
606 /// -- the binder itself does not capture `D`, but `D` is captured
607 /// by an inner binder.
609 /// We call this concept an "exclusive" binder `D` because all
610 /// De Bruijn indices within the type are contained within `0..D`
612 outer_exclusive_binder: ty::DebruijnIndex,
615 // `TyS` is used a lot. Make sure it doesn't unintentionally get bigger.
616 #[cfg(target_arch = "x86_64")]
617 static_assert_size!(TyS<'_>, 32);
619 impl<'tcx> Ord for TyS<'tcx> {
620 fn cmp(&self, other: &TyS<'tcx>) -> Ordering {
621 self.kind().cmp(other.kind())
625 impl<'tcx> PartialOrd for TyS<'tcx> {
626 fn partial_cmp(&self, other: &TyS<'tcx>) -> Option<Ordering> {
627 Some(self.kind().cmp(other.kind()))
631 impl<'tcx> PartialEq for TyS<'tcx> {
633 fn eq(&self, other: &TyS<'tcx>) -> bool {
637 impl<'tcx> Eq for TyS<'tcx> {}
639 impl<'tcx> Hash for TyS<'tcx> {
640 fn hash<H: Hasher>(&self, s: &mut H) {
641 (self as *const TyS<'_>).hash(s)
645 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for TyS<'tcx> {
646 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
650 // The other fields just provide fast access to information that is
651 // also contained in `kind`, so no need to hash them.
654 outer_exclusive_binder: _,
657 kind.hash_stable(hcx, hasher);
661 #[rustc_diagnostic_item = "Ty"]
662 pub type Ty<'tcx> = &'tcx TyS<'tcx>;
664 #[derive(Clone, Copy, PartialEq, Eq, Hash, TyEncodable, TyDecodable, HashStable)]
665 pub struct UpvarPath {
666 pub hir_id: hir::HirId,
669 /// Upvars do not get their own `NodeId`. Instead, we use the pair of
670 /// the original var ID (that is, the root variable that is referenced
671 /// by the upvar) and the ID of the closure expression.
672 #[derive(Clone, Copy, PartialEq, Eq, Hash, TyEncodable, TyDecodable, HashStable)]
674 pub var_path: UpvarPath,
675 pub closure_expr_id: LocalDefId,
679 pub fn new(var_hir_id: hir::HirId, closure_def_id: LocalDefId) -> UpvarId {
680 UpvarId { var_path: UpvarPath { hir_id: var_hir_id }, closure_expr_id: closure_def_id }
684 #[derive(Clone, PartialEq, Debug, TyEncodable, TyDecodable, Copy, HashStable)]
685 pub enum BorrowKind {
686 /// Data must be immutable and is aliasable.
689 /// Data must be immutable but not aliasable. This kind of borrow
690 /// cannot currently be expressed by the user and is used only in
691 /// implicit closure bindings. It is needed when the closure
692 /// is borrowing or mutating a mutable referent, e.g.:
695 /// let x: &mut isize = ...;
696 /// let y = || *x += 5;
699 /// If we were to try to translate this closure into a more explicit
700 /// form, we'd encounter an error with the code as written:
703 /// struct Env { x: & &mut isize }
704 /// let x: &mut isize = ...;
705 /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
706 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
709 /// This is then illegal because you cannot mutate a `&mut` found
710 /// in an aliasable location. To solve, you'd have to translate with
711 /// an `&mut` borrow:
714 /// struct Env { x: & &mut isize }
715 /// let x: &mut isize = ...;
716 /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
717 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
720 /// Now the assignment to `**env.x` is legal, but creating a
721 /// mutable pointer to `x` is not because `x` is not mutable. We
722 /// could fix this by declaring `x` as `let mut x`. This is ok in
723 /// user code, if awkward, but extra weird for closures, since the
724 /// borrow is hidden.
726 /// So we introduce a "unique imm" borrow -- the referent is
727 /// immutable, but not aliasable. This solves the problem. For
728 /// simplicity, we don't give users the way to express this
729 /// borrow, it's just used when translating closures.
732 /// Data is mutable and not aliasable.
736 /// Information describing the capture of an upvar. This is computed
737 /// during `typeck`, specifically by `regionck`.
738 #[derive(PartialEq, Clone, Debug, Copy, TyEncodable, TyDecodable, HashStable)]
739 pub enum UpvarCapture<'tcx> {
740 /// Upvar is captured by value. This is always true when the
741 /// closure is labeled `move`, but can also be true in other cases
742 /// depending on inference.
744 /// If the upvar was inferred to be captured by value (e.g. `move`
745 /// was not used), then the `Span` points to a usage that
746 /// required it. There may be more than one such usage
747 /// (e.g. `|| { a; a; }`), in which case we pick an
749 ByValue(Option<Span>),
751 /// Upvar is captured by reference.
752 ByRef(UpvarBorrow<'tcx>),
755 #[derive(PartialEq, Clone, Copy, TyEncodable, TyDecodable, HashStable)]
756 pub struct UpvarBorrow<'tcx> {
757 /// The kind of borrow: by-ref upvars have access to shared
758 /// immutable borrows, which are not part of the normal language
760 pub kind: BorrowKind,
762 /// Region of the resulting reference.
763 pub region: ty::Region<'tcx>,
766 /// Given the closure DefId this map provides a map of root variables to minimum
767 /// set of `CapturedPlace`s that need to be tracked to support all captures of that closure.
768 pub type MinCaptureInformationMap<'tcx> = FxHashMap<DefId, RootVariableMinCaptureList<'tcx>>;
770 /// Part of `MinCaptureInformationMap`; Maps a root variable to the list of `CapturedPlace`.
771 /// Used to track the minimum set of `Place`s that need to be captured to support all
772 /// Places captured by the closure starting at a given root variable.
774 /// This provides a convenient and quick way of checking if a variable being used within
775 /// a closure is a capture of a local variable.
776 pub type RootVariableMinCaptureList<'tcx> = FxIndexMap<hir::HirId, MinCaptureList<'tcx>>;
778 /// Part of `MinCaptureInformationMap`; List of `CapturePlace`s.
779 pub type MinCaptureList<'tcx> = Vec<CapturedPlace<'tcx>>;
781 /// A `Place` and the corresponding `CaptureInfo`.
782 #[derive(PartialEq, Clone, Debug, TyEncodable, TyDecodable, HashStable)]
783 pub struct CapturedPlace<'tcx> {
784 pub place: HirPlace<'tcx>,
785 pub info: CaptureInfo<'tcx>,
788 /// Part of `MinCaptureInformationMap`; describes the capture kind (&, &mut, move)
789 /// for a particular capture as well as identifying the part of the source code
790 /// that triggered this capture to occur.
791 #[derive(PartialEq, Clone, Debug, Copy, TyEncodable, TyDecodable, HashStable)]
792 pub struct CaptureInfo<'tcx> {
793 /// Expr Id pointing to use that resulted in selecting the current capture kind
795 /// If the user doesn't enable feature `capture_disjoint_fields` (RFC 2229) then, it is
796 /// possible that we don't see the use of a particular place resulting in expr_id being
797 /// None. In such case we fallback on uvpars_mentioned for span.
808 /// In this example, if `capture_disjoint_fields` is **not** set, then x will be captured,
809 /// but we won't see it being used during capture analysis, since it's essentially a discard.
810 pub expr_id: Option<hir::HirId>,
812 /// Capture mode that was selected
813 pub capture_kind: UpvarCapture<'tcx>,
816 pub type UpvarListMap = FxHashMap<DefId, FxIndexMap<hir::HirId, UpvarId>>;
817 pub type UpvarCaptureMap<'tcx> = FxHashMap<UpvarId, UpvarCapture<'tcx>>;
819 #[derive(Clone, Copy, PartialEq, Eq)]
820 pub enum IntVarValue {
822 UintType(ast::UintTy),
825 #[derive(Clone, Copy, PartialEq, Eq)]
826 pub struct FloatVarValue(pub ast::FloatTy);
828 impl ty::EarlyBoundRegion {
829 /// Does this early bound region have a name? Early bound regions normally
830 /// always have names except when using anonymous lifetimes (`'_`).
831 pub fn has_name(&self) -> bool {
832 self.name != kw::UnderscoreLifetime
836 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable)]
837 pub enum GenericParamDefKind {
841 object_lifetime_default: ObjectLifetimeDefault,
842 synthetic: Option<hir::SyntheticTyParamKind>,
847 impl GenericParamDefKind {
848 pub fn descr(&self) -> &'static str {
850 GenericParamDefKind::Lifetime => "lifetime",
851 GenericParamDefKind::Type { .. } => "type",
852 GenericParamDefKind::Const => "constant",
857 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable)]
858 pub struct GenericParamDef {
863 /// `pure_wrt_drop`, set by the (unsafe) `#[may_dangle]` attribute
864 /// on generic parameter `'a`/`T`, asserts data behind the parameter
865 /// `'a`/`T` won't be accessed during the parent type's `Drop` impl.
866 pub pure_wrt_drop: bool,
868 pub kind: GenericParamDefKind,
871 impl GenericParamDef {
872 pub fn to_early_bound_region_data(&self) -> ty::EarlyBoundRegion {
873 if let GenericParamDefKind::Lifetime = self.kind {
874 ty::EarlyBoundRegion { def_id: self.def_id, index: self.index, name: self.name }
876 bug!("cannot convert a non-lifetime parameter def to an early bound region")
882 pub struct GenericParamCount {
883 pub lifetimes: usize,
888 /// Information about the formal type/lifetime parameters associated
889 /// with an item or method. Analogous to `hir::Generics`.
891 /// The ordering of parameters is the same as in `Subst` (excluding child generics):
892 /// `Self` (optionally), `Lifetime` params..., `Type` params...
893 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable)]
894 pub struct Generics {
895 pub parent: Option<DefId>,
896 pub parent_count: usize,
897 pub params: Vec<GenericParamDef>,
899 /// Reverse map to the `index` field of each `GenericParamDef`.
900 #[stable_hasher(ignore)]
901 pub param_def_id_to_index: FxHashMap<DefId, u32>,
904 pub has_late_bound_regions: Option<Span>,
907 impl<'tcx> Generics {
908 pub fn count(&self) -> usize {
909 self.parent_count + self.params.len()
912 pub fn own_counts(&self) -> GenericParamCount {
913 // We could cache this as a property of `GenericParamCount`, but
914 // the aim is to refactor this away entirely eventually and the
915 // presence of this method will be a constant reminder.
916 let mut own_counts: GenericParamCount = Default::default();
918 for param in &self.params {
920 GenericParamDefKind::Lifetime => own_counts.lifetimes += 1,
921 GenericParamDefKind::Type { .. } => own_counts.types += 1,
922 GenericParamDefKind::Const => own_counts.consts += 1,
929 pub fn requires_monomorphization(&self, tcx: TyCtxt<'tcx>) -> bool {
930 if self.own_requires_monomorphization() {
934 if let Some(parent_def_id) = self.parent {
935 let parent = tcx.generics_of(parent_def_id);
936 parent.requires_monomorphization(tcx)
942 pub fn own_requires_monomorphization(&self) -> bool {
943 for param in &self.params {
945 GenericParamDefKind::Type { .. } | GenericParamDefKind::Const => return true,
946 GenericParamDefKind::Lifetime => {}
952 /// Returns the `GenericParamDef` with the given index.
953 pub fn param_at(&'tcx self, param_index: usize, tcx: TyCtxt<'tcx>) -> &'tcx GenericParamDef {
954 if let Some(index) = param_index.checked_sub(self.parent_count) {
957 tcx.generics_of(self.parent.expect("parent_count > 0 but no parent?"))
958 .param_at(param_index, tcx)
962 /// Returns the `GenericParamDef` associated with this `EarlyBoundRegion`.
965 param: &EarlyBoundRegion,
967 ) -> &'tcx GenericParamDef {
968 let param = self.param_at(param.index as usize, tcx);
970 GenericParamDefKind::Lifetime => param,
971 _ => bug!("expected lifetime parameter, but found another generic parameter"),
975 /// Returns the `GenericParamDef` associated with this `ParamTy`.
976 pub fn type_param(&'tcx self, param: &ParamTy, tcx: TyCtxt<'tcx>) -> &'tcx GenericParamDef {
977 let param = self.param_at(param.index as usize, tcx);
979 GenericParamDefKind::Type { .. } => param,
980 _ => bug!("expected type parameter, but found another generic parameter"),
984 /// Returns the `GenericParamDef` associated with this `ParamConst`.
985 pub fn const_param(&'tcx self, param: &ParamConst, tcx: TyCtxt<'tcx>) -> &GenericParamDef {
986 let param = self.param_at(param.index as usize, tcx);
988 GenericParamDefKind::Const => param,
989 _ => bug!("expected const parameter, but found another generic parameter"),
994 /// Bounds on generics.
995 #[derive(Copy, Clone, Default, Debug, TyEncodable, TyDecodable, HashStable)]
996 pub struct GenericPredicates<'tcx> {
997 pub parent: Option<DefId>,
998 pub predicates: &'tcx [(Predicate<'tcx>, Span)],
1001 impl<'tcx> GenericPredicates<'tcx> {
1005 substs: SubstsRef<'tcx>,
1006 ) -> InstantiatedPredicates<'tcx> {
1007 let mut instantiated = InstantiatedPredicates::empty();
1008 self.instantiate_into(tcx, &mut instantiated, substs);
1012 pub fn instantiate_own(
1015 substs: SubstsRef<'tcx>,
1016 ) -> InstantiatedPredicates<'tcx> {
1017 InstantiatedPredicates {
1018 predicates: self.predicates.iter().map(|(p, _)| p.subst(tcx, substs)).collect(),
1019 spans: self.predicates.iter().map(|(_, sp)| *sp).collect(),
1023 fn instantiate_into(
1026 instantiated: &mut InstantiatedPredicates<'tcx>,
1027 substs: SubstsRef<'tcx>,
1029 if let Some(def_id) = self.parent {
1030 tcx.predicates_of(def_id).instantiate_into(tcx, instantiated, substs);
1032 instantiated.predicates.extend(self.predicates.iter().map(|(p, _)| p.subst(tcx, substs)));
1033 instantiated.spans.extend(self.predicates.iter().map(|(_, sp)| *sp));
1036 pub fn instantiate_identity(&self, tcx: TyCtxt<'tcx>) -> InstantiatedPredicates<'tcx> {
1037 let mut instantiated = InstantiatedPredicates::empty();
1038 self.instantiate_identity_into(tcx, &mut instantiated);
1042 fn instantiate_identity_into(
1045 instantiated: &mut InstantiatedPredicates<'tcx>,
1047 if let Some(def_id) = self.parent {
1048 tcx.predicates_of(def_id).instantiate_identity_into(tcx, instantiated);
1050 instantiated.predicates.extend(self.predicates.iter().map(|(p, _)| p));
1051 instantiated.spans.extend(self.predicates.iter().map(|(_, s)| s));
1056 crate struct PredicateInner<'tcx> {
1057 kind: PredicateKind<'tcx>,
1059 /// See the comment for the corresponding field of [TyS].
1060 outer_exclusive_binder: ty::DebruijnIndex,
1063 #[cfg(target_arch = "x86_64")]
1064 static_assert_size!(PredicateInner<'_>, 48);
1066 #[derive(Clone, Copy, Lift)]
1067 pub struct Predicate<'tcx> {
1068 inner: &'tcx PredicateInner<'tcx>,
1071 impl<'tcx> PartialEq for Predicate<'tcx> {
1072 fn eq(&self, other: &Self) -> bool {
1073 // `self.kind` is always interned.
1074 ptr::eq(self.inner, other.inner)
1078 impl Hash for Predicate<'_> {
1079 fn hash<H: Hasher>(&self, s: &mut H) {
1080 (self.inner as *const PredicateInner<'_>).hash(s)
1084 impl<'tcx> Eq for Predicate<'tcx> {}
1086 impl<'tcx> Predicate<'tcx> {
1088 pub fn kind(self) -> &'tcx PredicateKind<'tcx> {
1092 /// Returns the inner `PredicateAtom`.
1094 /// The returned atom may contain unbound variables bound to binders skipped in this method.
1095 /// It is safe to reapply binders to the given atom.
1097 /// Note that this method panics in case this predicate has unbound variables.
1098 pub fn skip_binders(self) -> PredicateAtom<'tcx> {
1100 &PredicateKind::ForAll(binder) => binder.skip_binder(),
1101 &PredicateKind::Atom(atom) => {
1102 debug_assert!(!atom.has_escaping_bound_vars());
1108 /// Returns the inner `PredicateAtom`.
1110 /// Note that this method does not check if the predicate has unbound variables.
1112 /// Rebinding the returned atom can causes the previously bound variables
1113 /// to end up at the wrong binding level.
1114 pub fn skip_binders_unchecked(self) -> PredicateAtom<'tcx> {
1116 &PredicateKind::ForAll(binder) => binder.skip_binder(),
1117 &PredicateKind::Atom(atom) => atom,
1121 /// Converts this to a `Binder<PredicateAtom<'tcx>>`. If the value was an
1122 /// `Atom`, then it is not allowed to contain escaping bound vars.
1123 pub fn bound_atom(self) -> Binder<PredicateAtom<'tcx>> {
1125 &PredicateKind::ForAll(binder) => binder,
1126 &PredicateKind::Atom(atom) => {
1127 debug_assert!(!atom.has_escaping_bound_vars());
1133 /// Allows using a `Binder<PredicateAtom<'tcx>>` even if the given predicate previously
1134 /// contained unbound variables by shifting these variables outwards.
1135 pub fn bound_atom_with_opt_escaping(self, tcx: TyCtxt<'tcx>) -> Binder<PredicateAtom<'tcx>> {
1137 &PredicateKind::ForAll(binder) => binder,
1138 &PredicateKind::Atom(atom) => Binder::wrap_nonbinding(tcx, atom),
1143 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for Predicate<'tcx> {
1144 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
1145 let PredicateInner {
1148 // The other fields just provide fast access to information that is
1149 // also contained in `kind`, so no need to hash them.
1151 outer_exclusive_binder: _,
1154 kind.hash_stable(hcx, hasher);
1158 #[derive(Clone, Copy, PartialEq, Eq, Hash, TyEncodable, TyDecodable)]
1159 #[derive(HashStable, TypeFoldable)]
1160 pub enum PredicateKind<'tcx> {
1162 ForAll(Binder<PredicateAtom<'tcx>>),
1163 Atom(PredicateAtom<'tcx>),
1166 #[derive(Clone, Copy, PartialEq, Eq, Hash, TyEncodable, TyDecodable)]
1167 #[derive(HashStable, TypeFoldable)]
1168 pub enum PredicateAtom<'tcx> {
1169 /// Corresponds to `where Foo: Bar<A, B, C>`. `Foo` here would be
1170 /// the `Self` type of the trait reference and `A`, `B`, and `C`
1171 /// would be the type parameters.
1173 /// A trait predicate will have `Constness::Const` if it originates
1174 /// from a bound on a `const fn` without the `?const` opt-out (e.g.,
1175 /// `const fn foobar<Foo: Bar>() {}`).
1176 Trait(TraitPredicate<'tcx>, Constness),
1179 RegionOutlives(RegionOutlivesPredicate<'tcx>),
1182 TypeOutlives(TypeOutlivesPredicate<'tcx>),
1184 /// `where <T as TraitRef>::Name == X`, approximately.
1185 /// See the `ProjectionPredicate` struct for details.
1186 Projection(ProjectionPredicate<'tcx>),
1188 /// No syntax: `T` well-formed.
1189 WellFormed(GenericArg<'tcx>),
1191 /// Trait must be object-safe.
1194 /// No direct syntax. May be thought of as `where T: FnFoo<...>`
1195 /// for some substitutions `...` and `T` being a closure type.
1196 /// Satisfied (or refuted) once we know the closure's kind.
1197 ClosureKind(DefId, SubstsRef<'tcx>, ClosureKind),
1200 Subtype(SubtypePredicate<'tcx>),
1202 /// Constant initializer must evaluate successfully.
1203 ConstEvaluatable(ty::WithOptConstParam<DefId>, SubstsRef<'tcx>),
1205 /// Constants must be equal. The first component is the const that is expected.
1206 ConstEquate(&'tcx Const<'tcx>, &'tcx Const<'tcx>),
1208 /// Represents a type found in the environment that we can use for implied bounds.
1210 /// Only used for Chalk.
1211 TypeWellFormedFromEnv(Ty<'tcx>),
1214 impl<'tcx> PredicateAtom<'tcx> {
1215 /// Wraps `self` with the given qualifier if this predicate has any unbound variables.
1216 pub fn potentially_quantified(
1219 qualifier: impl FnOnce(Binder<PredicateAtom<'tcx>>) -> PredicateKind<'tcx>,
1220 ) -> Predicate<'tcx> {
1221 if self.has_escaping_bound_vars() {
1222 qualifier(Binder::bind(self))
1224 PredicateKind::Atom(self)
1230 /// The crate outlives map is computed during typeck and contains the
1231 /// outlives of every item in the local crate. You should not use it
1232 /// directly, because to do so will make your pass dependent on the
1233 /// HIR of every item in the local crate. Instead, use
1234 /// `tcx.inferred_outlives_of()` to get the outlives for a *particular*
1236 #[derive(HashStable)]
1237 pub struct CratePredicatesMap<'tcx> {
1238 /// For each struct with outlive bounds, maps to a vector of the
1239 /// predicate of its outlive bounds. If an item has no outlives
1240 /// bounds, it will have no entry.
1241 pub predicates: FxHashMap<DefId, &'tcx [(Predicate<'tcx>, Span)]>,
1244 impl<'tcx> Predicate<'tcx> {
1245 /// Performs a substitution suitable for going from a
1246 /// poly-trait-ref to supertraits that must hold if that
1247 /// poly-trait-ref holds. This is slightly different from a normal
1248 /// substitution in terms of what happens with bound regions. See
1249 /// lengthy comment below for details.
1250 pub fn subst_supertrait(
1253 trait_ref: &ty::PolyTraitRef<'tcx>,
1254 ) -> Predicate<'tcx> {
1255 // The interaction between HRTB and supertraits is not entirely
1256 // obvious. Let me walk you (and myself) through an example.
1258 // Let's start with an easy case. Consider two traits:
1260 // trait Foo<'a>: Bar<'a,'a> { }
1261 // trait Bar<'b,'c> { }
1263 // Now, if we have a trait reference `for<'x> T: Foo<'x>`, then
1264 // we can deduce that `for<'x> T: Bar<'x,'x>`. Basically, if we
1265 // knew that `Foo<'x>` (for any 'x) then we also know that
1266 // `Bar<'x,'x>` (for any 'x). This more-or-less falls out from
1267 // normal substitution.
1269 // In terms of why this is sound, the idea is that whenever there
1270 // is an impl of `T:Foo<'a>`, it must show that `T:Bar<'a,'a>`
1271 // holds. So if there is an impl of `T:Foo<'a>` that applies to
1272 // all `'a`, then we must know that `T:Bar<'a,'a>` holds for all
1275 // Another example to be careful of is this:
1277 // trait Foo1<'a>: for<'b> Bar1<'a,'b> { }
1278 // trait Bar1<'b,'c> { }
1280 // Here, if we have `for<'x> T: Foo1<'x>`, then what do we know?
1281 // The answer is that we know `for<'x,'b> T: Bar1<'x,'b>`. The
1282 // reason is similar to the previous example: any impl of
1283 // `T:Foo1<'x>` must show that `for<'b> T: Bar1<'x, 'b>`. So
1284 // basically we would want to collapse the bound lifetimes from
1285 // the input (`trait_ref`) and the supertraits.
1287 // To achieve this in practice is fairly straightforward. Let's
1288 // consider the more complicated scenario:
1290 // - We start out with `for<'x> T: Foo1<'x>`. In this case, `'x`
1291 // has a De Bruijn index of 1. We want to produce `for<'x,'b> T: Bar1<'x,'b>`,
1292 // where both `'x` and `'b` would have a DB index of 1.
1293 // The substitution from the input trait-ref is therefore going to be
1294 // `'a => 'x` (where `'x` has a DB index of 1).
1295 // - The super-trait-ref is `for<'b> Bar1<'a,'b>`, where `'a` is an
1296 // early-bound parameter and `'b' is a late-bound parameter with a
1298 // - If we replace `'a` with `'x` from the input, it too will have
1299 // a DB index of 1, and thus we'll have `for<'x,'b> Bar1<'x,'b>`
1300 // just as we wanted.
1302 // There is only one catch. If we just apply the substitution `'a
1303 // => 'x` to `for<'b> Bar1<'a,'b>`, the substitution code will
1304 // adjust the DB index because we substituting into a binder (it
1305 // tries to be so smart...) resulting in `for<'x> for<'b>
1306 // Bar1<'x,'b>` (we have no syntax for this, so use your
1307 // imagination). Basically the 'x will have DB index of 2 and 'b
1308 // will have DB index of 1. Not quite what we want. So we apply
1309 // the substitution to the *contents* of the trait reference,
1310 // rather than the trait reference itself (put another way, the
1311 // substitution code expects equal binding levels in the values
1312 // from the substitution and the value being substituted into, and
1313 // this trick achieves that).
1314 let substs = trait_ref.skip_binder().substs;
1315 let pred = self.skip_binders();
1316 let new = pred.subst(tcx, substs);
1317 if new != pred { new.potentially_quantified(tcx, PredicateKind::ForAll) } else { self }
1321 #[derive(Clone, Copy, PartialEq, Eq, Hash, TyEncodable, TyDecodable)]
1322 #[derive(HashStable, TypeFoldable)]
1323 pub struct TraitPredicate<'tcx> {
1324 pub trait_ref: TraitRef<'tcx>,
1327 pub type PolyTraitPredicate<'tcx> = ty::Binder<TraitPredicate<'tcx>>;
1329 impl<'tcx> TraitPredicate<'tcx> {
1330 pub fn def_id(self) -> DefId {
1331 self.trait_ref.def_id
1334 pub fn self_ty(self) -> Ty<'tcx> {
1335 self.trait_ref.self_ty()
1339 impl<'tcx> PolyTraitPredicate<'tcx> {
1340 pub fn def_id(self) -> DefId {
1341 // Ok to skip binder since trait `DefId` does not care about regions.
1342 self.skip_binder().def_id()
1346 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, TyEncodable, TyDecodable)]
1347 #[derive(HashStable, TypeFoldable)]
1348 pub struct OutlivesPredicate<A, B>(pub A, pub B); // `A: B`
1349 pub type RegionOutlivesPredicate<'tcx> = OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>;
1350 pub type TypeOutlivesPredicate<'tcx> = OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>;
1351 pub type PolyRegionOutlivesPredicate<'tcx> = ty::Binder<RegionOutlivesPredicate<'tcx>>;
1352 pub type PolyTypeOutlivesPredicate<'tcx> = ty::Binder<TypeOutlivesPredicate<'tcx>>;
1354 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, TyEncodable, TyDecodable)]
1355 #[derive(HashStable, TypeFoldable)]
1356 pub struct SubtypePredicate<'tcx> {
1357 pub a_is_expected: bool,
1361 pub type PolySubtypePredicate<'tcx> = ty::Binder<SubtypePredicate<'tcx>>;
1363 /// This kind of predicate has no *direct* correspondent in the
1364 /// syntax, but it roughly corresponds to the syntactic forms:
1366 /// 1. `T: TraitRef<..., Item = Type>`
1367 /// 2. `<T as TraitRef<...>>::Item == Type` (NYI)
1369 /// In particular, form #1 is "desugared" to the combination of a
1370 /// normal trait predicate (`T: TraitRef<...>`) and one of these
1371 /// predicates. Form #2 is a broader form in that it also permits
1372 /// equality between arbitrary types. Processing an instance of
1373 /// Form #2 eventually yields one of these `ProjectionPredicate`
1374 /// instances to normalize the LHS.
1375 #[derive(Copy, Clone, PartialEq, Eq, Hash, TyEncodable, TyDecodable)]
1376 #[derive(HashStable, TypeFoldable)]
1377 pub struct ProjectionPredicate<'tcx> {
1378 pub projection_ty: ProjectionTy<'tcx>,
1382 pub type PolyProjectionPredicate<'tcx> = Binder<ProjectionPredicate<'tcx>>;
1384 impl<'tcx> PolyProjectionPredicate<'tcx> {
1385 /// Returns the `DefId` of the associated item being projected.
1386 pub fn item_def_id(&self) -> DefId {
1387 self.skip_binder().projection_ty.item_def_id
1391 pub fn to_poly_trait_ref(&self, tcx: TyCtxt<'tcx>) -> PolyTraitRef<'tcx> {
1392 // Note: unlike with `TraitRef::to_poly_trait_ref()`,
1393 // `self.0.trait_ref` is permitted to have escaping regions.
1394 // This is because here `self` has a `Binder` and so does our
1395 // return value, so we are preserving the number of binding
1397 self.map_bound(|predicate| predicate.projection_ty.trait_ref(tcx))
1400 pub fn ty(&self) -> Binder<Ty<'tcx>> {
1401 self.map_bound(|predicate| predicate.ty)
1404 /// The `DefId` of the `TraitItem` for the associated type.
1406 /// Note that this is not the `DefId` of the `TraitRef` containing this
1407 /// associated type, which is in `tcx.associated_item(projection_def_id()).container`.
1408 pub fn projection_def_id(&self) -> DefId {
1409 // Ok to skip binder since trait `DefId` does not care about regions.
1410 self.skip_binder().projection_ty.item_def_id
1414 pub trait ToPolyTraitRef<'tcx> {
1415 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx>;
1418 impl<'tcx> ToPolyTraitRef<'tcx> for TraitRef<'tcx> {
1419 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
1420 ty::Binder::dummy(*self)
1424 impl<'tcx> ToPolyTraitRef<'tcx> for PolyTraitPredicate<'tcx> {
1425 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
1426 self.map_bound_ref(|trait_pred| trait_pred.trait_ref)
1430 pub trait ToPredicate<'tcx> {
1431 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx>;
1434 impl ToPredicate<'tcx> for PredicateKind<'tcx> {
1436 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1437 tcx.mk_predicate(self)
1441 impl ToPredicate<'tcx> for PredicateAtom<'tcx> {
1443 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1444 debug_assert!(!self.has_escaping_bound_vars(), "escaping bound vars for {:?}", self);
1445 tcx.mk_predicate(PredicateKind::Atom(self))
1449 impl<'tcx> ToPredicate<'tcx> for ConstnessAnd<TraitRef<'tcx>> {
1450 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1451 PredicateAtom::Trait(ty::TraitPredicate { trait_ref: self.value }, self.constness)
1456 impl<'tcx> ToPredicate<'tcx> for ConstnessAnd<PolyTraitRef<'tcx>> {
1457 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1459 value: self.value.map_bound(|trait_ref| ty::TraitPredicate { trait_ref }),
1460 constness: self.constness,
1466 impl<'tcx> ToPredicate<'tcx> for ConstnessAnd<PolyTraitPredicate<'tcx>> {
1467 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1468 PredicateAtom::Trait(self.value.skip_binder(), self.constness)
1469 .potentially_quantified(tcx, PredicateKind::ForAll)
1473 impl<'tcx> ToPredicate<'tcx> for PolyRegionOutlivesPredicate<'tcx> {
1474 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1475 PredicateAtom::RegionOutlives(self.skip_binder())
1476 .potentially_quantified(tcx, PredicateKind::ForAll)
1480 impl<'tcx> ToPredicate<'tcx> for PolyTypeOutlivesPredicate<'tcx> {
1481 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1482 PredicateAtom::TypeOutlives(self.skip_binder())
1483 .potentially_quantified(tcx, PredicateKind::ForAll)
1487 impl<'tcx> ToPredicate<'tcx> for PolyProjectionPredicate<'tcx> {
1488 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1489 PredicateAtom::Projection(self.skip_binder())
1490 .potentially_quantified(tcx, PredicateKind::ForAll)
1494 impl<'tcx> Predicate<'tcx> {
1495 pub fn to_opt_poly_trait_ref(self) -> Option<PolyTraitRef<'tcx>> {
1496 match self.skip_binders() {
1497 PredicateAtom::Trait(t, _) => Some(ty::Binder::bind(t.trait_ref)),
1498 PredicateAtom::Projection(..)
1499 | PredicateAtom::Subtype(..)
1500 | PredicateAtom::RegionOutlives(..)
1501 | PredicateAtom::WellFormed(..)
1502 | PredicateAtom::ObjectSafe(..)
1503 | PredicateAtom::ClosureKind(..)
1504 | PredicateAtom::TypeOutlives(..)
1505 | PredicateAtom::ConstEvaluatable(..)
1506 | PredicateAtom::ConstEquate(..)
1507 | PredicateAtom::TypeWellFormedFromEnv(..) => None,
1511 pub fn to_opt_type_outlives(self) -> Option<PolyTypeOutlivesPredicate<'tcx>> {
1512 match self.skip_binders() {
1513 PredicateAtom::TypeOutlives(data) => Some(ty::Binder::bind(data)),
1514 PredicateAtom::Trait(..)
1515 | PredicateAtom::Projection(..)
1516 | PredicateAtom::Subtype(..)
1517 | PredicateAtom::RegionOutlives(..)
1518 | PredicateAtom::WellFormed(..)
1519 | PredicateAtom::ObjectSafe(..)
1520 | PredicateAtom::ClosureKind(..)
1521 | PredicateAtom::ConstEvaluatable(..)
1522 | PredicateAtom::ConstEquate(..)
1523 | PredicateAtom::TypeWellFormedFromEnv(..) => None,
1528 /// Represents the bounds declared on a particular set of type
1529 /// parameters. Should eventually be generalized into a flag list of
1530 /// where-clauses. You can obtain a `InstantiatedPredicates` list from a
1531 /// `GenericPredicates` by using the `instantiate` method. Note that this method
1532 /// reflects an important semantic invariant of `InstantiatedPredicates`: while
1533 /// the `GenericPredicates` are expressed in terms of the bound type
1534 /// parameters of the impl/trait/whatever, an `InstantiatedPredicates` instance
1535 /// represented a set of bounds for some particular instantiation,
1536 /// meaning that the generic parameters have been substituted with
1541 /// struct Foo<T, U: Bar<T>> { ... }
1543 /// Here, the `GenericPredicates` for `Foo` would contain a list of bounds like
1544 /// `[[], [U:Bar<T>]]`. Now if there were some particular reference
1545 /// like `Foo<isize,usize>`, then the `InstantiatedPredicates` would be `[[],
1546 /// [usize:Bar<isize>]]`.
1547 #[derive(Clone, Debug, TypeFoldable)]
1548 pub struct InstantiatedPredicates<'tcx> {
1549 pub predicates: Vec<Predicate<'tcx>>,
1550 pub spans: Vec<Span>,
1553 impl<'tcx> InstantiatedPredicates<'tcx> {
1554 pub fn empty() -> InstantiatedPredicates<'tcx> {
1555 InstantiatedPredicates { predicates: vec![], spans: vec![] }
1558 pub fn is_empty(&self) -> bool {
1559 self.predicates.is_empty()
1563 rustc_index::newtype_index! {
1564 /// "Universes" are used during type- and trait-checking in the
1565 /// presence of `for<..>` binders to control what sets of names are
1566 /// visible. Universes are arranged into a tree: the root universe
1567 /// contains names that are always visible. Each child then adds a new
1568 /// set of names that are visible, in addition to those of its parent.
1569 /// We say that the child universe "extends" the parent universe with
1572 /// To make this more concrete, consider this program:
1576 /// fn bar<T>(x: T) {
1577 /// let y: for<'a> fn(&'a u8, Foo) = ...;
1581 /// The struct name `Foo` is in the root universe U0. But the type
1582 /// parameter `T`, introduced on `bar`, is in an extended universe U1
1583 /// -- i.e., within `bar`, we can name both `T` and `Foo`, but outside
1584 /// of `bar`, we cannot name `T`. Then, within the type of `y`, the
1585 /// region `'a` is in a universe U2 that extends U1, because we can
1586 /// name it inside the fn type but not outside.
1588 /// Universes are used to do type- and trait-checking around these
1589 /// "forall" binders (also called **universal quantification**). The
1590 /// idea is that when, in the body of `bar`, we refer to `T` as a
1591 /// type, we aren't referring to any type in particular, but rather a
1592 /// kind of "fresh" type that is distinct from all other types we have
1593 /// actually declared. This is called a **placeholder** type, and we
1594 /// use universes to talk about this. In other words, a type name in
1595 /// universe 0 always corresponds to some "ground" type that the user
1596 /// declared, but a type name in a non-zero universe is a placeholder
1597 /// type -- an idealized representative of "types in general" that we
1598 /// use for checking generic functions.
1599 pub struct UniverseIndex {
1601 DEBUG_FORMAT = "U{}",
1605 impl UniverseIndex {
1606 pub const ROOT: UniverseIndex = UniverseIndex::from_u32(0);
1608 /// Returns the "next" universe index in order -- this new index
1609 /// is considered to extend all previous universes. This
1610 /// corresponds to entering a `forall` quantifier. So, for
1611 /// example, suppose we have this type in universe `U`:
1614 /// for<'a> fn(&'a u32)
1617 /// Once we "enter" into this `for<'a>` quantifier, we are in a
1618 /// new universe that extends `U` -- in this new universe, we can
1619 /// name the region `'a`, but that region was not nameable from
1620 /// `U` because it was not in scope there.
1621 pub fn next_universe(self) -> UniverseIndex {
1622 UniverseIndex::from_u32(self.private.checked_add(1).unwrap())
1625 /// Returns `true` if `self` can name a name from `other` -- in other words,
1626 /// if the set of names in `self` is a superset of those in
1627 /// `other` (`self >= other`).
1628 pub fn can_name(self, other: UniverseIndex) -> bool {
1629 self.private >= other.private
1632 /// Returns `true` if `self` cannot name some names from `other` -- in other
1633 /// words, if the set of names in `self` is a strict subset of
1634 /// those in `other` (`self < other`).
1635 pub fn cannot_name(self, other: UniverseIndex) -> bool {
1636 self.private < other.private
1640 /// The "placeholder index" fully defines a placeholder region.
1641 /// Placeholder regions are identified by both a **universe** as well
1642 /// as a "bound-region" within that universe. The `bound_region` is
1643 /// basically a name -- distinct bound regions within the same
1644 /// universe are just two regions with an unknown relationship to one
1646 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TyEncodable, TyDecodable, PartialOrd, Ord)]
1647 pub struct Placeholder<T> {
1648 pub universe: UniverseIndex,
1652 impl<'a, T> HashStable<StableHashingContext<'a>> for Placeholder<T>
1654 T: HashStable<StableHashingContext<'a>>,
1656 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
1657 self.universe.hash_stable(hcx, hasher);
1658 self.name.hash_stable(hcx, hasher);
1662 pub type PlaceholderRegion = Placeholder<BoundRegion>;
1664 pub type PlaceholderType = Placeholder<BoundVar>;
1666 pub type PlaceholderConst = Placeholder<BoundVar>;
1668 /// A `DefId` which is potentially bundled with its corresponding generic parameter
1669 /// in case `did` is a const argument.
1671 /// This is used to prevent cycle errors during typeck
1672 /// as `type_of(const_arg)` depends on `typeck(owning_body)`
1673 /// which once again requires the type of its generic arguments.
1675 /// Luckily we only need to deal with const arguments once we
1676 /// know their corresponding parameters. We (ab)use this by
1677 /// calling `type_of(param_did)` for these arguments.
1680 /// #![feature(const_generics)]
1684 /// fn foo<const N: usize>(&self) -> usize { N }
1688 /// fn foo<const N: u8>(&self) -> usize { 42 }
1696 #[derive(Copy, Clone, Debug, TypeFoldable, Lift, TyEncodable, TyDecodable)]
1697 #[derive(PartialEq, Eq, PartialOrd, Ord)]
1698 #[derive(Hash, HashStable)]
1699 pub struct WithOptConstParam<T> {
1701 /// The `DefId` of the corresponding generic parameter in case `did` is
1702 /// a const argument.
1704 /// Note that even if `did` is a const argument, this may still be `None`.
1705 /// All queries taking `WithOptConstParam` start by calling `tcx.opt_const_param_of(def.did)`
1706 /// to potentially update `param_did` in case it `None`.
1707 pub const_param_did: Option<DefId>,
1710 impl<T> WithOptConstParam<T> {
1711 /// Creates a new `WithOptConstParam` setting `const_param_did` to `None`.
1713 pub fn unknown(did: T) -> WithOptConstParam<T> {
1714 WithOptConstParam { did, const_param_did: None }
1718 impl WithOptConstParam<LocalDefId> {
1719 /// Returns `Some((did, param_did))` if `def_id` is a const argument,
1720 /// `None` otherwise.
1722 pub fn try_lookup(did: LocalDefId, tcx: TyCtxt<'_>) -> Option<(LocalDefId, DefId)> {
1723 tcx.opt_const_param_of(did).map(|param_did| (did, param_did))
1726 /// In case `self` is unknown but `self.did` is a const argument, this returns
1727 /// a `WithOptConstParam` with the correct `const_param_did`.
1729 pub fn try_upgrade(self, tcx: TyCtxt<'_>) -> Option<WithOptConstParam<LocalDefId>> {
1730 if self.const_param_did.is_none() {
1731 if let const_param_did @ Some(_) = tcx.opt_const_param_of(self.did) {
1732 return Some(WithOptConstParam { did: self.did, const_param_did });
1739 pub fn to_global(self) -> WithOptConstParam<DefId> {
1740 WithOptConstParam { did: self.did.to_def_id(), const_param_did: self.const_param_did }
1743 pub fn def_id_for_type_of(self) -> DefId {
1744 if let Some(did) = self.const_param_did { did } else { self.did.to_def_id() }
1748 impl WithOptConstParam<DefId> {
1749 pub fn as_local(self) -> Option<WithOptConstParam<LocalDefId>> {
1752 .map(|did| WithOptConstParam { did, const_param_did: self.const_param_did })
1755 pub fn as_const_arg(self) -> Option<(LocalDefId, DefId)> {
1756 if let Some(param_did) = self.const_param_did {
1757 if let Some(did) = self.did.as_local() {
1758 return Some((did, param_did));
1765 pub fn expect_local(self) -> WithOptConstParam<LocalDefId> {
1766 self.as_local().unwrap()
1769 pub fn is_local(self) -> bool {
1773 pub fn def_id_for_type_of(self) -> DefId {
1774 self.const_param_did.unwrap_or(self.did)
1778 /// When type checking, we use the `ParamEnv` to track
1779 /// details about the set of where-clauses that are in scope at this
1780 /// particular point.
1781 #[derive(Copy, Clone, Hash, PartialEq, Eq)]
1782 pub struct ParamEnv<'tcx> {
1783 /// This packs both caller bounds and the reveal enum into one pointer.
1785 /// Caller bounds are `Obligation`s that the caller must satisfy. This is
1786 /// basically the set of bounds on the in-scope type parameters, translated
1787 /// into `Obligation`s, and elaborated and normalized.
1789 /// Use the `caller_bounds()` method to access.
1791 /// Typically, this is `Reveal::UserFacing`, but during codegen we
1792 /// want `Reveal::All`.
1794 /// Note: This is packed, use the reveal() method to access it.
1795 packed: CopyTaggedPtr<&'tcx List<Predicate<'tcx>>, traits::Reveal, true>,
1798 unsafe impl rustc_data_structures::tagged_ptr::Tag for traits::Reveal {
1799 const BITS: usize = 1;
1800 fn into_usize(self) -> usize {
1802 traits::Reveal::UserFacing => 0,
1803 traits::Reveal::All => 1,
1806 unsafe fn from_usize(ptr: usize) -> Self {
1808 0 => traits::Reveal::UserFacing,
1809 1 => traits::Reveal::All,
1810 _ => std::hint::unreachable_unchecked(),
1815 impl<'tcx> fmt::Debug for ParamEnv<'tcx> {
1816 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1817 f.debug_struct("ParamEnv")
1818 .field("caller_bounds", &self.caller_bounds())
1819 .field("reveal", &self.reveal())
1824 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for ParamEnv<'tcx> {
1825 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
1826 self.caller_bounds().hash_stable(hcx, hasher);
1827 self.reveal().hash_stable(hcx, hasher);
1831 impl<'tcx> TypeFoldable<'tcx> for ParamEnv<'tcx> {
1832 fn super_fold_with<F: ty::fold::TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
1833 ParamEnv::new(self.caller_bounds().fold_with(folder), self.reveal().fold_with(folder))
1836 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> ControlFlow<()> {
1837 self.caller_bounds().visit_with(visitor)?;
1838 self.reveal().visit_with(visitor)
1842 impl<'tcx> ParamEnv<'tcx> {
1843 /// Construct a trait environment suitable for contexts where
1844 /// there are no where-clauses in scope. Hidden types (like `impl
1845 /// Trait`) are left hidden, so this is suitable for ordinary
1848 pub fn empty() -> Self {
1849 Self::new(List::empty(), Reveal::UserFacing)
1853 pub fn caller_bounds(self) -> &'tcx List<Predicate<'tcx>> {
1854 self.packed.pointer()
1858 pub fn reveal(self) -> traits::Reveal {
1862 /// Construct a trait environment with no where-clauses in scope
1863 /// where the values of all `impl Trait` and other hidden types
1864 /// are revealed. This is suitable for monomorphized, post-typeck
1865 /// environments like codegen or doing optimizations.
1867 /// N.B., if you want to have predicates in scope, use `ParamEnv::new`,
1868 /// or invoke `param_env.with_reveal_all()`.
1870 pub fn reveal_all() -> Self {
1871 Self::new(List::empty(), Reveal::All)
1874 /// Construct a trait environment with the given set of predicates.
1876 pub fn new(caller_bounds: &'tcx List<Predicate<'tcx>>, reveal: Reveal) -> Self {
1877 ty::ParamEnv { packed: CopyTaggedPtr::new(caller_bounds, reveal) }
1880 pub fn with_user_facing(mut self) -> Self {
1881 self.packed.set_tag(Reveal::UserFacing);
1885 /// Returns a new parameter environment with the same clauses, but
1886 /// which "reveals" the true results of projections in all cases
1887 /// (even for associated types that are specializable). This is
1888 /// the desired behavior during codegen and certain other special
1889 /// contexts; normally though we want to use `Reveal::UserFacing`,
1890 /// which is the default.
1891 /// All opaque types in the caller_bounds of the `ParamEnv`
1892 /// will be normalized to their underlying types.
1893 /// See PR #65989 and issue #65918 for more details
1894 pub fn with_reveal_all_normalized(self, tcx: TyCtxt<'tcx>) -> Self {
1895 if self.packed.tag() == traits::Reveal::All {
1899 ParamEnv::new(tcx.normalize_opaque_types(self.caller_bounds()), Reveal::All)
1902 /// Returns this same environment but with no caller bounds.
1903 pub fn without_caller_bounds(self) -> Self {
1904 Self::new(List::empty(), self.reveal())
1907 /// Creates a suitable environment in which to perform trait
1908 /// queries on the given value. When type-checking, this is simply
1909 /// the pair of the environment plus value. But when reveal is set to
1910 /// All, then if `value` does not reference any type parameters, we will
1911 /// pair it with the empty environment. This improves caching and is generally
1914 /// N.B., we preserve the environment when type-checking because it
1915 /// is possible for the user to have wacky where-clauses like
1916 /// `where Box<u32>: Copy`, which are clearly never
1917 /// satisfiable. We generally want to behave as if they were true,
1918 /// although the surrounding function is never reachable.
1919 pub fn and<T: TypeFoldable<'tcx>>(self, value: T) -> ParamEnvAnd<'tcx, T> {
1920 match self.reveal() {
1921 Reveal::UserFacing => ParamEnvAnd { param_env: self, value },
1924 if value.is_global() {
1925 ParamEnvAnd { param_env: self.without_caller_bounds(), value }
1927 ParamEnvAnd { param_env: self, value }
1934 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1935 pub struct ConstnessAnd<T> {
1936 pub constness: Constness,
1940 // FIXME(ecstaticmorse): Audit all occurrences of `without_const().to_predicate(tcx)` to ensure that
1941 // the constness of trait bounds is being propagated correctly.
1942 pub trait WithConstness: Sized {
1944 fn with_constness(self, constness: Constness) -> ConstnessAnd<Self> {
1945 ConstnessAnd { constness, value: self }
1949 fn with_const(self) -> ConstnessAnd<Self> {
1950 self.with_constness(Constness::Const)
1954 fn without_const(self) -> ConstnessAnd<Self> {
1955 self.with_constness(Constness::NotConst)
1959 impl<T> WithConstness for T {}
1961 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TypeFoldable)]
1962 pub struct ParamEnvAnd<'tcx, T> {
1963 pub param_env: ParamEnv<'tcx>,
1967 impl<'tcx, T> ParamEnvAnd<'tcx, T> {
1968 pub fn into_parts(self) -> (ParamEnv<'tcx>, T) {
1969 (self.param_env, self.value)
1973 impl<'a, 'tcx, T> HashStable<StableHashingContext<'a>> for ParamEnvAnd<'tcx, T>
1975 T: HashStable<StableHashingContext<'a>>,
1977 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
1978 let ParamEnvAnd { ref param_env, ref value } = *self;
1980 param_env.hash_stable(hcx, hasher);
1981 value.hash_stable(hcx, hasher);
1985 #[derive(Copy, Clone, Debug, HashStable)]
1986 pub struct Destructor {
1987 /// The `DefId` of the destructor method
1992 #[derive(HashStable)]
1993 pub struct AdtFlags: u32 {
1994 const NO_ADT_FLAGS = 0;
1995 /// Indicates whether the ADT is an enum.
1996 const IS_ENUM = 1 << 0;
1997 /// Indicates whether the ADT is a union.
1998 const IS_UNION = 1 << 1;
1999 /// Indicates whether the ADT is a struct.
2000 const IS_STRUCT = 1 << 2;
2001 /// Indicates whether the ADT is a struct and has a constructor.
2002 const HAS_CTOR = 1 << 3;
2003 /// Indicates whether the type is `PhantomData`.
2004 const IS_PHANTOM_DATA = 1 << 4;
2005 /// Indicates whether the type has a `#[fundamental]` attribute.
2006 const IS_FUNDAMENTAL = 1 << 5;
2007 /// Indicates whether the type is `Box`.
2008 const IS_BOX = 1 << 6;
2009 /// Indicates whether the type is `ManuallyDrop`.
2010 const IS_MANUALLY_DROP = 1 << 7;
2011 /// Indicates whether the variant list of this ADT is `#[non_exhaustive]`.
2012 /// (i.e., this flag is never set unless this ADT is an enum).
2013 const IS_VARIANT_LIST_NON_EXHAUSTIVE = 1 << 8;
2018 #[derive(HashStable)]
2019 pub struct VariantFlags: u32 {
2020 const NO_VARIANT_FLAGS = 0;
2021 /// Indicates whether the field list of this variant is `#[non_exhaustive]`.
2022 const IS_FIELD_LIST_NON_EXHAUSTIVE = 1 << 0;
2023 /// Indicates whether this variant was obtained as part of recovering from
2024 /// a syntactic error. May be incomplete or bogus.
2025 const IS_RECOVERED = 1 << 1;
2029 /// Definition of a variant -- a struct's fields or a enum variant.
2030 #[derive(Debug, HashStable)]
2031 pub struct VariantDef {
2032 /// `DefId` that identifies the variant itself.
2033 /// If this variant belongs to a struct or union, then this is a copy of its `DefId`.
2035 /// `DefId` that identifies the variant's constructor.
2036 /// If this variant is a struct variant, then this is `None`.
2037 pub ctor_def_id: Option<DefId>,
2038 /// Variant or struct name.
2039 #[stable_hasher(project(name))]
2041 /// Discriminant of this variant.
2042 pub discr: VariantDiscr,
2043 /// Fields of this variant.
2044 pub fields: Vec<FieldDef>,
2045 /// Type of constructor of variant.
2046 pub ctor_kind: CtorKind,
2047 /// Flags of the variant (e.g. is field list non-exhaustive)?
2048 flags: VariantFlags,
2052 /// Creates a new `VariantDef`.
2054 /// `variant_did` is the `DefId` that identifies the enum variant (if this `VariantDef`
2055 /// represents an enum variant).
2057 /// `ctor_did` is the `DefId` that identifies the constructor of unit or
2058 /// tuple-variants/structs. If this is a `struct`-variant then this should be `None`.
2060 /// `parent_did` is the `DefId` of the `AdtDef` representing the enum or struct that
2061 /// owns this variant. It is used for checking if a struct has `#[non_exhaustive]` w/out having
2062 /// to go through the redirect of checking the ctor's attributes - but compiling a small crate
2063 /// requires loading the `AdtDef`s for all the structs in the universe (e.g., coherence for any
2064 /// built-in trait), and we do not want to load attributes twice.
2066 /// If someone speeds up attribute loading to not be a performance concern, they can
2067 /// remove this hack and use the constructor `DefId` everywhere.
2070 variant_did: Option<DefId>,
2071 ctor_def_id: Option<DefId>,
2072 discr: VariantDiscr,
2073 fields: Vec<FieldDef>,
2074 ctor_kind: CtorKind,
2078 is_field_list_non_exhaustive: bool,
2081 "VariantDef::new(ident = {:?}, variant_did = {:?}, ctor_def_id = {:?}, discr = {:?},
2082 fields = {:?}, ctor_kind = {:?}, adt_kind = {:?}, parent_did = {:?})",
2083 ident, variant_did, ctor_def_id, discr, fields, ctor_kind, adt_kind, parent_did,
2086 let mut flags = VariantFlags::NO_VARIANT_FLAGS;
2087 if is_field_list_non_exhaustive {
2088 flags |= VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE;
2092 flags |= VariantFlags::IS_RECOVERED;
2096 def_id: variant_did.unwrap_or(parent_did),
2106 /// Is this field list non-exhaustive?
2108 pub fn is_field_list_non_exhaustive(&self) -> bool {
2109 self.flags.intersects(VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE)
2112 /// Was this variant obtained as part of recovering from a syntactic error?
2114 pub fn is_recovered(&self) -> bool {
2115 self.flags.intersects(VariantFlags::IS_RECOVERED)
2119 #[derive(Copy, Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
2120 pub enum VariantDiscr {
2121 /// Explicit value for this variant, i.e., `X = 123`.
2122 /// The `DefId` corresponds to the embedded constant.
2125 /// The previous variant's discriminant plus one.
2126 /// For efficiency reasons, the distance from the
2127 /// last `Explicit` discriminant is being stored,
2128 /// or `0` for the first variant, if it has none.
2132 #[derive(Debug, HashStable)]
2133 pub struct FieldDef {
2135 #[stable_hasher(project(name))]
2137 pub vis: Visibility,
2140 /// The definition of a user-defined type, e.g., a `struct`, `enum`, or `union`.
2142 /// These are all interned (by `alloc_adt_def`) into the global arena.
2144 /// The initialism *ADT* stands for an [*algebraic data type (ADT)*][adt].
2145 /// This is slightly wrong because `union`s are not ADTs.
2146 /// Moreover, Rust only allows recursive data types through indirection.
2148 /// [adt]: https://en.wikipedia.org/wiki/Algebraic_data_type
2150 /// The `DefId` of the struct, enum or union item.
2152 /// Variants of the ADT. If this is a struct or union, then there will be a single variant.
2153 pub variants: IndexVec<VariantIdx, VariantDef>,
2154 /// Flags of the ADT (e.g., is this a struct? is this non-exhaustive?).
2156 /// Repr options provided by the user.
2157 pub repr: ReprOptions,
2160 impl PartialOrd for AdtDef {
2161 fn partial_cmp(&self, other: &AdtDef) -> Option<Ordering> {
2162 Some(self.cmp(&other))
2166 /// There should be only one AdtDef for each `did`, therefore
2167 /// it is fine to implement `Ord` only based on `did`.
2168 impl Ord for AdtDef {
2169 fn cmp(&self, other: &AdtDef) -> Ordering {
2170 self.did.cmp(&other.did)
2174 impl PartialEq for AdtDef {
2175 // `AdtDef`s are always interned, and this is part of `TyS` equality.
2177 fn eq(&self, other: &Self) -> bool {
2178 ptr::eq(self, other)
2182 impl Eq for AdtDef {}
2184 impl Hash for AdtDef {
2186 fn hash<H: Hasher>(&self, s: &mut H) {
2187 (self as *const AdtDef).hash(s)
2191 impl<S: Encoder> Encodable<S> for AdtDef {
2192 fn encode(&self, s: &mut S) -> Result<(), S::Error> {
2197 impl<'a> HashStable<StableHashingContext<'a>> for AdtDef {
2198 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
2200 static CACHE: RefCell<FxHashMap<usize, Fingerprint>> = Default::default();
2203 let hash: Fingerprint = CACHE.with(|cache| {
2204 let addr = self as *const AdtDef as usize;
2205 *cache.borrow_mut().entry(addr).or_insert_with(|| {
2206 let ty::AdtDef { did, ref variants, ref flags, ref repr } = *self;
2208 let mut hasher = StableHasher::new();
2209 did.hash_stable(hcx, &mut hasher);
2210 variants.hash_stable(hcx, &mut hasher);
2211 flags.hash_stable(hcx, &mut hasher);
2212 repr.hash_stable(hcx, &mut hasher);
2218 hash.hash_stable(hcx, hasher);
2222 #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
2229 impl Into<DataTypeKind> for AdtKind {
2230 fn into(self) -> DataTypeKind {
2232 AdtKind::Struct => DataTypeKind::Struct,
2233 AdtKind::Union => DataTypeKind::Union,
2234 AdtKind::Enum => DataTypeKind::Enum,
2240 #[derive(TyEncodable, TyDecodable, Default, HashStable)]
2241 pub struct ReprFlags: u8 {
2242 const IS_C = 1 << 0;
2243 const IS_SIMD = 1 << 1;
2244 const IS_TRANSPARENT = 1 << 2;
2245 // Internal only for now. If true, don't reorder fields.
2246 const IS_LINEAR = 1 << 3;
2247 // If true, don't expose any niche to type's context.
2248 const HIDE_NICHE = 1 << 4;
2249 // Any of these flags being set prevent field reordering optimisation.
2250 const IS_UNOPTIMISABLE = ReprFlags::IS_C.bits |
2251 ReprFlags::IS_SIMD.bits |
2252 ReprFlags::IS_LINEAR.bits;
2256 /// Represents the repr options provided by the user,
2257 #[derive(Copy, Clone, Debug, Eq, PartialEq, TyEncodable, TyDecodable, Default, HashStable)]
2258 pub struct ReprOptions {
2259 pub int: Option<attr::IntType>,
2260 pub align: Option<Align>,
2261 pub pack: Option<Align>,
2262 pub flags: ReprFlags,
2266 pub fn new(tcx: TyCtxt<'_>, did: DefId) -> ReprOptions {
2267 let mut flags = ReprFlags::empty();
2268 let mut size = None;
2269 let mut max_align: Option<Align> = None;
2270 let mut min_pack: Option<Align> = None;
2271 for attr in tcx.get_attrs(did).iter() {
2272 for r in attr::find_repr_attrs(&tcx.sess, attr) {
2273 flags.insert(match r {
2274 attr::ReprC => ReprFlags::IS_C,
2275 attr::ReprPacked(pack) => {
2276 let pack = Align::from_bytes(pack as u64).unwrap();
2277 min_pack = Some(if let Some(min_pack) = min_pack {
2284 attr::ReprTransparent => ReprFlags::IS_TRANSPARENT,
2285 attr::ReprNoNiche => ReprFlags::HIDE_NICHE,
2286 attr::ReprSimd => ReprFlags::IS_SIMD,
2287 attr::ReprInt(i) => {
2291 attr::ReprAlign(align) => {
2292 max_align = max_align.max(Some(Align::from_bytes(align as u64).unwrap()));
2299 // This is here instead of layout because the choice must make it into metadata.
2300 if !tcx.consider_optimizing(|| format!("Reorder fields of {:?}", tcx.def_path_str(did))) {
2301 flags.insert(ReprFlags::IS_LINEAR);
2303 ReprOptions { int: size, align: max_align, pack: min_pack, flags }
2307 pub fn simd(&self) -> bool {
2308 self.flags.contains(ReprFlags::IS_SIMD)
2311 pub fn c(&self) -> bool {
2312 self.flags.contains(ReprFlags::IS_C)
2315 pub fn packed(&self) -> bool {
2319 pub fn transparent(&self) -> bool {
2320 self.flags.contains(ReprFlags::IS_TRANSPARENT)
2323 pub fn linear(&self) -> bool {
2324 self.flags.contains(ReprFlags::IS_LINEAR)
2327 pub fn hide_niche(&self) -> bool {
2328 self.flags.contains(ReprFlags::HIDE_NICHE)
2331 /// Returns the discriminant type, given these `repr` options.
2332 /// This must only be called on enums!
2333 pub fn discr_type(&self) -> attr::IntType {
2334 self.int.unwrap_or(attr::SignedInt(ast::IntTy::Isize))
2337 /// Returns `true` if this `#[repr()]` should inhabit "smart enum
2338 /// layout" optimizations, such as representing `Foo<&T>` as a
2340 pub fn inhibit_enum_layout_opt(&self) -> bool {
2341 self.c() || self.int.is_some()
2344 /// Returns `true` if this `#[repr()]` should inhibit struct field reordering
2345 /// optimizations, such as with `repr(C)`, `repr(packed(1))`, or `repr(<int>)`.
2346 pub fn inhibit_struct_field_reordering_opt(&self) -> bool {
2347 if let Some(pack) = self.pack {
2348 if pack.bytes() == 1 {
2352 self.flags.intersects(ReprFlags::IS_UNOPTIMISABLE) || self.int.is_some()
2355 /// Returns `true` if this `#[repr()]` should inhibit union ABI optimisations.
2356 pub fn inhibit_union_abi_opt(&self) -> bool {
2362 /// Creates a new `AdtDef`.
2367 variants: IndexVec<VariantIdx, VariantDef>,
2370 debug!("AdtDef::new({:?}, {:?}, {:?}, {:?})", did, kind, variants, repr);
2371 let mut flags = AdtFlags::NO_ADT_FLAGS;
2373 if kind == AdtKind::Enum && tcx.has_attr(did, sym::non_exhaustive) {
2374 debug!("found non-exhaustive variant list for {:?}", did);
2375 flags = flags | AdtFlags::IS_VARIANT_LIST_NON_EXHAUSTIVE;
2378 flags |= match kind {
2379 AdtKind::Enum => AdtFlags::IS_ENUM,
2380 AdtKind::Union => AdtFlags::IS_UNION,
2381 AdtKind::Struct => AdtFlags::IS_STRUCT,
2384 if kind == AdtKind::Struct && variants[VariantIdx::new(0)].ctor_def_id.is_some() {
2385 flags |= AdtFlags::HAS_CTOR;
2388 let attrs = tcx.get_attrs(did);
2389 if tcx.sess.contains_name(&attrs, sym::fundamental) {
2390 flags |= AdtFlags::IS_FUNDAMENTAL;
2392 if Some(did) == tcx.lang_items().phantom_data() {
2393 flags |= AdtFlags::IS_PHANTOM_DATA;
2395 if Some(did) == tcx.lang_items().owned_box() {
2396 flags |= AdtFlags::IS_BOX;
2398 if Some(did) == tcx.lang_items().manually_drop() {
2399 flags |= AdtFlags::IS_MANUALLY_DROP;
2402 AdtDef { did, variants, flags, repr }
2405 /// Returns `true` if this is a struct.
2407 pub fn is_struct(&self) -> bool {
2408 self.flags.contains(AdtFlags::IS_STRUCT)
2411 /// Returns `true` if this is a union.
2413 pub fn is_union(&self) -> bool {
2414 self.flags.contains(AdtFlags::IS_UNION)
2417 /// Returns `true` if this is a enum.
2419 pub fn is_enum(&self) -> bool {
2420 self.flags.contains(AdtFlags::IS_ENUM)
2423 /// Returns `true` if the variant list of this ADT is `#[non_exhaustive]`.
2425 pub fn is_variant_list_non_exhaustive(&self) -> bool {
2426 self.flags.contains(AdtFlags::IS_VARIANT_LIST_NON_EXHAUSTIVE)
2429 /// Returns the kind of the ADT.
2431 pub fn adt_kind(&self) -> AdtKind {
2434 } else if self.is_union() {
2441 /// Returns a description of this abstract data type.
2442 pub fn descr(&self) -> &'static str {
2443 match self.adt_kind() {
2444 AdtKind::Struct => "struct",
2445 AdtKind::Union => "union",
2446 AdtKind::Enum => "enum",
2450 /// Returns a description of a variant of this abstract data type.
2452 pub fn variant_descr(&self) -> &'static str {
2453 match self.adt_kind() {
2454 AdtKind::Struct => "struct",
2455 AdtKind::Union => "union",
2456 AdtKind::Enum => "variant",
2460 /// If this function returns `true`, it implies that `is_struct` must return `true`.
2462 pub fn has_ctor(&self) -> bool {
2463 self.flags.contains(AdtFlags::HAS_CTOR)
2466 /// Returns `true` if this type is `#[fundamental]` for the purposes
2467 /// of coherence checking.
2469 pub fn is_fundamental(&self) -> bool {
2470 self.flags.contains(AdtFlags::IS_FUNDAMENTAL)
2473 /// Returns `true` if this is `PhantomData<T>`.
2475 pub fn is_phantom_data(&self) -> bool {
2476 self.flags.contains(AdtFlags::IS_PHANTOM_DATA)
2479 /// Returns `true` if this is Box<T>.
2481 pub fn is_box(&self) -> bool {
2482 self.flags.contains(AdtFlags::IS_BOX)
2485 /// Returns `true` if this is `ManuallyDrop<T>`.
2487 pub fn is_manually_drop(&self) -> bool {
2488 self.flags.contains(AdtFlags::IS_MANUALLY_DROP)
2491 /// Returns `true` if this type has a destructor.
2492 pub fn has_dtor(&self, tcx: TyCtxt<'tcx>) -> bool {
2493 self.destructor(tcx).is_some()
2496 /// Asserts this is a struct or union and returns its unique variant.
2497 pub fn non_enum_variant(&self) -> &VariantDef {
2498 assert!(self.is_struct() || self.is_union());
2499 &self.variants[VariantIdx::new(0)]
2503 pub fn predicates(&self, tcx: TyCtxt<'tcx>) -> GenericPredicates<'tcx> {
2504 tcx.predicates_of(self.did)
2507 /// Returns an iterator over all fields contained
2510 pub fn all_fields(&self) -> impl Iterator<Item = &FieldDef> + Clone {
2511 self.variants.iter().flat_map(|v| v.fields.iter())
2514 /// Whether the ADT lacks fields. Note that this includes uninhabited enums,
2515 /// e.g., `enum Void {}` is considered payload free as well.
2516 pub fn is_payloadfree(&self) -> bool {
2517 self.variants.iter().all(|v| v.fields.is_empty())
2520 /// Return a `VariantDef` given a variant id.
2521 pub fn variant_with_id(&self, vid: DefId) -> &VariantDef {
2522 self.variants.iter().find(|v| v.def_id == vid).expect("variant_with_id: unknown variant")
2525 /// Return a `VariantDef` given a constructor id.
2526 pub fn variant_with_ctor_id(&self, cid: DefId) -> &VariantDef {
2529 .find(|v| v.ctor_def_id == Some(cid))
2530 .expect("variant_with_ctor_id: unknown variant")
2533 /// Return the index of `VariantDef` given a variant id.
2534 pub fn variant_index_with_id(&self, vid: DefId) -> VariantIdx {
2537 .find(|(_, v)| v.def_id == vid)
2538 .expect("variant_index_with_id: unknown variant")
2542 /// Return the index of `VariantDef` given a constructor id.
2543 pub fn variant_index_with_ctor_id(&self, cid: DefId) -> VariantIdx {
2546 .find(|(_, v)| v.ctor_def_id == Some(cid))
2547 .expect("variant_index_with_ctor_id: unknown variant")
2551 pub fn variant_of_res(&self, res: Res) -> &VariantDef {
2553 Res::Def(DefKind::Variant, vid) => self.variant_with_id(vid),
2554 Res::Def(DefKind::Ctor(..), cid) => self.variant_with_ctor_id(cid),
2555 Res::Def(DefKind::Struct, _)
2556 | Res::Def(DefKind::Union, _)
2557 | Res::Def(DefKind::TyAlias, _)
2558 | Res::Def(DefKind::AssocTy, _)
2560 | Res::SelfCtor(..) => self.non_enum_variant(),
2561 _ => bug!("unexpected res {:?} in variant_of_res", res),
2566 pub fn eval_explicit_discr(&self, tcx: TyCtxt<'tcx>, expr_did: DefId) -> Option<Discr<'tcx>> {
2567 assert!(self.is_enum());
2568 let param_env = tcx.param_env(expr_did);
2569 let repr_type = self.repr.discr_type();
2570 match tcx.const_eval_poly(expr_did) {
2572 let ty = repr_type.to_ty(tcx);
2573 if let Some(b) = val.try_to_bits_for_ty(tcx, param_env, ty) {
2574 trace!("discriminants: {} ({:?})", b, repr_type);
2575 Some(Discr { val: b, ty })
2577 info!("invalid enum discriminant: {:#?}", val);
2578 crate::mir::interpret::struct_error(
2579 tcx.at(tcx.def_span(expr_did)),
2580 "constant evaluation of enum discriminant resulted in non-integer",
2587 let msg = match err {
2588 ErrorHandled::Reported(ErrorReported) | ErrorHandled::Linted => {
2589 "enum discriminant evaluation failed"
2591 ErrorHandled::TooGeneric => "enum discriminant depends on generics",
2593 tcx.sess.delay_span_bug(tcx.def_span(expr_did), msg);
2600 pub fn discriminants(
2603 ) -> impl Iterator<Item = (VariantIdx, Discr<'tcx>)> + Captures<'tcx> {
2604 assert!(self.is_enum());
2605 let repr_type = self.repr.discr_type();
2606 let initial = repr_type.initial_discriminant(tcx);
2607 let mut prev_discr = None::<Discr<'tcx>>;
2608 self.variants.iter_enumerated().map(move |(i, v)| {
2609 let mut discr = prev_discr.map_or(initial, |d| d.wrap_incr(tcx));
2610 if let VariantDiscr::Explicit(expr_did) = v.discr {
2611 if let Some(new_discr) = self.eval_explicit_discr(tcx, expr_did) {
2615 prev_discr = Some(discr);
2622 pub fn variant_range(&self) -> Range<VariantIdx> {
2623 VariantIdx::new(0)..VariantIdx::new(self.variants.len())
2626 /// Computes the discriminant value used by a specific variant.
2627 /// Unlike `discriminants`, this is (amortized) constant-time,
2628 /// only doing at most one query for evaluating an explicit
2629 /// discriminant (the last one before the requested variant),
2630 /// assuming there are no constant-evaluation errors there.
2632 pub fn discriminant_for_variant(
2635 variant_index: VariantIdx,
2637 assert!(self.is_enum());
2638 let (val, offset) = self.discriminant_def_for_variant(variant_index);
2639 let explicit_value = val
2640 .and_then(|expr_did| self.eval_explicit_discr(tcx, expr_did))
2641 .unwrap_or_else(|| self.repr.discr_type().initial_discriminant(tcx));
2642 explicit_value.checked_add(tcx, offset as u128).0
2645 /// Yields a `DefId` for the discriminant and an offset to add to it
2646 /// Alternatively, if there is no explicit discriminant, returns the
2647 /// inferred discriminant directly.
2648 pub fn discriminant_def_for_variant(&self, variant_index: VariantIdx) -> (Option<DefId>, u32) {
2649 assert!(!self.variants.is_empty());
2650 let mut explicit_index = variant_index.as_u32();
2653 match self.variants[VariantIdx::from_u32(explicit_index)].discr {
2654 ty::VariantDiscr::Relative(0) => {
2658 ty::VariantDiscr::Relative(distance) => {
2659 explicit_index -= distance;
2661 ty::VariantDiscr::Explicit(did) => {
2662 expr_did = Some(did);
2667 (expr_did, variant_index.as_u32() - explicit_index)
2670 pub fn destructor(&self, tcx: TyCtxt<'tcx>) -> Option<Destructor> {
2671 tcx.adt_destructor(self.did)
2674 /// Returns a list of types such that `Self: Sized` if and only
2675 /// if that type is `Sized`, or `TyErr` if this type is recursive.
2677 /// Oddly enough, checking that the sized-constraint is `Sized` is
2678 /// actually more expressive than checking all members:
2679 /// the `Sized` trait is inductive, so an associated type that references
2680 /// `Self` would prevent its containing ADT from being `Sized`.
2682 /// Due to normalization being eager, this applies even if
2683 /// the associated type is behind a pointer (e.g., issue #31299).
2684 pub fn sized_constraint(&self, tcx: TyCtxt<'tcx>) -> &'tcx [Ty<'tcx>] {
2685 tcx.adt_sized_constraint(self.did).0
2689 impl<'tcx> FieldDef {
2690 /// Returns the type of this field. The `subst` is typically obtained
2691 /// via the second field of `TyKind::AdtDef`.
2692 pub fn ty(&self, tcx: TyCtxt<'tcx>, subst: SubstsRef<'tcx>) -> Ty<'tcx> {
2693 tcx.type_of(self.did).subst(tcx, subst)
2697 /// Represents the various closure traits in the language. This
2698 /// will determine the type of the environment (`self`, in the
2699 /// desugaring) argument that the closure expects.
2701 /// You can get the environment type of a closure using
2702 /// `tcx.closure_env_ty()`.
2703 #[derive(Clone, Copy, PartialOrd, Ord, PartialEq, Eq, Hash, Debug, TyEncodable, TyDecodable)]
2704 #[derive(HashStable)]
2705 pub enum ClosureKind {
2706 // Warning: Ordering is significant here! The ordering is chosen
2707 // because the trait Fn is a subtrait of FnMut and so in turn, and
2708 // hence we order it so that Fn < FnMut < FnOnce.
2714 impl<'tcx> ClosureKind {
2715 // This is the initial value used when doing upvar inference.
2716 pub const LATTICE_BOTTOM: ClosureKind = ClosureKind::Fn;
2718 pub fn trait_did(&self, tcx: TyCtxt<'tcx>) -> DefId {
2720 ClosureKind::Fn => tcx.require_lang_item(LangItem::Fn, None),
2721 ClosureKind::FnMut => tcx.require_lang_item(LangItem::FnMut, None),
2722 ClosureKind::FnOnce => tcx.require_lang_item(LangItem::FnOnce, None),
2726 /// Returns `true` if a type that impls this closure kind
2727 /// must also implement `other`.
2728 pub fn extends(self, other: ty::ClosureKind) -> bool {
2731 (ClosureKind::Fn, ClosureKind::Fn)
2732 | (ClosureKind::Fn, ClosureKind::FnMut)
2733 | (ClosureKind::Fn, ClosureKind::FnOnce)
2734 | (ClosureKind::FnMut, ClosureKind::FnMut)
2735 | (ClosureKind::FnMut, ClosureKind::FnOnce)
2736 | (ClosureKind::FnOnce, ClosureKind::FnOnce)
2740 /// Returns the representative scalar type for this closure kind.
2741 /// See `TyS::to_opt_closure_kind` for more details.
2742 pub fn to_ty(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
2744 ty::ClosureKind::Fn => tcx.types.i8,
2745 ty::ClosureKind::FnMut => tcx.types.i16,
2746 ty::ClosureKind::FnOnce => tcx.types.i32,
2752 pub fn from_mutbl(m: hir::Mutability) -> BorrowKind {
2754 hir::Mutability::Mut => MutBorrow,
2755 hir::Mutability::Not => ImmBorrow,
2759 /// Returns a mutability `m` such that an `&m T` pointer could be used to obtain this borrow
2760 /// kind. Because borrow kinds are richer than mutabilities, we sometimes have to pick a
2761 /// mutability that is stronger than necessary so that it at least *would permit* the borrow in
2763 pub fn to_mutbl_lossy(self) -> hir::Mutability {
2765 MutBorrow => hir::Mutability::Mut,
2766 ImmBorrow => hir::Mutability::Not,
2768 // We have no type corresponding to a unique imm borrow, so
2769 // use `&mut`. It gives all the capabilities of an `&uniq`
2770 // and hence is a safe "over approximation".
2771 UniqueImmBorrow => hir::Mutability::Mut,
2775 pub fn to_user_str(&self) -> &'static str {
2777 MutBorrow => "mutable",
2778 ImmBorrow => "immutable",
2779 UniqueImmBorrow => "uniquely immutable",
2784 pub type Attributes<'tcx> = &'tcx [ast::Attribute];
2786 #[derive(Debug, PartialEq, Eq)]
2787 pub enum ImplOverlapKind {
2788 /// These impls are always allowed to overlap.
2790 /// Whether or not the impl is permitted due to the trait being a `#[marker]` trait
2793 /// These impls are allowed to overlap, but that raises
2794 /// an issue #33140 future-compatibility warning.
2796 /// Some background: in Rust 1.0, the trait-object types `Send + Sync` (today's
2797 /// `dyn Send + Sync`) and `Sync + Send` (now `dyn Sync + Send`) were different.
2799 /// The widely-used version 0.1.0 of the crate `traitobject` had accidentally relied
2800 /// that difference, making what reduces to the following set of impls:
2804 /// impl Trait for dyn Send + Sync {}
2805 /// impl Trait for dyn Sync + Send {}
2808 /// Obviously, once we made these types be identical, that code causes a coherence
2809 /// error and a fairly big headache for us. However, luckily for us, the trait
2810 /// `Trait` used in this case is basically a marker trait, and therefore having
2811 /// overlapping impls for it is sound.
2813 /// To handle this, we basically regard the trait as a marker trait, with an additional
2814 /// future-compatibility warning. To avoid accidentally "stabilizing" this feature,
2815 /// it has the following restrictions:
2817 /// 1. The trait must indeed be a marker-like trait (i.e., no items), and must be
2819 /// 2. The trait-ref of both impls must be equal.
2820 /// 3. The trait-ref of both impls must be a trait object type consisting only of
2822 /// 4. Neither of the impls can have any where-clauses.
2824 /// Once `traitobject` 0.1.0 is no longer an active concern, this hack can be removed.
2828 impl<'tcx> TyCtxt<'tcx> {
2829 pub fn typeck_body(self, body: hir::BodyId) -> &'tcx TypeckResults<'tcx> {
2830 self.typeck(self.hir().body_owner_def_id(body))
2833 /// Returns an iterator of the `DefId`s for all body-owners in this
2834 /// crate. If you would prefer to iterate over the bodies
2835 /// themselves, you can do `self.hir().krate().body_ids.iter()`.
2836 pub fn body_owners(self) -> impl Iterator<Item = LocalDefId> + Captures<'tcx> + 'tcx {
2841 .map(move |&body_id| self.hir().body_owner_def_id(body_id))
2844 pub fn par_body_owners<F: Fn(LocalDefId) + sync::Sync + sync::Send>(self, f: F) {
2845 par_iter(&self.hir().krate().body_ids)
2846 .for_each(|&body_id| f(self.hir().body_owner_def_id(body_id)));
2849 pub fn provided_trait_methods(self, id: DefId) -> impl 'tcx + Iterator<Item = &'tcx AssocItem> {
2850 self.associated_items(id)
2851 .in_definition_order()
2852 .filter(|item| item.kind == AssocKind::Fn && item.defaultness.has_value())
2855 fn item_name_from_hir(self, def_id: DefId) -> Option<Ident> {
2856 self.hir().get_if_local(def_id).and_then(|node| node.ident())
2859 fn item_name_from_def_id(self, def_id: DefId) -> Option<Symbol> {
2860 if def_id.index == CRATE_DEF_INDEX {
2861 Some(self.original_crate_name(def_id.krate))
2863 let def_key = self.def_key(def_id);
2864 match def_key.disambiguated_data.data {
2865 // The name of a constructor is that of its parent.
2866 rustc_hir::definitions::DefPathData::Ctor => self.item_name_from_def_id(DefId {
2867 krate: def_id.krate,
2868 index: def_key.parent.unwrap(),
2870 _ => def_key.disambiguated_data.data.get_opt_name(),
2875 /// Look up the name of an item across crates. This does not look at HIR.
2877 /// When possible, this function should be used for cross-crate lookups over
2878 /// [`opt_item_name`] to avoid invalidating the incremental cache. If you
2879 /// need to handle items without a name, or HIR items that will not be
2880 /// serialized cross-crate, or if you need the span of the item, use
2881 /// [`opt_item_name`] instead.
2883 /// [`opt_item_name`]: Self::opt_item_name
2884 pub fn item_name(self, id: DefId) -> Symbol {
2885 // Look at cross-crate items first to avoid invalidating the incremental cache
2886 // unless we have to.
2887 self.item_name_from_def_id(id).unwrap_or_else(|| {
2888 bug!("item_name: no name for {:?}", self.def_path(id));
2892 /// Look up the name and span of an item or [`Node`].
2894 /// See [`item_name`][Self::item_name] for more information.
2895 pub fn opt_item_name(self, def_id: DefId) -> Option<Ident> {
2896 // Look at the HIR first so the span will be correct if this is a local item.
2897 self.item_name_from_hir(def_id)
2898 .or_else(|| self.item_name_from_def_id(def_id).map(Ident::with_dummy_span))
2901 pub fn opt_associated_item(self, def_id: DefId) -> Option<&'tcx AssocItem> {
2902 let is_associated_item = if let Some(def_id) = def_id.as_local() {
2904 self.hir().get(self.hir().local_def_id_to_hir_id(def_id)),
2905 Node::TraitItem(_) | Node::ImplItem(_)
2909 self.def_kind(def_id),
2910 DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy
2914 is_associated_item.then(|| self.associated_item(def_id))
2917 pub fn field_index(self, hir_id: hir::HirId, typeck_results: &TypeckResults<'_>) -> usize {
2918 typeck_results.field_indices().get(hir_id).cloned().expect("no index for a field")
2921 pub fn find_field_index(self, ident: Ident, variant: &VariantDef) -> Option<usize> {
2922 variant.fields.iter().position(|field| self.hygienic_eq(ident, field.ident, variant.def_id))
2925 /// Returns `true` if the impls are the same polarity and the trait either
2926 /// has no items or is annotated `#[marker]` and prevents item overrides.
2927 pub fn impls_are_allowed_to_overlap(
2931 ) -> Option<ImplOverlapKind> {
2932 // If either trait impl references an error, they're allowed to overlap,
2933 // as one of them essentially doesn't exist.
2934 if self.impl_trait_ref(def_id1).map_or(false, |tr| tr.references_error())
2935 || self.impl_trait_ref(def_id2).map_or(false, |tr| tr.references_error())
2937 return Some(ImplOverlapKind::Permitted { marker: false });
2940 match (self.impl_polarity(def_id1), self.impl_polarity(def_id2)) {
2941 (ImplPolarity::Reservation, _) | (_, ImplPolarity::Reservation) => {
2942 // `#[rustc_reservation_impl]` impls don't overlap with anything
2944 "impls_are_allowed_to_overlap({:?}, {:?}) = Some(Permitted) (reservations)",
2947 return Some(ImplOverlapKind::Permitted { marker: false });
2949 (ImplPolarity::Positive, ImplPolarity::Negative)
2950 | (ImplPolarity::Negative, ImplPolarity::Positive) => {
2951 // `impl AutoTrait for Type` + `impl !AutoTrait for Type`
2953 "impls_are_allowed_to_overlap({:?}, {:?}) - None (differing polarities)",
2958 (ImplPolarity::Positive, ImplPolarity::Positive)
2959 | (ImplPolarity::Negative, ImplPolarity::Negative) => {}
2962 let is_marker_overlap = {
2963 let is_marker_impl = |def_id: DefId| -> bool {
2964 let trait_ref = self.impl_trait_ref(def_id);
2965 trait_ref.map_or(false, |tr| self.trait_def(tr.def_id).is_marker)
2967 is_marker_impl(def_id1) && is_marker_impl(def_id2)
2970 if is_marker_overlap {
2972 "impls_are_allowed_to_overlap({:?}, {:?}) = Some(Permitted) (marker overlap)",
2975 Some(ImplOverlapKind::Permitted { marker: true })
2977 if let Some(self_ty1) = self.issue33140_self_ty(def_id1) {
2978 if let Some(self_ty2) = self.issue33140_self_ty(def_id2) {
2979 if self_ty1 == self_ty2 {
2981 "impls_are_allowed_to_overlap({:?}, {:?}) - issue #33140 HACK",
2984 return Some(ImplOverlapKind::Issue33140);
2987 "impls_are_allowed_to_overlap({:?}, {:?}) - found {:?} != {:?}",
2988 def_id1, def_id2, self_ty1, self_ty2
2994 debug!("impls_are_allowed_to_overlap({:?}, {:?}) = None", def_id1, def_id2);
2999 /// Returns `ty::VariantDef` if `res` refers to a struct,
3000 /// or variant or their constructors, panics otherwise.
3001 pub fn expect_variant_res(self, res: Res) -> &'tcx VariantDef {
3003 Res::Def(DefKind::Variant, did) => {
3004 let enum_did = self.parent(did).unwrap();
3005 self.adt_def(enum_did).variant_with_id(did)
3007 Res::Def(DefKind::Struct | DefKind::Union, did) => self.adt_def(did).non_enum_variant(),
3008 Res::Def(DefKind::Ctor(CtorOf::Variant, ..), variant_ctor_did) => {
3009 let variant_did = self.parent(variant_ctor_did).unwrap();
3010 let enum_did = self.parent(variant_did).unwrap();
3011 self.adt_def(enum_did).variant_with_ctor_id(variant_ctor_did)
3013 Res::Def(DefKind::Ctor(CtorOf::Struct, ..), ctor_did) => {
3014 let struct_did = self.parent(ctor_did).expect("struct ctor has no parent");
3015 self.adt_def(struct_did).non_enum_variant()
3017 _ => bug!("expect_variant_res used with unexpected res {:?}", res),
3021 /// Returns the possibly-auto-generated MIR of a `(DefId, Subst)` pair.
3022 pub fn instance_mir(self, instance: ty::InstanceDef<'tcx>) -> &'tcx Body<'tcx> {
3024 ty::InstanceDef::Item(def) => self.optimized_mir_opt_const_arg(def),
3025 ty::InstanceDef::VtableShim(..)
3026 | ty::InstanceDef::ReifyShim(..)
3027 | ty::InstanceDef::Intrinsic(..)
3028 | ty::InstanceDef::FnPtrShim(..)
3029 | ty::InstanceDef::Virtual(..)
3030 | ty::InstanceDef::ClosureOnceShim { .. }
3031 | ty::InstanceDef::DropGlue(..)
3032 | ty::InstanceDef::CloneShim(..) => self.mir_shims(instance),
3036 /// Gets the attributes of a definition.
3037 pub fn get_attrs(self, did: DefId) -> Attributes<'tcx> {
3038 if let Some(did) = did.as_local() {
3039 self.hir().attrs(self.hir().local_def_id_to_hir_id(did))
3041 self.item_attrs(did)
3045 /// Determines whether an item is annotated with an attribute.
3046 pub fn has_attr(self, did: DefId, attr: Symbol) -> bool {
3047 self.sess.contains_name(&self.get_attrs(did), attr)
3050 /// Returns `true` if this is an `auto trait`.
3051 pub fn trait_is_auto(self, trait_def_id: DefId) -> bool {
3052 self.trait_def(trait_def_id).has_auto_impl
3055 pub fn generator_layout(self, def_id: DefId) -> &'tcx GeneratorLayout<'tcx> {
3056 self.optimized_mir(def_id).generator_layout.as_ref().unwrap()
3059 /// Given the `DefId` of an impl, returns the `DefId` of the trait it implements.
3060 /// If it implements no trait, returns `None`.
3061 pub fn trait_id_of_impl(self, def_id: DefId) -> Option<DefId> {
3062 self.impl_trait_ref(def_id).map(|tr| tr.def_id)
3065 /// If the given defid describes a method belonging to an impl, returns the
3066 /// `DefId` of the impl that the method belongs to; otherwise, returns `None`.
3067 pub fn impl_of_method(self, def_id: DefId) -> Option<DefId> {
3068 self.opt_associated_item(def_id).and_then(|trait_item| match trait_item.container {
3069 TraitContainer(_) => None,
3070 ImplContainer(def_id) => Some(def_id),
3074 /// Looks up the span of `impl_did` if the impl is local; otherwise returns `Err`
3075 /// with the name of the crate containing the impl.
3076 pub fn span_of_impl(self, impl_did: DefId) -> Result<Span, Symbol> {
3077 if let Some(impl_did) = impl_did.as_local() {
3078 let hir_id = self.hir().local_def_id_to_hir_id(impl_did);
3079 Ok(self.hir().span(hir_id))
3081 Err(self.crate_name(impl_did.krate))
3085 /// Hygienically compares a use-site name (`use_name`) for a field or an associated item with
3086 /// its supposed definition name (`def_name`). The method also needs `DefId` of the supposed
3087 /// definition's parent/scope to perform comparison.
3088 pub fn hygienic_eq(self, use_name: Ident, def_name: Ident, def_parent_def_id: DefId) -> bool {
3089 // We could use `Ident::eq` here, but we deliberately don't. The name
3090 // comparison fails frequently, and we want to avoid the expensive
3091 // `normalize_to_macros_2_0()` calls required for the span comparison whenever possible.
3092 use_name.name == def_name.name
3096 .hygienic_eq(def_name.span.ctxt(), self.expansion_that_defined(def_parent_def_id))
3099 pub fn expansion_that_defined(self, scope: DefId) -> ExpnId {
3100 match scope.as_local() {
3101 // Parsing and expansion aren't incremental, so we don't
3102 // need to go through a query for the same-crate case.
3103 Some(scope) => self.hir().definitions().expansion_that_defined(scope),
3104 None => self.expn_that_defined(scope),
3108 pub fn adjust_ident(self, mut ident: Ident, scope: DefId) -> Ident {
3109 ident.span.normalize_to_macros_2_0_and_adjust(self.expansion_that_defined(scope));
3113 pub fn adjust_ident_and_get_scope(
3118 ) -> (Ident, DefId) {
3120 match ident.span.normalize_to_macros_2_0_and_adjust(self.expansion_that_defined(scope))
3122 Some(actual_expansion) => {
3123 self.hir().definitions().parent_module_of_macro_def(actual_expansion)
3125 None => self.parent_module(block).to_def_id(),
3130 pub fn is_object_safe(self, key: DefId) -> bool {
3131 self.object_safety_violations(key).is_empty()
3135 #[derive(Clone, HashStable)]
3136 pub struct AdtSizedConstraint<'tcx>(pub &'tcx [Ty<'tcx>]);
3138 /// Yields the parent function's `DefId` if `def_id` is an `impl Trait` definition.
3139 pub fn is_impl_trait_defn(tcx: TyCtxt<'_>, def_id: DefId) -> Option<DefId> {
3140 if let Some(def_id) = def_id.as_local() {
3141 if let Node::Item(item) = tcx.hir().get(tcx.hir().local_def_id_to_hir_id(def_id)) {
3142 if let hir::ItemKind::OpaqueTy(ref opaque_ty) = item.kind {
3143 return opaque_ty.impl_trait_fn;
3150 pub fn provide(providers: &mut ty::query::Providers) {
3151 context::provide(providers);
3152 erase_regions::provide(providers);
3153 layout::provide(providers);
3154 util::provide(providers);
3155 print::provide(providers);
3156 super::util::bug::provide(providers);
3157 *providers = ty::query::Providers {
3158 trait_impls_of: trait_def::trait_impls_of_provider,
3159 all_local_trait_impls: trait_def::all_local_trait_impls,
3164 /// A map for the local crate mapping each type to a vector of its
3165 /// inherent impls. This is not meant to be used outside of coherence;
3166 /// rather, you should request the vector for a specific type via
3167 /// `tcx.inherent_impls(def_id)` so as to minimize your dependencies
3168 /// (constructing this map requires touching the entire crate).
3169 #[derive(Clone, Debug, Default, HashStable)]
3170 pub struct CrateInherentImpls {
3171 pub inherent_impls: DefIdMap<Vec<DefId>>,
3174 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, HashStable)]
3175 pub struct SymbolName<'tcx> {
3176 /// `&str` gives a consistent ordering, which ensures reproducible builds.
3177 pub name: &'tcx str,
3180 impl<'tcx> SymbolName<'tcx> {
3181 pub fn new(tcx: TyCtxt<'tcx>, name: &str) -> SymbolName<'tcx> {
3183 name: unsafe { str::from_utf8_unchecked(tcx.arena.alloc_slice(name.as_bytes())) },
3188 impl<'tcx> fmt::Display for SymbolName<'tcx> {
3189 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
3190 fmt::Display::fmt(&self.name, fmt)
3194 impl<'tcx> fmt::Debug for SymbolName<'tcx> {
3195 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
3196 fmt::Display::fmt(&self.name, fmt)