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