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