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