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