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