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::consts::{Const, ConstInt, ConstKind, InferConst, ScalarInt};
115 pub mod inhabitedness;
117 pub mod normalize_erasing_regions;
132 mod structural_impls;
137 pub struct ResolverOutputs {
138 pub definitions: rustc_hir::definitions::Definitions,
139 pub cstore: Box<CrateStoreDyn>,
140 pub visibilities: FxHashMap<LocalDefId, Visibility>,
141 pub extern_crate_map: FxHashMap<LocalDefId, CrateNum>,
142 pub maybe_unused_trait_imports: FxHashSet<LocalDefId>,
143 pub maybe_unused_extern_crates: Vec<(LocalDefId, Span)>,
144 pub export_map: ExportMap<LocalDefId>,
145 pub glob_map: FxHashMap<LocalDefId, FxHashSet<Symbol>>,
146 /// Extern prelude entries. The value is `true` if the entry was introduced
147 /// via `extern crate` item and not `--extern` option or compiler built-in.
148 pub extern_prelude: FxHashMap<Symbol, bool>,
151 #[derive(Clone, Copy, PartialEq, Eq, Debug, HashStable, Hash)]
152 pub enum AssocItemContainer {
153 TraitContainer(DefId),
154 ImplContainer(DefId),
157 impl AssocItemContainer {
158 /// Asserts that this is the `DefId` of an associated item declared
159 /// in a trait, and returns the trait `DefId`.
160 pub fn assert_trait(&self) -> DefId {
162 TraitContainer(id) => id,
163 _ => bug!("associated item has wrong container type: {:?}", self),
167 pub fn id(&self) -> DefId {
169 TraitContainer(id) => id,
170 ImplContainer(id) => id,
175 /// The "header" of an impl is everything outside the body: a Self type, a trait
176 /// ref (in the case of a trait impl), and a set of predicates (from the
177 /// bounds / where-clauses).
178 #[derive(Clone, Debug, TypeFoldable)]
179 pub struct ImplHeader<'tcx> {
180 pub impl_def_id: DefId,
181 pub self_ty: Ty<'tcx>,
182 pub trait_ref: Option<TraitRef<'tcx>>,
183 pub predicates: Vec<Predicate<'tcx>>,
186 #[derive(Copy, Clone, PartialEq, TyEncodable, TyDecodable, HashStable, Debug)]
187 pub enum ImplPolarity {
188 /// `impl Trait for Type`
190 /// `impl !Trait for Type`
192 /// `#[rustc_reservation_impl] impl Trait for Type`
194 /// This is a "stability hack", not a real Rust feature.
195 /// See #64631 for details.
199 #[derive(Copy, Clone, Debug, PartialEq, HashStable, Eq, Hash)]
200 pub struct AssocItem {
202 #[stable_hasher(project(name))]
206 pub defaultness: hir::Defaultness,
207 pub container: AssocItemContainer,
209 /// Whether this is a method with an explicit self
210 /// as its first parameter, allowing method calls.
211 pub fn_has_self_parameter: bool,
214 #[derive(Copy, Clone, PartialEq, Debug, HashStable, Eq, Hash)]
222 pub fn namespace(&self) -> Namespace {
224 ty::AssocKind::Type => Namespace::TypeNS,
225 ty::AssocKind::Const | ty::AssocKind::Fn => Namespace::ValueNS,
229 pub fn as_def_kind(&self) -> DefKind {
231 AssocKind::Const => DefKind::AssocConst,
232 AssocKind::Fn => DefKind::AssocFn,
233 AssocKind::Type => DefKind::AssocTy,
239 pub fn signature(&self, tcx: TyCtxt<'_>) -> String {
241 ty::AssocKind::Fn => {
242 // We skip the binder here because the binder would deanonymize all
243 // late-bound regions, and we don't want method signatures to show up
244 // `as for<'r> fn(&'r MyType)`. Pretty-printing handles late-bound
245 // regions just fine, showing `fn(&MyType)`.
246 tcx.fn_sig(self.def_id).skip_binder().to_string()
248 ty::AssocKind::Type => format!("type {};", self.ident),
249 ty::AssocKind::Const => {
250 format!("const {}: {:?};", self.ident, tcx.type_of(self.def_id))
256 /// A list of `ty::AssocItem`s in definition order that allows for efficient lookup by name.
258 /// When doing lookup by name, we try to postpone hygienic comparison for as long as possible since
259 /// it is relatively expensive. Instead, items are indexed by `Symbol` and hygienic comparison is
260 /// done only on items with the same name.
261 #[derive(Debug, Clone, PartialEq, HashStable)]
262 pub struct AssociatedItems<'tcx> {
263 items: SortedIndexMultiMap<u32, Symbol, &'tcx ty::AssocItem>,
266 impl<'tcx> AssociatedItems<'tcx> {
267 /// Constructs an `AssociatedItems` map from a series of `ty::AssocItem`s in definition order.
268 pub fn new(items_in_def_order: impl IntoIterator<Item = &'tcx ty::AssocItem>) -> Self {
269 let items = items_in_def_order.into_iter().map(|item| (item.ident.name, item)).collect();
270 AssociatedItems { items }
273 /// Returns a slice of associated items in the order they were defined.
275 /// New code should avoid relying on definition order. If you need a particular associated item
276 /// for a known trait, make that trait a lang item instead of indexing this array.
277 pub fn in_definition_order(&self) -> impl '_ + Iterator<Item = &ty::AssocItem> {
278 self.items.iter().map(|(_, v)| *v)
281 pub fn len(&self) -> usize {
285 /// Returns an iterator over all associated items with the given name, ignoring hygiene.
286 pub fn filter_by_name_unhygienic(
289 ) -> impl '_ + Iterator<Item = &ty::AssocItem> {
290 self.items.get_by_key(&name).copied()
293 /// Returns an iterator over all associated items with the given name.
295 /// Multiple items may have the same name if they are in different `Namespace`s. For example,
296 /// an associated type can have the same name as a method. Use one of the `find_by_name_and_*`
297 /// methods below if you know which item you are looking for.
298 pub fn filter_by_name(
302 parent_def_id: DefId,
303 ) -> impl 'a + Iterator<Item = &'a ty::AssocItem> {
304 self.filter_by_name_unhygienic(ident.name)
305 .filter(move |item| tcx.hygienic_eq(ident, item.ident, parent_def_id))
308 /// Returns the associated item with the given name and `AssocKind`, if one exists.
309 pub fn find_by_name_and_kind(
314 parent_def_id: DefId,
315 ) -> Option<&ty::AssocItem> {
316 self.filter_by_name_unhygienic(ident.name)
317 .filter(|item| item.kind == kind)
318 .find(|item| tcx.hygienic_eq(ident, item.ident, parent_def_id))
321 /// Returns the associated item with the given name in the given `Namespace`, if one exists.
322 pub fn find_by_name_and_namespace(
327 parent_def_id: DefId,
328 ) -> Option<&ty::AssocItem> {
329 self.filter_by_name_unhygienic(ident.name)
330 .filter(|item| item.kind.namespace() == ns)
331 .find(|item| tcx.hygienic_eq(ident, item.ident, parent_def_id))
335 #[derive(Clone, Debug, PartialEq, Eq, Copy, Hash, TyEncodable, TyDecodable, HashStable)]
336 pub enum Visibility {
337 /// Visible everywhere (including in other crates).
339 /// Visible only in the given crate-local module.
341 /// Not visible anywhere in the local crate. This is the visibility of private external items.
345 pub trait DefIdTree: Copy {
346 fn parent(self, id: DefId) -> Option<DefId>;
348 fn is_descendant_of(self, mut descendant: DefId, ancestor: DefId) -> bool {
349 if descendant.krate != ancestor.krate {
353 while descendant != ancestor {
354 match self.parent(descendant) {
355 Some(parent) => descendant = parent,
356 None => return false,
363 impl<'tcx> DefIdTree for TyCtxt<'tcx> {
364 fn parent(self, id: DefId) -> Option<DefId> {
365 self.def_key(id).parent.map(|index| DefId { index, ..id })
370 pub fn from_hir(visibility: &hir::Visibility<'_>, id: hir::HirId, tcx: TyCtxt<'_>) -> Self {
371 match visibility.node {
372 hir::VisibilityKind::Public => Visibility::Public,
373 hir::VisibilityKind::Crate(_) => Visibility::Restricted(DefId::local(CRATE_DEF_INDEX)),
374 hir::VisibilityKind::Restricted { ref path, .. } => match path.res {
375 // If there is no resolution, `resolve` will have already reported an error, so
376 // assume that the visibility is public to avoid reporting more privacy errors.
377 Res::Err => Visibility::Public,
378 def => Visibility::Restricted(def.def_id()),
380 hir::VisibilityKind::Inherited => {
381 Visibility::Restricted(tcx.parent_module(id).to_def_id())
386 /// Returns `true` if an item with this visibility is accessible from the given block.
387 pub fn is_accessible_from<T: DefIdTree>(self, module: DefId, tree: T) -> bool {
388 let restriction = match self {
389 // Public items are visible everywhere.
390 Visibility::Public => return true,
391 // Private items from other crates are visible nowhere.
392 Visibility::Invisible => return false,
393 // Restricted items are visible in an arbitrary local module.
394 Visibility::Restricted(other) if other.krate != module.krate => return false,
395 Visibility::Restricted(module) => module,
398 tree.is_descendant_of(module, restriction)
401 /// Returns `true` if this visibility is at least as accessible as the given visibility
402 pub fn is_at_least<T: DefIdTree>(self, vis: Visibility, tree: T) -> bool {
403 let vis_restriction = match vis {
404 Visibility::Public => return self == Visibility::Public,
405 Visibility::Invisible => return true,
406 Visibility::Restricted(module) => module,
409 self.is_accessible_from(vis_restriction, tree)
412 // Returns `true` if this item is visible anywhere in the local crate.
413 pub fn is_visible_locally(self) -> bool {
415 Visibility::Public => true,
416 Visibility::Restricted(def_id) => def_id.is_local(),
417 Visibility::Invisible => false,
422 /// The crate variances map is computed during typeck and contains the
423 /// variance of every item in the local crate. You should not use it
424 /// directly, because to do so will make your pass dependent on the
425 /// HIR of every item in the local crate. Instead, use
426 /// `tcx.variances_of()` to get the variance for a *particular*
428 #[derive(HashStable, Debug)]
429 pub struct CrateVariancesMap<'tcx> {
430 /// For each item with generics, maps to a vector of the variance
431 /// of its generics. If an item has no generics, it will have no
433 pub variances: FxHashMap<DefId, &'tcx [ty::Variance]>,
436 // Contains information needed to resolve types and (in the future) look up
437 // the types of AST nodes.
438 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
439 pub struct CReaderCacheKey {
444 #[allow(rustc::usage_of_ty_tykind)]
445 pub struct TyS<'tcx> {
446 /// This field shouldn't be used directly and may be removed in the future.
447 /// Use `TyS::kind()` instead.
449 /// This field shouldn't be used directly and may be removed in the future.
450 /// Use `TyS::flags()` instead.
453 /// This is a kind of confusing thing: it stores the smallest
456 /// (a) the binder itself captures nothing but
457 /// (b) all the late-bound things within the type are captured
458 /// by some sub-binder.
460 /// So, for a type without any late-bound things, like `u32`, this
461 /// will be *innermost*, because that is the innermost binder that
462 /// captures nothing. But for a type `&'D u32`, where `'D` is a
463 /// late-bound region with De Bruijn index `D`, this would be `D + 1`
464 /// -- the binder itself does not capture `D`, but `D` is captured
465 /// by an inner binder.
467 /// We call this concept an "exclusive" binder `D` because all
468 /// De Bruijn indices within the type are contained within `0..D`
470 outer_exclusive_binder: ty::DebruijnIndex,
473 impl<'tcx> TyS<'tcx> {
474 /// A constructor used only for internal testing.
475 #[allow(rustc::usage_of_ty_tykind)]
476 pub fn make_for_test(
479 outer_exclusive_binder: ty::DebruijnIndex,
481 TyS { kind, flags, outer_exclusive_binder }
485 // `TyS` is used a lot. Make sure it doesn't unintentionally get bigger.
486 #[cfg(target_arch = "x86_64")]
487 static_assert_size!(TyS<'_>, 32);
489 impl<'tcx> Ord for TyS<'tcx> {
490 fn cmp(&self, other: &TyS<'tcx>) -> Ordering {
491 self.kind().cmp(other.kind())
495 impl<'tcx> PartialOrd for TyS<'tcx> {
496 fn partial_cmp(&self, other: &TyS<'tcx>) -> Option<Ordering> {
497 Some(self.kind().cmp(other.kind()))
501 impl<'tcx> PartialEq for TyS<'tcx> {
503 fn eq(&self, other: &TyS<'tcx>) -> bool {
507 impl<'tcx> Eq for TyS<'tcx> {}
509 impl<'tcx> Hash for TyS<'tcx> {
510 fn hash<H: Hasher>(&self, s: &mut H) {
511 (self as *const TyS<'_>).hash(s)
515 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for TyS<'tcx> {
516 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
520 // The other fields just provide fast access to information that is
521 // also contained in `kind`, so no need to hash them.
524 outer_exclusive_binder: _,
527 kind.hash_stable(hcx, hasher);
531 #[rustc_diagnostic_item = "Ty"]
532 pub type Ty<'tcx> = &'tcx TyS<'tcx>;
546 pub struct UpvarPath {
547 pub hir_id: hir::HirId,
550 /// Upvars do not get their own `NodeId`. Instead, we use the pair of
551 /// the original var ID (that is, the root variable that is referenced
552 /// by the upvar) and the ID of the closure expression.
553 #[derive(Clone, Copy, PartialEq, Eq, Hash, TyEncodable, TyDecodable, TypeFoldable, HashStable)]
555 pub var_path: UpvarPath,
556 pub closure_expr_id: LocalDefId,
560 pub fn new(var_hir_id: hir::HirId, closure_def_id: LocalDefId) -> UpvarId {
561 UpvarId { var_path: UpvarPath { hir_id: var_hir_id }, closure_expr_id: closure_def_id }
565 #[derive(Clone, PartialEq, Debug, TyEncodable, TyDecodable, TypeFoldable, Copy, HashStable)]
566 pub enum BorrowKind {
567 /// Data must be immutable and is aliasable.
570 /// Data must be immutable but not aliasable. This kind of borrow
571 /// cannot currently be expressed by the user and is used only in
572 /// implicit closure bindings. It is needed when the closure
573 /// is borrowing or mutating a mutable referent, e.g.:
576 /// let x: &mut isize = ...;
577 /// let y = || *x += 5;
580 /// If we were to try to translate this closure into a more explicit
581 /// form, we'd encounter an error with the code as written:
584 /// struct Env { x: & &mut isize }
585 /// let x: &mut isize = ...;
586 /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
587 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
590 /// This is then illegal because you cannot mutate a `&mut` found
591 /// in an aliasable location. To solve, you'd have to translate with
592 /// an `&mut` borrow:
595 /// struct Env { x: & &mut isize }
596 /// let x: &mut isize = ...;
597 /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
598 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
601 /// Now the assignment to `**env.x` is legal, but creating a
602 /// mutable pointer to `x` is not because `x` is not mutable. We
603 /// could fix this by declaring `x` as `let mut x`. This is ok in
604 /// user code, if awkward, but extra weird for closures, since the
605 /// borrow is hidden.
607 /// So we introduce a "unique imm" borrow -- the referent is
608 /// immutable, but not aliasable. This solves the problem. For
609 /// simplicity, we don't give users the way to express this
610 /// borrow, it's just used when translating closures.
613 /// Data is mutable and not aliasable.
617 /// Information describing the capture of an upvar. This is computed
618 /// during `typeck`, specifically by `regionck`.
619 #[derive(PartialEq, Clone, Debug, Copy, TyEncodable, TyDecodable, TypeFoldable, HashStable)]
620 pub enum UpvarCapture<'tcx> {
621 /// Upvar is captured by value. This is always true when the
622 /// closure is labeled `move`, but can also be true in other cases
623 /// depending on inference.
625 /// If the upvar was inferred to be captured by value (e.g. `move`
626 /// was not used), then the `Span` points to a usage that
627 /// required it. There may be more than one such usage
628 /// (e.g. `|| { a; a; }`), in which case we pick an
630 ByValue(Option<Span>),
632 /// Upvar is captured by reference.
633 ByRef(UpvarBorrow<'tcx>),
636 #[derive(PartialEq, Clone, Copy, TyEncodable, TyDecodable, TypeFoldable, HashStable)]
637 pub struct UpvarBorrow<'tcx> {
638 /// The kind of borrow: by-ref upvars have access to shared
639 /// immutable borrows, which are not part of the normal language
641 pub kind: BorrowKind,
643 /// Region of the resulting reference.
644 pub region: ty::Region<'tcx>,
647 /// Given the closure DefId this map provides a map of root variables to minimum
648 /// set of `CapturedPlace`s that need to be tracked to support all captures of that closure.
649 pub type MinCaptureInformationMap<'tcx> = FxHashMap<DefId, RootVariableMinCaptureList<'tcx>>;
651 /// Part of `MinCaptureInformationMap`; Maps a root variable to the list of `CapturedPlace`.
652 /// Used to track the minimum set of `Place`s that need to be captured to support all
653 /// Places captured by the closure starting at a given root variable.
655 /// This provides a convenient and quick way of checking if a variable being used within
656 /// a closure is a capture of a local variable.
657 pub type RootVariableMinCaptureList<'tcx> = FxIndexMap<hir::HirId, MinCaptureList<'tcx>>;
659 /// Part of `MinCaptureInformationMap`; List of `CapturePlace`s.
660 pub type MinCaptureList<'tcx> = Vec<CapturedPlace<'tcx>>;
662 /// A composite describing a `Place` that is captured by a closure.
663 #[derive(PartialEq, Clone, Debug, TyEncodable, TyDecodable, TypeFoldable, HashStable)]
664 pub struct CapturedPlace<'tcx> {
665 /// The `Place` that is captured.
666 pub place: HirPlace<'tcx>,
668 /// `CaptureKind` and expression(s) that resulted in such capture of `place`.
669 pub info: CaptureInfo<'tcx>,
671 /// Represents if `place` can be mutated or not.
672 pub mutability: hir::Mutability,
675 impl CapturedPlace<'tcx> {
676 /// Returns the hir-id of the root variable for the captured place.
677 /// e.g., if `a.b.c` was captured, would return the hir-id for `a`.
678 pub fn get_root_variable(&self) -> hir::HirId {
679 match self.place.base {
680 HirPlaceBase::Upvar(upvar_id) => upvar_id.var_path.hir_id,
681 base => bug!("Expected upvar, found={:?}", base),
686 pub fn place_to_string_for_capture(tcx: TyCtxt<'tcx>, place: &HirPlace<'tcx>) -> String {
687 let name = match place.base {
688 HirPlaceBase::Upvar(upvar_id) => tcx.hir().name(upvar_id.var_path.hir_id).to_string(),
689 _ => bug!("Capture_information should only contain upvars"),
691 let mut curr_string = name;
693 for (i, proj) in place.projections.iter().enumerate() {
695 HirProjectionKind::Deref => {
696 curr_string = format!("*{}", curr_string);
698 HirProjectionKind::Field(idx, variant) => match place.ty_before_projection(i).kind() {
699 ty::Adt(def, ..) => {
700 curr_string = format!(
703 def.variants[variant].fields[idx as usize].ident.name.as_str()
707 curr_string = format!("{}.{}", curr_string, idx);
711 "Field projection applied to a type other than Adt or Tuple: {:?}.",
712 place.ty_before_projection(i).kind()
716 proj => bug!("{:?} unexpected because it isn't captured", proj),
720 curr_string.to_string()
723 /// Part of `MinCaptureInformationMap`; describes the capture kind (&, &mut, move)
724 /// for a particular capture as well as identifying the part of the source code
725 /// that triggered this capture to occur.
726 #[derive(PartialEq, Clone, Debug, Copy, TyEncodable, TyDecodable, TypeFoldable, HashStable)]
727 pub struct CaptureInfo<'tcx> {
728 /// Expr Id pointing to use that resulted in selecting the current capture kind
732 /// let mut t = (0,1);
735 /// println!("{}",t); // L1
739 /// `capture_kind_expr_id` will point to the use on L2 and `path_expr_id` will point to the
742 /// If the user doesn't enable feature `capture_disjoint_fields` (RFC 2229) then, it is
743 /// possible that we don't see the use of a particular place resulting in capture_kind_expr_id being
744 /// None. In such case we fallback on uvpars_mentioned for span.
755 /// In this example, if `capture_disjoint_fields` is **not** set, then x will be captured,
756 /// but we won't see it being used during capture analysis, since it's essentially a discard.
757 pub capture_kind_expr_id: Option<hir::HirId>,
758 /// Expr Id pointing to use that resulted the corresponding place being captured
760 /// See `capture_kind_expr_id` for example.
762 pub path_expr_id: Option<hir::HirId>,
764 /// Capture mode that was selected
765 pub capture_kind: UpvarCapture<'tcx>,
768 pub type UpvarListMap = FxHashMap<DefId, FxIndexMap<hir::HirId, UpvarId>>;
769 pub type UpvarCaptureMap<'tcx> = FxHashMap<UpvarId, UpvarCapture<'tcx>>;
771 impl ty::EarlyBoundRegion {
772 /// Does this early bound region have a name? Early bound regions normally
773 /// always have names except when using anonymous lifetimes (`'_`).
774 pub fn has_name(&self) -> bool {
775 self.name != kw::UnderscoreLifetime
779 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable)]
780 pub enum GenericParamDefKind {
784 object_lifetime_default: ObjectLifetimeDefault,
785 synthetic: Option<hir::SyntheticTyParamKind>,
790 impl GenericParamDefKind {
791 pub fn descr(&self) -> &'static str {
793 GenericParamDefKind::Lifetime => "lifetime",
794 GenericParamDefKind::Type { .. } => "type",
795 GenericParamDefKind::Const => "constant",
798 pub fn to_ord(&self, tcx: TyCtxt<'_>) -> ast::ParamKindOrd {
800 GenericParamDefKind::Lifetime => ast::ParamKindOrd::Lifetime,
801 GenericParamDefKind::Type { .. } => ast::ParamKindOrd::Type,
802 GenericParamDefKind::Const => {
803 ast::ParamKindOrd::Const { unordered: tcx.features().const_generics }
809 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable)]
810 pub struct GenericParamDef {
815 /// `pure_wrt_drop`, set by the (unsafe) `#[may_dangle]` attribute
816 /// on generic parameter `'a`/`T`, asserts data behind the parameter
817 /// `'a`/`T` won't be accessed during the parent type's `Drop` impl.
818 pub pure_wrt_drop: bool,
820 pub kind: GenericParamDefKind,
823 impl GenericParamDef {
824 pub fn to_early_bound_region_data(&self) -> ty::EarlyBoundRegion {
825 if let GenericParamDefKind::Lifetime = self.kind {
826 ty::EarlyBoundRegion { def_id: self.def_id, index: self.index, name: self.name }
828 bug!("cannot convert a non-lifetime parameter def to an early bound region")
834 pub struct GenericParamCount {
835 pub lifetimes: usize,
840 /// Information about the formal type/lifetime parameters associated
841 /// with an item or method. Analogous to `hir::Generics`.
843 /// The ordering of parameters is the same as in `Subst` (excluding child generics):
844 /// `Self` (optionally), `Lifetime` params..., `Type` params...
845 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable)]
846 pub struct Generics {
847 pub parent: Option<DefId>,
848 pub parent_count: usize,
849 pub params: Vec<GenericParamDef>,
851 /// Reverse map to the `index` field of each `GenericParamDef`.
852 #[stable_hasher(ignore)]
853 pub param_def_id_to_index: FxHashMap<DefId, u32>,
856 pub has_late_bound_regions: Option<Span>,
859 impl<'tcx> Generics {
860 pub fn count(&self) -> usize {
861 self.parent_count + self.params.len()
864 pub fn own_counts(&self) -> GenericParamCount {
865 // We could cache this as a property of `GenericParamCount`, but
866 // the aim is to refactor this away entirely eventually and the
867 // presence of this method will be a constant reminder.
868 let mut own_counts = GenericParamCount::default();
870 for param in &self.params {
872 GenericParamDefKind::Lifetime => own_counts.lifetimes += 1,
873 GenericParamDefKind::Type { .. } => own_counts.types += 1,
874 GenericParamDefKind::Const => own_counts.consts += 1,
881 pub fn own_defaults(&self) -> GenericParamCount {
882 let mut own_defaults = GenericParamCount::default();
884 for param in &self.params {
886 GenericParamDefKind::Lifetime => (),
887 GenericParamDefKind::Type { has_default, .. } => {
888 own_defaults.types += has_default as usize;
890 GenericParamDefKind::Const => {
891 // FIXME(const_generics:defaults)
899 pub fn requires_monomorphization(&self, tcx: TyCtxt<'tcx>) -> bool {
900 if self.own_requires_monomorphization() {
904 if let Some(parent_def_id) = self.parent {
905 let parent = tcx.generics_of(parent_def_id);
906 parent.requires_monomorphization(tcx)
912 pub fn own_requires_monomorphization(&self) -> bool {
913 for param in &self.params {
915 GenericParamDefKind::Type { .. } | GenericParamDefKind::Const => return true,
916 GenericParamDefKind::Lifetime => {}
922 /// Returns the `GenericParamDef` with the given index.
923 pub fn param_at(&'tcx self, param_index: usize, tcx: TyCtxt<'tcx>) -> &'tcx GenericParamDef {
924 if let Some(index) = param_index.checked_sub(self.parent_count) {
927 tcx.generics_of(self.parent.expect("parent_count > 0 but no parent?"))
928 .param_at(param_index, tcx)
932 /// Returns the `GenericParamDef` associated with this `EarlyBoundRegion`.
935 param: &EarlyBoundRegion,
937 ) -> &'tcx GenericParamDef {
938 let param = self.param_at(param.index as usize, tcx);
940 GenericParamDefKind::Lifetime => param,
941 _ => bug!("expected lifetime parameter, but found another generic parameter"),
945 /// Returns the `GenericParamDef` associated with this `ParamTy`.
946 pub fn type_param(&'tcx self, param: &ParamTy, tcx: TyCtxt<'tcx>) -> &'tcx GenericParamDef {
947 let param = self.param_at(param.index as usize, tcx);
949 GenericParamDefKind::Type { .. } => param,
950 _ => bug!("expected type parameter, but found another generic parameter"),
954 /// Returns the `GenericParamDef` associated with this `ParamConst`.
955 pub fn const_param(&'tcx self, param: &ParamConst, tcx: TyCtxt<'tcx>) -> &GenericParamDef {
956 let param = self.param_at(param.index as usize, tcx);
958 GenericParamDefKind::Const => param,
959 _ => bug!("expected const parameter, but found another generic parameter"),
964 /// Bounds on generics.
965 #[derive(Copy, Clone, Default, Debug, TyEncodable, TyDecodable, HashStable)]
966 pub struct GenericPredicates<'tcx> {
967 pub parent: Option<DefId>,
968 pub predicates: &'tcx [(Predicate<'tcx>, Span)],
971 impl<'tcx> GenericPredicates<'tcx> {
975 substs: SubstsRef<'tcx>,
976 ) -> InstantiatedPredicates<'tcx> {
977 let mut instantiated = InstantiatedPredicates::empty();
978 self.instantiate_into(tcx, &mut instantiated, substs);
982 pub fn instantiate_own(
985 substs: SubstsRef<'tcx>,
986 ) -> InstantiatedPredicates<'tcx> {
987 InstantiatedPredicates {
988 predicates: self.predicates.iter().map(|(p, _)| p.subst(tcx, substs)).collect(),
989 spans: self.predicates.iter().map(|(_, sp)| *sp).collect(),
996 instantiated: &mut InstantiatedPredicates<'tcx>,
997 substs: SubstsRef<'tcx>,
999 if let Some(def_id) = self.parent {
1000 tcx.predicates_of(def_id).instantiate_into(tcx, instantiated, substs);
1002 instantiated.predicates.extend(self.predicates.iter().map(|(p, _)| p.subst(tcx, substs)));
1003 instantiated.spans.extend(self.predicates.iter().map(|(_, sp)| *sp));
1006 pub fn instantiate_identity(&self, tcx: TyCtxt<'tcx>) -> InstantiatedPredicates<'tcx> {
1007 let mut instantiated = InstantiatedPredicates::empty();
1008 self.instantiate_identity_into(tcx, &mut instantiated);
1012 fn instantiate_identity_into(
1015 instantiated: &mut InstantiatedPredicates<'tcx>,
1017 if let Some(def_id) = self.parent {
1018 tcx.predicates_of(def_id).instantiate_identity_into(tcx, instantiated);
1020 instantiated.predicates.extend(self.predicates.iter().map(|(p, _)| p));
1021 instantiated.spans.extend(self.predicates.iter().map(|(_, s)| s));
1026 crate struct PredicateInner<'tcx> {
1027 kind: Binder<PredicateKind<'tcx>>,
1029 /// See the comment for the corresponding field of [TyS].
1030 outer_exclusive_binder: ty::DebruijnIndex,
1033 #[cfg(target_arch = "x86_64")]
1034 static_assert_size!(PredicateInner<'_>, 40);
1036 #[derive(Clone, Copy, Lift)]
1037 pub struct Predicate<'tcx> {
1038 inner: &'tcx PredicateInner<'tcx>,
1041 impl<'tcx> PartialEq for Predicate<'tcx> {
1042 fn eq(&self, other: &Self) -> bool {
1043 // `self.kind` is always interned.
1044 ptr::eq(self.inner, other.inner)
1048 impl Hash for Predicate<'_> {
1049 fn hash<H: Hasher>(&self, s: &mut H) {
1050 (self.inner as *const PredicateInner<'_>).hash(s)
1054 impl<'tcx> Eq for Predicate<'tcx> {}
1056 impl<'tcx> Predicate<'tcx> {
1057 /// Gets the inner `Binder<PredicateKind<'tcx>>`.
1059 pub fn kind(self) -> Binder<PredicateKind<'tcx>> {
1064 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for Predicate<'tcx> {
1065 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
1066 let PredicateInner {
1069 // The other fields just provide fast access to information that is
1070 // also contained in `kind`, so no need to hash them.
1072 outer_exclusive_binder: _,
1075 kind.hash_stable(hcx, hasher);
1079 #[derive(Clone, Copy, PartialEq, Eq, Hash, TyEncodable, TyDecodable)]
1080 #[derive(HashStable, TypeFoldable)]
1081 pub enum PredicateKind<'tcx> {
1082 /// Corresponds to `where Foo: Bar<A, B, C>`. `Foo` here would be
1083 /// the `Self` type of the trait reference and `A`, `B`, and `C`
1084 /// would be the type parameters.
1086 /// A trait predicate will have `Constness::Const` if it originates
1087 /// from a bound on a `const fn` without the `?const` opt-out (e.g.,
1088 /// `const fn foobar<Foo: Bar>() {}`).
1089 Trait(TraitPredicate<'tcx>, Constness),
1092 RegionOutlives(RegionOutlivesPredicate<'tcx>),
1095 TypeOutlives(TypeOutlivesPredicate<'tcx>),
1097 /// `where <T as TraitRef>::Name == X`, approximately.
1098 /// See the `ProjectionPredicate` struct for details.
1099 Projection(ProjectionPredicate<'tcx>),
1101 /// No syntax: `T` well-formed.
1102 WellFormed(GenericArg<'tcx>),
1104 /// Trait must be object-safe.
1107 /// No direct syntax. May be thought of as `where T: FnFoo<...>`
1108 /// for some substitutions `...` and `T` being a closure type.
1109 /// Satisfied (or refuted) once we know the closure's kind.
1110 ClosureKind(DefId, SubstsRef<'tcx>, ClosureKind),
1113 Subtype(SubtypePredicate<'tcx>),
1115 /// Constant initializer must evaluate successfully.
1116 ConstEvaluatable(ty::WithOptConstParam<DefId>, SubstsRef<'tcx>),
1118 /// Constants must be equal. The first component is the const that is expected.
1119 ConstEquate(&'tcx Const<'tcx>, &'tcx Const<'tcx>),
1121 /// Represents a type found in the environment that we can use for implied bounds.
1123 /// Only used for Chalk.
1124 TypeWellFormedFromEnv(Ty<'tcx>),
1127 /// The crate outlives map is computed during typeck and contains the
1128 /// outlives of every item in the local crate. You should not use it
1129 /// directly, because to do so will make your pass dependent on the
1130 /// HIR of every item in the local crate. Instead, use
1131 /// `tcx.inferred_outlives_of()` to get the outlives for a *particular*
1133 #[derive(HashStable, Debug)]
1134 pub struct CratePredicatesMap<'tcx> {
1135 /// For each struct with outlive bounds, maps to a vector of the
1136 /// predicate of its outlive bounds. If an item has no outlives
1137 /// bounds, it will have no entry.
1138 pub predicates: FxHashMap<DefId, &'tcx [(Predicate<'tcx>, Span)]>,
1141 impl<'tcx> Predicate<'tcx> {
1142 /// Performs a substitution suitable for going from a
1143 /// poly-trait-ref to supertraits that must hold if that
1144 /// poly-trait-ref holds. This is slightly different from a normal
1145 /// substitution in terms of what happens with bound regions. See
1146 /// lengthy comment below for details.
1147 pub fn subst_supertrait(
1150 trait_ref: &ty::PolyTraitRef<'tcx>,
1151 ) -> Predicate<'tcx> {
1152 // The interaction between HRTB and supertraits is not entirely
1153 // obvious. Let me walk you (and myself) through an example.
1155 // Let's start with an easy case. Consider two traits:
1157 // trait Foo<'a>: Bar<'a,'a> { }
1158 // trait Bar<'b,'c> { }
1160 // Now, if we have a trait reference `for<'x> T: Foo<'x>`, then
1161 // we can deduce that `for<'x> T: Bar<'x,'x>`. Basically, if we
1162 // knew that `Foo<'x>` (for any 'x) then we also know that
1163 // `Bar<'x,'x>` (for any 'x). This more-or-less falls out from
1164 // normal substitution.
1166 // In terms of why this is sound, the idea is that whenever there
1167 // is an impl of `T:Foo<'a>`, it must show that `T:Bar<'a,'a>`
1168 // holds. So if there is an impl of `T:Foo<'a>` that applies to
1169 // all `'a`, then we must know that `T:Bar<'a,'a>` holds for all
1172 // Another example to be careful of is this:
1174 // trait Foo1<'a>: for<'b> Bar1<'a,'b> { }
1175 // trait Bar1<'b,'c> { }
1177 // Here, if we have `for<'x> T: Foo1<'x>`, then what do we know?
1178 // The answer is that we know `for<'x,'b> T: Bar1<'x,'b>`. The
1179 // reason is similar to the previous example: any impl of
1180 // `T:Foo1<'x>` must show that `for<'b> T: Bar1<'x, 'b>`. So
1181 // basically we would want to collapse the bound lifetimes from
1182 // the input (`trait_ref`) and the supertraits.
1184 // To achieve this in practice is fairly straightforward. Let's
1185 // consider the more complicated scenario:
1187 // - We start out with `for<'x> T: Foo1<'x>`. In this case, `'x`
1188 // has a De Bruijn index of 1. We want to produce `for<'x,'b> T: Bar1<'x,'b>`,
1189 // where both `'x` and `'b` would have a DB index of 1.
1190 // The substitution from the input trait-ref is therefore going to be
1191 // `'a => 'x` (where `'x` has a DB index of 1).
1192 // - The super-trait-ref is `for<'b> Bar1<'a,'b>`, where `'a` is an
1193 // early-bound parameter and `'b' is a late-bound parameter with a
1195 // - If we replace `'a` with `'x` from the input, it too will have
1196 // a DB index of 1, and thus we'll have `for<'x,'b> Bar1<'x,'b>`
1197 // just as we wanted.
1199 // There is only one catch. If we just apply the substitution `'a
1200 // => 'x` to `for<'b> Bar1<'a,'b>`, the substitution code will
1201 // adjust the DB index because we substituting into a binder (it
1202 // tries to be so smart...) resulting in `for<'x> for<'b>
1203 // Bar1<'x,'b>` (we have no syntax for this, so use your
1204 // imagination). Basically the 'x will have DB index of 2 and 'b
1205 // will have DB index of 1. Not quite what we want. So we apply
1206 // the substitution to the *contents* of the trait reference,
1207 // rather than the trait reference itself (put another way, the
1208 // substitution code expects equal binding levels in the values
1209 // from the substitution and the value being substituted into, and
1210 // this trick achieves that).
1211 let substs = trait_ref.skip_binder().substs;
1212 let pred = self.kind().skip_binder();
1213 let new = pred.subst(tcx, substs);
1214 tcx.reuse_or_mk_predicate(self, ty::Binder::bind(new))
1218 #[derive(Clone, Copy, PartialEq, Eq, Hash, TyEncodable, TyDecodable)]
1219 #[derive(HashStable, TypeFoldable)]
1220 pub struct TraitPredicate<'tcx> {
1221 pub trait_ref: TraitRef<'tcx>,
1224 pub type PolyTraitPredicate<'tcx> = ty::Binder<TraitPredicate<'tcx>>;
1226 impl<'tcx> TraitPredicate<'tcx> {
1227 pub fn def_id(self) -> DefId {
1228 self.trait_ref.def_id
1231 pub fn self_ty(self) -> Ty<'tcx> {
1232 self.trait_ref.self_ty()
1236 impl<'tcx> PolyTraitPredicate<'tcx> {
1237 pub fn def_id(self) -> DefId {
1238 // Ok to skip binder since trait `DefId` does not care about regions.
1239 self.skip_binder().def_id()
1242 pub fn self_ty(self) -> ty::Binder<Ty<'tcx>> {
1243 self.map_bound(|trait_ref| trait_ref.self_ty())
1247 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, TyEncodable, TyDecodable)]
1248 #[derive(HashStable, TypeFoldable)]
1249 pub struct OutlivesPredicate<A, B>(pub A, pub B); // `A: B`
1250 pub type RegionOutlivesPredicate<'tcx> = OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>;
1251 pub type TypeOutlivesPredicate<'tcx> = OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>;
1252 pub type PolyRegionOutlivesPredicate<'tcx> = ty::Binder<RegionOutlivesPredicate<'tcx>>;
1253 pub type PolyTypeOutlivesPredicate<'tcx> = ty::Binder<TypeOutlivesPredicate<'tcx>>;
1255 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, TyEncodable, TyDecodable)]
1256 #[derive(HashStable, TypeFoldable)]
1257 pub struct SubtypePredicate<'tcx> {
1258 pub a_is_expected: bool,
1262 pub type PolySubtypePredicate<'tcx> = ty::Binder<SubtypePredicate<'tcx>>;
1264 /// This kind of predicate has no *direct* correspondent in the
1265 /// syntax, but it roughly corresponds to the syntactic forms:
1267 /// 1. `T: TraitRef<..., Item = Type>`
1268 /// 2. `<T as TraitRef<...>>::Item == Type` (NYI)
1270 /// In particular, form #1 is "desugared" to the combination of a
1271 /// normal trait predicate (`T: TraitRef<...>`) and one of these
1272 /// predicates. Form #2 is a broader form in that it also permits
1273 /// equality between arbitrary types. Processing an instance of
1274 /// Form #2 eventually yields one of these `ProjectionPredicate`
1275 /// instances to normalize the LHS.
1276 #[derive(Copy, Clone, PartialEq, Eq, Hash, TyEncodable, TyDecodable)]
1277 #[derive(HashStable, TypeFoldable)]
1278 pub struct ProjectionPredicate<'tcx> {
1279 pub projection_ty: ProjectionTy<'tcx>,
1283 pub type PolyProjectionPredicate<'tcx> = Binder<ProjectionPredicate<'tcx>>;
1285 impl<'tcx> PolyProjectionPredicate<'tcx> {
1286 /// Returns the `DefId` of the associated item being projected.
1287 pub fn item_def_id(&self) -> DefId {
1288 self.skip_binder().projection_ty.item_def_id
1291 /// Returns the `DefId` of the trait of the associated item being projected.
1293 pub fn trait_def_id(&self, tcx: TyCtxt<'tcx>) -> DefId {
1294 self.skip_binder().projection_ty.trait_def_id(tcx)
1298 pub fn projection_self_ty(&self) -> Binder<Ty<'tcx>> {
1299 self.map_bound(|predicate| predicate.projection_ty.self_ty())
1302 /// Get the [PolyTraitRef] required for this projection to be well formed.
1303 /// Note that for generic associated types the predicates of the associated
1304 /// type also need to be checked.
1306 pub fn required_poly_trait_ref(&self, tcx: TyCtxt<'tcx>) -> PolyTraitRef<'tcx> {
1307 // Note: unlike with `TraitRef::to_poly_trait_ref()`,
1308 // `self.0.trait_ref` is permitted to have escaping regions.
1309 // This is because here `self` has a `Binder` and so does our
1310 // return value, so we are preserving the number of binding
1312 self.map_bound(|predicate| predicate.projection_ty.trait_ref(tcx))
1315 pub fn ty(&self) -> Binder<Ty<'tcx>> {
1316 self.map_bound(|predicate| predicate.ty)
1319 /// The `DefId` of the `TraitItem` for the associated type.
1321 /// Note that this is not the `DefId` of the `TraitRef` containing this
1322 /// associated type, which is in `tcx.associated_item(projection_def_id()).container`.
1323 pub fn projection_def_id(&self) -> DefId {
1324 // Ok to skip binder since trait `DefId` does not care about regions.
1325 self.skip_binder().projection_ty.item_def_id
1329 pub trait ToPolyTraitRef<'tcx> {
1330 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx>;
1333 impl<'tcx> ToPolyTraitRef<'tcx> for TraitRef<'tcx> {
1334 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
1335 ty::Binder::dummy(*self)
1339 impl<'tcx> ToPolyTraitRef<'tcx> for PolyTraitPredicate<'tcx> {
1340 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
1341 self.map_bound_ref(|trait_pred| trait_pred.trait_ref)
1345 pub trait ToPredicate<'tcx> {
1346 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx>;
1349 impl ToPredicate<'tcx> for Binder<PredicateKind<'tcx>> {
1351 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1352 tcx.mk_predicate(self)
1356 impl ToPredicate<'tcx> for PredicateKind<'tcx> {
1358 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1359 tcx.mk_predicate(Binder::dummy(self))
1363 impl<'tcx> ToPredicate<'tcx> for ConstnessAnd<TraitRef<'tcx>> {
1364 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1365 PredicateKind::Trait(ty::TraitPredicate { trait_ref: self.value }, self.constness)
1370 impl<'tcx> ToPredicate<'tcx> for ConstnessAnd<PolyTraitRef<'tcx>> {
1371 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1373 value: self.value.map_bound(|trait_ref| ty::TraitPredicate { trait_ref }),
1374 constness: self.constness,
1380 impl<'tcx> ToPredicate<'tcx> for ConstnessAnd<PolyTraitPredicate<'tcx>> {
1381 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1382 self.value.map_bound(|value| PredicateKind::Trait(value, self.constness)).to_predicate(tcx)
1386 impl<'tcx> ToPredicate<'tcx> for PolyRegionOutlivesPredicate<'tcx> {
1387 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1388 self.map_bound(PredicateKind::RegionOutlives).to_predicate(tcx)
1392 impl<'tcx> ToPredicate<'tcx> for PolyTypeOutlivesPredicate<'tcx> {
1393 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1394 self.map_bound(PredicateKind::TypeOutlives).to_predicate(tcx)
1398 impl<'tcx> ToPredicate<'tcx> for PolyProjectionPredicate<'tcx> {
1399 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1400 self.map_bound(PredicateKind::Projection).to_predicate(tcx)
1404 impl<'tcx> Predicate<'tcx> {
1405 pub fn to_opt_poly_trait_ref(self) -> Option<ConstnessAnd<PolyTraitRef<'tcx>>> {
1406 let predicate = self.kind();
1407 match predicate.skip_binder() {
1408 PredicateKind::Trait(t, constness) => {
1409 Some(ConstnessAnd { constness, value: predicate.rebind(t.trait_ref) })
1411 PredicateKind::Projection(..)
1412 | PredicateKind::Subtype(..)
1413 | PredicateKind::RegionOutlives(..)
1414 | PredicateKind::WellFormed(..)
1415 | PredicateKind::ObjectSafe(..)
1416 | PredicateKind::ClosureKind(..)
1417 | PredicateKind::TypeOutlives(..)
1418 | PredicateKind::ConstEvaluatable(..)
1419 | PredicateKind::ConstEquate(..)
1420 | PredicateKind::TypeWellFormedFromEnv(..) => None,
1424 pub fn to_opt_type_outlives(self) -> Option<PolyTypeOutlivesPredicate<'tcx>> {
1425 let predicate = self.kind();
1426 match predicate.skip_binder() {
1427 PredicateKind::TypeOutlives(data) => Some(predicate.rebind(data)),
1428 PredicateKind::Trait(..)
1429 | PredicateKind::Projection(..)
1430 | PredicateKind::Subtype(..)
1431 | PredicateKind::RegionOutlives(..)
1432 | PredicateKind::WellFormed(..)
1433 | PredicateKind::ObjectSafe(..)
1434 | PredicateKind::ClosureKind(..)
1435 | PredicateKind::ConstEvaluatable(..)
1436 | PredicateKind::ConstEquate(..)
1437 | PredicateKind::TypeWellFormedFromEnv(..) => None,
1442 /// Represents the bounds declared on a particular set of type
1443 /// parameters. Should eventually be generalized into a flag list of
1444 /// where-clauses. You can obtain a `InstantiatedPredicates` list from a
1445 /// `GenericPredicates` by using the `instantiate` method. Note that this method
1446 /// reflects an important semantic invariant of `InstantiatedPredicates`: while
1447 /// the `GenericPredicates` are expressed in terms of the bound type
1448 /// parameters of the impl/trait/whatever, an `InstantiatedPredicates` instance
1449 /// represented a set of bounds for some particular instantiation,
1450 /// meaning that the generic parameters have been substituted with
1455 /// struct Foo<T, U: Bar<T>> { ... }
1457 /// Here, the `GenericPredicates` for `Foo` would contain a list of bounds like
1458 /// `[[], [U:Bar<T>]]`. Now if there were some particular reference
1459 /// like `Foo<isize,usize>`, then the `InstantiatedPredicates` would be `[[],
1460 /// [usize:Bar<isize>]]`.
1461 #[derive(Clone, Debug, TypeFoldable)]
1462 pub struct InstantiatedPredicates<'tcx> {
1463 pub predicates: Vec<Predicate<'tcx>>,
1464 pub spans: Vec<Span>,
1467 impl<'tcx> InstantiatedPredicates<'tcx> {
1468 pub fn empty() -> InstantiatedPredicates<'tcx> {
1469 InstantiatedPredicates { predicates: vec![], spans: vec![] }
1472 pub fn is_empty(&self) -> bool {
1473 self.predicates.is_empty()
1477 rustc_index::newtype_index! {
1478 /// "Universes" are used during type- and trait-checking in the
1479 /// presence of `for<..>` binders to control what sets of names are
1480 /// visible. Universes are arranged into a tree: the root universe
1481 /// contains names that are always visible. Each child then adds a new
1482 /// set of names that are visible, in addition to those of its parent.
1483 /// We say that the child universe "extends" the parent universe with
1486 /// To make this more concrete, consider this program:
1490 /// fn bar<T>(x: T) {
1491 /// let y: for<'a> fn(&'a u8, Foo) = ...;
1495 /// The struct name `Foo` is in the root universe U0. But the type
1496 /// parameter `T`, introduced on `bar`, is in an extended universe U1
1497 /// -- i.e., within `bar`, we can name both `T` and `Foo`, but outside
1498 /// of `bar`, we cannot name `T`. Then, within the type of `y`, the
1499 /// region `'a` is in a universe U2 that extends U1, because we can
1500 /// name it inside the fn type but not outside.
1502 /// Universes are used to do type- and trait-checking around these
1503 /// "forall" binders (also called **universal quantification**). The
1504 /// idea is that when, in the body of `bar`, we refer to `T` as a
1505 /// type, we aren't referring to any type in particular, but rather a
1506 /// kind of "fresh" type that is distinct from all other types we have
1507 /// actually declared. This is called a **placeholder** type, and we
1508 /// use universes to talk about this. In other words, a type name in
1509 /// universe 0 always corresponds to some "ground" type that the user
1510 /// declared, but a type name in a non-zero universe is a placeholder
1511 /// type -- an idealized representative of "types in general" that we
1512 /// use for checking generic functions.
1513 pub struct UniverseIndex {
1515 DEBUG_FORMAT = "U{}",
1519 impl UniverseIndex {
1520 pub const ROOT: UniverseIndex = UniverseIndex::from_u32(0);
1522 /// Returns the "next" universe index in order -- this new index
1523 /// is considered to extend all previous universes. This
1524 /// corresponds to entering a `forall` quantifier. So, for
1525 /// example, suppose we have this type in universe `U`:
1528 /// for<'a> fn(&'a u32)
1531 /// Once we "enter" into this `for<'a>` quantifier, we are in a
1532 /// new universe that extends `U` -- in this new universe, we can
1533 /// name the region `'a`, but that region was not nameable from
1534 /// `U` because it was not in scope there.
1535 pub fn next_universe(self) -> UniverseIndex {
1536 UniverseIndex::from_u32(self.private.checked_add(1).unwrap())
1539 /// Returns `true` if `self` can name a name from `other` -- in other words,
1540 /// if the set of names in `self` is a superset of those in
1541 /// `other` (`self >= other`).
1542 pub fn can_name(self, other: UniverseIndex) -> bool {
1543 self.private >= other.private
1546 /// Returns `true` if `self` cannot name some names from `other` -- in other
1547 /// words, if the set of names in `self` is a strict subset of
1548 /// those in `other` (`self < other`).
1549 pub fn cannot_name(self, other: UniverseIndex) -> bool {
1550 self.private < other.private
1554 /// The "placeholder index" fully defines a placeholder region, type, or const. Placeholders are
1555 /// identified by both a universe, as well as a name residing within that universe. Distinct bound
1556 /// regions/types/consts within the same universe simply have an unknown relationship to one
1558 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TyEncodable, TyDecodable, PartialOrd, Ord)]
1559 pub struct Placeholder<T> {
1560 pub universe: UniverseIndex,
1564 impl<'a, T> HashStable<StableHashingContext<'a>> for Placeholder<T>
1566 T: HashStable<StableHashingContext<'a>>,
1568 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
1569 self.universe.hash_stable(hcx, hasher);
1570 self.name.hash_stable(hcx, hasher);
1574 pub type PlaceholderRegion = Placeholder<BoundRegionKind>;
1576 pub type PlaceholderType = Placeholder<BoundVar>;
1578 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable)]
1579 #[derive(TyEncodable, TyDecodable, PartialOrd, Ord)]
1580 pub struct BoundConst<'tcx> {
1585 pub type PlaceholderConst<'tcx> = Placeholder<BoundConst<'tcx>>;
1587 /// A `DefId` which, in case it is a const argument, is potentially bundled with
1588 /// the `DefId` of the generic parameter it instantiates.
1590 /// This is used to avoid calls to `type_of` for const arguments during typeck
1591 /// which cause cycle errors.
1596 /// fn foo<const N: usize>(&self) -> [u8; N] { [0; N] }
1597 /// // ^ const parameter
1601 /// fn foo<const M: u8>(&self) -> usize { 42 }
1602 /// // ^ const parameter
1607 /// let _b = a.foo::<{ 3 + 7 }>();
1608 /// // ^^^^^^^^^ const argument
1612 /// Let's look at the call `a.foo::<{ 3 + 7 }>()` here. We do not know
1613 /// which `foo` is used until we know the type of `a`.
1615 /// We only know the type of `a` once we are inside of `typeck(main)`.
1616 /// We also end up normalizing the type of `_b` during `typeck(main)` which
1617 /// requires us to evaluate the const argument.
1619 /// To evaluate that const argument we need to know its type,
1620 /// which we would get using `type_of(const_arg)`. This requires us to
1621 /// resolve `foo` as it can be either `usize` or `u8` in this example.
1622 /// However, resolving `foo` once again requires `typeck(main)` to get the type of `a`,
1623 /// which results in a cycle.
1625 /// In short we must not call `type_of(const_arg)` during `typeck(main)`.
1627 /// When first creating the `ty::Const` of the const argument inside of `typeck` we have
1628 /// already resolved `foo` so we know which const parameter this argument instantiates.
1629 /// This means that we also know the expected result of `type_of(const_arg)` even if we
1630 /// aren't allowed to call that query: it is equal to `type_of(const_param)` which is
1631 /// trivial to compute.
1633 /// If we now want to use that constant in a place which potentionally needs its type
1634 /// we also pass the type of its `const_param`. This is the point of `WithOptConstParam`,
1635 /// except that instead of a `Ty` we bundle the `DefId` of the const parameter.
1636 /// Meaning that we need to use `type_of(const_param_did)` if `const_param_did` is `Some`
1637 /// to get the type of `did`.
1638 #[derive(Copy, Clone, Debug, TypeFoldable, Lift, TyEncodable, TyDecodable)]
1639 #[derive(PartialEq, Eq, PartialOrd, Ord)]
1640 #[derive(Hash, HashStable)]
1641 pub struct WithOptConstParam<T> {
1643 /// The `DefId` of the corresponding generic parameter in case `did` is
1644 /// a const argument.
1646 /// Note that even if `did` is a const argument, this may still be `None`.
1647 /// All queries taking `WithOptConstParam` start by calling `tcx.opt_const_param_of(def.did)`
1648 /// to potentially update `param_did` in the case it is `None`.
1649 pub const_param_did: Option<DefId>,
1652 impl<T> WithOptConstParam<T> {
1653 /// Creates a new `WithOptConstParam` setting `const_param_did` to `None`.
1655 pub fn unknown(did: T) -> WithOptConstParam<T> {
1656 WithOptConstParam { did, const_param_did: None }
1660 impl WithOptConstParam<LocalDefId> {
1661 /// Returns `Some((did, param_did))` if `def_id` is a const argument,
1662 /// `None` otherwise.
1664 pub fn try_lookup(did: LocalDefId, tcx: TyCtxt<'_>) -> Option<(LocalDefId, DefId)> {
1665 tcx.opt_const_param_of(did).map(|param_did| (did, param_did))
1668 /// In case `self` is unknown but `self.did` is a const argument, this returns
1669 /// a `WithOptConstParam` with the correct `const_param_did`.
1671 pub fn try_upgrade(self, tcx: TyCtxt<'_>) -> Option<WithOptConstParam<LocalDefId>> {
1672 if self.const_param_did.is_none() {
1673 if let const_param_did @ Some(_) = tcx.opt_const_param_of(self.did) {
1674 return Some(WithOptConstParam { did: self.did, const_param_did });
1681 pub fn to_global(self) -> WithOptConstParam<DefId> {
1682 WithOptConstParam { did: self.did.to_def_id(), const_param_did: self.const_param_did }
1685 pub fn def_id_for_type_of(self) -> DefId {
1686 if let Some(did) = self.const_param_did { did } else { self.did.to_def_id() }
1690 impl WithOptConstParam<DefId> {
1691 pub fn as_local(self) -> Option<WithOptConstParam<LocalDefId>> {
1694 .map(|did| WithOptConstParam { did, const_param_did: self.const_param_did })
1697 pub fn as_const_arg(self) -> Option<(LocalDefId, DefId)> {
1698 if let Some(param_did) = self.const_param_did {
1699 if let Some(did) = self.did.as_local() {
1700 return Some((did, param_did));
1707 pub fn expect_local(self) -> WithOptConstParam<LocalDefId> {
1708 self.as_local().unwrap()
1711 pub fn is_local(self) -> bool {
1715 pub fn def_id_for_type_of(self) -> DefId {
1716 self.const_param_did.unwrap_or(self.did)
1720 /// When type checking, we use the `ParamEnv` to track
1721 /// details about the set of where-clauses that are in scope at this
1722 /// particular point.
1723 #[derive(Copy, Clone, Hash, PartialEq, Eq)]
1724 pub struct ParamEnv<'tcx> {
1725 /// This packs both caller bounds and the reveal enum into one pointer.
1727 /// Caller bounds are `Obligation`s that the caller must satisfy. This is
1728 /// basically the set of bounds on the in-scope type parameters, translated
1729 /// into `Obligation`s, and elaborated and normalized.
1731 /// Use the `caller_bounds()` method to access.
1733 /// Typically, this is `Reveal::UserFacing`, but during codegen we
1734 /// want `Reveal::All`.
1736 /// Note: This is packed, use the reveal() method to access it.
1737 packed: CopyTaggedPtr<&'tcx List<Predicate<'tcx>>, traits::Reveal, true>,
1740 unsafe impl rustc_data_structures::tagged_ptr::Tag for traits::Reveal {
1741 const BITS: usize = 1;
1742 fn into_usize(self) -> usize {
1744 traits::Reveal::UserFacing => 0,
1745 traits::Reveal::All => 1,
1748 unsafe fn from_usize(ptr: usize) -> Self {
1750 0 => traits::Reveal::UserFacing,
1751 1 => traits::Reveal::All,
1752 _ => std::hint::unreachable_unchecked(),
1757 impl<'tcx> fmt::Debug for ParamEnv<'tcx> {
1758 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1759 f.debug_struct("ParamEnv")
1760 .field("caller_bounds", &self.caller_bounds())
1761 .field("reveal", &self.reveal())
1766 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for ParamEnv<'tcx> {
1767 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
1768 self.caller_bounds().hash_stable(hcx, hasher);
1769 self.reveal().hash_stable(hcx, hasher);
1773 impl<'tcx> TypeFoldable<'tcx> for ParamEnv<'tcx> {
1774 fn super_fold_with<F: ty::fold::TypeFolder<'tcx>>(self, folder: &mut F) -> Self {
1775 ParamEnv::new(self.caller_bounds().fold_with(folder), self.reveal().fold_with(folder))
1778 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> ControlFlow<V::BreakTy> {
1779 self.caller_bounds().visit_with(visitor)?;
1780 self.reveal().visit_with(visitor)
1784 impl<'tcx> ParamEnv<'tcx> {
1785 /// Construct a trait environment suitable for contexts where
1786 /// there are no where-clauses in scope. Hidden types (like `impl
1787 /// Trait`) are left hidden, so this is suitable for ordinary
1790 pub fn empty() -> Self {
1791 Self::new(List::empty(), Reveal::UserFacing)
1795 pub fn caller_bounds(self) -> &'tcx List<Predicate<'tcx>> {
1796 self.packed.pointer()
1800 pub fn reveal(self) -> traits::Reveal {
1804 /// Construct a trait environment with no where-clauses in scope
1805 /// where the values of all `impl Trait` and other hidden types
1806 /// are revealed. This is suitable for monomorphized, post-typeck
1807 /// environments like codegen or doing optimizations.
1809 /// N.B., if you want to have predicates in scope, use `ParamEnv::new`,
1810 /// or invoke `param_env.with_reveal_all()`.
1812 pub fn reveal_all() -> Self {
1813 Self::new(List::empty(), Reveal::All)
1816 /// Construct a trait environment with the given set of predicates.
1818 pub fn new(caller_bounds: &'tcx List<Predicate<'tcx>>, reveal: Reveal) -> Self {
1819 ty::ParamEnv { packed: CopyTaggedPtr::new(caller_bounds, reveal) }
1822 pub fn with_user_facing(mut self) -> Self {
1823 self.packed.set_tag(Reveal::UserFacing);
1827 /// Returns a new parameter environment with the same clauses, but
1828 /// which "reveals" the true results of projections in all cases
1829 /// (even for associated types that are specializable). This is
1830 /// the desired behavior during codegen and certain other special
1831 /// contexts; normally though we want to use `Reveal::UserFacing`,
1832 /// which is the default.
1833 /// All opaque types in the caller_bounds of the `ParamEnv`
1834 /// will be normalized to their underlying types.
1835 /// See PR #65989 and issue #65918 for more details
1836 pub fn with_reveal_all_normalized(self, tcx: TyCtxt<'tcx>) -> Self {
1837 if self.packed.tag() == traits::Reveal::All {
1841 ParamEnv::new(tcx.normalize_opaque_types(self.caller_bounds()), Reveal::All)
1844 /// Returns this same environment but with no caller bounds.
1845 pub fn without_caller_bounds(self) -> Self {
1846 Self::new(List::empty(), self.reveal())
1849 /// Creates a suitable environment in which to perform trait
1850 /// queries on the given value. When type-checking, this is simply
1851 /// the pair of the environment plus value. But when reveal is set to
1852 /// All, then if `value` does not reference any type parameters, we will
1853 /// pair it with the empty environment. This improves caching and is generally
1856 /// N.B., we preserve the environment when type-checking because it
1857 /// is possible for the user to have wacky where-clauses like
1858 /// `where Box<u32>: Copy`, which are clearly never
1859 /// satisfiable. We generally want to behave as if they were true,
1860 /// although the surrounding function is never reachable.
1861 pub fn and<T: TypeFoldable<'tcx>>(self, value: T) -> ParamEnvAnd<'tcx, T> {
1862 match self.reveal() {
1863 Reveal::UserFacing => ParamEnvAnd { param_env: self, value },
1866 if value.is_global() {
1867 ParamEnvAnd { param_env: self.without_caller_bounds(), value }
1869 ParamEnvAnd { param_env: self, value }
1876 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TypeFoldable)]
1877 pub struct ConstnessAnd<T> {
1878 pub constness: Constness,
1882 // FIXME(ecstaticmorse): Audit all occurrences of `without_const().to_predicate(tcx)` to ensure that
1883 // the constness of trait bounds is being propagated correctly.
1884 pub trait WithConstness: Sized {
1886 fn with_constness(self, constness: Constness) -> ConstnessAnd<Self> {
1887 ConstnessAnd { constness, value: self }
1891 fn with_const(self) -> ConstnessAnd<Self> {
1892 self.with_constness(Constness::Const)
1896 fn without_const(self) -> ConstnessAnd<Self> {
1897 self.with_constness(Constness::NotConst)
1901 impl<T> WithConstness for T {}
1903 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TypeFoldable)]
1904 pub struct ParamEnvAnd<'tcx, T> {
1905 pub param_env: ParamEnv<'tcx>,
1909 impl<'tcx, T> ParamEnvAnd<'tcx, T> {
1910 pub fn into_parts(self) -> (ParamEnv<'tcx>, T) {
1911 (self.param_env, self.value)
1915 impl<'a, 'tcx, T> HashStable<StableHashingContext<'a>> for ParamEnvAnd<'tcx, T>
1917 T: HashStable<StableHashingContext<'a>>,
1919 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
1920 let ParamEnvAnd { ref param_env, ref value } = *self;
1922 param_env.hash_stable(hcx, hasher);
1923 value.hash_stable(hcx, hasher);
1927 #[derive(Copy, Clone, Debug, HashStable)]
1928 pub struct Destructor {
1929 /// The `DefId` of the destructor method
1934 #[derive(HashStable)]
1935 pub struct AdtFlags: u32 {
1936 const NO_ADT_FLAGS = 0;
1937 /// Indicates whether the ADT is an enum.
1938 const IS_ENUM = 1 << 0;
1939 /// Indicates whether the ADT is a union.
1940 const IS_UNION = 1 << 1;
1941 /// Indicates whether the ADT is a struct.
1942 const IS_STRUCT = 1 << 2;
1943 /// Indicates whether the ADT is a struct and has a constructor.
1944 const HAS_CTOR = 1 << 3;
1945 /// Indicates whether the type is `PhantomData`.
1946 const IS_PHANTOM_DATA = 1 << 4;
1947 /// Indicates whether the type has a `#[fundamental]` attribute.
1948 const IS_FUNDAMENTAL = 1 << 5;
1949 /// Indicates whether the type is `Box`.
1950 const IS_BOX = 1 << 6;
1951 /// Indicates whether the type is `ManuallyDrop`.
1952 const IS_MANUALLY_DROP = 1 << 7;
1953 /// Indicates whether the variant list of this ADT is `#[non_exhaustive]`.
1954 /// (i.e., this flag is never set unless this ADT is an enum).
1955 const IS_VARIANT_LIST_NON_EXHAUSTIVE = 1 << 8;
1960 #[derive(HashStable)]
1961 pub struct VariantFlags: u32 {
1962 const NO_VARIANT_FLAGS = 0;
1963 /// Indicates whether the field list of this variant is `#[non_exhaustive]`.
1964 const IS_FIELD_LIST_NON_EXHAUSTIVE = 1 << 0;
1965 /// Indicates whether this variant was obtained as part of recovering from
1966 /// a syntactic error. May be incomplete or bogus.
1967 const IS_RECOVERED = 1 << 1;
1971 /// Definition of a variant -- a struct's fields or a enum variant.
1972 #[derive(Debug, HashStable)]
1973 pub struct VariantDef {
1974 /// `DefId` that identifies the variant itself.
1975 /// If this variant belongs to a struct or union, then this is a copy of its `DefId`.
1977 /// `DefId` that identifies the variant's constructor.
1978 /// If this variant is a struct variant, then this is `None`.
1979 pub ctor_def_id: Option<DefId>,
1980 /// Variant or struct name.
1981 #[stable_hasher(project(name))]
1983 /// Discriminant of this variant.
1984 pub discr: VariantDiscr,
1985 /// Fields of this variant.
1986 pub fields: Vec<FieldDef>,
1987 /// Type of constructor of variant.
1988 pub ctor_kind: CtorKind,
1989 /// Flags of the variant (e.g. is field list non-exhaustive)?
1990 flags: VariantFlags,
1994 /// Creates a new `VariantDef`.
1996 /// `variant_did` is the `DefId` that identifies the enum variant (if this `VariantDef`
1997 /// represents an enum variant).
1999 /// `ctor_did` is the `DefId` that identifies the constructor of unit or
2000 /// tuple-variants/structs. If this is a `struct`-variant then this should be `None`.
2002 /// `parent_did` is the `DefId` of the `AdtDef` representing the enum or struct that
2003 /// owns this variant. It is used for checking if a struct has `#[non_exhaustive]` w/out having
2004 /// to go through the redirect of checking the ctor's attributes - but compiling a small crate
2005 /// requires loading the `AdtDef`s for all the structs in the universe (e.g., coherence for any
2006 /// built-in trait), and we do not want to load attributes twice.
2008 /// If someone speeds up attribute loading to not be a performance concern, they can
2009 /// remove this hack and use the constructor `DefId` everywhere.
2012 variant_did: Option<DefId>,
2013 ctor_def_id: Option<DefId>,
2014 discr: VariantDiscr,
2015 fields: Vec<FieldDef>,
2016 ctor_kind: CtorKind,
2020 is_field_list_non_exhaustive: bool,
2023 "VariantDef::new(ident = {:?}, variant_did = {:?}, ctor_def_id = {:?}, discr = {:?},
2024 fields = {:?}, ctor_kind = {:?}, adt_kind = {:?}, parent_did = {:?})",
2025 ident, variant_did, ctor_def_id, discr, fields, ctor_kind, adt_kind, parent_did,
2028 let mut flags = VariantFlags::NO_VARIANT_FLAGS;
2029 if is_field_list_non_exhaustive {
2030 flags |= VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE;
2034 flags |= VariantFlags::IS_RECOVERED;
2038 def_id: variant_did.unwrap_or(parent_did),
2048 /// Is this field list non-exhaustive?
2050 pub fn is_field_list_non_exhaustive(&self) -> bool {
2051 self.flags.intersects(VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE)
2054 /// Was this variant obtained as part of recovering from a syntactic error?
2056 pub fn is_recovered(&self) -> bool {
2057 self.flags.intersects(VariantFlags::IS_RECOVERED)
2061 #[derive(Copy, Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
2062 pub enum VariantDiscr {
2063 /// Explicit value for this variant, i.e., `X = 123`.
2064 /// The `DefId` corresponds to the embedded constant.
2067 /// The previous variant's discriminant plus one.
2068 /// For efficiency reasons, the distance from the
2069 /// last `Explicit` discriminant is being stored,
2070 /// or `0` for the first variant, if it has none.
2074 #[derive(Debug, HashStable)]
2075 pub struct FieldDef {
2077 #[stable_hasher(project(name))]
2079 pub vis: Visibility,
2082 /// The definition of a user-defined type, e.g., a `struct`, `enum`, or `union`.
2084 /// These are all interned (by `alloc_adt_def`) into the global arena.
2086 /// The initialism *ADT* stands for an [*algebraic data type (ADT)*][adt].
2087 /// This is slightly wrong because `union`s are not ADTs.
2088 /// Moreover, Rust only allows recursive data types through indirection.
2090 /// [adt]: https://en.wikipedia.org/wiki/Algebraic_data_type
2092 /// The `DefId` of the struct, enum or union item.
2094 /// Variants of the ADT. If this is a struct or union, then there will be a single variant.
2095 pub variants: IndexVec<VariantIdx, VariantDef>,
2096 /// Flags of the ADT (e.g., is this a struct? is this non-exhaustive?).
2098 /// Repr options provided by the user.
2099 pub repr: ReprOptions,
2102 impl PartialOrd for AdtDef {
2103 fn partial_cmp(&self, other: &AdtDef) -> Option<Ordering> {
2104 Some(self.cmp(&other))
2108 /// There should be only one AdtDef for each `did`, therefore
2109 /// it is fine to implement `Ord` only based on `did`.
2110 impl Ord for AdtDef {
2111 fn cmp(&self, other: &AdtDef) -> Ordering {
2112 self.did.cmp(&other.did)
2116 impl PartialEq for AdtDef {
2117 // `AdtDef`s are always interned, and this is part of `TyS` equality.
2119 fn eq(&self, other: &Self) -> bool {
2120 ptr::eq(self, other)
2124 impl Eq for AdtDef {}
2126 impl Hash for AdtDef {
2128 fn hash<H: Hasher>(&self, s: &mut H) {
2129 (self as *const AdtDef).hash(s)
2133 impl<S: Encoder> Encodable<S> for AdtDef {
2134 fn encode(&self, s: &mut S) -> Result<(), S::Error> {
2139 impl<'a> HashStable<StableHashingContext<'a>> for AdtDef {
2140 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
2142 static CACHE: RefCell<FxHashMap<usize, Fingerprint>> = Default::default();
2145 let hash: Fingerprint = CACHE.with(|cache| {
2146 let addr = self as *const AdtDef as usize;
2147 *cache.borrow_mut().entry(addr).or_insert_with(|| {
2148 let ty::AdtDef { did, ref variants, ref flags, ref repr } = *self;
2150 let mut hasher = StableHasher::new();
2151 did.hash_stable(hcx, &mut hasher);
2152 variants.hash_stable(hcx, &mut hasher);
2153 flags.hash_stable(hcx, &mut hasher);
2154 repr.hash_stable(hcx, &mut hasher);
2160 hash.hash_stable(hcx, hasher);
2164 #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
2171 impl Into<DataTypeKind> for AdtKind {
2172 fn into(self) -> DataTypeKind {
2174 AdtKind::Struct => DataTypeKind::Struct,
2175 AdtKind::Union => DataTypeKind::Union,
2176 AdtKind::Enum => DataTypeKind::Enum,
2182 #[derive(TyEncodable, TyDecodable, Default, HashStable)]
2183 pub struct ReprFlags: u8 {
2184 const IS_C = 1 << 0;
2185 const IS_SIMD = 1 << 1;
2186 const IS_TRANSPARENT = 1 << 2;
2187 // Internal only for now. If true, don't reorder fields.
2188 const IS_LINEAR = 1 << 3;
2189 // If true, don't expose any niche to type's context.
2190 const HIDE_NICHE = 1 << 4;
2191 // Any of these flags being set prevent field reordering optimisation.
2192 const IS_UNOPTIMISABLE = ReprFlags::IS_C.bits |
2193 ReprFlags::IS_SIMD.bits |
2194 ReprFlags::IS_LINEAR.bits;
2198 /// Represents the repr options provided by the user,
2199 #[derive(Copy, Clone, Debug, Eq, PartialEq, TyEncodable, TyDecodable, Default, HashStable)]
2200 pub struct ReprOptions {
2201 pub int: Option<attr::IntType>,
2202 pub align: Option<Align>,
2203 pub pack: Option<Align>,
2204 pub flags: ReprFlags,
2208 pub fn new(tcx: TyCtxt<'_>, did: DefId) -> ReprOptions {
2209 let mut flags = ReprFlags::empty();
2210 let mut size = None;
2211 let mut max_align: Option<Align> = None;
2212 let mut min_pack: Option<Align> = None;
2213 for attr in tcx.get_attrs(did).iter() {
2214 for r in attr::find_repr_attrs(&tcx.sess, attr) {
2215 flags.insert(match r {
2216 attr::ReprC => ReprFlags::IS_C,
2217 attr::ReprPacked(pack) => {
2218 let pack = Align::from_bytes(pack as u64).unwrap();
2219 min_pack = Some(if let Some(min_pack) = min_pack {
2226 attr::ReprTransparent => ReprFlags::IS_TRANSPARENT,
2227 attr::ReprNoNiche => ReprFlags::HIDE_NICHE,
2228 attr::ReprSimd => ReprFlags::IS_SIMD,
2229 attr::ReprInt(i) => {
2233 attr::ReprAlign(align) => {
2234 max_align = max_align.max(Some(Align::from_bytes(align as u64).unwrap()));
2241 // This is here instead of layout because the choice must make it into metadata.
2242 if !tcx.consider_optimizing(|| format!("Reorder fields of {:?}", tcx.def_path_str(did))) {
2243 flags.insert(ReprFlags::IS_LINEAR);
2245 ReprOptions { int: size, align: max_align, pack: min_pack, flags }
2249 pub fn simd(&self) -> bool {
2250 self.flags.contains(ReprFlags::IS_SIMD)
2253 pub fn c(&self) -> bool {
2254 self.flags.contains(ReprFlags::IS_C)
2257 pub fn packed(&self) -> bool {
2261 pub fn transparent(&self) -> bool {
2262 self.flags.contains(ReprFlags::IS_TRANSPARENT)
2265 pub fn linear(&self) -> bool {
2266 self.flags.contains(ReprFlags::IS_LINEAR)
2269 pub fn hide_niche(&self) -> bool {
2270 self.flags.contains(ReprFlags::HIDE_NICHE)
2273 /// Returns the discriminant type, given these `repr` options.
2274 /// This must only be called on enums!
2275 pub fn discr_type(&self) -> attr::IntType {
2276 self.int.unwrap_or(attr::SignedInt(ast::IntTy::Isize))
2279 /// Returns `true` if this `#[repr()]` should inhabit "smart enum
2280 /// layout" optimizations, such as representing `Foo<&T>` as a
2282 pub fn inhibit_enum_layout_opt(&self) -> bool {
2283 self.c() || self.int.is_some()
2286 /// Returns `true` if this `#[repr()]` should inhibit struct field reordering
2287 /// optimizations, such as with `repr(C)`, `repr(packed(1))`, or `repr(<int>)`.
2288 pub fn inhibit_struct_field_reordering_opt(&self) -> bool {
2289 if let Some(pack) = self.pack {
2290 if pack.bytes() == 1 {
2294 self.flags.intersects(ReprFlags::IS_UNOPTIMISABLE) || self.int.is_some()
2297 /// Returns `true` if this `#[repr()]` should inhibit union ABI optimisations.
2298 pub fn inhibit_union_abi_opt(&self) -> bool {
2304 /// Creates a new `AdtDef`.
2309 variants: IndexVec<VariantIdx, VariantDef>,
2312 debug!("AdtDef::new({:?}, {:?}, {:?}, {:?})", did, kind, variants, repr);
2313 let mut flags = AdtFlags::NO_ADT_FLAGS;
2315 if kind == AdtKind::Enum && tcx.has_attr(did, sym::non_exhaustive) {
2316 debug!("found non-exhaustive variant list for {:?}", did);
2317 flags = flags | AdtFlags::IS_VARIANT_LIST_NON_EXHAUSTIVE;
2320 flags |= match kind {
2321 AdtKind::Enum => AdtFlags::IS_ENUM,
2322 AdtKind::Union => AdtFlags::IS_UNION,
2323 AdtKind::Struct => AdtFlags::IS_STRUCT,
2326 if kind == AdtKind::Struct && variants[VariantIdx::new(0)].ctor_def_id.is_some() {
2327 flags |= AdtFlags::HAS_CTOR;
2330 let attrs = tcx.get_attrs(did);
2331 if tcx.sess.contains_name(&attrs, sym::fundamental) {
2332 flags |= AdtFlags::IS_FUNDAMENTAL;
2334 if Some(did) == tcx.lang_items().phantom_data() {
2335 flags |= AdtFlags::IS_PHANTOM_DATA;
2337 if Some(did) == tcx.lang_items().owned_box() {
2338 flags |= AdtFlags::IS_BOX;
2340 if Some(did) == tcx.lang_items().manually_drop() {
2341 flags |= AdtFlags::IS_MANUALLY_DROP;
2344 AdtDef { did, variants, flags, repr }
2347 /// Returns `true` if this is a struct.
2349 pub fn is_struct(&self) -> bool {
2350 self.flags.contains(AdtFlags::IS_STRUCT)
2353 /// Returns `true` if this is a union.
2355 pub fn is_union(&self) -> bool {
2356 self.flags.contains(AdtFlags::IS_UNION)
2359 /// Returns `true` if this is a enum.
2361 pub fn is_enum(&self) -> bool {
2362 self.flags.contains(AdtFlags::IS_ENUM)
2365 /// Returns `true` if the variant list of this ADT is `#[non_exhaustive]`.
2367 pub fn is_variant_list_non_exhaustive(&self) -> bool {
2368 self.flags.contains(AdtFlags::IS_VARIANT_LIST_NON_EXHAUSTIVE)
2371 /// Returns the kind of the ADT.
2373 pub fn adt_kind(&self) -> AdtKind {
2376 } else if self.is_union() {
2383 /// Returns a description of this abstract data type.
2384 pub fn descr(&self) -> &'static str {
2385 match self.adt_kind() {
2386 AdtKind::Struct => "struct",
2387 AdtKind::Union => "union",
2388 AdtKind::Enum => "enum",
2392 /// Returns a description of a variant of this abstract data type.
2394 pub fn variant_descr(&self) -> &'static str {
2395 match self.adt_kind() {
2396 AdtKind::Struct => "struct",
2397 AdtKind::Union => "union",
2398 AdtKind::Enum => "variant",
2402 /// If this function returns `true`, it implies that `is_struct` must return `true`.
2404 pub fn has_ctor(&self) -> bool {
2405 self.flags.contains(AdtFlags::HAS_CTOR)
2408 /// Returns `true` if this type is `#[fundamental]` for the purposes
2409 /// of coherence checking.
2411 pub fn is_fundamental(&self) -> bool {
2412 self.flags.contains(AdtFlags::IS_FUNDAMENTAL)
2415 /// Returns `true` if this is `PhantomData<T>`.
2417 pub fn is_phantom_data(&self) -> bool {
2418 self.flags.contains(AdtFlags::IS_PHANTOM_DATA)
2421 /// Returns `true` if this is Box<T>.
2423 pub fn is_box(&self) -> bool {
2424 self.flags.contains(AdtFlags::IS_BOX)
2427 /// Returns `true` if this is `ManuallyDrop<T>`.
2429 pub fn is_manually_drop(&self) -> bool {
2430 self.flags.contains(AdtFlags::IS_MANUALLY_DROP)
2433 /// Returns `true` if this type has a destructor.
2434 pub fn has_dtor(&self, tcx: TyCtxt<'tcx>) -> bool {
2435 self.destructor(tcx).is_some()
2438 /// Asserts this is a struct or union and returns its unique variant.
2439 pub fn non_enum_variant(&self) -> &VariantDef {
2440 assert!(self.is_struct() || self.is_union());
2441 &self.variants[VariantIdx::new(0)]
2445 pub fn predicates(&self, tcx: TyCtxt<'tcx>) -> GenericPredicates<'tcx> {
2446 tcx.predicates_of(self.did)
2449 /// Returns an iterator over all fields contained
2452 pub fn all_fields(&self) -> impl Iterator<Item = &FieldDef> + Clone {
2453 self.variants.iter().flat_map(|v| v.fields.iter())
2456 /// Whether the ADT lacks fields. Note that this includes uninhabited enums,
2457 /// e.g., `enum Void {}` is considered payload free as well.
2458 pub fn is_payloadfree(&self) -> bool {
2459 self.variants.iter().all(|v| v.fields.is_empty())
2462 /// Return a `VariantDef` given a variant id.
2463 pub fn variant_with_id(&self, vid: DefId) -> &VariantDef {
2464 self.variants.iter().find(|v| v.def_id == vid).expect("variant_with_id: unknown variant")
2467 /// Return a `VariantDef` given a constructor id.
2468 pub fn variant_with_ctor_id(&self, cid: DefId) -> &VariantDef {
2471 .find(|v| v.ctor_def_id == Some(cid))
2472 .expect("variant_with_ctor_id: unknown variant")
2475 /// Return the index of `VariantDef` given a variant id.
2476 pub fn variant_index_with_id(&self, vid: DefId) -> VariantIdx {
2479 .find(|(_, v)| v.def_id == vid)
2480 .expect("variant_index_with_id: unknown variant")
2484 /// Return the index of `VariantDef` given a constructor id.
2485 pub fn variant_index_with_ctor_id(&self, cid: DefId) -> VariantIdx {
2488 .find(|(_, v)| v.ctor_def_id == Some(cid))
2489 .expect("variant_index_with_ctor_id: unknown variant")
2493 pub fn variant_of_res(&self, res: Res) -> &VariantDef {
2495 Res::Def(DefKind::Variant, vid) => self.variant_with_id(vid),
2496 Res::Def(DefKind::Ctor(..), cid) => self.variant_with_ctor_id(cid),
2497 Res::Def(DefKind::Struct, _)
2498 | Res::Def(DefKind::Union, _)
2499 | Res::Def(DefKind::TyAlias, _)
2500 | Res::Def(DefKind::AssocTy, _)
2502 | Res::SelfCtor(..) => self.non_enum_variant(),
2503 _ => bug!("unexpected res {:?} in variant_of_res", res),
2508 pub fn eval_explicit_discr(&self, tcx: TyCtxt<'tcx>, expr_did: DefId) -> Option<Discr<'tcx>> {
2509 assert!(self.is_enum());
2510 let param_env = tcx.param_env(expr_did);
2511 let repr_type = self.repr.discr_type();
2512 match tcx.const_eval_poly(expr_did) {
2514 let ty = repr_type.to_ty(tcx);
2515 if let Some(b) = val.try_to_bits_for_ty(tcx, param_env, ty) {
2516 trace!("discriminants: {} ({:?})", b, repr_type);
2517 Some(Discr { val: b, ty })
2519 info!("invalid enum discriminant: {:#?}", val);
2520 crate::mir::interpret::struct_error(
2521 tcx.at(tcx.def_span(expr_did)),
2522 "constant evaluation of enum discriminant resulted in non-integer",
2529 let msg = match err {
2530 ErrorHandled::Reported(ErrorReported) | ErrorHandled::Linted => {
2531 "enum discriminant evaluation failed"
2533 ErrorHandled::TooGeneric => "enum discriminant depends on generics",
2535 tcx.sess.delay_span_bug(tcx.def_span(expr_did), msg);
2542 pub fn discriminants(
2545 ) -> impl Iterator<Item = (VariantIdx, Discr<'tcx>)> + Captures<'tcx> {
2546 assert!(self.is_enum());
2547 let repr_type = self.repr.discr_type();
2548 let initial = repr_type.initial_discriminant(tcx);
2549 let mut prev_discr = None::<Discr<'tcx>>;
2550 self.variants.iter_enumerated().map(move |(i, v)| {
2551 let mut discr = prev_discr.map_or(initial, |d| d.wrap_incr(tcx));
2552 if let VariantDiscr::Explicit(expr_did) = v.discr {
2553 if let Some(new_discr) = self.eval_explicit_discr(tcx, expr_did) {
2557 prev_discr = Some(discr);
2564 pub fn variant_range(&self) -> Range<VariantIdx> {
2565 VariantIdx::new(0)..VariantIdx::new(self.variants.len())
2568 /// Computes the discriminant value used by a specific variant.
2569 /// Unlike `discriminants`, this is (amortized) constant-time,
2570 /// only doing at most one query for evaluating an explicit
2571 /// discriminant (the last one before the requested variant),
2572 /// assuming there are no constant-evaluation errors there.
2574 pub fn discriminant_for_variant(
2577 variant_index: VariantIdx,
2579 assert!(self.is_enum());
2580 let (val, offset) = self.discriminant_def_for_variant(variant_index);
2581 let explicit_value = val
2582 .and_then(|expr_did| self.eval_explicit_discr(tcx, expr_did))
2583 .unwrap_or_else(|| self.repr.discr_type().initial_discriminant(tcx));
2584 explicit_value.checked_add(tcx, offset as u128).0
2587 /// Yields a `DefId` for the discriminant and an offset to add to it
2588 /// Alternatively, if there is no explicit discriminant, returns the
2589 /// inferred discriminant directly.
2590 pub fn discriminant_def_for_variant(&self, variant_index: VariantIdx) -> (Option<DefId>, u32) {
2591 assert!(!self.variants.is_empty());
2592 let mut explicit_index = variant_index.as_u32();
2595 match self.variants[VariantIdx::from_u32(explicit_index)].discr {
2596 ty::VariantDiscr::Relative(0) => {
2600 ty::VariantDiscr::Relative(distance) => {
2601 explicit_index -= distance;
2603 ty::VariantDiscr::Explicit(did) => {
2604 expr_did = Some(did);
2609 (expr_did, variant_index.as_u32() - explicit_index)
2612 pub fn destructor(&self, tcx: TyCtxt<'tcx>) -> Option<Destructor> {
2613 tcx.adt_destructor(self.did)
2616 /// Returns a list of types such that `Self: Sized` if and only
2617 /// if that type is `Sized`, or `TyErr` if this type is recursive.
2619 /// Oddly enough, checking that the sized-constraint is `Sized` is
2620 /// actually more expressive than checking all members:
2621 /// the `Sized` trait is inductive, so an associated type that references
2622 /// `Self` would prevent its containing ADT from being `Sized`.
2624 /// Due to normalization being eager, this applies even if
2625 /// the associated type is behind a pointer (e.g., issue #31299).
2626 pub fn sized_constraint(&self, tcx: TyCtxt<'tcx>) -> &'tcx [Ty<'tcx>] {
2627 tcx.adt_sized_constraint(self.did).0
2631 impl<'tcx> FieldDef {
2632 /// Returns the type of this field. The `subst` is typically obtained
2633 /// via the second field of `TyKind::AdtDef`.
2634 pub fn ty(&self, tcx: TyCtxt<'tcx>, subst: SubstsRef<'tcx>) -> Ty<'tcx> {
2635 tcx.type_of(self.did).subst(tcx, subst)
2639 /// Represents the various closure traits in the language. This
2640 /// will determine the type of the environment (`self`, in the
2641 /// desugaring) argument that the closure expects.
2643 /// You can get the environment type of a closure using
2644 /// `tcx.closure_env_ty()`.
2645 #[derive(Clone, Copy, PartialOrd, Ord, PartialEq, Eq, Hash, Debug, TyEncodable, TyDecodable)]
2646 #[derive(HashStable)]
2647 pub enum ClosureKind {
2648 // Warning: Ordering is significant here! The ordering is chosen
2649 // because the trait Fn is a subtrait of FnMut and so in turn, and
2650 // hence we order it so that Fn < FnMut < FnOnce.
2656 impl<'tcx> ClosureKind {
2657 // This is the initial value used when doing upvar inference.
2658 pub const LATTICE_BOTTOM: ClosureKind = ClosureKind::Fn;
2660 pub fn trait_did(&self, tcx: TyCtxt<'tcx>) -> DefId {
2662 ClosureKind::Fn => tcx.require_lang_item(LangItem::Fn, None),
2663 ClosureKind::FnMut => tcx.require_lang_item(LangItem::FnMut, None),
2664 ClosureKind::FnOnce => tcx.require_lang_item(LangItem::FnOnce, None),
2668 /// Returns `true` if a type that impls this closure kind
2669 /// must also implement `other`.
2670 pub fn extends(self, other: ty::ClosureKind) -> bool {
2673 (ClosureKind::Fn, ClosureKind::Fn)
2674 | (ClosureKind::Fn, ClosureKind::FnMut)
2675 | (ClosureKind::Fn, ClosureKind::FnOnce)
2676 | (ClosureKind::FnMut, ClosureKind::FnMut)
2677 | (ClosureKind::FnMut, ClosureKind::FnOnce)
2678 | (ClosureKind::FnOnce, ClosureKind::FnOnce)
2682 /// Returns the representative scalar type for this closure kind.
2683 /// See `TyS::to_opt_closure_kind` for more details.
2684 pub fn to_ty(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
2686 ty::ClosureKind::Fn => tcx.types.i8,
2687 ty::ClosureKind::FnMut => tcx.types.i16,
2688 ty::ClosureKind::FnOnce => tcx.types.i32,
2694 pub fn from_mutbl(m: hir::Mutability) -> BorrowKind {
2696 hir::Mutability::Mut => MutBorrow,
2697 hir::Mutability::Not => ImmBorrow,
2701 /// Returns a mutability `m` such that an `&m T` pointer could be used to obtain this borrow
2702 /// kind. Because borrow kinds are richer than mutabilities, we sometimes have to pick a
2703 /// mutability that is stronger than necessary so that it at least *would permit* the borrow in
2705 pub fn to_mutbl_lossy(self) -> hir::Mutability {
2707 MutBorrow => hir::Mutability::Mut,
2708 ImmBorrow => hir::Mutability::Not,
2710 // We have no type corresponding to a unique imm borrow, so
2711 // use `&mut`. It gives all the capabilities of an `&uniq`
2712 // and hence is a safe "over approximation".
2713 UniqueImmBorrow => hir::Mutability::Mut,
2717 pub fn to_user_str(&self) -> &'static str {
2719 MutBorrow => "mutable",
2720 ImmBorrow => "immutable",
2721 UniqueImmBorrow => "uniquely immutable",
2726 pub type Attributes<'tcx> = &'tcx [ast::Attribute];
2728 #[derive(Debug, PartialEq, Eq)]
2729 pub enum ImplOverlapKind {
2730 /// These impls are always allowed to overlap.
2732 /// Whether or not the impl is permitted due to the trait being a `#[marker]` trait
2735 /// These impls are allowed to overlap, but that raises
2736 /// an issue #33140 future-compatibility warning.
2738 /// Some background: in Rust 1.0, the trait-object types `Send + Sync` (today's
2739 /// `dyn Send + Sync`) and `Sync + Send` (now `dyn Sync + Send`) were different.
2741 /// The widely-used version 0.1.0 of the crate `traitobject` had accidentally relied
2742 /// that difference, making what reduces to the following set of impls:
2746 /// impl Trait for dyn Send + Sync {}
2747 /// impl Trait for dyn Sync + Send {}
2750 /// Obviously, once we made these types be identical, that code causes a coherence
2751 /// error and a fairly big headache for us. However, luckily for us, the trait
2752 /// `Trait` used in this case is basically a marker trait, and therefore having
2753 /// overlapping impls for it is sound.
2755 /// To handle this, we basically regard the trait as a marker trait, with an additional
2756 /// future-compatibility warning. To avoid accidentally "stabilizing" this feature,
2757 /// it has the following restrictions:
2759 /// 1. The trait must indeed be a marker-like trait (i.e., no items), and must be
2761 /// 2. The trait-ref of both impls must be equal.
2762 /// 3. The trait-ref of both impls must be a trait object type consisting only of
2764 /// 4. Neither of the impls can have any where-clauses.
2766 /// Once `traitobject` 0.1.0 is no longer an active concern, this hack can be removed.
2770 impl<'tcx> TyCtxt<'tcx> {
2771 pub fn typeck_body(self, body: hir::BodyId) -> &'tcx TypeckResults<'tcx> {
2772 self.typeck(self.hir().body_owner_def_id(body))
2775 /// Returns an iterator of the `DefId`s for all body-owners in this
2776 /// crate. If you would prefer to iterate over the bodies
2777 /// themselves, you can do `self.hir().krate().body_ids.iter()`.
2778 pub fn body_owners(self) -> impl Iterator<Item = LocalDefId> + Captures<'tcx> + 'tcx {
2783 .map(move |&body_id| self.hir().body_owner_def_id(body_id))
2786 pub fn par_body_owners<F: Fn(LocalDefId) + sync::Sync + sync::Send>(self, f: F) {
2787 par_iter(&self.hir().krate().body_ids)
2788 .for_each(|&body_id| f(self.hir().body_owner_def_id(body_id)));
2791 pub fn provided_trait_methods(self, id: DefId) -> impl 'tcx + Iterator<Item = &'tcx AssocItem> {
2792 self.associated_items(id)
2793 .in_definition_order()
2794 .filter(|item| item.kind == AssocKind::Fn && item.defaultness.has_value())
2797 fn item_name_from_hir(self, def_id: DefId) -> Option<Ident> {
2798 self.hir().get_if_local(def_id).and_then(|node| node.ident())
2801 fn item_name_from_def_id(self, def_id: DefId) -> Option<Symbol> {
2802 if def_id.index == CRATE_DEF_INDEX {
2803 Some(self.original_crate_name(def_id.krate))
2805 let def_key = self.def_key(def_id);
2806 match def_key.disambiguated_data.data {
2807 // The name of a constructor is that of its parent.
2808 rustc_hir::definitions::DefPathData::Ctor => self.item_name_from_def_id(DefId {
2809 krate: def_id.krate,
2810 index: def_key.parent.unwrap(),
2812 _ => def_key.disambiguated_data.data.get_opt_name(),
2817 /// Look up the name of an item across crates. This does not look at HIR.
2819 /// When possible, this function should be used for cross-crate lookups over
2820 /// [`opt_item_name`] to avoid invalidating the incremental cache. If you
2821 /// need to handle items without a name, or HIR items that will not be
2822 /// serialized cross-crate, or if you need the span of the item, use
2823 /// [`opt_item_name`] instead.
2825 /// [`opt_item_name`]: Self::opt_item_name
2826 pub fn item_name(self, id: DefId) -> Symbol {
2827 // Look at cross-crate items first to avoid invalidating the incremental cache
2828 // unless we have to.
2829 self.item_name_from_def_id(id).unwrap_or_else(|| {
2830 bug!("item_name: no name for {:?}", self.def_path(id));
2834 /// Look up the name and span of an item or [`Node`].
2836 /// See [`item_name`][Self::item_name] for more information.
2837 pub fn opt_item_name(self, def_id: DefId) -> Option<Ident> {
2838 // Look at the HIR first so the span will be correct if this is a local item.
2839 self.item_name_from_hir(def_id)
2840 .or_else(|| self.item_name_from_def_id(def_id).map(Ident::with_dummy_span))
2843 pub fn opt_associated_item(self, def_id: DefId) -> Option<&'tcx AssocItem> {
2844 if let DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy = self.def_kind(def_id) {
2845 Some(self.associated_item(def_id))
2851 pub fn field_index(self, hir_id: hir::HirId, typeck_results: &TypeckResults<'_>) -> usize {
2852 typeck_results.field_indices().get(hir_id).cloned().expect("no index for a field")
2855 pub fn find_field_index(self, ident: Ident, variant: &VariantDef) -> Option<usize> {
2856 variant.fields.iter().position(|field| self.hygienic_eq(ident, field.ident, variant.def_id))
2859 /// Returns `true` if the impls are the same polarity and the trait either
2860 /// has no items or is annotated `#[marker]` and prevents item overrides.
2861 pub fn impls_are_allowed_to_overlap(
2865 ) -> Option<ImplOverlapKind> {
2866 // If either trait impl references an error, they're allowed to overlap,
2867 // as one of them essentially doesn't exist.
2868 if self.impl_trait_ref(def_id1).map_or(false, |tr| tr.references_error())
2869 || self.impl_trait_ref(def_id2).map_or(false, |tr| tr.references_error())
2871 return Some(ImplOverlapKind::Permitted { marker: false });
2874 match (self.impl_polarity(def_id1), self.impl_polarity(def_id2)) {
2875 (ImplPolarity::Reservation, _) | (_, ImplPolarity::Reservation) => {
2876 // `#[rustc_reservation_impl]` impls don't overlap with anything
2878 "impls_are_allowed_to_overlap({:?}, {:?}) = Some(Permitted) (reservations)",
2881 return Some(ImplOverlapKind::Permitted { marker: false });
2883 (ImplPolarity::Positive, ImplPolarity::Negative)
2884 | (ImplPolarity::Negative, ImplPolarity::Positive) => {
2885 // `impl AutoTrait for Type` + `impl !AutoTrait for Type`
2887 "impls_are_allowed_to_overlap({:?}, {:?}) - None (differing polarities)",
2892 (ImplPolarity::Positive, ImplPolarity::Positive)
2893 | (ImplPolarity::Negative, ImplPolarity::Negative) => {}
2896 let is_marker_overlap = {
2897 let is_marker_impl = |def_id: DefId| -> bool {
2898 let trait_ref = self.impl_trait_ref(def_id);
2899 trait_ref.map_or(false, |tr| self.trait_def(tr.def_id).is_marker)
2901 is_marker_impl(def_id1) && is_marker_impl(def_id2)
2904 if is_marker_overlap {
2906 "impls_are_allowed_to_overlap({:?}, {:?}) = Some(Permitted) (marker overlap)",
2909 Some(ImplOverlapKind::Permitted { marker: true })
2911 if let Some(self_ty1) = self.issue33140_self_ty(def_id1) {
2912 if let Some(self_ty2) = self.issue33140_self_ty(def_id2) {
2913 if self_ty1 == self_ty2 {
2915 "impls_are_allowed_to_overlap({:?}, {:?}) - issue #33140 HACK",
2918 return Some(ImplOverlapKind::Issue33140);
2921 "impls_are_allowed_to_overlap({:?}, {:?}) - found {:?} != {:?}",
2922 def_id1, def_id2, self_ty1, self_ty2
2928 debug!("impls_are_allowed_to_overlap({:?}, {:?}) = None", def_id1, def_id2);
2933 /// Returns `ty::VariantDef` if `res` refers to a struct,
2934 /// or variant or their constructors, panics otherwise.
2935 pub fn expect_variant_res(self, res: Res) -> &'tcx VariantDef {
2937 Res::Def(DefKind::Variant, did) => {
2938 let enum_did = self.parent(did).unwrap();
2939 self.adt_def(enum_did).variant_with_id(did)
2941 Res::Def(DefKind::Struct | DefKind::Union, did) => self.adt_def(did).non_enum_variant(),
2942 Res::Def(DefKind::Ctor(CtorOf::Variant, ..), variant_ctor_did) => {
2943 let variant_did = self.parent(variant_ctor_did).unwrap();
2944 let enum_did = self.parent(variant_did).unwrap();
2945 self.adt_def(enum_did).variant_with_ctor_id(variant_ctor_did)
2947 Res::Def(DefKind::Ctor(CtorOf::Struct, ..), ctor_did) => {
2948 let struct_did = self.parent(ctor_did).expect("struct ctor has no parent");
2949 self.adt_def(struct_did).non_enum_variant()
2951 _ => bug!("expect_variant_res used with unexpected res {:?}", res),
2955 /// Returns the possibly-auto-generated MIR of a `(DefId, Subst)` pair.
2956 pub fn instance_mir(self, instance: ty::InstanceDef<'tcx>) -> &'tcx Body<'tcx> {
2958 ty::InstanceDef::Item(def) => match self.def_kind(def.did) {
2961 | DefKind::AssocConst
2963 | DefKind::AnonConst => self.mir_for_ctfe_opt_const_arg(def),
2964 // If the caller wants `mir_for_ctfe` of a function they should not be using
2965 // `instance_mir`, so we'll assume const fn also wants the optimized version.
2967 assert_eq!(def.const_param_did, None);
2968 self.optimized_mir(def.did)
2971 ty::InstanceDef::VtableShim(..)
2972 | ty::InstanceDef::ReifyShim(..)
2973 | ty::InstanceDef::Intrinsic(..)
2974 | ty::InstanceDef::FnPtrShim(..)
2975 | ty::InstanceDef::Virtual(..)
2976 | ty::InstanceDef::ClosureOnceShim { .. }
2977 | ty::InstanceDef::DropGlue(..)
2978 | ty::InstanceDef::CloneShim(..) => self.mir_shims(instance),
2982 /// Gets the attributes of a definition.
2983 pub fn get_attrs(self, did: DefId) -> Attributes<'tcx> {
2984 if let Some(did) = did.as_local() {
2985 self.hir().attrs(self.hir().local_def_id_to_hir_id(did))
2987 self.item_attrs(did)
2991 /// Determines whether an item is annotated with an attribute.
2992 pub fn has_attr(self, did: DefId, attr: Symbol) -> bool {
2993 self.sess.contains_name(&self.get_attrs(did), attr)
2996 /// Returns `true` if this is an `auto trait`.
2997 pub fn trait_is_auto(self, trait_def_id: DefId) -> bool {
2998 self.trait_def(trait_def_id).has_auto_impl
3001 /// Returns layout of a generator. Layout might be unavailable if the
3002 /// generator is tainted by errors.
3003 pub fn generator_layout(self, def_id: DefId) -> Option<&'tcx GeneratorLayout<'tcx>> {
3004 self.optimized_mir(def_id).generator_layout()
3007 /// Given the `DefId` of an impl, returns the `DefId` of the trait it implements.
3008 /// If it implements no trait, returns `None`.
3009 pub fn trait_id_of_impl(self, def_id: DefId) -> Option<DefId> {
3010 self.impl_trait_ref(def_id).map(|tr| tr.def_id)
3013 /// If the given defid describes a method belonging to an impl, returns the
3014 /// `DefId` of the impl that the method belongs to; otherwise, returns `None`.
3015 pub fn impl_of_method(self, def_id: DefId) -> Option<DefId> {
3016 self.opt_associated_item(def_id).and_then(|trait_item| match trait_item.container {
3017 TraitContainer(_) => None,
3018 ImplContainer(def_id) => Some(def_id),
3022 /// Looks up the span of `impl_did` if the impl is local; otherwise returns `Err`
3023 /// with the name of the crate containing the impl.
3024 pub fn span_of_impl(self, impl_did: DefId) -> Result<Span, Symbol> {
3025 if let Some(impl_did) = impl_did.as_local() {
3026 let hir_id = self.hir().local_def_id_to_hir_id(impl_did);
3027 Ok(self.hir().span(hir_id))
3029 Err(self.crate_name(impl_did.krate))
3033 /// Hygienically compares a use-site name (`use_name`) for a field or an associated item with
3034 /// its supposed definition name (`def_name`). The method also needs `DefId` of the supposed
3035 /// definition's parent/scope to perform comparison.
3036 pub fn hygienic_eq(self, use_name: Ident, def_name: Ident, def_parent_def_id: DefId) -> bool {
3037 // We could use `Ident::eq` here, but we deliberately don't. The name
3038 // comparison fails frequently, and we want to avoid the expensive
3039 // `normalize_to_macros_2_0()` calls required for the span comparison whenever possible.
3040 use_name.name == def_name.name
3044 .hygienic_eq(def_name.span.ctxt(), self.expansion_that_defined(def_parent_def_id))
3047 pub fn expansion_that_defined(self, scope: DefId) -> ExpnId {
3048 match scope.as_local() {
3049 // Parsing and expansion aren't incremental, so we don't
3050 // need to go through a query for the same-crate case.
3051 Some(scope) => self.hir().definitions().expansion_that_defined(scope),
3052 None => self.expn_that_defined(scope),
3056 pub fn adjust_ident(self, mut ident: Ident, scope: DefId) -> Ident {
3057 ident.span.normalize_to_macros_2_0_and_adjust(self.expansion_that_defined(scope));
3061 pub fn adjust_ident_and_get_scope(
3066 ) -> (Ident, DefId) {
3068 match ident.span.normalize_to_macros_2_0_and_adjust(self.expansion_that_defined(scope))
3070 Some(actual_expansion) => {
3071 self.hir().definitions().parent_module_of_macro_def(actual_expansion)
3073 None => self.parent_module(block).to_def_id(),
3078 pub fn is_object_safe(self, key: DefId) -> bool {
3079 self.object_safety_violations(key).is_empty()
3083 #[derive(Clone, HashStable, Debug)]
3084 pub struct AdtSizedConstraint<'tcx>(pub &'tcx [Ty<'tcx>]);
3086 /// Yields the parent function's `DefId` if `def_id` is an `impl Trait` definition.
3087 pub fn is_impl_trait_defn(tcx: TyCtxt<'_>, def_id: DefId) -> Option<DefId> {
3088 if let Some(def_id) = def_id.as_local() {
3089 if let Node::Item(item) = tcx.hir().get(tcx.hir().local_def_id_to_hir_id(def_id)) {
3090 if let hir::ItemKind::OpaqueTy(ref opaque_ty) = item.kind {
3091 return opaque_ty.impl_trait_fn;
3098 pub fn int_ty(ity: ast::IntTy) -> IntTy {
3100 ast::IntTy::Isize => IntTy::Isize,
3101 ast::IntTy::I8 => IntTy::I8,
3102 ast::IntTy::I16 => IntTy::I16,
3103 ast::IntTy::I32 => IntTy::I32,
3104 ast::IntTy::I64 => IntTy::I64,
3105 ast::IntTy::I128 => IntTy::I128,
3109 pub fn uint_ty(uty: ast::UintTy) -> UintTy {
3111 ast::UintTy::Usize => UintTy::Usize,
3112 ast::UintTy::U8 => UintTy::U8,
3113 ast::UintTy::U16 => UintTy::U16,
3114 ast::UintTy::U32 => UintTy::U32,
3115 ast::UintTy::U64 => UintTy::U64,
3116 ast::UintTy::U128 => UintTy::U128,
3120 pub fn float_ty(fty: ast::FloatTy) -> FloatTy {
3122 ast::FloatTy::F32 => FloatTy::F32,
3123 ast::FloatTy::F64 => FloatTy::F64,
3127 pub fn ast_int_ty(ity: IntTy) -> ast::IntTy {
3129 IntTy::Isize => ast::IntTy::Isize,
3130 IntTy::I8 => ast::IntTy::I8,
3131 IntTy::I16 => ast::IntTy::I16,
3132 IntTy::I32 => ast::IntTy::I32,
3133 IntTy::I64 => ast::IntTy::I64,
3134 IntTy::I128 => ast::IntTy::I128,
3138 pub fn ast_uint_ty(uty: UintTy) -> ast::UintTy {
3140 UintTy::Usize => ast::UintTy::Usize,
3141 UintTy::U8 => ast::UintTy::U8,
3142 UintTy::U16 => ast::UintTy::U16,
3143 UintTy::U32 => ast::UintTy::U32,
3144 UintTy::U64 => ast::UintTy::U64,
3145 UintTy::U128 => ast::UintTy::U128,
3149 pub fn provide(providers: &mut ty::query::Providers) {
3150 context::provide(providers);
3151 erase_regions::provide(providers);
3152 layout::provide(providers);
3153 util::provide(providers);
3154 print::provide(providers);
3155 super::util::bug::provide(providers);
3156 *providers = ty::query::Providers {
3157 trait_impls_of: trait_def::trait_impls_of_provider,
3158 all_local_trait_impls: trait_def::all_local_trait_impls,
3159 type_uninhabited_from: inhabitedness::type_uninhabited_from,
3164 /// A map for the local crate mapping each type to a vector of its
3165 /// inherent impls. This is not meant to be used outside of coherence;
3166 /// rather, you should request the vector for a specific type via
3167 /// `tcx.inherent_impls(def_id)` so as to minimize your dependencies
3168 /// (constructing this map requires touching the entire crate).
3169 #[derive(Clone, Debug, Default, HashStable)]
3170 pub struct CrateInherentImpls {
3171 pub inherent_impls: DefIdMap<Vec<DefId>>,
3174 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, HashStable)]
3175 pub struct SymbolName<'tcx> {
3176 /// `&str` gives a consistent ordering, which ensures reproducible builds.
3177 pub name: &'tcx str,
3180 impl<'tcx> SymbolName<'tcx> {
3181 pub fn new(tcx: TyCtxt<'tcx>, name: &str) -> SymbolName<'tcx> {
3183 name: unsafe { str::from_utf8_unchecked(tcx.arena.alloc_slice(name.as_bytes())) },
3188 impl<'tcx> fmt::Display for SymbolName<'tcx> {
3189 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
3190 fmt::Display::fmt(&self.name, fmt)
3194 impl<'tcx> fmt::Debug for SymbolName<'tcx> {
3195 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
3196 fmt::Display::fmt(&self.name, fmt)