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