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