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;
27 use crate::mir::{Body, GeneratorLayout};
28 use crate::traits::{self, Reveal};
30 use crate::ty::subst::{GenericArg, InternalSubsts, Subst, SubstsRef};
31 use crate::ty::util::{Discr, IntTypeExt};
33 use rustc_attr as attr;
34 use rustc_data_structures::captures::Captures;
35 use rustc_data_structures::fingerprint::Fingerprint;
36 use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap};
37 use rustc_data_structures::sorted_map::SortedIndexMultiMap;
38 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
39 use rustc_data_structures::sync::{self, par_iter, ParallelIterator};
40 use rustc_data_structures::tagged_ptr::CopyTaggedPtr;
41 use rustc_errors::ErrorReported;
43 use rustc_hir::def::{CtorKind, CtorOf, DefKind, Namespace, Res};
44 use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, LocalDefId, CRATE_DEF_INDEX};
45 use rustc_hir::lang_items::LangItem;
46 use rustc_hir::{Constness, Node};
47 use rustc_index::vec::{Idx, IndexVec};
48 use rustc_macros::HashStable;
49 use rustc_serialize::{self, Encodable, Encoder};
50 use rustc_session::DataTypeKind;
51 use rustc_span::hygiene::ExpnId;
52 use rustc_span::symbol::{kw, sym, Ident, Symbol};
54 use rustc_target::abi::{Align, VariantIdx};
56 use std::cell::RefCell;
57 use std::cmp::Ordering;
58 use std::hash::{Hash, Hasher};
59 use std::ops::{ControlFlow, Range};
60 use std::{fmt, ptr, str};
62 pub use crate::ty::diagnostics::*;
63 pub use rustc_type_ir::InferTy::*;
64 pub use rustc_type_ir::*;
66 pub use self::binding::BindingMode;
67 pub use self::binding::BindingMode::*;
68 pub use self::consts::{Const, ConstInt, ConstKind, InferConst, ScalarInt};
69 pub use self::context::{
70 tls, CanonicalUserType, CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations,
71 CtxtInterners, DelaySpanBugEmitted, FreeRegionInfo, GeneratorInteriorTypeCause, GlobalCtxt,
72 Lift, ResolvedOpaqueTy, TyCtxt, TypeckResults, UserType, UserTypeAnnotationIndex,
74 pub use self::instance::{Instance, InstanceDef};
75 pub use self::list::List;
76 pub use self::sty::BoundRegionKind::*;
77 pub use self::sty::RegionKind::*;
78 pub use self::sty::TyKind::*;
80 Binder, BoundRegion, BoundRegionKind, BoundTy, BoundTyKind, BoundVar, CanonicalPolyFnSig,
81 ClosureSubsts, ClosureSubstsParts, ConstVid, EarlyBoundRegion, ExistentialPredicate,
82 ExistentialProjection, ExistentialTraitRef, FnSig, FreeRegion, GenSig, GeneratorSubsts,
83 GeneratorSubstsParts, ParamConst, ParamTy, PolyExistentialProjection, PolyExistentialTraitRef,
84 PolyFnSig, PolyGenSig, PolyTraitRef, ProjectionTy, Region, RegionKind, RegionVid, TraitRef,
85 TyKind, TypeAndMut, UpvarSubsts,
87 pub use self::trait_def::TraitDef;
98 pub mod inhabitedness;
100 pub mod normalize_erasing_regions;
116 mod structural_impls;
121 pub struct ResolverOutputs {
122 pub definitions: rustc_hir::definitions::Definitions,
123 pub cstore: Box<CrateStoreDyn>,
124 pub visibilities: FxHashMap<LocalDefId, Visibility>,
125 pub extern_crate_map: FxHashMap<LocalDefId, CrateNum>,
126 pub maybe_unused_trait_imports: FxHashSet<LocalDefId>,
127 pub maybe_unused_extern_crates: Vec<(LocalDefId, Span)>,
128 pub export_map: ExportMap<LocalDefId>,
129 pub glob_map: FxHashMap<LocalDefId, FxHashSet<Symbol>>,
130 /// Extern prelude entries. The value is `true` if the entry was introduced
131 /// via `extern crate` item and not `--extern` option or compiler built-in.
132 pub extern_prelude: FxHashMap<Symbol, bool>,
135 #[derive(Clone, Copy, PartialEq, Eq, Debug, HashStable, Hash)]
136 pub enum AssocItemContainer {
137 TraitContainer(DefId),
138 ImplContainer(DefId),
141 impl AssocItemContainer {
142 /// Asserts that this is the `DefId` of an associated item declared
143 /// in a trait, and returns the trait `DefId`.
144 pub fn assert_trait(&self) -> DefId {
146 TraitContainer(id) => id,
147 _ => bug!("associated item has wrong container type: {:?}", self),
151 pub fn id(&self) -> DefId {
153 TraitContainer(id) => id,
154 ImplContainer(id) => id,
159 /// The "header" of an impl is everything outside the body: a Self type, a trait
160 /// ref (in the case of a trait impl), and a set of predicates (from the
161 /// bounds / where-clauses).
162 #[derive(Clone, Debug, TypeFoldable)]
163 pub struct ImplHeader<'tcx> {
164 pub impl_def_id: DefId,
165 pub self_ty: Ty<'tcx>,
166 pub trait_ref: Option<TraitRef<'tcx>>,
167 pub predicates: Vec<Predicate<'tcx>>,
170 #[derive(Copy, Clone, PartialEq, TyEncodable, TyDecodable, HashStable, Debug)]
171 pub enum ImplPolarity {
172 /// `impl Trait for Type`
174 /// `impl !Trait for Type`
176 /// `#[rustc_reservation_impl] impl Trait for Type`
178 /// This is a "stability hack", not a real Rust feature.
179 /// See #64631 for details.
183 #[derive(Copy, Clone, Debug, PartialEq, HashStable, Eq, Hash)]
184 pub struct AssocItem {
186 #[stable_hasher(project(name))]
190 pub defaultness: hir::Defaultness,
191 pub container: AssocItemContainer,
193 /// Whether this is a method with an explicit self
194 /// as its first parameter, allowing method calls.
195 pub fn_has_self_parameter: bool,
198 #[derive(Copy, Clone, PartialEq, Debug, HashStable, Eq, Hash)]
206 pub fn namespace(&self) -> Namespace {
208 ty::AssocKind::Type => Namespace::TypeNS,
209 ty::AssocKind::Const | ty::AssocKind::Fn => Namespace::ValueNS,
213 pub fn as_def_kind(&self) -> DefKind {
215 AssocKind::Const => DefKind::AssocConst,
216 AssocKind::Fn => DefKind::AssocFn,
217 AssocKind::Type => DefKind::AssocTy,
223 pub fn signature(&self, tcx: TyCtxt<'_>) -> String {
225 ty::AssocKind::Fn => {
226 // We skip the binder here because the binder would deanonymize all
227 // late-bound regions, and we don't want method signatures to show up
228 // `as for<'r> fn(&'r MyType)`. Pretty-printing handles late-bound
229 // regions just fine, showing `fn(&MyType)`.
230 tcx.fn_sig(self.def_id).skip_binder().to_string()
232 ty::AssocKind::Type => format!("type {};", self.ident),
233 ty::AssocKind::Const => {
234 format!("const {}: {:?};", self.ident, tcx.type_of(self.def_id))
240 /// A list of `ty::AssocItem`s in definition order that allows for efficient lookup by name.
242 /// When doing lookup by name, we try to postpone hygienic comparison for as long as possible since
243 /// it is relatively expensive. Instead, items are indexed by `Symbol` and hygienic comparison is
244 /// done only on items with the same name.
245 #[derive(Debug, Clone, PartialEq, HashStable)]
246 pub struct AssociatedItems<'tcx> {
247 items: SortedIndexMultiMap<u32, Symbol, &'tcx ty::AssocItem>,
250 impl<'tcx> AssociatedItems<'tcx> {
251 /// Constructs an `AssociatedItems` map from a series of `ty::AssocItem`s in definition order.
252 pub fn new(items_in_def_order: impl IntoIterator<Item = &'tcx ty::AssocItem>) -> Self {
253 let items = items_in_def_order.into_iter().map(|item| (item.ident.name, item)).collect();
254 AssociatedItems { items }
257 /// Returns a slice of associated items in the order they were defined.
259 /// New code should avoid relying on definition order. If you need a particular associated item
260 /// for a known trait, make that trait a lang item instead of indexing this array.
261 pub fn in_definition_order(&self) -> impl '_ + Iterator<Item = &ty::AssocItem> {
262 self.items.iter().map(|(_, v)| *v)
265 pub fn len(&self) -> usize {
269 /// Returns an iterator over all associated items with the given name, ignoring hygiene.
270 pub fn filter_by_name_unhygienic(
273 ) -> impl '_ + Iterator<Item = &ty::AssocItem> {
274 self.items.get_by_key(&name).copied()
277 /// Returns an iterator over all associated items with the given name.
279 /// Multiple items may have the same name if they are in different `Namespace`s. For example,
280 /// an associated type can have the same name as a method. Use one of the `find_by_name_and_*`
281 /// methods below if you know which item you are looking for.
282 pub fn filter_by_name(
286 parent_def_id: DefId,
287 ) -> impl 'a + Iterator<Item = &'a ty::AssocItem> {
288 self.filter_by_name_unhygienic(ident.name)
289 .filter(move |item| tcx.hygienic_eq(ident, item.ident, parent_def_id))
292 /// Returns the associated item with the given name and `AssocKind`, if one exists.
293 pub fn find_by_name_and_kind(
298 parent_def_id: DefId,
299 ) -> Option<&ty::AssocItem> {
300 self.filter_by_name_unhygienic(ident.name)
301 .filter(|item| item.kind == kind)
302 .find(|item| tcx.hygienic_eq(ident, item.ident, parent_def_id))
305 /// Returns the associated item with the given name in the given `Namespace`, if one exists.
306 pub fn find_by_name_and_namespace(
311 parent_def_id: DefId,
312 ) -> Option<&ty::AssocItem> {
313 self.filter_by_name_unhygienic(ident.name)
314 .filter(|item| item.kind.namespace() == ns)
315 .find(|item| tcx.hygienic_eq(ident, item.ident, parent_def_id))
319 #[derive(Clone, Debug, PartialEq, Eq, Copy, Hash, TyEncodable, TyDecodable, HashStable)]
320 pub enum Visibility {
321 /// Visible everywhere (including in other crates).
323 /// Visible only in the given crate-local module.
325 /// Not visible anywhere in the local crate. This is the visibility of private external items.
329 pub trait DefIdTree: Copy {
330 fn parent(self, id: DefId) -> Option<DefId>;
332 fn is_descendant_of(self, mut descendant: DefId, ancestor: DefId) -> bool {
333 if descendant.krate != ancestor.krate {
337 while descendant != ancestor {
338 match self.parent(descendant) {
339 Some(parent) => descendant = parent,
340 None => return false,
347 impl<'tcx> DefIdTree for TyCtxt<'tcx> {
348 fn parent(self, id: DefId) -> Option<DefId> {
349 self.def_key(id).parent.map(|index| DefId { index, ..id })
354 pub fn from_hir(visibility: &hir::Visibility<'_>, id: hir::HirId, tcx: TyCtxt<'_>) -> Self {
355 match visibility.node {
356 hir::VisibilityKind::Public => Visibility::Public,
357 hir::VisibilityKind::Crate(_) => Visibility::Restricted(DefId::local(CRATE_DEF_INDEX)),
358 hir::VisibilityKind::Restricted { ref path, .. } => match path.res {
359 // If there is no resolution, `resolve` will have already reported an error, so
360 // assume that the visibility is public to avoid reporting more privacy errors.
361 Res::Err => Visibility::Public,
362 def => Visibility::Restricted(def.def_id()),
364 hir::VisibilityKind::Inherited => {
365 Visibility::Restricted(tcx.parent_module(id).to_def_id())
370 /// Returns `true` if an item with this visibility is accessible from the given block.
371 pub fn is_accessible_from<T: DefIdTree>(self, module: DefId, tree: T) -> bool {
372 let restriction = match self {
373 // Public items are visible everywhere.
374 Visibility::Public => return true,
375 // Private items from other crates are visible nowhere.
376 Visibility::Invisible => return false,
377 // Restricted items are visible in an arbitrary local module.
378 Visibility::Restricted(other) if other.krate != module.krate => return false,
379 Visibility::Restricted(module) => module,
382 tree.is_descendant_of(module, restriction)
385 /// Returns `true` if this visibility is at least as accessible as the given visibility
386 pub fn is_at_least<T: DefIdTree>(self, vis: Visibility, tree: T) -> bool {
387 let vis_restriction = match vis {
388 Visibility::Public => return self == Visibility::Public,
389 Visibility::Invisible => return true,
390 Visibility::Restricted(module) => module,
393 self.is_accessible_from(vis_restriction, tree)
396 // Returns `true` if this item is visible anywhere in the local crate.
397 pub fn is_visible_locally(self) -> bool {
399 Visibility::Public => true,
400 Visibility::Restricted(def_id) => def_id.is_local(),
401 Visibility::Invisible => false,
406 /// The crate variances map is computed during typeck and contains the
407 /// variance of every item in the local crate. You should not use it
408 /// directly, because to do so will make your pass dependent on the
409 /// HIR of every item in the local crate. Instead, use
410 /// `tcx.variances_of()` to get the variance for a *particular*
412 #[derive(HashStable, Debug)]
413 pub struct CrateVariancesMap<'tcx> {
414 /// For each item with generics, maps to a vector of the variance
415 /// of its generics. If an item has no generics, it will have no
417 pub variances: FxHashMap<DefId, &'tcx [ty::Variance]>,
420 // Contains information needed to resolve types and (in the future) look up
421 // the types of AST nodes.
422 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
423 pub struct CReaderCacheKey {
428 #[allow(rustc::usage_of_ty_tykind)]
429 pub struct TyS<'tcx> {
430 /// This field shouldn't be used directly and may be removed in the future.
431 /// Use `TyS::kind()` instead.
433 /// This field shouldn't be used directly and may be removed in the future.
434 /// Use `TyS::flags()` instead.
437 /// This is a kind of confusing thing: it stores the smallest
440 /// (a) the binder itself captures nothing but
441 /// (b) all the late-bound things within the type are captured
442 /// by some sub-binder.
444 /// So, for a type without any late-bound things, like `u32`, this
445 /// will be *innermost*, because that is the innermost binder that
446 /// captures nothing. But for a type `&'D u32`, where `'D` is a
447 /// late-bound region with De Bruijn index `D`, this would be `D + 1`
448 /// -- the binder itself does not capture `D`, but `D` is captured
449 /// by an inner binder.
451 /// We call this concept an "exclusive" binder `D` because all
452 /// De Bruijn indices within the type are contained within `0..D`
454 outer_exclusive_binder: ty::DebruijnIndex,
457 impl<'tcx> TyS<'tcx> {
458 /// A constructor used only for internal testing.
459 #[allow(rustc::usage_of_ty_tykind)]
460 pub fn make_for_test(
463 outer_exclusive_binder: ty::DebruijnIndex,
465 TyS { kind, flags, outer_exclusive_binder }
469 // `TyS` is used a lot. Make sure it doesn't unintentionally get bigger.
470 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
471 static_assert_size!(TyS<'_>, 32);
473 impl<'tcx> Ord for TyS<'tcx> {
474 fn cmp(&self, other: &TyS<'tcx>) -> Ordering {
475 self.kind().cmp(other.kind())
479 impl<'tcx> PartialOrd for TyS<'tcx> {
480 fn partial_cmp(&self, other: &TyS<'tcx>) -> Option<Ordering> {
481 Some(self.kind().cmp(other.kind()))
485 impl<'tcx> PartialEq for TyS<'tcx> {
487 fn eq(&self, other: &TyS<'tcx>) -> bool {
491 impl<'tcx> Eq for TyS<'tcx> {}
493 impl<'tcx> Hash for TyS<'tcx> {
494 fn hash<H: Hasher>(&self, s: &mut H) {
495 (self as *const TyS<'_>).hash(s)
499 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for TyS<'tcx> {
500 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
504 // The other fields just provide fast access to information that is
505 // also contained in `kind`, so no need to hash them.
508 outer_exclusive_binder: _,
511 kind.hash_stable(hcx, hasher);
515 #[rustc_diagnostic_item = "Ty"]
516 pub type Ty<'tcx> = &'tcx TyS<'tcx>;
530 pub struct UpvarPath {
531 pub hir_id: hir::HirId,
534 /// Upvars do not get their own `NodeId`. Instead, we use the pair of
535 /// the original var ID (that is, the root variable that is referenced
536 /// by the upvar) and the ID of the closure expression.
537 #[derive(Clone, Copy, PartialEq, Eq, Hash, TyEncodable, TyDecodable, TypeFoldable, HashStable)]
539 pub var_path: UpvarPath,
540 pub closure_expr_id: LocalDefId,
544 pub fn new(var_hir_id: hir::HirId, closure_def_id: LocalDefId) -> UpvarId {
545 UpvarId { var_path: UpvarPath { hir_id: var_hir_id }, closure_expr_id: closure_def_id }
549 #[derive(Clone, PartialEq, Debug, TyEncodable, TyDecodable, TypeFoldable, Copy, HashStable)]
550 pub enum BorrowKind {
551 /// Data must be immutable and is aliasable.
554 /// Data must be immutable but not aliasable. This kind of borrow
555 /// cannot currently be expressed by the user and is used only in
556 /// implicit closure bindings. It is needed when the closure
557 /// is borrowing or mutating a mutable referent, e.g.:
560 /// let x: &mut isize = ...;
561 /// let y = || *x += 5;
564 /// If we were to try to translate this closure into a more explicit
565 /// form, we'd encounter an error with the code as written:
568 /// struct Env { x: & &mut isize }
569 /// let x: &mut isize = ...;
570 /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
571 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
574 /// This is then illegal because you cannot mutate a `&mut` found
575 /// in an aliasable location. To solve, you'd have to translate with
576 /// an `&mut` borrow:
579 /// struct Env { x: & &mut isize }
580 /// let x: &mut isize = ...;
581 /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
582 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
585 /// Now the assignment to `**env.x` is legal, but creating a
586 /// mutable pointer to `x` is not because `x` is not mutable. We
587 /// could fix this by declaring `x` as `let mut x`. This is ok in
588 /// user code, if awkward, but extra weird for closures, since the
589 /// borrow is hidden.
591 /// So we introduce a "unique imm" borrow -- the referent is
592 /// immutable, but not aliasable. This solves the problem. For
593 /// simplicity, we don't give users the way to express this
594 /// borrow, it's just used when translating closures.
597 /// Data is mutable and not aliasable.
601 /// Information describing the capture of an upvar. This is computed
602 /// during `typeck`, specifically by `regionck`.
603 #[derive(PartialEq, Clone, Debug, Copy, TyEncodable, TyDecodable, TypeFoldable, HashStable)]
604 pub enum UpvarCapture<'tcx> {
605 /// Upvar is captured by value. This is always true when the
606 /// closure is labeled `move`, but can also be true in other cases
607 /// depending on inference.
609 /// If the upvar was inferred to be captured by value (e.g. `move`
610 /// was not used), then the `Span` points to a usage that
611 /// required it. There may be more than one such usage
612 /// (e.g. `|| { a; a; }`), in which case we pick an
614 ByValue(Option<Span>),
616 /// Upvar is captured by reference.
617 ByRef(UpvarBorrow<'tcx>),
620 #[derive(PartialEq, Clone, Copy, TyEncodable, TyDecodable, TypeFoldable, HashStable)]
621 pub struct UpvarBorrow<'tcx> {
622 /// The kind of borrow: by-ref upvars have access to shared
623 /// immutable borrows, which are not part of the normal language
625 pub kind: BorrowKind,
627 /// Region of the resulting reference.
628 pub region: ty::Region<'tcx>,
631 /// Given the closure DefId this map provides a map of root variables to minimum
632 /// set of `CapturedPlace`s that need to be tracked to support all captures of that closure.
633 pub type MinCaptureInformationMap<'tcx> = FxHashMap<DefId, RootVariableMinCaptureList<'tcx>>;
635 /// Part of `MinCaptureInformationMap`; Maps a root variable to the list of `CapturedPlace`.
636 /// Used to track the minimum set of `Place`s that need to be captured to support all
637 /// Places captured by the closure starting at a given root variable.
639 /// This provides a convenient and quick way of checking if a variable being used within
640 /// a closure is a capture of a local variable.
641 pub type RootVariableMinCaptureList<'tcx> = FxIndexMap<hir::HirId, MinCaptureList<'tcx>>;
643 /// Part of `MinCaptureInformationMap`; List of `CapturePlace`s.
644 pub type MinCaptureList<'tcx> = Vec<CapturedPlace<'tcx>>;
646 /// A composite describing a `Place` that is captured by a closure.
647 #[derive(PartialEq, Clone, Debug, TyEncodable, TyDecodable, TypeFoldable, HashStable)]
648 pub struct CapturedPlace<'tcx> {
649 /// The `Place` that is captured.
650 pub place: HirPlace<'tcx>,
652 /// `CaptureKind` and expression(s) that resulted in such capture of `place`.
653 pub info: CaptureInfo<'tcx>,
655 /// Represents if `place` can be mutated or not.
656 pub mutability: hir::Mutability,
659 impl CapturedPlace<'tcx> {
660 /// Returns the hir-id of the root variable for the captured place.
661 /// e.g., if `a.b.c` was captured, would return the hir-id for `a`.
662 pub fn get_root_variable(&self) -> hir::HirId {
663 match self.place.base {
664 HirPlaceBase::Upvar(upvar_id) => upvar_id.var_path.hir_id,
665 base => bug!("Expected upvar, found={:?}", base),
670 pub fn place_to_string_for_capture(tcx: TyCtxt<'tcx>, place: &HirPlace<'tcx>) -> String {
671 let name = match place.base {
672 HirPlaceBase::Upvar(upvar_id) => tcx.hir().name(upvar_id.var_path.hir_id).to_string(),
673 _ => bug!("Capture_information should only contain upvars"),
675 let mut curr_string = name;
677 for (i, proj) in place.projections.iter().enumerate() {
679 HirProjectionKind::Deref => {
680 curr_string = format!("*{}", curr_string);
682 HirProjectionKind::Field(idx, variant) => match place.ty_before_projection(i).kind() {
683 ty::Adt(def, ..) => {
684 curr_string = format!(
687 def.variants[variant].fields[idx as usize].ident.name.as_str()
691 curr_string = format!("{}.{}", curr_string, idx);
695 "Field projection applied to a type other than Adt or Tuple: {:?}.",
696 place.ty_before_projection(i).kind()
700 proj => bug!("{:?} unexpected because it isn't captured", proj),
704 curr_string.to_string()
707 /// Part of `MinCaptureInformationMap`; describes the capture kind (&, &mut, move)
708 /// for a particular capture as well as identifying the part of the source code
709 /// that triggered this capture to occur.
710 #[derive(PartialEq, Clone, Debug, Copy, TyEncodable, TyDecodable, TypeFoldable, HashStable)]
711 pub struct CaptureInfo<'tcx> {
712 /// Expr Id pointing to use that resulted in selecting the current capture kind
716 /// let mut t = (0,1);
719 /// println!("{}",t); // L1
723 /// `capture_kind_expr_id` will point to the use on L2 and `path_expr_id` will point to the
726 /// If the user doesn't enable feature `capture_disjoint_fields` (RFC 2229) then, it is
727 /// possible that we don't see the use of a particular place resulting in capture_kind_expr_id being
728 /// None. In such case we fallback on uvpars_mentioned for span.
739 /// In this example, if `capture_disjoint_fields` is **not** set, then x will be captured,
740 /// but we won't see it being used during capture analysis, since it's essentially a discard.
741 pub capture_kind_expr_id: Option<hir::HirId>,
742 /// Expr Id pointing to use that resulted the corresponding place being captured
744 /// See `capture_kind_expr_id` for example.
746 pub path_expr_id: Option<hir::HirId>,
748 /// Capture mode that was selected
749 pub capture_kind: UpvarCapture<'tcx>,
752 pub type UpvarListMap = FxHashMap<DefId, FxIndexMap<hir::HirId, UpvarId>>;
753 pub type UpvarCaptureMap<'tcx> = FxHashMap<UpvarId, UpvarCapture<'tcx>>;
755 impl ty::EarlyBoundRegion {
756 /// Does this early bound region have a name? Early bound regions normally
757 /// always have names except when using anonymous lifetimes (`'_`).
758 pub fn has_name(&self) -> bool {
759 self.name != kw::UnderscoreLifetime
763 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable)]
764 pub enum GenericParamDefKind {
768 object_lifetime_default: ObjectLifetimeDefault,
769 synthetic: Option<hir::SyntheticTyParamKind>,
774 impl GenericParamDefKind {
775 pub fn descr(&self) -> &'static str {
777 GenericParamDefKind::Lifetime => "lifetime",
778 GenericParamDefKind::Type { .. } => "type",
779 GenericParamDefKind::Const => "constant",
782 pub fn to_ord(&self, tcx: TyCtxt<'_>) -> ast::ParamKindOrd {
784 GenericParamDefKind::Lifetime => ast::ParamKindOrd::Lifetime,
785 GenericParamDefKind::Type { .. } => ast::ParamKindOrd::Type,
786 GenericParamDefKind::Const => {
787 ast::ParamKindOrd::Const { unordered: tcx.features().const_generics }
793 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable)]
794 pub struct GenericParamDef {
799 /// `pure_wrt_drop`, set by the (unsafe) `#[may_dangle]` attribute
800 /// on generic parameter `'a`/`T`, asserts data behind the parameter
801 /// `'a`/`T` won't be accessed during the parent type's `Drop` impl.
802 pub pure_wrt_drop: bool,
804 pub kind: GenericParamDefKind,
807 impl GenericParamDef {
808 pub fn to_early_bound_region_data(&self) -> ty::EarlyBoundRegion {
809 if let GenericParamDefKind::Lifetime = self.kind {
810 ty::EarlyBoundRegion { def_id: self.def_id, index: self.index, name: self.name }
812 bug!("cannot convert a non-lifetime parameter def to an early bound region")
818 pub struct GenericParamCount {
819 pub lifetimes: usize,
824 /// Information about the formal type/lifetime parameters associated
825 /// with an item or method. Analogous to `hir::Generics`.
827 /// The ordering of parameters is the same as in `Subst` (excluding child generics):
828 /// `Self` (optionally), `Lifetime` params..., `Type` params...
829 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable)]
830 pub struct Generics {
831 pub parent: Option<DefId>,
832 pub parent_count: usize,
833 pub params: Vec<GenericParamDef>,
835 /// Reverse map to the `index` field of each `GenericParamDef`.
836 #[stable_hasher(ignore)]
837 pub param_def_id_to_index: FxHashMap<DefId, u32>,
840 pub has_late_bound_regions: Option<Span>,
843 impl<'tcx> Generics {
844 pub fn count(&self) -> usize {
845 self.parent_count + self.params.len()
848 pub fn own_counts(&self) -> GenericParamCount {
849 // We could cache this as a property of `GenericParamCount`, but
850 // the aim is to refactor this away entirely eventually and the
851 // presence of this method will be a constant reminder.
852 let mut own_counts = GenericParamCount::default();
854 for param in &self.params {
856 GenericParamDefKind::Lifetime => own_counts.lifetimes += 1,
857 GenericParamDefKind::Type { .. } => own_counts.types += 1,
858 GenericParamDefKind::Const => own_counts.consts += 1,
865 pub fn own_defaults(&self) -> GenericParamCount {
866 let mut own_defaults = GenericParamCount::default();
868 for param in &self.params {
870 GenericParamDefKind::Lifetime => (),
871 GenericParamDefKind::Type { has_default, .. } => {
872 own_defaults.types += has_default as usize;
874 GenericParamDefKind::Const => {
875 // FIXME(const_generics:defaults)
883 pub fn requires_monomorphization(&self, tcx: TyCtxt<'tcx>) -> bool {
884 if self.own_requires_monomorphization() {
888 if let Some(parent_def_id) = self.parent {
889 let parent = tcx.generics_of(parent_def_id);
890 parent.requires_monomorphization(tcx)
896 pub fn own_requires_monomorphization(&self) -> bool {
897 for param in &self.params {
899 GenericParamDefKind::Type { .. } | GenericParamDefKind::Const => return true,
900 GenericParamDefKind::Lifetime => {}
906 /// Returns the `GenericParamDef` with the given index.
907 pub fn param_at(&'tcx self, param_index: usize, tcx: TyCtxt<'tcx>) -> &'tcx GenericParamDef {
908 if let Some(index) = param_index.checked_sub(self.parent_count) {
911 tcx.generics_of(self.parent.expect("parent_count > 0 but no parent?"))
912 .param_at(param_index, tcx)
916 /// Returns the `GenericParamDef` associated with this `EarlyBoundRegion`.
919 param: &EarlyBoundRegion,
921 ) -> &'tcx GenericParamDef {
922 let param = self.param_at(param.index as usize, tcx);
924 GenericParamDefKind::Lifetime => param,
925 _ => bug!("expected lifetime parameter, but found another generic parameter"),
929 /// Returns the `GenericParamDef` associated with this `ParamTy`.
930 pub fn type_param(&'tcx self, param: &ParamTy, tcx: TyCtxt<'tcx>) -> &'tcx GenericParamDef {
931 let param = self.param_at(param.index as usize, tcx);
933 GenericParamDefKind::Type { .. } => param,
934 _ => bug!("expected type parameter, but found another generic parameter"),
938 /// Returns the `GenericParamDef` associated with this `ParamConst`.
939 pub fn const_param(&'tcx self, param: &ParamConst, tcx: TyCtxt<'tcx>) -> &GenericParamDef {
940 let param = self.param_at(param.index as usize, tcx);
942 GenericParamDefKind::Const => param,
943 _ => bug!("expected const parameter, but found another generic parameter"),
948 /// Bounds on generics.
949 #[derive(Copy, Clone, Default, Debug, TyEncodable, TyDecodable, HashStable)]
950 pub struct GenericPredicates<'tcx> {
951 pub parent: Option<DefId>,
952 pub predicates: &'tcx [(Predicate<'tcx>, Span)],
955 impl<'tcx> GenericPredicates<'tcx> {
959 substs: SubstsRef<'tcx>,
960 ) -> InstantiatedPredicates<'tcx> {
961 let mut instantiated = InstantiatedPredicates::empty();
962 self.instantiate_into(tcx, &mut instantiated, substs);
966 pub fn instantiate_own(
969 substs: SubstsRef<'tcx>,
970 ) -> InstantiatedPredicates<'tcx> {
971 InstantiatedPredicates {
972 predicates: self.predicates.iter().map(|(p, _)| p.subst(tcx, substs)).collect(),
973 spans: self.predicates.iter().map(|(_, sp)| *sp).collect(),
980 instantiated: &mut InstantiatedPredicates<'tcx>,
981 substs: SubstsRef<'tcx>,
983 if let Some(def_id) = self.parent {
984 tcx.predicates_of(def_id).instantiate_into(tcx, instantiated, substs);
986 instantiated.predicates.extend(self.predicates.iter().map(|(p, _)| p.subst(tcx, substs)));
987 instantiated.spans.extend(self.predicates.iter().map(|(_, sp)| *sp));
990 pub fn instantiate_identity(&self, tcx: TyCtxt<'tcx>) -> InstantiatedPredicates<'tcx> {
991 let mut instantiated = InstantiatedPredicates::empty();
992 self.instantiate_identity_into(tcx, &mut instantiated);
996 fn instantiate_identity_into(
999 instantiated: &mut InstantiatedPredicates<'tcx>,
1001 if let Some(def_id) = self.parent {
1002 tcx.predicates_of(def_id).instantiate_identity_into(tcx, instantiated);
1004 instantiated.predicates.extend(self.predicates.iter().map(|(p, _)| p));
1005 instantiated.spans.extend(self.predicates.iter().map(|(_, s)| s));
1010 crate struct PredicateInner<'tcx> {
1011 kind: Binder<PredicateKind<'tcx>>,
1013 /// See the comment for the corresponding field of [TyS].
1014 outer_exclusive_binder: ty::DebruijnIndex,
1017 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
1018 static_assert_size!(PredicateInner<'_>, 40);
1020 #[derive(Clone, Copy, Lift)]
1021 pub struct Predicate<'tcx> {
1022 inner: &'tcx PredicateInner<'tcx>,
1025 impl<'tcx> PartialEq for Predicate<'tcx> {
1026 fn eq(&self, other: &Self) -> bool {
1027 // `self.kind` is always interned.
1028 ptr::eq(self.inner, other.inner)
1032 impl Hash for Predicate<'_> {
1033 fn hash<H: Hasher>(&self, s: &mut H) {
1034 (self.inner as *const PredicateInner<'_>).hash(s)
1038 impl<'tcx> Eq for Predicate<'tcx> {}
1040 impl<'tcx> Predicate<'tcx> {
1041 /// Gets the inner `Binder<PredicateKind<'tcx>>`.
1043 pub fn kind(self) -> Binder<PredicateKind<'tcx>> {
1048 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for Predicate<'tcx> {
1049 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
1050 let PredicateInner {
1053 // The other fields just provide fast access to information that is
1054 // also contained in `kind`, so no need to hash them.
1056 outer_exclusive_binder: _,
1059 kind.hash_stable(hcx, hasher);
1063 #[derive(Clone, Copy, PartialEq, Eq, Hash, TyEncodable, TyDecodable)]
1064 #[derive(HashStable, TypeFoldable)]
1065 pub enum PredicateKind<'tcx> {
1066 /// Corresponds to `where Foo: Bar<A, B, C>`. `Foo` here would be
1067 /// the `Self` type of the trait reference and `A`, `B`, and `C`
1068 /// would be the type parameters.
1070 /// A trait predicate will have `Constness::Const` if it originates
1071 /// from a bound on a `const fn` without the `?const` opt-out (e.g.,
1072 /// `const fn foobar<Foo: Bar>() {}`).
1073 Trait(TraitPredicate<'tcx>, Constness),
1076 RegionOutlives(RegionOutlivesPredicate<'tcx>),
1079 TypeOutlives(TypeOutlivesPredicate<'tcx>),
1081 /// `where <T as TraitRef>::Name == X`, approximately.
1082 /// See the `ProjectionPredicate` struct for details.
1083 Projection(ProjectionPredicate<'tcx>),
1085 /// No syntax: `T` well-formed.
1086 WellFormed(GenericArg<'tcx>),
1088 /// Trait must be object-safe.
1091 /// No direct syntax. May be thought of as `where T: FnFoo<...>`
1092 /// for some substitutions `...` and `T` being a closure type.
1093 /// Satisfied (or refuted) once we know the closure's kind.
1094 ClosureKind(DefId, SubstsRef<'tcx>, ClosureKind),
1097 Subtype(SubtypePredicate<'tcx>),
1099 /// Constant initializer must evaluate successfully.
1100 ConstEvaluatable(ty::WithOptConstParam<DefId>, SubstsRef<'tcx>),
1102 /// Constants must be equal. The first component is the const that is expected.
1103 ConstEquate(&'tcx Const<'tcx>, &'tcx Const<'tcx>),
1105 /// Represents a type found in the environment that we can use for implied bounds.
1107 /// Only used for Chalk.
1108 TypeWellFormedFromEnv(Ty<'tcx>),
1111 /// The crate outlives map is computed during typeck and contains the
1112 /// outlives of every item in the local crate. You should not use it
1113 /// directly, because to do so will make your pass dependent on the
1114 /// HIR of every item in the local crate. Instead, use
1115 /// `tcx.inferred_outlives_of()` to get the outlives for a *particular*
1117 #[derive(HashStable, Debug)]
1118 pub struct CratePredicatesMap<'tcx> {
1119 /// For each struct with outlive bounds, maps to a vector of the
1120 /// predicate of its outlive bounds. If an item has no outlives
1121 /// bounds, it will have no entry.
1122 pub predicates: FxHashMap<DefId, &'tcx [(Predicate<'tcx>, Span)]>,
1125 impl<'tcx> Predicate<'tcx> {
1126 /// Performs a substitution suitable for going from a
1127 /// poly-trait-ref to supertraits that must hold if that
1128 /// poly-trait-ref holds. This is slightly different from a normal
1129 /// substitution in terms of what happens with bound regions. See
1130 /// lengthy comment below for details.
1131 pub fn subst_supertrait(
1134 trait_ref: &ty::PolyTraitRef<'tcx>,
1135 ) -> Predicate<'tcx> {
1136 // The interaction between HRTB and supertraits is not entirely
1137 // obvious. Let me walk you (and myself) through an example.
1139 // Let's start with an easy case. Consider two traits:
1141 // trait Foo<'a>: Bar<'a,'a> { }
1142 // trait Bar<'b,'c> { }
1144 // Now, if we have a trait reference `for<'x> T: Foo<'x>`, then
1145 // we can deduce that `for<'x> T: Bar<'x,'x>`. Basically, if we
1146 // knew that `Foo<'x>` (for any 'x) then we also know that
1147 // `Bar<'x,'x>` (for any 'x). This more-or-less falls out from
1148 // normal substitution.
1150 // In terms of why this is sound, the idea is that whenever there
1151 // is an impl of `T:Foo<'a>`, it must show that `T:Bar<'a,'a>`
1152 // holds. So if there is an impl of `T:Foo<'a>` that applies to
1153 // all `'a`, then we must know that `T:Bar<'a,'a>` holds for all
1156 // Another example to be careful of is this:
1158 // trait Foo1<'a>: for<'b> Bar1<'a,'b> { }
1159 // trait Bar1<'b,'c> { }
1161 // Here, if we have `for<'x> T: Foo1<'x>`, then what do we know?
1162 // The answer is that we know `for<'x,'b> T: Bar1<'x,'b>`. The
1163 // reason is similar to the previous example: any impl of
1164 // `T:Foo1<'x>` must show that `for<'b> T: Bar1<'x, 'b>`. So
1165 // basically we would want to collapse the bound lifetimes from
1166 // the input (`trait_ref`) and the supertraits.
1168 // To achieve this in practice is fairly straightforward. Let's
1169 // consider the more complicated scenario:
1171 // - We start out with `for<'x> T: Foo1<'x>`. In this case, `'x`
1172 // has a De Bruijn index of 1. We want to produce `for<'x,'b> T: Bar1<'x,'b>`,
1173 // where both `'x` and `'b` would have a DB index of 1.
1174 // The substitution from the input trait-ref is therefore going to be
1175 // `'a => 'x` (where `'x` has a DB index of 1).
1176 // - The super-trait-ref is `for<'b> Bar1<'a,'b>`, where `'a` is an
1177 // early-bound parameter and `'b' is a late-bound parameter with a
1179 // - If we replace `'a` with `'x` from the input, it too will have
1180 // a DB index of 1, and thus we'll have `for<'x,'b> Bar1<'x,'b>`
1181 // just as we wanted.
1183 // There is only one catch. If we just apply the substitution `'a
1184 // => 'x` to `for<'b> Bar1<'a,'b>`, the substitution code will
1185 // adjust the DB index because we substituting into a binder (it
1186 // tries to be so smart...) resulting in `for<'x> for<'b>
1187 // Bar1<'x,'b>` (we have no syntax for this, so use your
1188 // imagination). Basically the 'x will have DB index of 2 and 'b
1189 // will have DB index of 1. Not quite what we want. So we apply
1190 // the substitution to the *contents* of the trait reference,
1191 // rather than the trait reference itself (put another way, the
1192 // substitution code expects equal binding levels in the values
1193 // from the substitution and the value being substituted into, and
1194 // this trick achieves that).
1195 let substs = trait_ref.skip_binder().substs;
1196 let pred = self.kind().skip_binder();
1197 let new = pred.subst(tcx, substs);
1198 tcx.reuse_or_mk_predicate(self, ty::Binder::bind(new))
1202 #[derive(Clone, Copy, PartialEq, Eq, Hash, TyEncodable, TyDecodable)]
1203 #[derive(HashStable, TypeFoldable)]
1204 pub struct TraitPredicate<'tcx> {
1205 pub trait_ref: TraitRef<'tcx>,
1208 pub type PolyTraitPredicate<'tcx> = ty::Binder<TraitPredicate<'tcx>>;
1210 impl<'tcx> TraitPredicate<'tcx> {
1211 pub fn def_id(self) -> DefId {
1212 self.trait_ref.def_id
1215 pub fn self_ty(self) -> Ty<'tcx> {
1216 self.trait_ref.self_ty()
1220 impl<'tcx> PolyTraitPredicate<'tcx> {
1221 pub fn def_id(self) -> DefId {
1222 // Ok to skip binder since trait `DefId` does not care about regions.
1223 self.skip_binder().def_id()
1226 pub fn self_ty(self) -> ty::Binder<Ty<'tcx>> {
1227 self.map_bound(|trait_ref| trait_ref.self_ty())
1231 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, TyEncodable, TyDecodable)]
1232 #[derive(HashStable, TypeFoldable)]
1233 pub struct OutlivesPredicate<A, B>(pub A, pub B); // `A: B`
1234 pub type RegionOutlivesPredicate<'tcx> = OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>;
1235 pub type TypeOutlivesPredicate<'tcx> = OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>;
1236 pub type PolyRegionOutlivesPredicate<'tcx> = ty::Binder<RegionOutlivesPredicate<'tcx>>;
1237 pub type PolyTypeOutlivesPredicate<'tcx> = ty::Binder<TypeOutlivesPredicate<'tcx>>;
1239 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, TyEncodable, TyDecodable)]
1240 #[derive(HashStable, TypeFoldable)]
1241 pub struct SubtypePredicate<'tcx> {
1242 pub a_is_expected: bool,
1246 pub type PolySubtypePredicate<'tcx> = ty::Binder<SubtypePredicate<'tcx>>;
1248 /// This kind of predicate has no *direct* correspondent in the
1249 /// syntax, but it roughly corresponds to the syntactic forms:
1251 /// 1. `T: TraitRef<..., Item = Type>`
1252 /// 2. `<T as TraitRef<...>>::Item == Type` (NYI)
1254 /// In particular, form #1 is "desugared" to the combination of a
1255 /// normal trait predicate (`T: TraitRef<...>`) and one of these
1256 /// predicates. Form #2 is a broader form in that it also permits
1257 /// equality between arbitrary types. Processing an instance of
1258 /// Form #2 eventually yields one of these `ProjectionPredicate`
1259 /// instances to normalize the LHS.
1260 #[derive(Copy, Clone, PartialEq, Eq, Hash, TyEncodable, TyDecodable)]
1261 #[derive(HashStable, TypeFoldable)]
1262 pub struct ProjectionPredicate<'tcx> {
1263 pub projection_ty: ProjectionTy<'tcx>,
1267 pub type PolyProjectionPredicate<'tcx> = Binder<ProjectionPredicate<'tcx>>;
1269 impl<'tcx> PolyProjectionPredicate<'tcx> {
1270 /// Returns the `DefId` of the associated item being projected.
1271 pub fn item_def_id(&self) -> DefId {
1272 self.skip_binder().projection_ty.item_def_id
1275 /// Returns the `DefId` of the trait of the associated item being projected.
1277 pub fn trait_def_id(&self, tcx: TyCtxt<'tcx>) -> DefId {
1278 self.skip_binder().projection_ty.trait_def_id(tcx)
1282 pub fn projection_self_ty(&self) -> Binder<Ty<'tcx>> {
1283 self.map_bound(|predicate| predicate.projection_ty.self_ty())
1286 /// Get the [PolyTraitRef] required for this projection to be well formed.
1287 /// Note that for generic associated types the predicates of the associated
1288 /// type also need to be checked.
1290 pub fn required_poly_trait_ref(&self, tcx: TyCtxt<'tcx>) -> PolyTraitRef<'tcx> {
1291 // Note: unlike with `TraitRef::to_poly_trait_ref()`,
1292 // `self.0.trait_ref` is permitted to have escaping regions.
1293 // This is because here `self` has a `Binder` and so does our
1294 // return value, so we are preserving the number of binding
1296 self.map_bound(|predicate| predicate.projection_ty.trait_ref(tcx))
1299 pub fn ty(&self) -> Binder<Ty<'tcx>> {
1300 self.map_bound(|predicate| predicate.ty)
1303 /// The `DefId` of the `TraitItem` for the associated type.
1305 /// Note that this is not the `DefId` of the `TraitRef` containing this
1306 /// associated type, which is in `tcx.associated_item(projection_def_id()).container`.
1307 pub fn projection_def_id(&self) -> DefId {
1308 // Ok to skip binder since trait `DefId` does not care about regions.
1309 self.skip_binder().projection_ty.item_def_id
1313 pub trait ToPolyTraitRef<'tcx> {
1314 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx>;
1317 impl<'tcx> ToPolyTraitRef<'tcx> for TraitRef<'tcx> {
1318 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
1319 ty::Binder::dummy(*self)
1323 impl<'tcx> ToPolyTraitRef<'tcx> for PolyTraitPredicate<'tcx> {
1324 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
1325 self.map_bound_ref(|trait_pred| trait_pred.trait_ref)
1329 pub trait ToPredicate<'tcx> {
1330 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx>;
1333 impl ToPredicate<'tcx> for Binder<PredicateKind<'tcx>> {
1335 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1336 tcx.mk_predicate(self)
1340 impl ToPredicate<'tcx> for PredicateKind<'tcx> {
1342 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1343 tcx.mk_predicate(Binder::dummy(self))
1347 impl<'tcx> ToPredicate<'tcx> for ConstnessAnd<TraitRef<'tcx>> {
1348 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1349 PredicateKind::Trait(ty::TraitPredicate { trait_ref: self.value }, self.constness)
1354 impl<'tcx> ToPredicate<'tcx> for ConstnessAnd<PolyTraitRef<'tcx>> {
1355 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1357 value: self.value.map_bound(|trait_ref| ty::TraitPredicate { trait_ref }),
1358 constness: self.constness,
1364 impl<'tcx> ToPredicate<'tcx> for ConstnessAnd<PolyTraitPredicate<'tcx>> {
1365 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1366 self.value.map_bound(|value| PredicateKind::Trait(value, self.constness)).to_predicate(tcx)
1370 impl<'tcx> ToPredicate<'tcx> for PolyRegionOutlivesPredicate<'tcx> {
1371 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1372 self.map_bound(PredicateKind::RegionOutlives).to_predicate(tcx)
1376 impl<'tcx> ToPredicate<'tcx> for PolyTypeOutlivesPredicate<'tcx> {
1377 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1378 self.map_bound(PredicateKind::TypeOutlives).to_predicate(tcx)
1382 impl<'tcx> ToPredicate<'tcx> for PolyProjectionPredicate<'tcx> {
1383 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1384 self.map_bound(PredicateKind::Projection).to_predicate(tcx)
1388 impl<'tcx> Predicate<'tcx> {
1389 pub fn to_opt_poly_trait_ref(self) -> Option<ConstnessAnd<PolyTraitRef<'tcx>>> {
1390 let predicate = self.kind();
1391 match predicate.skip_binder() {
1392 PredicateKind::Trait(t, constness) => {
1393 Some(ConstnessAnd { constness, value: predicate.rebind(t.trait_ref) })
1395 PredicateKind::Projection(..)
1396 | PredicateKind::Subtype(..)
1397 | PredicateKind::RegionOutlives(..)
1398 | PredicateKind::WellFormed(..)
1399 | PredicateKind::ObjectSafe(..)
1400 | PredicateKind::ClosureKind(..)
1401 | PredicateKind::TypeOutlives(..)
1402 | PredicateKind::ConstEvaluatable(..)
1403 | PredicateKind::ConstEquate(..)
1404 | PredicateKind::TypeWellFormedFromEnv(..) => None,
1408 pub fn to_opt_type_outlives(self) -> Option<PolyTypeOutlivesPredicate<'tcx>> {
1409 let predicate = self.kind();
1410 match predicate.skip_binder() {
1411 PredicateKind::TypeOutlives(data) => Some(predicate.rebind(data)),
1412 PredicateKind::Trait(..)
1413 | PredicateKind::Projection(..)
1414 | PredicateKind::Subtype(..)
1415 | PredicateKind::RegionOutlives(..)
1416 | PredicateKind::WellFormed(..)
1417 | PredicateKind::ObjectSafe(..)
1418 | PredicateKind::ClosureKind(..)
1419 | PredicateKind::ConstEvaluatable(..)
1420 | PredicateKind::ConstEquate(..)
1421 | PredicateKind::TypeWellFormedFromEnv(..) => None,
1426 /// Represents the bounds declared on a particular set of type
1427 /// parameters. Should eventually be generalized into a flag list of
1428 /// where-clauses. You can obtain a `InstantiatedPredicates` list from a
1429 /// `GenericPredicates` by using the `instantiate` method. Note that this method
1430 /// reflects an important semantic invariant of `InstantiatedPredicates`: while
1431 /// the `GenericPredicates` are expressed in terms of the bound type
1432 /// parameters of the impl/trait/whatever, an `InstantiatedPredicates` instance
1433 /// represented a set of bounds for some particular instantiation,
1434 /// meaning that the generic parameters have been substituted with
1439 /// struct Foo<T, U: Bar<T>> { ... }
1441 /// Here, the `GenericPredicates` for `Foo` would contain a list of bounds like
1442 /// `[[], [U:Bar<T>]]`. Now if there were some particular reference
1443 /// like `Foo<isize,usize>`, then the `InstantiatedPredicates` would be `[[],
1444 /// [usize:Bar<isize>]]`.
1445 #[derive(Clone, Debug, TypeFoldable)]
1446 pub struct InstantiatedPredicates<'tcx> {
1447 pub predicates: Vec<Predicate<'tcx>>,
1448 pub spans: Vec<Span>,
1451 impl<'tcx> InstantiatedPredicates<'tcx> {
1452 pub fn empty() -> InstantiatedPredicates<'tcx> {
1453 InstantiatedPredicates { predicates: vec![], spans: vec![] }
1456 pub fn is_empty(&self) -> bool {
1457 self.predicates.is_empty()
1461 rustc_index::newtype_index! {
1462 /// "Universes" are used during type- and trait-checking in the
1463 /// presence of `for<..>` binders to control what sets of names are
1464 /// visible. Universes are arranged into a tree: the root universe
1465 /// contains names that are always visible. Each child then adds a new
1466 /// set of names that are visible, in addition to those of its parent.
1467 /// We say that the child universe "extends" the parent universe with
1470 /// To make this more concrete, consider this program:
1474 /// fn bar<T>(x: T) {
1475 /// let y: for<'a> fn(&'a u8, Foo) = ...;
1479 /// The struct name `Foo` is in the root universe U0. But the type
1480 /// parameter `T`, introduced on `bar`, is in an extended universe U1
1481 /// -- i.e., within `bar`, we can name both `T` and `Foo`, but outside
1482 /// of `bar`, we cannot name `T`. Then, within the type of `y`, the
1483 /// region `'a` is in a universe U2 that extends U1, because we can
1484 /// name it inside the fn type but not outside.
1486 /// Universes are used to do type- and trait-checking around these
1487 /// "forall" binders (also called **universal quantification**). The
1488 /// idea is that when, in the body of `bar`, we refer to `T` as a
1489 /// type, we aren't referring to any type in particular, but rather a
1490 /// kind of "fresh" type that is distinct from all other types we have
1491 /// actually declared. This is called a **placeholder** type, and we
1492 /// use universes to talk about this. In other words, a type name in
1493 /// universe 0 always corresponds to some "ground" type that the user
1494 /// declared, but a type name in a non-zero universe is a placeholder
1495 /// type -- an idealized representative of "types in general" that we
1496 /// use for checking generic functions.
1497 pub struct UniverseIndex {
1499 DEBUG_FORMAT = "U{}",
1503 impl UniverseIndex {
1504 pub const ROOT: UniverseIndex = UniverseIndex::from_u32(0);
1506 /// Returns the "next" universe index in order -- this new index
1507 /// is considered to extend all previous universes. This
1508 /// corresponds to entering a `forall` quantifier. So, for
1509 /// example, suppose we have this type in universe `U`:
1512 /// for<'a> fn(&'a u32)
1515 /// Once we "enter" into this `for<'a>` quantifier, we are in a
1516 /// new universe that extends `U` -- in this new universe, we can
1517 /// name the region `'a`, but that region was not nameable from
1518 /// `U` because it was not in scope there.
1519 pub fn next_universe(self) -> UniverseIndex {
1520 UniverseIndex::from_u32(self.private.checked_add(1).unwrap())
1523 /// Returns `true` if `self` can name a name from `other` -- in other words,
1524 /// if the set of names in `self` is a superset of those in
1525 /// `other` (`self >= other`).
1526 pub fn can_name(self, other: UniverseIndex) -> bool {
1527 self.private >= other.private
1530 /// Returns `true` if `self` cannot name some names from `other` -- in other
1531 /// words, if the set of names in `self` is a strict subset of
1532 /// those in `other` (`self < other`).
1533 pub fn cannot_name(self, other: UniverseIndex) -> bool {
1534 self.private < other.private
1538 /// The "placeholder index" fully defines a placeholder region, type, or const. Placeholders are
1539 /// identified by both a universe, as well as a name residing within that universe. Distinct bound
1540 /// regions/types/consts within the same universe simply have an unknown relationship to one
1542 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TyEncodable, TyDecodable, PartialOrd, Ord)]
1543 pub struct Placeholder<T> {
1544 pub universe: UniverseIndex,
1548 impl<'a, T> HashStable<StableHashingContext<'a>> for Placeholder<T>
1550 T: HashStable<StableHashingContext<'a>>,
1552 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
1553 self.universe.hash_stable(hcx, hasher);
1554 self.name.hash_stable(hcx, hasher);
1558 pub type PlaceholderRegion = Placeholder<BoundRegionKind>;
1560 pub type PlaceholderType = Placeholder<BoundVar>;
1562 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable)]
1563 #[derive(TyEncodable, TyDecodable, PartialOrd, Ord)]
1564 pub struct BoundConst<'tcx> {
1569 pub type PlaceholderConst<'tcx> = Placeholder<BoundConst<'tcx>>;
1571 /// A `DefId` which, in case it is a const argument, is potentially bundled with
1572 /// the `DefId` of the generic parameter it instantiates.
1574 /// This is used to avoid calls to `type_of` for const arguments during typeck
1575 /// which cause cycle errors.
1580 /// fn foo<const N: usize>(&self) -> [u8; N] { [0; N] }
1581 /// // ^ const parameter
1585 /// fn foo<const M: u8>(&self) -> usize { 42 }
1586 /// // ^ const parameter
1591 /// let _b = a.foo::<{ 3 + 7 }>();
1592 /// // ^^^^^^^^^ const argument
1596 /// Let's look at the call `a.foo::<{ 3 + 7 }>()` here. We do not know
1597 /// which `foo` is used until we know the type of `a`.
1599 /// We only know the type of `a` once we are inside of `typeck(main)`.
1600 /// We also end up normalizing the type of `_b` during `typeck(main)` which
1601 /// requires us to evaluate the const argument.
1603 /// To evaluate that const argument we need to know its type,
1604 /// which we would get using `type_of(const_arg)`. This requires us to
1605 /// resolve `foo` as it can be either `usize` or `u8` in this example.
1606 /// However, resolving `foo` once again requires `typeck(main)` to get the type of `a`,
1607 /// which results in a cycle.
1609 /// In short we must not call `type_of(const_arg)` during `typeck(main)`.
1611 /// When first creating the `ty::Const` of the const argument inside of `typeck` we have
1612 /// already resolved `foo` so we know which const parameter this argument instantiates.
1613 /// This means that we also know the expected result of `type_of(const_arg)` even if we
1614 /// aren't allowed to call that query: it is equal to `type_of(const_param)` which is
1615 /// trivial to compute.
1617 /// If we now want to use that constant in a place which potentionally needs its type
1618 /// we also pass the type of its `const_param`. This is the point of `WithOptConstParam`,
1619 /// except that instead of a `Ty` we bundle the `DefId` of the const parameter.
1620 /// Meaning that we need to use `type_of(const_param_did)` if `const_param_did` is `Some`
1621 /// to get the type of `did`.
1622 #[derive(Copy, Clone, Debug, TypeFoldable, Lift, TyEncodable, TyDecodable)]
1623 #[derive(PartialEq, Eq, PartialOrd, Ord)]
1624 #[derive(Hash, HashStable)]
1625 pub struct WithOptConstParam<T> {
1627 /// The `DefId` of the corresponding generic parameter in case `did` is
1628 /// a const argument.
1630 /// Note that even if `did` is a const argument, this may still be `None`.
1631 /// All queries taking `WithOptConstParam` start by calling `tcx.opt_const_param_of(def.did)`
1632 /// to potentially update `param_did` in the case it is `None`.
1633 pub const_param_did: Option<DefId>,
1636 impl<T> WithOptConstParam<T> {
1637 /// Creates a new `WithOptConstParam` setting `const_param_did` to `None`.
1639 pub fn unknown(did: T) -> WithOptConstParam<T> {
1640 WithOptConstParam { did, const_param_did: None }
1644 impl WithOptConstParam<LocalDefId> {
1645 /// Returns `Some((did, param_did))` if `def_id` is a const argument,
1646 /// `None` otherwise.
1648 pub fn try_lookup(did: LocalDefId, tcx: TyCtxt<'_>) -> Option<(LocalDefId, DefId)> {
1649 tcx.opt_const_param_of(did).map(|param_did| (did, param_did))
1652 /// In case `self` is unknown but `self.did` is a const argument, this returns
1653 /// a `WithOptConstParam` with the correct `const_param_did`.
1655 pub fn try_upgrade(self, tcx: TyCtxt<'_>) -> Option<WithOptConstParam<LocalDefId>> {
1656 if self.const_param_did.is_none() {
1657 if let const_param_did @ Some(_) = tcx.opt_const_param_of(self.did) {
1658 return Some(WithOptConstParam { did: self.did, const_param_did });
1665 pub fn to_global(self) -> WithOptConstParam<DefId> {
1666 WithOptConstParam { did: self.did.to_def_id(), const_param_did: self.const_param_did }
1669 pub fn def_id_for_type_of(self) -> DefId {
1670 if let Some(did) = self.const_param_did { did } else { self.did.to_def_id() }
1674 impl WithOptConstParam<DefId> {
1675 pub fn as_local(self) -> Option<WithOptConstParam<LocalDefId>> {
1678 .map(|did| WithOptConstParam { did, const_param_did: self.const_param_did })
1681 pub fn as_const_arg(self) -> Option<(LocalDefId, DefId)> {
1682 if let Some(param_did) = self.const_param_did {
1683 if let Some(did) = self.did.as_local() {
1684 return Some((did, param_did));
1691 pub fn expect_local(self) -> WithOptConstParam<LocalDefId> {
1692 self.as_local().unwrap()
1695 pub fn is_local(self) -> bool {
1699 pub fn def_id_for_type_of(self) -> DefId {
1700 self.const_param_did.unwrap_or(self.did)
1704 /// When type checking, we use the `ParamEnv` to track
1705 /// details about the set of where-clauses that are in scope at this
1706 /// particular point.
1707 #[derive(Copy, Clone, Hash, PartialEq, Eq)]
1708 pub struct ParamEnv<'tcx> {
1709 /// This packs both caller bounds and the reveal enum into one pointer.
1711 /// Caller bounds are `Obligation`s that the caller must satisfy. This is
1712 /// basically the set of bounds on the in-scope type parameters, translated
1713 /// into `Obligation`s, and elaborated and normalized.
1715 /// Use the `caller_bounds()` method to access.
1717 /// Typically, this is `Reveal::UserFacing`, but during codegen we
1718 /// want `Reveal::All`.
1720 /// Note: This is packed, use the reveal() method to access it.
1721 packed: CopyTaggedPtr<&'tcx List<Predicate<'tcx>>, traits::Reveal, true>,
1724 unsafe impl rustc_data_structures::tagged_ptr::Tag for traits::Reveal {
1725 const BITS: usize = 1;
1726 fn into_usize(self) -> usize {
1728 traits::Reveal::UserFacing => 0,
1729 traits::Reveal::All => 1,
1732 unsafe fn from_usize(ptr: usize) -> Self {
1734 0 => traits::Reveal::UserFacing,
1735 1 => traits::Reveal::All,
1736 _ => std::hint::unreachable_unchecked(),
1741 impl<'tcx> fmt::Debug for ParamEnv<'tcx> {
1742 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1743 f.debug_struct("ParamEnv")
1744 .field("caller_bounds", &self.caller_bounds())
1745 .field("reveal", &self.reveal())
1750 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for ParamEnv<'tcx> {
1751 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
1752 self.caller_bounds().hash_stable(hcx, hasher);
1753 self.reveal().hash_stable(hcx, hasher);
1757 impl<'tcx> TypeFoldable<'tcx> for ParamEnv<'tcx> {
1758 fn super_fold_with<F: ty::fold::TypeFolder<'tcx>>(self, folder: &mut F) -> Self {
1759 ParamEnv::new(self.caller_bounds().fold_with(folder), self.reveal().fold_with(folder))
1762 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> ControlFlow<V::BreakTy> {
1763 self.caller_bounds().visit_with(visitor)?;
1764 self.reveal().visit_with(visitor)
1768 impl<'tcx> ParamEnv<'tcx> {
1769 /// Construct a trait environment suitable for contexts where
1770 /// there are no where-clauses in scope. Hidden types (like `impl
1771 /// Trait`) are left hidden, so this is suitable for ordinary
1774 pub fn empty() -> Self {
1775 Self::new(List::empty(), Reveal::UserFacing)
1779 pub fn caller_bounds(self) -> &'tcx List<Predicate<'tcx>> {
1780 self.packed.pointer()
1784 pub fn reveal(self) -> traits::Reveal {
1788 /// Construct a trait environment with no where-clauses in scope
1789 /// where the values of all `impl Trait` and other hidden types
1790 /// are revealed. This is suitable for monomorphized, post-typeck
1791 /// environments like codegen or doing optimizations.
1793 /// N.B., if you want to have predicates in scope, use `ParamEnv::new`,
1794 /// or invoke `param_env.with_reveal_all()`.
1796 pub fn reveal_all() -> Self {
1797 Self::new(List::empty(), Reveal::All)
1800 /// Construct a trait environment with the given set of predicates.
1802 pub fn new(caller_bounds: &'tcx List<Predicate<'tcx>>, reveal: Reveal) -> Self {
1803 ty::ParamEnv { packed: CopyTaggedPtr::new(caller_bounds, reveal) }
1806 pub fn with_user_facing(mut self) -> Self {
1807 self.packed.set_tag(Reveal::UserFacing);
1811 /// Returns a new parameter environment with the same clauses, but
1812 /// which "reveals" the true results of projections in all cases
1813 /// (even for associated types that are specializable). This is
1814 /// the desired behavior during codegen and certain other special
1815 /// contexts; normally though we want to use `Reveal::UserFacing`,
1816 /// which is the default.
1817 /// All opaque types in the caller_bounds of the `ParamEnv`
1818 /// will be normalized to their underlying types.
1819 /// See PR #65989 and issue #65918 for more details
1820 pub fn with_reveal_all_normalized(self, tcx: TyCtxt<'tcx>) -> Self {
1821 if self.packed.tag() == traits::Reveal::All {
1825 ParamEnv::new(tcx.normalize_opaque_types(self.caller_bounds()), Reveal::All)
1828 /// Returns this same environment but with no caller bounds.
1829 pub fn without_caller_bounds(self) -> Self {
1830 Self::new(List::empty(), self.reveal())
1833 /// Creates a suitable environment in which to perform trait
1834 /// queries on the given value. When type-checking, this is simply
1835 /// the pair of the environment plus value. But when reveal is set to
1836 /// All, then if `value` does not reference any type parameters, we will
1837 /// pair it with the empty environment. This improves caching and is generally
1840 /// N.B., we preserve the environment when type-checking because it
1841 /// is possible for the user to have wacky where-clauses like
1842 /// `where Box<u32>: Copy`, which are clearly never
1843 /// satisfiable. We generally want to behave as if they were true,
1844 /// although the surrounding function is never reachable.
1845 pub fn and<T: TypeFoldable<'tcx>>(self, value: T) -> ParamEnvAnd<'tcx, T> {
1846 match self.reveal() {
1847 Reveal::UserFacing => ParamEnvAnd { param_env: self, value },
1850 if value.is_global() {
1851 ParamEnvAnd { param_env: self.without_caller_bounds(), value }
1853 ParamEnvAnd { param_env: self, value }
1860 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TypeFoldable)]
1861 pub struct ConstnessAnd<T> {
1862 pub constness: Constness,
1866 // FIXME(ecstaticmorse): Audit all occurrences of `without_const().to_predicate(tcx)` to ensure that
1867 // the constness of trait bounds is being propagated correctly.
1868 pub trait WithConstness: Sized {
1870 fn with_constness(self, constness: Constness) -> ConstnessAnd<Self> {
1871 ConstnessAnd { constness, value: self }
1875 fn with_const(self) -> ConstnessAnd<Self> {
1876 self.with_constness(Constness::Const)
1880 fn without_const(self) -> ConstnessAnd<Self> {
1881 self.with_constness(Constness::NotConst)
1885 impl<T> WithConstness for T {}
1887 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TypeFoldable)]
1888 pub struct ParamEnvAnd<'tcx, T> {
1889 pub param_env: ParamEnv<'tcx>,
1893 impl<'tcx, T> ParamEnvAnd<'tcx, T> {
1894 pub fn into_parts(self) -> (ParamEnv<'tcx>, T) {
1895 (self.param_env, self.value)
1899 impl<'a, 'tcx, T> HashStable<StableHashingContext<'a>> for ParamEnvAnd<'tcx, T>
1901 T: HashStable<StableHashingContext<'a>>,
1903 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
1904 let ParamEnvAnd { ref param_env, ref value } = *self;
1906 param_env.hash_stable(hcx, hasher);
1907 value.hash_stable(hcx, hasher);
1911 #[derive(Copy, Clone, Debug, HashStable)]
1912 pub struct Destructor {
1913 /// The `DefId` of the destructor method
1918 #[derive(HashStable)]
1919 pub struct AdtFlags: u32 {
1920 const NO_ADT_FLAGS = 0;
1921 /// Indicates whether the ADT is an enum.
1922 const IS_ENUM = 1 << 0;
1923 /// Indicates whether the ADT is a union.
1924 const IS_UNION = 1 << 1;
1925 /// Indicates whether the ADT is a struct.
1926 const IS_STRUCT = 1 << 2;
1927 /// Indicates whether the ADT is a struct and has a constructor.
1928 const HAS_CTOR = 1 << 3;
1929 /// Indicates whether the type is `PhantomData`.
1930 const IS_PHANTOM_DATA = 1 << 4;
1931 /// Indicates whether the type has a `#[fundamental]` attribute.
1932 const IS_FUNDAMENTAL = 1 << 5;
1933 /// Indicates whether the type is `Box`.
1934 const IS_BOX = 1 << 6;
1935 /// Indicates whether the type is `ManuallyDrop`.
1936 const IS_MANUALLY_DROP = 1 << 7;
1937 /// Indicates whether the variant list of this ADT is `#[non_exhaustive]`.
1938 /// (i.e., this flag is never set unless this ADT is an enum).
1939 const IS_VARIANT_LIST_NON_EXHAUSTIVE = 1 << 8;
1944 #[derive(HashStable)]
1945 pub struct VariantFlags: u32 {
1946 const NO_VARIANT_FLAGS = 0;
1947 /// Indicates whether the field list of this variant is `#[non_exhaustive]`.
1948 const IS_FIELD_LIST_NON_EXHAUSTIVE = 1 << 0;
1949 /// Indicates whether this variant was obtained as part of recovering from
1950 /// a syntactic error. May be incomplete or bogus.
1951 const IS_RECOVERED = 1 << 1;
1955 /// Definition of a variant -- a struct's fields or a enum variant.
1956 #[derive(Debug, HashStable)]
1957 pub struct VariantDef {
1958 /// `DefId` that identifies the variant itself.
1959 /// If this variant belongs to a struct or union, then this is a copy of its `DefId`.
1961 /// `DefId` that identifies the variant's constructor.
1962 /// If this variant is a struct variant, then this is `None`.
1963 pub ctor_def_id: Option<DefId>,
1964 /// Variant or struct name.
1965 #[stable_hasher(project(name))]
1967 /// Discriminant of this variant.
1968 pub discr: VariantDiscr,
1969 /// Fields of this variant.
1970 pub fields: Vec<FieldDef>,
1971 /// Type of constructor of variant.
1972 pub ctor_kind: CtorKind,
1973 /// Flags of the variant (e.g. is field list non-exhaustive)?
1974 flags: VariantFlags,
1978 /// Creates a new `VariantDef`.
1980 /// `variant_did` is the `DefId` that identifies the enum variant (if this `VariantDef`
1981 /// represents an enum variant).
1983 /// `ctor_did` is the `DefId` that identifies the constructor of unit or
1984 /// tuple-variants/structs. If this is a `struct`-variant then this should be `None`.
1986 /// `parent_did` is the `DefId` of the `AdtDef` representing the enum or struct that
1987 /// owns this variant. It is used for checking if a struct has `#[non_exhaustive]` w/out having
1988 /// to go through the redirect of checking the ctor's attributes - but compiling a small crate
1989 /// requires loading the `AdtDef`s for all the structs in the universe (e.g., coherence for any
1990 /// built-in trait), and we do not want to load attributes twice.
1992 /// If someone speeds up attribute loading to not be a performance concern, they can
1993 /// remove this hack and use the constructor `DefId` everywhere.
1996 variant_did: Option<DefId>,
1997 ctor_def_id: Option<DefId>,
1998 discr: VariantDiscr,
1999 fields: Vec<FieldDef>,
2000 ctor_kind: CtorKind,
2004 is_field_list_non_exhaustive: bool,
2007 "VariantDef::new(ident = {:?}, variant_did = {:?}, ctor_def_id = {:?}, discr = {:?},
2008 fields = {:?}, ctor_kind = {:?}, adt_kind = {:?}, parent_did = {:?})",
2009 ident, variant_did, ctor_def_id, discr, fields, ctor_kind, adt_kind, parent_did,
2012 let mut flags = VariantFlags::NO_VARIANT_FLAGS;
2013 if is_field_list_non_exhaustive {
2014 flags |= VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE;
2018 flags |= VariantFlags::IS_RECOVERED;
2022 def_id: variant_did.unwrap_or(parent_did),
2032 /// Is this field list non-exhaustive?
2034 pub fn is_field_list_non_exhaustive(&self) -> bool {
2035 self.flags.intersects(VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE)
2038 /// Was this variant obtained as part of recovering from a syntactic error?
2040 pub fn is_recovered(&self) -> bool {
2041 self.flags.intersects(VariantFlags::IS_RECOVERED)
2045 #[derive(Copy, Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
2046 pub enum VariantDiscr {
2047 /// Explicit value for this variant, i.e., `X = 123`.
2048 /// The `DefId` corresponds to the embedded constant.
2051 /// The previous variant's discriminant plus one.
2052 /// For efficiency reasons, the distance from the
2053 /// last `Explicit` discriminant is being stored,
2054 /// or `0` for the first variant, if it has none.
2058 #[derive(Debug, HashStable)]
2059 pub struct FieldDef {
2061 #[stable_hasher(project(name))]
2063 pub vis: Visibility,
2066 /// The definition of a user-defined type, e.g., a `struct`, `enum`, or `union`.
2068 /// These are all interned (by `alloc_adt_def`) into the global arena.
2070 /// The initialism *ADT* stands for an [*algebraic data type (ADT)*][adt].
2071 /// This is slightly wrong because `union`s are not ADTs.
2072 /// Moreover, Rust only allows recursive data types through indirection.
2074 /// [adt]: https://en.wikipedia.org/wiki/Algebraic_data_type
2076 /// The `DefId` of the struct, enum or union item.
2078 /// Variants of the ADT. If this is a struct or union, then there will be a single variant.
2079 pub variants: IndexVec<VariantIdx, VariantDef>,
2080 /// Flags of the ADT (e.g., is this a struct? is this non-exhaustive?).
2082 /// Repr options provided by the user.
2083 pub repr: ReprOptions,
2086 impl PartialOrd for AdtDef {
2087 fn partial_cmp(&self, other: &AdtDef) -> Option<Ordering> {
2088 Some(self.cmp(&other))
2092 /// There should be only one AdtDef for each `did`, therefore
2093 /// it is fine to implement `Ord` only based on `did`.
2094 impl Ord for AdtDef {
2095 fn cmp(&self, other: &AdtDef) -> Ordering {
2096 self.did.cmp(&other.did)
2100 impl PartialEq for AdtDef {
2101 // `AdtDef`s are always interned, and this is part of `TyS` equality.
2103 fn eq(&self, other: &Self) -> bool {
2104 ptr::eq(self, other)
2108 impl Eq for AdtDef {}
2110 impl Hash for AdtDef {
2112 fn hash<H: Hasher>(&self, s: &mut H) {
2113 (self as *const AdtDef).hash(s)
2117 impl<S: Encoder> Encodable<S> for AdtDef {
2118 fn encode(&self, s: &mut S) -> Result<(), S::Error> {
2123 impl<'a> HashStable<StableHashingContext<'a>> for AdtDef {
2124 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
2126 static CACHE: RefCell<FxHashMap<usize, Fingerprint>> = Default::default();
2129 let hash: Fingerprint = CACHE.with(|cache| {
2130 let addr = self as *const AdtDef as usize;
2131 *cache.borrow_mut().entry(addr).or_insert_with(|| {
2132 let ty::AdtDef { did, ref variants, ref flags, ref repr } = *self;
2134 let mut hasher = StableHasher::new();
2135 did.hash_stable(hcx, &mut hasher);
2136 variants.hash_stable(hcx, &mut hasher);
2137 flags.hash_stable(hcx, &mut hasher);
2138 repr.hash_stable(hcx, &mut hasher);
2144 hash.hash_stable(hcx, hasher);
2148 #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
2155 impl Into<DataTypeKind> for AdtKind {
2156 fn into(self) -> DataTypeKind {
2158 AdtKind::Struct => DataTypeKind::Struct,
2159 AdtKind::Union => DataTypeKind::Union,
2160 AdtKind::Enum => DataTypeKind::Enum,
2166 #[derive(TyEncodable, TyDecodable, Default, HashStable)]
2167 pub struct ReprFlags: u8 {
2168 const IS_C = 1 << 0;
2169 const IS_SIMD = 1 << 1;
2170 const IS_TRANSPARENT = 1 << 2;
2171 // Internal only for now. If true, don't reorder fields.
2172 const IS_LINEAR = 1 << 3;
2173 // If true, don't expose any niche to type's context.
2174 const HIDE_NICHE = 1 << 4;
2175 // Any of these flags being set prevent field reordering optimisation.
2176 const IS_UNOPTIMISABLE = ReprFlags::IS_C.bits |
2177 ReprFlags::IS_SIMD.bits |
2178 ReprFlags::IS_LINEAR.bits;
2182 /// Represents the repr options provided by the user,
2183 #[derive(Copy, Clone, Debug, Eq, PartialEq, TyEncodable, TyDecodable, Default, HashStable)]
2184 pub struct ReprOptions {
2185 pub int: Option<attr::IntType>,
2186 pub align: Option<Align>,
2187 pub pack: Option<Align>,
2188 pub flags: ReprFlags,
2192 pub fn new(tcx: TyCtxt<'_>, did: DefId) -> ReprOptions {
2193 let mut flags = ReprFlags::empty();
2194 let mut size = None;
2195 let mut max_align: Option<Align> = None;
2196 let mut min_pack: Option<Align> = None;
2197 for attr in tcx.get_attrs(did).iter() {
2198 for r in attr::find_repr_attrs(&tcx.sess, attr) {
2199 flags.insert(match r {
2200 attr::ReprC => ReprFlags::IS_C,
2201 attr::ReprPacked(pack) => {
2202 let pack = Align::from_bytes(pack as u64).unwrap();
2203 min_pack = Some(if let Some(min_pack) = min_pack {
2210 attr::ReprTransparent => ReprFlags::IS_TRANSPARENT,
2211 attr::ReprNoNiche => ReprFlags::HIDE_NICHE,
2212 attr::ReprSimd => ReprFlags::IS_SIMD,
2213 attr::ReprInt(i) => {
2217 attr::ReprAlign(align) => {
2218 max_align = max_align.max(Some(Align::from_bytes(align as u64).unwrap()));
2225 // This is here instead of layout because the choice must make it into metadata.
2226 if !tcx.consider_optimizing(|| format!("Reorder fields of {:?}", tcx.def_path_str(did))) {
2227 flags.insert(ReprFlags::IS_LINEAR);
2229 ReprOptions { int: size, align: max_align, pack: min_pack, flags }
2233 pub fn simd(&self) -> bool {
2234 self.flags.contains(ReprFlags::IS_SIMD)
2237 pub fn c(&self) -> bool {
2238 self.flags.contains(ReprFlags::IS_C)
2241 pub fn packed(&self) -> bool {
2245 pub fn transparent(&self) -> bool {
2246 self.flags.contains(ReprFlags::IS_TRANSPARENT)
2249 pub fn linear(&self) -> bool {
2250 self.flags.contains(ReprFlags::IS_LINEAR)
2253 pub fn hide_niche(&self) -> bool {
2254 self.flags.contains(ReprFlags::HIDE_NICHE)
2257 /// Returns the discriminant type, given these `repr` options.
2258 /// This must only be called on enums!
2259 pub fn discr_type(&self) -> attr::IntType {
2260 self.int.unwrap_or(attr::SignedInt(ast::IntTy::Isize))
2263 /// Returns `true` if this `#[repr()]` should inhabit "smart enum
2264 /// layout" optimizations, such as representing `Foo<&T>` as a
2266 pub fn inhibit_enum_layout_opt(&self) -> bool {
2267 self.c() || self.int.is_some()
2270 /// Returns `true` if this `#[repr()]` should inhibit struct field reordering
2271 /// optimizations, such as with `repr(C)`, `repr(packed(1))`, or `repr(<int>)`.
2272 pub fn inhibit_struct_field_reordering_opt(&self) -> bool {
2273 if let Some(pack) = self.pack {
2274 if pack.bytes() == 1 {
2278 self.flags.intersects(ReprFlags::IS_UNOPTIMISABLE) || self.int.is_some()
2281 /// Returns `true` if this `#[repr()]` should inhibit union ABI optimisations.
2282 pub fn inhibit_union_abi_opt(&self) -> bool {
2288 /// Creates a new `AdtDef`.
2293 variants: IndexVec<VariantIdx, VariantDef>,
2296 debug!("AdtDef::new({:?}, {:?}, {:?}, {:?})", did, kind, variants, repr);
2297 let mut flags = AdtFlags::NO_ADT_FLAGS;
2299 if kind == AdtKind::Enum && tcx.has_attr(did, sym::non_exhaustive) {
2300 debug!("found non-exhaustive variant list for {:?}", did);
2301 flags = flags | AdtFlags::IS_VARIANT_LIST_NON_EXHAUSTIVE;
2304 flags |= match kind {
2305 AdtKind::Enum => AdtFlags::IS_ENUM,
2306 AdtKind::Union => AdtFlags::IS_UNION,
2307 AdtKind::Struct => AdtFlags::IS_STRUCT,
2310 if kind == AdtKind::Struct && variants[VariantIdx::new(0)].ctor_def_id.is_some() {
2311 flags |= AdtFlags::HAS_CTOR;
2314 let attrs = tcx.get_attrs(did);
2315 if tcx.sess.contains_name(&attrs, sym::fundamental) {
2316 flags |= AdtFlags::IS_FUNDAMENTAL;
2318 if Some(did) == tcx.lang_items().phantom_data() {
2319 flags |= AdtFlags::IS_PHANTOM_DATA;
2321 if Some(did) == tcx.lang_items().owned_box() {
2322 flags |= AdtFlags::IS_BOX;
2324 if Some(did) == tcx.lang_items().manually_drop() {
2325 flags |= AdtFlags::IS_MANUALLY_DROP;
2328 AdtDef { did, variants, flags, repr }
2331 /// Returns `true` if this is a struct.
2333 pub fn is_struct(&self) -> bool {
2334 self.flags.contains(AdtFlags::IS_STRUCT)
2337 /// Returns `true` if this is a union.
2339 pub fn is_union(&self) -> bool {
2340 self.flags.contains(AdtFlags::IS_UNION)
2343 /// Returns `true` if this is a enum.
2345 pub fn is_enum(&self) -> bool {
2346 self.flags.contains(AdtFlags::IS_ENUM)
2349 /// Returns `true` if the variant list of this ADT is `#[non_exhaustive]`.
2351 pub fn is_variant_list_non_exhaustive(&self) -> bool {
2352 self.flags.contains(AdtFlags::IS_VARIANT_LIST_NON_EXHAUSTIVE)
2355 /// Returns the kind of the ADT.
2357 pub fn adt_kind(&self) -> AdtKind {
2360 } else if self.is_union() {
2367 /// Returns a description of this abstract data type.
2368 pub fn descr(&self) -> &'static str {
2369 match self.adt_kind() {
2370 AdtKind::Struct => "struct",
2371 AdtKind::Union => "union",
2372 AdtKind::Enum => "enum",
2376 /// Returns a description of a variant of this abstract data type.
2378 pub fn variant_descr(&self) -> &'static str {
2379 match self.adt_kind() {
2380 AdtKind::Struct => "struct",
2381 AdtKind::Union => "union",
2382 AdtKind::Enum => "variant",
2386 /// If this function returns `true`, it implies that `is_struct` must return `true`.
2388 pub fn has_ctor(&self) -> bool {
2389 self.flags.contains(AdtFlags::HAS_CTOR)
2392 /// Returns `true` if this type is `#[fundamental]` for the purposes
2393 /// of coherence checking.
2395 pub fn is_fundamental(&self) -> bool {
2396 self.flags.contains(AdtFlags::IS_FUNDAMENTAL)
2399 /// Returns `true` if this is `PhantomData<T>`.
2401 pub fn is_phantom_data(&self) -> bool {
2402 self.flags.contains(AdtFlags::IS_PHANTOM_DATA)
2405 /// Returns `true` if this is Box<T>.
2407 pub fn is_box(&self) -> bool {
2408 self.flags.contains(AdtFlags::IS_BOX)
2411 /// Returns `true` if this is `ManuallyDrop<T>`.
2413 pub fn is_manually_drop(&self) -> bool {
2414 self.flags.contains(AdtFlags::IS_MANUALLY_DROP)
2417 /// Returns `true` if this type has a destructor.
2418 pub fn has_dtor(&self, tcx: TyCtxt<'tcx>) -> bool {
2419 self.destructor(tcx).is_some()
2422 /// Asserts this is a struct or union and returns its unique variant.
2423 pub fn non_enum_variant(&self) -> &VariantDef {
2424 assert!(self.is_struct() || self.is_union());
2425 &self.variants[VariantIdx::new(0)]
2429 pub fn predicates(&self, tcx: TyCtxt<'tcx>) -> GenericPredicates<'tcx> {
2430 tcx.predicates_of(self.did)
2433 /// Returns an iterator over all fields contained
2436 pub fn all_fields(&self) -> impl Iterator<Item = &FieldDef> + Clone {
2437 self.variants.iter().flat_map(|v| v.fields.iter())
2440 /// Whether the ADT lacks fields. Note that this includes uninhabited enums,
2441 /// e.g., `enum Void {}` is considered payload free as well.
2442 pub fn is_payloadfree(&self) -> bool {
2443 self.variants.iter().all(|v| v.fields.is_empty())
2446 /// Return a `VariantDef` given a variant id.
2447 pub fn variant_with_id(&self, vid: DefId) -> &VariantDef {
2448 self.variants.iter().find(|v| v.def_id == vid).expect("variant_with_id: unknown variant")
2451 /// Return a `VariantDef` given a constructor id.
2452 pub fn variant_with_ctor_id(&self, cid: DefId) -> &VariantDef {
2455 .find(|v| v.ctor_def_id == Some(cid))
2456 .expect("variant_with_ctor_id: unknown variant")
2459 /// Return the index of `VariantDef` given a variant id.
2460 pub fn variant_index_with_id(&self, vid: DefId) -> VariantIdx {
2463 .find(|(_, v)| v.def_id == vid)
2464 .expect("variant_index_with_id: unknown variant")
2468 /// Return the index of `VariantDef` given a constructor id.
2469 pub fn variant_index_with_ctor_id(&self, cid: DefId) -> VariantIdx {
2472 .find(|(_, v)| v.ctor_def_id == Some(cid))
2473 .expect("variant_index_with_ctor_id: unknown variant")
2477 pub fn variant_of_res(&self, res: Res) -> &VariantDef {
2479 Res::Def(DefKind::Variant, vid) => self.variant_with_id(vid),
2480 Res::Def(DefKind::Ctor(..), cid) => self.variant_with_ctor_id(cid),
2481 Res::Def(DefKind::Struct, _)
2482 | Res::Def(DefKind::Union, _)
2483 | Res::Def(DefKind::TyAlias, _)
2484 | Res::Def(DefKind::AssocTy, _)
2486 | Res::SelfCtor(..) => self.non_enum_variant(),
2487 _ => bug!("unexpected res {:?} in variant_of_res", res),
2492 pub fn eval_explicit_discr(&self, tcx: TyCtxt<'tcx>, expr_did: DefId) -> Option<Discr<'tcx>> {
2493 assert!(self.is_enum());
2494 let param_env = tcx.param_env(expr_did);
2495 let repr_type = self.repr.discr_type();
2496 match tcx.const_eval_poly(expr_did) {
2498 let ty = repr_type.to_ty(tcx);
2499 if let Some(b) = val.try_to_bits_for_ty(tcx, param_env, ty) {
2500 trace!("discriminants: {} ({:?})", b, repr_type);
2501 Some(Discr { val: b, ty })
2503 info!("invalid enum discriminant: {:#?}", val);
2504 crate::mir::interpret::struct_error(
2505 tcx.at(tcx.def_span(expr_did)),
2506 "constant evaluation of enum discriminant resulted in non-integer",
2513 let msg = match err {
2514 ErrorHandled::Reported(ErrorReported) | ErrorHandled::Linted => {
2515 "enum discriminant evaluation failed"
2517 ErrorHandled::TooGeneric => "enum discriminant depends on generics",
2519 tcx.sess.delay_span_bug(tcx.def_span(expr_did), msg);
2526 pub fn discriminants(
2529 ) -> impl Iterator<Item = (VariantIdx, Discr<'tcx>)> + Captures<'tcx> {
2530 assert!(self.is_enum());
2531 let repr_type = self.repr.discr_type();
2532 let initial = repr_type.initial_discriminant(tcx);
2533 let mut prev_discr = None::<Discr<'tcx>>;
2534 self.variants.iter_enumerated().map(move |(i, v)| {
2535 let mut discr = prev_discr.map_or(initial, |d| d.wrap_incr(tcx));
2536 if let VariantDiscr::Explicit(expr_did) = v.discr {
2537 if let Some(new_discr) = self.eval_explicit_discr(tcx, expr_did) {
2541 prev_discr = Some(discr);
2548 pub fn variant_range(&self) -> Range<VariantIdx> {
2549 VariantIdx::new(0)..VariantIdx::new(self.variants.len())
2552 /// Computes the discriminant value used by a specific variant.
2553 /// Unlike `discriminants`, this is (amortized) constant-time,
2554 /// only doing at most one query for evaluating an explicit
2555 /// discriminant (the last one before the requested variant),
2556 /// assuming there are no constant-evaluation errors there.
2558 pub fn discriminant_for_variant(
2561 variant_index: VariantIdx,
2563 assert!(self.is_enum());
2564 let (val, offset) = self.discriminant_def_for_variant(variant_index);
2565 let explicit_value = val
2566 .and_then(|expr_did| self.eval_explicit_discr(tcx, expr_did))
2567 .unwrap_or_else(|| self.repr.discr_type().initial_discriminant(tcx));
2568 explicit_value.checked_add(tcx, offset as u128).0
2571 /// Yields a `DefId` for the discriminant and an offset to add to it
2572 /// Alternatively, if there is no explicit discriminant, returns the
2573 /// inferred discriminant directly.
2574 pub fn discriminant_def_for_variant(&self, variant_index: VariantIdx) -> (Option<DefId>, u32) {
2575 assert!(!self.variants.is_empty());
2576 let mut explicit_index = variant_index.as_u32();
2579 match self.variants[VariantIdx::from_u32(explicit_index)].discr {
2580 ty::VariantDiscr::Relative(0) => {
2584 ty::VariantDiscr::Relative(distance) => {
2585 explicit_index -= distance;
2587 ty::VariantDiscr::Explicit(did) => {
2588 expr_did = Some(did);
2593 (expr_did, variant_index.as_u32() - explicit_index)
2596 pub fn destructor(&self, tcx: TyCtxt<'tcx>) -> Option<Destructor> {
2597 tcx.adt_destructor(self.did)
2600 /// Returns a list of types such that `Self: Sized` if and only
2601 /// if that type is `Sized`, or `TyErr` if this type is recursive.
2603 /// Oddly enough, checking that the sized-constraint is `Sized` is
2604 /// actually more expressive than checking all members:
2605 /// the `Sized` trait is inductive, so an associated type that references
2606 /// `Self` would prevent its containing ADT from being `Sized`.
2608 /// Due to normalization being eager, this applies even if
2609 /// the associated type is behind a pointer (e.g., issue #31299).
2610 pub fn sized_constraint(&self, tcx: TyCtxt<'tcx>) -> &'tcx [Ty<'tcx>] {
2611 tcx.adt_sized_constraint(self.did).0
2615 impl<'tcx> FieldDef {
2616 /// Returns the type of this field. The `subst` is typically obtained
2617 /// via the second field of `TyKind::AdtDef`.
2618 pub fn ty(&self, tcx: TyCtxt<'tcx>, subst: SubstsRef<'tcx>) -> Ty<'tcx> {
2619 tcx.type_of(self.did).subst(tcx, subst)
2623 /// Represents the various closure traits in the language. This
2624 /// will determine the type of the environment (`self`, in the
2625 /// desugaring) argument that the closure expects.
2627 /// You can get the environment type of a closure using
2628 /// `tcx.closure_env_ty()`.
2629 #[derive(Clone, Copy, PartialOrd, Ord, PartialEq, Eq, Hash, Debug, TyEncodable, TyDecodable)]
2630 #[derive(HashStable)]
2631 pub enum ClosureKind {
2632 // Warning: Ordering is significant here! The ordering is chosen
2633 // because the trait Fn is a subtrait of FnMut and so in turn, and
2634 // hence we order it so that Fn < FnMut < FnOnce.
2640 impl<'tcx> ClosureKind {
2641 // This is the initial value used when doing upvar inference.
2642 pub const LATTICE_BOTTOM: ClosureKind = ClosureKind::Fn;
2644 pub fn trait_did(&self, tcx: TyCtxt<'tcx>) -> DefId {
2646 ClosureKind::Fn => tcx.require_lang_item(LangItem::Fn, None),
2647 ClosureKind::FnMut => tcx.require_lang_item(LangItem::FnMut, None),
2648 ClosureKind::FnOnce => tcx.require_lang_item(LangItem::FnOnce, None),
2652 /// Returns `true` if a type that impls this closure kind
2653 /// must also implement `other`.
2654 pub fn extends(self, other: ty::ClosureKind) -> bool {
2657 (ClosureKind::Fn, ClosureKind::Fn)
2658 | (ClosureKind::Fn, ClosureKind::FnMut)
2659 | (ClosureKind::Fn, ClosureKind::FnOnce)
2660 | (ClosureKind::FnMut, ClosureKind::FnMut)
2661 | (ClosureKind::FnMut, ClosureKind::FnOnce)
2662 | (ClosureKind::FnOnce, ClosureKind::FnOnce)
2666 /// Returns the representative scalar type for this closure kind.
2667 /// See `TyS::to_opt_closure_kind` for more details.
2668 pub fn to_ty(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
2670 ty::ClosureKind::Fn => tcx.types.i8,
2671 ty::ClosureKind::FnMut => tcx.types.i16,
2672 ty::ClosureKind::FnOnce => tcx.types.i32,
2678 pub fn from_mutbl(m: hir::Mutability) -> BorrowKind {
2680 hir::Mutability::Mut => MutBorrow,
2681 hir::Mutability::Not => ImmBorrow,
2685 /// Returns a mutability `m` such that an `&m T` pointer could be used to obtain this borrow
2686 /// kind. Because borrow kinds are richer than mutabilities, we sometimes have to pick a
2687 /// mutability that is stronger than necessary so that it at least *would permit* the borrow in
2689 pub fn to_mutbl_lossy(self) -> hir::Mutability {
2691 MutBorrow => hir::Mutability::Mut,
2692 ImmBorrow => hir::Mutability::Not,
2694 // We have no type corresponding to a unique imm borrow, so
2695 // use `&mut`. It gives all the capabilities of an `&uniq`
2696 // and hence is a safe "over approximation".
2697 UniqueImmBorrow => hir::Mutability::Mut,
2701 pub fn to_user_str(&self) -> &'static str {
2703 MutBorrow => "mutable",
2704 ImmBorrow => "immutable",
2705 UniqueImmBorrow => "uniquely immutable",
2710 pub type Attributes<'tcx> = &'tcx [ast::Attribute];
2712 #[derive(Debug, PartialEq, Eq)]
2713 pub enum ImplOverlapKind {
2714 /// These impls are always allowed to overlap.
2716 /// Whether or not the impl is permitted due to the trait being a `#[marker]` trait
2719 /// These impls are allowed to overlap, but that raises
2720 /// an issue #33140 future-compatibility warning.
2722 /// Some background: in Rust 1.0, the trait-object types `Send + Sync` (today's
2723 /// `dyn Send + Sync`) and `Sync + Send` (now `dyn Sync + Send`) were different.
2725 /// The widely-used version 0.1.0 of the crate `traitobject` had accidentally relied
2726 /// that difference, making what reduces to the following set of impls:
2730 /// impl Trait for dyn Send + Sync {}
2731 /// impl Trait for dyn Sync + Send {}
2734 /// Obviously, once we made these types be identical, that code causes a coherence
2735 /// error and a fairly big headache for us. However, luckily for us, the trait
2736 /// `Trait` used in this case is basically a marker trait, and therefore having
2737 /// overlapping impls for it is sound.
2739 /// To handle this, we basically regard the trait as a marker trait, with an additional
2740 /// future-compatibility warning. To avoid accidentally "stabilizing" this feature,
2741 /// it has the following restrictions:
2743 /// 1. The trait must indeed be a marker-like trait (i.e., no items), and must be
2745 /// 2. The trait-ref of both impls must be equal.
2746 /// 3. The trait-ref of both impls must be a trait object type consisting only of
2748 /// 4. Neither of the impls can have any where-clauses.
2750 /// Once `traitobject` 0.1.0 is no longer an active concern, this hack can be removed.
2754 impl<'tcx> TyCtxt<'tcx> {
2755 pub fn typeck_body(self, body: hir::BodyId) -> &'tcx TypeckResults<'tcx> {
2756 self.typeck(self.hir().body_owner_def_id(body))
2759 /// Returns an iterator of the `DefId`s for all body-owners in this
2760 /// crate. If you would prefer to iterate over the bodies
2761 /// themselves, you can do `self.hir().krate().body_ids.iter()`.
2762 pub fn body_owners(self) -> impl Iterator<Item = LocalDefId> + Captures<'tcx> + 'tcx {
2767 .map(move |&body_id| self.hir().body_owner_def_id(body_id))
2770 pub fn par_body_owners<F: Fn(LocalDefId) + sync::Sync + sync::Send>(self, f: F) {
2771 par_iter(&self.hir().krate().body_ids)
2772 .for_each(|&body_id| f(self.hir().body_owner_def_id(body_id)));
2775 pub fn provided_trait_methods(self, id: DefId) -> impl 'tcx + Iterator<Item = &'tcx AssocItem> {
2776 self.associated_items(id)
2777 .in_definition_order()
2778 .filter(|item| item.kind == AssocKind::Fn && item.defaultness.has_value())
2781 fn item_name_from_hir(self, def_id: DefId) -> Option<Ident> {
2782 self.hir().get_if_local(def_id).and_then(|node| node.ident())
2785 fn item_name_from_def_id(self, def_id: DefId) -> Option<Symbol> {
2786 if def_id.index == CRATE_DEF_INDEX {
2787 Some(self.original_crate_name(def_id.krate))
2789 let def_key = self.def_key(def_id);
2790 match def_key.disambiguated_data.data {
2791 // The name of a constructor is that of its parent.
2792 rustc_hir::definitions::DefPathData::Ctor => self.item_name_from_def_id(DefId {
2793 krate: def_id.krate,
2794 index: def_key.parent.unwrap(),
2796 _ => def_key.disambiguated_data.data.get_opt_name(),
2801 /// Look up the name of an item across crates. This does not look at HIR.
2803 /// When possible, this function should be used for cross-crate lookups over
2804 /// [`opt_item_name`] to avoid invalidating the incremental cache. If you
2805 /// need to handle items without a name, or HIR items that will not be
2806 /// serialized cross-crate, or if you need the span of the item, use
2807 /// [`opt_item_name`] instead.
2809 /// [`opt_item_name`]: Self::opt_item_name
2810 pub fn item_name(self, id: DefId) -> Symbol {
2811 // Look at cross-crate items first to avoid invalidating the incremental cache
2812 // unless we have to.
2813 self.item_name_from_def_id(id).unwrap_or_else(|| {
2814 bug!("item_name: no name for {:?}", self.def_path(id));
2818 /// Look up the name and span of an item or [`Node`].
2820 /// See [`item_name`][Self::item_name] for more information.
2821 pub fn opt_item_name(self, def_id: DefId) -> Option<Ident> {
2822 // Look at the HIR first so the span will be correct if this is a local item.
2823 self.item_name_from_hir(def_id)
2824 .or_else(|| self.item_name_from_def_id(def_id).map(Ident::with_dummy_span))
2827 pub fn opt_associated_item(self, def_id: DefId) -> Option<&'tcx AssocItem> {
2828 if let DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy = self.def_kind(def_id) {
2829 Some(self.associated_item(def_id))
2835 pub fn field_index(self, hir_id: hir::HirId, typeck_results: &TypeckResults<'_>) -> usize {
2836 typeck_results.field_indices().get(hir_id).cloned().expect("no index for a field")
2839 pub fn find_field_index(self, ident: Ident, variant: &VariantDef) -> Option<usize> {
2840 variant.fields.iter().position(|field| self.hygienic_eq(ident, field.ident, variant.def_id))
2843 /// Returns `true` if the impls are the same polarity and the trait either
2844 /// has no items or is annotated `#[marker]` and prevents item overrides.
2845 pub fn impls_are_allowed_to_overlap(
2849 ) -> Option<ImplOverlapKind> {
2850 // If either trait impl references an error, they're allowed to overlap,
2851 // as one of them essentially doesn't exist.
2852 if self.impl_trait_ref(def_id1).map_or(false, |tr| tr.references_error())
2853 || self.impl_trait_ref(def_id2).map_or(false, |tr| tr.references_error())
2855 return Some(ImplOverlapKind::Permitted { marker: false });
2858 match (self.impl_polarity(def_id1), self.impl_polarity(def_id2)) {
2859 (ImplPolarity::Reservation, _) | (_, ImplPolarity::Reservation) => {
2860 // `#[rustc_reservation_impl]` impls don't overlap with anything
2862 "impls_are_allowed_to_overlap({:?}, {:?}) = Some(Permitted) (reservations)",
2865 return Some(ImplOverlapKind::Permitted { marker: false });
2867 (ImplPolarity::Positive, ImplPolarity::Negative)
2868 | (ImplPolarity::Negative, ImplPolarity::Positive) => {
2869 // `impl AutoTrait for Type` + `impl !AutoTrait for Type`
2871 "impls_are_allowed_to_overlap({:?}, {:?}) - None (differing polarities)",
2876 (ImplPolarity::Positive, ImplPolarity::Positive)
2877 | (ImplPolarity::Negative, ImplPolarity::Negative) => {}
2880 let is_marker_overlap = {
2881 let is_marker_impl = |def_id: DefId| -> bool {
2882 let trait_ref = self.impl_trait_ref(def_id);
2883 trait_ref.map_or(false, |tr| self.trait_def(tr.def_id).is_marker)
2885 is_marker_impl(def_id1) && is_marker_impl(def_id2)
2888 if is_marker_overlap {
2890 "impls_are_allowed_to_overlap({:?}, {:?}) = Some(Permitted) (marker overlap)",
2893 Some(ImplOverlapKind::Permitted { marker: true })
2895 if let Some(self_ty1) = self.issue33140_self_ty(def_id1) {
2896 if let Some(self_ty2) = self.issue33140_self_ty(def_id2) {
2897 if self_ty1 == self_ty2 {
2899 "impls_are_allowed_to_overlap({:?}, {:?}) - issue #33140 HACK",
2902 return Some(ImplOverlapKind::Issue33140);
2905 "impls_are_allowed_to_overlap({:?}, {:?}) - found {:?} != {:?}",
2906 def_id1, def_id2, self_ty1, self_ty2
2912 debug!("impls_are_allowed_to_overlap({:?}, {:?}) = None", def_id1, def_id2);
2917 /// Returns `ty::VariantDef` if `res` refers to a struct,
2918 /// or variant or their constructors, panics otherwise.
2919 pub fn expect_variant_res(self, res: Res) -> &'tcx VariantDef {
2921 Res::Def(DefKind::Variant, did) => {
2922 let enum_did = self.parent(did).unwrap();
2923 self.adt_def(enum_did).variant_with_id(did)
2925 Res::Def(DefKind::Struct | DefKind::Union, did) => self.adt_def(did).non_enum_variant(),
2926 Res::Def(DefKind::Ctor(CtorOf::Variant, ..), variant_ctor_did) => {
2927 let variant_did = self.parent(variant_ctor_did).unwrap();
2928 let enum_did = self.parent(variant_did).unwrap();
2929 self.adt_def(enum_did).variant_with_ctor_id(variant_ctor_did)
2931 Res::Def(DefKind::Ctor(CtorOf::Struct, ..), ctor_did) => {
2932 let struct_did = self.parent(ctor_did).expect("struct ctor has no parent");
2933 self.adt_def(struct_did).non_enum_variant()
2935 _ => bug!("expect_variant_res used with unexpected res {:?}", res),
2939 /// Returns the possibly-auto-generated MIR of a `(DefId, Subst)` pair.
2940 pub fn instance_mir(self, instance: ty::InstanceDef<'tcx>) -> &'tcx Body<'tcx> {
2942 ty::InstanceDef::Item(def) => match self.def_kind(def.did) {
2945 | DefKind::AssocConst
2947 | DefKind::AnonConst => self.mir_for_ctfe_opt_const_arg(def),
2948 // If the caller wants `mir_for_ctfe` of a function they should not be using
2949 // `instance_mir`, so we'll assume const fn also wants the optimized version.
2951 assert_eq!(def.const_param_did, None);
2952 self.optimized_mir(def.did)
2955 ty::InstanceDef::VtableShim(..)
2956 | ty::InstanceDef::ReifyShim(..)
2957 | ty::InstanceDef::Intrinsic(..)
2958 | ty::InstanceDef::FnPtrShim(..)
2959 | ty::InstanceDef::Virtual(..)
2960 | ty::InstanceDef::ClosureOnceShim { .. }
2961 | ty::InstanceDef::DropGlue(..)
2962 | ty::InstanceDef::CloneShim(..) => self.mir_shims(instance),
2966 /// Gets the attributes of a definition.
2967 pub fn get_attrs(self, did: DefId) -> Attributes<'tcx> {
2968 if let Some(did) = did.as_local() {
2969 self.hir().attrs(self.hir().local_def_id_to_hir_id(did))
2971 self.item_attrs(did)
2975 /// Determines whether an item is annotated with an attribute.
2976 pub fn has_attr(self, did: DefId, attr: Symbol) -> bool {
2977 self.sess.contains_name(&self.get_attrs(did), attr)
2980 /// Returns `true` if this is an `auto trait`.
2981 pub fn trait_is_auto(self, trait_def_id: DefId) -> bool {
2982 self.trait_def(trait_def_id).has_auto_impl
2985 /// Returns layout of a generator. Layout might be unavailable if the
2986 /// generator is tainted by errors.
2987 pub fn generator_layout(self, def_id: DefId) -> Option<&'tcx GeneratorLayout<'tcx>> {
2988 self.optimized_mir(def_id).generator_layout()
2991 /// Given the `DefId` of an impl, returns the `DefId` of the trait it implements.
2992 /// If it implements no trait, returns `None`.
2993 pub fn trait_id_of_impl(self, def_id: DefId) -> Option<DefId> {
2994 self.impl_trait_ref(def_id).map(|tr| tr.def_id)
2997 /// If the given defid describes a method belonging to an impl, returns the
2998 /// `DefId` of the impl that the method belongs to; otherwise, returns `None`.
2999 pub fn impl_of_method(self, def_id: DefId) -> Option<DefId> {
3000 self.opt_associated_item(def_id).and_then(|trait_item| match trait_item.container {
3001 TraitContainer(_) => None,
3002 ImplContainer(def_id) => Some(def_id),
3006 /// Looks up the span of `impl_did` if the impl is local; otherwise returns `Err`
3007 /// with the name of the crate containing the impl.
3008 pub fn span_of_impl(self, impl_did: DefId) -> Result<Span, Symbol> {
3009 if let Some(impl_did) = impl_did.as_local() {
3010 let hir_id = self.hir().local_def_id_to_hir_id(impl_did);
3011 Ok(self.hir().span(hir_id))
3013 Err(self.crate_name(impl_did.krate))
3017 /// Hygienically compares a use-site name (`use_name`) for a field or an associated item with
3018 /// its supposed definition name (`def_name`). The method also needs `DefId` of the supposed
3019 /// definition's parent/scope to perform comparison.
3020 pub fn hygienic_eq(self, use_name: Ident, def_name: Ident, def_parent_def_id: DefId) -> bool {
3021 // We could use `Ident::eq` here, but we deliberately don't. The name
3022 // comparison fails frequently, and we want to avoid the expensive
3023 // `normalize_to_macros_2_0()` calls required for the span comparison whenever possible.
3024 use_name.name == def_name.name
3028 .hygienic_eq(def_name.span.ctxt(), self.expansion_that_defined(def_parent_def_id))
3031 pub fn expansion_that_defined(self, scope: DefId) -> ExpnId {
3032 match scope.as_local() {
3033 // Parsing and expansion aren't incremental, so we don't
3034 // need to go through a query for the same-crate case.
3035 Some(scope) => self.hir().definitions().expansion_that_defined(scope),
3036 None => self.expn_that_defined(scope),
3040 pub fn adjust_ident(self, mut ident: Ident, scope: DefId) -> Ident {
3041 ident.span.normalize_to_macros_2_0_and_adjust(self.expansion_that_defined(scope));
3045 pub fn adjust_ident_and_get_scope(
3050 ) -> (Ident, DefId) {
3052 match ident.span.normalize_to_macros_2_0_and_adjust(self.expansion_that_defined(scope))
3054 Some(actual_expansion) => {
3055 self.hir().definitions().parent_module_of_macro_def(actual_expansion)
3057 None => self.parent_module(block).to_def_id(),
3062 pub fn is_object_safe(self, key: DefId) -> bool {
3063 self.object_safety_violations(key).is_empty()
3067 #[derive(Clone, HashStable, Debug)]
3068 pub struct AdtSizedConstraint<'tcx>(pub &'tcx [Ty<'tcx>]);
3070 /// Yields the parent function's `DefId` if `def_id` is an `impl Trait` definition.
3071 pub fn is_impl_trait_defn(tcx: TyCtxt<'_>, def_id: DefId) -> Option<DefId> {
3072 if let Some(def_id) = def_id.as_local() {
3073 if let Node::Item(item) = tcx.hir().get(tcx.hir().local_def_id_to_hir_id(def_id)) {
3074 if let hir::ItemKind::OpaqueTy(ref opaque_ty) = item.kind {
3075 return opaque_ty.impl_trait_fn;
3082 pub fn int_ty(ity: ast::IntTy) -> IntTy {
3084 ast::IntTy::Isize => IntTy::Isize,
3085 ast::IntTy::I8 => IntTy::I8,
3086 ast::IntTy::I16 => IntTy::I16,
3087 ast::IntTy::I32 => IntTy::I32,
3088 ast::IntTy::I64 => IntTy::I64,
3089 ast::IntTy::I128 => IntTy::I128,
3093 pub fn uint_ty(uty: ast::UintTy) -> UintTy {
3095 ast::UintTy::Usize => UintTy::Usize,
3096 ast::UintTy::U8 => UintTy::U8,
3097 ast::UintTy::U16 => UintTy::U16,
3098 ast::UintTy::U32 => UintTy::U32,
3099 ast::UintTy::U64 => UintTy::U64,
3100 ast::UintTy::U128 => UintTy::U128,
3104 pub fn float_ty(fty: ast::FloatTy) -> FloatTy {
3106 ast::FloatTy::F32 => FloatTy::F32,
3107 ast::FloatTy::F64 => FloatTy::F64,
3111 pub fn ast_int_ty(ity: IntTy) -> ast::IntTy {
3113 IntTy::Isize => ast::IntTy::Isize,
3114 IntTy::I8 => ast::IntTy::I8,
3115 IntTy::I16 => ast::IntTy::I16,
3116 IntTy::I32 => ast::IntTy::I32,
3117 IntTy::I64 => ast::IntTy::I64,
3118 IntTy::I128 => ast::IntTy::I128,
3122 pub fn ast_uint_ty(uty: UintTy) -> ast::UintTy {
3124 UintTy::Usize => ast::UintTy::Usize,
3125 UintTy::U8 => ast::UintTy::U8,
3126 UintTy::U16 => ast::UintTy::U16,
3127 UintTy::U32 => ast::UintTy::U32,
3128 UintTy::U64 => ast::UintTy::U64,
3129 UintTy::U128 => ast::UintTy::U128,
3133 pub fn provide(providers: &mut ty::query::Providers) {
3134 context::provide(providers);
3135 erase_regions::provide(providers);
3136 layout::provide(providers);
3137 util::provide(providers);
3138 print::provide(providers);
3139 super::util::bug::provide(providers);
3140 *providers = ty::query::Providers {
3141 trait_impls_of: trait_def::trait_impls_of_provider,
3142 all_local_trait_impls: trait_def::all_local_trait_impls,
3143 type_uninhabited_from: inhabitedness::type_uninhabited_from,
3148 /// A map for the local crate mapping each type to a vector of its
3149 /// inherent impls. This is not meant to be used outside of coherence;
3150 /// rather, you should request the vector for a specific type via
3151 /// `tcx.inherent_impls(def_id)` so as to minimize your dependencies
3152 /// (constructing this map requires touching the entire crate).
3153 #[derive(Clone, Debug, Default, HashStable)]
3154 pub struct CrateInherentImpls {
3155 pub inherent_impls: DefIdMap<Vec<DefId>>,
3158 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, HashStable)]
3159 pub struct SymbolName<'tcx> {
3160 /// `&str` gives a consistent ordering, which ensures reproducible builds.
3161 pub name: &'tcx str,
3164 impl<'tcx> SymbolName<'tcx> {
3165 pub fn new(tcx: TyCtxt<'tcx>, name: &str) -> SymbolName<'tcx> {
3167 name: unsafe { str::from_utf8_unchecked(tcx.arena.alloc_slice(name.as_bytes())) },
3172 impl<'tcx> fmt::Display for SymbolName<'tcx> {
3173 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
3174 fmt::Display::fmt(&self.name, fmt)
3178 impl<'tcx> fmt::Debug for SymbolName<'tcx> {
3179 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
3180 fmt::Display::fmt(&self.name, fmt)