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