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