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