]> git.lizzy.rs Git - rust.git/blob - src/librustc/ty/context.rs
rustc: Make `CrateStore` private to `TyCtxt`
[rust.git] / src / librustc / ty / context.rs
1 // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! type context book-keeping
12
13 use dep_graph::DepGraph;
14 use errors::DiagnosticBuilder;
15 use session::Session;
16 use middle;
17 use hir::{TraitCandidate, HirId, ItemLocalId};
18 use hir::def::{Def, Export};
19 use hir::def_id::{CrateNum, DefId, DefIndex, LOCAL_CRATE};
20 use hir::map as hir_map;
21 use hir::map::DefPathHash;
22 use lint::{self, Lint};
23 use ich::{self, StableHashingContext, NodeIdHashingMode};
24 use middle::const_val::ConstVal;
25 use middle::cstore::{CrateStore, LinkMeta, EncodedMetadataHashes};
26 use middle::cstore::EncodedMetadata;
27 use middle::free_region::FreeRegionMap;
28 use middle::lang_items;
29 use middle::resolve_lifetime::{self, ObjectLifetimeDefault};
30 use middle::stability;
31 use mir::Mir;
32 use mir::transform::Passes;
33 use ty::subst::{Kind, Substs};
34 use ty::ReprOptions;
35 use traits;
36 use ty::{self, Ty, TypeAndMut};
37 use ty::{TyS, TypeVariants, Slice};
38 use ty::{AdtKind, AdtDef, ClosureSubsts, GeneratorInterior, Region, Const};
39 use ty::{PolyFnSig, InferTy, ParamTy, ProjectionTy, ExistentialPredicate, Predicate};
40 use ty::RegionKind;
41 use ty::{TyVar, TyVid, IntVar, IntVid, FloatVar, FloatVid};
42 use ty::TypeVariants::*;
43 use ty::layout::{Layout, TargetDataLayout};
44 use ty::inhabitedness::DefIdForest;
45 use ty::maps;
46 use ty::steal::Steal;
47 use ty::BindingMode;
48 use util::nodemap::{NodeMap, NodeSet, DefIdSet, ItemLocalMap};
49 use util::nodemap::{FxHashMap, FxHashSet};
50 use rustc_data_structures::accumulate_vec::AccumulateVec;
51 use rustc_data_structures::stable_hasher::{HashStable, StableHasher,
52                                            StableHasherResult};
53
54 use arena::{TypedArena, DroplessArena};
55 use rustc_const_math::{ConstInt, ConstUsize};
56 use rustc_data_structures::indexed_vec::IndexVec;
57 use std::any::Any;
58 use std::borrow::Borrow;
59 use std::cell::{Cell, RefCell};
60 use std::cmp::Ordering;
61 use std::collections::hash_map::{self, Entry};
62 use std::hash::{Hash, Hasher};
63 use std::mem;
64 use std::ops::Deref;
65 use std::iter;
66 use std::rc::Rc;
67 use syntax::abi;
68 use syntax::ast::{self, Name, NodeId};
69 use syntax::attr;
70 use syntax::codemap::MultiSpan;
71 use syntax::symbol::{Symbol, keywords};
72 use syntax_pos::Span;
73
74 use hir;
75
76 /// Internal storage
77 pub struct GlobalArenas<'tcx> {
78     // internings
79     layout: TypedArena<Layout>,
80
81     // references
82     generics: TypedArena<ty::Generics>,
83     trait_def: TypedArena<ty::TraitDef>,
84     adt_def: TypedArena<ty::AdtDef>,
85     steal_mir: TypedArena<Steal<Mir<'tcx>>>,
86     mir: TypedArena<Mir<'tcx>>,
87     tables: TypedArena<ty::TypeckTables<'tcx>>,
88 }
89
90 impl<'tcx> GlobalArenas<'tcx> {
91     pub fn new() -> GlobalArenas<'tcx> {
92         GlobalArenas {
93             layout: TypedArena::new(),
94             generics: TypedArena::new(),
95             trait_def: TypedArena::new(),
96             adt_def: TypedArena::new(),
97             steal_mir: TypedArena::new(),
98             mir: TypedArena::new(),
99             tables: TypedArena::new(),
100         }
101     }
102 }
103
104 pub struct CtxtInterners<'tcx> {
105     /// The arena that types, regions, etc are allocated from
106     arena: &'tcx DroplessArena,
107
108     /// Specifically use a speedy hash algorithm for these hash sets,
109     /// they're accessed quite often.
110     type_: RefCell<FxHashSet<Interned<'tcx, TyS<'tcx>>>>,
111     type_list: RefCell<FxHashSet<Interned<'tcx, Slice<Ty<'tcx>>>>>,
112     substs: RefCell<FxHashSet<Interned<'tcx, Substs<'tcx>>>>,
113     region: RefCell<FxHashSet<Interned<'tcx, RegionKind>>>,
114     existential_predicates: RefCell<FxHashSet<Interned<'tcx, Slice<ExistentialPredicate<'tcx>>>>>,
115     predicates: RefCell<FxHashSet<Interned<'tcx, Slice<Predicate<'tcx>>>>>,
116     const_: RefCell<FxHashSet<Interned<'tcx, Const<'tcx>>>>,
117 }
118
119 impl<'gcx: 'tcx, 'tcx> CtxtInterners<'tcx> {
120     fn new(arena: &'tcx DroplessArena) -> CtxtInterners<'tcx> {
121         CtxtInterners {
122             arena,
123             type_: RefCell::new(FxHashSet()),
124             type_list: RefCell::new(FxHashSet()),
125             substs: RefCell::new(FxHashSet()),
126             region: RefCell::new(FxHashSet()),
127             existential_predicates: RefCell::new(FxHashSet()),
128             predicates: RefCell::new(FxHashSet()),
129             const_: RefCell::new(FxHashSet()),
130         }
131     }
132
133     /// Intern a type. global_interners is Some only if this is
134     /// a local interner and global_interners is its counterpart.
135     fn intern_ty(&self, st: TypeVariants<'tcx>,
136                  global_interners: Option<&CtxtInterners<'gcx>>)
137                  -> Ty<'tcx> {
138         let ty = {
139             let mut interner = self.type_.borrow_mut();
140             let global_interner = global_interners.map(|interners| {
141                 interners.type_.borrow_mut()
142             });
143             if let Some(&Interned(ty)) = interner.get(&st) {
144                 return ty;
145             }
146             if let Some(ref interner) = global_interner {
147                 if let Some(&Interned(ty)) = interner.get(&st) {
148                     return ty;
149                 }
150             }
151
152             let flags = super::flags::FlagComputation::for_sty(&st);
153             let ty_struct = TyS {
154                 sty: st,
155                 flags: flags.flags,
156                 region_depth: flags.depth,
157             };
158
159             // HACK(eddyb) Depend on flags being accurate to
160             // determine that all contents are in the global tcx.
161             // See comments on Lift for why we can't use that.
162             if !flags.flags.intersects(ty::TypeFlags::KEEP_IN_LOCAL_TCX) {
163                 if let Some(interner) = global_interners {
164                     let ty_struct: TyS<'gcx> = unsafe {
165                         mem::transmute(ty_struct)
166                     };
167                     let ty: Ty<'gcx> = interner.arena.alloc(ty_struct);
168                     global_interner.unwrap().insert(Interned(ty));
169                     return ty;
170                 }
171             } else {
172                 // Make sure we don't end up with inference
173                 // types/regions in the global tcx.
174                 if global_interners.is_none() {
175                     drop(interner);
176                     bug!("Attempted to intern `{:?}` which contains \
177                           inference types/regions in the global type context",
178                          &ty_struct);
179                 }
180             }
181
182             // Don't be &mut TyS.
183             let ty: Ty<'tcx> = self.arena.alloc(ty_struct);
184             interner.insert(Interned(ty));
185             ty
186         };
187
188         debug!("Interned type: {:?} Pointer: {:?}",
189             ty, ty as *const TyS);
190         ty
191     }
192
193 }
194
195 pub struct CommonTypes<'tcx> {
196     pub bool: Ty<'tcx>,
197     pub char: Ty<'tcx>,
198     pub isize: Ty<'tcx>,
199     pub i8: Ty<'tcx>,
200     pub i16: Ty<'tcx>,
201     pub i32: Ty<'tcx>,
202     pub i64: Ty<'tcx>,
203     pub i128: Ty<'tcx>,
204     pub usize: Ty<'tcx>,
205     pub u8: Ty<'tcx>,
206     pub u16: Ty<'tcx>,
207     pub u32: Ty<'tcx>,
208     pub u64: Ty<'tcx>,
209     pub u128: Ty<'tcx>,
210     pub f32: Ty<'tcx>,
211     pub f64: Ty<'tcx>,
212     pub never: Ty<'tcx>,
213     pub err: Ty<'tcx>,
214
215     pub re_empty: Region<'tcx>,
216     pub re_static: Region<'tcx>,
217     pub re_erased: Region<'tcx>,
218 }
219
220 pub struct LocalTableInContext<'a, V: 'a> {
221     local_id_root: Option<DefId>,
222     data: &'a ItemLocalMap<V>
223 }
224
225 /// Validate that the given HirId (respectively its `local_id` part) can be
226 /// safely used as a key in the tables of a TypeckTable. For that to be
227 /// the case, the HirId must have the same `owner` as all the other IDs in
228 /// this table (signified by `local_id_root`). Otherwise the HirId
229 /// would be in a different frame of reference and using its `local_id`
230 /// would result in lookup errors, or worse, in silently wrong data being
231 /// stored/returned.
232 fn validate_hir_id_for_typeck_tables(local_id_root: Option<DefId>,
233                                      hir_id: hir::HirId,
234                                      mut_access: bool) {
235     if cfg!(debug_assertions) {
236         if let Some(local_id_root) = local_id_root {
237             if hir_id.owner != local_id_root.index {
238                 ty::tls::with(|tcx| {
239                     let node_id = tcx.hir
240                                      .definitions()
241                                      .find_node_for_hir_id(hir_id);
242
243                     bug!("node {} with HirId::owner {:?} cannot be placed in \
244                           TypeckTables with local_id_root {:?}",
245                           tcx.hir.node_to_string(node_id),
246                           DefId::local(hir_id.owner),
247                           local_id_root)
248                 });
249             }
250         } else {
251             // We use "Null Object" TypeckTables in some of the analysis passes.
252             // These are just expected to be empty and their `local_id_root` is
253             // `None`. Therefore we cannot verify whether a given `HirId` would
254             // be a valid key for the given table. Instead we make sure that
255             // nobody tries to write to such a Null Object table.
256             if mut_access {
257                 bug!("access to invalid TypeckTables")
258             }
259         }
260     }
261 }
262
263 impl<'a, V> LocalTableInContext<'a, V> {
264     pub fn contains_key(&self, id: hir::HirId) -> bool {
265         validate_hir_id_for_typeck_tables(self.local_id_root, id, false);
266         self.data.contains_key(&id.local_id)
267     }
268
269     pub fn get(&self, id: hir::HirId) -> Option<&V> {
270         validate_hir_id_for_typeck_tables(self.local_id_root, id, false);
271         self.data.get(&id.local_id)
272     }
273
274     pub fn iter(&self) -> hash_map::Iter<hir::ItemLocalId, V> {
275         self.data.iter()
276     }
277 }
278
279 impl<'a, V> ::std::ops::Index<hir::HirId> for LocalTableInContext<'a, V> {
280     type Output = V;
281
282     fn index(&self, key: hir::HirId) -> &V {
283         self.get(key).expect("LocalTableInContext: key not found")
284     }
285 }
286
287 pub struct LocalTableInContextMut<'a, V: 'a> {
288     local_id_root: Option<DefId>,
289     data: &'a mut ItemLocalMap<V>
290 }
291
292 impl<'a, V> LocalTableInContextMut<'a, V> {
293     pub fn get_mut(&mut self, id: hir::HirId) -> Option<&mut V> {
294         validate_hir_id_for_typeck_tables(self.local_id_root, id, true);
295         self.data.get_mut(&id.local_id)
296     }
297
298     pub fn entry(&mut self, id: hir::HirId) -> Entry<hir::ItemLocalId, V> {
299         validate_hir_id_for_typeck_tables(self.local_id_root, id, true);
300         self.data.entry(id.local_id)
301     }
302
303     pub fn insert(&mut self, id: hir::HirId, val: V) -> Option<V> {
304         validate_hir_id_for_typeck_tables(self.local_id_root, id, true);
305         self.data.insert(id.local_id, val)
306     }
307
308     pub fn remove(&mut self, id: hir::HirId) -> Option<V> {
309         validate_hir_id_for_typeck_tables(self.local_id_root, id, true);
310         self.data.remove(&id.local_id)
311     }
312 }
313
314 #[derive(RustcEncodable, RustcDecodable)]
315 pub struct TypeckTables<'tcx> {
316     /// The HirId::owner all ItemLocalIds in this table are relative to.
317     pub local_id_root: Option<DefId>,
318
319     /// Resolved definitions for `<T>::X` associated paths and
320     /// method calls, including those of overloaded operators.
321     type_dependent_defs: ItemLocalMap<Def>,
322
323     /// Stores the types for various nodes in the AST.  Note that this table
324     /// is not guaranteed to be populated until after typeck.  See
325     /// typeck::check::fn_ctxt for details.
326     node_types: ItemLocalMap<Ty<'tcx>>,
327
328     /// Stores the type parameters which were substituted to obtain the type
329     /// of this node.  This only applies to nodes that refer to entities
330     /// parameterized by type parameters, such as generic fns, types, or
331     /// other items.
332     node_substs: ItemLocalMap<&'tcx Substs<'tcx>>,
333
334     adjustments: ItemLocalMap<Vec<ty::adjustment::Adjustment<'tcx>>>,
335
336     // Stores the actual binding mode for all instances of hir::BindingAnnotation.
337     pat_binding_modes: ItemLocalMap<BindingMode>,
338
339     /// Borrows
340     pub upvar_capture_map: ty::UpvarCaptureMap<'tcx>,
341
342     /// Records the type of each closure.
343     closure_tys: ItemLocalMap<ty::PolyFnSig<'tcx>>,
344
345     /// Records the kind of each closure and the span and name of the variable
346     /// that caused the closure to be this kind.
347     closure_kinds: ItemLocalMap<(ty::ClosureKind, Option<(Span, ast::Name)>)>,
348
349     generator_sigs: ItemLocalMap<Option<ty::GenSig<'tcx>>>,
350
351     generator_interiors: ItemLocalMap<ty::GeneratorInterior<'tcx>>,
352
353     /// For each fn, records the "liberated" types of its arguments
354     /// and return type. Liberated means that all bound regions
355     /// (including late-bound regions) are replaced with free
356     /// equivalents. This table is not used in trans (since regions
357     /// are erased there) and hence is not serialized to metadata.
358     liberated_fn_sigs: ItemLocalMap<ty::FnSig<'tcx>>,
359
360     /// For each FRU expression, record the normalized types of the fields
361     /// of the struct - this is needed because it is non-trivial to
362     /// normalize while preserving regions. This table is used only in
363     /// MIR construction and hence is not serialized to metadata.
364     fru_field_types: ItemLocalMap<Vec<Ty<'tcx>>>,
365
366     /// Maps a cast expression to its kind. This is keyed on the
367     /// *from* expression of the cast, not the cast itself.
368     cast_kinds: ItemLocalMap<ty::cast::CastKind>,
369
370     /// Set of trait imports actually used in the method resolution.
371     /// This is used for warning unused imports.
372     pub used_trait_imports: DefIdSet,
373
374     /// If any errors occurred while type-checking this body,
375     /// this field will be set to `true`.
376     pub tainted_by_errors: bool,
377
378     /// Stores the free-region relationships that were deduced from
379     /// its where clauses and parameter types. These are then
380     /// read-again by borrowck.
381     pub free_region_map: FreeRegionMap<'tcx>,
382 }
383
384 impl<'tcx> TypeckTables<'tcx> {
385     pub fn empty(local_id_root: Option<DefId>) -> TypeckTables<'tcx> {
386         TypeckTables {
387             local_id_root,
388             type_dependent_defs: ItemLocalMap(),
389             node_types: ItemLocalMap(),
390             node_substs: ItemLocalMap(),
391             adjustments: ItemLocalMap(),
392             pat_binding_modes: ItemLocalMap(),
393             upvar_capture_map: FxHashMap(),
394             generator_sigs: ItemLocalMap(),
395             generator_interiors: ItemLocalMap(),
396             closure_tys: ItemLocalMap(),
397             closure_kinds: ItemLocalMap(),
398             liberated_fn_sigs: ItemLocalMap(),
399             fru_field_types: ItemLocalMap(),
400             cast_kinds: ItemLocalMap(),
401             used_trait_imports: DefIdSet(),
402             tainted_by_errors: false,
403             free_region_map: FreeRegionMap::new(),
404         }
405     }
406
407     /// Returns the final resolution of a `QPath` in an `Expr` or `Pat` node.
408     pub fn qpath_def(&self, qpath: &hir::QPath, id: hir::HirId) -> Def {
409         match *qpath {
410             hir::QPath::Resolved(_, ref path) => path.def,
411             hir::QPath::TypeRelative(..) => {
412                 validate_hir_id_for_typeck_tables(self.local_id_root, id, false);
413                 self.type_dependent_defs.get(&id.local_id).cloned().unwrap_or(Def::Err)
414             }
415         }
416     }
417
418     pub fn type_dependent_defs(&self) -> LocalTableInContext<Def> {
419         LocalTableInContext {
420             local_id_root: self.local_id_root,
421             data: &self.type_dependent_defs
422         }
423     }
424
425     pub fn type_dependent_defs_mut(&mut self) -> LocalTableInContextMut<Def> {
426         LocalTableInContextMut {
427             local_id_root: self.local_id_root,
428             data: &mut self.type_dependent_defs
429         }
430     }
431
432     pub fn node_types(&self) -> LocalTableInContext<Ty<'tcx>> {
433         LocalTableInContext {
434             local_id_root: self.local_id_root,
435             data: &self.node_types
436         }
437     }
438
439     pub fn node_types_mut(&mut self) -> LocalTableInContextMut<Ty<'tcx>> {
440         LocalTableInContextMut {
441             local_id_root: self.local_id_root,
442             data: &mut self.node_types
443         }
444     }
445
446     pub fn node_id_to_type(&self, id: hir::HirId) -> Ty<'tcx> {
447         match self.node_id_to_type_opt(id) {
448             Some(ty) => ty,
449             None => {
450                 bug!("node_id_to_type: no type for node `{}`",
451                     tls::with(|tcx| {
452                         let id = tcx.hir.definitions().find_node_for_hir_id(id);
453                         tcx.hir.node_to_string(id)
454                     }))
455             }
456         }
457     }
458
459     pub fn node_id_to_type_opt(&self, id: hir::HirId) -> Option<Ty<'tcx>> {
460         validate_hir_id_for_typeck_tables(self.local_id_root, id, false);
461         self.node_types.get(&id.local_id).cloned()
462     }
463
464     pub fn node_substs_mut(&mut self) -> LocalTableInContextMut<&'tcx Substs<'tcx>> {
465         LocalTableInContextMut {
466             local_id_root: self.local_id_root,
467             data: &mut self.node_substs
468         }
469     }
470
471     pub fn node_substs(&self, id: hir::HirId) -> &'tcx Substs<'tcx> {
472         validate_hir_id_for_typeck_tables(self.local_id_root, id, false);
473         self.node_substs.get(&id.local_id).cloned().unwrap_or(Substs::empty())
474     }
475
476     pub fn node_substs_opt(&self, id: hir::HirId) -> Option<&'tcx Substs<'tcx>> {
477         validate_hir_id_for_typeck_tables(self.local_id_root, id, false);
478         self.node_substs.get(&id.local_id).cloned()
479     }
480
481     // Returns the type of a pattern as a monotype. Like @expr_ty, this function
482     // doesn't provide type parameter substitutions.
483     pub fn pat_ty(&self, pat: &hir::Pat) -> Ty<'tcx> {
484         self.node_id_to_type(pat.hir_id)
485     }
486
487     pub fn pat_ty_opt(&self, pat: &hir::Pat) -> Option<Ty<'tcx>> {
488         self.node_id_to_type_opt(pat.hir_id)
489     }
490
491     // Returns the type of an expression as a monotype.
492     //
493     // NB (1): This is the PRE-ADJUSTMENT TYPE for the expression.  That is, in
494     // some cases, we insert `Adjustment` annotations such as auto-deref or
495     // auto-ref.  The type returned by this function does not consider such
496     // adjustments.  See `expr_ty_adjusted()` instead.
497     //
498     // NB (2): This type doesn't provide type parameter substitutions; e.g. if you
499     // ask for the type of "id" in "id(3)", it will return "fn(&isize) -> isize"
500     // instead of "fn(ty) -> T with T = isize".
501     pub fn expr_ty(&self, expr: &hir::Expr) -> Ty<'tcx> {
502         self.node_id_to_type(expr.hir_id)
503     }
504
505     pub fn expr_ty_opt(&self, expr: &hir::Expr) -> Option<Ty<'tcx>> {
506         self.node_id_to_type_opt(expr.hir_id)
507     }
508
509     pub fn adjustments(&self) -> LocalTableInContext<Vec<ty::adjustment::Adjustment<'tcx>>> {
510         LocalTableInContext {
511             local_id_root: self.local_id_root,
512             data: &self.adjustments
513         }
514     }
515
516     pub fn adjustments_mut(&mut self)
517                            -> LocalTableInContextMut<Vec<ty::adjustment::Adjustment<'tcx>>> {
518         LocalTableInContextMut {
519             local_id_root: self.local_id_root,
520             data: &mut self.adjustments
521         }
522     }
523
524     pub fn expr_adjustments(&self, expr: &hir::Expr)
525                             -> &[ty::adjustment::Adjustment<'tcx>] {
526         validate_hir_id_for_typeck_tables(self.local_id_root, expr.hir_id, false);
527         self.adjustments.get(&expr.hir_id.local_id).map_or(&[], |a| &a[..])
528     }
529
530     /// Returns the type of `expr`, considering any `Adjustment`
531     /// entry recorded for that expression.
532     pub fn expr_ty_adjusted(&self, expr: &hir::Expr) -> Ty<'tcx> {
533         self.expr_adjustments(expr)
534             .last()
535             .map_or_else(|| self.expr_ty(expr), |adj| adj.target)
536     }
537
538     pub fn expr_ty_adjusted_opt(&self, expr: &hir::Expr) -> Option<Ty<'tcx>> {
539         self.expr_adjustments(expr)
540             .last()
541             .map(|adj| adj.target)
542             .or_else(|| self.expr_ty_opt(expr))
543     }
544
545     pub fn is_method_call(&self, expr: &hir::Expr) -> bool {
546         // Only paths and method calls/overloaded operators have
547         // entries in type_dependent_defs, ignore the former here.
548         if let hir::ExprPath(_) = expr.node {
549             return false;
550         }
551
552         match self.type_dependent_defs().get(expr.hir_id) {
553             Some(&Def::Method(_)) => true,
554             _ => false
555         }
556     }
557
558     pub fn pat_binding_modes(&self) -> LocalTableInContext<BindingMode> {
559         LocalTableInContext {
560             local_id_root: self.local_id_root,
561             data: &self.pat_binding_modes
562         }
563     }
564
565     pub fn pat_binding_modes_mut(&mut self)
566                            -> LocalTableInContextMut<BindingMode> {
567         LocalTableInContextMut {
568             local_id_root: self.local_id_root,
569             data: &mut self.pat_binding_modes
570         }
571     }
572
573     pub fn upvar_capture(&self, upvar_id: ty::UpvarId) -> ty::UpvarCapture<'tcx> {
574         self.upvar_capture_map[&upvar_id]
575     }
576
577     pub fn closure_tys(&self) -> LocalTableInContext<ty::PolyFnSig<'tcx>> {
578         LocalTableInContext {
579             local_id_root: self.local_id_root,
580             data: &self.closure_tys
581         }
582     }
583
584     pub fn closure_tys_mut(&mut self)
585                            -> LocalTableInContextMut<ty::PolyFnSig<'tcx>> {
586         LocalTableInContextMut {
587             local_id_root: self.local_id_root,
588             data: &mut self.closure_tys
589         }
590     }
591
592     pub fn closure_kinds(&self) -> LocalTableInContext<(ty::ClosureKind,
593                                                         Option<(Span, ast::Name)>)> {
594         LocalTableInContext {
595             local_id_root: self.local_id_root,
596             data: &self.closure_kinds
597         }
598     }
599
600     pub fn closure_kinds_mut(&mut self)
601             -> LocalTableInContextMut<(ty::ClosureKind, Option<(Span, ast::Name)>)> {
602         LocalTableInContextMut {
603             local_id_root: self.local_id_root,
604             data: &mut self.closure_kinds
605         }
606     }
607
608     pub fn liberated_fn_sigs(&self) -> LocalTableInContext<ty::FnSig<'tcx>> {
609         LocalTableInContext {
610             local_id_root: self.local_id_root,
611             data: &self.liberated_fn_sigs
612         }
613     }
614
615     pub fn liberated_fn_sigs_mut(&mut self) -> LocalTableInContextMut<ty::FnSig<'tcx>> {
616         LocalTableInContextMut {
617             local_id_root: self.local_id_root,
618             data: &mut self.liberated_fn_sigs
619         }
620     }
621
622     pub fn fru_field_types(&self) -> LocalTableInContext<Vec<Ty<'tcx>>> {
623         LocalTableInContext {
624             local_id_root: self.local_id_root,
625             data: &self.fru_field_types
626         }
627     }
628
629     pub fn fru_field_types_mut(&mut self) -> LocalTableInContextMut<Vec<Ty<'tcx>>> {
630         LocalTableInContextMut {
631             local_id_root: self.local_id_root,
632             data: &mut self.fru_field_types
633         }
634     }
635
636     pub fn cast_kinds(&self) -> LocalTableInContext<ty::cast::CastKind> {
637         LocalTableInContext {
638             local_id_root: self.local_id_root,
639             data: &self.cast_kinds
640         }
641     }
642
643     pub fn cast_kinds_mut(&mut self) -> LocalTableInContextMut<ty::cast::CastKind> {
644         LocalTableInContextMut {
645             local_id_root: self.local_id_root,
646             data: &mut self.cast_kinds
647         }
648     }
649
650     pub fn generator_sigs(&self)
651         -> LocalTableInContext<Option<ty::GenSig<'tcx>>>
652     {
653         LocalTableInContext {
654             local_id_root: self.local_id_root,
655             data: &self.generator_sigs,
656         }
657     }
658
659     pub fn generator_sigs_mut(&mut self)
660         -> LocalTableInContextMut<Option<ty::GenSig<'tcx>>>
661     {
662         LocalTableInContextMut {
663             local_id_root: self.local_id_root,
664             data: &mut self.generator_sigs,
665         }
666     }
667
668     pub fn generator_interiors(&self)
669         -> LocalTableInContext<ty::GeneratorInterior<'tcx>>
670     {
671         LocalTableInContext {
672             local_id_root: self.local_id_root,
673             data: &self.generator_interiors,
674         }
675     }
676
677     pub fn generator_interiors_mut(&mut self)
678         -> LocalTableInContextMut<ty::GeneratorInterior<'tcx>>
679     {
680         LocalTableInContextMut {
681             local_id_root: self.local_id_root,
682             data: &mut self.generator_interiors,
683         }
684     }
685 }
686
687 impl<'a, 'gcx, 'tcx> HashStable<StableHashingContext<'a, 'gcx, 'tcx>> for TypeckTables<'gcx> {
688     fn hash_stable<W: StableHasherResult>(&self,
689                                           hcx: &mut StableHashingContext<'a, 'gcx, 'tcx>,
690                                           hasher: &mut StableHasher<W>) {
691         let ty::TypeckTables {
692             local_id_root,
693             ref type_dependent_defs,
694             ref node_types,
695             ref node_substs,
696             ref adjustments,
697             ref pat_binding_modes,
698             ref upvar_capture_map,
699             ref closure_tys,
700             ref closure_kinds,
701             ref liberated_fn_sigs,
702             ref fru_field_types,
703
704             ref cast_kinds,
705
706             ref used_trait_imports,
707             tainted_by_errors,
708             ref free_region_map,
709             ref generator_sigs,
710             ref generator_interiors,
711         } = *self;
712
713         hcx.with_node_id_hashing_mode(NodeIdHashingMode::HashDefPath, |hcx| {
714             ich::hash_stable_itemlocalmap(hcx, hasher, type_dependent_defs);
715             ich::hash_stable_itemlocalmap(hcx, hasher, node_types);
716             ich::hash_stable_itemlocalmap(hcx, hasher, node_substs);
717             ich::hash_stable_itemlocalmap(hcx, hasher, adjustments);
718             ich::hash_stable_itemlocalmap(hcx, hasher, pat_binding_modes);
719             ich::hash_stable_hashmap(hcx, hasher, upvar_capture_map, |hcx, up_var_id| {
720                 let ty::UpvarId {
721                     var_id,
722                     closure_expr_id
723                 } = *up_var_id;
724
725                 let local_id_root =
726                     local_id_root.expect("trying to hash invalid TypeckTables");
727
728                 let var_owner_def_id = DefId {
729                     krate: local_id_root.krate,
730                     index: var_id.owner,
731                 };
732                 let closure_def_id = DefId {
733                     krate: local_id_root.krate,
734                     index: closure_expr_id,
735                 };
736                 ((hcx.def_path_hash(var_owner_def_id), var_id.local_id),
737                  hcx.def_path_hash(closure_def_id))
738             });
739
740             ich::hash_stable_itemlocalmap(hcx, hasher, closure_tys);
741             ich::hash_stable_itemlocalmap(hcx, hasher, closure_kinds);
742             ich::hash_stable_itemlocalmap(hcx, hasher, liberated_fn_sigs);
743             ich::hash_stable_itemlocalmap(hcx, hasher, fru_field_types);
744             ich::hash_stable_itemlocalmap(hcx, hasher, cast_kinds);
745             ich::hash_stable_itemlocalmap(hcx, hasher, generator_sigs);
746             ich::hash_stable_itemlocalmap(hcx, hasher, generator_interiors);
747
748             ich::hash_stable_hashset(hcx, hasher, used_trait_imports, |hcx, def_id| {
749                 hcx.def_path_hash(*def_id)
750             });
751
752             tainted_by_errors.hash_stable(hcx, hasher);
753             free_region_map.hash_stable(hcx, hasher);
754         })
755     }
756 }
757
758 impl<'tcx> CommonTypes<'tcx> {
759     fn new(interners: &CtxtInterners<'tcx>) -> CommonTypes<'tcx> {
760         let mk = |sty| interners.intern_ty(sty, None);
761         let mk_region = |r| {
762             if let Some(r) = interners.region.borrow().get(&r) {
763                 return r.0;
764             }
765             let r = interners.arena.alloc(r);
766             interners.region.borrow_mut().insert(Interned(r));
767             &*r
768         };
769         CommonTypes {
770             bool: mk(TyBool),
771             char: mk(TyChar),
772             never: mk(TyNever),
773             err: mk(TyError),
774             isize: mk(TyInt(ast::IntTy::Is)),
775             i8: mk(TyInt(ast::IntTy::I8)),
776             i16: mk(TyInt(ast::IntTy::I16)),
777             i32: mk(TyInt(ast::IntTy::I32)),
778             i64: mk(TyInt(ast::IntTy::I64)),
779             i128: mk(TyInt(ast::IntTy::I128)),
780             usize: mk(TyUint(ast::UintTy::Us)),
781             u8: mk(TyUint(ast::UintTy::U8)),
782             u16: mk(TyUint(ast::UintTy::U16)),
783             u32: mk(TyUint(ast::UintTy::U32)),
784             u64: mk(TyUint(ast::UintTy::U64)),
785             u128: mk(TyUint(ast::UintTy::U128)),
786             f32: mk(TyFloat(ast::FloatTy::F32)),
787             f64: mk(TyFloat(ast::FloatTy::F64)),
788
789             re_empty: mk_region(RegionKind::ReEmpty),
790             re_static: mk_region(RegionKind::ReStatic),
791             re_erased: mk_region(RegionKind::ReErased),
792         }
793     }
794 }
795
796 /// The data structure to keep track of all the information that typechecker
797 /// generates so that so that it can be reused and doesn't have to be redone
798 /// later on.
799 #[derive(Copy, Clone)]
800 pub struct TyCtxt<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
801     gcx: &'a GlobalCtxt<'gcx>,
802     interners: &'a CtxtInterners<'tcx>
803 }
804
805 impl<'a, 'gcx, 'tcx> Deref for TyCtxt<'a, 'gcx, 'tcx> {
806     type Target = &'a GlobalCtxt<'gcx>;
807     fn deref(&self) -> &Self::Target {
808         &self.gcx
809     }
810 }
811
812 pub struct GlobalCtxt<'tcx> {
813     global_arenas: &'tcx GlobalArenas<'tcx>,
814     global_interners: CtxtInterners<'tcx>,
815
816     cstore: &'tcx CrateStore,
817
818     pub sess: &'tcx Session,
819
820
821     pub trans_trait_caches: traits::trans::TransTraitCaches<'tcx>,
822
823     pub dep_graph: DepGraph,
824
825     /// Common types, pre-interned for your convenience.
826     pub types: CommonTypes<'tcx>,
827
828     /// Map indicating what traits are in scope for places where this
829     /// is relevant; generated by resolve.
830     trait_map: FxHashMap<DefIndex, Rc<FxHashMap<ItemLocalId, Rc<Vec<TraitCandidate>>>>>,
831
832     /// Export map produced by name resolution.
833     export_map: FxHashMap<DefId, Rc<Vec<Export>>>,
834
835     named_region_map: NamedRegionMap,
836
837     pub hir: hir_map::Map<'tcx>,
838
839     /// A map from DefPathHash -> DefId. Includes DefIds from the local crate
840     /// as well as all upstream crates. Only populated in incremental mode.
841     pub def_path_hash_to_def_id: Option<FxHashMap<DefPathHash, DefId>>,
842
843     pub maps: maps::Maps<'tcx>,
844
845     pub mir_passes: Rc<Passes>,
846
847     // Records the free variables refrenced by every closure
848     // expression. Do not track deps for this, just recompute it from
849     // scratch every time.
850     freevars: FxHashMap<DefId, Rc<Vec<hir::Freevar>>>,
851
852     maybe_unused_trait_imports: FxHashSet<DefId>,
853
854     maybe_unused_extern_crates: Vec<(DefId, Span)>,
855
856     // Internal cache for metadata decoding. No need to track deps on this.
857     pub rcache: RefCell<FxHashMap<ty::CReaderCacheKey, Ty<'tcx>>>,
858
859     // FIXME dep tracking -- should be harmless enough
860     pub normalized_cache: RefCell<FxHashMap<Ty<'tcx>, Ty<'tcx>>>,
861
862     pub inhabitedness_cache: RefCell<FxHashMap<Ty<'tcx>, DefIdForest>>,
863
864     /// Set of nodes which mark locals as mutable which end up getting used at
865     /// some point. Local variable definitions not in this set can be warned
866     /// about.
867     pub used_mut_nodes: RefCell<NodeSet>,
868
869     /// Caches the results of trait selection. This cache is used
870     /// for things that do not have to do with the parameters in scope.
871     pub selection_cache: traits::SelectionCache<'tcx>,
872
873     /// Caches the results of trait evaluation. This cache is used
874     /// for things that do not have to do with the parameters in scope.
875     /// Merge this with `selection_cache`?
876     pub evaluation_cache: traits::EvaluationCache<'tcx>,
877
878     /// Maps Expr NodeId's to `true` iff `&expr` can have 'static lifetime.
879     pub rvalue_promotable_to_static: RefCell<NodeMap<bool>>,
880
881     /// The definite name of the current crate after taking into account
882     /// attributes, commandline parameters, etc.
883     pub crate_name: Symbol,
884
885     /// Data layout specification for the current target.
886     pub data_layout: TargetDataLayout,
887
888     /// Used to prevent layout from recursing too deeply.
889     pub layout_depth: Cell<usize>,
890
891     /// Map from function to the `#[derive]` mode that it's defining. Only used
892     /// by `proc-macro` crates.
893     pub derive_macros: RefCell<NodeMap<Symbol>>,
894
895     stability_interner: RefCell<FxHashSet<&'tcx attr::Stability>>,
896
897     layout_interner: RefCell<FxHashSet<&'tcx Layout>>,
898
899     /// A vector of every trait accessible in the whole crate
900     /// (i.e. including those from subcrates). This is used only for
901     /// error reporting, and so is lazily initialized and generally
902     /// shouldn't taint the common path (hence the RefCell).
903     pub all_traits: RefCell<Option<Vec<DefId>>>,
904 }
905
906 impl<'tcx> GlobalCtxt<'tcx> {
907     /// Get the global TyCtxt.
908     pub fn global_tcx<'a>(&'a self) -> TyCtxt<'a, 'tcx, 'tcx> {
909         TyCtxt {
910             gcx: self,
911             interners: &self.global_interners
912         }
913     }
914 }
915
916 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
917     pub fn alloc_generics(self, generics: ty::Generics) -> &'gcx ty::Generics {
918         self.global_arenas.generics.alloc(generics)
919     }
920
921     pub fn alloc_steal_mir(self, mir: Mir<'gcx>) -> &'gcx Steal<Mir<'gcx>> {
922         self.global_arenas.steal_mir.alloc(Steal::new(mir))
923     }
924
925     pub fn alloc_mir(self, mir: Mir<'gcx>) -> &'gcx Mir<'gcx> {
926         self.global_arenas.mir.alloc(mir)
927     }
928
929     pub fn alloc_tables(self, tables: ty::TypeckTables<'gcx>) -> &'gcx ty::TypeckTables<'gcx> {
930         self.global_arenas.tables.alloc(tables)
931     }
932
933     pub fn alloc_trait_def(self, def: ty::TraitDef) -> &'gcx ty::TraitDef {
934         self.global_arenas.trait_def.alloc(def)
935     }
936
937     pub fn alloc_adt_def(self,
938                          did: DefId,
939                          kind: AdtKind,
940                          variants: Vec<ty::VariantDef>,
941                          repr: ReprOptions)
942                          -> &'gcx ty::AdtDef {
943         let def = ty::AdtDef::new(self, did, kind, variants, repr);
944         self.global_arenas.adt_def.alloc(def)
945     }
946
947     pub fn alloc_byte_array(self, bytes: &[u8]) -> &'gcx [u8] {
948         if bytes.is_empty() {
949             &[]
950         } else {
951             self.global_interners.arena.alloc_slice(bytes)
952         }
953     }
954
955     pub fn alloc_const_slice(self, values: &[&'tcx ty::Const<'tcx>])
956                              -> &'tcx [&'tcx ty::Const<'tcx>] {
957         if values.is_empty() {
958             &[]
959         } else {
960             self.interners.arena.alloc_slice(values)
961         }
962     }
963
964     pub fn alloc_name_const_slice(self, values: &[(ast::Name, &'tcx ty::Const<'tcx>)])
965                                   -> &'tcx [(ast::Name, &'tcx ty::Const<'tcx>)] {
966         if values.is_empty() {
967             &[]
968         } else {
969             self.interners.arena.alloc_slice(values)
970         }
971     }
972
973     pub fn intern_stability(self, stab: attr::Stability) -> &'gcx attr::Stability {
974         if let Some(st) = self.stability_interner.borrow().get(&stab) {
975             return st;
976         }
977
978         let interned = self.global_interners.arena.alloc(stab);
979         if let Some(prev) = self.stability_interner.borrow_mut().replace(interned) {
980             bug!("Tried to overwrite interned Stability: {:?}", prev)
981         }
982         interned
983     }
984
985     pub fn intern_layout(self, layout: Layout) -> &'gcx Layout {
986         if let Some(layout) = self.layout_interner.borrow().get(&layout) {
987             return layout;
988         }
989
990         let interned = self.global_arenas.layout.alloc(layout);
991         if let Some(prev) = self.layout_interner.borrow_mut().replace(interned) {
992             bug!("Tried to overwrite interned Layout: {:?}", prev)
993         }
994         interned
995     }
996
997     pub fn lift<T: ?Sized + Lift<'tcx>>(self, value: &T) -> Option<T::Lifted> {
998         value.lift_to_tcx(self)
999     }
1000
1001     /// Like lift, but only tries in the global tcx.
1002     pub fn lift_to_global<T: ?Sized + Lift<'gcx>>(self, value: &T) -> Option<T::Lifted> {
1003         value.lift_to_tcx(self.global_tcx())
1004     }
1005
1006     /// Returns true if self is the same as self.global_tcx().
1007     fn is_global(self) -> bool {
1008         let local = self.interners as *const _;
1009         let global = &self.global_interners as *const _;
1010         local as usize == global as usize
1011     }
1012
1013     /// Create a type context and call the closure with a `TyCtxt` reference
1014     /// to the context. The closure enforces that the type context and any interned
1015     /// value (types, substs, etc.) can only be used while `ty::tls` has a valid
1016     /// reference to the context, to allow formatting values that need it.
1017     pub fn create_and_enter<F, R>(s: &'tcx Session,
1018                                   cstore: &'tcx CrateStore,
1019                                   local_providers: ty::maps::Providers<'tcx>,
1020                                   extern_providers: ty::maps::Providers<'tcx>,
1021                                   mir_passes: Rc<Passes>,
1022                                   arenas: &'tcx GlobalArenas<'tcx>,
1023                                   arena: &'tcx DroplessArena,
1024                                   resolutions: ty::Resolutions,
1025                                   named_region_map: resolve_lifetime::NamedRegionMap,
1026                                   hir: hir_map::Map<'tcx>,
1027                                   crate_name: &str,
1028                                   f: F) -> R
1029                                   where F: for<'b> FnOnce(TyCtxt<'b, 'tcx, 'tcx>) -> R
1030     {
1031         let data_layout = TargetDataLayout::parse(s);
1032         let interners = CtxtInterners::new(arena);
1033         let common_types = CommonTypes::new(&interners);
1034         let dep_graph = hir.dep_graph.clone();
1035         let max_cnum = cstore.crates_untracked().iter().map(|c| c.as_usize()).max().unwrap_or(0);
1036         let mut providers = IndexVec::from_elem_n(extern_providers, max_cnum + 1);
1037         providers[LOCAL_CRATE] = local_providers;
1038
1039         let def_path_hash_to_def_id = if s.opts.build_dep_graph() {
1040             let upstream_def_path_tables: Vec<(CrateNum, Rc<_>)> = cstore
1041                 .crates_untracked()
1042                 .iter()
1043                 .map(|&cnum| (cnum, cstore.def_path_table(cnum)))
1044                 .collect();
1045
1046             let def_path_tables = || {
1047                 upstream_def_path_tables
1048                     .iter()
1049                     .map(|&(cnum, ref rc)| (cnum, &**rc))
1050                     .chain(iter::once((LOCAL_CRATE, hir.definitions().def_path_table())))
1051             };
1052
1053             // Precompute the capacity of the hashmap so we don't have to
1054             // re-allocate when populating it.
1055             let capacity = def_path_tables().map(|(_, t)| t.size()).sum::<usize>();
1056
1057             let mut map: FxHashMap<_, _> = FxHashMap::with_capacity_and_hasher(
1058                 capacity,
1059                 ::std::default::Default::default()
1060             );
1061
1062             for (cnum, def_path_table) in def_path_tables() {
1063                 def_path_table.add_def_path_hashes_to(cnum, &mut map);
1064             }
1065
1066             Some(map)
1067         } else {
1068             None
1069         };
1070
1071         let mut trait_map = FxHashMap();
1072         for (k, v) in resolutions.trait_map {
1073             let hir_id = hir.node_to_hir_id(k);
1074             let map = trait_map.entry(hir_id.owner)
1075                 .or_insert_with(|| Rc::new(FxHashMap()));
1076             Rc::get_mut(map).unwrap().insert(hir_id.local_id, Rc::new(v));
1077         }
1078         let mut defs = FxHashMap();
1079         for (k, v) in named_region_map.defs {
1080             let hir_id = hir.node_to_hir_id(k);
1081             let map = defs.entry(hir_id.owner)
1082                 .or_insert_with(|| Rc::new(FxHashMap()));
1083             Rc::get_mut(map).unwrap().insert(hir_id.local_id, v);
1084         }
1085         let mut late_bound = FxHashMap();
1086         for k in named_region_map.late_bound {
1087             let hir_id = hir.node_to_hir_id(k);
1088             let map = late_bound.entry(hir_id.owner)
1089                 .or_insert_with(|| Rc::new(FxHashSet()));
1090             Rc::get_mut(map).unwrap().insert(hir_id.local_id);
1091         }
1092         let mut object_lifetime_defaults = FxHashMap();
1093         for (k, v) in named_region_map.object_lifetime_defaults {
1094             let hir_id = hir.node_to_hir_id(k);
1095             let map = object_lifetime_defaults.entry(hir_id.owner)
1096                 .or_insert_with(|| Rc::new(FxHashMap()));
1097             Rc::get_mut(map).unwrap().insert(hir_id.local_id, Rc::new(v));
1098         }
1099
1100         tls::enter_global(GlobalCtxt {
1101             sess: s,
1102             cstore,
1103             trans_trait_caches: traits::trans::TransTraitCaches::new(dep_graph.clone()),
1104             global_arenas: arenas,
1105             global_interners: interners,
1106             dep_graph: dep_graph.clone(),
1107             types: common_types,
1108             named_region_map: NamedRegionMap {
1109                 defs,
1110                 late_bound,
1111                 object_lifetime_defaults,
1112             },
1113             trait_map,
1114             export_map: resolutions.export_map.into_iter().map(|(k, v)| {
1115                 (k, Rc::new(v))
1116             }).collect(),
1117             freevars: resolutions.freevars.into_iter().map(|(k, v)| {
1118                 (hir.local_def_id(k), Rc::new(v))
1119             }).collect(),
1120             maybe_unused_trait_imports:
1121                 resolutions.maybe_unused_trait_imports
1122                     .into_iter()
1123                     .map(|id| hir.local_def_id(id))
1124                     .collect(),
1125             maybe_unused_extern_crates:
1126                 resolutions.maybe_unused_extern_crates
1127                     .into_iter()
1128                     .map(|(id, sp)| (hir.local_def_id(id), sp))
1129                     .collect(),
1130             hir,
1131             def_path_hash_to_def_id,
1132             maps: maps::Maps::new(providers),
1133             mir_passes,
1134             rcache: RefCell::new(FxHashMap()),
1135             normalized_cache: RefCell::new(FxHashMap()),
1136             inhabitedness_cache: RefCell::new(FxHashMap()),
1137             used_mut_nodes: RefCell::new(NodeSet()),
1138             selection_cache: traits::SelectionCache::new(),
1139             evaluation_cache: traits::EvaluationCache::new(),
1140             rvalue_promotable_to_static: RefCell::new(NodeMap()),
1141             crate_name: Symbol::intern(crate_name),
1142             data_layout,
1143             layout_interner: RefCell::new(FxHashSet()),
1144             layout_depth: Cell::new(0),
1145             derive_macros: RefCell::new(NodeMap()),
1146             stability_interner: RefCell::new(FxHashSet()),
1147             all_traits: RefCell::new(None),
1148        }, f)
1149     }
1150
1151     pub fn consider_optimizing<T: Fn() -> String>(&self, msg: T) -> bool {
1152         let cname = self.crate_name(LOCAL_CRATE).as_str();
1153         self.sess.consider_optimizing(&cname, msg)
1154     }
1155
1156     pub fn lang_items(self) -> Rc<middle::lang_items::LanguageItems> {
1157         // FIXME(#42293) Right now we insert a `with_ignore` node in the dep
1158         // graph here to ignore the fact that `get_lang_items` below depends on
1159         // the entire crate.  For now this'll prevent false positives of
1160         // recompiling too much when anything changes.
1161         //
1162         // Once red/green incremental compilation lands we should be able to
1163         // remove this because while the crate changes often the lint level map
1164         // will change rarely.
1165         self.dep_graph.with_ignore(|| {
1166             self.get_lang_items(LOCAL_CRATE)
1167         })
1168     }
1169
1170     pub fn stability(self) -> Rc<stability::Index<'tcx>> {
1171         // FIXME(#42293) we should actually track this, but fails too many tests
1172         // today.
1173         self.dep_graph.with_ignore(|| {
1174             self.stability_index(LOCAL_CRATE)
1175         })
1176     }
1177
1178     pub fn crates(self) -> Rc<Vec<CrateNum>> {
1179         self.all_crate_nums(LOCAL_CRATE)
1180     }
1181
1182     pub fn def_key(self, id: DefId) -> hir_map::DefKey {
1183         if id.is_local() {
1184             self.hir.def_key(id)
1185         } else {
1186             self.cstore.def_key(id)
1187         }
1188     }
1189
1190     /// Convert a `DefId` into its fully expanded `DefPath` (every
1191     /// `DefId` is really just an interned def-path).
1192     ///
1193     /// Note that if `id` is not local to this crate, the result will
1194     ///  be a non-local `DefPath`.
1195     pub fn def_path(self, id: DefId) -> hir_map::DefPath {
1196         if id.is_local() {
1197             self.hir.def_path(id)
1198         } else {
1199             self.cstore.def_path(id)
1200         }
1201     }
1202
1203     #[inline]
1204     pub fn def_path_hash(self, def_id: DefId) -> hir_map::DefPathHash {
1205         if def_id.is_local() {
1206             self.hir.definitions().def_path_hash(def_id.index)
1207         } else {
1208             self.cstore.def_path_hash(def_id)
1209         }
1210     }
1211
1212     pub fn metadata_encoding_version(self) -> Vec<u8> {
1213         self.cstore.metadata_encoding_version().to_vec()
1214     }
1215
1216     // Note that this is *untracked* and should only be used within the query
1217     // system if the result is otherwise tracked through queries
1218     pub fn crate_data_as_rc_any(self, cnum: CrateNum) -> Rc<Any> {
1219         self.cstore.crate_data_as_rc_any(cnum)
1220     }
1221 }
1222
1223 impl<'a, 'tcx> TyCtxt<'a, 'tcx, 'tcx> {
1224     pub fn encode_metadata(self, link_meta: &LinkMeta, reachable: &NodeSet)
1225         -> (EncodedMetadata, EncodedMetadataHashes)
1226     {
1227         self.cstore.encode_metadata(self, link_meta, reachable)
1228     }
1229 }
1230
1231 impl<'gcx: 'tcx, 'tcx> GlobalCtxt<'gcx> {
1232     /// Call the closure with a local `TyCtxt` using the given arena.
1233     pub fn enter_local<F, R>(&self, arena: &'tcx DroplessArena, f: F) -> R
1234         where F: for<'a> FnOnce(TyCtxt<'a, 'gcx, 'tcx>) -> R
1235     {
1236         let interners = CtxtInterners::new(arena);
1237         tls::enter(self, &interners, f)
1238     }
1239 }
1240
1241 /// A trait implemented for all X<'a> types which can be safely and
1242 /// efficiently converted to X<'tcx> as long as they are part of the
1243 /// provided TyCtxt<'tcx>.
1244 /// This can be done, for example, for Ty<'tcx> or &'tcx Substs<'tcx>
1245 /// by looking them up in their respective interners.
1246 ///
1247 /// However, this is still not the best implementation as it does
1248 /// need to compare the components, even for interned values.
1249 /// It would be more efficient if TypedArena provided a way to
1250 /// determine whether the address is in the allocated range.
1251 ///
1252 /// None is returned if the value or one of the components is not part
1253 /// of the provided context.
1254 /// For Ty, None can be returned if either the type interner doesn't
1255 /// contain the TypeVariants key or if the address of the interned
1256 /// pointer differs. The latter case is possible if a primitive type,
1257 /// e.g. `()` or `u8`, was interned in a different context.
1258 pub trait Lift<'tcx> {
1259     type Lifted;
1260     fn lift_to_tcx<'a, 'gcx>(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Option<Self::Lifted>;
1261 }
1262
1263 impl<'a, 'tcx> Lift<'tcx> for Ty<'a> {
1264     type Lifted = Ty<'tcx>;
1265     fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>) -> Option<Ty<'tcx>> {
1266         if tcx.interners.arena.in_arena(*self as *const _) {
1267             return Some(unsafe { mem::transmute(*self) });
1268         }
1269         // Also try in the global tcx if we're not that.
1270         if !tcx.is_global() {
1271             self.lift_to_tcx(tcx.global_tcx())
1272         } else {
1273             None
1274         }
1275     }
1276 }
1277
1278 impl<'a, 'tcx> Lift<'tcx> for Region<'a> {
1279     type Lifted = Region<'tcx>;
1280     fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>) -> Option<Region<'tcx>> {
1281         if tcx.interners.arena.in_arena(*self as *const _) {
1282             return Some(unsafe { mem::transmute(*self) });
1283         }
1284         // Also try in the global tcx if we're not that.
1285         if !tcx.is_global() {
1286             self.lift_to_tcx(tcx.global_tcx())
1287         } else {
1288             None
1289         }
1290     }
1291 }
1292
1293 impl<'a, 'tcx> Lift<'tcx> for &'a Const<'a> {
1294     type Lifted = &'tcx Const<'tcx>;
1295     fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>) -> Option<&'tcx Const<'tcx>> {
1296         if tcx.interners.arena.in_arena(*self as *const _) {
1297             return Some(unsafe { mem::transmute(*self) });
1298         }
1299         // Also try in the global tcx if we're not that.
1300         if !tcx.is_global() {
1301             self.lift_to_tcx(tcx.global_tcx())
1302         } else {
1303             None
1304         }
1305     }
1306 }
1307
1308 impl<'a, 'tcx> Lift<'tcx> for &'a Substs<'a> {
1309     type Lifted = &'tcx Substs<'tcx>;
1310     fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>) -> Option<&'tcx Substs<'tcx>> {
1311         if self.len() == 0 {
1312             return Some(Slice::empty());
1313         }
1314         if tcx.interners.arena.in_arena(&self[..] as *const _) {
1315             return Some(unsafe { mem::transmute(*self) });
1316         }
1317         // Also try in the global tcx if we're not that.
1318         if !tcx.is_global() {
1319             self.lift_to_tcx(tcx.global_tcx())
1320         } else {
1321             None
1322         }
1323     }
1324 }
1325
1326 impl<'a, 'tcx> Lift<'tcx> for &'a Slice<Ty<'a>> {
1327     type Lifted = &'tcx Slice<Ty<'tcx>>;
1328     fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>)
1329                              -> Option<&'tcx Slice<Ty<'tcx>>> {
1330         if self.len() == 0 {
1331             return Some(Slice::empty());
1332         }
1333         if tcx.interners.arena.in_arena(*self as *const _) {
1334             return Some(unsafe { mem::transmute(*self) });
1335         }
1336         // Also try in the global tcx if we're not that.
1337         if !tcx.is_global() {
1338             self.lift_to_tcx(tcx.global_tcx())
1339         } else {
1340             None
1341         }
1342     }
1343 }
1344
1345 impl<'a, 'tcx> Lift<'tcx> for &'a Slice<ExistentialPredicate<'a>> {
1346     type Lifted = &'tcx Slice<ExistentialPredicate<'tcx>>;
1347     fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>)
1348         -> Option<&'tcx Slice<ExistentialPredicate<'tcx>>> {
1349         if self.is_empty() {
1350             return Some(Slice::empty());
1351         }
1352         if tcx.interners.arena.in_arena(*self as *const _) {
1353             return Some(unsafe { mem::transmute(*self) });
1354         }
1355         // Also try in the global tcx if we're not that.
1356         if !tcx.is_global() {
1357             self.lift_to_tcx(tcx.global_tcx())
1358         } else {
1359             None
1360         }
1361     }
1362 }
1363
1364 impl<'a, 'tcx> Lift<'tcx> for &'a Slice<Predicate<'a>> {
1365     type Lifted = &'tcx Slice<Predicate<'tcx>>;
1366     fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>)
1367         -> Option<&'tcx Slice<Predicate<'tcx>>> {
1368         if self.is_empty() {
1369             return Some(Slice::empty());
1370         }
1371         if tcx.interners.arena.in_arena(*self as *const _) {
1372             return Some(unsafe { mem::transmute(*self) });
1373         }
1374         // Also try in the global tcx if we're not that.
1375         if !tcx.is_global() {
1376             self.lift_to_tcx(tcx.global_tcx())
1377         } else {
1378             None
1379         }
1380     }
1381 }
1382
1383 pub mod tls {
1384     use super::{CtxtInterners, GlobalCtxt, TyCtxt};
1385
1386     use std::cell::Cell;
1387     use std::fmt;
1388     use syntax_pos;
1389
1390     /// Marker types used for the scoped TLS slot.
1391     /// The type context cannot be used directly because the scoped TLS
1392     /// in libstd doesn't allow types generic over lifetimes.
1393     enum ThreadLocalGlobalCtxt {}
1394     enum ThreadLocalInterners {}
1395
1396     thread_local! {
1397         static TLS_TCX: Cell<Option<(*const ThreadLocalGlobalCtxt,
1398                                      *const ThreadLocalInterners)>> = Cell::new(None)
1399     }
1400
1401     fn span_debug(span: syntax_pos::Span, f: &mut fmt::Formatter) -> fmt::Result {
1402         with(|tcx| {
1403             write!(f, "{}", tcx.sess.codemap().span_to_string(span))
1404         })
1405     }
1406
1407     pub fn enter_global<'gcx, F, R>(gcx: GlobalCtxt<'gcx>, f: F) -> R
1408         where F: for<'a> FnOnce(TyCtxt<'a, 'gcx, 'gcx>) -> R
1409     {
1410         syntax_pos::SPAN_DEBUG.with(|span_dbg| {
1411             let original_span_debug = span_dbg.get();
1412             span_dbg.set(span_debug);
1413             let result = enter(&gcx, &gcx.global_interners, f);
1414             span_dbg.set(original_span_debug);
1415             result
1416         })
1417     }
1418
1419     pub fn enter<'a, 'gcx: 'tcx, 'tcx, F, R>(gcx: &'a GlobalCtxt<'gcx>,
1420                                              interners: &'a CtxtInterners<'tcx>,
1421                                              f: F) -> R
1422         where F: FnOnce(TyCtxt<'a, 'gcx, 'tcx>) -> R
1423     {
1424         let gcx_ptr = gcx as *const _ as *const ThreadLocalGlobalCtxt;
1425         let interners_ptr = interners as *const _ as *const ThreadLocalInterners;
1426         TLS_TCX.with(|tls| {
1427             let prev = tls.get();
1428             tls.set(Some((gcx_ptr, interners_ptr)));
1429             let ret = f(TyCtxt {
1430                 gcx,
1431                 interners,
1432             });
1433             tls.set(prev);
1434             ret
1435         })
1436     }
1437
1438     pub fn with<F, R>(f: F) -> R
1439         where F: for<'a, 'gcx, 'tcx> FnOnce(TyCtxt<'a, 'gcx, 'tcx>) -> R
1440     {
1441         TLS_TCX.with(|tcx| {
1442             let (gcx, interners) = tcx.get().unwrap();
1443             let gcx = unsafe { &*(gcx as *const GlobalCtxt) };
1444             let interners = unsafe { &*(interners as *const CtxtInterners) };
1445             f(TyCtxt {
1446                 gcx,
1447                 interners,
1448             })
1449         })
1450     }
1451
1452     pub fn with_opt<F, R>(f: F) -> R
1453         where F: for<'a, 'gcx, 'tcx> FnOnce(Option<TyCtxt<'a, 'gcx, 'tcx>>) -> R
1454     {
1455         if TLS_TCX.with(|tcx| tcx.get().is_some()) {
1456             with(|v| f(Some(v)))
1457         } else {
1458             f(None)
1459         }
1460     }
1461 }
1462
1463 macro_rules! sty_debug_print {
1464     ($ctxt: expr, $($variant: ident),*) => {{
1465         // curious inner module to allow variant names to be used as
1466         // variable names.
1467         #[allow(non_snake_case)]
1468         mod inner {
1469             use ty::{self, TyCtxt};
1470             use ty::context::Interned;
1471
1472             #[derive(Copy, Clone)]
1473             struct DebugStat {
1474                 total: usize,
1475                 region_infer: usize,
1476                 ty_infer: usize,
1477                 both_infer: usize,
1478             }
1479
1480             pub fn go(tcx: TyCtxt) {
1481                 let mut total = DebugStat {
1482                     total: 0,
1483                     region_infer: 0, ty_infer: 0, both_infer: 0,
1484                 };
1485                 $(let mut $variant = total;)*
1486
1487
1488                 for &Interned(t) in tcx.interners.type_.borrow().iter() {
1489                     let variant = match t.sty {
1490                         ty::TyBool | ty::TyChar | ty::TyInt(..) | ty::TyUint(..) |
1491                             ty::TyFloat(..) | ty::TyStr | ty::TyNever => continue,
1492                         ty::TyError => /* unimportant */ continue,
1493                         $(ty::$variant(..) => &mut $variant,)*
1494                     };
1495                     let region = t.flags.intersects(ty::TypeFlags::HAS_RE_INFER);
1496                     let ty = t.flags.intersects(ty::TypeFlags::HAS_TY_INFER);
1497
1498                     variant.total += 1;
1499                     total.total += 1;
1500                     if region { total.region_infer += 1; variant.region_infer += 1 }
1501                     if ty { total.ty_infer += 1; variant.ty_infer += 1 }
1502                     if region && ty { total.both_infer += 1; variant.both_infer += 1 }
1503                 }
1504                 println!("Ty interner             total           ty region  both");
1505                 $(println!("    {:18}: {uses:6} {usespc:4.1}%, \
1506 {ty:4.1}% {region:5.1}% {both:4.1}%",
1507                            stringify!($variant),
1508                            uses = $variant.total,
1509                            usespc = $variant.total as f64 * 100.0 / total.total as f64,
1510                            ty = $variant.ty_infer as f64 * 100.0  / total.total as f64,
1511                            region = $variant.region_infer as f64 * 100.0  / total.total as f64,
1512                            both = $variant.both_infer as f64 * 100.0  / total.total as f64);
1513                   )*
1514                 println!("                  total {uses:6}        \
1515 {ty:4.1}% {region:5.1}% {both:4.1}%",
1516                          uses = total.total,
1517                          ty = total.ty_infer as f64 * 100.0  / total.total as f64,
1518                          region = total.region_infer as f64 * 100.0  / total.total as f64,
1519                          both = total.both_infer as f64 * 100.0  / total.total as f64)
1520             }
1521         }
1522
1523         inner::go($ctxt)
1524     }}
1525 }
1526
1527 impl<'a, 'tcx> TyCtxt<'a, 'tcx, 'tcx> {
1528     pub fn print_debug_stats(self) {
1529         sty_debug_print!(
1530             self,
1531             TyAdt, TyArray, TySlice, TyRawPtr, TyRef, TyFnDef, TyFnPtr, TyGenerator,
1532             TyDynamic, TyClosure, TyTuple, TyParam, TyInfer, TyProjection, TyAnon);
1533
1534         println!("Substs interner: #{}", self.interners.substs.borrow().len());
1535         println!("Region interner: #{}", self.interners.region.borrow().len());
1536         println!("Stability interner: #{}", self.stability_interner.borrow().len());
1537         println!("Layout interner: #{}", self.layout_interner.borrow().len());
1538     }
1539 }
1540
1541
1542 /// An entry in an interner.
1543 struct Interned<'tcx, T: 'tcx+?Sized>(&'tcx T);
1544
1545 // NB: An Interned<Ty> compares and hashes as a sty.
1546 impl<'tcx> PartialEq for Interned<'tcx, TyS<'tcx>> {
1547     fn eq(&self, other: &Interned<'tcx, TyS<'tcx>>) -> bool {
1548         self.0.sty == other.0.sty
1549     }
1550 }
1551
1552 impl<'tcx> Eq for Interned<'tcx, TyS<'tcx>> {}
1553
1554 impl<'tcx> Hash for Interned<'tcx, TyS<'tcx>> {
1555     fn hash<H: Hasher>(&self, s: &mut H) {
1556         self.0.sty.hash(s)
1557     }
1558 }
1559
1560 impl<'tcx: 'lcx, 'lcx> Borrow<TypeVariants<'lcx>> for Interned<'tcx, TyS<'tcx>> {
1561     fn borrow<'a>(&'a self) -> &'a TypeVariants<'lcx> {
1562         &self.0.sty
1563     }
1564 }
1565
1566 // NB: An Interned<Slice<T>> compares and hashes as its elements.
1567 impl<'tcx, T: PartialEq> PartialEq for Interned<'tcx, Slice<T>> {
1568     fn eq(&self, other: &Interned<'tcx, Slice<T>>) -> bool {
1569         self.0[..] == other.0[..]
1570     }
1571 }
1572
1573 impl<'tcx, T: Eq> Eq for Interned<'tcx, Slice<T>> {}
1574
1575 impl<'tcx, T: Hash> Hash for Interned<'tcx, Slice<T>> {
1576     fn hash<H: Hasher>(&self, s: &mut H) {
1577         self.0[..].hash(s)
1578     }
1579 }
1580
1581 impl<'tcx: 'lcx, 'lcx> Borrow<[Ty<'lcx>]> for Interned<'tcx, Slice<Ty<'tcx>>> {
1582     fn borrow<'a>(&'a self) -> &'a [Ty<'lcx>] {
1583         &self.0[..]
1584     }
1585 }
1586
1587 impl<'tcx: 'lcx, 'lcx> Borrow<[Kind<'lcx>]> for Interned<'tcx, Substs<'tcx>> {
1588     fn borrow<'a>(&'a self) -> &'a [Kind<'lcx>] {
1589         &self.0[..]
1590     }
1591 }
1592
1593 impl<'tcx> Borrow<RegionKind> for Interned<'tcx, RegionKind> {
1594     fn borrow<'a>(&'a self) -> &'a RegionKind {
1595         &self.0
1596     }
1597 }
1598
1599 impl<'tcx: 'lcx, 'lcx> Borrow<[ExistentialPredicate<'lcx>]>
1600     for Interned<'tcx, Slice<ExistentialPredicate<'tcx>>> {
1601     fn borrow<'a>(&'a self) -> &'a [ExistentialPredicate<'lcx>] {
1602         &self.0[..]
1603     }
1604 }
1605
1606 impl<'tcx: 'lcx, 'lcx> Borrow<[Predicate<'lcx>]>
1607     for Interned<'tcx, Slice<Predicate<'tcx>>> {
1608     fn borrow<'a>(&'a self) -> &'a [Predicate<'lcx>] {
1609         &self.0[..]
1610     }
1611 }
1612
1613 impl<'tcx: 'lcx, 'lcx> Borrow<Const<'lcx>> for Interned<'tcx, Const<'tcx>> {
1614     fn borrow<'a>(&'a self) -> &'a Const<'lcx> {
1615         &self.0
1616     }
1617 }
1618
1619 macro_rules! intern_method {
1620     ($lt_tcx:tt, $name:ident: $method:ident($alloc:ty,
1621                                             $alloc_method:ident,
1622                                             $alloc_to_key:expr,
1623                                             $alloc_to_ret:expr,
1624                                             $needs_infer:expr) -> $ty:ty) => {
1625         impl<'a, 'gcx, $lt_tcx> TyCtxt<'a, 'gcx, $lt_tcx> {
1626             pub fn $method(self, v: $alloc) -> &$lt_tcx $ty {
1627                 {
1628                     let key = ($alloc_to_key)(&v);
1629                     if let Some(i) = self.interners.$name.borrow().get(key) {
1630                         return i.0;
1631                     }
1632                     if !self.is_global() {
1633                         if let Some(i) = self.global_interners.$name.borrow().get(key) {
1634                             return i.0;
1635                         }
1636                     }
1637                 }
1638
1639                 // HACK(eddyb) Depend on flags being accurate to
1640                 // determine that all contents are in the global tcx.
1641                 // See comments on Lift for why we can't use that.
1642                 if !($needs_infer)(&v) {
1643                     if !self.is_global() {
1644                         let v = unsafe {
1645                             mem::transmute(v)
1646                         };
1647                         let i = ($alloc_to_ret)(self.global_interners.arena.$alloc_method(v));
1648                         self.global_interners.$name.borrow_mut().insert(Interned(i));
1649                         return i;
1650                     }
1651                 } else {
1652                     // Make sure we don't end up with inference
1653                     // types/regions in the global tcx.
1654                     if self.is_global() {
1655                         bug!("Attempted to intern `{:?}` which contains \
1656                               inference types/regions in the global type context",
1657                              v);
1658                     }
1659                 }
1660
1661                 let i = ($alloc_to_ret)(self.interners.arena.$alloc_method(v));
1662                 self.interners.$name.borrow_mut().insert(Interned(i));
1663                 i
1664             }
1665         }
1666     }
1667 }
1668
1669 macro_rules! direct_interners {
1670     ($lt_tcx:tt, $($name:ident: $method:ident($needs_infer:expr) -> $ty:ty),+) => {
1671         $(impl<$lt_tcx> PartialEq for Interned<$lt_tcx, $ty> {
1672             fn eq(&self, other: &Self) -> bool {
1673                 self.0 == other.0
1674             }
1675         }
1676
1677         impl<$lt_tcx> Eq for Interned<$lt_tcx, $ty> {}
1678
1679         impl<$lt_tcx> Hash for Interned<$lt_tcx, $ty> {
1680             fn hash<H: Hasher>(&self, s: &mut H) {
1681                 self.0.hash(s)
1682             }
1683         }
1684
1685         intern_method!($lt_tcx, $name: $method($ty, alloc, |x| x, |x| x, $needs_infer) -> $ty);)+
1686     }
1687 }
1688
1689 pub fn keep_local<'tcx, T: ty::TypeFoldable<'tcx>>(x: &T) -> bool {
1690     x.has_type_flags(ty::TypeFlags::KEEP_IN_LOCAL_TCX)
1691 }
1692
1693 direct_interners!('tcx,
1694     region: mk_region(|r| {
1695         match r {
1696             &ty::ReVar(_) | &ty::ReSkolemized(..) => true,
1697             _ => false
1698         }
1699     }) -> RegionKind,
1700     const_: mk_const(|c: &Const| keep_local(&c.ty) || keep_local(&c.val)) -> Const<'tcx>
1701 );
1702
1703 macro_rules! slice_interners {
1704     ($($field:ident: $method:ident($ty:ident)),+) => (
1705         $(intern_method!('tcx, $field: $method(&[$ty<'tcx>], alloc_slice, Deref::deref,
1706                                                |xs: &[$ty]| -> &Slice<$ty> {
1707             unsafe { mem::transmute(xs) }
1708         }, |xs: &[$ty]| xs.iter().any(keep_local)) -> Slice<$ty<'tcx>>);)+
1709     )
1710 }
1711
1712 slice_interners!(
1713     existential_predicates: _intern_existential_predicates(ExistentialPredicate),
1714     predicates: _intern_predicates(Predicate),
1715     type_list: _intern_type_list(Ty),
1716     substs: _intern_substs(Kind)
1717 );
1718
1719 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
1720     /// Create an unsafe fn ty based on a safe fn ty.
1721     pub fn safe_to_unsafe_fn_ty(self, sig: PolyFnSig<'tcx>) -> Ty<'tcx> {
1722         assert_eq!(sig.unsafety(), hir::Unsafety::Normal);
1723         self.mk_fn_ptr(sig.map_bound(|sig| ty::FnSig {
1724             unsafety: hir::Unsafety::Unsafe,
1725             ..sig
1726         }))
1727     }
1728
1729     // Interns a type/name combination, stores the resulting box in cx.interners,
1730     // and returns the box as cast to an unsafe ptr (see comments for Ty above).
1731     pub fn mk_ty(self, st: TypeVariants<'tcx>) -> Ty<'tcx> {
1732         let global_interners = if !self.is_global() {
1733             Some(&self.global_interners)
1734         } else {
1735             None
1736         };
1737         self.interners.intern_ty(st, global_interners)
1738     }
1739
1740     pub fn mk_mach_int(self, tm: ast::IntTy) -> Ty<'tcx> {
1741         match tm {
1742             ast::IntTy::Is   => self.types.isize,
1743             ast::IntTy::I8   => self.types.i8,
1744             ast::IntTy::I16  => self.types.i16,
1745             ast::IntTy::I32  => self.types.i32,
1746             ast::IntTy::I64  => self.types.i64,
1747             ast::IntTy::I128  => self.types.i128,
1748         }
1749     }
1750
1751     pub fn mk_mach_uint(self, tm: ast::UintTy) -> Ty<'tcx> {
1752         match tm {
1753             ast::UintTy::Us   => self.types.usize,
1754             ast::UintTy::U8   => self.types.u8,
1755             ast::UintTy::U16  => self.types.u16,
1756             ast::UintTy::U32  => self.types.u32,
1757             ast::UintTy::U64  => self.types.u64,
1758             ast::UintTy::U128  => self.types.u128,
1759         }
1760     }
1761
1762     pub fn mk_mach_float(self, tm: ast::FloatTy) -> Ty<'tcx> {
1763         match tm {
1764             ast::FloatTy::F32  => self.types.f32,
1765             ast::FloatTy::F64  => self.types.f64,
1766         }
1767     }
1768
1769     pub fn mk_str(self) -> Ty<'tcx> {
1770         self.mk_ty(TyStr)
1771     }
1772
1773     pub fn mk_static_str(self) -> Ty<'tcx> {
1774         self.mk_imm_ref(self.types.re_static, self.mk_str())
1775     }
1776
1777     pub fn mk_adt(self, def: &'tcx AdtDef, substs: &'tcx Substs<'tcx>) -> Ty<'tcx> {
1778         // take a copy of substs so that we own the vectors inside
1779         self.mk_ty(TyAdt(def, substs))
1780     }
1781
1782     pub fn mk_box(self, ty: Ty<'tcx>) -> Ty<'tcx> {
1783         let def_id = self.require_lang_item(lang_items::OwnedBoxLangItem);
1784         let adt_def = self.adt_def(def_id);
1785         let substs = self.mk_substs(iter::once(Kind::from(ty)));
1786         self.mk_ty(TyAdt(adt_def, substs))
1787     }
1788
1789     pub fn mk_ptr(self, tm: TypeAndMut<'tcx>) -> Ty<'tcx> {
1790         self.mk_ty(TyRawPtr(tm))
1791     }
1792
1793     pub fn mk_ref(self, r: Region<'tcx>, tm: TypeAndMut<'tcx>) -> Ty<'tcx> {
1794         self.mk_ty(TyRef(r, tm))
1795     }
1796
1797     pub fn mk_mut_ref(self, r: Region<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
1798         self.mk_ref(r, TypeAndMut {ty: ty, mutbl: hir::MutMutable})
1799     }
1800
1801     pub fn mk_imm_ref(self, r: Region<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
1802         self.mk_ref(r, TypeAndMut {ty: ty, mutbl: hir::MutImmutable})
1803     }
1804
1805     pub fn mk_mut_ptr(self, ty: Ty<'tcx>) -> Ty<'tcx> {
1806         self.mk_ptr(TypeAndMut {ty: ty, mutbl: hir::MutMutable})
1807     }
1808
1809     pub fn mk_imm_ptr(self, ty: Ty<'tcx>) -> Ty<'tcx> {
1810         self.mk_ptr(TypeAndMut {ty: ty, mutbl: hir::MutImmutable})
1811     }
1812
1813     pub fn mk_nil_ptr(self) -> Ty<'tcx> {
1814         self.mk_imm_ptr(self.mk_nil())
1815     }
1816
1817     pub fn mk_array(self, ty: Ty<'tcx>, n: u64) -> Ty<'tcx> {
1818         let n = ConstUsize::new(n, self.sess.target.usize_ty).unwrap();
1819         self.mk_array_const_usize(ty, n)
1820     }
1821
1822     pub fn mk_array_const_usize(self, ty: Ty<'tcx>, n: ConstUsize) -> Ty<'tcx> {
1823         self.mk_ty(TyArray(ty, self.mk_const(ty::Const {
1824             val: ConstVal::Integral(ConstInt::Usize(n)),
1825             ty: self.types.usize
1826         })))
1827     }
1828
1829     pub fn mk_slice(self, ty: Ty<'tcx>) -> Ty<'tcx> {
1830         self.mk_ty(TySlice(ty))
1831     }
1832
1833     pub fn intern_tup(self, ts: &[Ty<'tcx>], defaulted: bool) -> Ty<'tcx> {
1834         self.mk_ty(TyTuple(self.intern_type_list(ts), defaulted))
1835     }
1836
1837     pub fn mk_tup<I: InternAs<[Ty<'tcx>], Ty<'tcx>>>(self, iter: I,
1838                                                      defaulted: bool) -> I::Output {
1839         iter.intern_with(|ts| self.mk_ty(TyTuple(self.intern_type_list(ts), defaulted)))
1840     }
1841
1842     pub fn mk_nil(self) -> Ty<'tcx> {
1843         self.intern_tup(&[], false)
1844     }
1845
1846     pub fn mk_diverging_default(self) -> Ty<'tcx> {
1847         if self.sess.features.borrow().never_type {
1848             self.types.never
1849         } else {
1850             self.intern_tup(&[], true)
1851         }
1852     }
1853
1854     pub fn mk_bool(self) -> Ty<'tcx> {
1855         self.mk_ty(TyBool)
1856     }
1857
1858     pub fn mk_fn_def(self, def_id: DefId,
1859                      substs: &'tcx Substs<'tcx>) -> Ty<'tcx> {
1860         self.mk_ty(TyFnDef(def_id, substs))
1861     }
1862
1863     pub fn mk_fn_ptr(self, fty: PolyFnSig<'tcx>) -> Ty<'tcx> {
1864         self.mk_ty(TyFnPtr(fty))
1865     }
1866
1867     pub fn mk_dynamic(
1868         self,
1869         obj: ty::Binder<&'tcx Slice<ExistentialPredicate<'tcx>>>,
1870         reg: ty::Region<'tcx>
1871     ) -> Ty<'tcx> {
1872         self.mk_ty(TyDynamic(obj, reg))
1873     }
1874
1875     pub fn mk_projection(self,
1876                          item_def_id: DefId,
1877                          substs: &'tcx Substs<'tcx>)
1878         -> Ty<'tcx> {
1879             self.mk_ty(TyProjection(ProjectionTy {
1880                 item_def_id,
1881                 substs,
1882             }))
1883         }
1884
1885     pub fn mk_closure(self,
1886                       closure_id: DefId,
1887                       substs: &'tcx Substs<'tcx>)
1888         -> Ty<'tcx> {
1889         self.mk_closure_from_closure_substs(closure_id, ClosureSubsts {
1890             substs,
1891         })
1892     }
1893
1894     pub fn mk_closure_from_closure_substs(self,
1895                                           closure_id: DefId,
1896                                           closure_substs: ClosureSubsts<'tcx>)
1897                                           -> Ty<'tcx> {
1898         self.mk_ty(TyClosure(closure_id, closure_substs))
1899     }
1900
1901     pub fn mk_generator(self,
1902                         id: DefId,
1903                         closure_substs: ClosureSubsts<'tcx>,
1904                         interior: GeneratorInterior<'tcx>)
1905                         -> Ty<'tcx> {
1906         self.mk_ty(TyGenerator(id, closure_substs, interior))
1907     }
1908
1909     pub fn mk_var(self, v: TyVid) -> Ty<'tcx> {
1910         self.mk_infer(TyVar(v))
1911     }
1912
1913     pub fn mk_int_var(self, v: IntVid) -> Ty<'tcx> {
1914         self.mk_infer(IntVar(v))
1915     }
1916
1917     pub fn mk_float_var(self, v: FloatVid) -> Ty<'tcx> {
1918         self.mk_infer(FloatVar(v))
1919     }
1920
1921     pub fn mk_infer(self, it: InferTy) -> Ty<'tcx> {
1922         self.mk_ty(TyInfer(it))
1923     }
1924
1925     pub fn mk_param(self,
1926                     index: u32,
1927                     name: Name) -> Ty<'tcx> {
1928         self.mk_ty(TyParam(ParamTy { idx: index, name: name }))
1929     }
1930
1931     pub fn mk_self_type(self) -> Ty<'tcx> {
1932         self.mk_param(0, keywords::SelfType.name())
1933     }
1934
1935     pub fn mk_param_from_def(self, def: &ty::TypeParameterDef) -> Ty<'tcx> {
1936         self.mk_param(def.index, def.name)
1937     }
1938
1939     pub fn mk_anon(self, def_id: DefId, substs: &'tcx Substs<'tcx>) -> Ty<'tcx> {
1940         self.mk_ty(TyAnon(def_id, substs))
1941     }
1942
1943     pub fn intern_existential_predicates(self, eps: &[ExistentialPredicate<'tcx>])
1944         -> &'tcx Slice<ExistentialPredicate<'tcx>> {
1945         assert!(!eps.is_empty());
1946         assert!(eps.windows(2).all(|w| w[0].cmp(self, &w[1]) != Ordering::Greater));
1947         self._intern_existential_predicates(eps)
1948     }
1949
1950     pub fn intern_predicates(self, preds: &[Predicate<'tcx>])
1951         -> &'tcx Slice<Predicate<'tcx>> {
1952         // FIXME consider asking the input slice to be sorted to avoid
1953         // re-interning permutations, in which case that would be asserted
1954         // here.
1955         if preds.len() == 0 {
1956             // The macro-generated method below asserts we don't intern an empty slice.
1957             Slice::empty()
1958         } else {
1959             self._intern_predicates(preds)
1960         }
1961     }
1962
1963     pub fn intern_type_list(self, ts: &[Ty<'tcx>]) -> &'tcx Slice<Ty<'tcx>> {
1964         if ts.len() == 0 {
1965             Slice::empty()
1966         } else {
1967             self._intern_type_list(ts)
1968         }
1969     }
1970
1971     pub fn intern_substs(self, ts: &[Kind<'tcx>]) -> &'tcx Slice<Kind<'tcx>> {
1972         if ts.len() == 0 {
1973             Slice::empty()
1974         } else {
1975             self._intern_substs(ts)
1976         }
1977     }
1978
1979     pub fn mk_fn_sig<I>(self,
1980                         inputs: I,
1981                         output: I::Item,
1982                         variadic: bool,
1983                         unsafety: hir::Unsafety,
1984                         abi: abi::Abi)
1985         -> <I::Item as InternIteratorElement<Ty<'tcx>, ty::FnSig<'tcx>>>::Output
1986         where I: Iterator,
1987               I::Item: InternIteratorElement<Ty<'tcx>, ty::FnSig<'tcx>>
1988     {
1989         inputs.chain(iter::once(output)).intern_with(|xs| ty::FnSig {
1990             inputs_and_output: self.intern_type_list(xs),
1991             variadic, unsafety, abi
1992         })
1993     }
1994
1995     pub fn mk_existential_predicates<I: InternAs<[ExistentialPredicate<'tcx>],
1996                                      &'tcx Slice<ExistentialPredicate<'tcx>>>>(self, iter: I)
1997                                      -> I::Output {
1998         iter.intern_with(|xs| self.intern_existential_predicates(xs))
1999     }
2000
2001     pub fn mk_predicates<I: InternAs<[Predicate<'tcx>],
2002                                      &'tcx Slice<Predicate<'tcx>>>>(self, iter: I)
2003                                      -> I::Output {
2004         iter.intern_with(|xs| self.intern_predicates(xs))
2005     }
2006
2007     pub fn mk_type_list<I: InternAs<[Ty<'tcx>],
2008                         &'tcx Slice<Ty<'tcx>>>>(self, iter: I) -> I::Output {
2009         iter.intern_with(|xs| self.intern_type_list(xs))
2010     }
2011
2012     pub fn mk_substs<I: InternAs<[Kind<'tcx>],
2013                      &'tcx Slice<Kind<'tcx>>>>(self, iter: I) -> I::Output {
2014         iter.intern_with(|xs| self.intern_substs(xs))
2015     }
2016
2017     pub fn mk_substs_trait(self,
2018                      s: Ty<'tcx>,
2019                      t: &[Ty<'tcx>])
2020                     -> &'tcx Substs<'tcx>
2021     {
2022         self.mk_substs(iter::once(s).chain(t.into_iter().cloned()).map(Kind::from))
2023     }
2024
2025     pub fn lint_node<S: Into<MultiSpan>>(self,
2026                                          lint: &'static Lint,
2027                                          id: NodeId,
2028                                          span: S,
2029                                          msg: &str) {
2030         self.struct_span_lint_node(lint, id, span.into(), msg).emit()
2031     }
2032
2033     pub fn lint_node_note<S: Into<MultiSpan>>(self,
2034                                               lint: &'static Lint,
2035                                               id: NodeId,
2036                                               span: S,
2037                                               msg: &str,
2038                                               note: &str) {
2039         let mut err = self.struct_span_lint_node(lint, id, span.into(), msg);
2040         err.note(note);
2041         err.emit()
2042     }
2043
2044     pub fn lint_level_at_node(self, lint: &'static Lint, mut id: NodeId)
2045         -> (lint::Level, lint::LintSource)
2046     {
2047         // Right now we insert a `with_ignore` node in the dep graph here to
2048         // ignore the fact that `lint_levels` below depends on the entire crate.
2049         // For now this'll prevent false positives of recompiling too much when
2050         // anything changes.
2051         //
2052         // Once red/green incremental compilation lands we should be able to
2053         // remove this because while the crate changes often the lint level map
2054         // will change rarely.
2055         self.dep_graph.with_ignore(|| {
2056             let sets = self.lint_levels(LOCAL_CRATE);
2057             loop {
2058                 let hir_id = self.hir.definitions().node_to_hir_id(id);
2059                 if let Some(pair) = sets.level_and_source(lint, hir_id) {
2060                     return pair
2061                 }
2062                 let next = self.hir.get_parent_node(id);
2063                 if next == id {
2064                     bug!("lint traversal reached the root of the crate");
2065                 }
2066                 id = next;
2067             }
2068         })
2069     }
2070
2071     pub fn struct_span_lint_node<S: Into<MultiSpan>>(self,
2072                                                      lint: &'static Lint,
2073                                                      id: NodeId,
2074                                                      span: S,
2075                                                      msg: &str)
2076         -> DiagnosticBuilder<'tcx>
2077     {
2078         let (level, src) = self.lint_level_at_node(lint, id);
2079         lint::struct_lint_level(self.sess, lint, level, src, Some(span.into()), msg)
2080     }
2081
2082     pub fn struct_lint_node(self, lint: &'static Lint, id: NodeId, msg: &str)
2083         -> DiagnosticBuilder<'tcx>
2084     {
2085         let (level, src) = self.lint_level_at_node(lint, id);
2086         lint::struct_lint_level(self.sess, lint, level, src, None, msg)
2087     }
2088
2089     pub fn in_scope_traits(self, id: HirId) -> Option<Rc<Vec<TraitCandidate>>> {
2090         self.in_scope_traits_map(id.owner)
2091             .and_then(|map| map.get(&id.local_id).cloned())
2092     }
2093
2094     pub fn named_region(self, id: HirId) -> Option<resolve_lifetime::Region> {
2095         self.named_region_map(id.owner)
2096             .and_then(|map| map.get(&id.local_id).cloned())
2097     }
2098
2099     pub fn is_late_bound(self, id: HirId) -> bool {
2100         self.is_late_bound_map(id.owner)
2101             .map(|set| set.contains(&id.local_id))
2102             .unwrap_or(false)
2103     }
2104
2105     pub fn object_lifetime_defaults(self, id: HirId)
2106         -> Option<Rc<Vec<ObjectLifetimeDefault>>>
2107     {
2108         self.object_lifetime_defaults_map(id.owner)
2109             .and_then(|map| map.get(&id.local_id).cloned())
2110     }
2111 }
2112
2113 pub trait InternAs<T: ?Sized, R> {
2114     type Output;
2115     fn intern_with<F>(self, f: F) -> Self::Output
2116         where F: FnOnce(&T) -> R;
2117 }
2118
2119 impl<I, T, R, E> InternAs<[T], R> for I
2120     where E: InternIteratorElement<T, R>,
2121           I: Iterator<Item=E> {
2122     type Output = E::Output;
2123     fn intern_with<F>(self, f: F) -> Self::Output
2124         where F: FnOnce(&[T]) -> R {
2125         E::intern_with(self, f)
2126     }
2127 }
2128
2129 pub trait InternIteratorElement<T, R>: Sized {
2130     type Output;
2131     fn intern_with<I: Iterator<Item=Self>, F: FnOnce(&[T]) -> R>(iter: I, f: F) -> Self::Output;
2132 }
2133
2134 impl<T, R> InternIteratorElement<T, R> for T {
2135     type Output = R;
2136     fn intern_with<I: Iterator<Item=Self>, F: FnOnce(&[T]) -> R>(iter: I, f: F) -> Self::Output {
2137         f(&iter.collect::<AccumulateVec<[_; 8]>>())
2138     }
2139 }
2140
2141 impl<'a, T, R> InternIteratorElement<T, R> for &'a T
2142     where T: Clone + 'a
2143 {
2144     type Output = R;
2145     fn intern_with<I: Iterator<Item=Self>, F: FnOnce(&[T]) -> R>(iter: I, f: F) -> Self::Output {
2146         f(&iter.cloned().collect::<AccumulateVec<[_; 8]>>())
2147     }
2148 }
2149
2150 impl<T, R, E> InternIteratorElement<T, R> for Result<T, E> {
2151     type Output = Result<R, E>;
2152     fn intern_with<I: Iterator<Item=Self>, F: FnOnce(&[T]) -> R>(iter: I, f: F) -> Self::Output {
2153         Ok(f(&iter.collect::<Result<AccumulateVec<[_; 8]>, _>>()?))
2154     }
2155 }
2156
2157 struct NamedRegionMap {
2158     defs: FxHashMap<DefIndex, Rc<FxHashMap<ItemLocalId, resolve_lifetime::Region>>>,
2159     late_bound: FxHashMap<DefIndex, Rc<FxHashSet<ItemLocalId>>>,
2160     object_lifetime_defaults:
2161         FxHashMap<
2162             DefIndex,
2163             Rc<FxHashMap<ItemLocalId, Rc<Vec<ObjectLifetimeDefault>>>>,
2164         >,
2165 }
2166
2167 pub fn provide(providers: &mut ty::maps::Providers) {
2168     // FIXME(#44234) - almost all of these queries have no sub-queries and
2169     // therefore no actual inputs, they're just reading tables calculated in
2170     // resolve! Does this work? Unsure! That's what the issue is about
2171     providers.in_scope_traits_map = |tcx, id| tcx.gcx.trait_map.get(&id).cloned();
2172     providers.module_exports = |tcx, id| tcx.gcx.export_map.get(&id).cloned();
2173     providers.named_region_map = |tcx, id| tcx.gcx.named_region_map.defs.get(&id).cloned();
2174     providers.is_late_bound_map = |tcx, id| tcx.gcx.named_region_map.late_bound.get(&id).cloned();
2175     providers.object_lifetime_defaults_map = |tcx, id| {
2176         tcx.gcx.named_region_map.object_lifetime_defaults.get(&id).cloned()
2177     };
2178     providers.crate_name = |tcx, id| {
2179         assert_eq!(id, LOCAL_CRATE);
2180         tcx.crate_name
2181     };
2182     providers.get_lang_items = |tcx, id| {
2183         assert_eq!(id, LOCAL_CRATE);
2184         Rc::new(middle::lang_items::collect(tcx))
2185     };
2186     providers.freevars = |tcx, id| tcx.gcx.freevars.get(&id).cloned();
2187     providers.maybe_unused_trait_import = |tcx, id| {
2188         tcx.maybe_unused_trait_imports.contains(&id)
2189     };
2190     providers.maybe_unused_extern_crates = |tcx, cnum| {
2191         assert_eq!(cnum, LOCAL_CRATE);
2192         Rc::new(tcx.maybe_unused_extern_crates.clone())
2193     };
2194
2195     providers.stability_index = |tcx, cnum| {
2196         assert_eq!(cnum, LOCAL_CRATE);
2197         Rc::new(stability::Index::new(tcx))
2198     };
2199     providers.lookup_stability = |tcx, id| {
2200         assert_eq!(id.krate, LOCAL_CRATE);
2201         let id = tcx.hir.definitions().def_index_to_hir_id(id.index);
2202         tcx.stability().local_stability(id)
2203     };
2204     providers.lookup_deprecation_entry = |tcx, id| {
2205         assert_eq!(id.krate, LOCAL_CRATE);
2206         let id = tcx.hir.definitions().def_index_to_hir_id(id.index);
2207         tcx.stability().local_deprecation_entry(id)
2208     };
2209     providers.extern_mod_stmt_cnum = |tcx, id| {
2210         let id = tcx.hir.as_local_node_id(id).unwrap();
2211         tcx.cstore.extern_mod_stmt_cnum_untracked(id)
2212     };
2213     providers.all_crate_nums = |tcx, cnum| {
2214         assert_eq!(cnum, LOCAL_CRATE);
2215         Rc::new(tcx.cstore.crates_untracked())
2216     };
2217     providers.postorder_cnums = |tcx, cnum| {
2218         assert_eq!(cnum, LOCAL_CRATE);
2219         Rc::new(tcx.cstore.postorder_cnums_untracked())
2220     };
2221 }