1 //! Defines how the compiler represents types internally.
3 //! Two important entities in this module are:
5 //! - [`rustc_middle::ty::Ty`], used to represent the semantics of a type.
6 //! - [`rustc_middle::ty::TyCtxt`], the central data structure in the compiler.
8 //! For more information, see ["The `ty` module: representing types"] in the ructc-dev-guide.
10 //! ["The `ty` module: representing types"]: https://rustc-dev-guide.rust-lang.org/ty.html
12 // ignore-tidy-filelength
13 pub use self::fold::{TypeFoldable, TypeFolder, TypeVisitor};
14 pub use self::AssocItemContainer::*;
15 pub use self::BorrowKind::*;
16 pub use self::IntVarValue::*;
17 pub use self::Variance::*;
19 use crate::hir::exports::ExportMap;
20 use crate::hir::place::{
21 Place as HirPlace, PlaceBase as HirPlaceBase, ProjectionKind as HirProjectionKind,
23 use crate::ich::StableHashingContext;
24 use crate::middle::cstore::CrateStoreDyn;
25 use crate::middle::resolve_lifetime::ObjectLifetimeDefault;
26 use crate::mir::interpret::ErrorHandled;
28 use crate::mir::GeneratorLayout;
29 use crate::traits::{self, Reveal};
31 use crate::ty::subst::{GenericArg, InternalSubsts, Subst, SubstsRef};
32 use crate::ty::util::{Discr, IntTypeExt};
34 use rustc_attr as attr;
35 use rustc_data_structures::captures::Captures;
36 use rustc_data_structures::fingerprint::Fingerprint;
37 use rustc_data_structures::fx::FxHashMap;
38 use rustc_data_structures::fx::FxHashSet;
39 use rustc_data_structures::fx::FxIndexMap;
40 use rustc_data_structures::sorted_map::SortedIndexMultiMap;
41 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
42 use rustc_data_structures::sync::{self, par_iter, ParallelIterator};
43 use rustc_data_structures::tagged_ptr::CopyTaggedPtr;
44 use rustc_errors::ErrorReported;
46 use rustc_hir::def::{CtorKind, CtorOf, DefKind, Namespace, Res};
47 use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, LocalDefId, CRATE_DEF_INDEX};
48 use rustc_hir::lang_items::LangItem;
49 use rustc_hir::{Constness, Node};
50 use rustc_index::vec::{Idx, IndexVec};
51 use rustc_macros::HashStable;
52 use rustc_serialize::{self, Encodable, Encoder};
53 use rustc_session::DataTypeKind;
54 use rustc_span::hygiene::ExpnId;
55 use rustc_span::symbol::{kw, sym, Ident, Symbol};
57 use rustc_target::abi::{Align, VariantIdx};
59 use std::cell::RefCell;
60 use std::cmp::Ordering;
62 use std::hash::{Hash, Hasher};
63 use std::ops::{ControlFlow, Range};
67 pub use self::sty::BoundRegionKind::*;
68 pub use self::sty::RegionKind;
69 pub use self::sty::RegionKind::*;
70 pub use self::sty::TyKind::*;
71 pub use self::sty::{Binder, BoundTy, BoundTyKind, BoundVar};
72 pub use self::sty::{BoundRegion, BoundRegionKind, EarlyBoundRegion, FreeRegion, Region};
73 pub use self::sty::{CanonicalPolyFnSig, FnSig, GenSig, PolyFnSig, PolyGenSig};
74 pub use self::sty::{ClosureSubsts, GeneratorSubsts, TypeAndMut, UpvarSubsts};
75 pub use self::sty::{ClosureSubstsParts, GeneratorSubstsParts};
76 pub use self::sty::{ConstVid, RegionVid};
77 pub use self::sty::{ExistentialPredicate, ParamConst, ParamTy, ProjectionTy};
78 pub use self::sty::{ExistentialProjection, PolyExistentialProjection};
79 pub use self::sty::{ExistentialTraitRef, PolyExistentialTraitRef};
80 pub use self::sty::{PolyTraitRef, TraitRef, TyKind};
81 pub use crate::ty::diagnostics::*;
82 pub use rustc_type_ir::InferTy::*;
83 pub use rustc_type_ir::*;
85 pub use self::binding::BindingMode;
86 pub use self::binding::BindingMode::*;
88 pub use self::context::{tls, FreeRegionInfo, TyCtxt};
89 pub use self::context::{
90 CanonicalUserType, CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations,
91 DelaySpanBugEmitted, ResolvedOpaqueTy, UserType, UserTypeAnnotationIndex,
93 pub use self::context::{
94 CtxtInterners, GeneratorInteriorTypeCause, GlobalCtxt, Lift, TypeckResults,
97 pub use self::instance::{Instance, InstanceDef};
99 pub use self::list::List;
101 pub use self::trait_def::TraitDef;
103 pub use self::query::queries;
105 pub use self::consts::{Const, ConstInt, ConstKind, InferConst, ScalarInt};
117 pub mod inhabitedness;
119 pub mod normalize_erasing_regions;
134 mod structural_impls;
139 pub struct ResolverOutputs {
140 pub definitions: rustc_hir::definitions::Definitions,
141 pub cstore: Box<CrateStoreDyn>,
142 pub visibilities: FxHashMap<LocalDefId, Visibility>,
143 pub extern_crate_map: FxHashMap<LocalDefId, CrateNum>,
144 pub maybe_unused_trait_imports: FxHashSet<LocalDefId>,
145 pub maybe_unused_extern_crates: Vec<(LocalDefId, Span)>,
146 pub export_map: ExportMap<LocalDefId>,
147 pub glob_map: FxHashMap<LocalDefId, FxHashSet<Symbol>>,
148 /// Extern prelude entries. The value is `true` if the entry was introduced
149 /// via `extern crate` item and not `--extern` option or compiler built-in.
150 pub extern_prelude: FxHashMap<Symbol, bool>,
153 #[derive(Clone, Copy, PartialEq, Eq, Debug, HashStable, Hash)]
154 pub enum AssocItemContainer {
155 TraitContainer(DefId),
156 ImplContainer(DefId),
159 impl AssocItemContainer {
160 /// Asserts that this is the `DefId` of an associated item declared
161 /// in a trait, and returns the trait `DefId`.
162 pub fn assert_trait(&self) -> DefId {
164 TraitContainer(id) => id,
165 _ => bug!("associated item has wrong container type: {:?}", self),
169 pub fn id(&self) -> DefId {
171 TraitContainer(id) => id,
172 ImplContainer(id) => id,
177 /// The "header" of an impl is everything outside the body: a Self type, a trait
178 /// ref (in the case of a trait impl), and a set of predicates (from the
179 /// bounds / where-clauses).
180 #[derive(Clone, Debug, TypeFoldable)]
181 pub struct ImplHeader<'tcx> {
182 pub impl_def_id: DefId,
183 pub self_ty: Ty<'tcx>,
184 pub trait_ref: Option<TraitRef<'tcx>>,
185 pub predicates: Vec<Predicate<'tcx>>,
188 #[derive(Copy, Clone, PartialEq, TyEncodable, TyDecodable, HashStable, Debug)]
189 pub enum ImplPolarity {
190 /// `impl Trait for Type`
192 /// `impl !Trait for Type`
194 /// `#[rustc_reservation_impl] impl Trait for Type`
196 /// This is a "stability hack", not a real Rust feature.
197 /// See #64631 for details.
201 #[derive(Copy, Clone, Debug, PartialEq, HashStable, Eq, Hash)]
202 pub struct AssocItem {
204 #[stable_hasher(project(name))]
208 pub defaultness: hir::Defaultness,
209 pub container: AssocItemContainer,
211 /// Whether this is a method with an explicit self
212 /// as its first parameter, allowing method calls.
213 pub fn_has_self_parameter: bool,
216 #[derive(Copy, Clone, PartialEq, Debug, HashStable, Eq, Hash)]
224 pub fn namespace(&self) -> Namespace {
226 ty::AssocKind::Type => Namespace::TypeNS,
227 ty::AssocKind::Const | ty::AssocKind::Fn => Namespace::ValueNS,
231 pub fn as_def_kind(&self) -> DefKind {
233 AssocKind::Const => DefKind::AssocConst,
234 AssocKind::Fn => DefKind::AssocFn,
235 AssocKind::Type => DefKind::AssocTy,
241 pub fn signature(&self, tcx: TyCtxt<'_>) -> String {
243 ty::AssocKind::Fn => {
244 // We skip the binder here because the binder would deanonymize all
245 // late-bound regions, and we don't want method signatures to show up
246 // `as for<'r> fn(&'r MyType)`. Pretty-printing handles late-bound
247 // regions just fine, showing `fn(&MyType)`.
248 tcx.fn_sig(self.def_id).skip_binder().to_string()
250 ty::AssocKind::Type => format!("type {};", self.ident),
251 ty::AssocKind::Const => {
252 format!("const {}: {:?};", self.ident, tcx.type_of(self.def_id))
258 /// A list of `ty::AssocItem`s in definition order that allows for efficient lookup by name.
260 /// When doing lookup by name, we try to postpone hygienic comparison for as long as possible since
261 /// it is relatively expensive. Instead, items are indexed by `Symbol` and hygienic comparison is
262 /// done only on items with the same name.
263 #[derive(Debug, Clone, PartialEq, HashStable)]
264 pub struct AssociatedItems<'tcx> {
265 items: SortedIndexMultiMap<u32, Symbol, &'tcx ty::AssocItem>,
268 impl<'tcx> AssociatedItems<'tcx> {
269 /// Constructs an `AssociatedItems` map from a series of `ty::AssocItem`s in definition order.
270 pub fn new(items_in_def_order: impl IntoIterator<Item = &'tcx ty::AssocItem>) -> Self {
271 let items = items_in_def_order.into_iter().map(|item| (item.ident.name, item)).collect();
272 AssociatedItems { items }
275 /// Returns a slice of associated items in the order they were defined.
277 /// New code should avoid relying on definition order. If you need a particular associated item
278 /// for a known trait, make that trait a lang item instead of indexing this array.
279 pub fn in_definition_order(&self) -> impl '_ + Iterator<Item = &ty::AssocItem> {
280 self.items.iter().map(|(_, v)| *v)
283 pub fn len(&self) -> usize {
287 /// Returns an iterator over all associated items with the given name, ignoring hygiene.
288 pub fn filter_by_name_unhygienic(
291 ) -> impl '_ + Iterator<Item = &ty::AssocItem> {
292 self.items.get_by_key(&name).copied()
295 /// Returns an iterator over all associated items with the given name.
297 /// Multiple items may have the same name if they are in different `Namespace`s. For example,
298 /// an associated type can have the same name as a method. Use one of the `find_by_name_and_*`
299 /// methods below if you know which item you are looking for.
300 pub fn filter_by_name(
304 parent_def_id: DefId,
305 ) -> impl 'a + Iterator<Item = &'a ty::AssocItem> {
306 self.filter_by_name_unhygienic(ident.name)
307 .filter(move |item| tcx.hygienic_eq(ident, item.ident, parent_def_id))
310 /// Returns the associated item with the given name and `AssocKind`, if one exists.
311 pub fn find_by_name_and_kind(
316 parent_def_id: DefId,
317 ) -> Option<&ty::AssocItem> {
318 self.filter_by_name_unhygienic(ident.name)
319 .filter(|item| item.kind == kind)
320 .find(|item| tcx.hygienic_eq(ident, item.ident, parent_def_id))
323 /// Returns the associated item with the given name in the given `Namespace`, if one exists.
324 pub fn find_by_name_and_namespace(
329 parent_def_id: DefId,
330 ) -> Option<&ty::AssocItem> {
331 self.filter_by_name_unhygienic(ident.name)
332 .filter(|item| item.kind.namespace() == ns)
333 .find(|item| tcx.hygienic_eq(ident, item.ident, parent_def_id))
337 #[derive(Clone, Debug, PartialEq, Eq, Copy, Hash, TyEncodable, TyDecodable, HashStable)]
338 pub enum Visibility {
339 /// Visible everywhere (including in other crates).
341 /// Visible only in the given crate-local module.
343 /// Not visible anywhere in the local crate. This is the visibility of private external items.
347 pub trait DefIdTree: Copy {
348 fn parent(self, id: DefId) -> Option<DefId>;
350 fn is_descendant_of(self, mut descendant: DefId, ancestor: DefId) -> bool {
351 if descendant.krate != ancestor.krate {
355 while descendant != ancestor {
356 match self.parent(descendant) {
357 Some(parent) => descendant = parent,
358 None => return false,
365 impl<'tcx> DefIdTree for TyCtxt<'tcx> {
366 fn parent(self, id: DefId) -> Option<DefId> {
367 self.def_key(id).parent.map(|index| DefId { index, ..id })
372 pub fn from_hir(visibility: &hir::Visibility<'_>, id: hir::HirId, tcx: TyCtxt<'_>) -> Self {
373 match visibility.node {
374 hir::VisibilityKind::Public => Visibility::Public,
375 hir::VisibilityKind::Crate(_) => Visibility::Restricted(DefId::local(CRATE_DEF_INDEX)),
376 hir::VisibilityKind::Restricted { ref path, .. } => match path.res {
377 // If there is no resolution, `resolve` will have already reported an error, so
378 // assume that the visibility is public to avoid reporting more privacy errors.
379 Res::Err => Visibility::Public,
380 def => Visibility::Restricted(def.def_id()),
382 hir::VisibilityKind::Inherited => {
383 Visibility::Restricted(tcx.parent_module(id).to_def_id())
388 /// Returns `true` if an item with this visibility is accessible from the given block.
389 pub fn is_accessible_from<T: DefIdTree>(self, module: DefId, tree: T) -> bool {
390 let restriction = match self {
391 // Public items are visible everywhere.
392 Visibility::Public => return true,
393 // Private items from other crates are visible nowhere.
394 Visibility::Invisible => return false,
395 // Restricted items are visible in an arbitrary local module.
396 Visibility::Restricted(other) if other.krate != module.krate => return false,
397 Visibility::Restricted(module) => module,
400 tree.is_descendant_of(module, restriction)
403 /// Returns `true` if this visibility is at least as accessible as the given visibility
404 pub fn is_at_least<T: DefIdTree>(self, vis: Visibility, tree: T) -> bool {
405 let vis_restriction = match vis {
406 Visibility::Public => return self == Visibility::Public,
407 Visibility::Invisible => return true,
408 Visibility::Restricted(module) => module,
411 self.is_accessible_from(vis_restriction, tree)
414 // Returns `true` if this item is visible anywhere in the local crate.
415 pub fn is_visible_locally(self) -> bool {
417 Visibility::Public => true,
418 Visibility::Restricted(def_id) => def_id.is_local(),
419 Visibility::Invisible => false,
424 /// The crate variances map is computed during typeck and contains the
425 /// variance of every item in the local crate. You should not use it
426 /// directly, because to do so will make your pass dependent on the
427 /// HIR of every item in the local crate. Instead, use
428 /// `tcx.variances_of()` to get the variance for a *particular*
430 #[derive(HashStable, Debug)]
431 pub struct CrateVariancesMap<'tcx> {
432 /// For each item with generics, maps to a vector of the variance
433 /// of its generics. If an item has no generics, it will have no
435 pub variances: FxHashMap<DefId, &'tcx [ty::Variance]>,
438 // Contains information needed to resolve types and (in the future) look up
439 // the types of AST nodes.
440 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
441 pub struct CReaderCacheKey {
446 #[allow(rustc::usage_of_ty_tykind)]
447 pub struct TyS<'tcx> {
448 /// This field shouldn't be used directly and may be removed in the future.
449 /// Use `TyS::kind()` instead.
451 /// This field shouldn't be used directly and may be removed in the future.
452 /// Use `TyS::flags()` instead.
455 /// This is a kind of confusing thing: it stores the smallest
458 /// (a) the binder itself captures nothing but
459 /// (b) all the late-bound things within the type are captured
460 /// by some sub-binder.
462 /// So, for a type without any late-bound things, like `u32`, this
463 /// will be *innermost*, because that is the innermost binder that
464 /// captures nothing. But for a type `&'D u32`, where `'D` is a
465 /// late-bound region with De Bruijn index `D`, this would be `D + 1`
466 /// -- the binder itself does not capture `D`, but `D` is captured
467 /// by an inner binder.
469 /// We call this concept an "exclusive" binder `D` because all
470 /// De Bruijn indices within the type are contained within `0..D`
472 outer_exclusive_binder: ty::DebruijnIndex,
475 impl<'tcx> TyS<'tcx> {
476 /// A constructor used only for internal testing.
477 #[allow(rustc::usage_of_ty_tykind)]
478 pub fn make_for_test(
481 outer_exclusive_binder: ty::DebruijnIndex,
483 TyS { kind, flags, outer_exclusive_binder }
487 // `TyS` is used a lot. Make sure it doesn't unintentionally get bigger.
488 #[cfg(target_arch = "x86_64")]
489 static_assert_size!(TyS<'_>, 32);
491 impl<'tcx> Ord for TyS<'tcx> {
492 fn cmp(&self, other: &TyS<'tcx>) -> Ordering {
493 self.kind().cmp(other.kind())
497 impl<'tcx> PartialOrd for TyS<'tcx> {
498 fn partial_cmp(&self, other: &TyS<'tcx>) -> Option<Ordering> {
499 Some(self.kind().cmp(other.kind()))
503 impl<'tcx> PartialEq for TyS<'tcx> {
505 fn eq(&self, other: &TyS<'tcx>) -> bool {
509 impl<'tcx> Eq for TyS<'tcx> {}
511 impl<'tcx> Hash for TyS<'tcx> {
512 fn hash<H: Hasher>(&self, s: &mut H) {
513 (self as *const TyS<'_>).hash(s)
517 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for TyS<'tcx> {
518 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
522 // The other fields just provide fast access to information that is
523 // also contained in `kind`, so no need to hash them.
526 outer_exclusive_binder: _,
529 kind.hash_stable(hcx, hasher);
533 #[rustc_diagnostic_item = "Ty"]
534 pub type Ty<'tcx> = &'tcx TyS<'tcx>;
548 pub struct UpvarPath {
549 pub hir_id: hir::HirId,
552 /// Upvars do not get their own `NodeId`. Instead, we use the pair of
553 /// the original var ID (that is, the root variable that is referenced
554 /// by the upvar) and the ID of the closure expression.
555 #[derive(Clone, Copy, PartialEq, Eq, Hash, TyEncodable, TyDecodable, TypeFoldable, HashStable)]
557 pub var_path: UpvarPath,
558 pub closure_expr_id: LocalDefId,
562 pub fn new(var_hir_id: hir::HirId, closure_def_id: LocalDefId) -> UpvarId {
563 UpvarId { var_path: UpvarPath { hir_id: var_hir_id }, closure_expr_id: closure_def_id }
567 #[derive(Clone, PartialEq, Debug, TyEncodable, TyDecodable, TypeFoldable, Copy, HashStable)]
568 pub enum BorrowKind {
569 /// Data must be immutable and is aliasable.
572 /// Data must be immutable but not aliasable. This kind of borrow
573 /// cannot currently be expressed by the user and is used only in
574 /// implicit closure bindings. It is needed when the closure
575 /// is borrowing or mutating a mutable referent, e.g.:
578 /// let x: &mut isize = ...;
579 /// let y = || *x += 5;
582 /// If we were to try to translate this closure into a more explicit
583 /// form, we'd encounter an error with the code as written:
586 /// struct Env { x: & &mut isize }
587 /// let x: &mut isize = ...;
588 /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
589 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
592 /// This is then illegal because you cannot mutate a `&mut` found
593 /// in an aliasable location. To solve, you'd have to translate with
594 /// an `&mut` borrow:
597 /// struct Env { x: & &mut isize }
598 /// let x: &mut isize = ...;
599 /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
600 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
603 /// Now the assignment to `**env.x` is legal, but creating a
604 /// mutable pointer to `x` is not because `x` is not mutable. We
605 /// could fix this by declaring `x` as `let mut x`. This is ok in
606 /// user code, if awkward, but extra weird for closures, since the
607 /// borrow is hidden.
609 /// So we introduce a "unique imm" borrow -- the referent is
610 /// immutable, but not aliasable. This solves the problem. For
611 /// simplicity, we don't give users the way to express this
612 /// borrow, it's just used when translating closures.
615 /// Data is mutable and not aliasable.
619 /// Information describing the capture of an upvar. This is computed
620 /// during `typeck`, specifically by `regionck`.
621 #[derive(PartialEq, Clone, Debug, Copy, TyEncodable, TyDecodable, TypeFoldable, HashStable)]
622 pub enum UpvarCapture<'tcx> {
623 /// Upvar is captured by value. This is always true when the
624 /// closure is labeled `move`, but can also be true in other cases
625 /// depending on inference.
627 /// If the upvar was inferred to be captured by value (e.g. `move`
628 /// was not used), then the `Span` points to a usage that
629 /// required it. There may be more than one such usage
630 /// (e.g. `|| { a; a; }`), in which case we pick an
632 ByValue(Option<Span>),
634 /// Upvar is captured by reference.
635 ByRef(UpvarBorrow<'tcx>),
638 #[derive(PartialEq, Clone, Copy, TyEncodable, TyDecodable, TypeFoldable, HashStable)]
639 pub struct UpvarBorrow<'tcx> {
640 /// The kind of borrow: by-ref upvars have access to shared
641 /// immutable borrows, which are not part of the normal language
643 pub kind: BorrowKind,
645 /// Region of the resulting reference.
646 pub region: ty::Region<'tcx>,
649 /// Given the closure DefId this map provides a map of root variables to minimum
650 /// set of `CapturedPlace`s that need to be tracked to support all captures of that closure.
651 pub type MinCaptureInformationMap<'tcx> = FxHashMap<DefId, RootVariableMinCaptureList<'tcx>>;
653 /// Part of `MinCaptureInformationMap`; Maps a root variable to the list of `CapturedPlace`.
654 /// Used to track the minimum set of `Place`s that need to be captured to support all
655 /// Places captured by the closure starting at a given root variable.
657 /// This provides a convenient and quick way of checking if a variable being used within
658 /// a closure is a capture of a local variable.
659 pub type RootVariableMinCaptureList<'tcx> = FxIndexMap<hir::HirId, MinCaptureList<'tcx>>;
661 /// Part of `MinCaptureInformationMap`; List of `CapturePlace`s.
662 pub type MinCaptureList<'tcx> = Vec<CapturedPlace<'tcx>>;
664 /// A `Place` and the corresponding `CaptureInfo`.
665 #[derive(PartialEq, Clone, Debug, TyEncodable, TyDecodable, TypeFoldable, HashStable)]
666 pub struct CapturedPlace<'tcx> {
667 pub place: HirPlace<'tcx>,
668 pub info: CaptureInfo<'tcx>,
671 pub fn place_to_string_for_capture(tcx: TyCtxt<'tcx>, place: &HirPlace<'tcx>) -> String {
672 let name = match place.base {
673 HirPlaceBase::Upvar(upvar_id) => tcx.hir().name(upvar_id.var_path.hir_id).to_string(),
674 _ => bug!("Capture_information should only contain upvars"),
676 let mut curr_string = name;
678 for (i, proj) in place.projections.iter().enumerate() {
680 HirProjectionKind::Deref => {
681 curr_string = format!("*{}", curr_string);
683 HirProjectionKind::Field(idx, variant) => match place.ty_before_projection(i).kind() {
684 ty::Adt(def, ..) => {
685 curr_string = format!(
688 def.variants[variant].fields[idx as usize].ident.name.as_str()
692 curr_string = format!("{}.{}", curr_string, idx);
696 "Field projection applied to a type other than Adt or Tuple: {:?}.",
697 place.ty_before_projection(i).kind()
701 proj => bug!("{:?} unexpected because it isn't captured", proj),
705 curr_string.to_string()
708 /// Part of `MinCaptureInformationMap`; describes the capture kind (&, &mut, move)
709 /// for a particular capture as well as identifying the part of the source code
710 /// that triggered this capture to occur.
711 #[derive(PartialEq, Clone, Debug, Copy, TyEncodable, TyDecodable, TypeFoldable, HashStable)]
712 pub struct CaptureInfo<'tcx> {
713 /// Expr Id pointing to use that resulted in selecting the current capture kind
717 /// let mut t = (0,1);
720 /// println!("{}",t); // L1
724 /// `capture_kind_expr_id` will point to the use on L2 and `path_expr_id` will point to the
727 /// If the user doesn't enable feature `capture_disjoint_fields` (RFC 2229) then, it is
728 /// possible that we don't see the use of a particular place resulting in capture_kind_expr_id being
729 /// None. In such case we fallback on uvpars_mentioned for span.
740 /// In this example, if `capture_disjoint_fields` is **not** set, then x will be captured,
741 /// but we won't see it being used during capture analysis, since it's essentially a discard.
742 pub capture_kind_expr_id: Option<hir::HirId>,
743 /// Expr Id pointing to use that resulted the corresponding place being captured
745 /// See `capture_kind_expr_id` for example.
747 pub path_expr_id: Option<hir::HirId>,
749 /// Capture mode that was selected
750 pub capture_kind: UpvarCapture<'tcx>,
753 pub type UpvarListMap = FxHashMap<DefId, FxIndexMap<hir::HirId, UpvarId>>;
754 pub type UpvarCaptureMap<'tcx> = FxHashMap<UpvarId, UpvarCapture<'tcx>>;
756 impl ty::EarlyBoundRegion {
757 /// Does this early bound region have a name? Early bound regions normally
758 /// always have names except when using anonymous lifetimes (`'_`).
759 pub fn has_name(&self) -> bool {
760 self.name != kw::UnderscoreLifetime
764 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable)]
765 pub enum GenericParamDefKind {
769 object_lifetime_default: ObjectLifetimeDefault,
770 synthetic: Option<hir::SyntheticTyParamKind>,
775 impl GenericParamDefKind {
776 pub fn descr(&self) -> &'static str {
778 GenericParamDefKind::Lifetime => "lifetime",
779 GenericParamDefKind::Type { .. } => "type",
780 GenericParamDefKind::Const => "constant",
783 pub fn to_ord(&self, tcx: TyCtxt<'_>) -> ast::ParamKindOrd {
785 GenericParamDefKind::Lifetime => ast::ParamKindOrd::Lifetime,
786 GenericParamDefKind::Type { .. } => ast::ParamKindOrd::Type,
787 GenericParamDefKind::Const => {
788 ast::ParamKindOrd::Const { unordered: tcx.features().const_generics }
794 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable)]
795 pub struct GenericParamDef {
800 /// `pure_wrt_drop`, set by the (unsafe) `#[may_dangle]` attribute
801 /// on generic parameter `'a`/`T`, asserts data behind the parameter
802 /// `'a`/`T` won't be accessed during the parent type's `Drop` impl.
803 pub pure_wrt_drop: bool,
805 pub kind: GenericParamDefKind,
808 impl GenericParamDef {
809 pub fn to_early_bound_region_data(&self) -> ty::EarlyBoundRegion {
810 if let GenericParamDefKind::Lifetime = self.kind {
811 ty::EarlyBoundRegion { def_id: self.def_id, index: self.index, name: self.name }
813 bug!("cannot convert a non-lifetime parameter def to an early bound region")
819 pub struct GenericParamCount {
820 pub lifetimes: usize,
825 /// Information about the formal type/lifetime parameters associated
826 /// with an item or method. Analogous to `hir::Generics`.
828 /// The ordering of parameters is the same as in `Subst` (excluding child generics):
829 /// `Self` (optionally), `Lifetime` params..., `Type` params...
830 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable)]
831 pub struct Generics {
832 pub parent: Option<DefId>,
833 pub parent_count: usize,
834 pub params: Vec<GenericParamDef>,
836 /// Reverse map to the `index` field of each `GenericParamDef`.
837 #[stable_hasher(ignore)]
838 pub param_def_id_to_index: FxHashMap<DefId, u32>,
841 pub has_late_bound_regions: Option<Span>,
844 impl<'tcx> Generics {
845 pub fn count(&self) -> usize {
846 self.parent_count + self.params.len()
849 pub fn own_counts(&self) -> GenericParamCount {
850 // We could cache this as a property of `GenericParamCount`, but
851 // the aim is to refactor this away entirely eventually and the
852 // presence of this method will be a constant reminder.
853 let mut own_counts = GenericParamCount::default();
855 for param in &self.params {
857 GenericParamDefKind::Lifetime => own_counts.lifetimes += 1,
858 GenericParamDefKind::Type { .. } => own_counts.types += 1,
859 GenericParamDefKind::Const => own_counts.consts += 1,
866 pub fn own_defaults(&self) -> GenericParamCount {
867 let mut own_defaults = GenericParamCount::default();
869 for param in &self.params {
871 GenericParamDefKind::Lifetime => (),
872 GenericParamDefKind::Type { has_default, .. } => {
873 own_defaults.types += has_default as usize;
875 GenericParamDefKind::Const => {
876 // FIXME(const_generics:defaults)
884 pub fn requires_monomorphization(&self, tcx: TyCtxt<'tcx>) -> bool {
885 if self.own_requires_monomorphization() {
889 if let Some(parent_def_id) = self.parent {
890 let parent = tcx.generics_of(parent_def_id);
891 parent.requires_monomorphization(tcx)
897 pub fn own_requires_monomorphization(&self) -> bool {
898 for param in &self.params {
900 GenericParamDefKind::Type { .. } | GenericParamDefKind::Const => return true,
901 GenericParamDefKind::Lifetime => {}
907 /// Returns the `GenericParamDef` with the given index.
908 pub fn param_at(&'tcx self, param_index: usize, tcx: TyCtxt<'tcx>) -> &'tcx GenericParamDef {
909 if let Some(index) = param_index.checked_sub(self.parent_count) {
912 tcx.generics_of(self.parent.expect("parent_count > 0 but no parent?"))
913 .param_at(param_index, tcx)
917 /// Returns the `GenericParamDef` associated with this `EarlyBoundRegion`.
920 param: &EarlyBoundRegion,
922 ) -> &'tcx GenericParamDef {
923 let param = self.param_at(param.index as usize, tcx);
925 GenericParamDefKind::Lifetime => param,
926 _ => bug!("expected lifetime parameter, but found another generic parameter"),
930 /// Returns the `GenericParamDef` associated with this `ParamTy`.
931 pub fn type_param(&'tcx self, param: &ParamTy, tcx: TyCtxt<'tcx>) -> &'tcx GenericParamDef {
932 let param = self.param_at(param.index as usize, tcx);
934 GenericParamDefKind::Type { .. } => param,
935 _ => bug!("expected type parameter, but found another generic parameter"),
939 /// Returns the `GenericParamDef` associated with this `ParamConst`.
940 pub fn const_param(&'tcx self, param: &ParamConst, tcx: TyCtxt<'tcx>) -> &GenericParamDef {
941 let param = self.param_at(param.index as usize, tcx);
943 GenericParamDefKind::Const => param,
944 _ => bug!("expected const parameter, but found another generic parameter"),
949 /// Bounds on generics.
950 #[derive(Copy, Clone, Default, Debug, TyEncodable, TyDecodable, HashStable)]
951 pub struct GenericPredicates<'tcx> {
952 pub parent: Option<DefId>,
953 pub predicates: &'tcx [(Predicate<'tcx>, Span)],
956 impl<'tcx> GenericPredicates<'tcx> {
960 substs: SubstsRef<'tcx>,
961 ) -> InstantiatedPredicates<'tcx> {
962 let mut instantiated = InstantiatedPredicates::empty();
963 self.instantiate_into(tcx, &mut instantiated, substs);
967 pub fn instantiate_own(
970 substs: SubstsRef<'tcx>,
971 ) -> InstantiatedPredicates<'tcx> {
972 InstantiatedPredicates {
973 predicates: self.predicates.iter().map(|(p, _)| p.subst(tcx, substs)).collect(),
974 spans: self.predicates.iter().map(|(_, sp)| *sp).collect(),
981 instantiated: &mut InstantiatedPredicates<'tcx>,
982 substs: SubstsRef<'tcx>,
984 if let Some(def_id) = self.parent {
985 tcx.predicates_of(def_id).instantiate_into(tcx, instantiated, substs);
987 instantiated.predicates.extend(self.predicates.iter().map(|(p, _)| p.subst(tcx, substs)));
988 instantiated.spans.extend(self.predicates.iter().map(|(_, sp)| *sp));
991 pub fn instantiate_identity(&self, tcx: TyCtxt<'tcx>) -> InstantiatedPredicates<'tcx> {
992 let mut instantiated = InstantiatedPredicates::empty();
993 self.instantiate_identity_into(tcx, &mut instantiated);
997 fn instantiate_identity_into(
1000 instantiated: &mut InstantiatedPredicates<'tcx>,
1002 if let Some(def_id) = self.parent {
1003 tcx.predicates_of(def_id).instantiate_identity_into(tcx, instantiated);
1005 instantiated.predicates.extend(self.predicates.iter().map(|(p, _)| p));
1006 instantiated.spans.extend(self.predicates.iter().map(|(_, s)| s));
1011 crate struct PredicateInner<'tcx> {
1012 kind: Binder<PredicateKind<'tcx>>,
1014 /// See the comment for the corresponding field of [TyS].
1015 outer_exclusive_binder: ty::DebruijnIndex,
1018 #[cfg(target_arch = "x86_64")]
1019 static_assert_size!(PredicateInner<'_>, 40);
1021 #[derive(Clone, Copy, Lift)]
1022 pub struct Predicate<'tcx> {
1023 inner: &'tcx PredicateInner<'tcx>,
1026 impl<'tcx> PartialEq for Predicate<'tcx> {
1027 fn eq(&self, other: &Self) -> bool {
1028 // `self.kind` is always interned.
1029 ptr::eq(self.inner, other.inner)
1033 impl Hash for Predicate<'_> {
1034 fn hash<H: Hasher>(&self, s: &mut H) {
1035 (self.inner as *const PredicateInner<'_>).hash(s)
1039 impl<'tcx> Eq for Predicate<'tcx> {}
1041 impl<'tcx> Predicate<'tcx> {
1042 /// Gets the inner `Binder<PredicateKind<'tcx>>`.
1043 pub fn kind(self) -> Binder<PredicateKind<'tcx>> {
1048 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for Predicate<'tcx> {
1049 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
1050 let PredicateInner {
1053 // The other fields just provide fast access to information that is
1054 // also contained in `kind`, so no need to hash them.
1056 outer_exclusive_binder: _,
1059 kind.hash_stable(hcx, hasher);
1063 #[derive(Clone, Copy, PartialEq, Eq, Hash, TyEncodable, TyDecodable)]
1064 #[derive(HashStable, TypeFoldable)]
1065 pub enum PredicateKind<'tcx> {
1066 /// Corresponds to `where Foo: Bar<A, B, C>`. `Foo` here would be
1067 /// the `Self` type of the trait reference and `A`, `B`, and `C`
1068 /// would be the type parameters.
1070 /// A trait predicate will have `Constness::Const` if it originates
1071 /// from a bound on a `const fn` without the `?const` opt-out (e.g.,
1072 /// `const fn foobar<Foo: Bar>() {}`).
1073 Trait(TraitPredicate<'tcx>, Constness),
1076 RegionOutlives(RegionOutlivesPredicate<'tcx>),
1079 TypeOutlives(TypeOutlivesPredicate<'tcx>),
1081 /// `where <T as TraitRef>::Name == X`, approximately.
1082 /// See the `ProjectionPredicate` struct for details.
1083 Projection(ProjectionPredicate<'tcx>),
1085 /// No syntax: `T` well-formed.
1086 WellFormed(GenericArg<'tcx>),
1088 /// Trait must be object-safe.
1091 /// No direct syntax. May be thought of as `where T: FnFoo<...>`
1092 /// for some substitutions `...` and `T` being a closure type.
1093 /// Satisfied (or refuted) once we know the closure's kind.
1094 ClosureKind(DefId, SubstsRef<'tcx>, ClosureKind),
1097 Subtype(SubtypePredicate<'tcx>),
1099 /// Constant initializer must evaluate successfully.
1100 ConstEvaluatable(ty::WithOptConstParam<DefId>, SubstsRef<'tcx>),
1102 /// Constants must be equal. The first component is the const that is expected.
1103 ConstEquate(&'tcx Const<'tcx>, &'tcx Const<'tcx>),
1105 /// Represents a type found in the environment that we can use for implied bounds.
1107 /// Only used for Chalk.
1108 TypeWellFormedFromEnv(Ty<'tcx>),
1111 /// The crate outlives map is computed during typeck and contains the
1112 /// outlives of every item in the local crate. You should not use it
1113 /// directly, because to do so will make your pass dependent on the
1114 /// HIR of every item in the local crate. Instead, use
1115 /// `tcx.inferred_outlives_of()` to get the outlives for a *particular*
1117 #[derive(HashStable, Debug)]
1118 pub struct CratePredicatesMap<'tcx> {
1119 /// For each struct with outlive bounds, maps to a vector of the
1120 /// predicate of its outlive bounds. If an item has no outlives
1121 /// bounds, it will have no entry.
1122 pub predicates: FxHashMap<DefId, &'tcx [(Predicate<'tcx>, Span)]>,
1125 impl<'tcx> Predicate<'tcx> {
1126 /// Performs a substitution suitable for going from a
1127 /// poly-trait-ref to supertraits that must hold if that
1128 /// poly-trait-ref holds. This is slightly different from a normal
1129 /// substitution in terms of what happens with bound regions. See
1130 /// lengthy comment below for details.
1131 pub fn subst_supertrait(
1134 trait_ref: &ty::PolyTraitRef<'tcx>,
1135 ) -> Predicate<'tcx> {
1136 // The interaction between HRTB and supertraits is not entirely
1137 // obvious. Let me walk you (and myself) through an example.
1139 // Let's start with an easy case. Consider two traits:
1141 // trait Foo<'a>: Bar<'a,'a> { }
1142 // trait Bar<'b,'c> { }
1144 // Now, if we have a trait reference `for<'x> T: Foo<'x>`, then
1145 // we can deduce that `for<'x> T: Bar<'x,'x>`. Basically, if we
1146 // knew that `Foo<'x>` (for any 'x) then we also know that
1147 // `Bar<'x,'x>` (for any 'x). This more-or-less falls out from
1148 // normal substitution.
1150 // In terms of why this is sound, the idea is that whenever there
1151 // is an impl of `T:Foo<'a>`, it must show that `T:Bar<'a,'a>`
1152 // holds. So if there is an impl of `T:Foo<'a>` that applies to
1153 // all `'a`, then we must know that `T:Bar<'a,'a>` holds for all
1156 // Another example to be careful of is this:
1158 // trait Foo1<'a>: for<'b> Bar1<'a,'b> { }
1159 // trait Bar1<'b,'c> { }
1161 // Here, if we have `for<'x> T: Foo1<'x>`, then what do we know?
1162 // The answer is that we know `for<'x,'b> T: Bar1<'x,'b>`. The
1163 // reason is similar to the previous example: any impl of
1164 // `T:Foo1<'x>` must show that `for<'b> T: Bar1<'x, 'b>`. So
1165 // basically we would want to collapse the bound lifetimes from
1166 // the input (`trait_ref`) and the supertraits.
1168 // To achieve this in practice is fairly straightforward. Let's
1169 // consider the more complicated scenario:
1171 // - We start out with `for<'x> T: Foo1<'x>`. In this case, `'x`
1172 // has a De Bruijn index of 1. We want to produce `for<'x,'b> T: Bar1<'x,'b>`,
1173 // where both `'x` and `'b` would have a DB index of 1.
1174 // The substitution from the input trait-ref is therefore going to be
1175 // `'a => 'x` (where `'x` has a DB index of 1).
1176 // - The super-trait-ref is `for<'b> Bar1<'a,'b>`, where `'a` is an
1177 // early-bound parameter and `'b' is a late-bound parameter with a
1179 // - If we replace `'a` with `'x` from the input, it too will have
1180 // a DB index of 1, and thus we'll have `for<'x,'b> Bar1<'x,'b>`
1181 // just as we wanted.
1183 // There is only one catch. If we just apply the substitution `'a
1184 // => 'x` to `for<'b> Bar1<'a,'b>`, the substitution code will
1185 // adjust the DB index because we substituting into a binder (it
1186 // tries to be so smart...) resulting in `for<'x> for<'b>
1187 // Bar1<'x,'b>` (we have no syntax for this, so use your
1188 // imagination). Basically the 'x will have DB index of 2 and 'b
1189 // will have DB index of 1. Not quite what we want. So we apply
1190 // the substitution to the *contents* of the trait reference,
1191 // rather than the trait reference itself (put another way, the
1192 // substitution code expects equal binding levels in the values
1193 // from the substitution and the value being substituted into, and
1194 // this trick achieves that).
1195 let substs = trait_ref.skip_binder().substs;
1196 let pred = self.kind().skip_binder();
1197 let new = pred.subst(tcx, substs);
1198 tcx.reuse_or_mk_predicate(self, ty::Binder::bind(new))
1202 #[derive(Clone, Copy, PartialEq, Eq, Hash, TyEncodable, TyDecodable)]
1203 #[derive(HashStable, TypeFoldable)]
1204 pub struct TraitPredicate<'tcx> {
1205 pub trait_ref: TraitRef<'tcx>,
1208 pub type PolyTraitPredicate<'tcx> = ty::Binder<TraitPredicate<'tcx>>;
1210 impl<'tcx> TraitPredicate<'tcx> {
1211 pub fn def_id(self) -> DefId {
1212 self.trait_ref.def_id
1215 pub fn self_ty(self) -> Ty<'tcx> {
1216 self.trait_ref.self_ty()
1220 impl<'tcx> PolyTraitPredicate<'tcx> {
1221 pub fn def_id(self) -> DefId {
1222 // Ok to skip binder since trait `DefId` does not care about regions.
1223 self.skip_binder().def_id()
1226 pub fn self_ty(self) -> ty::Binder<Ty<'tcx>> {
1227 self.map_bound(|trait_ref| trait_ref.self_ty())
1231 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, TyEncodable, TyDecodable)]
1232 #[derive(HashStable, TypeFoldable)]
1233 pub struct OutlivesPredicate<A, B>(pub A, pub B); // `A: B`
1234 pub type RegionOutlivesPredicate<'tcx> = OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>;
1235 pub type TypeOutlivesPredicate<'tcx> = OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>;
1236 pub type PolyRegionOutlivesPredicate<'tcx> = ty::Binder<RegionOutlivesPredicate<'tcx>>;
1237 pub type PolyTypeOutlivesPredicate<'tcx> = ty::Binder<TypeOutlivesPredicate<'tcx>>;
1239 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, TyEncodable, TyDecodable)]
1240 #[derive(HashStable, TypeFoldable)]
1241 pub struct SubtypePredicate<'tcx> {
1242 pub a_is_expected: bool,
1246 pub type PolySubtypePredicate<'tcx> = ty::Binder<SubtypePredicate<'tcx>>;
1248 /// This kind of predicate has no *direct* correspondent in the
1249 /// syntax, but it roughly corresponds to the syntactic forms:
1251 /// 1. `T: TraitRef<..., Item = Type>`
1252 /// 2. `<T as TraitRef<...>>::Item == Type` (NYI)
1254 /// In particular, form #1 is "desugared" to the combination of a
1255 /// normal trait predicate (`T: TraitRef<...>`) and one of these
1256 /// predicates. Form #2 is a broader form in that it also permits
1257 /// equality between arbitrary types. Processing an instance of
1258 /// Form #2 eventually yields one of these `ProjectionPredicate`
1259 /// instances to normalize the LHS.
1260 #[derive(Copy, Clone, PartialEq, Eq, Hash, TyEncodable, TyDecodable)]
1261 #[derive(HashStable, TypeFoldable)]
1262 pub struct ProjectionPredicate<'tcx> {
1263 pub projection_ty: ProjectionTy<'tcx>,
1267 pub type PolyProjectionPredicate<'tcx> = Binder<ProjectionPredicate<'tcx>>;
1269 impl<'tcx> PolyProjectionPredicate<'tcx> {
1270 /// Returns the `DefId` of the associated item being projected.
1271 pub fn item_def_id(&self) -> DefId {
1272 self.skip_binder().projection_ty.item_def_id
1276 pub fn to_poly_trait_ref(&self, tcx: TyCtxt<'tcx>) -> PolyTraitRef<'tcx> {
1277 // Note: unlike with `TraitRef::to_poly_trait_ref()`,
1278 // `self.0.trait_ref` is permitted to have escaping regions.
1279 // This is because here `self` has a `Binder` and so does our
1280 // return value, so we are preserving the number of binding
1282 self.map_bound(|predicate| predicate.projection_ty.trait_ref(tcx))
1285 pub fn ty(&self) -> Binder<Ty<'tcx>> {
1286 self.map_bound(|predicate| predicate.ty)
1289 /// The `DefId` of the `TraitItem` for the associated type.
1291 /// Note that this is not the `DefId` of the `TraitRef` containing this
1292 /// associated type, which is in `tcx.associated_item(projection_def_id()).container`.
1293 pub fn projection_def_id(&self) -> DefId {
1294 // Ok to skip binder since trait `DefId` does not care about regions.
1295 self.skip_binder().projection_ty.item_def_id
1299 pub trait ToPolyTraitRef<'tcx> {
1300 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx>;
1303 impl<'tcx> ToPolyTraitRef<'tcx> for TraitRef<'tcx> {
1304 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
1305 ty::Binder::dummy(*self)
1309 impl<'tcx> ToPolyTraitRef<'tcx> for PolyTraitPredicate<'tcx> {
1310 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
1311 self.map_bound_ref(|trait_pred| trait_pred.trait_ref)
1315 pub trait ToPredicate<'tcx> {
1316 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx>;
1319 impl ToPredicate<'tcx> for Binder<PredicateKind<'tcx>> {
1321 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1322 tcx.mk_predicate(self)
1326 impl ToPredicate<'tcx> for PredicateKind<'tcx> {
1328 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1329 tcx.mk_predicate(Binder::dummy(self))
1333 impl<'tcx> ToPredicate<'tcx> for ConstnessAnd<TraitRef<'tcx>> {
1334 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1335 PredicateKind::Trait(ty::TraitPredicate { trait_ref: self.value }, self.constness)
1340 impl<'tcx> ToPredicate<'tcx> for ConstnessAnd<PolyTraitRef<'tcx>> {
1341 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1343 value: self.value.map_bound(|trait_ref| ty::TraitPredicate { trait_ref }),
1344 constness: self.constness,
1350 impl<'tcx> ToPredicate<'tcx> for ConstnessAnd<PolyTraitPredicate<'tcx>> {
1351 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1352 self.value.map_bound(|value| PredicateKind::Trait(value, self.constness)).to_predicate(tcx)
1356 impl<'tcx> ToPredicate<'tcx> for PolyRegionOutlivesPredicate<'tcx> {
1357 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1358 self.map_bound(PredicateKind::RegionOutlives).to_predicate(tcx)
1362 impl<'tcx> ToPredicate<'tcx> for PolyTypeOutlivesPredicate<'tcx> {
1363 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1364 self.map_bound(PredicateKind::TypeOutlives).to_predicate(tcx)
1368 impl<'tcx> ToPredicate<'tcx> for PolyProjectionPredicate<'tcx> {
1369 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1370 self.map_bound(PredicateKind::Projection).to_predicate(tcx)
1374 impl<'tcx> Predicate<'tcx> {
1375 pub fn to_opt_poly_trait_ref(self) -> Option<ConstnessAnd<PolyTraitRef<'tcx>>> {
1376 let predicate = self.kind();
1377 match predicate.skip_binder() {
1378 PredicateKind::Trait(t, constness) => {
1379 Some(ConstnessAnd { constness, value: predicate.rebind(t.trait_ref) })
1381 PredicateKind::Projection(..)
1382 | PredicateKind::Subtype(..)
1383 | PredicateKind::RegionOutlives(..)
1384 | PredicateKind::WellFormed(..)
1385 | PredicateKind::ObjectSafe(..)
1386 | PredicateKind::ClosureKind(..)
1387 | PredicateKind::TypeOutlives(..)
1388 | PredicateKind::ConstEvaluatable(..)
1389 | PredicateKind::ConstEquate(..)
1390 | PredicateKind::TypeWellFormedFromEnv(..) => None,
1394 pub fn to_opt_type_outlives(self) -> Option<PolyTypeOutlivesPredicate<'tcx>> {
1395 let predicate = self.kind();
1396 match predicate.skip_binder() {
1397 PredicateKind::TypeOutlives(data) => Some(predicate.rebind(data)),
1398 PredicateKind::Trait(..)
1399 | PredicateKind::Projection(..)
1400 | PredicateKind::Subtype(..)
1401 | PredicateKind::RegionOutlives(..)
1402 | PredicateKind::WellFormed(..)
1403 | PredicateKind::ObjectSafe(..)
1404 | PredicateKind::ClosureKind(..)
1405 | PredicateKind::ConstEvaluatable(..)
1406 | PredicateKind::ConstEquate(..)
1407 | PredicateKind::TypeWellFormedFromEnv(..) => None,
1412 /// Represents the bounds declared on a particular set of type
1413 /// parameters. Should eventually be generalized into a flag list of
1414 /// where-clauses. You can obtain a `InstantiatedPredicates` list from a
1415 /// `GenericPredicates` by using the `instantiate` method. Note that this method
1416 /// reflects an important semantic invariant of `InstantiatedPredicates`: while
1417 /// the `GenericPredicates` are expressed in terms of the bound type
1418 /// parameters of the impl/trait/whatever, an `InstantiatedPredicates` instance
1419 /// represented a set of bounds for some particular instantiation,
1420 /// meaning that the generic parameters have been substituted with
1425 /// struct Foo<T, U: Bar<T>> { ... }
1427 /// Here, the `GenericPredicates` for `Foo` would contain a list of bounds like
1428 /// `[[], [U:Bar<T>]]`. Now if there were some particular reference
1429 /// like `Foo<isize,usize>`, then the `InstantiatedPredicates` would be `[[],
1430 /// [usize:Bar<isize>]]`.
1431 #[derive(Clone, Debug, TypeFoldable)]
1432 pub struct InstantiatedPredicates<'tcx> {
1433 pub predicates: Vec<Predicate<'tcx>>,
1434 pub spans: Vec<Span>,
1437 impl<'tcx> InstantiatedPredicates<'tcx> {
1438 pub fn empty() -> InstantiatedPredicates<'tcx> {
1439 InstantiatedPredicates { predicates: vec![], spans: vec![] }
1442 pub fn is_empty(&self) -> bool {
1443 self.predicates.is_empty()
1447 rustc_index::newtype_index! {
1448 /// "Universes" are used during type- and trait-checking in the
1449 /// presence of `for<..>` binders to control what sets of names are
1450 /// visible. Universes are arranged into a tree: the root universe
1451 /// contains names that are always visible. Each child then adds a new
1452 /// set of names that are visible, in addition to those of its parent.
1453 /// We say that the child universe "extends" the parent universe with
1456 /// To make this more concrete, consider this program:
1460 /// fn bar<T>(x: T) {
1461 /// let y: for<'a> fn(&'a u8, Foo) = ...;
1465 /// The struct name `Foo` is in the root universe U0. But the type
1466 /// parameter `T`, introduced on `bar`, is in an extended universe U1
1467 /// -- i.e., within `bar`, we can name both `T` and `Foo`, but outside
1468 /// of `bar`, we cannot name `T`. Then, within the type of `y`, the
1469 /// region `'a` is in a universe U2 that extends U1, because we can
1470 /// name it inside the fn type but not outside.
1472 /// Universes are used to do type- and trait-checking around these
1473 /// "forall" binders (also called **universal quantification**). The
1474 /// idea is that when, in the body of `bar`, we refer to `T` as a
1475 /// type, we aren't referring to any type in particular, but rather a
1476 /// kind of "fresh" type that is distinct from all other types we have
1477 /// actually declared. This is called a **placeholder** type, and we
1478 /// use universes to talk about this. In other words, a type name in
1479 /// universe 0 always corresponds to some "ground" type that the user
1480 /// declared, but a type name in a non-zero universe is a placeholder
1481 /// type -- an idealized representative of "types in general" that we
1482 /// use for checking generic functions.
1483 pub struct UniverseIndex {
1485 DEBUG_FORMAT = "U{}",
1489 impl UniverseIndex {
1490 pub const ROOT: UniverseIndex = UniverseIndex::from_u32(0);
1492 /// Returns the "next" universe index in order -- this new index
1493 /// is considered to extend all previous universes. This
1494 /// corresponds to entering a `forall` quantifier. So, for
1495 /// example, suppose we have this type in universe `U`:
1498 /// for<'a> fn(&'a u32)
1501 /// Once we "enter" into this `for<'a>` quantifier, we are in a
1502 /// new universe that extends `U` -- in this new universe, we can
1503 /// name the region `'a`, but that region was not nameable from
1504 /// `U` because it was not in scope there.
1505 pub fn next_universe(self) -> UniverseIndex {
1506 UniverseIndex::from_u32(self.private.checked_add(1).unwrap())
1509 /// Returns `true` if `self` can name a name from `other` -- in other words,
1510 /// if the set of names in `self` is a superset of those in
1511 /// `other` (`self >= other`).
1512 pub fn can_name(self, other: UniverseIndex) -> bool {
1513 self.private >= other.private
1516 /// Returns `true` if `self` cannot name some names from `other` -- in other
1517 /// words, if the set of names in `self` is a strict subset of
1518 /// those in `other` (`self < other`).
1519 pub fn cannot_name(self, other: UniverseIndex) -> bool {
1520 self.private < other.private
1524 /// The "placeholder index" fully defines a placeholder region, type, or const. Placeholders are
1525 /// identified by both a universe, as well as a name residing within that universe. Distinct bound
1526 /// regions/types/consts within the same universe simply have an unknown relationship to one
1528 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TyEncodable, TyDecodable, PartialOrd, Ord)]
1529 pub struct Placeholder<T> {
1530 pub universe: UniverseIndex,
1534 impl<'a, T> HashStable<StableHashingContext<'a>> for Placeholder<T>
1536 T: HashStable<StableHashingContext<'a>>,
1538 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
1539 self.universe.hash_stable(hcx, hasher);
1540 self.name.hash_stable(hcx, hasher);
1544 pub type PlaceholderRegion = Placeholder<BoundRegionKind>;
1546 pub type PlaceholderType = Placeholder<BoundVar>;
1548 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable)]
1549 #[derive(TyEncodable, TyDecodable, PartialOrd, Ord)]
1550 pub struct BoundConst<'tcx> {
1555 pub type PlaceholderConst<'tcx> = Placeholder<BoundConst<'tcx>>;
1557 /// A `DefId` which, in case it is a const argument, is potentially bundled with
1558 /// the `DefId` of the generic parameter it instantiates.
1560 /// This is used to avoid calls to `type_of` for const arguments during typeck
1561 /// which cause cycle errors.
1566 /// fn foo<const N: usize>(&self) -> [u8; N] { [0; N] }
1567 /// // ^ const parameter
1571 /// fn foo<const M: u8>(&self) -> usize { 42 }
1572 /// // ^ const parameter
1577 /// let _b = a.foo::<{ 3 + 7 }>();
1578 /// // ^^^^^^^^^ const argument
1582 /// Let's look at the call `a.foo::<{ 3 + 7 }>()` here. We do not know
1583 /// which `foo` is used until we know the type of `a`.
1585 /// We only know the type of `a` once we are inside of `typeck(main)`.
1586 /// We also end up normalizing the type of `_b` during `typeck(main)` which
1587 /// requires us to evaluate the const argument.
1589 /// To evaluate that const argument we need to know its type,
1590 /// which we would get using `type_of(const_arg)`. This requires us to
1591 /// resolve `foo` as it can be either `usize` or `u8` in this example.
1592 /// However, resolving `foo` once again requires `typeck(main)` to get the type of `a`,
1593 /// which results in a cycle.
1595 /// In short we must not call `type_of(const_arg)` during `typeck(main)`.
1597 /// When first creating the `ty::Const` of the const argument inside of `typeck` we have
1598 /// already resolved `foo` so we know which const parameter this argument instantiates.
1599 /// This means that we also know the expected result of `type_of(const_arg)` even if we
1600 /// aren't allowed to call that query: it is equal to `type_of(const_param)` which is
1601 /// trivial to compute.
1603 /// If we now want to use that constant in a place which potentionally needs its type
1604 /// we also pass the type of its `const_param`. This is the point of `WithOptConstParam`,
1605 /// except that instead of a `Ty` we bundle the `DefId` of the const parameter.
1606 /// Meaning that we need to use `type_of(const_param_did)` if `const_param_did` is `Some`
1607 /// to get the type of `did`.
1608 #[derive(Copy, Clone, Debug, TypeFoldable, Lift, TyEncodable, TyDecodable)]
1609 #[derive(PartialEq, Eq, PartialOrd, Ord)]
1610 #[derive(Hash, HashStable)]
1611 pub struct WithOptConstParam<T> {
1613 /// The `DefId` of the corresponding generic parameter in case `did` is
1614 /// a const argument.
1616 /// Note that even if `did` is a const argument, this may still be `None`.
1617 /// All queries taking `WithOptConstParam` start by calling `tcx.opt_const_param_of(def.did)`
1618 /// to potentially update `param_did` in the case it is `None`.
1619 pub const_param_did: Option<DefId>,
1622 impl<T> WithOptConstParam<T> {
1623 /// Creates a new `WithOptConstParam` setting `const_param_did` to `None`.
1625 pub fn unknown(did: T) -> WithOptConstParam<T> {
1626 WithOptConstParam { did, const_param_did: None }
1630 impl WithOptConstParam<LocalDefId> {
1631 /// Returns `Some((did, param_did))` if `def_id` is a const argument,
1632 /// `None` otherwise.
1634 pub fn try_lookup(did: LocalDefId, tcx: TyCtxt<'_>) -> Option<(LocalDefId, DefId)> {
1635 tcx.opt_const_param_of(did).map(|param_did| (did, param_did))
1638 /// In case `self` is unknown but `self.did` is a const argument, this returns
1639 /// a `WithOptConstParam` with the correct `const_param_did`.
1641 pub fn try_upgrade(self, tcx: TyCtxt<'_>) -> Option<WithOptConstParam<LocalDefId>> {
1642 if self.const_param_did.is_none() {
1643 if let const_param_did @ Some(_) = tcx.opt_const_param_of(self.did) {
1644 return Some(WithOptConstParam { did: self.did, const_param_did });
1651 pub fn to_global(self) -> WithOptConstParam<DefId> {
1652 WithOptConstParam { did: self.did.to_def_id(), const_param_did: self.const_param_did }
1655 pub fn def_id_for_type_of(self) -> DefId {
1656 if let Some(did) = self.const_param_did { did } else { self.did.to_def_id() }
1660 impl WithOptConstParam<DefId> {
1661 pub fn as_local(self) -> Option<WithOptConstParam<LocalDefId>> {
1664 .map(|did| WithOptConstParam { did, const_param_did: self.const_param_did })
1667 pub fn as_const_arg(self) -> Option<(LocalDefId, DefId)> {
1668 if let Some(param_did) = self.const_param_did {
1669 if let Some(did) = self.did.as_local() {
1670 return Some((did, param_did));
1677 pub fn expect_local(self) -> WithOptConstParam<LocalDefId> {
1678 self.as_local().unwrap()
1681 pub fn is_local(self) -> bool {
1685 pub fn def_id_for_type_of(self) -> DefId {
1686 self.const_param_did.unwrap_or(self.did)
1690 /// When type checking, we use the `ParamEnv` to track
1691 /// details about the set of where-clauses that are in scope at this
1692 /// particular point.
1693 #[derive(Copy, Clone, Hash, PartialEq, Eq)]
1694 pub struct ParamEnv<'tcx> {
1695 /// This packs both caller bounds and the reveal enum into one pointer.
1697 /// Caller bounds are `Obligation`s that the caller must satisfy. This is
1698 /// basically the set of bounds on the in-scope type parameters, translated
1699 /// into `Obligation`s, and elaborated and normalized.
1701 /// Use the `caller_bounds()` method to access.
1703 /// Typically, this is `Reveal::UserFacing`, but during codegen we
1704 /// want `Reveal::All`.
1706 /// Note: This is packed, use the reveal() method to access it.
1707 packed: CopyTaggedPtr<&'tcx List<Predicate<'tcx>>, traits::Reveal, true>,
1710 unsafe impl rustc_data_structures::tagged_ptr::Tag for traits::Reveal {
1711 const BITS: usize = 1;
1712 fn into_usize(self) -> usize {
1714 traits::Reveal::UserFacing => 0,
1715 traits::Reveal::All => 1,
1718 unsafe fn from_usize(ptr: usize) -> Self {
1720 0 => traits::Reveal::UserFacing,
1721 1 => traits::Reveal::All,
1722 _ => std::hint::unreachable_unchecked(),
1727 impl<'tcx> fmt::Debug for ParamEnv<'tcx> {
1728 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1729 f.debug_struct("ParamEnv")
1730 .field("caller_bounds", &self.caller_bounds())
1731 .field("reveal", &self.reveal())
1736 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for ParamEnv<'tcx> {
1737 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
1738 self.caller_bounds().hash_stable(hcx, hasher);
1739 self.reveal().hash_stable(hcx, hasher);
1743 impl<'tcx> TypeFoldable<'tcx> for ParamEnv<'tcx> {
1744 fn super_fold_with<F: ty::fold::TypeFolder<'tcx>>(self, folder: &mut F) -> Self {
1745 ParamEnv::new(self.caller_bounds().fold_with(folder), self.reveal().fold_with(folder))
1748 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> ControlFlow<V::BreakTy> {
1749 self.caller_bounds().visit_with(visitor)?;
1750 self.reveal().visit_with(visitor)
1754 impl<'tcx> ParamEnv<'tcx> {
1755 /// Construct a trait environment suitable for contexts where
1756 /// there are no where-clauses in scope. Hidden types (like `impl
1757 /// Trait`) are left hidden, so this is suitable for ordinary
1760 pub fn empty() -> Self {
1761 Self::new(List::empty(), Reveal::UserFacing)
1765 pub fn caller_bounds(self) -> &'tcx List<Predicate<'tcx>> {
1766 self.packed.pointer()
1770 pub fn reveal(self) -> traits::Reveal {
1774 /// Construct a trait environment with no where-clauses in scope
1775 /// where the values of all `impl Trait` and other hidden types
1776 /// are revealed. This is suitable for monomorphized, post-typeck
1777 /// environments like codegen or doing optimizations.
1779 /// N.B., if you want to have predicates in scope, use `ParamEnv::new`,
1780 /// or invoke `param_env.with_reveal_all()`.
1782 pub fn reveal_all() -> Self {
1783 Self::new(List::empty(), Reveal::All)
1786 /// Construct a trait environment with the given set of predicates.
1788 pub fn new(caller_bounds: &'tcx List<Predicate<'tcx>>, reveal: Reveal) -> Self {
1789 ty::ParamEnv { packed: CopyTaggedPtr::new(caller_bounds, reveal) }
1792 pub fn with_user_facing(mut self) -> Self {
1793 self.packed.set_tag(Reveal::UserFacing);
1797 /// Returns a new parameter environment with the same clauses, but
1798 /// which "reveals" the true results of projections in all cases
1799 /// (even for associated types that are specializable). This is
1800 /// the desired behavior during codegen and certain other special
1801 /// contexts; normally though we want to use `Reveal::UserFacing`,
1802 /// which is the default.
1803 /// All opaque types in the caller_bounds of the `ParamEnv`
1804 /// will be normalized to their underlying types.
1805 /// See PR #65989 and issue #65918 for more details
1806 pub fn with_reveal_all_normalized(self, tcx: TyCtxt<'tcx>) -> Self {
1807 if self.packed.tag() == traits::Reveal::All {
1811 ParamEnv::new(tcx.normalize_opaque_types(self.caller_bounds()), Reveal::All)
1814 /// Returns this same environment but with no caller bounds.
1815 pub fn without_caller_bounds(self) -> Self {
1816 Self::new(List::empty(), self.reveal())
1819 /// Creates a suitable environment in which to perform trait
1820 /// queries on the given value. When type-checking, this is simply
1821 /// the pair of the environment plus value. But when reveal is set to
1822 /// All, then if `value` does not reference any type parameters, we will
1823 /// pair it with the empty environment. This improves caching and is generally
1826 /// N.B., we preserve the environment when type-checking because it
1827 /// is possible for the user to have wacky where-clauses like
1828 /// `where Box<u32>: Copy`, which are clearly never
1829 /// satisfiable. We generally want to behave as if they were true,
1830 /// although the surrounding function is never reachable.
1831 pub fn and<T: TypeFoldable<'tcx>>(self, value: T) -> ParamEnvAnd<'tcx, T> {
1832 match self.reveal() {
1833 Reveal::UserFacing => ParamEnvAnd { param_env: self, value },
1836 if value.is_global() {
1837 ParamEnvAnd { param_env: self.without_caller_bounds(), value }
1839 ParamEnvAnd { param_env: self, value }
1846 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TypeFoldable)]
1847 pub struct ConstnessAnd<T> {
1848 pub constness: Constness,
1852 // FIXME(ecstaticmorse): Audit all occurrences of `without_const().to_predicate(tcx)` to ensure that
1853 // the constness of trait bounds is being propagated correctly.
1854 pub trait WithConstness: Sized {
1856 fn with_constness(self, constness: Constness) -> ConstnessAnd<Self> {
1857 ConstnessAnd { constness, value: self }
1861 fn with_const(self) -> ConstnessAnd<Self> {
1862 self.with_constness(Constness::Const)
1866 fn without_const(self) -> ConstnessAnd<Self> {
1867 self.with_constness(Constness::NotConst)
1871 impl<T> WithConstness for T {}
1873 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TypeFoldable)]
1874 pub struct ParamEnvAnd<'tcx, T> {
1875 pub param_env: ParamEnv<'tcx>,
1879 impl<'tcx, T> ParamEnvAnd<'tcx, T> {
1880 pub fn into_parts(self) -> (ParamEnv<'tcx>, T) {
1881 (self.param_env, self.value)
1885 impl<'a, 'tcx, T> HashStable<StableHashingContext<'a>> for ParamEnvAnd<'tcx, T>
1887 T: HashStable<StableHashingContext<'a>>,
1889 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
1890 let ParamEnvAnd { ref param_env, ref value } = *self;
1892 param_env.hash_stable(hcx, hasher);
1893 value.hash_stable(hcx, hasher);
1897 #[derive(Copy, Clone, Debug, HashStable)]
1898 pub struct Destructor {
1899 /// The `DefId` of the destructor method
1904 #[derive(HashStable)]
1905 pub struct AdtFlags: u32 {
1906 const NO_ADT_FLAGS = 0;
1907 /// Indicates whether the ADT is an enum.
1908 const IS_ENUM = 1 << 0;
1909 /// Indicates whether the ADT is a union.
1910 const IS_UNION = 1 << 1;
1911 /// Indicates whether the ADT is a struct.
1912 const IS_STRUCT = 1 << 2;
1913 /// Indicates whether the ADT is a struct and has a constructor.
1914 const HAS_CTOR = 1 << 3;
1915 /// Indicates whether the type is `PhantomData`.
1916 const IS_PHANTOM_DATA = 1 << 4;
1917 /// Indicates whether the type has a `#[fundamental]` attribute.
1918 const IS_FUNDAMENTAL = 1 << 5;
1919 /// Indicates whether the type is `Box`.
1920 const IS_BOX = 1 << 6;
1921 /// Indicates whether the type is `ManuallyDrop`.
1922 const IS_MANUALLY_DROP = 1 << 7;
1923 /// Indicates whether the variant list of this ADT is `#[non_exhaustive]`.
1924 /// (i.e., this flag is never set unless this ADT is an enum).
1925 const IS_VARIANT_LIST_NON_EXHAUSTIVE = 1 << 8;
1930 #[derive(HashStable)]
1931 pub struct VariantFlags: u32 {
1932 const NO_VARIANT_FLAGS = 0;
1933 /// Indicates whether the field list of this variant is `#[non_exhaustive]`.
1934 const IS_FIELD_LIST_NON_EXHAUSTIVE = 1 << 0;
1935 /// Indicates whether this variant was obtained as part of recovering from
1936 /// a syntactic error. May be incomplete or bogus.
1937 const IS_RECOVERED = 1 << 1;
1941 /// Definition of a variant -- a struct's fields or a enum variant.
1942 #[derive(Debug, HashStable)]
1943 pub struct VariantDef {
1944 /// `DefId` that identifies the variant itself.
1945 /// If this variant belongs to a struct or union, then this is a copy of its `DefId`.
1947 /// `DefId` that identifies the variant's constructor.
1948 /// If this variant is a struct variant, then this is `None`.
1949 pub ctor_def_id: Option<DefId>,
1950 /// Variant or struct name.
1951 #[stable_hasher(project(name))]
1953 /// Discriminant of this variant.
1954 pub discr: VariantDiscr,
1955 /// Fields of this variant.
1956 pub fields: Vec<FieldDef>,
1957 /// Type of constructor of variant.
1958 pub ctor_kind: CtorKind,
1959 /// Flags of the variant (e.g. is field list non-exhaustive)?
1960 flags: VariantFlags,
1964 /// Creates a new `VariantDef`.
1966 /// `variant_did` is the `DefId` that identifies the enum variant (if this `VariantDef`
1967 /// represents an enum variant).
1969 /// `ctor_did` is the `DefId` that identifies the constructor of unit or
1970 /// tuple-variants/structs. If this is a `struct`-variant then this should be `None`.
1972 /// `parent_did` is the `DefId` of the `AdtDef` representing the enum or struct that
1973 /// owns this variant. It is used for checking if a struct has `#[non_exhaustive]` w/out having
1974 /// to go through the redirect of checking the ctor's attributes - but compiling a small crate
1975 /// requires loading the `AdtDef`s for all the structs in the universe (e.g., coherence for any
1976 /// built-in trait), and we do not want to load attributes twice.
1978 /// If someone speeds up attribute loading to not be a performance concern, they can
1979 /// remove this hack and use the constructor `DefId` everywhere.
1982 variant_did: Option<DefId>,
1983 ctor_def_id: Option<DefId>,
1984 discr: VariantDiscr,
1985 fields: Vec<FieldDef>,
1986 ctor_kind: CtorKind,
1990 is_field_list_non_exhaustive: bool,
1993 "VariantDef::new(ident = {:?}, variant_did = {:?}, ctor_def_id = {:?}, discr = {:?},
1994 fields = {:?}, ctor_kind = {:?}, adt_kind = {:?}, parent_did = {:?})",
1995 ident, variant_did, ctor_def_id, discr, fields, ctor_kind, adt_kind, parent_did,
1998 let mut flags = VariantFlags::NO_VARIANT_FLAGS;
1999 if is_field_list_non_exhaustive {
2000 flags |= VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE;
2004 flags |= VariantFlags::IS_RECOVERED;
2008 def_id: variant_did.unwrap_or(parent_did),
2018 /// Is this field list non-exhaustive?
2020 pub fn is_field_list_non_exhaustive(&self) -> bool {
2021 self.flags.intersects(VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE)
2024 /// Was this variant obtained as part of recovering from a syntactic error?
2026 pub fn is_recovered(&self) -> bool {
2027 self.flags.intersects(VariantFlags::IS_RECOVERED)
2031 #[derive(Copy, Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
2032 pub enum VariantDiscr {
2033 /// Explicit value for this variant, i.e., `X = 123`.
2034 /// The `DefId` corresponds to the embedded constant.
2037 /// The previous variant's discriminant plus one.
2038 /// For efficiency reasons, the distance from the
2039 /// last `Explicit` discriminant is being stored,
2040 /// or `0` for the first variant, if it has none.
2044 #[derive(Debug, HashStable)]
2045 pub struct FieldDef {
2047 #[stable_hasher(project(name))]
2049 pub vis: Visibility,
2052 /// The definition of a user-defined type, e.g., a `struct`, `enum`, or `union`.
2054 /// These are all interned (by `alloc_adt_def`) into the global arena.
2056 /// The initialism *ADT* stands for an [*algebraic data type (ADT)*][adt].
2057 /// This is slightly wrong because `union`s are not ADTs.
2058 /// Moreover, Rust only allows recursive data types through indirection.
2060 /// [adt]: https://en.wikipedia.org/wiki/Algebraic_data_type
2062 /// The `DefId` of the struct, enum or union item.
2064 /// Variants of the ADT. If this is a struct or union, then there will be a single variant.
2065 pub variants: IndexVec<VariantIdx, VariantDef>,
2066 /// Flags of the ADT (e.g., is this a struct? is this non-exhaustive?).
2068 /// Repr options provided by the user.
2069 pub repr: ReprOptions,
2072 impl PartialOrd for AdtDef {
2073 fn partial_cmp(&self, other: &AdtDef) -> Option<Ordering> {
2074 Some(self.cmp(&other))
2078 /// There should be only one AdtDef for each `did`, therefore
2079 /// it is fine to implement `Ord` only based on `did`.
2080 impl Ord for AdtDef {
2081 fn cmp(&self, other: &AdtDef) -> Ordering {
2082 self.did.cmp(&other.did)
2086 impl PartialEq for AdtDef {
2087 // `AdtDef`s are always interned, and this is part of `TyS` equality.
2089 fn eq(&self, other: &Self) -> bool {
2090 ptr::eq(self, other)
2094 impl Eq for AdtDef {}
2096 impl Hash for AdtDef {
2098 fn hash<H: Hasher>(&self, s: &mut H) {
2099 (self as *const AdtDef).hash(s)
2103 impl<S: Encoder> Encodable<S> for AdtDef {
2104 fn encode(&self, s: &mut S) -> Result<(), S::Error> {
2109 impl<'a> HashStable<StableHashingContext<'a>> for AdtDef {
2110 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
2112 static CACHE: RefCell<FxHashMap<usize, Fingerprint>> = Default::default();
2115 let hash: Fingerprint = CACHE.with(|cache| {
2116 let addr = self as *const AdtDef as usize;
2117 *cache.borrow_mut().entry(addr).or_insert_with(|| {
2118 let ty::AdtDef { did, ref variants, ref flags, ref repr } = *self;
2120 let mut hasher = StableHasher::new();
2121 did.hash_stable(hcx, &mut hasher);
2122 variants.hash_stable(hcx, &mut hasher);
2123 flags.hash_stable(hcx, &mut hasher);
2124 repr.hash_stable(hcx, &mut hasher);
2130 hash.hash_stable(hcx, hasher);
2134 #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
2141 impl Into<DataTypeKind> for AdtKind {
2142 fn into(self) -> DataTypeKind {
2144 AdtKind::Struct => DataTypeKind::Struct,
2145 AdtKind::Union => DataTypeKind::Union,
2146 AdtKind::Enum => DataTypeKind::Enum,
2152 #[derive(TyEncodable, TyDecodable, Default, HashStable)]
2153 pub struct ReprFlags: u8 {
2154 const IS_C = 1 << 0;
2155 const IS_SIMD = 1 << 1;
2156 const IS_TRANSPARENT = 1 << 2;
2157 // Internal only for now. If true, don't reorder fields.
2158 const IS_LINEAR = 1 << 3;
2159 // If true, don't expose any niche to type's context.
2160 const HIDE_NICHE = 1 << 4;
2161 // Any of these flags being set prevent field reordering optimisation.
2162 const IS_UNOPTIMISABLE = ReprFlags::IS_C.bits |
2163 ReprFlags::IS_SIMD.bits |
2164 ReprFlags::IS_LINEAR.bits;
2168 /// Represents the repr options provided by the user,
2169 #[derive(Copy, Clone, Debug, Eq, PartialEq, TyEncodable, TyDecodable, Default, HashStable)]
2170 pub struct ReprOptions {
2171 pub int: Option<attr::IntType>,
2172 pub align: Option<Align>,
2173 pub pack: Option<Align>,
2174 pub flags: ReprFlags,
2178 pub fn new(tcx: TyCtxt<'_>, did: DefId) -> ReprOptions {
2179 let mut flags = ReprFlags::empty();
2180 let mut size = None;
2181 let mut max_align: Option<Align> = None;
2182 let mut min_pack: Option<Align> = None;
2183 for attr in tcx.get_attrs(did).iter() {
2184 for r in attr::find_repr_attrs(&tcx.sess, attr) {
2185 flags.insert(match r {
2186 attr::ReprC => ReprFlags::IS_C,
2187 attr::ReprPacked(pack) => {
2188 let pack = Align::from_bytes(pack as u64).unwrap();
2189 min_pack = Some(if let Some(min_pack) = min_pack {
2196 attr::ReprTransparent => ReprFlags::IS_TRANSPARENT,
2197 attr::ReprNoNiche => ReprFlags::HIDE_NICHE,
2198 attr::ReprSimd => ReprFlags::IS_SIMD,
2199 attr::ReprInt(i) => {
2203 attr::ReprAlign(align) => {
2204 max_align = max_align.max(Some(Align::from_bytes(align as u64).unwrap()));
2211 // This is here instead of layout because the choice must make it into metadata.
2212 if !tcx.consider_optimizing(|| format!("Reorder fields of {:?}", tcx.def_path_str(did))) {
2213 flags.insert(ReprFlags::IS_LINEAR);
2215 ReprOptions { int: size, align: max_align, pack: min_pack, flags }
2219 pub fn simd(&self) -> bool {
2220 self.flags.contains(ReprFlags::IS_SIMD)
2223 pub fn c(&self) -> bool {
2224 self.flags.contains(ReprFlags::IS_C)
2227 pub fn packed(&self) -> bool {
2231 pub fn transparent(&self) -> bool {
2232 self.flags.contains(ReprFlags::IS_TRANSPARENT)
2235 pub fn linear(&self) -> bool {
2236 self.flags.contains(ReprFlags::IS_LINEAR)
2239 pub fn hide_niche(&self) -> bool {
2240 self.flags.contains(ReprFlags::HIDE_NICHE)
2243 /// Returns the discriminant type, given these `repr` options.
2244 /// This must only be called on enums!
2245 pub fn discr_type(&self) -> attr::IntType {
2246 self.int.unwrap_or(attr::SignedInt(ast::IntTy::Isize))
2249 /// Returns `true` if this `#[repr()]` should inhabit "smart enum
2250 /// layout" optimizations, such as representing `Foo<&T>` as a
2252 pub fn inhibit_enum_layout_opt(&self) -> bool {
2253 self.c() || self.int.is_some()
2256 /// Returns `true` if this `#[repr()]` should inhibit struct field reordering
2257 /// optimizations, such as with `repr(C)`, `repr(packed(1))`, or `repr(<int>)`.
2258 pub fn inhibit_struct_field_reordering_opt(&self) -> bool {
2259 if let Some(pack) = self.pack {
2260 if pack.bytes() == 1 {
2264 self.flags.intersects(ReprFlags::IS_UNOPTIMISABLE) || self.int.is_some()
2267 /// Returns `true` if this `#[repr()]` should inhibit union ABI optimisations.
2268 pub fn inhibit_union_abi_opt(&self) -> bool {
2274 /// Creates a new `AdtDef`.
2279 variants: IndexVec<VariantIdx, VariantDef>,
2282 debug!("AdtDef::new({:?}, {:?}, {:?}, {:?})", did, kind, variants, repr);
2283 let mut flags = AdtFlags::NO_ADT_FLAGS;
2285 if kind == AdtKind::Enum && tcx.has_attr(did, sym::non_exhaustive) {
2286 debug!("found non-exhaustive variant list for {:?}", did);
2287 flags = flags | AdtFlags::IS_VARIANT_LIST_NON_EXHAUSTIVE;
2290 flags |= match kind {
2291 AdtKind::Enum => AdtFlags::IS_ENUM,
2292 AdtKind::Union => AdtFlags::IS_UNION,
2293 AdtKind::Struct => AdtFlags::IS_STRUCT,
2296 if kind == AdtKind::Struct && variants[VariantIdx::new(0)].ctor_def_id.is_some() {
2297 flags |= AdtFlags::HAS_CTOR;
2300 let attrs = tcx.get_attrs(did);
2301 if tcx.sess.contains_name(&attrs, sym::fundamental) {
2302 flags |= AdtFlags::IS_FUNDAMENTAL;
2304 if Some(did) == tcx.lang_items().phantom_data() {
2305 flags |= AdtFlags::IS_PHANTOM_DATA;
2307 if Some(did) == tcx.lang_items().owned_box() {
2308 flags |= AdtFlags::IS_BOX;
2310 if Some(did) == tcx.lang_items().manually_drop() {
2311 flags |= AdtFlags::IS_MANUALLY_DROP;
2314 AdtDef { did, variants, flags, repr }
2317 /// Returns `true` if this is a struct.
2319 pub fn is_struct(&self) -> bool {
2320 self.flags.contains(AdtFlags::IS_STRUCT)
2323 /// Returns `true` if this is a union.
2325 pub fn is_union(&self) -> bool {
2326 self.flags.contains(AdtFlags::IS_UNION)
2329 /// Returns `true` if this is a enum.
2331 pub fn is_enum(&self) -> bool {
2332 self.flags.contains(AdtFlags::IS_ENUM)
2335 /// Returns `true` if the variant list of this ADT is `#[non_exhaustive]`.
2337 pub fn is_variant_list_non_exhaustive(&self) -> bool {
2338 self.flags.contains(AdtFlags::IS_VARIANT_LIST_NON_EXHAUSTIVE)
2341 /// Returns the kind of the ADT.
2343 pub fn adt_kind(&self) -> AdtKind {
2346 } else if self.is_union() {
2353 /// Returns a description of this abstract data type.
2354 pub fn descr(&self) -> &'static str {
2355 match self.adt_kind() {
2356 AdtKind::Struct => "struct",
2357 AdtKind::Union => "union",
2358 AdtKind::Enum => "enum",
2362 /// Returns a description of a variant of this abstract data type.
2364 pub fn variant_descr(&self) -> &'static str {
2365 match self.adt_kind() {
2366 AdtKind::Struct => "struct",
2367 AdtKind::Union => "union",
2368 AdtKind::Enum => "variant",
2372 /// If this function returns `true`, it implies that `is_struct` must return `true`.
2374 pub fn has_ctor(&self) -> bool {
2375 self.flags.contains(AdtFlags::HAS_CTOR)
2378 /// Returns `true` if this type is `#[fundamental]` for the purposes
2379 /// of coherence checking.
2381 pub fn is_fundamental(&self) -> bool {
2382 self.flags.contains(AdtFlags::IS_FUNDAMENTAL)
2385 /// Returns `true` if this is `PhantomData<T>`.
2387 pub fn is_phantom_data(&self) -> bool {
2388 self.flags.contains(AdtFlags::IS_PHANTOM_DATA)
2391 /// Returns `true` if this is Box<T>.
2393 pub fn is_box(&self) -> bool {
2394 self.flags.contains(AdtFlags::IS_BOX)
2397 /// Returns `true` if this is `ManuallyDrop<T>`.
2399 pub fn is_manually_drop(&self) -> bool {
2400 self.flags.contains(AdtFlags::IS_MANUALLY_DROP)
2403 /// Returns `true` if this type has a destructor.
2404 pub fn has_dtor(&self, tcx: TyCtxt<'tcx>) -> bool {
2405 self.destructor(tcx).is_some()
2408 /// Asserts this is a struct or union and returns its unique variant.
2409 pub fn non_enum_variant(&self) -> &VariantDef {
2410 assert!(self.is_struct() || self.is_union());
2411 &self.variants[VariantIdx::new(0)]
2415 pub fn predicates(&self, tcx: TyCtxt<'tcx>) -> GenericPredicates<'tcx> {
2416 tcx.predicates_of(self.did)
2419 /// Returns an iterator over all fields contained
2422 pub fn all_fields(&self) -> impl Iterator<Item = &FieldDef> + Clone {
2423 self.variants.iter().flat_map(|v| v.fields.iter())
2426 /// Whether the ADT lacks fields. Note that this includes uninhabited enums,
2427 /// e.g., `enum Void {}` is considered payload free as well.
2428 pub fn is_payloadfree(&self) -> bool {
2429 self.variants.iter().all(|v| v.fields.is_empty())
2432 /// Return a `VariantDef` given a variant id.
2433 pub fn variant_with_id(&self, vid: DefId) -> &VariantDef {
2434 self.variants.iter().find(|v| v.def_id == vid).expect("variant_with_id: unknown variant")
2437 /// Return a `VariantDef` given a constructor id.
2438 pub fn variant_with_ctor_id(&self, cid: DefId) -> &VariantDef {
2441 .find(|v| v.ctor_def_id == Some(cid))
2442 .expect("variant_with_ctor_id: unknown variant")
2445 /// Return the index of `VariantDef` given a variant id.
2446 pub fn variant_index_with_id(&self, vid: DefId) -> VariantIdx {
2449 .find(|(_, v)| v.def_id == vid)
2450 .expect("variant_index_with_id: unknown variant")
2454 /// Return the index of `VariantDef` given a constructor id.
2455 pub fn variant_index_with_ctor_id(&self, cid: DefId) -> VariantIdx {
2458 .find(|(_, v)| v.ctor_def_id == Some(cid))
2459 .expect("variant_index_with_ctor_id: unknown variant")
2463 pub fn variant_of_res(&self, res: Res) -> &VariantDef {
2465 Res::Def(DefKind::Variant, vid) => self.variant_with_id(vid),
2466 Res::Def(DefKind::Ctor(..), cid) => self.variant_with_ctor_id(cid),
2467 Res::Def(DefKind::Struct, _)
2468 | Res::Def(DefKind::Union, _)
2469 | Res::Def(DefKind::TyAlias, _)
2470 | Res::Def(DefKind::AssocTy, _)
2472 | Res::SelfCtor(..) => self.non_enum_variant(),
2473 _ => bug!("unexpected res {:?} in variant_of_res", res),
2478 pub fn eval_explicit_discr(&self, tcx: TyCtxt<'tcx>, expr_did: DefId) -> Option<Discr<'tcx>> {
2479 assert!(self.is_enum());
2480 let param_env = tcx.param_env(expr_did);
2481 let repr_type = self.repr.discr_type();
2482 match tcx.const_eval_poly(expr_did) {
2484 let ty = repr_type.to_ty(tcx);
2485 if let Some(b) = val.try_to_bits_for_ty(tcx, param_env, ty) {
2486 trace!("discriminants: {} ({:?})", b, repr_type);
2487 Some(Discr { val: b, ty })
2489 info!("invalid enum discriminant: {:#?}", val);
2490 crate::mir::interpret::struct_error(
2491 tcx.at(tcx.def_span(expr_did)),
2492 "constant evaluation of enum discriminant resulted in non-integer",
2499 let msg = match err {
2500 ErrorHandled::Reported(ErrorReported) | ErrorHandled::Linted => {
2501 "enum discriminant evaluation failed"
2503 ErrorHandled::TooGeneric => "enum discriminant depends on generics",
2505 tcx.sess.delay_span_bug(tcx.def_span(expr_did), msg);
2512 pub fn discriminants(
2515 ) -> impl Iterator<Item = (VariantIdx, Discr<'tcx>)> + Captures<'tcx> {
2516 assert!(self.is_enum());
2517 let repr_type = self.repr.discr_type();
2518 let initial = repr_type.initial_discriminant(tcx);
2519 let mut prev_discr = None::<Discr<'tcx>>;
2520 self.variants.iter_enumerated().map(move |(i, v)| {
2521 let mut discr = prev_discr.map_or(initial, |d| d.wrap_incr(tcx));
2522 if let VariantDiscr::Explicit(expr_did) = v.discr {
2523 if let Some(new_discr) = self.eval_explicit_discr(tcx, expr_did) {
2527 prev_discr = Some(discr);
2534 pub fn variant_range(&self) -> Range<VariantIdx> {
2535 VariantIdx::new(0)..VariantIdx::new(self.variants.len())
2538 /// Computes the discriminant value used by a specific variant.
2539 /// Unlike `discriminants`, this is (amortized) constant-time,
2540 /// only doing at most one query for evaluating an explicit
2541 /// discriminant (the last one before the requested variant),
2542 /// assuming there are no constant-evaluation errors there.
2544 pub fn discriminant_for_variant(
2547 variant_index: VariantIdx,
2549 assert!(self.is_enum());
2550 let (val, offset) = self.discriminant_def_for_variant(variant_index);
2551 let explicit_value = val
2552 .and_then(|expr_did| self.eval_explicit_discr(tcx, expr_did))
2553 .unwrap_or_else(|| self.repr.discr_type().initial_discriminant(tcx));
2554 explicit_value.checked_add(tcx, offset as u128).0
2557 /// Yields a `DefId` for the discriminant and an offset to add to it
2558 /// Alternatively, if there is no explicit discriminant, returns the
2559 /// inferred discriminant directly.
2560 pub fn discriminant_def_for_variant(&self, variant_index: VariantIdx) -> (Option<DefId>, u32) {
2561 assert!(!self.variants.is_empty());
2562 let mut explicit_index = variant_index.as_u32();
2565 match self.variants[VariantIdx::from_u32(explicit_index)].discr {
2566 ty::VariantDiscr::Relative(0) => {
2570 ty::VariantDiscr::Relative(distance) => {
2571 explicit_index -= distance;
2573 ty::VariantDiscr::Explicit(did) => {
2574 expr_did = Some(did);
2579 (expr_did, variant_index.as_u32() - explicit_index)
2582 pub fn destructor(&self, tcx: TyCtxt<'tcx>) -> Option<Destructor> {
2583 tcx.adt_destructor(self.did)
2586 /// Returns a list of types such that `Self: Sized` if and only
2587 /// if that type is `Sized`, or `TyErr` if this type is recursive.
2589 /// Oddly enough, checking that the sized-constraint is `Sized` is
2590 /// actually more expressive than checking all members:
2591 /// the `Sized` trait is inductive, so an associated type that references
2592 /// `Self` would prevent its containing ADT from being `Sized`.
2594 /// Due to normalization being eager, this applies even if
2595 /// the associated type is behind a pointer (e.g., issue #31299).
2596 pub fn sized_constraint(&self, tcx: TyCtxt<'tcx>) -> &'tcx [Ty<'tcx>] {
2597 tcx.adt_sized_constraint(self.did).0
2601 impl<'tcx> FieldDef {
2602 /// Returns the type of this field. The `subst` is typically obtained
2603 /// via the second field of `TyKind::AdtDef`.
2604 pub fn ty(&self, tcx: TyCtxt<'tcx>, subst: SubstsRef<'tcx>) -> Ty<'tcx> {
2605 tcx.type_of(self.did).subst(tcx, subst)
2609 /// Represents the various closure traits in the language. This
2610 /// will determine the type of the environment (`self`, in the
2611 /// desugaring) argument that the closure expects.
2613 /// You can get the environment type of a closure using
2614 /// `tcx.closure_env_ty()`.
2615 #[derive(Clone, Copy, PartialOrd, Ord, PartialEq, Eq, Hash, Debug, TyEncodable, TyDecodable)]
2616 #[derive(HashStable)]
2617 pub enum ClosureKind {
2618 // Warning: Ordering is significant here! The ordering is chosen
2619 // because the trait Fn is a subtrait of FnMut and so in turn, and
2620 // hence we order it so that Fn < FnMut < FnOnce.
2626 impl<'tcx> ClosureKind {
2627 // This is the initial value used when doing upvar inference.
2628 pub const LATTICE_BOTTOM: ClosureKind = ClosureKind::Fn;
2630 pub fn trait_did(&self, tcx: TyCtxt<'tcx>) -> DefId {
2632 ClosureKind::Fn => tcx.require_lang_item(LangItem::Fn, None),
2633 ClosureKind::FnMut => tcx.require_lang_item(LangItem::FnMut, None),
2634 ClosureKind::FnOnce => tcx.require_lang_item(LangItem::FnOnce, None),
2638 /// Returns `true` if a type that impls this closure kind
2639 /// must also implement `other`.
2640 pub fn extends(self, other: ty::ClosureKind) -> bool {
2643 (ClosureKind::Fn, ClosureKind::Fn)
2644 | (ClosureKind::Fn, ClosureKind::FnMut)
2645 | (ClosureKind::Fn, ClosureKind::FnOnce)
2646 | (ClosureKind::FnMut, ClosureKind::FnMut)
2647 | (ClosureKind::FnMut, ClosureKind::FnOnce)
2648 | (ClosureKind::FnOnce, ClosureKind::FnOnce)
2652 /// Returns the representative scalar type for this closure kind.
2653 /// See `TyS::to_opt_closure_kind` for more details.
2654 pub fn to_ty(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
2656 ty::ClosureKind::Fn => tcx.types.i8,
2657 ty::ClosureKind::FnMut => tcx.types.i16,
2658 ty::ClosureKind::FnOnce => tcx.types.i32,
2664 pub fn from_mutbl(m: hir::Mutability) -> BorrowKind {
2666 hir::Mutability::Mut => MutBorrow,
2667 hir::Mutability::Not => ImmBorrow,
2671 /// Returns a mutability `m` such that an `&m T` pointer could be used to obtain this borrow
2672 /// kind. Because borrow kinds are richer than mutabilities, we sometimes have to pick a
2673 /// mutability that is stronger than necessary so that it at least *would permit* the borrow in
2675 pub fn to_mutbl_lossy(self) -> hir::Mutability {
2677 MutBorrow => hir::Mutability::Mut,
2678 ImmBorrow => hir::Mutability::Not,
2680 // We have no type corresponding to a unique imm borrow, so
2681 // use `&mut`. It gives all the capabilities of an `&uniq`
2682 // and hence is a safe "over approximation".
2683 UniqueImmBorrow => hir::Mutability::Mut,
2687 pub fn to_user_str(&self) -> &'static str {
2689 MutBorrow => "mutable",
2690 ImmBorrow => "immutable",
2691 UniqueImmBorrow => "uniquely immutable",
2696 pub type Attributes<'tcx> = &'tcx [ast::Attribute];
2698 #[derive(Debug, PartialEq, Eq)]
2699 pub enum ImplOverlapKind {
2700 /// These impls are always allowed to overlap.
2702 /// Whether or not the impl is permitted due to the trait being a `#[marker]` trait
2705 /// These impls are allowed to overlap, but that raises
2706 /// an issue #33140 future-compatibility warning.
2708 /// Some background: in Rust 1.0, the trait-object types `Send + Sync` (today's
2709 /// `dyn Send + Sync`) and `Sync + Send` (now `dyn Sync + Send`) were different.
2711 /// The widely-used version 0.1.0 of the crate `traitobject` had accidentally relied
2712 /// that difference, making what reduces to the following set of impls:
2716 /// impl Trait for dyn Send + Sync {}
2717 /// impl Trait for dyn Sync + Send {}
2720 /// Obviously, once we made these types be identical, that code causes a coherence
2721 /// error and a fairly big headache for us. However, luckily for us, the trait
2722 /// `Trait` used in this case is basically a marker trait, and therefore having
2723 /// overlapping impls for it is sound.
2725 /// To handle this, we basically regard the trait as a marker trait, with an additional
2726 /// future-compatibility warning. To avoid accidentally "stabilizing" this feature,
2727 /// it has the following restrictions:
2729 /// 1. The trait must indeed be a marker-like trait (i.e., no items), and must be
2731 /// 2. The trait-ref of both impls must be equal.
2732 /// 3. The trait-ref of both impls must be a trait object type consisting only of
2734 /// 4. Neither of the impls can have any where-clauses.
2736 /// Once `traitobject` 0.1.0 is no longer an active concern, this hack can be removed.
2740 impl<'tcx> TyCtxt<'tcx> {
2741 pub fn typeck_body(self, body: hir::BodyId) -> &'tcx TypeckResults<'tcx> {
2742 self.typeck(self.hir().body_owner_def_id(body))
2745 /// Returns an iterator of the `DefId`s for all body-owners in this
2746 /// crate. If you would prefer to iterate over the bodies
2747 /// themselves, you can do `self.hir().krate().body_ids.iter()`.
2748 pub fn body_owners(self) -> impl Iterator<Item = LocalDefId> + Captures<'tcx> + 'tcx {
2753 .map(move |&body_id| self.hir().body_owner_def_id(body_id))
2756 pub fn par_body_owners<F: Fn(LocalDefId) + sync::Sync + sync::Send>(self, f: F) {
2757 par_iter(&self.hir().krate().body_ids)
2758 .for_each(|&body_id| f(self.hir().body_owner_def_id(body_id)));
2761 pub fn provided_trait_methods(self, id: DefId) -> impl 'tcx + Iterator<Item = &'tcx AssocItem> {
2762 self.associated_items(id)
2763 .in_definition_order()
2764 .filter(|item| item.kind == AssocKind::Fn && item.defaultness.has_value())
2767 fn item_name_from_hir(self, def_id: DefId) -> Option<Ident> {
2768 self.hir().get_if_local(def_id).and_then(|node| node.ident())
2771 fn item_name_from_def_id(self, def_id: DefId) -> Option<Symbol> {
2772 if def_id.index == CRATE_DEF_INDEX {
2773 Some(self.original_crate_name(def_id.krate))
2775 let def_key = self.def_key(def_id);
2776 match def_key.disambiguated_data.data {
2777 // The name of a constructor is that of its parent.
2778 rustc_hir::definitions::DefPathData::Ctor => self.item_name_from_def_id(DefId {
2779 krate: def_id.krate,
2780 index: def_key.parent.unwrap(),
2782 _ => def_key.disambiguated_data.data.get_opt_name(),
2787 /// Look up the name of an item across crates. This does not look at HIR.
2789 /// When possible, this function should be used for cross-crate lookups over
2790 /// [`opt_item_name`] to avoid invalidating the incremental cache. If you
2791 /// need to handle items without a name, or HIR items that will not be
2792 /// serialized cross-crate, or if you need the span of the item, use
2793 /// [`opt_item_name`] instead.
2795 /// [`opt_item_name`]: Self::opt_item_name
2796 pub fn item_name(self, id: DefId) -> Symbol {
2797 // Look at cross-crate items first to avoid invalidating the incremental cache
2798 // unless we have to.
2799 self.item_name_from_def_id(id).unwrap_or_else(|| {
2800 bug!("item_name: no name for {:?}", self.def_path(id));
2804 /// Look up the name and span of an item or [`Node`].
2806 /// See [`item_name`][Self::item_name] for more information.
2807 pub fn opt_item_name(self, def_id: DefId) -> Option<Ident> {
2808 // Look at the HIR first so the span will be correct if this is a local item.
2809 self.item_name_from_hir(def_id)
2810 .or_else(|| self.item_name_from_def_id(def_id).map(Ident::with_dummy_span))
2813 pub fn opt_associated_item(self, def_id: DefId) -> Option<&'tcx AssocItem> {
2814 if let DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy = self.def_kind(def_id) {
2815 Some(self.associated_item(def_id))
2821 pub fn field_index(self, hir_id: hir::HirId, typeck_results: &TypeckResults<'_>) -> usize {
2822 typeck_results.field_indices().get(hir_id).cloned().expect("no index for a field")
2825 pub fn find_field_index(self, ident: Ident, variant: &VariantDef) -> Option<usize> {
2826 variant.fields.iter().position(|field| self.hygienic_eq(ident, field.ident, variant.def_id))
2829 /// Returns `true` if the impls are the same polarity and the trait either
2830 /// has no items or is annotated `#[marker]` and prevents item overrides.
2831 pub fn impls_are_allowed_to_overlap(
2835 ) -> Option<ImplOverlapKind> {
2836 // If either trait impl references an error, they're allowed to overlap,
2837 // as one of them essentially doesn't exist.
2838 if self.impl_trait_ref(def_id1).map_or(false, |tr| tr.references_error())
2839 || self.impl_trait_ref(def_id2).map_or(false, |tr| tr.references_error())
2841 return Some(ImplOverlapKind::Permitted { marker: false });
2844 match (self.impl_polarity(def_id1), self.impl_polarity(def_id2)) {
2845 (ImplPolarity::Reservation, _) | (_, ImplPolarity::Reservation) => {
2846 // `#[rustc_reservation_impl]` impls don't overlap with anything
2848 "impls_are_allowed_to_overlap({:?}, {:?}) = Some(Permitted) (reservations)",
2851 return Some(ImplOverlapKind::Permitted { marker: false });
2853 (ImplPolarity::Positive, ImplPolarity::Negative)
2854 | (ImplPolarity::Negative, ImplPolarity::Positive) => {
2855 // `impl AutoTrait for Type` + `impl !AutoTrait for Type`
2857 "impls_are_allowed_to_overlap({:?}, {:?}) - None (differing polarities)",
2862 (ImplPolarity::Positive, ImplPolarity::Positive)
2863 | (ImplPolarity::Negative, ImplPolarity::Negative) => {}
2866 let is_marker_overlap = {
2867 let is_marker_impl = |def_id: DefId| -> bool {
2868 let trait_ref = self.impl_trait_ref(def_id);
2869 trait_ref.map_or(false, |tr| self.trait_def(tr.def_id).is_marker)
2871 is_marker_impl(def_id1) && is_marker_impl(def_id2)
2874 if is_marker_overlap {
2876 "impls_are_allowed_to_overlap({:?}, {:?}) = Some(Permitted) (marker overlap)",
2879 Some(ImplOverlapKind::Permitted { marker: true })
2881 if let Some(self_ty1) = self.issue33140_self_ty(def_id1) {
2882 if let Some(self_ty2) = self.issue33140_self_ty(def_id2) {
2883 if self_ty1 == self_ty2 {
2885 "impls_are_allowed_to_overlap({:?}, {:?}) - issue #33140 HACK",
2888 return Some(ImplOverlapKind::Issue33140);
2891 "impls_are_allowed_to_overlap({:?}, {:?}) - found {:?} != {:?}",
2892 def_id1, def_id2, self_ty1, self_ty2
2898 debug!("impls_are_allowed_to_overlap({:?}, {:?}) = None", def_id1, def_id2);
2903 /// Returns `ty::VariantDef` if `res` refers to a struct,
2904 /// or variant or their constructors, panics otherwise.
2905 pub fn expect_variant_res(self, res: Res) -> &'tcx VariantDef {
2907 Res::Def(DefKind::Variant, did) => {
2908 let enum_did = self.parent(did).unwrap();
2909 self.adt_def(enum_did).variant_with_id(did)
2911 Res::Def(DefKind::Struct | DefKind::Union, did) => self.adt_def(did).non_enum_variant(),
2912 Res::Def(DefKind::Ctor(CtorOf::Variant, ..), variant_ctor_did) => {
2913 let variant_did = self.parent(variant_ctor_did).unwrap();
2914 let enum_did = self.parent(variant_did).unwrap();
2915 self.adt_def(enum_did).variant_with_ctor_id(variant_ctor_did)
2917 Res::Def(DefKind::Ctor(CtorOf::Struct, ..), ctor_did) => {
2918 let struct_did = self.parent(ctor_did).expect("struct ctor has no parent");
2919 self.adt_def(struct_did).non_enum_variant()
2921 _ => bug!("expect_variant_res used with unexpected res {:?}", res),
2925 /// Returns the possibly-auto-generated MIR of a `(DefId, Subst)` pair.
2926 pub fn instance_mir(self, instance: ty::InstanceDef<'tcx>) -> &'tcx Body<'tcx> {
2928 ty::InstanceDef::Item(def) => match self.def_kind(def.did) {
2931 | DefKind::AssocConst
2933 | DefKind::AnonConst => self.mir_for_ctfe_opt_const_arg(def),
2934 // If the caller wants `mir_for_ctfe` of a function they should not be using
2935 // `instance_mir`, so we'll assume const fn also wants the optimized version.
2936 _ => self.optimized_mir_or_const_arg_mir(def),
2938 ty::InstanceDef::VtableShim(..)
2939 | ty::InstanceDef::ReifyShim(..)
2940 | ty::InstanceDef::Intrinsic(..)
2941 | ty::InstanceDef::FnPtrShim(..)
2942 | ty::InstanceDef::Virtual(..)
2943 | ty::InstanceDef::ClosureOnceShim { .. }
2944 | ty::InstanceDef::DropGlue(..)
2945 | ty::InstanceDef::CloneShim(..) => self.mir_shims(instance),
2949 /// Gets the attributes of a definition.
2950 pub fn get_attrs(self, did: DefId) -> Attributes<'tcx> {
2951 if let Some(did) = did.as_local() {
2952 self.hir().attrs(self.hir().local_def_id_to_hir_id(did))
2954 self.item_attrs(did)
2958 /// Determines whether an item is annotated with an attribute.
2959 pub fn has_attr(self, did: DefId, attr: Symbol) -> bool {
2960 self.sess.contains_name(&self.get_attrs(did), attr)
2963 /// Returns `true` if this is an `auto trait`.
2964 pub fn trait_is_auto(self, trait_def_id: DefId) -> bool {
2965 self.trait_def(trait_def_id).has_auto_impl
2968 /// Returns layout of a generator. Layout might be unavailable if the
2969 /// generator is tainted by errors.
2970 pub fn generator_layout(self, def_id: DefId) -> Option<&'tcx GeneratorLayout<'tcx>> {
2971 self.optimized_mir(def_id).generator_layout.as_ref()
2974 /// Given the `DefId` of an impl, returns the `DefId` of the trait it implements.
2975 /// If it implements no trait, returns `None`.
2976 pub fn trait_id_of_impl(self, def_id: DefId) -> Option<DefId> {
2977 self.impl_trait_ref(def_id).map(|tr| tr.def_id)
2980 /// If the given defid describes a method belonging to an impl, returns the
2981 /// `DefId` of the impl that the method belongs to; otherwise, returns `None`.
2982 pub fn impl_of_method(self, def_id: DefId) -> Option<DefId> {
2983 self.opt_associated_item(def_id).and_then(|trait_item| match trait_item.container {
2984 TraitContainer(_) => None,
2985 ImplContainer(def_id) => Some(def_id),
2989 /// Looks up the span of `impl_did` if the impl is local; otherwise returns `Err`
2990 /// with the name of the crate containing the impl.
2991 pub fn span_of_impl(self, impl_did: DefId) -> Result<Span, Symbol> {
2992 if let Some(impl_did) = impl_did.as_local() {
2993 let hir_id = self.hir().local_def_id_to_hir_id(impl_did);
2994 Ok(self.hir().span(hir_id))
2996 Err(self.crate_name(impl_did.krate))
3000 /// Hygienically compares a use-site name (`use_name`) for a field or an associated item with
3001 /// its supposed definition name (`def_name`). The method also needs `DefId` of the supposed
3002 /// definition's parent/scope to perform comparison.
3003 pub fn hygienic_eq(self, use_name: Ident, def_name: Ident, def_parent_def_id: DefId) -> bool {
3004 // We could use `Ident::eq` here, but we deliberately don't. The name
3005 // comparison fails frequently, and we want to avoid the expensive
3006 // `normalize_to_macros_2_0()` calls required for the span comparison whenever possible.
3007 use_name.name == def_name.name
3011 .hygienic_eq(def_name.span.ctxt(), self.expansion_that_defined(def_parent_def_id))
3014 pub fn expansion_that_defined(self, scope: DefId) -> ExpnId {
3015 match scope.as_local() {
3016 // Parsing and expansion aren't incremental, so we don't
3017 // need to go through a query for the same-crate case.
3018 Some(scope) => self.hir().definitions().expansion_that_defined(scope),
3019 None => self.expn_that_defined(scope),
3023 pub fn adjust_ident(self, mut ident: Ident, scope: DefId) -> Ident {
3024 ident.span.normalize_to_macros_2_0_and_adjust(self.expansion_that_defined(scope));
3028 pub fn adjust_ident_and_get_scope(
3033 ) -> (Ident, DefId) {
3035 match ident.span.normalize_to_macros_2_0_and_adjust(self.expansion_that_defined(scope))
3037 Some(actual_expansion) => {
3038 self.hir().definitions().parent_module_of_macro_def(actual_expansion)
3040 None => self.parent_module(block).to_def_id(),
3045 pub fn is_object_safe(self, key: DefId) -> bool {
3046 self.object_safety_violations(key).is_empty()
3050 #[derive(Clone, HashStable, Debug)]
3051 pub struct AdtSizedConstraint<'tcx>(pub &'tcx [Ty<'tcx>]);
3053 /// Yields the parent function's `DefId` if `def_id` is an `impl Trait` definition.
3054 pub fn is_impl_trait_defn(tcx: TyCtxt<'_>, def_id: DefId) -> Option<DefId> {
3055 if let Some(def_id) = def_id.as_local() {
3056 if let Node::Item(item) = tcx.hir().get(tcx.hir().local_def_id_to_hir_id(def_id)) {
3057 if let hir::ItemKind::OpaqueTy(ref opaque_ty) = item.kind {
3058 return opaque_ty.impl_trait_fn;
3065 pub fn int_ty(ity: ast::IntTy) -> IntTy {
3067 ast::IntTy::Isize => IntTy::Isize,
3068 ast::IntTy::I8 => IntTy::I8,
3069 ast::IntTy::I16 => IntTy::I16,
3070 ast::IntTy::I32 => IntTy::I32,
3071 ast::IntTy::I64 => IntTy::I64,
3072 ast::IntTy::I128 => IntTy::I128,
3076 pub fn uint_ty(uty: ast::UintTy) -> UintTy {
3078 ast::UintTy::Usize => UintTy::Usize,
3079 ast::UintTy::U8 => UintTy::U8,
3080 ast::UintTy::U16 => UintTy::U16,
3081 ast::UintTy::U32 => UintTy::U32,
3082 ast::UintTy::U64 => UintTy::U64,
3083 ast::UintTy::U128 => UintTy::U128,
3087 pub fn float_ty(fty: ast::FloatTy) -> FloatTy {
3089 ast::FloatTy::F32 => FloatTy::F32,
3090 ast::FloatTy::F64 => FloatTy::F64,
3094 pub fn ast_int_ty(ity: IntTy) -> ast::IntTy {
3096 IntTy::Isize => ast::IntTy::Isize,
3097 IntTy::I8 => ast::IntTy::I8,
3098 IntTy::I16 => ast::IntTy::I16,
3099 IntTy::I32 => ast::IntTy::I32,
3100 IntTy::I64 => ast::IntTy::I64,
3101 IntTy::I128 => ast::IntTy::I128,
3105 pub fn ast_uint_ty(uty: UintTy) -> ast::UintTy {
3107 UintTy::Usize => ast::UintTy::Usize,
3108 UintTy::U8 => ast::UintTy::U8,
3109 UintTy::U16 => ast::UintTy::U16,
3110 UintTy::U32 => ast::UintTy::U32,
3111 UintTy::U64 => ast::UintTy::U64,
3112 UintTy::U128 => ast::UintTy::U128,
3116 pub fn provide(providers: &mut ty::query::Providers) {
3117 context::provide(providers);
3118 erase_regions::provide(providers);
3119 layout::provide(providers);
3120 util::provide(providers);
3121 print::provide(providers);
3122 super::util::bug::provide(providers);
3123 *providers = ty::query::Providers {
3124 trait_impls_of: trait_def::trait_impls_of_provider,
3125 all_local_trait_impls: trait_def::all_local_trait_impls,
3126 type_uninhabited_from: inhabitedness::type_uninhabited_from,
3131 /// A map for the local crate mapping each type to a vector of its
3132 /// inherent impls. This is not meant to be used outside of coherence;
3133 /// rather, you should request the vector for a specific type via
3134 /// `tcx.inherent_impls(def_id)` so as to minimize your dependencies
3135 /// (constructing this map requires touching the entire crate).
3136 #[derive(Clone, Debug, Default, HashStable)]
3137 pub struct CrateInherentImpls {
3138 pub inherent_impls: DefIdMap<Vec<DefId>>,
3141 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, HashStable)]
3142 pub struct SymbolName<'tcx> {
3143 /// `&str` gives a consistent ordering, which ensures reproducible builds.
3144 pub name: &'tcx str,
3147 impl<'tcx> SymbolName<'tcx> {
3148 pub fn new(tcx: TyCtxt<'tcx>, name: &str) -> SymbolName<'tcx> {
3150 name: unsafe { str::from_utf8_unchecked(tcx.arena.alloc_slice(name.as_bytes())) },
3155 impl<'tcx> fmt::Display for SymbolName<'tcx> {
3156 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
3157 fmt::Display::fmt(&self.name, fmt)
3161 impl<'tcx> fmt::Debug for SymbolName<'tcx> {
3162 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
3163 fmt::Display::fmt(&self.name, fmt)