1 //! Type context book-keeping.
3 use crate::arena::Arena;
4 use crate::dep_graph::{DepGraph, DepKind, DepKindStruct};
5 use crate::hir::place::Place as HirPlace;
6 use crate::infer::canonical::{Canonical, CanonicalVarInfo, CanonicalVarInfos};
7 use crate::lint::{struct_lint_level, LintLevelSource};
8 use crate::middle::codegen_fn_attrs::CodegenFnAttrs;
9 use crate::middle::resolve_lifetime;
10 use crate::middle::stability;
11 use crate::mir::interpret::{self, Allocation, ConstAllocation};
13 Body, BorrowCheckResult, Field, Local, Place, PlaceElem, ProjectionKind, Promoted,
15 use crate::thir::Thir;
17 use crate::ty::query::{self, TyCtxtAt};
18 use crate::ty::subst::{GenericArg, GenericArgKind, InternalSubsts, Subst, SubstsRef, UserSubsts};
20 self, AdtDef, AdtDefData, AdtKind, Binder, BindingMode, BoundVar, CanonicalPolyFnSig,
21 ClosureSizeProfileData, Const, ConstS, ConstVid, DefIdTree, ExistentialPredicate, FloatTy,
22 FloatVar, FloatVid, GenericParamDefKind, InferConst, InferTy, IntTy, IntVar, IntVid, List,
23 ParamConst, ParamTy, PolyFnSig, Predicate, PredicateKind, PredicateS, ProjectionTy, Region,
24 RegionKind, ReprOptions, TraitObjectVisitor, Ty, TyKind, TyS, TyVar, TyVid, TypeAndMut, UintTy,
27 use rustc_data_structures::fingerprint::Fingerprint;
28 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
29 use rustc_data_structures::intern::{Interned, WithStableHash};
30 use rustc_data_structures::memmap::Mmap;
31 use rustc_data_structures::profiling::SelfProfilerRef;
32 use rustc_data_structures::sharded::{IntoPointer, ShardedHashMap};
33 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
34 use rustc_data_structures::steal::Steal;
35 use rustc_data_structures::sync::{self, Lock, Lrc, ReadGuard, RwLock, WorkerLocal};
36 use rustc_data_structures::vec_map::VecMap;
37 use rustc_errors::{DecorateLint, ErrorGuaranteed, LintDiagnosticBuilder, MultiSpan};
39 use rustc_hir::def::{DefKind, Res};
40 use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, LocalDefId, LOCAL_CRATE};
41 use rustc_hir::definitions::Definitions;
42 use rustc_hir::intravisit::Visitor;
43 use rustc_hir::lang_items::LangItem;
45 Constness, ExprKind, HirId, ImplItemKind, ItemKind, ItemLocalId, ItemLocalMap, ItemLocalSet,
46 Node, TraitCandidate, TraitItemKind,
48 use rustc_index::vec::{Idx, IndexVec};
49 use rustc_macros::HashStable;
50 use rustc_middle::mir::FakeReadCause;
51 use rustc_query_system::ich::StableHashingContext;
52 use rustc_serialize::opaque::{FileEncodeResult, FileEncoder};
53 use rustc_session::config::{CrateType, OutputFilenames};
54 use rustc_session::cstore::CrateStoreDyn;
55 use rustc_session::lint::{Level, Lint};
56 use rustc_session::Limit;
57 use rustc_session::Session;
58 use rustc_span::def_id::{DefPathHash, StableCrateId};
59 use rustc_span::source_map::SourceMap;
60 use rustc_span::symbol::{kw, sym, Ident, Symbol};
61 use rustc_span::{Span, DUMMY_SP};
62 use rustc_target::abi::{Layout, LayoutS, TargetDataLayout, VariantIdx};
63 use rustc_target::spec::abi;
64 use rustc_type_ir::sty::TyKind::*;
65 use rustc_type_ir::{InternAs, InternIteratorElement, Interner, TypeFlags};
68 use std::borrow::Borrow;
69 use std::cmp::Ordering;
70 use std::collections::hash_map::{self, Entry};
72 use std::hash::{Hash, Hasher};
75 use std::ops::{Bound, Deref};
78 use super::{ImplPolarity, RvalueScopes};
80 pub trait OnDiskCache<'tcx>: rustc_data_structures::sync::Sync {
81 /// Creates a new `OnDiskCache` instance from the serialized data in `data`.
82 fn new(sess: &'tcx Session, data: Mmap, start_pos: usize) -> Self
86 fn new_empty(source_map: &'tcx SourceMap) -> Self
90 fn drop_serialized_data(&self, tcx: TyCtxt<'tcx>);
92 fn serialize(&self, tcx: TyCtxt<'tcx>, encoder: FileEncoder) -> FileEncodeResult;
95 #[allow(rustc::usage_of_ty_tykind)]
96 impl<'tcx> Interner for TyCtxt<'tcx> {
97 type AdtDef = ty::AdtDef<'tcx>;
98 type SubstsRef = ty::SubstsRef<'tcx>;
101 type Const = ty::Const<'tcx>;
102 type Region = Region<'tcx>;
103 type TypeAndMut = TypeAndMut<'tcx>;
104 type Mutability = hir::Mutability;
105 type Movability = hir::Movability;
106 type PolyFnSig = PolyFnSig<'tcx>;
107 type ListBinderExistentialPredicate = &'tcx List<Binder<'tcx, ExistentialPredicate<'tcx>>>;
108 type BinderListTy = Binder<'tcx, &'tcx List<Ty<'tcx>>>;
109 type ListTy = &'tcx List<Ty<'tcx>>;
110 type ProjectionTy = ty::ProjectionTy<'tcx>;
111 type ParamTy = ParamTy;
112 type BoundTy = ty::BoundTy;
113 type PlaceholderType = ty::PlaceholderType;
114 type InferTy = InferTy;
115 type DelaySpanBugEmitted = DelaySpanBugEmitted;
116 type PredicateKind = ty::PredicateKind<'tcx>;
117 type AllocId = crate::mir::interpret::AllocId;
119 type EarlyBoundRegion = ty::EarlyBoundRegion;
120 type BoundRegion = ty::BoundRegion;
121 type FreeRegion = ty::FreeRegion;
122 type RegionVid = ty::RegionVid;
123 type PlaceholderRegion = ty::PlaceholderRegion;
126 /// A type that is not publicly constructable. This prevents people from making [`TyKind::Error`]s
127 /// except through the error-reporting functions on a [`tcx`][TyCtxt].
128 #[derive(Copy, Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
129 #[derive(TyEncodable, TyDecodable, HashStable)]
130 pub struct DelaySpanBugEmitted {
131 pub reported: ErrorGuaranteed,
135 type InternedSet<'tcx, T> = ShardedHashMap<InternedInSet<'tcx, T>, ()>;
137 pub struct CtxtInterners<'tcx> {
138 /// The arena that types, regions, etc. are allocated from.
139 arena: &'tcx WorkerLocal<Arena<'tcx>>,
141 // Specifically use a speedy hash algorithm for these hash sets, since
142 // they're accessed quite often.
143 type_: InternedSet<'tcx, WithStableHash<TyS<'tcx>>>,
144 substs: InternedSet<'tcx, InternalSubsts<'tcx>>,
145 canonical_var_infos: InternedSet<'tcx, List<CanonicalVarInfo<'tcx>>>,
146 region: InternedSet<'tcx, RegionKind<'tcx>>,
147 poly_existential_predicates:
148 InternedSet<'tcx, List<ty::Binder<'tcx, ExistentialPredicate<'tcx>>>>,
149 predicate: InternedSet<'tcx, PredicateS<'tcx>>,
150 predicates: InternedSet<'tcx, List<Predicate<'tcx>>>,
151 projs: InternedSet<'tcx, List<ProjectionKind>>,
152 place_elems: InternedSet<'tcx, List<PlaceElem<'tcx>>>,
153 const_: InternedSet<'tcx, ConstS<'tcx>>,
154 const_allocation: InternedSet<'tcx, Allocation>,
155 bound_variable_kinds: InternedSet<'tcx, List<ty::BoundVariableKind>>,
156 layout: InternedSet<'tcx, LayoutS<'tcx>>,
157 adt_def: InternedSet<'tcx, AdtDefData>,
160 impl<'tcx> CtxtInterners<'tcx> {
161 fn new(arena: &'tcx WorkerLocal<Arena<'tcx>>) -> CtxtInterners<'tcx> {
164 type_: Default::default(),
165 substs: Default::default(),
166 region: Default::default(),
167 poly_existential_predicates: Default::default(),
168 canonical_var_infos: Default::default(),
169 predicate: Default::default(),
170 predicates: Default::default(),
171 projs: Default::default(),
172 place_elems: Default::default(),
173 const_: Default::default(),
174 const_allocation: Default::default(),
175 bound_variable_kinds: Default::default(),
176 layout: Default::default(),
177 adt_def: Default::default(),
182 #[allow(rustc::usage_of_ty_tykind)]
188 definitions: &rustc_hir::definitions::Definitions,
189 cstore: &CrateStoreDyn,
190 source_span: &IndexVec<LocalDefId, Span>,
192 Ty(Interned::new_unchecked(
194 .intern(kind, |kind| {
195 let flags = super::flags::FlagComputation::for_kind(&kind);
197 // It's impossible to hash inference regions (and will ICE), so we don't need to try to cache them.
198 // Without incremental, we rarely stable-hash types, so let's not do it proactively.
199 let stable_hash = if flags.flags.intersects(TypeFlags::HAS_RE_INFER)
200 || sess.opts.incremental.is_none()
204 let mut hasher = StableHasher::new();
205 let mut hcx = StableHashingContext::ignore_spans(
211 kind.hash_stable(&mut hcx, &mut hasher);
215 let ty_struct = TyS {
218 outer_exclusive_binder: flags.outer_exclusive_binder,
222 self.arena.alloc(WithStableHash { internee: ty_struct, stable_hash }),
230 fn intern_predicate(&self, kind: Binder<'tcx, PredicateKind<'tcx>>) -> Predicate<'tcx> {
231 Predicate(Interned::new_unchecked(
233 .intern(kind, |kind| {
234 let flags = super::flags::FlagComputation::for_predicate(kind);
236 let predicate_struct = PredicateS {
239 outer_exclusive_binder: flags.outer_exclusive_binder,
242 InternedInSet(self.arena.alloc(predicate_struct))
249 pub struct CommonTypes<'tcx> {
269 pub self_param: Ty<'tcx>,
271 /// Dummy type used for the `Self` of a `TraitRef` created for converting
272 /// a trait object, and which gets removed in `ExistentialTraitRef`.
273 /// This type must not appear anywhere in other converted types.
274 pub trait_object_dummy_self: Ty<'tcx>,
277 pub struct CommonLifetimes<'tcx> {
278 /// `ReEmpty` in the root universe.
279 pub re_root_empty: Region<'tcx>,
282 pub re_static: Region<'tcx>,
284 /// Erased region, used outside of type inference.
285 pub re_erased: Region<'tcx>,
288 pub struct CommonConsts<'tcx> {
289 pub unit: Const<'tcx>,
292 pub struct LocalTableInContext<'a, V> {
293 hir_owner: LocalDefId,
294 data: &'a ItemLocalMap<V>,
297 /// Validate that the given HirId (respectively its `local_id` part) can be
298 /// safely used as a key in the maps of a TypeckResults. For that to be
299 /// the case, the HirId must have the same `owner` as all the other IDs in
300 /// this table (signified by `hir_owner`). Otherwise the HirId
301 /// would be in a different frame of reference and using its `local_id`
302 /// would result in lookup errors, or worse, in silently wrong data being
305 fn validate_hir_id_for_typeck_results(hir_owner: LocalDefId, hir_id: hir::HirId) {
306 if hir_id.owner != hir_owner {
307 invalid_hir_id_for_typeck_results(hir_owner, hir_id);
313 fn invalid_hir_id_for_typeck_results(hir_owner: LocalDefId, hir_id: hir::HirId) {
314 ty::tls::with(|tcx| {
316 "node {} with HirId::owner {:?} cannot be placed in TypeckResults with hir_owner {:?}",
317 tcx.hir().node_to_string(hir_id),
324 impl<'a, V> LocalTableInContext<'a, V> {
325 pub fn contains_key(&self, id: hir::HirId) -> bool {
326 validate_hir_id_for_typeck_results(self.hir_owner, id);
327 self.data.contains_key(&id.local_id)
330 pub fn get(&self, id: hir::HirId) -> Option<&V> {
331 validate_hir_id_for_typeck_results(self.hir_owner, id);
332 self.data.get(&id.local_id)
335 pub fn iter(&self) -> hash_map::Iter<'_, hir::ItemLocalId, V> {
340 impl<'a, V> ::std::ops::Index<hir::HirId> for LocalTableInContext<'a, V> {
343 fn index(&self, key: hir::HirId) -> &V {
344 self.get(key).expect("LocalTableInContext: key not found")
348 pub struct LocalTableInContextMut<'a, V> {
349 hir_owner: LocalDefId,
350 data: &'a mut ItemLocalMap<V>,
353 impl<'a, V> LocalTableInContextMut<'a, V> {
354 pub fn get_mut(&mut self, id: hir::HirId) -> Option<&mut V> {
355 validate_hir_id_for_typeck_results(self.hir_owner, id);
356 self.data.get_mut(&id.local_id)
359 pub fn entry(&mut self, id: hir::HirId) -> Entry<'_, hir::ItemLocalId, V> {
360 validate_hir_id_for_typeck_results(self.hir_owner, id);
361 self.data.entry(id.local_id)
364 pub fn insert(&mut self, id: hir::HirId, val: V) -> Option<V> {
365 validate_hir_id_for_typeck_results(self.hir_owner, id);
366 self.data.insert(id.local_id, val)
369 pub fn remove(&mut self, id: hir::HirId) -> Option<V> {
370 validate_hir_id_for_typeck_results(self.hir_owner, id);
371 self.data.remove(&id.local_id)
375 /// Whenever a value may be live across a generator yield, the type of that value winds up in the
376 /// `GeneratorInteriorTypeCause` struct. This struct adds additional information about such
377 /// captured types that can be useful for diagnostics. In particular, it stores the span that
378 /// caused a given type to be recorded, along with the scope that enclosed the value (which can
379 /// be used to find the await that the value is live across).
383 /// ```ignore (pseudo-Rust)
391 /// Here, we would store the type `T`, the span of the value `x`, the "scope-span" for
392 /// the scope that contains `x`, the expr `T` evaluated from, and the span of `foo.await`.
393 #[derive(TyEncodable, TyDecodable, Clone, Debug, Eq, Hash, PartialEq, HashStable)]
394 #[derive(TypeFoldable, TypeVisitable)]
395 pub struct GeneratorInteriorTypeCause<'tcx> {
396 /// Type of the captured binding.
398 /// Span of the binding that was captured.
400 /// Span of the scope of the captured binding.
401 pub scope_span: Option<Span>,
402 /// Span of `.await` or `yield` expression.
403 pub yield_span: Span,
404 /// Expr which the type evaluated from.
405 pub expr: Option<hir::HirId>,
408 // This type holds diagnostic information on generators and async functions across crate boundaries
409 // and is used to provide better error messages
410 #[derive(TyEncodable, TyDecodable, Clone, Debug, HashStable)]
411 pub struct GeneratorDiagnosticData<'tcx> {
412 pub generator_interior_types: ty::Binder<'tcx, Vec<GeneratorInteriorTypeCause<'tcx>>>,
413 pub hir_owner: DefId,
414 pub nodes_types: ItemLocalMap<Ty<'tcx>>,
415 pub adjustments: ItemLocalMap<Vec<ty::adjustment::Adjustment<'tcx>>>,
418 #[derive(TyEncodable, TyDecodable, Debug, HashStable)]
419 pub struct TypeckResults<'tcx> {
420 /// The `HirId::owner` all `ItemLocalId`s in this table are relative to.
421 pub hir_owner: LocalDefId,
423 /// Resolved definitions for `<T>::X` associated paths and
424 /// method calls, including those of overloaded operators.
425 type_dependent_defs: ItemLocalMap<Result<(DefKind, DefId), ErrorGuaranteed>>,
427 /// Resolved field indices for field accesses in expressions (`S { field }`, `obj.field`)
428 /// or patterns (`S { field }`). The index is often useful by itself, but to learn more
429 /// about the field you also need definition of the variant to which the field
430 /// belongs, but it may not exist if it's a tuple field (`tuple.0`).
431 field_indices: ItemLocalMap<usize>,
433 /// Stores the types for various nodes in the AST. Note that this table
434 /// is not guaranteed to be populated outside inference. See
435 /// typeck::check::fn_ctxt for details.
436 node_types: ItemLocalMap<Ty<'tcx>>,
438 /// Stores the type parameters which were substituted to obtain the type
439 /// of this node. This only applies to nodes that refer to entities
440 /// parameterized by type parameters, such as generic fns, types, or
442 node_substs: ItemLocalMap<SubstsRef<'tcx>>,
444 /// This will either store the canonicalized types provided by the user
445 /// or the substitutions that the user explicitly gave (if any) attached
446 /// to `id`. These will not include any inferred values. The canonical form
447 /// is used to capture things like `_` or other unspecified values.
449 /// For example, if the user wrote `foo.collect::<Vec<_>>()`, then the
450 /// canonical substitutions would include only `for<X> { Vec<X> }`.
452 /// See also `AscribeUserType` statement in MIR.
453 user_provided_types: ItemLocalMap<CanonicalUserType<'tcx>>,
455 /// Stores the canonicalized types provided by the user. See also
456 /// `AscribeUserType` statement in MIR.
457 pub user_provided_sigs: DefIdMap<CanonicalPolyFnSig<'tcx>>,
459 adjustments: ItemLocalMap<Vec<ty::adjustment::Adjustment<'tcx>>>,
461 /// Stores the actual binding mode for all instances of hir::BindingAnnotation.
462 pat_binding_modes: ItemLocalMap<BindingMode>,
464 /// Stores the types which were implicitly dereferenced in pattern binding modes
465 /// for later usage in THIR lowering. For example,
468 /// match &&Some(5i32) {
473 /// leads to a `vec![&&Option<i32>, &Option<i32>]`. Empty vectors are not stored.
476 /// <https://github.com/rust-lang/rfcs/blob/master/text/2005-match-ergonomics.md#definitions>
477 pat_adjustments: ItemLocalMap<Vec<Ty<'tcx>>>,
479 /// Records the reasons that we picked the kind of each closure;
480 /// not all closures are present in the map.
481 closure_kind_origins: ItemLocalMap<(Span, HirPlace<'tcx>)>,
483 /// For each fn, records the "liberated" types of its arguments
484 /// and return type. Liberated means that all bound regions
485 /// (including late-bound regions) are replaced with free
486 /// equivalents. This table is not used in codegen (since regions
487 /// are erased there) and hence is not serialized to metadata.
489 /// This table also contains the "revealed" values for any `impl Trait`
490 /// that appear in the signature and whose values are being inferred
491 /// by this function.
496 /// # use std::fmt::Debug;
497 /// fn foo(x: &u32) -> impl Debug { *x }
500 /// The function signature here would be:
502 /// ```ignore (illustrative)
503 /// for<'a> fn(&'a u32) -> Foo
506 /// where `Foo` is an opaque type created for this function.
509 /// The *liberated* form of this would be
511 /// ```ignore (illustrative)
512 /// fn(&'a u32) -> u32
515 /// Note that `'a` is not bound (it would be an `ReFree`) and
516 /// that the `Foo` opaque type is replaced by its hidden type.
517 liberated_fn_sigs: ItemLocalMap<ty::FnSig<'tcx>>,
519 /// For each FRU expression, record the normalized types of the fields
520 /// of the struct - this is needed because it is non-trivial to
521 /// normalize while preserving regions. This table is used only in
522 /// MIR construction and hence is not serialized to metadata.
523 fru_field_types: ItemLocalMap<Vec<Ty<'tcx>>>,
525 /// For every coercion cast we add the HIR node ID of the cast
526 /// expression to this set.
527 coercion_casts: ItemLocalSet,
529 /// Set of trait imports actually used in the method resolution.
530 /// This is used for warning unused imports. During type
531 /// checking, this `Lrc` should not be cloned: it must have a ref-count
532 /// of 1 so that we can insert things into the set mutably.
533 pub used_trait_imports: Lrc<FxHashSet<LocalDefId>>,
535 /// If any errors occurred while type-checking this body,
536 /// this field will be set to `Some(ErrorGuaranteed)`.
537 pub tainted_by_errors: Option<ErrorGuaranteed>,
539 /// All the opaque types that have hidden types set
540 /// by this function. For return-position-impl-trait we also store the
541 /// type here, so that mir-borrowck can figure out hidden types,
542 /// even if they are only set in dead code (which doesn't show up in MIR).
543 /// For type-alias-impl-trait, this map is only used to prevent query cycles,
544 /// so the hidden types are all `None`.
545 pub concrete_opaque_types: VecMap<LocalDefId, Option<Ty<'tcx>>>,
547 /// Tracks the minimum captures required for a closure;
548 /// see `MinCaptureInformationMap` for more details.
549 pub closure_min_captures: ty::MinCaptureInformationMap<'tcx>,
551 /// Tracks the fake reads required for a closure and the reason for the fake read.
552 /// When performing pattern matching for closures, there are times we don't end up
553 /// reading places that are mentioned in a closure (because of _ patterns). However,
554 /// to ensure the places are initialized, we introduce fake reads.
555 /// Consider these two examples:
556 /// ``` (discriminant matching with only wildcard arm)
558 /// let c = || match x { _ => () };
560 /// In this example, we don't need to actually read/borrow `x` in `c`, and so we don't
561 /// want to capture it. However, we do still want an error here, because `x` should have
562 /// to be initialized at the point where c is created. Therefore, we add a "fake read"
564 /// ``` (destructured assignments)
566 /// let (t1, t2) = t;
569 /// In the second example, we capture the disjoint fields of `t` (`t.0` & `t.1`), but
570 /// we never capture `t`. This becomes an issue when we build MIR as we require
571 /// information on `t` in order to create place `t.0` and `t.1`. We can solve this
572 /// issue by fake reading `t`.
573 pub closure_fake_reads: FxHashMap<LocalDefId, Vec<(HirPlace<'tcx>, FakeReadCause, hir::HirId)>>,
575 /// Tracks the rvalue scoping rules which defines finer scoping for rvalue expressions
576 /// by applying extended parameter rules.
577 /// Details may be find in `rustc_typeck::check::rvalue_scopes`.
578 pub rvalue_scopes: RvalueScopes,
580 /// Stores the type, expression, span and optional scope span of all types
581 /// that are live across the yield of this generator (if a generator).
582 pub generator_interior_types: ty::Binder<'tcx, Vec<GeneratorInteriorTypeCause<'tcx>>>,
584 /// We sometimes treat byte string literals (which are of type `&[u8; N]`)
585 /// as `&[u8]`, depending on the pattern in which they are used.
586 /// This hashset records all instances where we behave
587 /// like this to allow `const_to_pat` to reliably handle this situation.
588 pub treat_byte_string_as_slice: ItemLocalSet,
590 /// Contains the data for evaluating the effect of feature `capture_disjoint_fields`
592 pub closure_size_eval: FxHashMap<LocalDefId, ClosureSizeProfileData<'tcx>>,
595 impl<'tcx> TypeckResults<'tcx> {
596 pub fn new(hir_owner: LocalDefId) -> TypeckResults<'tcx> {
599 type_dependent_defs: Default::default(),
600 field_indices: Default::default(),
601 user_provided_types: Default::default(),
602 user_provided_sigs: Default::default(),
603 node_types: Default::default(),
604 node_substs: Default::default(),
605 adjustments: Default::default(),
606 pat_binding_modes: Default::default(),
607 pat_adjustments: Default::default(),
608 closure_kind_origins: Default::default(),
609 liberated_fn_sigs: Default::default(),
610 fru_field_types: Default::default(),
611 coercion_casts: Default::default(),
612 used_trait_imports: Lrc::new(Default::default()),
613 tainted_by_errors: None,
614 concrete_opaque_types: Default::default(),
615 closure_min_captures: Default::default(),
616 closure_fake_reads: Default::default(),
617 rvalue_scopes: Default::default(),
618 generator_interior_types: ty::Binder::dummy(Default::default()),
619 treat_byte_string_as_slice: Default::default(),
620 closure_size_eval: Default::default(),
624 /// Returns the final resolution of a `QPath` in an `Expr` or `Pat` node.
625 pub fn qpath_res(&self, qpath: &hir::QPath<'_>, id: hir::HirId) -> Res {
627 hir::QPath::Resolved(_, ref path) => path.res,
628 hir::QPath::TypeRelative(..) | hir::QPath::LangItem(..) => self
629 .type_dependent_def(id)
630 .map_or(Res::Err, |(kind, def_id)| Res::Def(kind, def_id)),
634 pub fn type_dependent_defs(
636 ) -> LocalTableInContext<'_, Result<(DefKind, DefId), ErrorGuaranteed>> {
637 LocalTableInContext { hir_owner: self.hir_owner, data: &self.type_dependent_defs }
640 pub fn type_dependent_def(&self, id: HirId) -> Option<(DefKind, DefId)> {
641 validate_hir_id_for_typeck_results(self.hir_owner, id);
642 self.type_dependent_defs.get(&id.local_id).cloned().and_then(|r| r.ok())
645 pub fn type_dependent_def_id(&self, id: HirId) -> Option<DefId> {
646 self.type_dependent_def(id).map(|(_, def_id)| def_id)
649 pub fn type_dependent_defs_mut(
651 ) -> LocalTableInContextMut<'_, Result<(DefKind, DefId), ErrorGuaranteed>> {
652 LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.type_dependent_defs }
655 pub fn field_indices(&self) -> LocalTableInContext<'_, usize> {
656 LocalTableInContext { hir_owner: self.hir_owner, data: &self.field_indices }
659 pub fn field_indices_mut(&mut self) -> LocalTableInContextMut<'_, usize> {
660 LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.field_indices }
663 pub fn user_provided_types(&self) -> LocalTableInContext<'_, CanonicalUserType<'tcx>> {
664 LocalTableInContext { hir_owner: self.hir_owner, data: &self.user_provided_types }
667 pub fn user_provided_types_mut(
669 ) -> LocalTableInContextMut<'_, CanonicalUserType<'tcx>> {
670 LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.user_provided_types }
673 pub fn node_types(&self) -> LocalTableInContext<'_, Ty<'tcx>> {
674 LocalTableInContext { hir_owner: self.hir_owner, data: &self.node_types }
677 pub fn node_types_mut(&mut self) -> LocalTableInContextMut<'_, Ty<'tcx>> {
678 LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.node_types }
681 pub fn get_generator_diagnostic_data(&self) -> GeneratorDiagnosticData<'tcx> {
682 let generator_interior_type = self.generator_interior_types.map_bound_ref(|vec| {
685 GeneratorInteriorTypeCause {
688 scope_span: item.scope_span,
689 yield_span: item.yield_span,
690 expr: None, //FIXME: Passing expression over crate boundaries is impossible at the moment
695 GeneratorDiagnosticData {
696 generator_interior_types: generator_interior_type,
697 hir_owner: self.hir_owner.to_def_id(),
698 nodes_types: self.node_types.clone(),
699 adjustments: self.adjustments.clone(),
703 pub fn node_type(&self, id: hir::HirId) -> Ty<'tcx> {
704 self.node_type_opt(id).unwrap_or_else(|| {
705 bug!("node_type: no type for node `{}`", tls::with(|tcx| tcx.hir().node_to_string(id)))
709 pub fn node_type_opt(&self, id: hir::HirId) -> Option<Ty<'tcx>> {
710 validate_hir_id_for_typeck_results(self.hir_owner, id);
711 self.node_types.get(&id.local_id).cloned()
714 pub fn node_substs_mut(&mut self) -> LocalTableInContextMut<'_, SubstsRef<'tcx>> {
715 LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.node_substs }
718 pub fn node_substs(&self, id: hir::HirId) -> SubstsRef<'tcx> {
719 validate_hir_id_for_typeck_results(self.hir_owner, id);
720 self.node_substs.get(&id.local_id).cloned().unwrap_or_else(|| InternalSubsts::empty())
723 pub fn node_substs_opt(&self, id: hir::HirId) -> Option<SubstsRef<'tcx>> {
724 validate_hir_id_for_typeck_results(self.hir_owner, id);
725 self.node_substs.get(&id.local_id).cloned()
728 // Returns the type of a pattern as a monotype. Like @expr_ty, this function
729 // doesn't provide type parameter substitutions.
730 pub fn pat_ty(&self, pat: &hir::Pat<'_>) -> Ty<'tcx> {
731 self.node_type(pat.hir_id)
734 // Returns the type of an expression as a monotype.
736 // NB (1): This is the PRE-ADJUSTMENT TYPE for the expression. That is, in
737 // some cases, we insert `Adjustment` annotations such as auto-deref or
738 // auto-ref. The type returned by this function does not consider such
739 // adjustments. See `expr_ty_adjusted()` instead.
741 // NB (2): This type doesn't provide type parameter substitutions; e.g., if you
742 // ask for the type of "id" in "id(3)", it will return "fn(&isize) -> isize"
743 // instead of "fn(ty) -> T with T = isize".
744 pub fn expr_ty(&self, expr: &hir::Expr<'_>) -> Ty<'tcx> {
745 self.node_type(expr.hir_id)
748 pub fn expr_ty_opt(&self, expr: &hir::Expr<'_>) -> Option<Ty<'tcx>> {
749 self.node_type_opt(expr.hir_id)
752 pub fn adjustments(&self) -> LocalTableInContext<'_, Vec<ty::adjustment::Adjustment<'tcx>>> {
753 LocalTableInContext { hir_owner: self.hir_owner, data: &self.adjustments }
756 pub fn adjustments_mut(
758 ) -> LocalTableInContextMut<'_, Vec<ty::adjustment::Adjustment<'tcx>>> {
759 LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.adjustments }
762 pub fn expr_adjustments(&self, expr: &hir::Expr<'_>) -> &[ty::adjustment::Adjustment<'tcx>] {
763 validate_hir_id_for_typeck_results(self.hir_owner, expr.hir_id);
764 self.adjustments.get(&expr.hir_id.local_id).map_or(&[], |a| &a[..])
767 /// Returns the type of `expr`, considering any `Adjustment`
768 /// entry recorded for that expression.
769 pub fn expr_ty_adjusted(&self, expr: &hir::Expr<'_>) -> Ty<'tcx> {
770 self.expr_adjustments(expr).last().map_or_else(|| self.expr_ty(expr), |adj| adj.target)
773 pub fn expr_ty_adjusted_opt(&self, expr: &hir::Expr<'_>) -> Option<Ty<'tcx>> {
774 self.expr_adjustments(expr).last().map(|adj| adj.target).or_else(|| self.expr_ty_opt(expr))
777 pub fn is_method_call(&self, expr: &hir::Expr<'_>) -> bool {
778 // Only paths and method calls/overloaded operators have
779 // entries in type_dependent_defs, ignore the former here.
780 if let hir::ExprKind::Path(_) = expr.kind {
784 matches!(self.type_dependent_defs().get(expr.hir_id), Some(Ok((DefKind::AssocFn, _))))
787 pub fn extract_binding_mode(&self, s: &Session, id: HirId, sp: Span) -> Option<BindingMode> {
788 self.pat_binding_modes().get(id).copied().or_else(|| {
789 s.delay_span_bug(sp, "missing binding mode");
794 pub fn pat_binding_modes(&self) -> LocalTableInContext<'_, BindingMode> {
795 LocalTableInContext { hir_owner: self.hir_owner, data: &self.pat_binding_modes }
798 pub fn pat_binding_modes_mut(&mut self) -> LocalTableInContextMut<'_, BindingMode> {
799 LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.pat_binding_modes }
802 pub fn pat_adjustments(&self) -> LocalTableInContext<'_, Vec<Ty<'tcx>>> {
803 LocalTableInContext { hir_owner: self.hir_owner, data: &self.pat_adjustments }
806 pub fn pat_adjustments_mut(&mut self) -> LocalTableInContextMut<'_, Vec<Ty<'tcx>>> {
807 LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.pat_adjustments }
810 /// For a given closure, returns the iterator of `ty::CapturedPlace`s that are captured
812 pub fn closure_min_captures_flattened(
814 closure_def_id: LocalDefId,
815 ) -> impl Iterator<Item = &ty::CapturedPlace<'tcx>> {
816 self.closure_min_captures
817 .get(&closure_def_id)
818 .map(|closure_min_captures| closure_min_captures.values().flat_map(|v| v.iter()))
823 pub fn closure_kind_origins(&self) -> LocalTableInContext<'_, (Span, HirPlace<'tcx>)> {
824 LocalTableInContext { hir_owner: self.hir_owner, data: &self.closure_kind_origins }
827 pub fn closure_kind_origins_mut(
829 ) -> LocalTableInContextMut<'_, (Span, HirPlace<'tcx>)> {
830 LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.closure_kind_origins }
833 pub fn liberated_fn_sigs(&self) -> LocalTableInContext<'_, ty::FnSig<'tcx>> {
834 LocalTableInContext { hir_owner: self.hir_owner, data: &self.liberated_fn_sigs }
837 pub fn liberated_fn_sigs_mut(&mut self) -> LocalTableInContextMut<'_, ty::FnSig<'tcx>> {
838 LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.liberated_fn_sigs }
841 pub fn fru_field_types(&self) -> LocalTableInContext<'_, Vec<Ty<'tcx>>> {
842 LocalTableInContext { hir_owner: self.hir_owner, data: &self.fru_field_types }
845 pub fn fru_field_types_mut(&mut self) -> LocalTableInContextMut<'_, Vec<Ty<'tcx>>> {
846 LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.fru_field_types }
849 pub fn is_coercion_cast(&self, hir_id: hir::HirId) -> bool {
850 validate_hir_id_for_typeck_results(self.hir_owner, hir_id);
851 self.coercion_casts.contains(&hir_id.local_id)
854 pub fn set_coercion_cast(&mut self, id: ItemLocalId) {
855 self.coercion_casts.insert(id);
858 pub fn coercion_casts(&self) -> &ItemLocalSet {
863 rustc_index::newtype_index! {
864 pub struct UserTypeAnnotationIndex {
866 DEBUG_FORMAT = "UserType({})",
867 const START_INDEX = 0,
871 /// Mapping of type annotation indices to canonical user type annotations.
872 pub type CanonicalUserTypeAnnotations<'tcx> =
873 IndexVec<UserTypeAnnotationIndex, CanonicalUserTypeAnnotation<'tcx>>;
875 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable, TypeVisitable, Lift)]
876 pub struct CanonicalUserTypeAnnotation<'tcx> {
877 pub user_ty: Box<CanonicalUserType<'tcx>>,
879 pub inferred_ty: Ty<'tcx>,
882 /// Canonicalized user type annotation.
883 pub type CanonicalUserType<'tcx> = Canonical<'tcx, UserType<'tcx>>;
885 impl<'tcx> CanonicalUserType<'tcx> {
886 /// Returns `true` if this represents a substitution of the form `[?0, ?1, ?2]`,
887 /// i.e., each thing is mapped to a canonical variable with the same index.
888 pub fn is_identity(&self) -> bool {
890 UserType::Ty(_) => false,
891 UserType::TypeOf(_, user_substs) => {
892 if user_substs.user_self_ty.is_some() {
896 iter::zip(user_substs.substs, BoundVar::new(0)..).all(|(kind, cvar)| {
897 match kind.unpack() {
898 GenericArgKind::Type(ty) => match ty.kind() {
899 ty::Bound(debruijn, b) => {
900 // We only allow a `ty::INNERMOST` index in substitutions.
901 assert_eq!(*debruijn, ty::INNERMOST);
907 GenericArgKind::Lifetime(r) => match *r {
908 ty::ReLateBound(debruijn, br) => {
909 // We only allow a `ty::INNERMOST` index in substitutions.
910 assert_eq!(debruijn, ty::INNERMOST);
916 GenericArgKind::Const(ct) => match ct.kind() {
917 ty::ConstKind::Bound(debruijn, b) => {
918 // We only allow a `ty::INNERMOST` index in substitutions.
919 assert_eq!(debruijn, ty::INNERMOST);
931 /// A user-given type annotation attached to a constant. These arise
932 /// from constants that are named via paths, like `Foo::<A>::new` and
934 #[derive(Copy, Clone, Debug, PartialEq, TyEncodable, TyDecodable)]
935 #[derive(HashStable, TypeFoldable, TypeVisitable, Lift)]
936 pub enum UserType<'tcx> {
939 /// The canonical type is the result of `type_of(def_id)` with the
940 /// given substitutions applied.
941 TypeOf(DefId, UserSubsts<'tcx>),
944 impl<'tcx> CommonTypes<'tcx> {
946 interners: &CtxtInterners<'tcx>,
948 definitions: &rustc_hir::definitions::Definitions,
949 cstore: &CrateStoreDyn,
950 source_span: &IndexVec<LocalDefId, Span>,
951 ) -> CommonTypes<'tcx> {
952 let mk = |ty| interners.intern_ty(ty, sess, definitions, cstore, source_span);
955 unit: mk(Tuple(List::empty())),
959 isize: mk(Int(ty::IntTy::Isize)),
960 i8: mk(Int(ty::IntTy::I8)),
961 i16: mk(Int(ty::IntTy::I16)),
962 i32: mk(Int(ty::IntTy::I32)),
963 i64: mk(Int(ty::IntTy::I64)),
964 i128: mk(Int(ty::IntTy::I128)),
965 usize: mk(Uint(ty::UintTy::Usize)),
966 u8: mk(Uint(ty::UintTy::U8)),
967 u16: mk(Uint(ty::UintTy::U16)),
968 u32: mk(Uint(ty::UintTy::U32)),
969 u64: mk(Uint(ty::UintTy::U64)),
970 u128: mk(Uint(ty::UintTy::U128)),
971 f32: mk(Float(ty::FloatTy::F32)),
972 f64: mk(Float(ty::FloatTy::F64)),
974 self_param: mk(ty::Param(ty::ParamTy { index: 0, name: kw::SelfUpper })),
976 trait_object_dummy_self: mk(Infer(ty::FreshTy(0))),
981 impl<'tcx> CommonLifetimes<'tcx> {
982 fn new(interners: &CtxtInterners<'tcx>) -> CommonLifetimes<'tcx> {
984 Region(Interned::new_unchecked(
985 interners.region.intern(r, |r| InternedInSet(interners.arena.alloc(r))).0,
990 re_root_empty: mk(ty::ReEmpty(ty::UniverseIndex::ROOT)),
991 re_static: mk(ty::ReStatic),
992 re_erased: mk(ty::ReErased),
997 impl<'tcx> CommonConsts<'tcx> {
998 fn new(interners: &CtxtInterners<'tcx>, types: &CommonTypes<'tcx>) -> CommonConsts<'tcx> {
1000 Const(Interned::new_unchecked(
1001 interners.const_.intern(c, |c| InternedInSet(interners.arena.alloc(c))).0,
1006 unit: mk_const(ty::ConstS {
1007 kind: ty::ConstKind::Value(ty::ValTree::zst()),
1014 // This struct contains information regarding the `ReFree(FreeRegion)` corresponding to a lifetime
1017 pub struct FreeRegionInfo {
1018 // `LocalDefId` corresponding to FreeRegion
1019 pub def_id: LocalDefId,
1020 // the bound region corresponding to FreeRegion
1021 pub boundregion: ty::BoundRegionKind,
1022 // checks if bound region is in Impl Item
1023 pub is_impl_item: bool,
1026 /// The central data structure of the compiler. It stores references
1027 /// to the various **arenas** and also houses the results of the
1028 /// various **compiler queries** that have been performed. See the
1029 /// [rustc dev guide] for more details.
1031 /// [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/ty.html
1032 #[derive(Copy, Clone)]
1033 #[rustc_diagnostic_item = "TyCtxt"]
1034 #[rustc_pass_by_value]
1035 pub struct TyCtxt<'tcx> {
1036 gcx: &'tcx GlobalCtxt<'tcx>,
1039 impl<'tcx> Deref for TyCtxt<'tcx> {
1040 type Target = &'tcx GlobalCtxt<'tcx>;
1042 fn deref(&self) -> &Self::Target {
1047 pub struct GlobalCtxt<'tcx> {
1048 pub arena: &'tcx WorkerLocal<Arena<'tcx>>,
1049 pub hir_arena: &'tcx WorkerLocal<hir::Arena<'tcx>>,
1051 interners: CtxtInterners<'tcx>,
1053 pub sess: &'tcx Session,
1055 /// This only ever stores a `LintStore` but we don't want a dependency on that type here.
1057 /// FIXME(Centril): consider `dyn LintStoreMarker` once
1058 /// we can upcast to `Any` for some additional type safety.
1059 pub lint_store: Lrc<dyn Any + sync::Sync + sync::Send>,
1061 pub dep_graph: DepGraph,
1063 pub prof: SelfProfilerRef,
1065 /// Common types, pre-interned for your convenience.
1066 pub types: CommonTypes<'tcx>,
1068 /// Common lifetimes, pre-interned for your convenience.
1069 pub lifetimes: CommonLifetimes<'tcx>,
1071 /// Common consts, pre-interned for your convenience.
1072 pub consts: CommonConsts<'tcx>,
1074 definitions: RwLock<Definitions>,
1075 cstore: Box<CrateStoreDyn>,
1077 /// Output of the resolver.
1078 pub(crate) untracked_resolutions: ty::ResolverOutputs,
1079 untracked_resolver_for_lowering: Steal<ty::ResolverAstLowering>,
1080 /// The entire crate as AST. This field serves as the input for the hir_crate query,
1081 /// which lowers it from AST to HIR. It must not be read or used by anything else.
1082 pub untracked_crate: Steal<Lrc<ast::Crate>>,
1084 /// This provides access to the incremental compilation on-disk cache for query results.
1085 /// Do not access this directly. It is only meant to be used by
1086 /// `DepGraph::try_mark_green()` and the query infrastructure.
1087 /// This is `None` if we are not incremental compilation mode
1088 pub on_disk_cache: Option<&'tcx dyn OnDiskCache<'tcx>>,
1090 pub queries: &'tcx dyn query::QueryEngine<'tcx>,
1091 pub query_caches: query::QueryCaches<'tcx>,
1092 query_kinds: &'tcx [DepKindStruct<'tcx>],
1094 // Internal caches for metadata decoding. No need to track deps on this.
1095 pub ty_rcache: Lock<FxHashMap<ty::CReaderCacheKey, Ty<'tcx>>>,
1096 pub pred_rcache: Lock<FxHashMap<ty::CReaderCacheKey, Predicate<'tcx>>>,
1098 /// Caches the results of trait selection. This cache is used
1099 /// for things that do not have to do with the parameters in scope.
1100 pub selection_cache: traits::SelectionCache<'tcx>,
1102 /// Caches the results of trait evaluation. This cache is used
1103 /// for things that do not have to do with the parameters in scope.
1104 /// Merge this with `selection_cache`?
1105 pub evaluation_cache: traits::EvaluationCache<'tcx>,
1107 /// The definite name of the current crate after taking into account
1108 /// attributes, commandline parameters, etc.
1111 /// Data layout specification for the current target.
1112 pub data_layout: TargetDataLayout,
1114 /// Stores memory for globals (statics/consts).
1115 pub(crate) alloc_map: Lock<interpret::AllocMap<'tcx>>,
1117 output_filenames: Arc<OutputFilenames>,
1120 impl<'tcx> TyCtxt<'tcx> {
1121 /// Expects a body and returns its codegen attributes.
1123 /// Unlike `codegen_fn_attrs`, this returns `CodegenFnAttrs::EMPTY` for
1125 pub fn body_codegen_attrs(self, def_id: DefId) -> &'tcx CodegenFnAttrs {
1126 let def_kind = self.def_kind(def_id);
1127 if def_kind.has_codegen_attrs() {
1128 self.codegen_fn_attrs(def_id)
1131 DefKind::AnonConst | DefKind::AssocConst | DefKind::Const | DefKind::InlineConst
1133 CodegenFnAttrs::EMPTY
1136 "body_codegen_fn_attrs called on unexpected definition: {:?} {:?}",
1143 pub fn typeck_opt_const_arg(
1145 def: ty::WithOptConstParam<LocalDefId>,
1146 ) -> &'tcx TypeckResults<'tcx> {
1147 if let Some(param_did) = def.const_param_did {
1148 self.typeck_const_arg((def.did, param_did))
1150 self.typeck(def.did)
1154 pub fn mir_borrowck_opt_const_arg(
1156 def: ty::WithOptConstParam<LocalDefId>,
1157 ) -> &'tcx BorrowCheckResult<'tcx> {
1158 if let Some(param_did) = def.const_param_did {
1159 self.mir_borrowck_const_arg((def.did, param_did))
1161 self.mir_borrowck(def.did)
1165 pub fn alloc_steal_thir(self, thir: Thir<'tcx>) -> &'tcx Steal<Thir<'tcx>> {
1166 self.arena.alloc(Steal::new(thir))
1169 pub fn alloc_steal_mir(self, mir: Body<'tcx>) -> &'tcx Steal<Body<'tcx>> {
1170 self.arena.alloc(Steal::new(mir))
1173 pub fn alloc_steal_promoted(
1175 promoted: IndexVec<Promoted, Body<'tcx>>,
1176 ) -> &'tcx Steal<IndexVec<Promoted, Body<'tcx>>> {
1177 self.arena.alloc(Steal::new(promoted))
1180 pub fn alloc_adt_def(
1184 variants: IndexVec<VariantIdx, ty::VariantDef>,
1186 ) -> ty::AdtDef<'tcx> {
1187 self.intern_adt_def(ty::AdtDefData::new(self, did, kind, variants, repr))
1190 /// Allocates a read-only byte or string literal for `mir::interpret`.
1191 pub fn allocate_bytes(self, bytes: &[u8]) -> interpret::AllocId {
1192 // Create an allocation that just contains these bytes.
1193 let alloc = interpret::Allocation::from_bytes_byte_aligned_immutable(bytes);
1194 let alloc = self.intern_const_alloc(alloc);
1195 self.create_memory_alloc(alloc)
1198 /// Returns a range of the start/end indices specified with the
1199 /// `rustc_layout_scalar_valid_range` attribute.
1200 // FIXME(eddyb) this is an awkward spot for this method, maybe move it?
1201 pub fn layout_scalar_valid_range(self, def_id: DefId) -> (Bound<u128>, Bound<u128>) {
1203 let Some(attr) = self.get_attr(def_id, name) else {
1204 return Bound::Unbounded;
1206 debug!("layout_scalar_valid_range: attr={:?}", attr);
1209 ast::NestedMetaItem::Literal(ast::Lit {
1210 kind: ast::LitKind::Int(a, _), ..
1213 ) = attr.meta_item_list().as_deref()
1218 .delay_span_bug(attr.span, "invalid rustc_layout_scalar_valid_range attribute");
1223 get(sym::rustc_layout_scalar_valid_range_start),
1224 get(sym::rustc_layout_scalar_valid_range_end),
1228 pub fn lift<T: Lift<'tcx>>(self, value: T) -> Option<T::Lifted> {
1229 value.lift_to_tcx(self)
1232 /// Creates a type context and call the closure with a `TyCtxt` reference
1233 /// to the context. The closure enforces that the type context and any interned
1234 /// value (types, substs, etc.) can only be used while `ty::tls` has a valid
1235 /// reference to the context, to allow formatting values that need it.
1236 pub fn create_global_ctxt(
1238 lint_store: Lrc<dyn Any + sync::Send + sync::Sync>,
1239 arena: &'tcx WorkerLocal<Arena<'tcx>>,
1240 hir_arena: &'tcx WorkerLocal<hir::Arena<'tcx>>,
1241 definitions: Definitions,
1242 cstore: Box<CrateStoreDyn>,
1243 untracked_resolutions: ty::ResolverOutputs,
1244 untracked_resolver_for_lowering: ty::ResolverAstLowering,
1245 krate: Lrc<ast::Crate>,
1246 dep_graph: DepGraph,
1247 on_disk_cache: Option<&'tcx dyn OnDiskCache<'tcx>>,
1248 queries: &'tcx dyn query::QueryEngine<'tcx>,
1249 query_kinds: &'tcx [DepKindStruct<'tcx>],
1251 output_filenames: OutputFilenames,
1252 ) -> GlobalCtxt<'tcx> {
1253 let data_layout = TargetDataLayout::parse(&s.target).unwrap_or_else(|err| {
1256 let interners = CtxtInterners::new(arena);
1257 let common_types = CommonTypes::new(
1262 // This is only used to create a stable hashing context.
1263 &untracked_resolutions.source_span,
1265 let common_lifetimes = CommonLifetimes::new(&interners);
1266 let common_consts = CommonConsts::new(&interners, &common_types);
1275 definitions: RwLock::new(definitions),
1277 prof: s.prof.clone(),
1278 types: common_types,
1279 lifetimes: common_lifetimes,
1280 consts: common_consts,
1281 untracked_resolutions,
1282 untracked_resolver_for_lowering: Steal::new(untracked_resolver_for_lowering),
1283 untracked_crate: Steal::new(krate),
1286 query_caches: query::QueryCaches::default(),
1288 ty_rcache: Default::default(),
1289 pred_rcache: Default::default(),
1290 selection_cache: Default::default(),
1291 evaluation_cache: Default::default(),
1292 crate_name: Symbol::intern(crate_name),
1294 alloc_map: Lock::new(interpret::AllocMap::new()),
1295 output_filenames: Arc::new(output_filenames),
1299 pub(crate) fn query_kind(self, k: DepKind) -> &'tcx DepKindStruct<'tcx> {
1300 &self.query_kinds[k as usize]
1303 /// Constructs a `TyKind::Error` type and registers a `delay_span_bug` to ensure it gets used.
1305 pub fn ty_error(self) -> Ty<'tcx> {
1306 self.ty_error_with_message(DUMMY_SP, "TyKind::Error constructed but no error reported")
1309 /// Constructs a `TyKind::Error` type and registers a `delay_span_bug` with the given `msg` to
1310 /// ensure it gets used.
1312 pub fn ty_error_with_message<S: Into<MultiSpan>>(self, span: S, msg: &str) -> Ty<'tcx> {
1313 let reported = self.sess.delay_span_bug(span, msg);
1314 self.mk_ty(Error(DelaySpanBugEmitted { reported, _priv: () }))
1317 /// Like [TyCtxt::ty_error] but for constants.
1319 pub fn const_error(self, ty: Ty<'tcx>) -> Const<'tcx> {
1320 self.const_error_with_message(
1323 "ty::ConstKind::Error constructed but no error reported",
1327 /// Like [TyCtxt::ty_error_with_message] but for constants.
1329 pub fn const_error_with_message<S: Into<MultiSpan>>(
1335 let reported = self.sess.delay_span_bug(span, msg);
1336 self.mk_const(ty::ConstS {
1337 kind: ty::ConstKind::Error(DelaySpanBugEmitted { reported, _priv: () }),
1342 pub fn consider_optimizing<T: Fn() -> String>(self, msg: T) -> bool {
1343 let cname = self.crate_name(LOCAL_CRATE);
1344 self.sess.consider_optimizing(cname.as_str(), msg)
1347 /// Obtain all lang items of this crate and all dependencies (recursively)
1348 pub fn lang_items(self) -> &'tcx rustc_hir::lang_items::LanguageItems {
1349 self.get_lang_items(())
1352 /// Obtain the given diagnostic item's `DefId`. Use `is_diagnostic_item` if you just want to
1353 /// compare against another `DefId`, since `is_diagnostic_item` is cheaper.
1354 pub fn get_diagnostic_item(self, name: Symbol) -> Option<DefId> {
1355 self.all_diagnostic_items(()).name_to_id.get(&name).copied()
1358 /// Obtain the diagnostic item's name
1359 pub fn get_diagnostic_name(self, id: DefId) -> Option<Symbol> {
1360 self.diagnostic_items(id.krate).id_to_name.get(&id).copied()
1363 /// Check whether the diagnostic item with the given `name` has the given `DefId`.
1364 pub fn is_diagnostic_item(self, name: Symbol, did: DefId) -> bool {
1365 self.diagnostic_items(did.krate).name_to_id.get(&name) == Some(&did)
1368 pub fn stability(self) -> &'tcx stability::Index {
1369 self.stability_index(())
1372 pub fn features(self) -> &'tcx rustc_feature::Features {
1373 self.features_query(())
1376 pub fn def_key(self, id: DefId) -> rustc_hir::definitions::DefKey {
1377 // Accessing the DefKey is ok, since it is part of DefPathHash.
1378 if let Some(id) = id.as_local() {
1379 self.definitions_untracked().def_key(id)
1381 self.cstore.def_key(id)
1385 /// Converts a `DefId` into its fully expanded `DefPath` (every
1386 /// `DefId` is really just an interned `DefPath`).
1388 /// Note that if `id` is not local to this crate, the result will
1389 /// be a non-local `DefPath`.
1390 pub fn def_path(self, id: DefId) -> rustc_hir::definitions::DefPath {
1391 // Accessing the DefPath is ok, since it is part of DefPathHash.
1392 if let Some(id) = id.as_local() {
1393 self.definitions_untracked().def_path(id)
1395 self.cstore.def_path(id)
1400 pub fn def_path_hash(self, def_id: DefId) -> rustc_hir::definitions::DefPathHash {
1401 // Accessing the DefPathHash is ok, it is incr. comp. stable.
1402 if let Some(def_id) = def_id.as_local() {
1403 self.definitions_untracked().def_path_hash(def_id)
1405 self.cstore.def_path_hash(def_id)
1410 pub fn stable_crate_id(self, crate_num: CrateNum) -> StableCrateId {
1411 if crate_num == LOCAL_CRATE {
1412 self.sess.local_stable_crate_id()
1414 self.cstore.stable_crate_id(crate_num)
1418 /// Maps a StableCrateId to the corresponding CrateNum. This method assumes
1419 /// that the crate in question has already been loaded by the CrateStore.
1421 pub fn stable_crate_id_to_crate_num(self, stable_crate_id: StableCrateId) -> CrateNum {
1422 if stable_crate_id == self.sess.local_stable_crate_id() {
1425 self.cstore.stable_crate_id_to_crate_num(stable_crate_id)
1429 /// Converts a `DefPathHash` to its corresponding `DefId` in the current compilation
1430 /// session, if it still exists. This is used during incremental compilation to
1431 /// turn a deserialized `DefPathHash` into its current `DefId`.
1432 pub fn def_path_hash_to_def_id(self, hash: DefPathHash, err: &mut dyn FnMut() -> !) -> DefId {
1433 debug!("def_path_hash_to_def_id({:?})", hash);
1435 let stable_crate_id = hash.stable_crate_id();
1437 // If this is a DefPathHash from the local crate, we can look up the
1438 // DefId in the tcx's `Definitions`.
1439 if stable_crate_id == self.sess.local_stable_crate_id() {
1440 self.definitions.read().local_def_path_hash_to_def_id(hash, err).to_def_id()
1442 // If this is a DefPathHash from an upstream crate, let the CrateStore map
1444 let cnum = self.cstore.stable_crate_id_to_crate_num(stable_crate_id);
1445 self.cstore.def_path_hash_to_def_id(cnum, hash)
1449 pub fn def_path_debug_str(self, def_id: DefId) -> String {
1450 // We are explicitly not going through queries here in order to get
1451 // crate name and stable crate id since this code is called from debug!()
1452 // statements within the query system and we'd run into endless
1453 // recursion otherwise.
1454 let (crate_name, stable_crate_id) = if def_id.is_local() {
1455 (self.crate_name, self.sess.local_stable_crate_id())
1457 let cstore = &self.cstore;
1458 (cstore.crate_name(def_id.krate), cstore.stable_crate_id(def_id.krate))
1464 // Don't print the whole stable crate id. That's just
1465 // annoying in debug output.
1466 stable_crate_id.to_u64() >> 8 * 6,
1467 self.def_path(def_id).to_string_no_crate_verbose()
1471 /// Create a new definition within the incr. comp. engine.
1472 pub fn create_def(self, parent: LocalDefId, data: hir::definitions::DefPathData) -> LocalDefId {
1473 // This function modifies `self.definitions` using a side-effect.
1474 // We need to ensure that these side effects are re-run by the incr. comp. engine.
1475 // Depending on the forever-red node will tell the graph that the calling query
1476 // needs to be re-evaluated.
1477 use rustc_query_system::dep_graph::DepNodeIndex;
1478 self.dep_graph.read_index(DepNodeIndex::FOREVER_RED_NODE);
1480 // The following call has the side effect of modifying the tables inside `definitions`.
1481 // These very tables are relied on by the incr. comp. engine to decode DepNodes and to
1482 // decode the on-disk cache.
1484 // Any LocalDefId which is used within queries, either as key or result, either:
1485 // - has been created before the construction of the TyCtxt;
1486 // - has been created by this call to `create_def`.
1487 // As a consequence, this LocalDefId is always re-created before it is needed by the incr.
1488 // comp. engine itself.
1490 // This call also writes to the value of `source_span` and `expn_that_defined` queries.
1491 // This is fine because:
1492 // - those queries are `eval_always` so we won't miss their result changing;
1493 // - this write will have happened before these queries are called.
1494 self.definitions.write().create_def(parent, data)
1497 pub fn iter_local_def_id(self) -> impl Iterator<Item = LocalDefId> + 'tcx {
1498 // Create a dependency to the crate to be sure we re-execute this when the amount of
1499 // definitions change.
1500 self.ensure().hir_crate(());
1501 // Leak a read lock once we start iterating on definitions, to prevent adding new ones
1502 // while iterating. If some query needs to add definitions, it should be `ensure`d above.
1503 let definitions = self.definitions.leak();
1504 definitions.iter_local_def_id()
1507 pub fn def_path_table(self) -> &'tcx rustc_hir::definitions::DefPathTable {
1508 // Create a dependency to the crate to be sure we re-execute this when the amount of
1509 // definitions change.
1510 self.ensure().hir_crate(());
1511 // Leak a read lock once we start iterating on definitions, to prevent adding new ones
1512 // while iterating. If some query needs to add definitions, it should be `ensure`d above.
1513 let definitions = self.definitions.leak();
1514 definitions.def_path_table()
1517 pub fn def_path_hash_to_def_index_map(
1519 ) -> &'tcx rustc_hir::def_path_hash_map::DefPathHashMap {
1520 // Create a dependency to the crate to be sure we re-execute this when the amount of
1521 // definitions change.
1522 self.ensure().hir_crate(());
1523 // Leak a read lock once we start iterating on definitions, to prevent adding new ones
1524 // while iterating. If some query needs to add definitions, it should be `ensure`d above.
1525 let definitions = self.definitions.leak();
1526 definitions.def_path_hash_to_def_index_map()
1529 /// Note that this is *untracked* and should only be used within the query
1530 /// system if the result is otherwise tracked through queries
1531 pub fn cstore_untracked(self) -> &'tcx CrateStoreDyn {
1535 /// Note that this is *untracked* and should only be used within the query
1536 /// system if the result is otherwise tracked through queries
1538 pub fn definitions_untracked(self) -> ReadGuard<'tcx, Definitions> {
1539 self.definitions.read()
1542 /// Note that this is *untracked* and should only be used within the query
1543 /// system if the result is otherwise tracked through queries
1545 pub fn source_span_untracked(self, def_id: LocalDefId) -> Span {
1546 self.untracked_resolutions.source_span.get(def_id).copied().unwrap_or(DUMMY_SP)
1550 pub fn with_stable_hashing_context<R>(
1552 f: impl FnOnce(StableHashingContext<'_>) -> R,
1554 let definitions = self.definitions_untracked();
1555 let hcx = StableHashingContext::new(
1559 &self.untracked_resolutions.source_span,
1564 pub fn serialize_query_result_cache(self, encoder: FileEncoder) -> FileEncodeResult {
1565 self.on_disk_cache.as_ref().map_or(Ok(0), |c| c.serialize(self, encoder))
1568 /// If `true`, we should use lazy normalization for constants, otherwise
1569 /// we still evaluate them eagerly.
1571 pub fn lazy_normalization(self) -> bool {
1572 let features = self.features();
1573 // Note: We only use lazy normalization for generic const expressions.
1574 features.generic_const_exprs
1578 pub fn local_crate_exports_generics(self) -> bool {
1579 debug_assert!(self.sess.opts.share_generics());
1581 self.sess.crate_types().iter().any(|crate_type| {
1583 CrateType::Executable
1584 | CrateType::Staticlib
1585 | CrateType::ProcMacro
1586 | CrateType::Cdylib => false,
1588 // FIXME rust-lang/rust#64319, rust-lang/rust#64872:
1589 // We want to block export of generics from dylibs,
1590 // but we must fix rust-lang/rust#65890 before we can
1591 // do that robustly.
1592 CrateType::Dylib => true,
1594 CrateType::Rlib => true,
1599 // Returns the `DefId` and the `BoundRegionKind` corresponding to the given region.
1600 pub fn is_suitable_region(self, region: Region<'tcx>) -> Option<FreeRegionInfo> {
1601 let (suitable_region_binding_scope, bound_region) = match *region {
1602 ty::ReFree(ref free_region) => {
1603 (free_region.scope.expect_local(), free_region.bound_region)
1605 ty::ReEarlyBound(ref ebr) => (
1606 self.local_parent(ebr.def_id.expect_local()),
1607 ty::BoundRegionKind::BrNamed(ebr.def_id, ebr.name),
1609 _ => return None, // not a free region
1612 let is_impl_item = match self.hir().find_by_def_id(suitable_region_binding_scope) {
1613 Some(Node::Item(..) | Node::TraitItem(..)) => false,
1614 Some(Node::ImplItem(..)) => {
1615 self.is_bound_region_in_impl_item(suitable_region_binding_scope)
1620 Some(FreeRegionInfo {
1621 def_id: suitable_region_binding_scope,
1622 boundregion: bound_region,
1627 /// Given a `DefId` for an `fn`, return all the `dyn` and `impl` traits in its return type.
1628 pub fn return_type_impl_or_dyn_traits(
1630 scope_def_id: LocalDefId,
1631 ) -> Vec<&'tcx hir::Ty<'tcx>> {
1632 let hir_id = self.hir().local_def_id_to_hir_id(scope_def_id);
1633 let Some(hir::FnDecl { output: hir::FnRetTy::Return(hir_output), .. }) = self.hir().fn_decl_by_hir_id(hir_id) else {
1637 let mut v = TraitObjectVisitor(vec![], self.hir());
1638 v.visit_ty(hir_output);
1642 pub fn return_type_impl_trait(self, scope_def_id: LocalDefId) -> Option<(Ty<'tcx>, Span)> {
1643 // `type_of()` will fail on these (#55796, #86483), so only allow `fn`s or closures.
1644 match self.hir().get_by_def_id(scope_def_id) {
1645 Node::Item(&hir::Item { kind: ItemKind::Fn(..), .. }) => {}
1646 Node::TraitItem(&hir::TraitItem { kind: TraitItemKind::Fn(..), .. }) => {}
1647 Node::ImplItem(&hir::ImplItem { kind: ImplItemKind::Fn(..), .. }) => {}
1648 Node::Expr(&hir::Expr { kind: ExprKind::Closure { .. }, .. }) => {}
1652 let ret_ty = self.type_of(scope_def_id);
1653 match ret_ty.kind() {
1654 ty::FnDef(_, _) => {
1655 let sig = ret_ty.fn_sig(self);
1656 let output = self.erase_late_bound_regions(sig.output());
1657 if output.is_impl_trait() {
1658 let hir_id = self.hir().local_def_id_to_hir_id(scope_def_id);
1659 let fn_decl = self.hir().fn_decl_by_hir_id(hir_id).unwrap();
1660 Some((output, fn_decl.output.span()))
1669 // Checks if the bound region is in Impl Item.
1670 pub fn is_bound_region_in_impl_item(self, suitable_region_binding_scope: LocalDefId) -> bool {
1671 let container_id = self.parent(suitable_region_binding_scope.to_def_id());
1672 if self.impl_trait_ref(container_id).is_some() {
1673 // For now, we do not try to target impls of traits. This is
1674 // because this message is going to suggest that the user
1675 // change the fn signature, but they may not be free to do so,
1676 // since the signature must match the trait.
1678 // FIXME(#42706) -- in some cases, we could do better here.
1684 /// Determines whether identifiers in the assembly have strict naming rules.
1685 /// Currently, only NVPTX* targets need it.
1686 pub fn has_strict_asm_symbol_naming(self) -> bool {
1687 self.sess.target.arch.contains("nvptx")
1690 /// Returns `&'static core::panic::Location<'static>`.
1691 pub fn caller_location_ty(self) -> Ty<'tcx> {
1693 self.lifetimes.re_static,
1694 self.bound_type_of(self.require_lang_item(LangItem::PanicLocation, None))
1695 .subst(self, self.mk_substs([self.lifetimes.re_static.into()].iter())),
1699 /// Returns a displayable description and article for the given `def_id` (e.g. `("a", "struct")`).
1700 pub fn article_and_description(self, def_id: DefId) -> (&'static str, &'static str) {
1701 match self.def_kind(def_id) {
1702 DefKind::Generator => match self.generator_kind(def_id).unwrap() {
1703 rustc_hir::GeneratorKind::Async(..) => ("an", "async closure"),
1704 rustc_hir::GeneratorKind::Gen => ("a", "generator"),
1706 def_kind => (def_kind.article(), def_kind.descr(def_id)),
1710 pub fn type_length_limit(self) -> Limit {
1711 self.limits(()).type_length_limit
1714 pub fn recursion_limit(self) -> Limit {
1715 self.limits(()).recursion_limit
1718 pub fn move_size_limit(self) -> Limit {
1719 self.limits(()).move_size_limit
1722 pub fn const_eval_limit(self) -> Limit {
1723 self.limits(()).const_eval_limit
1726 pub fn all_traits(self) -> impl Iterator<Item = DefId> + 'tcx {
1727 iter::once(LOCAL_CRATE)
1728 .chain(self.crates(()).iter().copied())
1729 .flat_map(move |cnum| self.traits_in_crate(cnum).iter().copied())
1733 /// A trait implemented for all `X<'a>` types that can be safely and
1734 /// efficiently converted to `X<'tcx>` as long as they are part of the
1735 /// provided `TyCtxt<'tcx>`.
1736 /// This can be done, for example, for `Ty<'tcx>` or `SubstsRef<'tcx>`
1737 /// by looking them up in their respective interners.
1739 /// However, this is still not the best implementation as it does
1740 /// need to compare the components, even for interned values.
1741 /// It would be more efficient if `TypedArena` provided a way to
1742 /// determine whether the address is in the allocated range.
1744 /// `None` is returned if the value or one of the components is not part
1745 /// of the provided context.
1746 /// For `Ty`, `None` can be returned if either the type interner doesn't
1747 /// contain the `TyKind` key or if the address of the interned
1748 /// pointer differs. The latter case is possible if a primitive type,
1749 /// e.g., `()` or `u8`, was interned in a different context.
1750 pub trait Lift<'tcx>: fmt::Debug {
1751 type Lifted: fmt::Debug + 'tcx;
1752 fn lift_to_tcx(self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted>;
1755 macro_rules! nop_lift {
1756 ($set:ident; $ty:ty => $lifted:ty) => {
1757 impl<'a, 'tcx> Lift<'tcx> for $ty {
1758 type Lifted = $lifted;
1759 fn lift_to_tcx(self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
1760 if tcx.interners.$set.contains_pointer_to(&InternedInSet(&*self.0.0)) {
1761 // SAFETY: `self` is interned and therefore valid
1762 // for the entire lifetime of the `TyCtxt`.
1763 Some(unsafe { mem::transmute(self) })
1772 // Can't use the macros as we have reuse the `substs` here.
1774 // See `intern_type_list` for more info.
1775 impl<'a, 'tcx> Lift<'tcx> for &'a List<Ty<'a>> {
1776 type Lifted = &'tcx List<Ty<'tcx>>;
1777 fn lift_to_tcx(self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
1778 if self.is_empty() {
1779 return Some(List::empty());
1781 if tcx.interners.substs.contains_pointer_to(&InternedInSet(self.as_substs())) {
1782 // SAFETY: `self` is interned and therefore valid
1783 // for the entire lifetime of the `TyCtxt`.
1784 Some(unsafe { mem::transmute::<&'a List<Ty<'a>>, &'tcx List<Ty<'tcx>>>(self) })
1791 macro_rules! nop_list_lift {
1792 ($set:ident; $ty:ty => $lifted:ty) => {
1793 impl<'a, 'tcx> Lift<'tcx> for &'a List<$ty> {
1794 type Lifted = &'tcx List<$lifted>;
1795 fn lift_to_tcx(self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
1796 if self.is_empty() {
1797 return Some(List::empty());
1799 if tcx.interners.$set.contains_pointer_to(&InternedInSet(self)) {
1800 Some(unsafe { mem::transmute(self) })
1809 nop_lift! {type_; Ty<'a> => Ty<'tcx>}
1810 nop_lift! {region; Region<'a> => Region<'tcx>}
1811 nop_lift! {const_; Const<'a> => Const<'tcx>}
1812 nop_lift! {const_allocation; ConstAllocation<'a> => ConstAllocation<'tcx>}
1813 nop_lift! {predicate; Predicate<'a> => Predicate<'tcx>}
1815 nop_list_lift! {poly_existential_predicates; ty::Binder<'a, ExistentialPredicate<'a>> => ty::Binder<'tcx, ExistentialPredicate<'tcx>>}
1816 nop_list_lift! {predicates; Predicate<'a> => Predicate<'tcx>}
1817 nop_list_lift! {canonical_var_infos; CanonicalVarInfo<'a> => CanonicalVarInfo<'tcx>}
1818 nop_list_lift! {projs; ProjectionKind => ProjectionKind}
1819 nop_list_lift! {bound_variable_kinds; ty::BoundVariableKind => ty::BoundVariableKind}
1821 // This is the impl for `&'a InternalSubsts<'a>`.
1822 nop_list_lift! {substs; GenericArg<'a> => GenericArg<'tcx>}
1824 CloneLiftImpls! { for<'tcx> { Constness, traits::WellFormedLoc, } }
1827 use super::{ptr_eq, GlobalCtxt, TyCtxt};
1829 use crate::dep_graph::TaskDepsRef;
1830 use crate::ty::query;
1831 use rustc_data_structures::sync::{self, Lock};
1832 use rustc_errors::Diagnostic;
1834 use thin_vec::ThinVec;
1836 #[cfg(not(parallel_compiler))]
1837 use std::cell::Cell;
1839 #[cfg(parallel_compiler)]
1840 use rustc_rayon_core as rayon_core;
1842 /// This is the implicit state of rustc. It contains the current
1843 /// `TyCtxt` and query. It is updated when creating a local interner or
1844 /// executing a new query. Whenever there's a `TyCtxt` value available
1845 /// you should also have access to an `ImplicitCtxt` through the functions
1848 pub struct ImplicitCtxt<'a, 'tcx> {
1849 /// The current `TyCtxt`.
1850 pub tcx: TyCtxt<'tcx>,
1852 /// The current query job, if any. This is updated by `JobOwner::start` in
1853 /// `ty::query::plumbing` when executing a query.
1854 pub query: Option<query::QueryJobId>,
1856 /// Where to store diagnostics for the current query job, if any.
1857 /// This is updated by `JobOwner::start` in `ty::query::plumbing` when executing a query.
1858 pub diagnostics: Option<&'a Lock<ThinVec<Diagnostic>>>,
1860 /// Used to prevent queries from calling too deeply.
1861 pub query_depth: usize,
1863 /// The current dep graph task. This is used to add dependencies to queries
1864 /// when executing them.
1865 pub task_deps: TaskDepsRef<'a>,
1868 impl<'a, 'tcx> ImplicitCtxt<'a, 'tcx> {
1869 pub fn new(gcx: &'tcx GlobalCtxt<'tcx>) -> Self {
1870 let tcx = TyCtxt { gcx };
1876 task_deps: TaskDepsRef::Ignore,
1881 /// Sets Rayon's thread-local variable, which is preserved for Rayon jobs
1882 /// to `value` during the call to `f`. It is restored to its previous value after.
1883 /// This is used to set the pointer to the new `ImplicitCtxt`.
1884 #[cfg(parallel_compiler)]
1886 fn set_tlv<F: FnOnce() -> R, R>(value: usize, f: F) -> R {
1887 rayon_core::tlv::with(value, f)
1890 /// Gets Rayon's thread-local variable, which is preserved for Rayon jobs.
1891 /// This is used to get the pointer to the current `ImplicitCtxt`.
1892 #[cfg(parallel_compiler)]
1894 pub fn get_tlv() -> usize {
1895 rayon_core::tlv::get()
1898 #[cfg(not(parallel_compiler))]
1900 /// A thread local variable that stores a pointer to the current `ImplicitCtxt`.
1901 static TLV: Cell<usize> = const { Cell::new(0) };
1904 /// Sets TLV to `value` during the call to `f`.
1905 /// It is restored to its previous value after.
1906 /// This is used to set the pointer to the new `ImplicitCtxt`.
1907 #[cfg(not(parallel_compiler))]
1909 fn set_tlv<F: FnOnce() -> R, R>(value: usize, f: F) -> R {
1910 let old = get_tlv();
1911 let _reset = rustc_data_structures::OnDrop(move || TLV.with(|tlv| tlv.set(old)));
1912 TLV.with(|tlv| tlv.set(value));
1916 /// Gets the pointer to the current `ImplicitCtxt`.
1917 #[cfg(not(parallel_compiler))]
1919 fn get_tlv() -> usize {
1920 TLV.with(|tlv| tlv.get())
1923 /// Sets `context` as the new current `ImplicitCtxt` for the duration of the function `f`.
1925 pub fn enter_context<'a, 'tcx, F, R>(context: &ImplicitCtxt<'a, 'tcx>, f: F) -> R
1927 F: FnOnce(&ImplicitCtxt<'a, 'tcx>) -> R,
1929 set_tlv(context as *const _ as usize, || f(&context))
1932 /// Allows access to the current `ImplicitCtxt` in a closure if one is available.
1934 pub fn with_context_opt<F, R>(f: F) -> R
1936 F: for<'a, 'tcx> FnOnce(Option<&ImplicitCtxt<'a, 'tcx>>) -> R,
1938 let context = get_tlv();
1942 // We could get an `ImplicitCtxt` pointer from another thread.
1943 // Ensure that `ImplicitCtxt` is `Sync`.
1944 sync::assert_sync::<ImplicitCtxt<'_, '_>>();
1946 unsafe { f(Some(&*(context as *const ImplicitCtxt<'_, '_>))) }
1950 /// Allows access to the current `ImplicitCtxt`.
1951 /// Panics if there is no `ImplicitCtxt` available.
1953 pub fn with_context<F, R>(f: F) -> R
1955 F: for<'a, 'tcx> FnOnce(&ImplicitCtxt<'a, 'tcx>) -> R,
1957 with_context_opt(|opt_context| f(opt_context.expect("no ImplicitCtxt stored in tls")))
1960 /// Allows access to the current `ImplicitCtxt` whose tcx field is the same as the tcx argument
1961 /// passed in. This means the closure is given an `ImplicitCtxt` with the same `'tcx` lifetime
1962 /// as the `TyCtxt` passed in.
1963 /// This will panic if you pass it a `TyCtxt` which is different from the current
1964 /// `ImplicitCtxt`'s `tcx` field.
1966 pub fn with_related_context<'tcx, F, R>(tcx: TyCtxt<'tcx>, f: F) -> R
1968 F: FnOnce(&ImplicitCtxt<'_, 'tcx>) -> R,
1970 with_context(|context| unsafe {
1971 assert!(ptr_eq(context.tcx.gcx, tcx.gcx));
1972 let context: &ImplicitCtxt<'_, '_> = mem::transmute(context);
1977 /// Allows access to the `TyCtxt` in the current `ImplicitCtxt`.
1978 /// Panics if there is no `ImplicitCtxt` available.
1980 pub fn with<F, R>(f: F) -> R
1982 F: for<'tcx> FnOnce(TyCtxt<'tcx>) -> R,
1984 with_context(|context| f(context.tcx))
1987 /// Allows access to the `TyCtxt` in the current `ImplicitCtxt`.
1988 /// The closure is passed None if there is no `ImplicitCtxt` available.
1990 pub fn with_opt<F, R>(f: F) -> R
1992 F: for<'tcx> FnOnce(Option<TyCtxt<'tcx>>) -> R,
1994 with_context_opt(|opt_context| f(opt_context.map(|context| context.tcx)))
1998 macro_rules! sty_debug_print {
1999 ($fmt: expr, $ctxt: expr, $($variant: ident),*) => {{
2000 // Curious inner module to allow variant names to be used as
2002 #[allow(non_snake_case)]
2004 use crate::ty::{self, TyCtxt};
2005 use crate::ty::context::InternedInSet;
2007 #[derive(Copy, Clone)]
2016 pub fn go(fmt: &mut std::fmt::Formatter<'_>, tcx: TyCtxt<'_>) -> std::fmt::Result {
2017 let mut total = DebugStat {
2024 $(let mut $variant = total;)*
2026 let shards = tcx.interners.type_.lock_shards();
2027 let types = shards.iter().flat_map(|shard| shard.keys());
2028 for &InternedInSet(t) in types {
2029 let variant = match t.kind {
2030 ty::Bool | ty::Char | ty::Int(..) | ty::Uint(..) |
2031 ty::Float(..) | ty::Str | ty::Never => continue,
2032 ty::Error(_) => /* unimportant */ continue,
2033 $(ty::$variant(..) => &mut $variant,)*
2035 let lt = t.flags.intersects(ty::TypeFlags::HAS_RE_INFER);
2036 let ty = t.flags.intersects(ty::TypeFlags::HAS_TY_INFER);
2037 let ct = t.flags.intersects(ty::TypeFlags::HAS_CT_INFER);
2041 if lt { total.lt_infer += 1; variant.lt_infer += 1 }
2042 if ty { total.ty_infer += 1; variant.ty_infer += 1 }
2043 if ct { total.ct_infer += 1; variant.ct_infer += 1 }
2044 if lt && ty && ct { total.all_infer += 1; variant.all_infer += 1 }
2046 writeln!(fmt, "Ty interner total ty lt ct all")?;
2047 $(writeln!(fmt, " {:18}: {uses:6} {usespc:4.1}%, \
2048 {ty:4.1}% {lt:5.1}% {ct:4.1}% {all:4.1}%",
2049 stringify!($variant),
2050 uses = $variant.total,
2051 usespc = $variant.total as f64 * 100.0 / total.total as f64,
2052 ty = $variant.ty_infer as f64 * 100.0 / total.total as f64,
2053 lt = $variant.lt_infer as f64 * 100.0 / total.total as f64,
2054 ct = $variant.ct_infer as f64 * 100.0 / total.total as f64,
2055 all = $variant.all_infer as f64 * 100.0 / total.total as f64)?;
2057 writeln!(fmt, " total {uses:6} \
2058 {ty:4.1}% {lt:5.1}% {ct:4.1}% {all:4.1}%",
2060 ty = total.ty_infer as f64 * 100.0 / total.total as f64,
2061 lt = total.lt_infer as f64 * 100.0 / total.total as f64,
2062 ct = total.ct_infer as f64 * 100.0 / total.total as f64,
2063 all = total.all_infer as f64 * 100.0 / total.total as f64)
2067 inner::go($fmt, $ctxt)
2071 impl<'tcx> TyCtxt<'tcx> {
2072 pub fn debug_stats(self) -> impl std::fmt::Debug + 'tcx {
2073 struct DebugStats<'tcx>(TyCtxt<'tcx>);
2075 impl<'tcx> std::fmt::Debug for DebugStats<'tcx> {
2076 fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2101 writeln!(fmt, "InternalSubsts interner: #{}", self.0.interners.substs.len())?;
2102 writeln!(fmt, "Region interner: #{}", self.0.interners.region.len())?;
2105 "Const Allocation interner: #{}",
2106 self.0.interners.const_allocation.len()
2108 writeln!(fmt, "Layout interner: #{}", self.0.interners.layout.len())?;
2118 // This type holds a `T` in the interner. The `T` is stored in the arena and
2119 // this type just holds a pointer to it, but it still effectively owns it. It
2120 // impls `Borrow` so that it can be looked up using the original
2121 // (non-arena-memory-owning) types.
2122 struct InternedInSet<'tcx, T: ?Sized>(&'tcx T);
2124 impl<'tcx, T: 'tcx + ?Sized> Clone for InternedInSet<'tcx, T> {
2125 fn clone(&self) -> Self {
2126 InternedInSet(self.0)
2130 impl<'tcx, T: 'tcx + ?Sized> Copy for InternedInSet<'tcx, T> {}
2132 impl<'tcx, T: 'tcx + ?Sized> IntoPointer for InternedInSet<'tcx, T> {
2133 fn into_pointer(&self) -> *const () {
2134 self.0 as *const _ as *const ()
2138 #[allow(rustc::usage_of_ty_tykind)]
2139 impl<'tcx> Borrow<TyKind<'tcx>> for InternedInSet<'tcx, WithStableHash<TyS<'tcx>>> {
2140 fn borrow<'a>(&'a self) -> &'a TyKind<'tcx> {
2145 impl<'tcx> PartialEq for InternedInSet<'tcx, WithStableHash<TyS<'tcx>>> {
2146 fn eq(&self, other: &InternedInSet<'tcx, WithStableHash<TyS<'tcx>>>) -> bool {
2147 // The `Borrow` trait requires that `x.borrow() == y.borrow()` equals
2149 self.0.kind == other.0.kind
2153 impl<'tcx> Eq for InternedInSet<'tcx, WithStableHash<TyS<'tcx>>> {}
2155 impl<'tcx> Hash for InternedInSet<'tcx, WithStableHash<TyS<'tcx>>> {
2156 fn hash<H: Hasher>(&self, s: &mut H) {
2157 // The `Borrow` trait requires that `x.borrow().hash(s) == x.hash(s)`.
2162 impl<'tcx> Borrow<Binder<'tcx, PredicateKind<'tcx>>> for InternedInSet<'tcx, PredicateS<'tcx>> {
2163 fn borrow<'a>(&'a self) -> &'a Binder<'tcx, PredicateKind<'tcx>> {
2168 impl<'tcx> PartialEq for InternedInSet<'tcx, PredicateS<'tcx>> {
2169 fn eq(&self, other: &InternedInSet<'tcx, PredicateS<'tcx>>) -> bool {
2170 // The `Borrow` trait requires that `x.borrow() == y.borrow()` equals
2172 self.0.kind == other.0.kind
2176 impl<'tcx> Eq for InternedInSet<'tcx, PredicateS<'tcx>> {}
2178 impl<'tcx> Hash for InternedInSet<'tcx, PredicateS<'tcx>> {
2179 fn hash<H: Hasher>(&self, s: &mut H) {
2180 // The `Borrow` trait requires that `x.borrow().hash(s) == x.hash(s)`.
2185 impl<'tcx, T> Borrow<[T]> for InternedInSet<'tcx, List<T>> {
2186 fn borrow<'a>(&'a self) -> &'a [T] {
2191 impl<'tcx, T: PartialEq> PartialEq for InternedInSet<'tcx, List<T>> {
2192 fn eq(&self, other: &InternedInSet<'tcx, List<T>>) -> bool {
2193 // The `Borrow` trait requires that `x.borrow() == y.borrow()` equals
2195 self.0[..] == other.0[..]
2199 impl<'tcx, T: Eq> Eq for InternedInSet<'tcx, List<T>> {}
2201 impl<'tcx, T: Hash> Hash for InternedInSet<'tcx, List<T>> {
2202 fn hash<H: Hasher>(&self, s: &mut H) {
2203 // The `Borrow` trait requires that `x.borrow().hash(s) == x.hash(s)`.
2208 macro_rules! direct_interners {
2209 ($($name:ident: $method:ident($ty:ty): $ret_ctor:ident -> $ret_ty:ty,)+) => {
2210 $(impl<'tcx> Borrow<$ty> for InternedInSet<'tcx, $ty> {
2211 fn borrow<'a>(&'a self) -> &'a $ty {
2216 impl<'tcx> PartialEq for InternedInSet<'tcx, $ty> {
2217 fn eq(&self, other: &Self) -> bool {
2218 // The `Borrow` trait requires that `x.borrow() == y.borrow()`
2224 impl<'tcx> Eq for InternedInSet<'tcx, $ty> {}
2226 impl<'tcx> Hash for InternedInSet<'tcx, $ty> {
2227 fn hash<H: Hasher>(&self, s: &mut H) {
2228 // The `Borrow` trait requires that `x.borrow().hash(s) ==
2234 impl<'tcx> TyCtxt<'tcx> {
2235 pub fn $method(self, v: $ty) -> $ret_ty {
2236 $ret_ctor(Interned::new_unchecked(self.interners.$name.intern(v, |v| {
2237 InternedInSet(self.interners.arena.alloc(v))
2245 region: mk_region(RegionKind<'tcx>): Region -> Region<'tcx>,
2246 const_: mk_const(ConstS<'tcx>): Const -> Const<'tcx>,
2247 const_allocation: intern_const_alloc(Allocation): ConstAllocation -> ConstAllocation<'tcx>,
2248 layout: intern_layout(LayoutS<'tcx>): Layout -> Layout<'tcx>,
2249 adt_def: intern_adt_def(AdtDefData): AdtDef -> AdtDef<'tcx>,
2252 macro_rules! slice_interners {
2253 ($($field:ident: $method:ident($ty:ty)),+ $(,)?) => (
2254 impl<'tcx> TyCtxt<'tcx> {
2255 $(pub fn $method(self, v: &[$ty]) -> &'tcx List<$ty> {
2256 self.interners.$field.intern_ref(v, || {
2257 InternedInSet(List::from_arena(&*self.arena, v))
2265 substs: _intern_substs(GenericArg<'tcx>),
2266 canonical_var_infos: _intern_canonical_var_infos(CanonicalVarInfo<'tcx>),
2267 poly_existential_predicates:
2268 _intern_poly_existential_predicates(ty::Binder<'tcx, ExistentialPredicate<'tcx>>),
2269 predicates: _intern_predicates(Predicate<'tcx>),
2270 projs: _intern_projs(ProjectionKind),
2271 place_elems: _intern_place_elems(PlaceElem<'tcx>),
2272 bound_variable_kinds: _intern_bound_variable_kinds(ty::BoundVariableKind),
2275 impl<'tcx> TyCtxt<'tcx> {
2276 /// Given a `fn` type, returns an equivalent `unsafe fn` type;
2277 /// that is, a `fn` type that is equivalent in every way for being
2279 pub fn safe_to_unsafe_fn_ty(self, sig: PolyFnSig<'tcx>) -> Ty<'tcx> {
2280 assert_eq!(sig.unsafety(), hir::Unsafety::Normal);
2281 self.mk_fn_ptr(sig.map_bound(|sig| ty::FnSig { unsafety: hir::Unsafety::Unsafe, ..sig }))
2284 /// Given the def_id of a Trait `trait_def_id` and the name of an associated item `assoc_name`
2285 /// returns true if the `trait_def_id` defines an associated item of name `assoc_name`.
2286 pub fn trait_may_define_assoc_type(self, trait_def_id: DefId, assoc_name: Ident) -> bool {
2287 self.super_traits_of(trait_def_id).any(|trait_did| {
2288 self.associated_items(trait_did)
2289 .find_by_name_and_kind(self, assoc_name, ty::AssocKind::Type, trait_did)
2294 /// Given a `ty`, return whether it's an `impl Future<...>`.
2295 pub fn ty_is_opaque_future(self, ty: Ty<'_>) -> bool {
2296 let ty::Opaque(def_id, _) = ty.kind() else { return false };
2297 let future_trait = self.lang_items().future_trait().unwrap();
2299 self.explicit_item_bounds(def_id).iter().any(|(predicate, _)| {
2300 let ty::PredicateKind::Trait(trait_predicate) = predicate.kind().skip_binder() else {
2303 trait_predicate.trait_ref.def_id == future_trait
2304 && trait_predicate.polarity == ImplPolarity::Positive
2308 /// Computes the def-ids of the transitive supertraits of `trait_def_id`. This (intentionally)
2309 /// does not compute the full elaborated super-predicates but just the set of def-ids. It is used
2310 /// to identify which traits may define a given associated type to help avoid cycle errors.
2311 /// Returns a `DefId` iterator.
2312 fn super_traits_of(self, trait_def_id: DefId) -> impl Iterator<Item = DefId> + 'tcx {
2313 let mut set = FxHashSet::default();
2314 let mut stack = vec![trait_def_id];
2316 set.insert(trait_def_id);
2318 iter::from_fn(move || -> Option<DefId> {
2319 let trait_did = stack.pop()?;
2320 let generic_predicates = self.super_predicates_of(trait_did);
2322 for (predicate, _) in generic_predicates.predicates {
2323 if let ty::PredicateKind::Trait(data) = predicate.kind().skip_binder() {
2324 if set.insert(data.def_id()) {
2325 stack.push(data.def_id());
2334 /// Given a closure signature, returns an equivalent fn signature. Detuples
2335 /// and so forth -- so e.g., if we have a sig with `Fn<(u32, i32)>` then
2336 /// you would get a `fn(u32, i32)`.
2337 /// `unsafety` determines the unsafety of the fn signature. If you pass
2338 /// `hir::Unsafety::Unsafe` in the previous example, then you would get
2339 /// an `unsafe fn (u32, i32)`.
2340 /// It cannot convert a closure that requires unsafe.
2341 pub fn signature_unclosure(
2343 sig: PolyFnSig<'tcx>,
2344 unsafety: hir::Unsafety,
2345 ) -> PolyFnSig<'tcx> {
2347 let params_iter = match s.inputs()[0].kind() {
2348 ty::Tuple(params) => params.into_iter(),
2351 self.mk_fn_sig(params_iter, s.output(), s.c_variadic, unsafety, abi::Abi::Rust)
2355 /// Same a `self.mk_region(kind)`, but avoids accessing the interners if
2358 pub fn reuse_or_mk_region(self, r: Region<'tcx>, kind: RegionKind<'tcx>) -> Region<'tcx> {
2359 if *r == kind { r } else { self.mk_region(kind) }
2362 #[allow(rustc::usage_of_ty_tykind)]
2364 pub fn mk_ty(self, st: TyKind<'tcx>) -> Ty<'tcx> {
2365 self.interners.intern_ty(
2368 &self.definitions.read(),
2370 // This is only used to create a stable hashing context.
2371 &self.untracked_resolutions.source_span,
2376 pub fn mk_predicate(self, binder: Binder<'tcx, PredicateKind<'tcx>>) -> Predicate<'tcx> {
2377 self.interners.intern_predicate(binder)
2381 pub fn reuse_or_mk_predicate(
2383 pred: Predicate<'tcx>,
2384 binder: Binder<'tcx, PredicateKind<'tcx>>,
2385 ) -> Predicate<'tcx> {
2386 if pred.kind() != binder { self.mk_predicate(binder) } else { pred }
2389 pub fn mk_mach_int(self, tm: IntTy) -> Ty<'tcx> {
2391 IntTy::Isize => self.types.isize,
2392 IntTy::I8 => self.types.i8,
2393 IntTy::I16 => self.types.i16,
2394 IntTy::I32 => self.types.i32,
2395 IntTy::I64 => self.types.i64,
2396 IntTy::I128 => self.types.i128,
2400 pub fn mk_mach_uint(self, tm: UintTy) -> Ty<'tcx> {
2402 UintTy::Usize => self.types.usize,
2403 UintTy::U8 => self.types.u8,
2404 UintTy::U16 => self.types.u16,
2405 UintTy::U32 => self.types.u32,
2406 UintTy::U64 => self.types.u64,
2407 UintTy::U128 => self.types.u128,
2411 pub fn mk_mach_float(self, tm: FloatTy) -> Ty<'tcx> {
2413 FloatTy::F32 => self.types.f32,
2414 FloatTy::F64 => self.types.f64,
2419 pub fn mk_static_str(self) -> Ty<'tcx> {
2420 self.mk_imm_ref(self.lifetimes.re_static, self.types.str_)
2424 pub fn mk_adt(self, def: AdtDef<'tcx>, substs: SubstsRef<'tcx>) -> Ty<'tcx> {
2425 // Take a copy of substs so that we own the vectors inside.
2426 self.mk_ty(Adt(def, substs))
2430 pub fn mk_foreign(self, def_id: DefId) -> Ty<'tcx> {
2431 self.mk_ty(Foreign(def_id))
2434 fn mk_generic_adt(self, wrapper_def_id: DefId, ty_param: Ty<'tcx>) -> Ty<'tcx> {
2435 let adt_def = self.adt_def(wrapper_def_id);
2437 InternalSubsts::for_item(self, wrapper_def_id, |param, substs| match param.kind {
2438 GenericParamDefKind::Lifetime | GenericParamDefKind::Const { .. } => bug!(),
2439 GenericParamDefKind::Type { has_default, .. } => {
2440 if param.index == 0 {
2443 assert!(has_default);
2444 self.bound_type_of(param.def_id).subst(self, substs).into()
2448 self.mk_ty(Adt(adt_def, substs))
2452 pub fn mk_box(self, ty: Ty<'tcx>) -> Ty<'tcx> {
2453 let def_id = self.require_lang_item(LangItem::OwnedBox, None);
2454 self.mk_generic_adt(def_id, ty)
2458 pub fn mk_lang_item(self, ty: Ty<'tcx>, item: LangItem) -> Option<Ty<'tcx>> {
2459 let def_id = self.lang_items().require(item).ok()?;
2460 Some(self.mk_generic_adt(def_id, ty))
2464 pub fn mk_diagnostic_item(self, ty: Ty<'tcx>, name: Symbol) -> Option<Ty<'tcx>> {
2465 let def_id = self.get_diagnostic_item(name)?;
2466 Some(self.mk_generic_adt(def_id, ty))
2470 pub fn mk_maybe_uninit(self, ty: Ty<'tcx>) -> Ty<'tcx> {
2471 let def_id = self.require_lang_item(LangItem::MaybeUninit, None);
2472 self.mk_generic_adt(def_id, ty)
2476 pub fn mk_ptr(self, tm: TypeAndMut<'tcx>) -> Ty<'tcx> {
2477 self.mk_ty(RawPtr(tm))
2481 pub fn mk_ref(self, r: Region<'tcx>, tm: TypeAndMut<'tcx>) -> Ty<'tcx> {
2482 self.mk_ty(Ref(r, tm.ty, tm.mutbl))
2486 pub fn mk_mut_ref(self, r: Region<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
2487 self.mk_ref(r, TypeAndMut { ty, mutbl: hir::Mutability::Mut })
2491 pub fn mk_imm_ref(self, r: Region<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
2492 self.mk_ref(r, TypeAndMut { ty, mutbl: hir::Mutability::Not })
2496 pub fn mk_mut_ptr(self, ty: Ty<'tcx>) -> Ty<'tcx> {
2497 self.mk_ptr(TypeAndMut { ty, mutbl: hir::Mutability::Mut })
2501 pub fn mk_imm_ptr(self, ty: Ty<'tcx>) -> Ty<'tcx> {
2502 self.mk_ptr(TypeAndMut { ty, mutbl: hir::Mutability::Not })
2506 pub fn mk_array(self, ty: Ty<'tcx>, n: u64) -> Ty<'tcx> {
2507 self.mk_ty(Array(ty, ty::Const::from_usize(self, n)))
2511 pub fn mk_slice(self, ty: Ty<'tcx>) -> Ty<'tcx> {
2512 self.mk_ty(Slice(ty))
2516 pub fn intern_tup(self, ts: &[Ty<'tcx>]) -> Ty<'tcx> {
2517 self.mk_ty(Tuple(self.intern_type_list(&ts)))
2520 pub fn mk_tup<I: InternAs<[Ty<'tcx>], Ty<'tcx>>>(self, iter: I) -> I::Output {
2521 iter.intern_with(|ts| self.mk_ty(Tuple(self.intern_type_list(&ts))))
2525 pub fn mk_unit(self) -> Ty<'tcx> {
2530 pub fn mk_diverging_default(self) -> Ty<'tcx> {
2531 if self.features().never_type_fallback { self.types.never } else { self.types.unit }
2535 pub fn mk_fn_def(self, def_id: DefId, substs: SubstsRef<'tcx>) -> Ty<'tcx> {
2536 self.mk_ty(FnDef(def_id, substs))
2540 pub fn mk_fn_ptr(self, fty: PolyFnSig<'tcx>) -> Ty<'tcx> {
2541 self.mk_ty(FnPtr(fty))
2547 obj: &'tcx List<ty::Binder<'tcx, ExistentialPredicate<'tcx>>>,
2548 reg: ty::Region<'tcx>,
2550 self.mk_ty(Dynamic(obj, reg))
2554 pub fn mk_projection(self, item_def_id: DefId, substs: SubstsRef<'tcx>) -> Ty<'tcx> {
2555 self.mk_ty(Projection(ProjectionTy { item_def_id, substs }))
2559 pub fn mk_closure(self, closure_id: DefId, closure_substs: SubstsRef<'tcx>) -> Ty<'tcx> {
2560 self.mk_ty(Closure(closure_id, closure_substs))
2564 pub fn mk_generator(
2567 generator_substs: SubstsRef<'tcx>,
2568 movability: hir::Movability,
2570 self.mk_ty(Generator(id, generator_substs, movability))
2574 pub fn mk_generator_witness(self, types: ty::Binder<'tcx, &'tcx List<Ty<'tcx>>>) -> Ty<'tcx> {
2575 self.mk_ty(GeneratorWitness(types))
2579 pub fn mk_ty_var(self, v: TyVid) -> Ty<'tcx> {
2580 self.mk_ty_infer(TyVar(v))
2584 pub fn mk_const_var(self, v: ConstVid<'tcx>, ty: Ty<'tcx>) -> Const<'tcx> {
2585 self.mk_const(ty::ConstS { kind: ty::ConstKind::Infer(InferConst::Var(v)), ty })
2589 pub fn mk_int_var(self, v: IntVid) -> Ty<'tcx> {
2590 self.mk_ty_infer(IntVar(v))
2594 pub fn mk_float_var(self, v: FloatVid) -> Ty<'tcx> {
2595 self.mk_ty_infer(FloatVar(v))
2599 pub fn mk_ty_infer(self, it: InferTy) -> Ty<'tcx> {
2600 self.mk_ty(Infer(it))
2604 pub fn mk_const_infer(self, ic: InferConst<'tcx>, ty: Ty<'tcx>) -> ty::Const<'tcx> {
2605 self.mk_const(ty::ConstS { kind: ty::ConstKind::Infer(ic), ty })
2609 pub fn mk_ty_param(self, index: u32, name: Symbol) -> Ty<'tcx> {
2610 self.mk_ty(Param(ParamTy { index, name }))
2614 pub fn mk_const_param(self, index: u32, name: Symbol, ty: Ty<'tcx>) -> Const<'tcx> {
2615 self.mk_const(ty::ConstS { kind: ty::ConstKind::Param(ParamConst { index, name }), ty })
2618 pub fn mk_param_from_def(self, param: &ty::GenericParamDef) -> GenericArg<'tcx> {
2620 GenericParamDefKind::Lifetime => {
2621 self.mk_region(ty::ReEarlyBound(param.to_early_bound_region_data())).into()
2623 GenericParamDefKind::Type { .. } => self.mk_ty_param(param.index, param.name).into(),
2624 GenericParamDefKind::Const { .. } => {
2625 self.mk_const_param(param.index, param.name, self.type_of(param.def_id)).into()
2631 pub fn mk_opaque(self, def_id: DefId, substs: SubstsRef<'tcx>) -> Ty<'tcx> {
2632 self.mk_ty(Opaque(def_id, substs))
2635 pub fn mk_place_field(self, place: Place<'tcx>, f: Field, ty: Ty<'tcx>) -> Place<'tcx> {
2636 self.mk_place_elem(place, PlaceElem::Field(f, ty))
2639 pub fn mk_place_deref(self, place: Place<'tcx>) -> Place<'tcx> {
2640 self.mk_place_elem(place, PlaceElem::Deref)
2643 pub fn mk_place_downcast(
2646 adt_def: AdtDef<'tcx>,
2647 variant_index: VariantIdx,
2651 PlaceElem::Downcast(Some(adt_def.variant(variant_index).name), variant_index),
2655 pub fn mk_place_downcast_unnamed(
2658 variant_index: VariantIdx,
2660 self.mk_place_elem(place, PlaceElem::Downcast(None, variant_index))
2663 pub fn mk_place_index(self, place: Place<'tcx>, index: Local) -> Place<'tcx> {
2664 self.mk_place_elem(place, PlaceElem::Index(index))
2667 /// This method copies `Place`'s projection, add an element and reintern it. Should not be used
2668 /// to build a full `Place` it's just a convenient way to grab a projection and modify it in
2670 pub fn mk_place_elem(self, place: Place<'tcx>, elem: PlaceElem<'tcx>) -> Place<'tcx> {
2671 let mut projection = place.projection.to_vec();
2672 projection.push(elem);
2674 Place { local: place.local, projection: self.intern_place_elems(&projection) }
2677 pub fn intern_poly_existential_predicates(
2679 eps: &[ty::Binder<'tcx, ExistentialPredicate<'tcx>>],
2680 ) -> &'tcx List<ty::Binder<'tcx, ExistentialPredicate<'tcx>>> {
2681 assert!(!eps.is_empty());
2684 .all(|[a, b]| a.skip_binder().stable_cmp(self, &b.skip_binder())
2685 != Ordering::Greater)
2687 self._intern_poly_existential_predicates(eps)
2690 pub fn intern_predicates(self, preds: &[Predicate<'tcx>]) -> &'tcx List<Predicate<'tcx>> {
2691 // FIXME consider asking the input slice to be sorted to avoid
2692 // re-interning permutations, in which case that would be asserted
2694 if preds.is_empty() {
2695 // The macro-generated method below asserts we don't intern an empty slice.
2698 self._intern_predicates(preds)
2702 pub fn intern_type_list(self, ts: &[Ty<'tcx>]) -> &'tcx List<Ty<'tcx>> {
2706 // Actually intern type lists as lists of `GenericArg`s.
2708 // Transmuting from `Ty<'tcx>` to `GenericArg<'tcx>` is sound
2709 // as explained in ty_slice_as_generic_arg`. With this,
2710 // we guarantee that even when transmuting between `List<Ty<'tcx>>`
2711 // and `List<GenericArg<'tcx>>`, the uniqueness requirement for
2713 let substs = self._intern_substs(ty::subst::ty_slice_as_generic_args(ts));
2714 substs.try_as_type_list().unwrap()
2718 pub fn intern_substs(self, ts: &[GenericArg<'tcx>]) -> &'tcx List<GenericArg<'tcx>> {
2719 if ts.is_empty() { List::empty() } else { self._intern_substs(ts) }
2722 pub fn intern_projs(self, ps: &[ProjectionKind]) -> &'tcx List<ProjectionKind> {
2723 if ps.is_empty() { List::empty() } else { self._intern_projs(ps) }
2726 pub fn intern_place_elems(self, ts: &[PlaceElem<'tcx>]) -> &'tcx List<PlaceElem<'tcx>> {
2727 if ts.is_empty() { List::empty() } else { self._intern_place_elems(ts) }
2730 pub fn intern_canonical_var_infos(
2732 ts: &[CanonicalVarInfo<'tcx>],
2733 ) -> CanonicalVarInfos<'tcx> {
2734 if ts.is_empty() { List::empty() } else { self._intern_canonical_var_infos(ts) }
2737 pub fn intern_bound_variable_kinds(
2739 ts: &[ty::BoundVariableKind],
2740 ) -> &'tcx List<ty::BoundVariableKind> {
2741 if ts.is_empty() { List::empty() } else { self._intern_bound_variable_kinds(ts) }
2744 pub fn mk_fn_sig<I>(
2749 unsafety: hir::Unsafety,
2751 ) -> <I::Item as InternIteratorElement<Ty<'tcx>, ty::FnSig<'tcx>>>::Output
2753 I: Iterator<Item: InternIteratorElement<Ty<'tcx>, ty::FnSig<'tcx>>>,
2755 inputs.chain(iter::once(output)).intern_with(|xs| ty::FnSig {
2756 inputs_and_output: self.intern_type_list(xs),
2763 pub fn mk_poly_existential_predicates<
2765 [ty::Binder<'tcx, ExistentialPredicate<'tcx>>],
2766 &'tcx List<ty::Binder<'tcx, ExistentialPredicate<'tcx>>>,
2772 iter.intern_with(|xs| self.intern_poly_existential_predicates(xs))
2775 pub fn mk_predicates<I: InternAs<[Predicate<'tcx>], &'tcx List<Predicate<'tcx>>>>(
2779 iter.intern_with(|xs| self.intern_predicates(xs))
2782 pub fn mk_type_list<I: InternAs<[Ty<'tcx>], &'tcx List<Ty<'tcx>>>>(self, iter: I) -> I::Output {
2783 iter.intern_with(|xs| self.intern_type_list(xs))
2786 pub fn mk_substs<I: InternAs<[GenericArg<'tcx>], &'tcx List<GenericArg<'tcx>>>>(
2790 iter.intern_with(|xs| self.intern_substs(xs))
2793 pub fn mk_place_elems<I: InternAs<[PlaceElem<'tcx>], &'tcx List<PlaceElem<'tcx>>>>(
2797 iter.intern_with(|xs| self.intern_place_elems(xs))
2800 pub fn mk_substs_trait(self, self_ty: Ty<'tcx>, rest: &[GenericArg<'tcx>]) -> SubstsRef<'tcx> {
2801 self.mk_substs(iter::once(self_ty.into()).chain(rest.iter().cloned()))
2804 pub fn mk_bound_variable_kinds<
2805 I: InternAs<[ty::BoundVariableKind], &'tcx List<ty::BoundVariableKind>>,
2810 iter.intern_with(|xs| self.intern_bound_variable_kinds(xs))
2813 /// Walks upwards from `id` to find a node which might change lint levels with attributes.
2814 /// It stops at `bound` and just returns it if reached.
2815 pub fn maybe_lint_level_root_bounded(self, mut id: HirId, bound: HirId) -> HirId {
2816 let hir = self.hir();
2822 if hir.attrs(id).iter().any(|attr| Level::from_attr(attr).is_some()) {
2825 let next = hir.get_parent_node(id);
2827 bug!("lint traversal reached the root of the crate");
2833 pub fn lint_level_at_node(
2835 lint: &'static Lint,
2837 ) -> (Level, LintLevelSource) {
2838 let sets = self.lint_levels(());
2840 if let Some(pair) = sets.level_and_source(lint, id, self.sess) {
2843 let next = self.hir().get_parent_node(id);
2845 bug!("lint traversal reached the root of the crate");
2851 /// Emit a lint at `span` from a lint struct (some type that implements `DecorateLint`,
2852 /// typically generated by `#[derive(LintDiagnostic)]`).
2853 pub fn emit_spanned_lint(
2855 lint: &'static Lint,
2857 span: impl Into<MultiSpan>,
2858 decorator: impl for<'a> DecorateLint<'a, ()>,
2860 self.struct_span_lint_hir(lint, hir_id, span, |diag| decorator.decorate_lint(diag))
2863 pub fn struct_span_lint_hir(
2865 lint: &'static Lint,
2867 span: impl Into<MultiSpan>,
2868 decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a, ()>),
2870 let (level, src) = self.lint_level_at_node(lint, hir_id);
2871 struct_lint_level(self.sess, lint, level, src, Some(span.into()), decorate);
2874 /// Emit a lint from a lint struct (some type that implements `DecorateLint`, typically
2875 /// generated by `#[derive(LintDiagnostic)]`).
2878 lint: &'static Lint,
2880 decorator: impl for<'a> DecorateLint<'a, ()>,
2882 self.struct_lint_node(lint, id, |diag| decorator.decorate_lint(diag))
2885 pub fn struct_lint_node(
2887 lint: &'static Lint,
2889 decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a, ()>),
2891 let (level, src) = self.lint_level_at_node(lint, id);
2892 struct_lint_level(self.sess, lint, level, src, None, decorate);
2895 pub fn in_scope_traits(self, id: HirId) -> Option<&'tcx [TraitCandidate]> {
2896 let map = self.in_scope_traits_map(id.owner)?;
2897 let candidates = map.get(&id.local_id)?;
2901 pub fn named_region(self, id: HirId) -> Option<resolve_lifetime::Region> {
2902 debug!(?id, "named_region");
2903 self.named_region_map(id.owner).and_then(|map| map.get(&id.local_id).cloned())
2906 pub fn is_late_bound(self, id: HirId) -> bool {
2907 self.is_late_bound_map(id.owner).map_or(false, |set| {
2908 let def_id = self.hir().local_def_id(id);
2909 set.contains(&def_id)
2913 pub fn late_bound_vars(self, id: HirId) -> &'tcx List<ty::BoundVariableKind> {
2914 self.mk_bound_variable_kinds(
2915 self.late_bound_vars_map(id.owner)
2916 .and_then(|map| map.get(&id.local_id).cloned())
2917 .unwrap_or_else(|| {
2918 bug!("No bound vars found for {:?} ({:?})", self.hir().node_to_string(id), id)
2924 /// Whether the `def_id` counts as const fn in the current crate, considering all active
2926 pub fn is_const_fn(self, def_id: DefId) -> bool {
2927 if self.is_const_fn_raw(def_id) {
2928 match self.lookup_const_stability(def_id) {
2929 Some(stability) if stability.is_const_unstable() => {
2930 // has a `rustc_const_unstable` attribute, check whether the user enabled the
2931 // corresponding feature gate.
2933 .declared_lib_features
2935 .any(|&(sym, _)| sym == stability.feature)
2937 // functions without const stability are either stable user written
2938 // const fn or the user is using feature gates and we thus don't
2939 // care what they do
2947 /// Whether the trait impl is marked const. This does not consider stability or feature gates.
2948 pub fn is_const_trait_impl_raw(self, def_id: DefId) -> bool {
2949 let Some(local_def_id) = def_id.as_local() else { return false };
2950 let hir_id = self.local_def_id_to_hir_id(local_def_id);
2951 let node = self.hir().get(hir_id);
2955 hir::Node::Item(hir::Item {
2956 kind: hir::ItemKind::Impl(hir::Impl { constness: hir::Constness::Const, .. }),
2963 impl<'tcx> TyCtxtAt<'tcx> {
2964 /// Constructs a `TyKind::Error` type and registers a `delay_span_bug` to ensure it gets used.
2966 pub fn ty_error(self) -> Ty<'tcx> {
2967 self.tcx.ty_error_with_message(self.span, "TyKind::Error constructed but no error reported")
2970 /// Constructs a `TyKind::Error` type and registers a `delay_span_bug` with the given `msg to
2971 /// ensure it gets used.
2973 pub fn ty_error_with_message(self, msg: &str) -> Ty<'tcx> {
2974 self.tcx.ty_error_with_message(self.span, msg)
2978 // We are comparing types with different invariant lifetimes, so `ptr::eq`
2979 // won't work for us.
2980 fn ptr_eq<T, U>(t: *const T, u: *const U) -> bool {
2981 t as *const () == u as *const ()
2984 pub fn provide(providers: &mut ty::query::Providers) {
2985 providers.resolutions = |tcx, ()| &tcx.untracked_resolutions;
2986 providers.resolver_for_lowering = |tcx, ()| &tcx.untracked_resolver_for_lowering;
2987 providers.module_reexports =
2988 |tcx, id| tcx.resolutions(()).reexport_map.get(&id).map(|v| &v[..]);
2989 providers.crate_name = |tcx, id| {
2990 assert_eq!(id, LOCAL_CRATE);
2993 providers.maybe_unused_trait_imports =
2994 |tcx, ()| &tcx.resolutions(()).maybe_unused_trait_imports;
2995 providers.maybe_unused_extern_crates =
2996 |tcx, ()| &tcx.resolutions(()).maybe_unused_extern_crates[..];
2997 providers.names_imported_by_glob_use = |tcx, id| {
2998 tcx.arena.alloc(tcx.resolutions(()).glob_map.get(&id).cloned().unwrap_or_default())
3001 providers.extern_mod_stmt_cnum =
3002 |tcx, id| tcx.resolutions(()).extern_crate_map.get(&id).cloned();
3003 providers.output_filenames = |tcx, ()| &tcx.output_filenames;
3004 providers.features_query = |tcx, ()| tcx.sess.features_untracked();
3005 providers.is_panic_runtime = |tcx, cnum| {
3006 assert_eq!(cnum, LOCAL_CRATE);
3007 tcx.sess.contains_name(tcx.hir().krate_attrs(), sym::panic_runtime)
3009 providers.is_compiler_builtins = |tcx, cnum| {
3010 assert_eq!(cnum, LOCAL_CRATE);
3011 tcx.sess.contains_name(tcx.hir().krate_attrs(), sym::compiler_builtins)
3013 providers.has_panic_handler = |tcx, cnum| {
3014 assert_eq!(cnum, LOCAL_CRATE);
3015 // We want to check if the panic handler was defined in this crate
3016 tcx.lang_items().panic_impl().map_or(false, |did| did.is_local())