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