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