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