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