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