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