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