]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_middle/src/ty/context.rs
ProjectionTy.item_def_id -> ProjectionTy.def_id
[rust.git] / compiler / rustc_middle / src / ty / context.rs
1 //! Type context book-keeping.
2
3 #![allow(rustc::usage_of_ty_tykind)]
4
5 use crate::arena::Arena;
6 use crate::dep_graph::{DepGraph, DepKindStruct};
7 use crate::hir::place::Place as HirPlace;
8 use crate::infer::canonical::{Canonical, CanonicalVarInfo, CanonicalVarInfos};
9 use crate::lint::struct_lint_level;
10 use crate::middle::codegen_fn_attrs::CodegenFnAttrs;
11 use crate::middle::resolve_lifetime;
12 use crate::middle::stability;
13 use crate::mir::interpret::{self, Allocation, ConstAllocation};
14 use crate::mir::{
15     Body, BorrowCheckResult, Field, Local, Place, PlaceElem, ProjectionKind, Promoted,
16 };
17 use crate::thir::Thir;
18 use crate::traits;
19 use crate::ty::query::{self, TyCtxtAt};
20 use crate::ty::{
21     self, AdtDef, AdtDefData, AdtKind, Binder, BindingMode, BoundVar, CanonicalPolyFnSig,
22     ClosureSizeProfileData, Const, ConstS, DefIdTree, FloatTy, FloatVar, FloatVid,
23     GenericParamDefKind, InferTy, IntTy, IntVar, IntVid, List, ParamConst, ParamTy,
24     PolyExistentialPredicate, PolyFnSig, Predicate, PredicateKind, ProjectionTy, Region,
25     RegionKind, ReprOptions, TraitObjectVisitor, Ty, TyKind, TyVar, TyVid, TypeAndMut, UintTy,
26     Visibility,
27 };
28 use crate::ty::{GenericArg, GenericArgKind, InternalSubsts, SubstsRef, UserSubsts};
29 use rustc_ast as ast;
30 use rustc_data_structures::fingerprint::Fingerprint;
31 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
32 use rustc_data_structures::intern::Interned;
33 use rustc_data_structures::memmap::Mmap;
34 use rustc_data_structures::profiling::SelfProfilerRef;
35 use rustc_data_structures::sharded::{IntoPointer, ShardedHashMap};
36 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
37 use rustc_data_structures::steal::Steal;
38 use rustc_data_structures::sync::{self, Lock, Lrc, ReadGuard, WorkerLocal};
39 use rustc_data_structures::unord::UnordSet;
40 use rustc_data_structures::vec_map::VecMap;
41 use rustc_errors::{
42     DecorateLint, DiagnosticBuilder, DiagnosticMessage, ErrorGuaranteed, MultiSpan,
43 };
44 use rustc_hir as hir;
45 use rustc_hir::def::{DefKind, Res};
46 use rustc_hir::def_id::{CrateNum, DefId, LocalDefId, LocalDefIdMap, LOCAL_CRATE};
47 use rustc_hir::definitions::Definitions;
48 use rustc_hir::hir_id::OwnerId;
49 use rustc_hir::intravisit::Visitor;
50 use rustc_hir::lang_items::LangItem;
51 use rustc_hir::{
52     Constness, ExprKind, HirId, ImplItemKind, ItemKind, ItemLocalId, ItemLocalMap, ItemLocalSet,
53     Node, TraitCandidate, TraitItemKind,
54 };
55 use rustc_index::vec::{Idx, IndexVec};
56 use rustc_macros::HashStable;
57 use rustc_middle::mir::FakeReadCause;
58 use rustc_query_system::dep_graph::DepNodeIndex;
59 use rustc_query_system::ich::StableHashingContext;
60 use rustc_serialize::opaque::{FileEncodeResult, FileEncoder};
61 use rustc_session::config::{CrateType, OutputFilenames};
62 use rustc_session::cstore::{CrateStoreDyn, Untracked};
63 use rustc_session::lint::Lint;
64 use rustc_session::Limit;
65 use rustc_session::Session;
66 use rustc_span::def_id::{DefPathHash, StableCrateId};
67 use rustc_span::source_map::SourceMap;
68 use rustc_span::symbol::{kw, sym, Ident, Symbol};
69 use rustc_span::{Span, DUMMY_SP};
70 use rustc_target::abi::{Layout, LayoutS, TargetDataLayout, VariantIdx};
71 use rustc_target::spec::abi;
72 use rustc_type_ir::sty::TyKind::*;
73 use rustc_type_ir::WithCachedTypeInfo;
74 use rustc_type_ir::{DynKind, InternAs, InternIteratorElement, Interner, TypeFlags};
75
76 use std::any::Any;
77 use std::borrow::Borrow;
78 use std::cmp::Ordering;
79 use std::collections::hash_map::{self, Entry};
80 use std::fmt;
81 use std::hash::{Hash, Hasher};
82 use std::iter;
83 use std::mem;
84 use std::ops::{Bound, Deref};
85 use std::sync::Arc;
86
87 use super::{ImplPolarity, RvalueScopes};
88
89 pub trait OnDiskCache<'tcx>: rustc_data_structures::sync::Sync {
90     /// Creates a new `OnDiskCache` instance from the serialized data in `data`.
91     fn new(sess: &'tcx Session, data: Mmap, start_pos: usize) -> Self
92     where
93         Self: Sized;
94
95     fn new_empty(source_map: &'tcx SourceMap) -> Self
96     where
97         Self: Sized;
98
99     fn drop_serialized_data(&self, tcx: TyCtxt<'tcx>);
100
101     fn serialize(&self, tcx: TyCtxt<'tcx>, encoder: FileEncoder) -> FileEncodeResult;
102 }
103
104 #[allow(rustc::usage_of_ty_tykind)]
105 impl<'tcx> Interner for TyCtxt<'tcx> {
106     type AdtDef = ty::AdtDef<'tcx>;
107     type SubstsRef = ty::SubstsRef<'tcx>;
108     type DefId = DefId;
109     type Ty = Ty<'tcx>;
110     type Const = ty::Const<'tcx>;
111     type Region = Region<'tcx>;
112     type TypeAndMut = TypeAndMut<'tcx>;
113     type Mutability = hir::Mutability;
114     type Movability = hir::Movability;
115     type PolyFnSig = PolyFnSig<'tcx>;
116     type ListBinderExistentialPredicate = &'tcx List<PolyExistentialPredicate<'tcx>>;
117     type BinderListTy = Binder<'tcx, &'tcx List<Ty<'tcx>>>;
118     type ListTy = &'tcx List<Ty<'tcx>>;
119     type ProjectionTy = ty::ProjectionTy<'tcx>;
120     type OpaqueTy = ty::OpaqueTy<'tcx>;
121     type ParamTy = ParamTy;
122     type BoundTy = ty::BoundTy;
123     type PlaceholderType = ty::PlaceholderType;
124     type InferTy = InferTy;
125     type ErrorGuaranteed = ErrorGuaranteed;
126     type PredicateKind = ty::PredicateKind<'tcx>;
127     type AllocId = crate::mir::interpret::AllocId;
128
129     type EarlyBoundRegion = ty::EarlyBoundRegion;
130     type BoundRegion = ty::BoundRegion;
131     type FreeRegion = ty::FreeRegion;
132     type RegionVid = ty::RegionVid;
133     type PlaceholderRegion = ty::PlaceholderRegion;
134 }
135
136 type InternedSet<'tcx, T> = ShardedHashMap<InternedInSet<'tcx, T>, ()>;
137
138 pub struct CtxtInterners<'tcx> {
139     /// The arena that types, regions, etc. are allocated from.
140     arena: &'tcx WorkerLocal<Arena<'tcx>>,
141
142     // Specifically use a speedy hash algorithm for these hash sets, since
143     // they're accessed quite often.
144     type_: InternedSet<'tcx, WithCachedTypeInfo<TyKind<'tcx>>>,
145     const_lists: InternedSet<'tcx, List<ty::Const<'tcx>>>,
146     substs: InternedSet<'tcx, InternalSubsts<'tcx>>,
147     canonical_var_infos: InternedSet<'tcx, List<CanonicalVarInfo<'tcx>>>,
148     region: InternedSet<'tcx, RegionKind<'tcx>>,
149     poly_existential_predicates: InternedSet<'tcx, List<PolyExistentialPredicate<'tcx>>>,
150     predicate: InternedSet<'tcx, WithCachedTypeInfo<ty::Binder<'tcx, PredicateKind<'tcx>>>>,
151     predicates: InternedSet<'tcx, List<Predicate<'tcx>>>,
152     projs: InternedSet<'tcx, List<ProjectionKind>>,
153     place_elems: InternedSet<'tcx, List<PlaceElem<'tcx>>>,
154     const_: InternedSet<'tcx, ConstS<'tcx>>,
155     const_allocation: InternedSet<'tcx, Allocation>,
156     bound_variable_kinds: InternedSet<'tcx, List<ty::BoundVariableKind>>,
157     layout: InternedSet<'tcx, LayoutS<VariantIdx>>,
158     adt_def: InternedSet<'tcx, AdtDefData>,
159 }
160
161 impl<'tcx> CtxtInterners<'tcx> {
162     fn new(arena: &'tcx WorkerLocal<Arena<'tcx>>) -> CtxtInterners<'tcx> {
163         CtxtInterners {
164             arena,
165             type_: Default::default(),
166             const_lists: Default::default(),
167             substs: Default::default(),
168             region: Default::default(),
169             poly_existential_predicates: Default::default(),
170             canonical_var_infos: Default::default(),
171             predicate: Default::default(),
172             predicates: Default::default(),
173             projs: Default::default(),
174             place_elems: Default::default(),
175             const_: Default::default(),
176             const_allocation: Default::default(),
177             bound_variable_kinds: Default::default(),
178             layout: Default::default(),
179             adt_def: Default::default(),
180         }
181     }
182
183     /// Interns a type.
184     #[allow(rustc::usage_of_ty_tykind)]
185     #[inline(never)]
186     fn intern_ty(&self, kind: TyKind<'tcx>, sess: &Session, untracked: &Untracked) -> Ty<'tcx> {
187         Ty(Interned::new_unchecked(
188             self.type_
189                 .intern(kind, |kind| {
190                     let flags = super::flags::FlagComputation::for_kind(&kind);
191                     let stable_hash = self.stable_hash(&flags, sess, untracked, &kind);
192
193                     InternedInSet(self.arena.alloc(WithCachedTypeInfo {
194                         internee: kind,
195                         stable_hash,
196                         flags: flags.flags,
197                         outer_exclusive_binder: flags.outer_exclusive_binder,
198                     }))
199                 })
200                 .0,
201         ))
202     }
203
204     fn stable_hash<'a, T: HashStable<StableHashingContext<'a>>>(
205         &self,
206         flags: &ty::flags::FlagComputation,
207         sess: &'a Session,
208         untracked: &'a Untracked,
209         val: &T,
210     ) -> Fingerprint {
211         // It's impossible to hash inference variables (and will ICE), so we don't need to try to cache them.
212         // Without incremental, we rarely stable-hash types, so let's not do it proactively.
213         if flags.flags.intersects(TypeFlags::NEEDS_INFER) || sess.opts.incremental.is_none() {
214             Fingerprint::ZERO
215         } else {
216             let mut hasher = StableHasher::new();
217             let mut hcx = StableHashingContext::new(sess, untracked);
218             val.hash_stable(&mut hcx, &mut hasher);
219             hasher.finish()
220         }
221     }
222
223     #[inline(never)]
224     fn intern_predicate(
225         &self,
226         kind: Binder<'tcx, PredicateKind<'tcx>>,
227         sess: &Session,
228         untracked: &Untracked,
229     ) -> Predicate<'tcx> {
230         Predicate(Interned::new_unchecked(
231             self.predicate
232                 .intern(kind, |kind| {
233                     let flags = super::flags::FlagComputation::for_predicate(kind);
234
235                     let stable_hash = self.stable_hash(&flags, sess, untracked, &kind);
236
237                     InternedInSet(self.arena.alloc(WithCachedTypeInfo {
238                         internee: kind,
239                         stable_hash,
240                         flags: flags.flags,
241                         outer_exclusive_binder: flags.outer_exclusive_binder,
242                     }))
243                 })
244                 .0,
245         ))
246     }
247 }
248
249 pub struct CommonTypes<'tcx> {
250     pub unit: Ty<'tcx>,
251     pub bool: Ty<'tcx>,
252     pub char: Ty<'tcx>,
253     pub isize: Ty<'tcx>,
254     pub i8: Ty<'tcx>,
255     pub i16: Ty<'tcx>,
256     pub i32: Ty<'tcx>,
257     pub i64: Ty<'tcx>,
258     pub i128: Ty<'tcx>,
259     pub usize: Ty<'tcx>,
260     pub u8: Ty<'tcx>,
261     pub u16: Ty<'tcx>,
262     pub u32: Ty<'tcx>,
263     pub u64: Ty<'tcx>,
264     pub u128: Ty<'tcx>,
265     pub f32: Ty<'tcx>,
266     pub f64: Ty<'tcx>,
267     pub str_: Ty<'tcx>,
268     pub never: Ty<'tcx>,
269     pub self_param: Ty<'tcx>,
270
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>,
275 }
276
277 pub struct CommonLifetimes<'tcx> {
278     /// `ReStatic`
279     pub re_static: Region<'tcx>,
280
281     /// Erased region, used outside of type inference.
282     pub re_erased: Region<'tcx>,
283 }
284
285 pub struct CommonConsts<'tcx> {
286     pub unit: Const<'tcx>,
287 }
288
289 pub struct LocalTableInContext<'a, V> {
290     hir_owner: OwnerId,
291     data: &'a ItemLocalMap<V>,
292 }
293
294 /// Validate that the given HirId (respectively its `local_id` part) can be
295 /// safely used as a key in the maps of a TypeckResults. For that to be
296 /// the case, the HirId must have the same `owner` as all the other IDs in
297 /// this table (signified by `hir_owner`). Otherwise the HirId
298 /// would be in a different frame of reference and using its `local_id`
299 /// would result in lookup errors, or worse, in silently wrong data being
300 /// stored/returned.
301 #[inline]
302 fn validate_hir_id_for_typeck_results(hir_owner: OwnerId, hir_id: hir::HirId) {
303     if hir_id.owner != hir_owner {
304         invalid_hir_id_for_typeck_results(hir_owner, hir_id);
305     }
306 }
307
308 #[cold]
309 #[inline(never)]
310 fn invalid_hir_id_for_typeck_results(hir_owner: OwnerId, hir_id: hir::HirId) {
311     ty::tls::with(|tcx| {
312         bug!(
313             "node {} with HirId::owner {:?} cannot be placed in TypeckResults with hir_owner {:?}",
314             tcx.hir().node_to_string(hir_id),
315             hir_id.owner,
316             hir_owner
317         )
318     });
319 }
320
321 impl<'a, V> LocalTableInContext<'a, V> {
322     pub fn contains_key(&self, id: hir::HirId) -> bool {
323         validate_hir_id_for_typeck_results(self.hir_owner, id);
324         self.data.contains_key(&id.local_id)
325     }
326
327     pub fn get(&self, id: hir::HirId) -> Option<&V> {
328         validate_hir_id_for_typeck_results(self.hir_owner, id);
329         self.data.get(&id.local_id)
330     }
331
332     pub fn iter(&self) -> hash_map::Iter<'_, hir::ItemLocalId, V> {
333         self.data.iter()
334     }
335 }
336
337 impl<'a, V> ::std::ops::Index<hir::HirId> for LocalTableInContext<'a, V> {
338     type Output = V;
339
340     fn index(&self, key: hir::HirId) -> &V {
341         self.get(key).expect("LocalTableInContext: key not found")
342     }
343 }
344
345 pub struct LocalTableInContextMut<'a, V> {
346     hir_owner: OwnerId,
347     data: &'a mut ItemLocalMap<V>,
348 }
349
350 impl<'a, V> LocalTableInContextMut<'a, V> {
351     pub fn get_mut(&mut self, id: hir::HirId) -> Option<&mut V> {
352         validate_hir_id_for_typeck_results(self.hir_owner, id);
353         self.data.get_mut(&id.local_id)
354     }
355
356     pub fn entry(&mut self, id: hir::HirId) -> Entry<'_, hir::ItemLocalId, V> {
357         validate_hir_id_for_typeck_results(self.hir_owner, id);
358         self.data.entry(id.local_id)
359     }
360
361     pub fn insert(&mut self, id: hir::HirId, val: V) -> Option<V> {
362         validate_hir_id_for_typeck_results(self.hir_owner, id);
363         self.data.insert(id.local_id, val)
364     }
365
366     pub fn remove(&mut self, id: hir::HirId) -> Option<V> {
367         validate_hir_id_for_typeck_results(self.hir_owner, id);
368         self.data.remove(&id.local_id)
369     }
370 }
371
372 /// Whenever a value may be live across a generator yield, the type of that value winds up in the
373 /// `GeneratorInteriorTypeCause` struct. This struct adds additional information about such
374 /// captured types that can be useful for diagnostics. In particular, it stores the span that
375 /// caused a given type to be recorded, along with the scope that enclosed the value (which can
376 /// be used to find the await that the value is live across).
377 ///
378 /// For example:
379 ///
380 /// ```ignore (pseudo-Rust)
381 /// async move {
382 ///     let x: T = expr;
383 ///     foo.await
384 ///     ...
385 /// }
386 /// ```
387 ///
388 /// Here, we would store the type `T`, the span of the value `x`, the "scope-span" for
389 /// the scope that contains `x`, the expr `T` evaluated from, and the span of `foo.await`.
390 #[derive(TyEncodable, TyDecodable, Clone, Debug, Eq, Hash, PartialEq, HashStable)]
391 #[derive(TypeFoldable, TypeVisitable)]
392 pub struct GeneratorInteriorTypeCause<'tcx> {
393     /// Type of the captured binding.
394     pub ty: Ty<'tcx>,
395     /// Span of the binding that was captured.
396     pub span: Span,
397     /// Span of the scope of the captured binding.
398     pub scope_span: Option<Span>,
399     /// Span of `.await` or `yield` expression.
400     pub yield_span: Span,
401     /// Expr which the type evaluated from.
402     pub expr: Option<hir::HirId>,
403 }
404
405 // This type holds diagnostic information on generators and async functions across crate boundaries
406 // and is used to provide better error messages
407 #[derive(TyEncodable, TyDecodable, Clone, Debug, HashStable)]
408 pub struct GeneratorDiagnosticData<'tcx> {
409     pub generator_interior_types: ty::Binder<'tcx, Vec<GeneratorInteriorTypeCause<'tcx>>>,
410     pub hir_owner: DefId,
411     pub nodes_types: ItemLocalMap<Ty<'tcx>>,
412     pub adjustments: ItemLocalMap<Vec<ty::adjustment::Adjustment<'tcx>>>,
413 }
414
415 #[derive(TyEncodable, TyDecodable, Debug, HashStable)]
416 pub struct TypeckResults<'tcx> {
417     /// The `HirId::owner` all `ItemLocalId`s in this table are relative to.
418     pub hir_owner: OwnerId,
419
420     /// Resolved definitions for `<T>::X` associated paths and
421     /// method calls, including those of overloaded operators.
422     type_dependent_defs: ItemLocalMap<Result<(DefKind, DefId), ErrorGuaranteed>>,
423
424     /// Resolved field indices for field accesses in expressions (`S { field }`, `obj.field`)
425     /// or patterns (`S { field }`). The index is often useful by itself, but to learn more
426     /// about the field you also need definition of the variant to which the field
427     /// belongs, but it may not exist if it's a tuple field (`tuple.0`).
428     field_indices: ItemLocalMap<usize>,
429
430     /// Stores the types for various nodes in the AST. Note that this table
431     /// is not guaranteed to be populated outside inference. See
432     /// typeck::check::fn_ctxt for details.
433     node_types: ItemLocalMap<Ty<'tcx>>,
434
435     /// Stores the type parameters which were substituted to obtain the type
436     /// of this node. This only applies to nodes that refer to entities
437     /// parameterized by type parameters, such as generic fns, types, or
438     /// other items.
439     node_substs: ItemLocalMap<SubstsRef<'tcx>>,
440
441     /// This will either store the canonicalized types provided by the user
442     /// or the substitutions that the user explicitly gave (if any) attached
443     /// to `id`. These will not include any inferred values. The canonical form
444     /// is used to capture things like `_` or other unspecified values.
445     ///
446     /// For example, if the user wrote `foo.collect::<Vec<_>>()`, then the
447     /// canonical substitutions would include only `for<X> { Vec<X> }`.
448     ///
449     /// See also `AscribeUserType` statement in MIR.
450     user_provided_types: ItemLocalMap<CanonicalUserType<'tcx>>,
451
452     /// Stores the canonicalized types provided by the user. See also
453     /// `AscribeUserType` statement in MIR.
454     pub user_provided_sigs: LocalDefIdMap<CanonicalPolyFnSig<'tcx>>,
455
456     adjustments: ItemLocalMap<Vec<ty::adjustment::Adjustment<'tcx>>>,
457
458     /// Stores the actual binding mode for all instances of hir::BindingAnnotation.
459     pat_binding_modes: ItemLocalMap<BindingMode>,
460
461     /// Stores the types which were implicitly dereferenced in pattern binding modes
462     /// for later usage in THIR lowering. For example,
463     ///
464     /// ```
465     /// match &&Some(5i32) {
466     ///     Some(n) => {},
467     ///     _ => {},
468     /// }
469     /// ```
470     /// leads to a `vec![&&Option<i32>, &Option<i32>]`. Empty vectors are not stored.
471     ///
472     /// See:
473     /// <https://github.com/rust-lang/rfcs/blob/master/text/2005-match-ergonomics.md#definitions>
474     pat_adjustments: ItemLocalMap<Vec<Ty<'tcx>>>,
475
476     /// Records the reasons that we picked the kind of each closure;
477     /// not all closures are present in the map.
478     closure_kind_origins: ItemLocalMap<(Span, HirPlace<'tcx>)>,
479
480     /// For each fn, records the "liberated" types of its arguments
481     /// and return type. Liberated means that all bound regions
482     /// (including late-bound regions) are replaced with free
483     /// equivalents. This table is not used in codegen (since regions
484     /// are erased there) and hence is not serialized to metadata.
485     ///
486     /// This table also contains the "revealed" values for any `impl Trait`
487     /// that appear in the signature and whose values are being inferred
488     /// by this function.
489     ///
490     /// # Example
491     ///
492     /// ```rust
493     /// # use std::fmt::Debug;
494     /// fn foo(x: &u32) -> impl Debug { *x }
495     /// ```
496     ///
497     /// The function signature here would be:
498     ///
499     /// ```ignore (illustrative)
500     /// for<'a> fn(&'a u32) -> Foo
501     /// ```
502     ///
503     /// where `Foo` is an opaque type created for this function.
504     ///
505     ///
506     /// The *liberated* form of this would be
507     ///
508     /// ```ignore (illustrative)
509     /// fn(&'a u32) -> u32
510     /// ```
511     ///
512     /// Note that `'a` is not bound (it would be an `ReFree`) and
513     /// that the `Foo` opaque type is replaced by its hidden type.
514     liberated_fn_sigs: ItemLocalMap<ty::FnSig<'tcx>>,
515
516     /// For each FRU expression, record the normalized types of the fields
517     /// of the struct - this is needed because it is non-trivial to
518     /// normalize while preserving regions. This table is used only in
519     /// MIR construction and hence is not serialized to metadata.
520     fru_field_types: ItemLocalMap<Vec<Ty<'tcx>>>,
521
522     /// For every coercion cast we add the HIR node ID of the cast
523     /// expression to this set.
524     coercion_casts: ItemLocalSet,
525
526     /// Set of trait imports actually used in the method resolution.
527     /// This is used for warning unused imports. During type
528     /// checking, this `Lrc` should not be cloned: it must have a ref-count
529     /// of 1 so that we can insert things into the set mutably.
530     pub used_trait_imports: Lrc<UnordSet<LocalDefId>>,
531
532     /// If any errors occurred while type-checking this body,
533     /// this field will be set to `Some(ErrorGuaranteed)`.
534     pub tainted_by_errors: Option<ErrorGuaranteed>,
535
536     /// All the opaque types that have hidden types set
537     /// by this function. We also store the
538     /// type here, so that mir-borrowck can use it as a hint for figuring out hidden types,
539     /// even if they are only set in dead code (which doesn't show up in MIR).
540     pub concrete_opaque_types: VecMap<LocalDefId, ty::OpaqueHiddenType<'tcx>>,
541
542     /// Tracks the minimum captures required for a closure;
543     /// see `MinCaptureInformationMap` for more details.
544     pub closure_min_captures: ty::MinCaptureInformationMap<'tcx>,
545
546     /// Tracks the fake reads required for a closure and the reason for the fake read.
547     /// When performing pattern matching for closures, there are times we don't end up
548     /// reading places that are mentioned in a closure (because of _ patterns). However,
549     /// to ensure the places are initialized, we introduce fake reads.
550     /// Consider these two examples:
551     /// ``` (discriminant matching with only wildcard arm)
552     /// let x: u8;
553     /// let c = || match x { _ => () };
554     /// ```
555     /// In this example, we don't need to actually read/borrow `x` in `c`, and so we don't
556     /// want to capture it. However, we do still want an error here, because `x` should have
557     /// to be initialized at the point where c is created. Therefore, we add a "fake read"
558     /// instead.
559     /// ``` (destructured assignments)
560     /// let c = || {
561     ///     let (t1, t2) = t;
562     /// }
563     /// ```
564     /// In the second example, we capture the disjoint fields of `t` (`t.0` & `t.1`), but
565     /// we never capture `t`. This becomes an issue when we build MIR as we require
566     /// information on `t` in order to create place `t.0` and `t.1`. We can solve this
567     /// issue by fake reading `t`.
568     pub closure_fake_reads: FxHashMap<LocalDefId, Vec<(HirPlace<'tcx>, FakeReadCause, hir::HirId)>>,
569
570     /// Tracks the rvalue scoping rules which defines finer scoping for rvalue expressions
571     /// by applying extended parameter rules.
572     /// Details may be find in `rustc_hir_analysis::check::rvalue_scopes`.
573     pub rvalue_scopes: RvalueScopes,
574
575     /// Stores the type, expression, span and optional scope span of all types
576     /// that are live across the yield of this generator (if a generator).
577     pub generator_interior_types: ty::Binder<'tcx, Vec<GeneratorInteriorTypeCause<'tcx>>>,
578
579     /// We sometimes treat byte string literals (which are of type `&[u8; N]`)
580     /// as `&[u8]`, depending on the pattern  in which they are used.
581     /// This hashset records all instances where we behave
582     /// like this to allow `const_to_pat` to reliably handle this situation.
583     pub treat_byte_string_as_slice: ItemLocalSet,
584
585     /// Contains the data for evaluating the effect of feature `capture_disjoint_fields`
586     /// on closure size.
587     pub closure_size_eval: FxHashMap<LocalDefId, ClosureSizeProfileData<'tcx>>,
588 }
589
590 impl<'tcx> TypeckResults<'tcx> {
591     pub fn new(hir_owner: OwnerId) -> TypeckResults<'tcx> {
592         TypeckResults {
593             hir_owner,
594             type_dependent_defs: Default::default(),
595             field_indices: Default::default(),
596             user_provided_types: Default::default(),
597             user_provided_sigs: Default::default(),
598             node_types: Default::default(),
599             node_substs: Default::default(),
600             adjustments: Default::default(),
601             pat_binding_modes: Default::default(),
602             pat_adjustments: Default::default(),
603             closure_kind_origins: Default::default(),
604             liberated_fn_sigs: Default::default(),
605             fru_field_types: Default::default(),
606             coercion_casts: Default::default(),
607             used_trait_imports: Lrc::new(Default::default()),
608             tainted_by_errors: None,
609             concrete_opaque_types: Default::default(),
610             closure_min_captures: Default::default(),
611             closure_fake_reads: Default::default(),
612             rvalue_scopes: Default::default(),
613             generator_interior_types: ty::Binder::dummy(Default::default()),
614             treat_byte_string_as_slice: Default::default(),
615             closure_size_eval: Default::default(),
616         }
617     }
618
619     /// Returns the final resolution of a `QPath` in an `Expr` or `Pat` node.
620     pub fn qpath_res(&self, qpath: &hir::QPath<'_>, id: hir::HirId) -> Res {
621         match *qpath {
622             hir::QPath::Resolved(_, ref path) => path.res,
623             hir::QPath::TypeRelative(..) | hir::QPath::LangItem(..) => self
624                 .type_dependent_def(id)
625                 .map_or(Res::Err, |(kind, def_id)| Res::Def(kind, def_id)),
626         }
627     }
628
629     pub fn type_dependent_defs(
630         &self,
631     ) -> LocalTableInContext<'_, Result<(DefKind, DefId), ErrorGuaranteed>> {
632         LocalTableInContext { hir_owner: self.hir_owner, data: &self.type_dependent_defs }
633     }
634
635     pub fn type_dependent_def(&self, id: HirId) -> Option<(DefKind, DefId)> {
636         validate_hir_id_for_typeck_results(self.hir_owner, id);
637         self.type_dependent_defs.get(&id.local_id).cloned().and_then(|r| r.ok())
638     }
639
640     pub fn type_dependent_def_id(&self, id: HirId) -> Option<DefId> {
641         self.type_dependent_def(id).map(|(_, def_id)| def_id)
642     }
643
644     pub fn type_dependent_defs_mut(
645         &mut self,
646     ) -> LocalTableInContextMut<'_, Result<(DefKind, DefId), ErrorGuaranteed>> {
647         LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.type_dependent_defs }
648     }
649
650     pub fn field_indices(&self) -> LocalTableInContext<'_, usize> {
651         LocalTableInContext { hir_owner: self.hir_owner, data: &self.field_indices }
652     }
653
654     pub fn field_indices_mut(&mut self) -> LocalTableInContextMut<'_, usize> {
655         LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.field_indices }
656     }
657
658     pub fn field_index(&self, id: hir::HirId) -> usize {
659         self.field_indices().get(id).cloned().expect("no index for a field")
660     }
661
662     pub fn opt_field_index(&self, id: hir::HirId) -> Option<usize> {
663         self.field_indices().get(id).cloned()
664     }
665
666     pub fn user_provided_types(&self) -> LocalTableInContext<'_, CanonicalUserType<'tcx>> {
667         LocalTableInContext { hir_owner: self.hir_owner, data: &self.user_provided_types }
668     }
669
670     pub fn user_provided_types_mut(
671         &mut self,
672     ) -> LocalTableInContextMut<'_, CanonicalUserType<'tcx>> {
673         LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.user_provided_types }
674     }
675
676     pub fn node_types(&self) -> LocalTableInContext<'_, Ty<'tcx>> {
677         LocalTableInContext { hir_owner: self.hir_owner, data: &self.node_types }
678     }
679
680     pub fn node_types_mut(&mut self) -> LocalTableInContextMut<'_, Ty<'tcx>> {
681         LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.node_types }
682     }
683
684     pub fn get_generator_diagnostic_data(&self) -> GeneratorDiagnosticData<'tcx> {
685         let generator_interior_type = self.generator_interior_types.map_bound_ref(|vec| {
686             vec.iter()
687                 .map(|item| {
688                     GeneratorInteriorTypeCause {
689                         ty: item.ty,
690                         span: item.span,
691                         scope_span: item.scope_span,
692                         yield_span: item.yield_span,
693                         expr: None, //FIXME: Passing expression over crate boundaries is impossible at the moment
694                     }
695                 })
696                 .collect::<Vec<_>>()
697         });
698         GeneratorDiagnosticData {
699             generator_interior_types: generator_interior_type,
700             hir_owner: self.hir_owner.to_def_id(),
701             nodes_types: self.node_types.clone(),
702             adjustments: self.adjustments.clone(),
703         }
704     }
705
706     pub fn node_type(&self, id: hir::HirId) -> Ty<'tcx> {
707         self.node_type_opt(id).unwrap_or_else(|| {
708             bug!("node_type: no type for node `{}`", tls::with(|tcx| tcx.hir().node_to_string(id)))
709         })
710     }
711
712     pub fn node_type_opt(&self, id: hir::HirId) -> Option<Ty<'tcx>> {
713         validate_hir_id_for_typeck_results(self.hir_owner, id);
714         self.node_types.get(&id.local_id).cloned()
715     }
716
717     pub fn node_substs_mut(&mut self) -> LocalTableInContextMut<'_, SubstsRef<'tcx>> {
718         LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.node_substs }
719     }
720
721     pub fn node_substs(&self, id: hir::HirId) -> SubstsRef<'tcx> {
722         validate_hir_id_for_typeck_results(self.hir_owner, id);
723         self.node_substs.get(&id.local_id).cloned().unwrap_or_else(|| InternalSubsts::empty())
724     }
725
726     pub fn node_substs_opt(&self, id: hir::HirId) -> Option<SubstsRef<'tcx>> {
727         validate_hir_id_for_typeck_results(self.hir_owner, id);
728         self.node_substs.get(&id.local_id).cloned()
729     }
730
731     /// Returns the type of a pattern as a monotype. Like [`expr_ty`], this function
732     /// doesn't provide type parameter substitutions.
733     ///
734     /// [`expr_ty`]: TypeckResults::expr_ty
735     pub fn pat_ty(&self, pat: &hir::Pat<'_>) -> Ty<'tcx> {
736         self.node_type(pat.hir_id)
737     }
738
739     /// Returns the type of an expression as a monotype.
740     ///
741     /// NB (1): This is the PRE-ADJUSTMENT TYPE for the expression.  That is, in
742     /// some cases, we insert `Adjustment` annotations such as auto-deref or
743     /// auto-ref.  The type returned by this function does not consider such
744     /// adjustments.  See `expr_ty_adjusted()` instead.
745     ///
746     /// NB (2): This type doesn't provide type parameter substitutions; e.g., if you
747     /// ask for the type of `id` in `id(3)`, it will return `fn(&isize) -> isize`
748     /// instead of `fn(ty) -> T with T = isize`.
749     pub fn expr_ty(&self, expr: &hir::Expr<'_>) -> Ty<'tcx> {
750         self.node_type(expr.hir_id)
751     }
752
753     pub fn expr_ty_opt(&self, expr: &hir::Expr<'_>) -> Option<Ty<'tcx>> {
754         self.node_type_opt(expr.hir_id)
755     }
756
757     pub fn adjustments(&self) -> LocalTableInContext<'_, Vec<ty::adjustment::Adjustment<'tcx>>> {
758         LocalTableInContext { hir_owner: self.hir_owner, data: &self.adjustments }
759     }
760
761     pub fn adjustments_mut(
762         &mut self,
763     ) -> LocalTableInContextMut<'_, Vec<ty::adjustment::Adjustment<'tcx>>> {
764         LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.adjustments }
765     }
766
767     pub fn expr_adjustments(&self, expr: &hir::Expr<'_>) -> &[ty::adjustment::Adjustment<'tcx>] {
768         validate_hir_id_for_typeck_results(self.hir_owner, expr.hir_id);
769         self.adjustments.get(&expr.hir_id.local_id).map_or(&[], |a| &a[..])
770     }
771
772     /// Returns the type of `expr`, considering any `Adjustment`
773     /// entry recorded for that expression.
774     pub fn expr_ty_adjusted(&self, expr: &hir::Expr<'_>) -> Ty<'tcx> {
775         self.expr_adjustments(expr).last().map_or_else(|| self.expr_ty(expr), |adj| adj.target)
776     }
777
778     pub fn expr_ty_adjusted_opt(&self, expr: &hir::Expr<'_>) -> Option<Ty<'tcx>> {
779         self.expr_adjustments(expr).last().map(|adj| adj.target).or_else(|| self.expr_ty_opt(expr))
780     }
781
782     pub fn is_method_call(&self, expr: &hir::Expr<'_>) -> bool {
783         // Only paths and method calls/overloaded operators have
784         // entries in type_dependent_defs, ignore the former here.
785         if let hir::ExprKind::Path(_) = expr.kind {
786             return false;
787         }
788
789         matches!(self.type_dependent_defs().get(expr.hir_id), Some(Ok((DefKind::AssocFn, _))))
790     }
791
792     pub fn extract_binding_mode(&self, s: &Session, id: HirId, sp: Span) -> Option<BindingMode> {
793         self.pat_binding_modes().get(id).copied().or_else(|| {
794             s.delay_span_bug(sp, "missing binding mode");
795             None
796         })
797     }
798
799     pub fn pat_binding_modes(&self) -> LocalTableInContext<'_, BindingMode> {
800         LocalTableInContext { hir_owner: self.hir_owner, data: &self.pat_binding_modes }
801     }
802
803     pub fn pat_binding_modes_mut(&mut self) -> LocalTableInContextMut<'_, BindingMode> {
804         LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.pat_binding_modes }
805     }
806
807     pub fn pat_adjustments(&self) -> LocalTableInContext<'_, Vec<Ty<'tcx>>> {
808         LocalTableInContext { hir_owner: self.hir_owner, data: &self.pat_adjustments }
809     }
810
811     pub fn pat_adjustments_mut(&mut self) -> LocalTableInContextMut<'_, Vec<Ty<'tcx>>> {
812         LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.pat_adjustments }
813     }
814
815     /// For a given closure, returns the iterator of `ty::CapturedPlace`s that are captured
816     /// by the closure.
817     pub fn closure_min_captures_flattened(
818         &self,
819         closure_def_id: LocalDefId,
820     ) -> impl Iterator<Item = &ty::CapturedPlace<'tcx>> {
821         self.closure_min_captures
822             .get(&closure_def_id)
823             .map(|closure_min_captures| closure_min_captures.values().flat_map(|v| v.iter()))
824             .into_iter()
825             .flatten()
826     }
827
828     pub fn closure_kind_origins(&self) -> LocalTableInContext<'_, (Span, HirPlace<'tcx>)> {
829         LocalTableInContext { hir_owner: self.hir_owner, data: &self.closure_kind_origins }
830     }
831
832     pub fn closure_kind_origins_mut(
833         &mut self,
834     ) -> LocalTableInContextMut<'_, (Span, HirPlace<'tcx>)> {
835         LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.closure_kind_origins }
836     }
837
838     pub fn liberated_fn_sigs(&self) -> LocalTableInContext<'_, ty::FnSig<'tcx>> {
839         LocalTableInContext { hir_owner: self.hir_owner, data: &self.liberated_fn_sigs }
840     }
841
842     pub fn liberated_fn_sigs_mut(&mut self) -> LocalTableInContextMut<'_, ty::FnSig<'tcx>> {
843         LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.liberated_fn_sigs }
844     }
845
846     pub fn fru_field_types(&self) -> LocalTableInContext<'_, Vec<Ty<'tcx>>> {
847         LocalTableInContext { hir_owner: self.hir_owner, data: &self.fru_field_types }
848     }
849
850     pub fn fru_field_types_mut(&mut self) -> LocalTableInContextMut<'_, Vec<Ty<'tcx>>> {
851         LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.fru_field_types }
852     }
853
854     pub fn is_coercion_cast(&self, hir_id: hir::HirId) -> bool {
855         validate_hir_id_for_typeck_results(self.hir_owner, hir_id);
856         self.coercion_casts.contains(&hir_id.local_id)
857     }
858
859     pub fn set_coercion_cast(&mut self, id: ItemLocalId) {
860         self.coercion_casts.insert(id);
861     }
862
863     pub fn coercion_casts(&self) -> &ItemLocalSet {
864         &self.coercion_casts
865     }
866 }
867
868 rustc_index::newtype_index! {
869     pub struct UserTypeAnnotationIndex {
870         derive [HashStable]
871         DEBUG_FORMAT = "UserType({})",
872         const START_INDEX = 0,
873     }
874 }
875
876 /// Mapping of type annotation indices to canonical user type annotations.
877 pub type CanonicalUserTypeAnnotations<'tcx> =
878     IndexVec<UserTypeAnnotationIndex, CanonicalUserTypeAnnotation<'tcx>>;
879
880 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable, TypeVisitable, Lift)]
881 pub struct CanonicalUserTypeAnnotation<'tcx> {
882     pub user_ty: Box<CanonicalUserType<'tcx>>,
883     pub span: Span,
884     pub inferred_ty: Ty<'tcx>,
885 }
886
887 /// Canonicalized user type annotation.
888 pub type CanonicalUserType<'tcx> = Canonical<'tcx, UserType<'tcx>>;
889
890 impl<'tcx> CanonicalUserType<'tcx> {
891     /// Returns `true` if this represents a substitution of the form `[?0, ?1, ?2]`,
892     /// i.e., each thing is mapped to a canonical variable with the same index.
893     pub fn is_identity(&self) -> bool {
894         match self.value {
895             UserType::Ty(_) => false,
896             UserType::TypeOf(_, user_substs) => {
897                 if user_substs.user_self_ty.is_some() {
898                     return false;
899                 }
900
901                 iter::zip(user_substs.substs, BoundVar::new(0)..).all(|(kind, cvar)| {
902                     match kind.unpack() {
903                         GenericArgKind::Type(ty) => match ty.kind() {
904                             ty::Bound(debruijn, b) => {
905                                 // We only allow a `ty::INNERMOST` index in substitutions.
906                                 assert_eq!(*debruijn, ty::INNERMOST);
907                                 cvar == b.var
908                             }
909                             _ => false,
910                         },
911
912                         GenericArgKind::Lifetime(r) => match *r {
913                             ty::ReLateBound(debruijn, br) => {
914                                 // We only allow a `ty::INNERMOST` index in substitutions.
915                                 assert_eq!(debruijn, ty::INNERMOST);
916                                 cvar == br.var
917                             }
918                             _ => false,
919                         },
920
921                         GenericArgKind::Const(ct) => match ct.kind() {
922                             ty::ConstKind::Bound(debruijn, b) => {
923                                 // We only allow a `ty::INNERMOST` index in substitutions.
924                                 assert_eq!(debruijn, ty::INNERMOST);
925                                 cvar == b
926                             }
927                             _ => false,
928                         },
929                     }
930                 })
931             }
932         }
933     }
934 }
935
936 /// A user-given type annotation attached to a constant. These arise
937 /// from constants that are named via paths, like `Foo::<A>::new` and
938 /// so forth.
939 #[derive(Copy, Clone, Debug, PartialEq, TyEncodable, TyDecodable)]
940 #[derive(HashStable, TypeFoldable, TypeVisitable, Lift)]
941 pub enum UserType<'tcx> {
942     Ty(Ty<'tcx>),
943
944     /// The canonical type is the result of `type_of(def_id)` with the
945     /// given substitutions applied.
946     TypeOf(DefId, UserSubsts<'tcx>),
947 }
948
949 impl<'tcx> CommonTypes<'tcx> {
950     fn new(
951         interners: &CtxtInterners<'tcx>,
952         sess: &Session,
953         untracked: &Untracked,
954     ) -> CommonTypes<'tcx> {
955         let mk = |ty| interners.intern_ty(ty, sess, untracked);
956
957         CommonTypes {
958             unit: mk(Tuple(List::empty())),
959             bool: mk(Bool),
960             char: mk(Char),
961             never: mk(Never),
962             isize: mk(Int(ty::IntTy::Isize)),
963             i8: mk(Int(ty::IntTy::I8)),
964             i16: mk(Int(ty::IntTy::I16)),
965             i32: mk(Int(ty::IntTy::I32)),
966             i64: mk(Int(ty::IntTy::I64)),
967             i128: mk(Int(ty::IntTy::I128)),
968             usize: mk(Uint(ty::UintTy::Usize)),
969             u8: mk(Uint(ty::UintTy::U8)),
970             u16: mk(Uint(ty::UintTy::U16)),
971             u32: mk(Uint(ty::UintTy::U32)),
972             u64: mk(Uint(ty::UintTy::U64)),
973             u128: mk(Uint(ty::UintTy::U128)),
974             f32: mk(Float(ty::FloatTy::F32)),
975             f64: mk(Float(ty::FloatTy::F64)),
976             str_: mk(Str),
977             self_param: mk(ty::Param(ty::ParamTy { index: 0, name: kw::SelfUpper })),
978
979             trait_object_dummy_self: mk(Infer(ty::FreshTy(0))),
980         }
981     }
982 }
983
984 impl<'tcx> CommonLifetimes<'tcx> {
985     fn new(interners: &CtxtInterners<'tcx>) -> CommonLifetimes<'tcx> {
986         let mk = |r| {
987             Region(Interned::new_unchecked(
988                 interners.region.intern(r, |r| InternedInSet(interners.arena.alloc(r))).0,
989             ))
990         };
991
992         CommonLifetimes { re_static: mk(ty::ReStatic), re_erased: mk(ty::ReErased) }
993     }
994 }
995
996 impl<'tcx> CommonConsts<'tcx> {
997     fn new(interners: &CtxtInterners<'tcx>, types: &CommonTypes<'tcx>) -> CommonConsts<'tcx> {
998         let mk_const = |c| {
999             Const(Interned::new_unchecked(
1000                 interners.const_.intern(c, |c| InternedInSet(interners.arena.alloc(c))).0,
1001             ))
1002         };
1003
1004         CommonConsts {
1005             unit: mk_const(ty::ConstS {
1006                 kind: ty::ConstKind::Value(ty::ValTree::zst()),
1007                 ty: types.unit,
1008             }),
1009         }
1010     }
1011 }
1012
1013 /// This struct contains information regarding the `ReFree(FreeRegion)` corresponding to a lifetime
1014 /// conflict.
1015 #[derive(Debug)]
1016 pub struct FreeRegionInfo {
1017     /// `LocalDefId` corresponding to FreeRegion
1018     pub def_id: LocalDefId,
1019     /// the bound region corresponding to FreeRegion
1020     pub boundregion: ty::BoundRegionKind,
1021     /// checks if bound region is in Impl Item
1022     pub is_impl_item: bool,
1023 }
1024
1025 /// This struct should only be created by `create_def`.
1026 #[derive(Copy, Clone)]
1027 pub struct TyCtxtFeed<'tcx, KEY: Copy> {
1028     pub tcx: TyCtxt<'tcx>,
1029     // Do not allow direct access, as downstream code must not mutate this field.
1030     key: KEY,
1031 }
1032
1033 impl<'tcx> TyCtxt<'tcx> {
1034     pub fn feed_unit_query(self) -> TyCtxtFeed<'tcx, ()> {
1035         TyCtxtFeed { tcx: self, key: () }
1036     }
1037 }
1038
1039 impl<'tcx, KEY: Copy> TyCtxtFeed<'tcx, KEY> {
1040     #[inline(always)]
1041     pub fn key(&self) -> KEY {
1042         self.key
1043     }
1044 }
1045
1046 impl<'tcx> TyCtxtFeed<'tcx, LocalDefId> {
1047     #[inline(always)]
1048     pub fn def_id(&self) -> LocalDefId {
1049         self.key
1050     }
1051 }
1052
1053 /// The central data structure of the compiler. It stores references
1054 /// to the various **arenas** and also houses the results of the
1055 /// various **compiler queries** that have been performed. See the
1056 /// [rustc dev guide] for more details.
1057 ///
1058 /// [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/ty.html
1059 #[derive(Copy, Clone)]
1060 #[rustc_diagnostic_item = "TyCtxt"]
1061 #[rustc_pass_by_value]
1062 pub struct TyCtxt<'tcx> {
1063     gcx: &'tcx GlobalCtxt<'tcx>,
1064 }
1065
1066 impl<'tcx> Deref for TyCtxt<'tcx> {
1067     type Target = &'tcx GlobalCtxt<'tcx>;
1068     #[inline(always)]
1069     fn deref(&self) -> &Self::Target {
1070         &self.gcx
1071     }
1072 }
1073
1074 pub struct GlobalCtxt<'tcx> {
1075     pub arena: &'tcx WorkerLocal<Arena<'tcx>>,
1076     pub hir_arena: &'tcx WorkerLocal<hir::Arena<'tcx>>,
1077
1078     interners: CtxtInterners<'tcx>,
1079
1080     pub sess: &'tcx Session,
1081
1082     /// This only ever stores a `LintStore` but we don't want a dependency on that type here.
1083     ///
1084     /// FIXME(Centril): consider `dyn LintStoreMarker` once
1085     /// we can upcast to `Any` for some additional type safety.
1086     pub lint_store: Lrc<dyn Any + sync::Sync + sync::Send>,
1087
1088     pub dep_graph: DepGraph,
1089
1090     pub prof: SelfProfilerRef,
1091
1092     /// Common types, pre-interned for your convenience.
1093     pub types: CommonTypes<'tcx>,
1094
1095     /// Common lifetimes, pre-interned for your convenience.
1096     pub lifetimes: CommonLifetimes<'tcx>,
1097
1098     /// Common consts, pre-interned for your convenience.
1099     pub consts: CommonConsts<'tcx>,
1100
1101     untracked: Untracked,
1102     /// Output of the resolver.
1103     pub(crate) untracked_resolutions: ty::ResolverGlobalCtxt,
1104     /// The entire crate as AST. This field serves as the input for the hir_crate query,
1105     /// which lowers it from AST to HIR. It must not be read or used by anything else.
1106     pub untracked_crate: Steal<Lrc<ast::Crate>>,
1107
1108     /// This provides access to the incremental compilation on-disk cache for query results.
1109     /// Do not access this directly. It is only meant to be used by
1110     /// `DepGraph::try_mark_green()` and the query infrastructure.
1111     /// This is `None` if we are not incremental compilation mode
1112     pub on_disk_cache: Option<&'tcx dyn OnDiskCache<'tcx>>,
1113
1114     pub queries: &'tcx dyn query::QueryEngine<'tcx>,
1115     pub query_caches: query::QueryCaches<'tcx>,
1116     pub(crate) query_kinds: &'tcx [DepKindStruct<'tcx>],
1117
1118     // Internal caches for metadata decoding. No need to track deps on this.
1119     pub ty_rcache: Lock<FxHashMap<ty::CReaderCacheKey, Ty<'tcx>>>,
1120     pub pred_rcache: Lock<FxHashMap<ty::CReaderCacheKey, Predicate<'tcx>>>,
1121
1122     /// Caches the results of trait selection. This cache is used
1123     /// for things that do not have to do with the parameters in scope.
1124     pub selection_cache: traits::SelectionCache<'tcx>,
1125
1126     /// Caches the results of trait evaluation. This cache is used
1127     /// for things that do not have to do with the parameters in scope.
1128     /// Merge this with `selection_cache`?
1129     pub evaluation_cache: traits::EvaluationCache<'tcx>,
1130
1131     /// The definite name of the current crate after taking into account
1132     /// attributes, commandline parameters, etc.
1133     crate_name: Symbol,
1134
1135     /// Data layout specification for the current target.
1136     pub data_layout: TargetDataLayout,
1137
1138     /// Stores memory for globals (statics/consts).
1139     pub(crate) alloc_map: Lock<interpret::AllocMap<'tcx>>,
1140
1141     output_filenames: Arc<OutputFilenames>,
1142 }
1143
1144 impl<'tcx> TyCtxt<'tcx> {
1145     /// Expects a body and returns its codegen attributes.
1146     ///
1147     /// Unlike `codegen_fn_attrs`, this returns `CodegenFnAttrs::EMPTY` for
1148     /// constants.
1149     pub fn body_codegen_attrs(self, def_id: DefId) -> &'tcx CodegenFnAttrs {
1150         let def_kind = self.def_kind(def_id);
1151         if def_kind.has_codegen_attrs() {
1152             self.codegen_fn_attrs(def_id)
1153         } else if matches!(
1154             def_kind,
1155             DefKind::AnonConst | DefKind::AssocConst | DefKind::Const | DefKind::InlineConst
1156         ) {
1157             CodegenFnAttrs::EMPTY
1158         } else {
1159             bug!(
1160                 "body_codegen_fn_attrs called on unexpected definition: {:?} {:?}",
1161                 def_id,
1162                 def_kind
1163             )
1164         }
1165     }
1166
1167     pub fn typeck_opt_const_arg(
1168         self,
1169         def: ty::WithOptConstParam<LocalDefId>,
1170     ) -> &'tcx TypeckResults<'tcx> {
1171         if let Some(param_did) = def.const_param_did {
1172             self.typeck_const_arg((def.did, param_did))
1173         } else {
1174             self.typeck(def.did)
1175         }
1176     }
1177
1178     pub fn mir_borrowck_opt_const_arg(
1179         self,
1180         def: ty::WithOptConstParam<LocalDefId>,
1181     ) -> &'tcx BorrowCheckResult<'tcx> {
1182         if let Some(param_did) = def.const_param_did {
1183             self.mir_borrowck_const_arg((def.did, param_did))
1184         } else {
1185             self.mir_borrowck(def.did)
1186         }
1187     }
1188
1189     pub fn alloc_steal_thir(self, thir: Thir<'tcx>) -> &'tcx Steal<Thir<'tcx>> {
1190         self.arena.alloc(Steal::new(thir))
1191     }
1192
1193     pub fn alloc_steal_mir(self, mir: Body<'tcx>) -> &'tcx Steal<Body<'tcx>> {
1194         self.arena.alloc(Steal::new(mir))
1195     }
1196
1197     pub fn alloc_steal_promoted(
1198         self,
1199         promoted: IndexVec<Promoted, Body<'tcx>>,
1200     ) -> &'tcx Steal<IndexVec<Promoted, Body<'tcx>>> {
1201         self.arena.alloc(Steal::new(promoted))
1202     }
1203
1204     pub fn alloc_adt_def(
1205         self,
1206         did: DefId,
1207         kind: AdtKind,
1208         variants: IndexVec<VariantIdx, ty::VariantDef>,
1209         repr: ReprOptions,
1210     ) -> ty::AdtDef<'tcx> {
1211         self.intern_adt_def(ty::AdtDefData::new(self, did, kind, variants, repr))
1212     }
1213
1214     /// Allocates a read-only byte or string literal for `mir::interpret`.
1215     pub fn allocate_bytes(self, bytes: &[u8]) -> interpret::AllocId {
1216         // Create an allocation that just contains these bytes.
1217         let alloc = interpret::Allocation::from_bytes_byte_aligned_immutable(bytes);
1218         let alloc = self.intern_const_alloc(alloc);
1219         self.create_memory_alloc(alloc)
1220     }
1221
1222     /// Returns a range of the start/end indices specified with the
1223     /// `rustc_layout_scalar_valid_range` attribute.
1224     // FIXME(eddyb) this is an awkward spot for this method, maybe move it?
1225     pub fn layout_scalar_valid_range(self, def_id: DefId) -> (Bound<u128>, Bound<u128>) {
1226         let get = |name| {
1227             let Some(attr) = self.get_attr(def_id, name) else {
1228                 return Bound::Unbounded;
1229             };
1230             debug!("layout_scalar_valid_range: attr={:?}", attr);
1231             if let Some(
1232                 &[
1233                     ast::NestedMetaItem::Lit(ast::MetaItemLit {
1234                         kind: ast::LitKind::Int(a, _),
1235                         ..
1236                     }),
1237                 ],
1238             ) = attr.meta_item_list().as_deref()
1239             {
1240                 Bound::Included(a)
1241             } else {
1242                 self.sess
1243                     .delay_span_bug(attr.span, "invalid rustc_layout_scalar_valid_range attribute");
1244                 Bound::Unbounded
1245             }
1246         };
1247         (
1248             get(sym::rustc_layout_scalar_valid_range_start),
1249             get(sym::rustc_layout_scalar_valid_range_end),
1250         )
1251     }
1252
1253     pub fn lift<T: Lift<'tcx>>(self, value: T) -> Option<T::Lifted> {
1254         value.lift_to_tcx(self)
1255     }
1256
1257     /// Creates a type context and call the closure with a `TyCtxt` reference
1258     /// to the context. The closure enforces that the type context and any interned
1259     /// value (types, substs, etc.) can only be used while `ty::tls` has a valid
1260     /// reference to the context, to allow formatting values that need it.
1261     pub fn create_global_ctxt(
1262         s: &'tcx Session,
1263         lint_store: Lrc<dyn Any + sync::Send + sync::Sync>,
1264         arena: &'tcx WorkerLocal<Arena<'tcx>>,
1265         hir_arena: &'tcx WorkerLocal<hir::Arena<'tcx>>,
1266         untracked_resolutions: ty::ResolverGlobalCtxt,
1267         untracked: Untracked,
1268         krate: Lrc<ast::Crate>,
1269         dep_graph: DepGraph,
1270         on_disk_cache: Option<&'tcx dyn OnDiskCache<'tcx>>,
1271         queries: &'tcx dyn query::QueryEngine<'tcx>,
1272         query_kinds: &'tcx [DepKindStruct<'tcx>],
1273         crate_name: Symbol,
1274         output_filenames: OutputFilenames,
1275     ) -> GlobalCtxt<'tcx> {
1276         let data_layout = s.target.parse_data_layout().unwrap_or_else(|err| {
1277             s.emit_fatal(err);
1278         });
1279         let interners = CtxtInterners::new(arena);
1280         let common_types = CommonTypes::new(&interners, s, &untracked);
1281         let common_lifetimes = CommonLifetimes::new(&interners);
1282         let common_consts = CommonConsts::new(&interners, &common_types);
1283
1284         GlobalCtxt {
1285             sess: s,
1286             lint_store,
1287             arena,
1288             hir_arena,
1289             interners,
1290             dep_graph,
1291             prof: s.prof.clone(),
1292             types: common_types,
1293             lifetimes: common_lifetimes,
1294             consts: common_consts,
1295             untracked,
1296             untracked_resolutions,
1297             untracked_crate: Steal::new(krate),
1298             on_disk_cache,
1299             queries,
1300             query_caches: query::QueryCaches::default(),
1301             query_kinds,
1302             ty_rcache: Default::default(),
1303             pred_rcache: Default::default(),
1304             selection_cache: Default::default(),
1305             evaluation_cache: Default::default(),
1306             crate_name,
1307             data_layout,
1308             alloc_map: Lock::new(interpret::AllocMap::new()),
1309             output_filenames: Arc::new(output_filenames),
1310         }
1311     }
1312
1313     /// Constructs a `TyKind::Error` type with current `ErrorGuaranteed`
1314     #[track_caller]
1315     pub fn ty_error_with_guaranteed(self, reported: ErrorGuaranteed) -> Ty<'tcx> {
1316         self.mk_ty(Error(reported))
1317     }
1318
1319     /// Constructs a `TyKind::Error` type and registers a `delay_span_bug` to ensure it gets used.
1320     #[track_caller]
1321     pub fn ty_error(self) -> Ty<'tcx> {
1322         self.ty_error_with_message(DUMMY_SP, "TyKind::Error constructed but no error reported")
1323     }
1324
1325     /// Constructs a `TyKind::Error` type and registers a `delay_span_bug` with the given `msg` to
1326     /// ensure it gets used.
1327     #[track_caller]
1328     pub fn ty_error_with_message<S: Into<MultiSpan>>(self, span: S, msg: &str) -> Ty<'tcx> {
1329         let reported = self.sess.delay_span_bug(span, msg);
1330         self.mk_ty(Error(reported))
1331     }
1332
1333     /// Like [TyCtxt::ty_error] but for constants, with current `ErrorGuaranteed`
1334     #[track_caller]
1335     pub fn const_error_with_guaranteed(
1336         self,
1337         ty: Ty<'tcx>,
1338         reported: ErrorGuaranteed,
1339     ) -> Const<'tcx> {
1340         self.mk_const(ty::ConstKind::Error(reported), ty)
1341     }
1342
1343     /// Like [TyCtxt::ty_error] but for constants.
1344     #[track_caller]
1345     pub fn const_error(self, ty: Ty<'tcx>) -> Const<'tcx> {
1346         self.const_error_with_message(
1347             ty,
1348             DUMMY_SP,
1349             "ty::ConstKind::Error constructed but no error reported",
1350         )
1351     }
1352
1353     /// Like [TyCtxt::ty_error_with_message] but for constants.
1354     #[track_caller]
1355     pub fn const_error_with_message<S: Into<MultiSpan>>(
1356         self,
1357         ty: Ty<'tcx>,
1358         span: S,
1359         msg: &str,
1360     ) -> Const<'tcx> {
1361         let reported = self.sess.delay_span_bug(span, msg);
1362         self.mk_const(ty::ConstKind::Error(reported), ty)
1363     }
1364
1365     pub fn consider_optimizing<T: Fn() -> String>(self, msg: T) -> bool {
1366         let cname = self.crate_name(LOCAL_CRATE);
1367         self.sess.consider_optimizing(cname.as_str(), msg)
1368     }
1369
1370     /// Obtain all lang items of this crate and all dependencies (recursively)
1371     pub fn lang_items(self) -> &'tcx rustc_hir::lang_items::LanguageItems {
1372         self.get_lang_items(())
1373     }
1374
1375     /// Obtain the given diagnostic item's `DefId`. Use `is_diagnostic_item` if you just want to
1376     /// compare against another `DefId`, since `is_diagnostic_item` is cheaper.
1377     pub fn get_diagnostic_item(self, name: Symbol) -> Option<DefId> {
1378         self.all_diagnostic_items(()).name_to_id.get(&name).copied()
1379     }
1380
1381     /// Obtain the diagnostic item's name
1382     pub fn get_diagnostic_name(self, id: DefId) -> Option<Symbol> {
1383         self.diagnostic_items(id.krate).id_to_name.get(&id).copied()
1384     }
1385
1386     /// Check whether the diagnostic item with the given `name` has the given `DefId`.
1387     pub fn is_diagnostic_item(self, name: Symbol, did: DefId) -> bool {
1388         self.diagnostic_items(did.krate).name_to_id.get(&name) == Some(&did)
1389     }
1390
1391     /// Returns `true` if the node pointed to by `def_id` is a generator for an async construct.
1392     pub fn generator_is_async(self, def_id: DefId) -> bool {
1393         matches!(self.generator_kind(def_id), Some(hir::GeneratorKind::Async(_)))
1394     }
1395
1396     pub fn stability(self) -> &'tcx stability::Index {
1397         self.stability_index(())
1398     }
1399
1400     pub fn features(self) -> &'tcx rustc_feature::Features {
1401         self.features_query(())
1402     }
1403
1404     pub fn def_key(self, id: DefId) -> rustc_hir::definitions::DefKey {
1405         // Accessing the DefKey is ok, since it is part of DefPathHash.
1406         if let Some(id) = id.as_local() {
1407             self.definitions_untracked().def_key(id)
1408         } else {
1409             self.untracked.cstore.def_key(id)
1410         }
1411     }
1412
1413     /// Converts a `DefId` into its fully expanded `DefPath` (every
1414     /// `DefId` is really just an interned `DefPath`).
1415     ///
1416     /// Note that if `id` is not local to this crate, the result will
1417     ///  be a non-local `DefPath`.
1418     pub fn def_path(self, id: DefId) -> rustc_hir::definitions::DefPath {
1419         // Accessing the DefPath is ok, since it is part of DefPathHash.
1420         if let Some(id) = id.as_local() {
1421             self.definitions_untracked().def_path(id)
1422         } else {
1423             self.untracked.cstore.def_path(id)
1424         }
1425     }
1426
1427     #[inline]
1428     pub fn def_path_hash(self, def_id: DefId) -> rustc_hir::definitions::DefPathHash {
1429         // Accessing the DefPathHash is ok, it is incr. comp. stable.
1430         if let Some(def_id) = def_id.as_local() {
1431             self.definitions_untracked().def_path_hash(def_id)
1432         } else {
1433             self.untracked.cstore.def_path_hash(def_id)
1434         }
1435     }
1436
1437     #[inline]
1438     pub fn stable_crate_id(self, crate_num: CrateNum) -> StableCrateId {
1439         if crate_num == LOCAL_CRATE {
1440             self.sess.local_stable_crate_id()
1441         } else {
1442             self.untracked.cstore.stable_crate_id(crate_num)
1443         }
1444     }
1445
1446     /// Maps a StableCrateId to the corresponding CrateNum. This method assumes
1447     /// that the crate in question has already been loaded by the CrateStore.
1448     #[inline]
1449     pub fn stable_crate_id_to_crate_num(self, stable_crate_id: StableCrateId) -> CrateNum {
1450         if stable_crate_id == self.sess.local_stable_crate_id() {
1451             LOCAL_CRATE
1452         } else {
1453             self.untracked.cstore.stable_crate_id_to_crate_num(stable_crate_id)
1454         }
1455     }
1456
1457     /// Converts a `DefPathHash` to its corresponding `DefId` in the current compilation
1458     /// session, if it still exists. This is used during incremental compilation to
1459     /// turn a deserialized `DefPathHash` into its current `DefId`.
1460     pub fn def_path_hash_to_def_id(self, hash: DefPathHash, err: &mut dyn FnMut() -> !) -> DefId {
1461         debug!("def_path_hash_to_def_id({:?})", hash);
1462
1463         let stable_crate_id = hash.stable_crate_id();
1464
1465         // If this is a DefPathHash from the local crate, we can look up the
1466         // DefId in the tcx's `Definitions`.
1467         if stable_crate_id == self.sess.local_stable_crate_id() {
1468             self.untracked.definitions.read().local_def_path_hash_to_def_id(hash, err).to_def_id()
1469         } else {
1470             // If this is a DefPathHash from an upstream crate, let the CrateStore map
1471             // it to a DefId.
1472             let cstore = &*self.untracked.cstore;
1473             let cnum = cstore.stable_crate_id_to_crate_num(stable_crate_id);
1474             cstore.def_path_hash_to_def_id(cnum, hash)
1475         }
1476     }
1477
1478     pub fn def_path_debug_str(self, def_id: DefId) -> String {
1479         // We are explicitly not going through queries here in order to get
1480         // crate name and stable crate id since this code is called from debug!()
1481         // statements within the query system and we'd run into endless
1482         // recursion otherwise.
1483         let (crate_name, stable_crate_id) = if def_id.is_local() {
1484             (self.crate_name, self.sess.local_stable_crate_id())
1485         } else {
1486             let cstore = &*self.untracked.cstore;
1487             (cstore.crate_name(def_id.krate), cstore.stable_crate_id(def_id.krate))
1488         };
1489
1490         format!(
1491             "{}[{:04x}]{}",
1492             crate_name,
1493             // Don't print the whole stable crate id. That's just
1494             // annoying in debug output.
1495             stable_crate_id.to_u64() >> 8 * 6,
1496             self.def_path(def_id).to_string_no_crate_verbose()
1497         )
1498     }
1499 }
1500
1501 impl<'tcx> TyCtxtAt<'tcx> {
1502     /// Create a new definition within the incr. comp. engine.
1503     pub fn create_def(
1504         self,
1505         parent: LocalDefId,
1506         data: hir::definitions::DefPathData,
1507     ) -> TyCtxtFeed<'tcx, LocalDefId> {
1508         // This function modifies `self.definitions` using a side-effect.
1509         // We need to ensure that these side effects are re-run by the incr. comp. engine.
1510         // Depending on the forever-red node will tell the graph that the calling query
1511         // needs to be re-evaluated.
1512         self.dep_graph.read_index(DepNodeIndex::FOREVER_RED_NODE);
1513
1514         // The following call has the side effect of modifying the tables inside `definitions`.
1515         // These very tables are relied on by the incr. comp. engine to decode DepNodes and to
1516         // decode the on-disk cache.
1517         //
1518         // Any LocalDefId which is used within queries, either as key or result, either:
1519         // - has been created before the construction of the TyCtxt;
1520         // - has been created by this call to `create_def`.
1521         // As a consequence, this LocalDefId is always re-created before it is needed by the incr.
1522         // comp. engine itself.
1523         //
1524         // This call also writes to the value of `source_span` and `expn_that_defined` queries.
1525         // This is fine because:
1526         // - those queries are `eval_always` so we won't miss their result changing;
1527         // - this write will have happened before these queries are called.
1528         let key = self.untracked.definitions.write().create_def(parent, data);
1529
1530         let feed = TyCtxtFeed { tcx: self.tcx, key };
1531         feed.def_span(self.span);
1532         feed
1533     }
1534 }
1535
1536 impl<'tcx> TyCtxt<'tcx> {
1537     pub fn iter_local_def_id(self) -> impl Iterator<Item = LocalDefId> + 'tcx {
1538         // Create a dependency to the red node to be sure we re-execute this when the amount of
1539         // definitions change.
1540         self.dep_graph.read_index(DepNodeIndex::FOREVER_RED_NODE);
1541
1542         let definitions = &self.untracked.definitions;
1543         std::iter::from_generator(|| {
1544             let mut i = 0;
1545
1546             // Recompute the number of definitions each time, because our caller may be creating
1547             // new ones.
1548             while i < { definitions.read().num_definitions() } {
1549                 let local_def_index = rustc_span::def_id::DefIndex::from_usize(i);
1550                 yield LocalDefId { local_def_index };
1551                 i += 1;
1552             }
1553
1554             // Leak a read lock once we finish iterating on definitions, to prevent adding new ones.
1555             definitions.leak();
1556         })
1557     }
1558
1559     pub fn def_path_table(self) -> &'tcx rustc_hir::definitions::DefPathTable {
1560         // Create a dependency to the crate to be sure we re-execute this when the amount of
1561         // definitions change.
1562         self.dep_graph.read_index(DepNodeIndex::FOREVER_RED_NODE);
1563
1564         // Leak a read lock once we start iterating on definitions, to prevent adding new ones
1565         // while iterating.  If some query needs to add definitions, it should be `ensure`d above.
1566         let definitions = self.untracked.definitions.leak();
1567         definitions.def_path_table()
1568     }
1569
1570     pub fn def_path_hash_to_def_index_map(
1571         self,
1572     ) -> &'tcx rustc_hir::def_path_hash_map::DefPathHashMap {
1573         // Create a dependency to the crate to be sure we re-execute this when the amount of
1574         // definitions change.
1575         self.ensure().hir_crate(());
1576         // Leak a read lock once we start iterating on definitions, to prevent adding new ones
1577         // while iterating.  If some query needs to add definitions, it should be `ensure`d above.
1578         let definitions = self.untracked.definitions.leak();
1579         definitions.def_path_hash_to_def_index_map()
1580     }
1581
1582     /// Note that this is *untracked* and should only be used within the query
1583     /// system if the result is otherwise tracked through queries
1584     pub fn cstore_untracked(self) -> &'tcx CrateStoreDyn {
1585         &*self.untracked.cstore
1586     }
1587
1588     /// Note that this is *untracked* and should only be used within the query
1589     /// system if the result is otherwise tracked through queries
1590     #[inline]
1591     pub fn definitions_untracked(self) -> ReadGuard<'tcx, Definitions> {
1592         self.untracked.definitions.read()
1593     }
1594
1595     /// Note that this is *untracked* and should only be used within the query
1596     /// system if the result is otherwise tracked through queries
1597     #[inline]
1598     pub fn source_span_untracked(self, def_id: LocalDefId) -> Span {
1599         self.untracked.source_span.get(def_id).copied().unwrap_or(DUMMY_SP)
1600     }
1601
1602     #[inline(always)]
1603     pub fn with_stable_hashing_context<R>(
1604         self,
1605         f: impl FnOnce(StableHashingContext<'_>) -> R,
1606     ) -> R {
1607         f(StableHashingContext::new(self.sess, &self.untracked))
1608     }
1609
1610     pub fn serialize_query_result_cache(self, encoder: FileEncoder) -> FileEncodeResult {
1611         self.on_disk_cache.as_ref().map_or(Ok(0), |c| c.serialize(self, encoder))
1612     }
1613
1614     /// If `true`, we should use lazy normalization for constants, otherwise
1615     /// we still evaluate them eagerly.
1616     #[inline]
1617     pub fn lazy_normalization(self) -> bool {
1618         let features = self.features();
1619         // Note: We only use lazy normalization for generic const expressions.
1620         features.generic_const_exprs
1621     }
1622
1623     #[inline]
1624     pub fn local_crate_exports_generics(self) -> bool {
1625         debug_assert!(self.sess.opts.share_generics());
1626
1627         self.sess.crate_types().iter().any(|crate_type| {
1628             match crate_type {
1629                 CrateType::Executable
1630                 | CrateType::Staticlib
1631                 | CrateType::ProcMacro
1632                 | CrateType::Cdylib => false,
1633
1634                 // FIXME rust-lang/rust#64319, rust-lang/rust#64872:
1635                 // We want to block export of generics from dylibs,
1636                 // but we must fix rust-lang/rust#65890 before we can
1637                 // do that robustly.
1638                 CrateType::Dylib => true,
1639
1640                 CrateType::Rlib => true,
1641             }
1642         })
1643     }
1644
1645     /// Returns the `DefId` and the `BoundRegionKind` corresponding to the given region.
1646     pub fn is_suitable_region(self, region: Region<'tcx>) -> Option<FreeRegionInfo> {
1647         let (suitable_region_binding_scope, bound_region) = match *region {
1648             ty::ReFree(ref free_region) => {
1649                 (free_region.scope.expect_local(), free_region.bound_region)
1650             }
1651             ty::ReEarlyBound(ref ebr) => (
1652                 self.local_parent(ebr.def_id.expect_local()),
1653                 ty::BoundRegionKind::BrNamed(ebr.def_id, ebr.name),
1654             ),
1655             _ => return None, // not a free region
1656         };
1657
1658         let is_impl_item = match self.hir().find_by_def_id(suitable_region_binding_scope) {
1659             Some(Node::Item(..) | Node::TraitItem(..)) => false,
1660             Some(Node::ImplItem(..)) => {
1661                 self.is_bound_region_in_impl_item(suitable_region_binding_scope)
1662             }
1663             _ => return None,
1664         };
1665
1666         Some(FreeRegionInfo {
1667             def_id: suitable_region_binding_scope,
1668             boundregion: bound_region,
1669             is_impl_item,
1670         })
1671     }
1672
1673     /// Given a `DefId` for an `fn`, return all the `dyn` and `impl` traits in its return type.
1674     pub fn return_type_impl_or_dyn_traits(
1675         self,
1676         scope_def_id: LocalDefId,
1677     ) -> Vec<&'tcx hir::Ty<'tcx>> {
1678         let hir_id = self.hir().local_def_id_to_hir_id(scope_def_id);
1679         let Some(hir::FnDecl { output: hir::FnRetTy::Return(hir_output), .. }) = self.hir().fn_decl_by_hir_id(hir_id) else {
1680             return vec![];
1681         };
1682
1683         let mut v = TraitObjectVisitor(vec![], self.hir());
1684         v.visit_ty(hir_output);
1685         v.0
1686     }
1687
1688     pub fn return_type_impl_trait(self, scope_def_id: LocalDefId) -> Option<(Ty<'tcx>, Span)> {
1689         // `type_of()` will fail on these (#55796, #86483), so only allow `fn`s or closures.
1690         match self.hir().get_by_def_id(scope_def_id) {
1691             Node::Item(&hir::Item { kind: ItemKind::Fn(..), .. }) => {}
1692             Node::TraitItem(&hir::TraitItem { kind: TraitItemKind::Fn(..), .. }) => {}
1693             Node::ImplItem(&hir::ImplItem { kind: ImplItemKind::Fn(..), .. }) => {}
1694             Node::Expr(&hir::Expr { kind: ExprKind::Closure { .. }, .. }) => {}
1695             _ => return None,
1696         }
1697
1698         let ret_ty = self.type_of(scope_def_id);
1699         match ret_ty.kind() {
1700             ty::FnDef(_, _) => {
1701                 let sig = ret_ty.fn_sig(self);
1702                 let output = self.erase_late_bound_regions(sig.output());
1703                 if output.is_impl_trait() {
1704                     let hir_id = self.hir().local_def_id_to_hir_id(scope_def_id);
1705                     let fn_decl = self.hir().fn_decl_by_hir_id(hir_id).unwrap();
1706                     Some((output, fn_decl.output.span()))
1707                 } else {
1708                     None
1709                 }
1710             }
1711             _ => None,
1712         }
1713     }
1714
1715     /// Checks if the bound region is in Impl Item.
1716     pub fn is_bound_region_in_impl_item(self, suitable_region_binding_scope: LocalDefId) -> bool {
1717         let container_id = self.parent(suitable_region_binding_scope.to_def_id());
1718         if self.impl_trait_ref(container_id).is_some() {
1719             // For now, we do not try to target impls of traits. This is
1720             // because this message is going to suggest that the user
1721             // change the fn signature, but they may not be free to do so,
1722             // since the signature must match the trait.
1723             //
1724             // FIXME(#42706) -- in some cases, we could do better here.
1725             return true;
1726         }
1727         false
1728     }
1729
1730     /// Determines whether identifiers in the assembly have strict naming rules.
1731     /// Currently, only NVPTX* targets need it.
1732     pub fn has_strict_asm_symbol_naming(self) -> bool {
1733         self.sess.target.arch.contains("nvptx")
1734     }
1735
1736     /// Returns `&'static core::panic::Location<'static>`.
1737     pub fn caller_location_ty(self) -> Ty<'tcx> {
1738         self.mk_imm_ref(
1739             self.lifetimes.re_static,
1740             self.bound_type_of(self.require_lang_item(LangItem::PanicLocation, None))
1741                 .subst(self, self.mk_substs([self.lifetimes.re_static.into()].iter())),
1742         )
1743     }
1744
1745     /// Returns a displayable description and article for the given `def_id` (e.g. `("a", "struct")`).
1746     pub fn article_and_description(self, def_id: DefId) -> (&'static str, &'static str) {
1747         match self.def_kind(def_id) {
1748             DefKind::Generator => match self.generator_kind(def_id).unwrap() {
1749                 rustc_hir::GeneratorKind::Async(..) => ("an", "async closure"),
1750                 rustc_hir::GeneratorKind::Gen => ("a", "generator"),
1751             },
1752             def_kind => (def_kind.article(), def_kind.descr(def_id)),
1753         }
1754     }
1755
1756     pub fn type_length_limit(self) -> Limit {
1757         self.limits(()).type_length_limit
1758     }
1759
1760     pub fn recursion_limit(self) -> Limit {
1761         self.limits(()).recursion_limit
1762     }
1763
1764     pub fn move_size_limit(self) -> Limit {
1765         self.limits(()).move_size_limit
1766     }
1767
1768     pub fn const_eval_limit(self) -> Limit {
1769         self.limits(()).const_eval_limit
1770     }
1771
1772     pub fn all_traits(self) -> impl Iterator<Item = DefId> + 'tcx {
1773         iter::once(LOCAL_CRATE)
1774             .chain(self.crates(()).iter().copied())
1775             .flat_map(move |cnum| self.traits_in_crate(cnum).iter().copied())
1776     }
1777
1778     #[inline]
1779     pub fn local_visibility(self, def_id: LocalDefId) -> Visibility {
1780         self.visibility(def_id).expect_local()
1781     }
1782 }
1783
1784 /// A trait implemented for all `X<'a>` types that can be safely and
1785 /// efficiently converted to `X<'tcx>` as long as they are part of the
1786 /// provided `TyCtxt<'tcx>`.
1787 /// This can be done, for example, for `Ty<'tcx>` or `SubstsRef<'tcx>`
1788 /// by looking them up in their respective interners.
1789 ///
1790 /// However, this is still not the best implementation as it does
1791 /// need to compare the components, even for interned values.
1792 /// It would be more efficient if `TypedArena` provided a way to
1793 /// determine whether the address is in the allocated range.
1794 ///
1795 /// `None` is returned if the value or one of the components is not part
1796 /// of the provided context.
1797 /// For `Ty`, `None` can be returned if either the type interner doesn't
1798 /// contain the `TyKind` key or if the address of the interned
1799 /// pointer differs. The latter case is possible if a primitive type,
1800 /// e.g., `()` or `u8`, was interned in a different context.
1801 pub trait Lift<'tcx>: fmt::Debug {
1802     type Lifted: fmt::Debug + 'tcx;
1803     fn lift_to_tcx(self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted>;
1804 }
1805
1806 macro_rules! nop_lift {
1807     ($set:ident; $ty:ty => $lifted:ty) => {
1808         impl<'a, 'tcx> Lift<'tcx> for $ty {
1809             type Lifted = $lifted;
1810             fn lift_to_tcx(self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
1811                 if tcx.interners.$set.contains_pointer_to(&InternedInSet(&*self.0.0)) {
1812                     // SAFETY: `self` is interned and therefore valid
1813                     // for the entire lifetime of the `TyCtxt`.
1814                     Some(unsafe { mem::transmute(self) })
1815                 } else {
1816                     None
1817                 }
1818             }
1819         }
1820     };
1821 }
1822
1823 // Can't use the macros as we have reuse the `substs` here.
1824 //
1825 // See `intern_type_list` for more info.
1826 impl<'a, 'tcx> Lift<'tcx> for &'a List<Ty<'a>> {
1827     type Lifted = &'tcx List<Ty<'tcx>>;
1828     fn lift_to_tcx(self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
1829         if self.is_empty() {
1830             return Some(List::empty());
1831         }
1832         if tcx.interners.substs.contains_pointer_to(&InternedInSet(self.as_substs())) {
1833             // SAFETY: `self` is interned and therefore valid
1834             // for the entire lifetime of the `TyCtxt`.
1835             Some(unsafe { mem::transmute::<&'a List<Ty<'a>>, &'tcx List<Ty<'tcx>>>(self) })
1836         } else {
1837             None
1838         }
1839     }
1840 }
1841
1842 macro_rules! nop_list_lift {
1843     ($set:ident; $ty:ty => $lifted:ty) => {
1844         impl<'a, 'tcx> Lift<'tcx> for &'a List<$ty> {
1845             type Lifted = &'tcx List<$lifted>;
1846             fn lift_to_tcx(self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
1847                 if self.is_empty() {
1848                     return Some(List::empty());
1849                 }
1850                 if tcx.interners.$set.contains_pointer_to(&InternedInSet(self)) {
1851                     Some(unsafe { mem::transmute(self) })
1852                 } else {
1853                     None
1854                 }
1855             }
1856         }
1857     };
1858 }
1859
1860 nop_lift! {type_; Ty<'a> => Ty<'tcx>}
1861 nop_lift! {region; Region<'a> => Region<'tcx>}
1862 nop_lift! {const_; Const<'a> => Const<'tcx>}
1863 nop_lift! {const_allocation; ConstAllocation<'a> => ConstAllocation<'tcx>}
1864 nop_lift! {predicate; Predicate<'a> => Predicate<'tcx>}
1865
1866 nop_list_lift! {poly_existential_predicates; PolyExistentialPredicate<'a> => PolyExistentialPredicate<'tcx>}
1867 nop_list_lift! {predicates; Predicate<'a> => Predicate<'tcx>}
1868 nop_list_lift! {canonical_var_infos; CanonicalVarInfo<'a> => CanonicalVarInfo<'tcx>}
1869 nop_list_lift! {projs; ProjectionKind => ProjectionKind}
1870 nop_list_lift! {bound_variable_kinds; ty::BoundVariableKind => ty::BoundVariableKind}
1871
1872 // This is the impl for `&'a InternalSubsts<'a>`.
1873 nop_list_lift! {substs; GenericArg<'a> => GenericArg<'tcx>}
1874
1875 CloneLiftImpls! { for<'tcx> {
1876     Constness, traits::WellFormedLoc, ImplPolarity, crate::mir::ReturnConstraint,
1877 } }
1878
1879 pub mod tls {
1880     use super::{ptr_eq, GlobalCtxt, TyCtxt};
1881
1882     use crate::dep_graph::TaskDepsRef;
1883     use crate::ty::query;
1884     use rustc_data_structures::sync::{self, Lock};
1885     use rustc_errors::Diagnostic;
1886     use std::mem;
1887     use thin_vec::ThinVec;
1888
1889     #[cfg(not(parallel_compiler))]
1890     use std::cell::Cell;
1891
1892     #[cfg(parallel_compiler)]
1893     use rustc_rayon_core as rayon_core;
1894
1895     /// This is the implicit state of rustc. It contains the current
1896     /// `TyCtxt` and query. It is updated when creating a local interner or
1897     /// executing a new query. Whenever there's a `TyCtxt` value available
1898     /// you should also have access to an `ImplicitCtxt` through the functions
1899     /// in this module.
1900     #[derive(Clone)]
1901     pub struct ImplicitCtxt<'a, 'tcx> {
1902         /// The current `TyCtxt`.
1903         pub tcx: TyCtxt<'tcx>,
1904
1905         /// The current query job, if any. This is updated by `JobOwner::start` in
1906         /// `ty::query::plumbing` when executing a query.
1907         pub query: Option<query::QueryJobId>,
1908
1909         /// Where to store diagnostics for the current query job, if any.
1910         /// This is updated by `JobOwner::start` in `ty::query::plumbing` when executing a query.
1911         pub diagnostics: Option<&'a Lock<ThinVec<Diagnostic>>>,
1912
1913         /// Used to prevent queries from calling too deeply.
1914         pub query_depth: usize,
1915
1916         /// The current dep graph task. This is used to add dependencies to queries
1917         /// when executing them.
1918         pub task_deps: TaskDepsRef<'a>,
1919     }
1920
1921     impl<'a, 'tcx> ImplicitCtxt<'a, 'tcx> {
1922         pub fn new(gcx: &'tcx GlobalCtxt<'tcx>) -> Self {
1923             let tcx = TyCtxt { gcx };
1924             ImplicitCtxt {
1925                 tcx,
1926                 query: None,
1927                 diagnostics: None,
1928                 query_depth: 0,
1929                 task_deps: TaskDepsRef::Ignore,
1930             }
1931         }
1932     }
1933
1934     /// Sets Rayon's thread-local variable, which is preserved for Rayon jobs
1935     /// to `value` during the call to `f`. It is restored to its previous value after.
1936     /// This is used to set the pointer to the new `ImplicitCtxt`.
1937     #[cfg(parallel_compiler)]
1938     #[inline]
1939     fn set_tlv<F: FnOnce() -> R, R>(value: usize, f: F) -> R {
1940         rayon_core::tlv::with(value, f)
1941     }
1942
1943     /// Gets Rayon's thread-local variable, which is preserved for Rayon jobs.
1944     /// This is used to get the pointer to the current `ImplicitCtxt`.
1945     #[cfg(parallel_compiler)]
1946     #[inline]
1947     pub fn get_tlv() -> usize {
1948         rayon_core::tlv::get()
1949     }
1950
1951     #[cfg(not(parallel_compiler))]
1952     thread_local! {
1953         /// A thread local variable that stores a pointer to the current `ImplicitCtxt`.
1954         static TLV: Cell<usize> = const { Cell::new(0) };
1955     }
1956
1957     /// Sets TLV to `value` during the call to `f`.
1958     /// It is restored to its previous value after.
1959     /// This is used to set the pointer to the new `ImplicitCtxt`.
1960     #[cfg(not(parallel_compiler))]
1961     #[inline]
1962     fn set_tlv<F: FnOnce() -> R, R>(value: usize, f: F) -> R {
1963         let old = get_tlv();
1964         let _reset = rustc_data_structures::OnDrop(move || TLV.with(|tlv| tlv.set(old)));
1965         TLV.with(|tlv| tlv.set(value));
1966         f()
1967     }
1968
1969     /// Gets the pointer to the current `ImplicitCtxt`.
1970     #[cfg(not(parallel_compiler))]
1971     #[inline]
1972     fn get_tlv() -> usize {
1973         TLV.with(|tlv| tlv.get())
1974     }
1975
1976     /// Sets `context` as the new current `ImplicitCtxt` for the duration of the function `f`.
1977     #[inline]
1978     pub fn enter_context<'a, 'tcx, F, R>(context: &ImplicitCtxt<'a, 'tcx>, f: F) -> R
1979     where
1980         F: FnOnce(&ImplicitCtxt<'a, 'tcx>) -> R,
1981     {
1982         set_tlv(context as *const _ as usize, || f(&context))
1983     }
1984
1985     /// Allows access to the current `ImplicitCtxt` in a closure if one is available.
1986     #[inline]
1987     pub fn with_context_opt<F, R>(f: F) -> R
1988     where
1989         F: for<'a, 'tcx> FnOnce(Option<&ImplicitCtxt<'a, 'tcx>>) -> R,
1990     {
1991         let context = get_tlv();
1992         if context == 0 {
1993             f(None)
1994         } else {
1995             // We could get an `ImplicitCtxt` pointer from another thread.
1996             // Ensure that `ImplicitCtxt` is `Sync`.
1997             sync::assert_sync::<ImplicitCtxt<'_, '_>>();
1998
1999             unsafe { f(Some(&*(context as *const ImplicitCtxt<'_, '_>))) }
2000         }
2001     }
2002
2003     /// Allows access to the current `ImplicitCtxt`.
2004     /// Panics if there is no `ImplicitCtxt` available.
2005     #[inline]
2006     pub fn with_context<F, R>(f: F) -> R
2007     where
2008         F: for<'a, 'tcx> FnOnce(&ImplicitCtxt<'a, 'tcx>) -> R,
2009     {
2010         with_context_opt(|opt_context| f(opt_context.expect("no ImplicitCtxt stored in tls")))
2011     }
2012
2013     /// Allows access to the current `ImplicitCtxt` whose tcx field is the same as the tcx argument
2014     /// passed in. This means the closure is given an `ImplicitCtxt` with the same `'tcx` lifetime
2015     /// as the `TyCtxt` passed in.
2016     /// This will panic if you pass it a `TyCtxt` which is different from the current
2017     /// `ImplicitCtxt`'s `tcx` field.
2018     #[inline]
2019     pub fn with_related_context<'tcx, F, R>(tcx: TyCtxt<'tcx>, f: F) -> R
2020     where
2021         F: FnOnce(&ImplicitCtxt<'_, 'tcx>) -> R,
2022     {
2023         with_context(|context| unsafe {
2024             assert!(ptr_eq(context.tcx.gcx, tcx.gcx));
2025             let context: &ImplicitCtxt<'_, '_> = mem::transmute(context);
2026             f(context)
2027         })
2028     }
2029
2030     /// Allows access to the `TyCtxt` in the current `ImplicitCtxt`.
2031     /// Panics if there is no `ImplicitCtxt` available.
2032     #[inline]
2033     pub fn with<F, R>(f: F) -> R
2034     where
2035         F: for<'tcx> FnOnce(TyCtxt<'tcx>) -> R,
2036     {
2037         with_context(|context| f(context.tcx))
2038     }
2039
2040     /// Allows access to the `TyCtxt` in the current `ImplicitCtxt`.
2041     /// The closure is passed None if there is no `ImplicitCtxt` available.
2042     #[inline]
2043     pub fn with_opt<F, R>(f: F) -> R
2044     where
2045         F: for<'tcx> FnOnce(Option<TyCtxt<'tcx>>) -> R,
2046     {
2047         with_context_opt(|opt_context| f(opt_context.map(|context| context.tcx)))
2048     }
2049 }
2050
2051 macro_rules! sty_debug_print {
2052     ($fmt: expr, $ctxt: expr, $($variant: ident),*) => {{
2053         // Curious inner module to allow variant names to be used as
2054         // variable names.
2055         #[allow(non_snake_case)]
2056         mod inner {
2057             use crate::ty::{self, TyCtxt};
2058             use crate::ty::context::InternedInSet;
2059
2060             #[derive(Copy, Clone)]
2061             struct DebugStat {
2062                 total: usize,
2063                 lt_infer: usize,
2064                 ty_infer: usize,
2065                 ct_infer: usize,
2066                 all_infer: usize,
2067             }
2068
2069             pub fn go(fmt: &mut std::fmt::Formatter<'_>, tcx: TyCtxt<'_>) -> std::fmt::Result {
2070                 let mut total = DebugStat {
2071                     total: 0,
2072                     lt_infer: 0,
2073                     ty_infer: 0,
2074                     ct_infer: 0,
2075                     all_infer: 0,
2076                 };
2077                 $(let mut $variant = total;)*
2078
2079                 let shards = tcx.interners.type_.lock_shards();
2080                 let types = shards.iter().flat_map(|shard| shard.keys());
2081                 for &InternedInSet(t) in types {
2082                     let variant = match t.internee {
2083                         ty::Bool | ty::Char | ty::Int(..) | ty::Uint(..) |
2084                             ty::Float(..) | ty::Str | ty::Never => continue,
2085                         ty::Error(_) => /* unimportant */ continue,
2086                         $(ty::$variant(..) => &mut $variant,)*
2087                     };
2088                     let lt = t.flags.intersects(ty::TypeFlags::HAS_RE_INFER);
2089                     let ty = t.flags.intersects(ty::TypeFlags::HAS_TY_INFER);
2090                     let ct = t.flags.intersects(ty::TypeFlags::HAS_CT_INFER);
2091
2092                     variant.total += 1;
2093                     total.total += 1;
2094                     if lt { total.lt_infer += 1; variant.lt_infer += 1 }
2095                     if ty { total.ty_infer += 1; variant.ty_infer += 1 }
2096                     if ct { total.ct_infer += 1; variant.ct_infer += 1 }
2097                     if lt && ty && ct { total.all_infer += 1; variant.all_infer += 1 }
2098                 }
2099                 writeln!(fmt, "Ty interner             total           ty lt ct all")?;
2100                 $(writeln!(fmt, "    {:18}: {uses:6} {usespc:4.1}%, \
2101                             {ty:4.1}% {lt:5.1}% {ct:4.1}% {all:4.1}%",
2102                     stringify!($variant),
2103                     uses = $variant.total,
2104                     usespc = $variant.total as f64 * 100.0 / total.total as f64,
2105                     ty = $variant.ty_infer as f64 * 100.0  / total.total as f64,
2106                     lt = $variant.lt_infer as f64 * 100.0  / total.total as f64,
2107                     ct = $variant.ct_infer as f64 * 100.0  / total.total as f64,
2108                     all = $variant.all_infer as f64 * 100.0  / total.total as f64)?;
2109                 )*
2110                 writeln!(fmt, "                  total {uses:6}        \
2111                           {ty:4.1}% {lt:5.1}% {ct:4.1}% {all:4.1}%",
2112                     uses = total.total,
2113                     ty = total.ty_infer as f64 * 100.0  / total.total as f64,
2114                     lt = total.lt_infer as f64 * 100.0  / total.total as f64,
2115                     ct = total.ct_infer as f64 * 100.0  / total.total as f64,
2116                     all = total.all_infer as f64 * 100.0  / total.total as f64)
2117             }
2118         }
2119
2120         inner::go($fmt, $ctxt)
2121     }}
2122 }
2123
2124 impl<'tcx> TyCtxt<'tcx> {
2125     pub fn debug_stats(self) -> impl std::fmt::Debug + 'tcx {
2126         struct DebugStats<'tcx>(TyCtxt<'tcx>);
2127
2128         impl<'tcx> std::fmt::Debug for DebugStats<'tcx> {
2129             fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2130                 sty_debug_print!(
2131                     fmt,
2132                     self.0,
2133                     Adt,
2134                     Array,
2135                     Slice,
2136                     RawPtr,
2137                     Ref,
2138                     FnDef,
2139                     FnPtr,
2140                     Placeholder,
2141                     Generator,
2142                     GeneratorWitness,
2143                     Dynamic,
2144                     Closure,
2145                     Tuple,
2146                     Bound,
2147                     Param,
2148                     Infer,
2149                     Projection,
2150                     Opaque,
2151                     Foreign
2152                 )?;
2153
2154                 writeln!(fmt, "InternalSubsts interner: #{}", self.0.interners.substs.len())?;
2155                 writeln!(fmt, "Region interner: #{}", self.0.interners.region.len())?;
2156                 writeln!(
2157                     fmt,
2158                     "Const Allocation interner: #{}",
2159                     self.0.interners.const_allocation.len()
2160                 )?;
2161                 writeln!(fmt, "Layout interner: #{}", self.0.interners.layout.len())?;
2162
2163                 Ok(())
2164             }
2165         }
2166
2167         DebugStats(self)
2168     }
2169 }
2170
2171 // This type holds a `T` in the interner. The `T` is stored in the arena and
2172 // this type just holds a pointer to it, but it still effectively owns it. It
2173 // impls `Borrow` so that it can be looked up using the original
2174 // (non-arena-memory-owning) types.
2175 struct InternedInSet<'tcx, T: ?Sized>(&'tcx T);
2176
2177 impl<'tcx, T: 'tcx + ?Sized> Clone for InternedInSet<'tcx, T> {
2178     fn clone(&self) -> Self {
2179         InternedInSet(self.0)
2180     }
2181 }
2182
2183 impl<'tcx, T: 'tcx + ?Sized> Copy for InternedInSet<'tcx, T> {}
2184
2185 impl<'tcx, T: 'tcx + ?Sized> IntoPointer for InternedInSet<'tcx, T> {
2186     fn into_pointer(&self) -> *const () {
2187         self.0 as *const _ as *const ()
2188     }
2189 }
2190
2191 #[allow(rustc::usage_of_ty_tykind)]
2192 impl<'tcx, T> Borrow<T> for InternedInSet<'tcx, WithCachedTypeInfo<T>> {
2193     fn borrow<'a>(&'a self) -> &'a T {
2194         &self.0.internee
2195     }
2196 }
2197
2198 impl<'tcx, T: PartialEq> PartialEq for InternedInSet<'tcx, WithCachedTypeInfo<T>> {
2199     fn eq(&self, other: &InternedInSet<'tcx, WithCachedTypeInfo<T>>) -> bool {
2200         // The `Borrow` trait requires that `x.borrow() == y.borrow()` equals
2201         // `x == y`.
2202         self.0.internee == other.0.internee
2203     }
2204 }
2205
2206 impl<'tcx, T: Eq> Eq for InternedInSet<'tcx, WithCachedTypeInfo<T>> {}
2207
2208 impl<'tcx, T: Hash> Hash for InternedInSet<'tcx, WithCachedTypeInfo<T>> {
2209     fn hash<H: Hasher>(&self, s: &mut H) {
2210         // The `Borrow` trait requires that `x.borrow().hash(s) == x.hash(s)`.
2211         self.0.internee.hash(s)
2212     }
2213 }
2214
2215 impl<'tcx, T> Borrow<[T]> for InternedInSet<'tcx, List<T>> {
2216     fn borrow<'a>(&'a self) -> &'a [T] {
2217         &self.0[..]
2218     }
2219 }
2220
2221 impl<'tcx, T: PartialEq> PartialEq for InternedInSet<'tcx, List<T>> {
2222     fn eq(&self, other: &InternedInSet<'tcx, List<T>>) -> bool {
2223         // The `Borrow` trait requires that `x.borrow() == y.borrow()` equals
2224         // `x == y`.
2225         self.0[..] == other.0[..]
2226     }
2227 }
2228
2229 impl<'tcx, T: Eq> Eq for InternedInSet<'tcx, List<T>> {}
2230
2231 impl<'tcx, T: Hash> Hash for InternedInSet<'tcx, List<T>> {
2232     fn hash<H: Hasher>(&self, s: &mut H) {
2233         // The `Borrow` trait requires that `x.borrow().hash(s) == x.hash(s)`.
2234         self.0[..].hash(s)
2235     }
2236 }
2237
2238 macro_rules! direct_interners {
2239     ($($name:ident: $method:ident($ty:ty): $ret_ctor:ident -> $ret_ty:ty,)+) => {
2240         $(impl<'tcx> Borrow<$ty> for InternedInSet<'tcx, $ty> {
2241             fn borrow<'a>(&'a self) -> &'a $ty {
2242                 &self.0
2243             }
2244         }
2245
2246         impl<'tcx> PartialEq for InternedInSet<'tcx, $ty> {
2247             fn eq(&self, other: &Self) -> bool {
2248                 // The `Borrow` trait requires that `x.borrow() == y.borrow()`
2249                 // equals `x == y`.
2250                 self.0 == other.0
2251             }
2252         }
2253
2254         impl<'tcx> Eq for InternedInSet<'tcx, $ty> {}
2255
2256         impl<'tcx> Hash for InternedInSet<'tcx, $ty> {
2257             fn hash<H: Hasher>(&self, s: &mut H) {
2258                 // The `Borrow` trait requires that `x.borrow().hash(s) ==
2259                 // x.hash(s)`.
2260                 self.0.hash(s)
2261             }
2262         }
2263
2264         impl<'tcx> TyCtxt<'tcx> {
2265             pub fn $method(self, v: $ty) -> $ret_ty {
2266                 $ret_ctor(Interned::new_unchecked(self.interners.$name.intern(v, |v| {
2267                     InternedInSet(self.interners.arena.alloc(v))
2268                 }).0))
2269             }
2270         })+
2271     }
2272 }
2273
2274 direct_interners! {
2275     region: mk_region(RegionKind<'tcx>): Region -> Region<'tcx>,
2276     const_: mk_const_internal(ConstS<'tcx>): Const -> Const<'tcx>,
2277     const_allocation: intern_const_alloc(Allocation): ConstAllocation -> ConstAllocation<'tcx>,
2278     layout: intern_layout(LayoutS<VariantIdx>): Layout -> Layout<'tcx>,
2279     adt_def: intern_adt_def(AdtDefData): AdtDef -> AdtDef<'tcx>,
2280 }
2281
2282 macro_rules! slice_interners {
2283     ($($field:ident: $method:ident($ty:ty)),+ $(,)?) => (
2284         impl<'tcx> TyCtxt<'tcx> {
2285             $(pub fn $method(self, v: &[$ty]) -> &'tcx List<$ty> {
2286                 self.interners.$field.intern_ref(v, || {
2287                     InternedInSet(List::from_arena(&*self.arena, v))
2288                 }).0
2289             })+
2290         }
2291     );
2292 }
2293
2294 slice_interners!(
2295     const_lists: _intern_const_list(Const<'tcx>),
2296     substs: _intern_substs(GenericArg<'tcx>),
2297     canonical_var_infos: _intern_canonical_var_infos(CanonicalVarInfo<'tcx>),
2298     poly_existential_predicates:
2299         _intern_poly_existential_predicates(PolyExistentialPredicate<'tcx>),
2300     predicates: _intern_predicates(Predicate<'tcx>),
2301     projs: _intern_projs(ProjectionKind),
2302     place_elems: _intern_place_elems(PlaceElem<'tcx>),
2303     bound_variable_kinds: _intern_bound_variable_kinds(ty::BoundVariableKind),
2304 );
2305
2306 impl<'tcx> TyCtxt<'tcx> {
2307     /// Given a `fn` type, returns an equivalent `unsafe fn` type;
2308     /// that is, a `fn` type that is equivalent in every way for being
2309     /// unsafe.
2310     pub fn safe_to_unsafe_fn_ty(self, sig: PolyFnSig<'tcx>) -> Ty<'tcx> {
2311         assert_eq!(sig.unsafety(), hir::Unsafety::Normal);
2312         self.mk_fn_ptr(sig.map_bound(|sig| ty::FnSig { unsafety: hir::Unsafety::Unsafe, ..sig }))
2313     }
2314
2315     /// Given the def_id of a Trait `trait_def_id` and the name of an associated item `assoc_name`
2316     /// returns true if the `trait_def_id` defines an associated item of name `assoc_name`.
2317     pub fn trait_may_define_assoc_type(self, trait_def_id: DefId, assoc_name: Ident) -> bool {
2318         self.super_traits_of(trait_def_id).any(|trait_did| {
2319             self.associated_items(trait_did)
2320                 .find_by_name_and_kind(self, assoc_name, ty::AssocKind::Type, trait_did)
2321                 .is_some()
2322         })
2323     }
2324
2325     /// Given a `ty`, return whether it's an `impl Future<...>`.
2326     pub fn ty_is_opaque_future(self, ty: Ty<'_>) -> bool {
2327         let ty::Opaque(ty::OpaqueTy { def_id, substs: _ }) = ty.kind() else { return false };
2328         let future_trait = self.require_lang_item(LangItem::Future, None);
2329
2330         self.explicit_item_bounds(def_id).iter().any(|(predicate, _)| {
2331             let ty::PredicateKind::Clause(ty::Clause::Trait(trait_predicate)) = predicate.kind().skip_binder() else {
2332                 return false;
2333             };
2334             trait_predicate.trait_ref.def_id == future_trait
2335                 && trait_predicate.polarity == ImplPolarity::Positive
2336         })
2337     }
2338
2339     /// Computes the def-ids of the transitive supertraits of `trait_def_id`. This (intentionally)
2340     /// does not compute the full elaborated super-predicates but just the set of def-ids. It is used
2341     /// to identify which traits may define a given associated type to help avoid cycle errors.
2342     /// Returns a `DefId` iterator.
2343     fn super_traits_of(self, trait_def_id: DefId) -> impl Iterator<Item = DefId> + 'tcx {
2344         let mut set = FxHashSet::default();
2345         let mut stack = vec![trait_def_id];
2346
2347         set.insert(trait_def_id);
2348
2349         iter::from_fn(move || -> Option<DefId> {
2350             let trait_did = stack.pop()?;
2351             let generic_predicates = self.super_predicates_of(trait_did);
2352
2353             for (predicate, _) in generic_predicates.predicates {
2354                 if let ty::PredicateKind::Clause(ty::Clause::Trait(data)) =
2355                     predicate.kind().skip_binder()
2356                 {
2357                     if set.insert(data.def_id()) {
2358                         stack.push(data.def_id());
2359                     }
2360                 }
2361             }
2362
2363             Some(trait_did)
2364         })
2365     }
2366
2367     /// Given a closure signature, returns an equivalent fn signature. Detuples
2368     /// and so forth -- so e.g., if we have a sig with `Fn<(u32, i32)>` then
2369     /// you would get a `fn(u32, i32)`.
2370     /// `unsafety` determines the unsafety of the fn signature. If you pass
2371     /// `hir::Unsafety::Unsafe` in the previous example, then you would get
2372     /// an `unsafe fn (u32, i32)`.
2373     /// It cannot convert a closure that requires unsafe.
2374     pub fn signature_unclosure(
2375         self,
2376         sig: PolyFnSig<'tcx>,
2377         unsafety: hir::Unsafety,
2378     ) -> PolyFnSig<'tcx> {
2379         sig.map_bound(|s| {
2380             let params_iter = match s.inputs()[0].kind() {
2381                 ty::Tuple(params) => params.into_iter(),
2382                 _ => bug!(),
2383             };
2384             self.mk_fn_sig(params_iter, s.output(), s.c_variadic, unsafety, abi::Abi::Rust)
2385         })
2386     }
2387
2388     /// Same a `self.mk_region(kind)`, but avoids accessing the interners if
2389     /// `*r == kind`.
2390     #[inline]
2391     pub fn reuse_or_mk_region(self, r: Region<'tcx>, kind: RegionKind<'tcx>) -> Region<'tcx> {
2392         if *r == kind { r } else { self.mk_region(kind) }
2393     }
2394
2395     #[allow(rustc::usage_of_ty_tykind)]
2396     #[inline]
2397     pub fn mk_ty(self, st: TyKind<'tcx>) -> Ty<'tcx> {
2398         self.interners.intern_ty(
2399             st,
2400             self.sess,
2401             // This is only used to create a stable hashing context.
2402             &self.untracked,
2403         )
2404     }
2405
2406     #[inline]
2407     pub fn mk_predicate(self, binder: Binder<'tcx, PredicateKind<'tcx>>) -> Predicate<'tcx> {
2408         self.interners.intern_predicate(
2409             binder,
2410             self.sess,
2411             // This is only used to create a stable hashing context.
2412             &self.untracked,
2413         )
2414     }
2415
2416     #[inline]
2417     pub fn reuse_or_mk_predicate(
2418         self,
2419         pred: Predicate<'tcx>,
2420         binder: Binder<'tcx, PredicateKind<'tcx>>,
2421     ) -> Predicate<'tcx> {
2422         if pred.kind() != binder { self.mk_predicate(binder) } else { pred }
2423     }
2424
2425     pub fn mk_mach_int(self, tm: IntTy) -> Ty<'tcx> {
2426         match tm {
2427             IntTy::Isize => self.types.isize,
2428             IntTy::I8 => self.types.i8,
2429             IntTy::I16 => self.types.i16,
2430             IntTy::I32 => self.types.i32,
2431             IntTy::I64 => self.types.i64,
2432             IntTy::I128 => self.types.i128,
2433         }
2434     }
2435
2436     pub fn mk_mach_uint(self, tm: UintTy) -> Ty<'tcx> {
2437         match tm {
2438             UintTy::Usize => self.types.usize,
2439             UintTy::U8 => self.types.u8,
2440             UintTy::U16 => self.types.u16,
2441             UintTy::U32 => self.types.u32,
2442             UintTy::U64 => self.types.u64,
2443             UintTy::U128 => self.types.u128,
2444         }
2445     }
2446
2447     pub fn mk_mach_float(self, tm: FloatTy) -> Ty<'tcx> {
2448         match tm {
2449             FloatTy::F32 => self.types.f32,
2450             FloatTy::F64 => self.types.f64,
2451         }
2452     }
2453
2454     #[inline]
2455     pub fn mk_static_str(self) -> Ty<'tcx> {
2456         self.mk_imm_ref(self.lifetimes.re_static, self.types.str_)
2457     }
2458
2459     #[inline]
2460     pub fn mk_adt(self, def: AdtDef<'tcx>, substs: SubstsRef<'tcx>) -> Ty<'tcx> {
2461         // Take a copy of substs so that we own the vectors inside.
2462         self.mk_ty(Adt(def, substs))
2463     }
2464
2465     #[inline]
2466     pub fn mk_foreign(self, def_id: DefId) -> Ty<'tcx> {
2467         self.mk_ty(Foreign(def_id))
2468     }
2469
2470     fn mk_generic_adt(self, wrapper_def_id: DefId, ty_param: Ty<'tcx>) -> Ty<'tcx> {
2471         let adt_def = self.adt_def(wrapper_def_id);
2472         let substs =
2473             InternalSubsts::for_item(self, wrapper_def_id, |param, substs| match param.kind {
2474                 GenericParamDefKind::Lifetime | GenericParamDefKind::Const { .. } => bug!(),
2475                 GenericParamDefKind::Type { has_default, .. } => {
2476                     if param.index == 0 {
2477                         ty_param.into()
2478                     } else {
2479                         assert!(has_default);
2480                         self.bound_type_of(param.def_id).subst(self, substs).into()
2481                     }
2482                 }
2483             });
2484         self.mk_ty(Adt(adt_def, substs))
2485     }
2486
2487     #[inline]
2488     pub fn mk_box(self, ty: Ty<'tcx>) -> Ty<'tcx> {
2489         let def_id = self.require_lang_item(LangItem::OwnedBox, None);
2490         self.mk_generic_adt(def_id, ty)
2491     }
2492
2493     #[inline]
2494     pub fn mk_lang_item(self, ty: Ty<'tcx>, item: LangItem) -> Option<Ty<'tcx>> {
2495         let def_id = self.lang_items().get(item)?;
2496         Some(self.mk_generic_adt(def_id, ty))
2497     }
2498
2499     #[inline]
2500     pub fn mk_diagnostic_item(self, ty: Ty<'tcx>, name: Symbol) -> Option<Ty<'tcx>> {
2501         let def_id = self.get_diagnostic_item(name)?;
2502         Some(self.mk_generic_adt(def_id, ty))
2503     }
2504
2505     #[inline]
2506     pub fn mk_maybe_uninit(self, ty: Ty<'tcx>) -> Ty<'tcx> {
2507         let def_id = self.require_lang_item(LangItem::MaybeUninit, None);
2508         self.mk_generic_adt(def_id, ty)
2509     }
2510
2511     #[inline]
2512     pub fn mk_ptr(self, tm: TypeAndMut<'tcx>) -> Ty<'tcx> {
2513         self.mk_ty(RawPtr(tm))
2514     }
2515
2516     #[inline]
2517     pub fn mk_ref(self, r: Region<'tcx>, tm: TypeAndMut<'tcx>) -> Ty<'tcx> {
2518         self.mk_ty(Ref(r, tm.ty, tm.mutbl))
2519     }
2520
2521     #[inline]
2522     pub fn mk_mut_ref(self, r: Region<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
2523         self.mk_ref(r, TypeAndMut { ty, mutbl: hir::Mutability::Mut })
2524     }
2525
2526     #[inline]
2527     pub fn mk_imm_ref(self, r: Region<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
2528         self.mk_ref(r, TypeAndMut { ty, mutbl: hir::Mutability::Not })
2529     }
2530
2531     #[inline]
2532     pub fn mk_mut_ptr(self, ty: Ty<'tcx>) -> Ty<'tcx> {
2533         self.mk_ptr(TypeAndMut { ty, mutbl: hir::Mutability::Mut })
2534     }
2535
2536     #[inline]
2537     pub fn mk_imm_ptr(self, ty: Ty<'tcx>) -> Ty<'tcx> {
2538         self.mk_ptr(TypeAndMut { ty, mutbl: hir::Mutability::Not })
2539     }
2540
2541     #[inline]
2542     pub fn mk_array(self, ty: Ty<'tcx>, n: u64) -> Ty<'tcx> {
2543         self.mk_ty(Array(ty, ty::Const::from_usize(self, n)))
2544     }
2545
2546     #[inline]
2547     pub fn mk_slice(self, ty: Ty<'tcx>) -> Ty<'tcx> {
2548         self.mk_ty(Slice(ty))
2549     }
2550
2551     #[inline]
2552     pub fn intern_tup(self, ts: &[Ty<'tcx>]) -> Ty<'tcx> {
2553         self.mk_ty(Tuple(self.intern_type_list(&ts)))
2554     }
2555
2556     pub fn mk_tup<I: InternAs<Ty<'tcx>, Ty<'tcx>>>(self, iter: I) -> I::Output {
2557         iter.intern_with(|ts| self.mk_ty(Tuple(self.intern_type_list(&ts))))
2558     }
2559
2560     #[inline]
2561     pub fn mk_unit(self) -> Ty<'tcx> {
2562         self.types.unit
2563     }
2564
2565     #[inline]
2566     pub fn mk_diverging_default(self) -> Ty<'tcx> {
2567         if self.features().never_type_fallback { self.types.never } else { self.types.unit }
2568     }
2569
2570     #[inline]
2571     pub fn mk_fn_def(self, def_id: DefId, substs: SubstsRef<'tcx>) -> Ty<'tcx> {
2572         debug_assert_eq!(
2573             self.generics_of(def_id).count(),
2574             substs.len(),
2575             "wrong number of generic parameters for {def_id:?}: {substs:?}",
2576         );
2577         self.mk_ty(FnDef(def_id, substs))
2578     }
2579
2580     #[inline]
2581     pub fn mk_fn_ptr(self, fty: PolyFnSig<'tcx>) -> Ty<'tcx> {
2582         self.mk_ty(FnPtr(fty))
2583     }
2584
2585     #[inline]
2586     pub fn mk_dynamic(
2587         self,
2588         obj: &'tcx List<PolyExistentialPredicate<'tcx>>,
2589         reg: ty::Region<'tcx>,
2590         repr: DynKind,
2591     ) -> Ty<'tcx> {
2592         self.mk_ty(Dynamic(obj, reg, repr))
2593     }
2594
2595     #[inline]
2596     pub fn mk_projection(self, item_def_id: DefId, substs: SubstsRef<'tcx>) -> Ty<'tcx> {
2597         debug_assert_eq!(
2598             self.generics_of(item_def_id).count(),
2599             substs.len(),
2600             "wrong number of generic parameters for {item_def_id:?}: {substs:?}",
2601         );
2602         self.mk_ty(Projection(ProjectionTy { def_id: item_def_id, substs }))
2603     }
2604
2605     #[inline]
2606     pub fn mk_closure(self, closure_id: DefId, closure_substs: SubstsRef<'tcx>) -> Ty<'tcx> {
2607         self.mk_ty(Closure(closure_id, closure_substs))
2608     }
2609
2610     #[inline]
2611     pub fn mk_generator(
2612         self,
2613         id: DefId,
2614         generator_substs: SubstsRef<'tcx>,
2615         movability: hir::Movability,
2616     ) -> Ty<'tcx> {
2617         self.mk_ty(Generator(id, generator_substs, movability))
2618     }
2619
2620     #[inline]
2621     pub fn mk_generator_witness(self, types: ty::Binder<'tcx, &'tcx List<Ty<'tcx>>>) -> Ty<'tcx> {
2622         self.mk_ty(GeneratorWitness(types))
2623     }
2624
2625     #[inline]
2626     pub fn mk_ty_var(self, v: TyVid) -> Ty<'tcx> {
2627         self.mk_ty_infer(TyVar(v))
2628     }
2629
2630     #[inline]
2631     pub fn mk_const(self, kind: impl Into<ty::ConstKind<'tcx>>, ty: Ty<'tcx>) -> Const<'tcx> {
2632         self.mk_const_internal(ty::ConstS { kind: kind.into(), ty })
2633     }
2634
2635     #[inline]
2636     pub fn mk_int_var(self, v: IntVid) -> Ty<'tcx> {
2637         self.mk_ty_infer(IntVar(v))
2638     }
2639
2640     #[inline]
2641     pub fn mk_float_var(self, v: FloatVid) -> Ty<'tcx> {
2642         self.mk_ty_infer(FloatVar(v))
2643     }
2644
2645     #[inline]
2646     pub fn mk_ty_infer(self, it: InferTy) -> Ty<'tcx> {
2647         self.mk_ty(Infer(it))
2648     }
2649
2650     #[inline]
2651     pub fn mk_ty_param(self, index: u32, name: Symbol) -> Ty<'tcx> {
2652         self.mk_ty(Param(ParamTy { index, name }))
2653     }
2654
2655     pub fn mk_param_from_def(self, param: &ty::GenericParamDef) -> GenericArg<'tcx> {
2656         match param.kind {
2657             GenericParamDefKind::Lifetime => {
2658                 self.mk_region(ty::ReEarlyBound(param.to_early_bound_region_data())).into()
2659             }
2660             GenericParamDefKind::Type { .. } => self.mk_ty_param(param.index, param.name).into(),
2661             GenericParamDefKind::Const { .. } => self
2662                 .mk_const(
2663                     ParamConst { index: param.index, name: param.name },
2664                     self.type_of(param.def_id),
2665                 )
2666                 .into(),
2667         }
2668     }
2669
2670     #[inline]
2671     pub fn mk_opaque(self, def_id: DefId, substs: SubstsRef<'tcx>) -> Ty<'tcx> {
2672         self.mk_ty(Opaque(ty::OpaqueTy { def_id, substs }))
2673     }
2674
2675     pub fn mk_place_field(self, place: Place<'tcx>, f: Field, ty: Ty<'tcx>) -> Place<'tcx> {
2676         self.mk_place_elem(place, PlaceElem::Field(f, ty))
2677     }
2678
2679     pub fn mk_place_deref(self, place: Place<'tcx>) -> Place<'tcx> {
2680         self.mk_place_elem(place, PlaceElem::Deref)
2681     }
2682
2683     pub fn mk_place_downcast(
2684         self,
2685         place: Place<'tcx>,
2686         adt_def: AdtDef<'tcx>,
2687         variant_index: VariantIdx,
2688     ) -> Place<'tcx> {
2689         self.mk_place_elem(
2690             place,
2691             PlaceElem::Downcast(Some(adt_def.variant(variant_index).name), variant_index),
2692         )
2693     }
2694
2695     pub fn mk_place_downcast_unnamed(
2696         self,
2697         place: Place<'tcx>,
2698         variant_index: VariantIdx,
2699     ) -> Place<'tcx> {
2700         self.mk_place_elem(place, PlaceElem::Downcast(None, variant_index))
2701     }
2702
2703     pub fn mk_place_index(self, place: Place<'tcx>, index: Local) -> Place<'tcx> {
2704         self.mk_place_elem(place, PlaceElem::Index(index))
2705     }
2706
2707     /// This method copies `Place`'s projection, add an element and reintern it. Should not be used
2708     /// to build a full `Place` it's just a convenient way to grab a projection and modify it in
2709     /// flight.
2710     pub fn mk_place_elem(self, place: Place<'tcx>, elem: PlaceElem<'tcx>) -> Place<'tcx> {
2711         let mut projection = place.projection.to_vec();
2712         projection.push(elem);
2713
2714         Place { local: place.local, projection: self.intern_place_elems(&projection) }
2715     }
2716
2717     pub fn intern_poly_existential_predicates(
2718         self,
2719         eps: &[PolyExistentialPredicate<'tcx>],
2720     ) -> &'tcx List<PolyExistentialPredicate<'tcx>> {
2721         assert!(!eps.is_empty());
2722         assert!(
2723             eps.array_windows()
2724                 .all(|[a, b]| a.skip_binder().stable_cmp(self, &b.skip_binder())
2725                     != Ordering::Greater)
2726         );
2727         self._intern_poly_existential_predicates(eps)
2728     }
2729
2730     pub fn intern_predicates(self, preds: &[Predicate<'tcx>]) -> &'tcx List<Predicate<'tcx>> {
2731         // FIXME consider asking the input slice to be sorted to avoid
2732         // re-interning permutations, in which case that would be asserted
2733         // here.
2734         if preds.is_empty() {
2735             // The macro-generated method below asserts we don't intern an empty slice.
2736             List::empty()
2737         } else {
2738             self._intern_predicates(preds)
2739         }
2740     }
2741
2742     pub fn mk_const_list<I: InternAs<ty::Const<'tcx>, &'tcx List<ty::Const<'tcx>>>>(
2743         self,
2744         iter: I,
2745     ) -> I::Output {
2746         iter.intern_with(|xs| self.intern_const_list(xs))
2747     }
2748
2749     pub fn intern_const_list(self, cs: &[ty::Const<'tcx>]) -> &'tcx List<ty::Const<'tcx>> {
2750         if cs.is_empty() { List::empty() } else { self._intern_const_list(cs) }
2751     }
2752
2753     pub fn intern_type_list(self, ts: &[Ty<'tcx>]) -> &'tcx List<Ty<'tcx>> {
2754         if ts.is_empty() {
2755             List::empty()
2756         } else {
2757             // Actually intern type lists as lists of `GenericArg`s.
2758             //
2759             // Transmuting from `Ty<'tcx>` to `GenericArg<'tcx>` is sound
2760             // as explained in ty_slice_as_generic_arg`. With this,
2761             // we guarantee that even when transmuting between `List<Ty<'tcx>>`
2762             // and `List<GenericArg<'tcx>>`, the uniqueness requirement for
2763             // lists is upheld.
2764             let substs = self._intern_substs(ty::subst::ty_slice_as_generic_args(ts));
2765             substs.try_as_type_list().unwrap()
2766         }
2767     }
2768
2769     pub fn intern_substs(self, ts: &[GenericArg<'tcx>]) -> &'tcx List<GenericArg<'tcx>> {
2770         if ts.is_empty() { List::empty() } else { self._intern_substs(ts) }
2771     }
2772
2773     pub fn intern_projs(self, ps: &[ProjectionKind]) -> &'tcx List<ProjectionKind> {
2774         if ps.is_empty() { List::empty() } else { self._intern_projs(ps) }
2775     }
2776
2777     pub fn intern_place_elems(self, ts: &[PlaceElem<'tcx>]) -> &'tcx List<PlaceElem<'tcx>> {
2778         if ts.is_empty() { List::empty() } else { self._intern_place_elems(ts) }
2779     }
2780
2781     pub fn intern_canonical_var_infos(
2782         self,
2783         ts: &[CanonicalVarInfo<'tcx>],
2784     ) -> CanonicalVarInfos<'tcx> {
2785         if ts.is_empty() { List::empty() } else { self._intern_canonical_var_infos(ts) }
2786     }
2787
2788     pub fn intern_bound_variable_kinds(
2789         self,
2790         ts: &[ty::BoundVariableKind],
2791     ) -> &'tcx List<ty::BoundVariableKind> {
2792         if ts.is_empty() { List::empty() } else { self._intern_bound_variable_kinds(ts) }
2793     }
2794
2795     pub fn mk_fn_sig<I>(
2796         self,
2797         inputs: I,
2798         output: I::Item,
2799         c_variadic: bool,
2800         unsafety: hir::Unsafety,
2801         abi: abi::Abi,
2802     ) -> <I::Item as InternIteratorElement<Ty<'tcx>, ty::FnSig<'tcx>>>::Output
2803     where
2804         I: Iterator<Item: InternIteratorElement<Ty<'tcx>, ty::FnSig<'tcx>>>,
2805     {
2806         inputs.chain(iter::once(output)).intern_with(|xs| ty::FnSig {
2807             inputs_and_output: self.intern_type_list(xs),
2808             c_variadic,
2809             unsafety,
2810             abi,
2811         })
2812     }
2813
2814     pub fn mk_poly_existential_predicates<
2815         I: InternAs<PolyExistentialPredicate<'tcx>, &'tcx List<PolyExistentialPredicate<'tcx>>>,
2816     >(
2817         self,
2818         iter: I,
2819     ) -> I::Output {
2820         iter.intern_with(|xs| self.intern_poly_existential_predicates(xs))
2821     }
2822
2823     pub fn mk_predicates<I: InternAs<Predicate<'tcx>, &'tcx List<Predicate<'tcx>>>>(
2824         self,
2825         iter: I,
2826     ) -> I::Output {
2827         iter.intern_with(|xs| self.intern_predicates(xs))
2828     }
2829
2830     pub fn mk_type_list<I: InternAs<Ty<'tcx>, &'tcx List<Ty<'tcx>>>>(self, iter: I) -> I::Output {
2831         iter.intern_with(|xs| self.intern_type_list(xs))
2832     }
2833
2834     pub fn mk_substs<I: InternAs<GenericArg<'tcx>, &'tcx List<GenericArg<'tcx>>>>(
2835         self,
2836         iter: I,
2837     ) -> I::Output {
2838         iter.intern_with(|xs| self.intern_substs(xs))
2839     }
2840
2841     pub fn mk_place_elems<I: InternAs<PlaceElem<'tcx>, &'tcx List<PlaceElem<'tcx>>>>(
2842         self,
2843         iter: I,
2844     ) -> I::Output {
2845         iter.intern_with(|xs| self.intern_place_elems(xs))
2846     }
2847
2848     pub fn mk_substs_trait(
2849         self,
2850         self_ty: Ty<'tcx>,
2851         rest: impl IntoIterator<Item = GenericArg<'tcx>>,
2852     ) -> SubstsRef<'tcx> {
2853         self.mk_substs(iter::once(self_ty.into()).chain(rest))
2854     }
2855
2856     pub fn mk_trait_ref(
2857         self,
2858         trait_def_id: DefId,
2859         substs: impl IntoIterator<Item = impl Into<GenericArg<'tcx>>>,
2860     ) -> ty::TraitRef<'tcx> {
2861         let substs = substs.into_iter().map(Into::into);
2862         let n = self.generics_of(trait_def_id).count();
2863         debug_assert_eq!(
2864             (n, Some(n)),
2865             substs.size_hint(),
2866             "wrong number of generic parameters for {trait_def_id:?}: {:?} \nDid you accidentally include the self-type in the params list?",
2867             substs.collect::<Vec<_>>(),
2868         );
2869         let substs = self.mk_substs(substs);
2870         ty::TraitRef::new(trait_def_id, substs)
2871     }
2872
2873     pub fn mk_bound_variable_kinds<
2874         I: InternAs<ty::BoundVariableKind, &'tcx List<ty::BoundVariableKind>>,
2875     >(
2876         self,
2877         iter: I,
2878     ) -> I::Output {
2879         iter.intern_with(|xs| self.intern_bound_variable_kinds(xs))
2880     }
2881
2882     /// Emit a lint at `span` from a lint struct (some type that implements `DecorateLint`,
2883     /// typically generated by `#[derive(LintDiagnostic)]`).
2884     pub fn emit_spanned_lint(
2885         self,
2886         lint: &'static Lint,
2887         hir_id: HirId,
2888         span: impl Into<MultiSpan>,
2889         decorator: impl for<'a> DecorateLint<'a, ()>,
2890     ) {
2891         let msg = decorator.msg();
2892         let (level, src) = self.lint_level_at_node(lint, hir_id);
2893         struct_lint_level(self.sess, lint, level, src, Some(span.into()), msg, |diag| {
2894             decorator.decorate_lint(diag)
2895         })
2896     }
2897
2898     /// Emit a lint at the appropriate level for a hir node, with an associated span.
2899     ///
2900     /// Return value of the `decorate` closure is ignored, see [`struct_lint_level`] for a detailed explanation.
2901     ///
2902     /// [`struct_lint_level`]: rustc_middle::lint::struct_lint_level#decorate-signature
2903     #[rustc_lint_diagnostics]
2904     pub fn struct_span_lint_hir(
2905         self,
2906         lint: &'static Lint,
2907         hir_id: HirId,
2908         span: impl Into<MultiSpan>,
2909         msg: impl Into<DiagnosticMessage>,
2910         decorate: impl for<'a, 'b> FnOnce(
2911             &'b mut DiagnosticBuilder<'a, ()>,
2912         ) -> &'b mut DiagnosticBuilder<'a, ()>,
2913     ) {
2914         let (level, src) = self.lint_level_at_node(lint, hir_id);
2915         struct_lint_level(self.sess, lint, level, src, Some(span.into()), msg, decorate);
2916     }
2917
2918     /// Emit a lint from a lint struct (some type that implements `DecorateLint`, typically
2919     /// generated by `#[derive(LintDiagnostic)]`).
2920     pub fn emit_lint(
2921         self,
2922         lint: &'static Lint,
2923         id: HirId,
2924         decorator: impl for<'a> DecorateLint<'a, ()>,
2925     ) {
2926         self.struct_lint_node(lint, id, decorator.msg(), |diag| decorator.decorate_lint(diag))
2927     }
2928
2929     /// Emit a lint at the appropriate level for a hir node.
2930     ///
2931     /// Return value of the `decorate` closure is ignored, see [`struct_lint_level`] for a detailed explanation.
2932     ///
2933     /// [`struct_lint_level`]: rustc_middle::lint::struct_lint_level#decorate-signature
2934     #[rustc_lint_diagnostics]
2935     pub fn struct_lint_node(
2936         self,
2937         lint: &'static Lint,
2938         id: HirId,
2939         msg: impl Into<DiagnosticMessage>,
2940         decorate: impl for<'a, 'b> FnOnce(
2941             &'b mut DiagnosticBuilder<'a, ()>,
2942         ) -> &'b mut DiagnosticBuilder<'a, ()>,
2943     ) {
2944         let (level, src) = self.lint_level_at_node(lint, id);
2945         struct_lint_level(self.sess, lint, level, src, None, msg, decorate);
2946     }
2947
2948     pub fn in_scope_traits(self, id: HirId) -> Option<&'tcx [TraitCandidate]> {
2949         let map = self.in_scope_traits_map(id.owner)?;
2950         let candidates = map.get(&id.local_id)?;
2951         Some(&*candidates)
2952     }
2953
2954     pub fn named_region(self, id: HirId) -> Option<resolve_lifetime::Region> {
2955         debug!(?id, "named_region");
2956         self.named_region_map(id.owner).and_then(|map| map.get(&id.local_id).cloned())
2957     }
2958
2959     pub fn is_late_bound(self, id: HirId) -> bool {
2960         self.is_late_bound_map(id.owner.def_id).map_or(false, |set| {
2961             let def_id = self.hir().local_def_id(id);
2962             set.contains(&def_id)
2963         })
2964     }
2965
2966     pub fn late_bound_vars(self, id: HirId) -> &'tcx List<ty::BoundVariableKind> {
2967         self.mk_bound_variable_kinds(
2968             self.late_bound_vars_map(id.owner)
2969                 .and_then(|map| map.get(&id.local_id).cloned())
2970                 .unwrap_or_else(|| {
2971                     bug!("No bound vars found for {:?} ({:?})", self.hir().node_to_string(id), id)
2972                 })
2973                 .iter(),
2974         )
2975     }
2976
2977     /// Whether the `def_id` counts as const fn in the current crate, considering all active
2978     /// feature gates
2979     pub fn is_const_fn(self, def_id: DefId) -> bool {
2980         if self.is_const_fn_raw(def_id) {
2981             match self.lookup_const_stability(def_id) {
2982                 Some(stability) if stability.is_const_unstable() => {
2983                     // has a `rustc_const_unstable` attribute, check whether the user enabled the
2984                     // corresponding feature gate.
2985                     self.features()
2986                         .declared_lib_features
2987                         .iter()
2988                         .any(|&(sym, _)| sym == stability.feature)
2989                 }
2990                 // functions without const stability are either stable user written
2991                 // const fn or the user is using feature gates and we thus don't
2992                 // care what they do
2993                 _ => true,
2994             }
2995         } else {
2996             false
2997         }
2998     }
2999
3000     /// Whether the trait impl is marked const. This does not consider stability or feature gates.
3001     pub fn is_const_trait_impl_raw(self, def_id: DefId) -> bool {
3002         let Some(local_def_id) = def_id.as_local() else { return false };
3003         let hir_id = self.local_def_id_to_hir_id(local_def_id);
3004         let node = self.hir().get(hir_id);
3005
3006         matches!(
3007             node,
3008             hir::Node::Item(hir::Item {
3009                 kind: hir::ItemKind::Impl(hir::Impl { constness: hir::Constness::Const, .. }),
3010                 ..
3011             })
3012         )
3013     }
3014 }
3015
3016 impl<'tcx> TyCtxtAt<'tcx> {
3017     /// Constructs a `TyKind::Error` type and registers a `delay_span_bug` to ensure it gets used.
3018     #[track_caller]
3019     pub fn ty_error(self) -> Ty<'tcx> {
3020         self.tcx.ty_error_with_message(self.span, "TyKind::Error constructed but no error reported")
3021     }
3022
3023     /// Constructs a `TyKind::Error` type and registers a `delay_span_bug` with the given `msg to
3024     /// ensure it gets used.
3025     #[track_caller]
3026     pub fn ty_error_with_message(self, msg: &str) -> Ty<'tcx> {
3027         self.tcx.ty_error_with_message(self.span, msg)
3028     }
3029
3030     pub fn mk_trait_ref(
3031         self,
3032         trait_lang_item: LangItem,
3033         substs: impl IntoIterator<Item = impl Into<ty::GenericArg<'tcx>>>,
3034     ) -> ty::TraitRef<'tcx> {
3035         let trait_def_id = self.require_lang_item(trait_lang_item, Some(self.span));
3036         self.tcx.mk_trait_ref(trait_def_id, substs)
3037     }
3038 }
3039
3040 /// Parameter attributes that can only be determined by examining the body of a function instead
3041 /// of just its signature.
3042 ///
3043 /// These can be useful for optimization purposes when a function is directly called. We compute
3044 /// them and store them into the crate metadata so that downstream crates can make use of them.
3045 ///
3046 /// Right now, we only have `read_only`, but `no_capture` and `no_alias` might be useful in the
3047 /// future.
3048 #[derive(Clone, Copy, PartialEq, Debug, Default, TyDecodable, TyEncodable, HashStable)]
3049 pub struct DeducedParamAttrs {
3050     /// The parameter is marked immutable in the function and contains no `UnsafeCell` (i.e. its
3051     /// type is freeze).
3052     pub read_only: bool,
3053 }
3054
3055 // We are comparing types with different invariant lifetimes, so `ptr::eq`
3056 // won't work for us.
3057 fn ptr_eq<T, U>(t: *const T, u: *const U) -> bool {
3058     t as *const () == u as *const ()
3059 }
3060
3061 pub fn provide(providers: &mut ty::query::Providers) {
3062     providers.resolutions = |tcx, ()| &tcx.untracked_resolutions;
3063     providers.module_reexports =
3064         |tcx, id| tcx.resolutions(()).reexport_map.get(&id).map(|v| &v[..]);
3065     providers.crate_name = |tcx, id| {
3066         assert_eq!(id, LOCAL_CRATE);
3067         tcx.crate_name
3068     };
3069     providers.maybe_unused_trait_imports =
3070         |tcx, ()| &tcx.resolutions(()).maybe_unused_trait_imports;
3071     providers.maybe_unused_extern_crates =
3072         |tcx, ()| &tcx.resolutions(()).maybe_unused_extern_crates[..];
3073     providers.names_imported_by_glob_use = |tcx, id| {
3074         tcx.arena.alloc(tcx.resolutions(()).glob_map.get(&id).cloned().unwrap_or_default())
3075     };
3076
3077     providers.extern_mod_stmt_cnum =
3078         |tcx, id| tcx.resolutions(()).extern_crate_map.get(&id).cloned();
3079     providers.output_filenames = |tcx, ()| &tcx.output_filenames;
3080     providers.features_query = |tcx, ()| tcx.sess.features_untracked();
3081     providers.is_panic_runtime = |tcx, cnum| {
3082         assert_eq!(cnum, LOCAL_CRATE);
3083         tcx.sess.contains_name(tcx.hir().krate_attrs(), sym::panic_runtime)
3084     };
3085     providers.is_compiler_builtins = |tcx, cnum| {
3086         assert_eq!(cnum, LOCAL_CRATE);
3087         tcx.sess.contains_name(tcx.hir().krate_attrs(), sym::compiler_builtins)
3088     };
3089     providers.has_panic_handler = |tcx, cnum| {
3090         assert_eq!(cnum, LOCAL_CRATE);
3091         // We want to check if the panic handler was defined in this crate
3092         tcx.lang_items().panic_impl().map_or(false, |did| did.is_local())
3093     };
3094     providers.source_span =
3095         |tcx, def_id| tcx.untracked.source_span.get(def_id).copied().unwrap_or(DUMMY_SP);
3096 }