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