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