]> git.lizzy.rs Git - rust.git/blob - src/librustc/ty/context.rs
rustc: Remove the `used_unsafe` field on 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::{TraitMap};
18 use hir::def::{Def, ExportMap};
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;
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 specializes_cache: RefCell<traits::SpecializesCache>,
812
813     pub trans_trait_caches: traits::trans::TransTraitCaches<'tcx>,
814
815     pub dep_graph: DepGraph,
816
817     /// Common types, pre-interned for your convenience.
818     pub types: CommonTypes<'tcx>,
819
820     /// Map indicating what traits are in scope for places where this
821     /// is relevant; generated by resolve.
822     pub trait_map: TraitMap,
823
824     /// Export map produced by name resolution.
825     pub export_map: ExportMap,
826
827     pub named_region_map: resolve_lifetime::NamedRegionMap,
828
829     pub hir: hir_map::Map<'tcx>,
830
831     /// A map from DefPathHash -> DefId. Includes DefIds from the local crate
832     /// as well as all upstream crates. Only populated in incremental mode.
833     pub def_path_hash_to_def_id: Option<FxHashMap<DefPathHash, DefId>>,
834
835     pub maps: maps::Maps<'tcx>,
836
837     pub mir_passes: Rc<Passes>,
838
839     // Records the free variables refrenced by every closure
840     // expression. Do not track deps for this, just recompute it from
841     // scratch every time.
842     pub freevars: RefCell<FreevarMap>,
843
844     pub maybe_unused_trait_imports: NodeSet,
845
846     pub maybe_unused_extern_crates: Vec<(NodeId, Span)>,
847
848     // Internal cache for metadata decoding. No need to track deps on this.
849     pub rcache: RefCell<FxHashMap<ty::CReaderCacheKey, Ty<'tcx>>>,
850
851     // FIXME dep tracking -- should be harmless enough
852     pub normalized_cache: RefCell<FxHashMap<Ty<'tcx>, Ty<'tcx>>>,
853
854     pub inhabitedness_cache: RefCell<FxHashMap<Ty<'tcx>, DefIdForest>>,
855
856     pub lang_items: middle::lang_items::LanguageItems,
857
858     /// Set of nodes which mark locals as mutable which end up getting used at
859     /// some point. Local variable definitions not in this set can be warned
860     /// about.
861     pub used_mut_nodes: RefCell<NodeSet>,
862
863     /// Maps any item's def-id to its stability index.
864     pub stability: RefCell<stability::Index<'tcx>>,
865
866     /// Caches the results of trait selection. This cache is used
867     /// for things that do not have to do with the parameters in scope.
868     pub selection_cache: traits::SelectionCache<'tcx>,
869
870     /// Caches the results of trait evaluation. This cache is used
871     /// for things that do not have to do with the parameters in scope.
872     /// Merge this with `selection_cache`?
873     pub evaluation_cache: traits::EvaluationCache<'tcx>,
874
875     /// Maps Expr NodeId's to `true` iff `&expr` can have 'static lifetime.
876     pub rvalue_promotable_to_static: RefCell<NodeMap<bool>>,
877
878     /// The definite name of the current crate after taking into account
879     /// attributes, commandline parameters, etc.
880     pub crate_name: Symbol,
881
882     /// Data layout specification for the current target.
883     pub data_layout: TargetDataLayout,
884
885     /// Used to prevent layout from recursing too deeply.
886     pub layout_depth: Cell<usize>,
887
888     /// Map from function to the `#[derive]` mode that it's defining. Only used
889     /// by `proc-macro` crates.
890     pub derive_macros: RefCell<NodeMap<Symbol>>,
891
892     stability_interner: RefCell<FxHashSet<&'tcx attr::Stability>>,
893
894     layout_interner: RefCell<FxHashSet<&'tcx Layout>>,
895
896     /// A vector of every trait accessible in the whole crate
897     /// (i.e. including those from subcrates). This is used only for
898     /// error reporting, and so is lazily initialized and generally
899     /// shouldn't taint the common path (hence the RefCell).
900     pub all_traits: RefCell<Option<Vec<DefId>>>,
901 }
902
903 impl<'tcx> GlobalCtxt<'tcx> {
904     /// Get the global TyCtxt.
905     pub fn global_tcx<'a>(&'a self) -> TyCtxt<'a, 'tcx, 'tcx> {
906         TyCtxt {
907             gcx: self,
908             interners: &self.global_interners
909         }
910     }
911 }
912
913 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
914     pub fn crate_name(self, cnum: CrateNum) -> Symbol {
915         if cnum == LOCAL_CRATE {
916             self.crate_name
917         } else {
918             self.sess.cstore.crate_name(cnum)
919         }
920     }
921
922     pub fn original_crate_name(self, cnum: CrateNum) -> Symbol {
923         if cnum == LOCAL_CRATE {
924             self.crate_name.clone()
925         } else {
926             self.sess.cstore.original_crate_name(cnum)
927         }
928     }
929
930     pub fn crate_disambiguator(self, cnum: CrateNum) -> Symbol {
931         if cnum == LOCAL_CRATE {
932             self.sess.local_crate_disambiguator()
933         } else {
934             self.sess.cstore.crate_disambiguator(cnum)
935         }
936     }
937
938     pub fn alloc_generics(self, generics: ty::Generics) -> &'gcx ty::Generics {
939         self.global_arenas.generics.alloc(generics)
940     }
941
942     pub fn alloc_steal_mir(self, mir: Mir<'gcx>) -> &'gcx Steal<Mir<'gcx>> {
943         self.global_arenas.steal_mir.alloc(Steal::new(mir))
944     }
945
946     pub fn alloc_mir(self, mir: Mir<'gcx>) -> &'gcx Mir<'gcx> {
947         self.global_arenas.mir.alloc(mir)
948     }
949
950     pub fn alloc_tables(self, tables: ty::TypeckTables<'gcx>) -> &'gcx ty::TypeckTables<'gcx> {
951         self.global_arenas.tables.alloc(tables)
952     }
953
954     pub fn alloc_trait_def(self, def: ty::TraitDef) -> &'gcx ty::TraitDef {
955         self.global_arenas.trait_def.alloc(def)
956     }
957
958     pub fn alloc_adt_def(self,
959                          did: DefId,
960                          kind: AdtKind,
961                          variants: Vec<ty::VariantDef>,
962                          repr: ReprOptions)
963                          -> &'gcx ty::AdtDef {
964         let def = ty::AdtDef::new(self, did, kind, variants, repr);
965         self.global_arenas.adt_def.alloc(def)
966     }
967
968     pub fn intern_stability(self, stab: attr::Stability) -> &'gcx attr::Stability {
969         if let Some(st) = self.stability_interner.borrow().get(&stab) {
970             return st;
971         }
972
973         let interned = self.global_interners.arena.alloc(stab);
974         if let Some(prev) = self.stability_interner.borrow_mut().replace(interned) {
975             bug!("Tried to overwrite interned Stability: {:?}", prev)
976         }
977         interned
978     }
979
980     pub fn intern_layout(self, layout: Layout) -> &'gcx Layout {
981         if let Some(layout) = self.layout_interner.borrow().get(&layout) {
982             return layout;
983         }
984
985         let interned = self.global_arenas.layout.alloc(layout);
986         if let Some(prev) = self.layout_interner.borrow_mut().replace(interned) {
987             bug!("Tried to overwrite interned Layout: {:?}", prev)
988         }
989         interned
990     }
991
992     pub fn lift<T: ?Sized + Lift<'tcx>>(self, value: &T) -> Option<T::Lifted> {
993         value.lift_to_tcx(self)
994     }
995
996     /// Like lift, but only tries in the global tcx.
997     pub fn lift_to_global<T: ?Sized + Lift<'gcx>>(self, value: &T) -> Option<T::Lifted> {
998         value.lift_to_tcx(self.global_tcx())
999     }
1000
1001     /// Returns true if self is the same as self.global_tcx().
1002     fn is_global(self) -> bool {
1003         let local = self.interners as *const _;
1004         let global = &self.global_interners as *const _;
1005         local as usize == global as usize
1006     }
1007
1008     /// Create a type context and call the closure with a `TyCtxt` reference
1009     /// to the context. The closure enforces that the type context and any interned
1010     /// value (types, substs, etc.) can only be used while `ty::tls` has a valid
1011     /// reference to the context, to allow formatting values that need it.
1012     pub fn create_and_enter<F, R>(s: &'tcx Session,
1013                                   local_providers: ty::maps::Providers<'tcx>,
1014                                   extern_providers: ty::maps::Providers<'tcx>,
1015                                   mir_passes: Rc<Passes>,
1016                                   arenas: &'tcx GlobalArenas<'tcx>,
1017                                   arena: &'tcx DroplessArena,
1018                                   resolutions: ty::Resolutions,
1019                                   named_region_map: resolve_lifetime::NamedRegionMap,
1020                                   hir: hir_map::Map<'tcx>,
1021                                   lang_items: middle::lang_items::LanguageItems,
1022                                   stability: stability::Index<'tcx>,
1023                                   crate_name: &str,
1024                                   f: F) -> R
1025                                   where F: for<'b> FnOnce(TyCtxt<'b, 'tcx, 'tcx>) -> R
1026     {
1027         let data_layout = TargetDataLayout::parse(s);
1028         let interners = CtxtInterners::new(arena);
1029         let common_types = CommonTypes::new(&interners);
1030         let dep_graph = hir.dep_graph.clone();
1031         let max_cnum = s.cstore.crates().iter().map(|c| c.as_usize()).max().unwrap_or(0);
1032         let mut providers = IndexVec::from_elem_n(extern_providers, max_cnum + 1);
1033         providers[LOCAL_CRATE] = local_providers;
1034
1035         let def_path_hash_to_def_id = if s.opts.build_dep_graph() {
1036             let upstream_def_path_tables: Vec<(CrateNum, Rc<_>)> = s
1037                 .cstore
1038                 .crates()
1039                 .iter()
1040                 .map(|&cnum| (cnum, s.cstore.def_path_table(cnum)))
1041                 .collect();
1042
1043             let def_path_tables = || {
1044                 upstream_def_path_tables
1045                     .iter()
1046                     .map(|&(cnum, ref rc)| (cnum, &**rc))
1047                     .chain(iter::once((LOCAL_CRATE, hir.definitions().def_path_table())))
1048             };
1049
1050             // Precompute the capacity of the hashmap so we don't have to
1051             // re-allocate when populating it.
1052             let capacity = def_path_tables().map(|(_, t)| t.size()).sum::<usize>();
1053
1054             let mut map: FxHashMap<_, _> = FxHashMap::with_capacity_and_hasher(
1055                 capacity,
1056                 ::std::default::Default::default()
1057             );
1058
1059             for (cnum, def_path_table) in def_path_tables() {
1060                 def_path_table.add_def_path_hashes_to(cnum, &mut map);
1061             }
1062
1063             Some(map)
1064         } else {
1065             None
1066         };
1067
1068         tls::enter_global(GlobalCtxt {
1069             sess: s,
1070             trans_trait_caches: traits::trans::TransTraitCaches::new(dep_graph.clone()),
1071             specializes_cache: RefCell::new(traits::SpecializesCache::new()),
1072             global_arenas: arenas,
1073             global_interners: interners,
1074             dep_graph: dep_graph.clone(),
1075             types: common_types,
1076             named_region_map,
1077             trait_map: resolutions.trait_map,
1078             export_map: resolutions.export_map,
1079             hir,
1080             def_path_hash_to_def_id,
1081             maps: maps::Maps::new(providers),
1082             mir_passes,
1083             freevars: RefCell::new(resolutions.freevars),
1084             maybe_unused_trait_imports: resolutions.maybe_unused_trait_imports,
1085             maybe_unused_extern_crates: resolutions.maybe_unused_extern_crates,
1086             rcache: RefCell::new(FxHashMap()),
1087             normalized_cache: RefCell::new(FxHashMap()),
1088             inhabitedness_cache: RefCell::new(FxHashMap()),
1089             lang_items,
1090             used_mut_nodes: RefCell::new(NodeSet()),
1091             stability: RefCell::new(stability),
1092             selection_cache: traits::SelectionCache::new(),
1093             evaluation_cache: traits::EvaluationCache::new(),
1094             rvalue_promotable_to_static: RefCell::new(NodeMap()),
1095             crate_name: Symbol::intern(crate_name),
1096             data_layout,
1097             layout_interner: RefCell::new(FxHashSet()),
1098             layout_depth: Cell::new(0),
1099             derive_macros: RefCell::new(NodeMap()),
1100             stability_interner: RefCell::new(FxHashSet()),
1101             all_traits: RefCell::new(None),
1102        }, f)
1103     }
1104
1105     pub fn consider_optimizing<T: Fn() -> String>(&self, msg: T) -> bool {
1106         let cname = self.crate_name(LOCAL_CRATE).as_str();
1107         self.sess.consider_optimizing(&cname, msg)
1108     }
1109 }
1110
1111 impl<'gcx: 'tcx, 'tcx> GlobalCtxt<'gcx> {
1112     /// Call the closure with a local `TyCtxt` using the given arena.
1113     pub fn enter_local<F, R>(&self, arena: &'tcx DroplessArena, f: F) -> R
1114         where F: for<'a> FnOnce(TyCtxt<'a, 'gcx, 'tcx>) -> R
1115     {
1116         let interners = CtxtInterners::new(arena);
1117         tls::enter(self, &interners, f)
1118     }
1119 }
1120
1121 /// A trait implemented for all X<'a> types which can be safely and
1122 /// efficiently converted to X<'tcx> as long as they are part of the
1123 /// provided TyCtxt<'tcx>.
1124 /// This can be done, for example, for Ty<'tcx> or &'tcx Substs<'tcx>
1125 /// by looking them up in their respective interners.
1126 ///
1127 /// However, this is still not the best implementation as it does
1128 /// need to compare the components, even for interned values.
1129 /// It would be more efficient if TypedArena provided a way to
1130 /// determine whether the address is in the allocated range.
1131 ///
1132 /// None is returned if the value or one of the components is not part
1133 /// of the provided context.
1134 /// For Ty, None can be returned if either the type interner doesn't
1135 /// contain the TypeVariants key or if the address of the interned
1136 /// pointer differs. The latter case is possible if a primitive type,
1137 /// e.g. `()` or `u8`, was interned in a different context.
1138 pub trait Lift<'tcx> {
1139     type Lifted;
1140     fn lift_to_tcx<'a, 'gcx>(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Option<Self::Lifted>;
1141 }
1142
1143 impl<'a, 'tcx> Lift<'tcx> for ty::ParamEnv<'a> {
1144     type Lifted = ty::ParamEnv<'tcx>;
1145     fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>) -> Option<ty::ParamEnv<'tcx>> {
1146         self.caller_bounds.lift_to_tcx(tcx).and_then(|caller_bounds| {
1147             Some(ty::ParamEnv {
1148                 reveal: self.reveal,
1149                 caller_bounds,
1150             })
1151         })
1152     }
1153 }
1154
1155 impl<'a, 'tcx> Lift<'tcx> for Ty<'a> {
1156     type Lifted = Ty<'tcx>;
1157     fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>) -> Option<Ty<'tcx>> {
1158         if tcx.interners.arena.in_arena(*self as *const _) {
1159             return Some(unsafe { mem::transmute(*self) });
1160         }
1161         // Also try in the global tcx if we're not that.
1162         if !tcx.is_global() {
1163             self.lift_to_tcx(tcx.global_tcx())
1164         } else {
1165             None
1166         }
1167     }
1168 }
1169
1170 impl<'a, 'tcx> Lift<'tcx> for &'a Substs<'a> {
1171     type Lifted = &'tcx Substs<'tcx>;
1172     fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>) -> Option<&'tcx Substs<'tcx>> {
1173         if self.len() == 0 {
1174             return Some(Slice::empty());
1175         }
1176         if tcx.interners.arena.in_arena(&self[..] as *const _) {
1177             return Some(unsafe { mem::transmute(*self) });
1178         }
1179         // Also try in the global tcx if we're not that.
1180         if !tcx.is_global() {
1181             self.lift_to_tcx(tcx.global_tcx())
1182         } else {
1183             None
1184         }
1185     }
1186 }
1187
1188 impl<'a, 'tcx> Lift<'tcx> for Region<'a> {
1189     type Lifted = Region<'tcx>;
1190     fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>) -> Option<Region<'tcx>> {
1191         if tcx.interners.arena.in_arena(*self as *const _) {
1192             return Some(unsafe { mem::transmute(*self) });
1193         }
1194         // Also try in the global tcx if we're not that.
1195         if !tcx.is_global() {
1196             self.lift_to_tcx(tcx.global_tcx())
1197         } else {
1198             None
1199         }
1200     }
1201 }
1202
1203 impl<'a, 'tcx> Lift<'tcx> for &'a Slice<Ty<'a>> {
1204     type Lifted = &'tcx Slice<Ty<'tcx>>;
1205     fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>)
1206                              -> Option<&'tcx Slice<Ty<'tcx>>> {
1207         if self.len() == 0 {
1208             return Some(Slice::empty());
1209         }
1210         if tcx.interners.arena.in_arena(*self as *const _) {
1211             return Some(unsafe { mem::transmute(*self) });
1212         }
1213         // Also try in the global tcx if we're not that.
1214         if !tcx.is_global() {
1215             self.lift_to_tcx(tcx.global_tcx())
1216         } else {
1217             None
1218         }
1219     }
1220 }
1221
1222 impl<'a, 'tcx> Lift<'tcx> for &'a Slice<ExistentialPredicate<'a>> {
1223     type Lifted = &'tcx Slice<ExistentialPredicate<'tcx>>;
1224     fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>)
1225         -> Option<&'tcx Slice<ExistentialPredicate<'tcx>>> {
1226         if self.is_empty() {
1227             return Some(Slice::empty());
1228         }
1229         if tcx.interners.arena.in_arena(*self as *const _) {
1230             return Some(unsafe { mem::transmute(*self) });
1231         }
1232         // Also try in the global tcx if we're not that.
1233         if !tcx.is_global() {
1234             self.lift_to_tcx(tcx.global_tcx())
1235         } else {
1236             None
1237         }
1238     }
1239 }
1240
1241 impl<'a, 'tcx> Lift<'tcx> for &'a Slice<Predicate<'a>> {
1242     type Lifted = &'tcx Slice<Predicate<'tcx>>;
1243     fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>)
1244         -> Option<&'tcx Slice<Predicate<'tcx>>> {
1245         if self.is_empty() {
1246             return Some(Slice::empty());
1247         }
1248         if tcx.interners.arena.in_arena(*self as *const _) {
1249             return Some(unsafe { mem::transmute(*self) });
1250         }
1251         // Also try in the global tcx if we're not that.
1252         if !tcx.is_global() {
1253             self.lift_to_tcx(tcx.global_tcx())
1254         } else {
1255             None
1256         }
1257     }
1258 }
1259
1260 pub mod tls {
1261     use super::{CtxtInterners, GlobalCtxt, TyCtxt};
1262
1263     use std::cell::Cell;
1264     use std::fmt;
1265     use syntax_pos;
1266
1267     /// Marker types used for the scoped TLS slot.
1268     /// The type context cannot be used directly because the scoped TLS
1269     /// in libstd doesn't allow types generic over lifetimes.
1270     enum ThreadLocalGlobalCtxt {}
1271     enum ThreadLocalInterners {}
1272
1273     thread_local! {
1274         static TLS_TCX: Cell<Option<(*const ThreadLocalGlobalCtxt,
1275                                      *const ThreadLocalInterners)>> = Cell::new(None)
1276     }
1277
1278     fn span_debug(span: syntax_pos::Span, f: &mut fmt::Formatter) -> fmt::Result {
1279         with(|tcx| {
1280             write!(f, "{}", tcx.sess.codemap().span_to_string(span))
1281         })
1282     }
1283
1284     pub fn enter_global<'gcx, F, R>(gcx: GlobalCtxt<'gcx>, f: F) -> R
1285         where F: for<'a> FnOnce(TyCtxt<'a, 'gcx, 'gcx>) -> R
1286     {
1287         syntax_pos::SPAN_DEBUG.with(|span_dbg| {
1288             let original_span_debug = span_dbg.get();
1289             span_dbg.set(span_debug);
1290             let result = enter(&gcx, &gcx.global_interners, f);
1291             span_dbg.set(original_span_debug);
1292             result
1293         })
1294     }
1295
1296     pub fn enter<'a, 'gcx: 'tcx, 'tcx, F, R>(gcx: &'a GlobalCtxt<'gcx>,
1297                                              interners: &'a CtxtInterners<'tcx>,
1298                                              f: F) -> R
1299         where F: FnOnce(TyCtxt<'a, 'gcx, 'tcx>) -> R
1300     {
1301         let gcx_ptr = gcx as *const _ as *const ThreadLocalGlobalCtxt;
1302         let interners_ptr = interners as *const _ as *const ThreadLocalInterners;
1303         TLS_TCX.with(|tls| {
1304             let prev = tls.get();
1305             tls.set(Some((gcx_ptr, interners_ptr)));
1306             let ret = f(TyCtxt {
1307                 gcx,
1308                 interners,
1309             });
1310             tls.set(prev);
1311             ret
1312         })
1313     }
1314
1315     pub fn with<F, R>(f: F) -> R
1316         where F: for<'a, 'gcx, 'tcx> FnOnce(TyCtxt<'a, 'gcx, 'tcx>) -> R
1317     {
1318         TLS_TCX.with(|tcx| {
1319             let (gcx, interners) = tcx.get().unwrap();
1320             let gcx = unsafe { &*(gcx as *const GlobalCtxt) };
1321             let interners = unsafe { &*(interners as *const CtxtInterners) };
1322             f(TyCtxt {
1323                 gcx,
1324                 interners,
1325             })
1326         })
1327     }
1328
1329     pub fn with_opt<F, R>(f: F) -> R
1330         where F: for<'a, 'gcx, 'tcx> FnOnce(Option<TyCtxt<'a, 'gcx, 'tcx>>) -> R
1331     {
1332         if TLS_TCX.with(|tcx| tcx.get().is_some()) {
1333             with(|v| f(Some(v)))
1334         } else {
1335             f(None)
1336         }
1337     }
1338 }
1339
1340 macro_rules! sty_debug_print {
1341     ($ctxt: expr, $($variant: ident),*) => {{
1342         // curious inner module to allow variant names to be used as
1343         // variable names.
1344         #[allow(non_snake_case)]
1345         mod inner {
1346             use ty::{self, TyCtxt};
1347             use ty::context::Interned;
1348
1349             #[derive(Copy, Clone)]
1350             struct DebugStat {
1351                 total: usize,
1352                 region_infer: usize,
1353                 ty_infer: usize,
1354                 both_infer: usize,
1355             }
1356
1357             pub fn go(tcx: TyCtxt) {
1358                 let mut total = DebugStat {
1359                     total: 0,
1360                     region_infer: 0, ty_infer: 0, both_infer: 0,
1361                 };
1362                 $(let mut $variant = total;)*
1363
1364
1365                 for &Interned(t) in tcx.interners.type_.borrow().iter() {
1366                     let variant = match t.sty {
1367                         ty::TyBool | ty::TyChar | ty::TyInt(..) | ty::TyUint(..) |
1368                             ty::TyFloat(..) | ty::TyStr | ty::TyNever => continue,
1369                         ty::TyError => /* unimportant */ continue,
1370                         $(ty::$variant(..) => &mut $variant,)*
1371                     };
1372                     let region = t.flags.intersects(ty::TypeFlags::HAS_RE_INFER);
1373                     let ty = t.flags.intersects(ty::TypeFlags::HAS_TY_INFER);
1374
1375                     variant.total += 1;
1376                     total.total += 1;
1377                     if region { total.region_infer += 1; variant.region_infer += 1 }
1378                     if ty { total.ty_infer += 1; variant.ty_infer += 1 }
1379                     if region && ty { total.both_infer += 1; variant.both_infer += 1 }
1380                 }
1381                 println!("Ty interner             total           ty region  both");
1382                 $(println!("    {:18}: {uses:6} {usespc:4.1}%, \
1383 {ty:4.1}% {region:5.1}% {both:4.1}%",
1384                            stringify!($variant),
1385                            uses = $variant.total,
1386                            usespc = $variant.total as f64 * 100.0 / total.total as f64,
1387                            ty = $variant.ty_infer as f64 * 100.0  / total.total as f64,
1388                            region = $variant.region_infer as f64 * 100.0  / total.total as f64,
1389                            both = $variant.both_infer as f64 * 100.0  / total.total as f64);
1390                   )*
1391                 println!("                  total {uses:6}        \
1392 {ty:4.1}% {region:5.1}% {both:4.1}%",
1393                          uses = total.total,
1394                          ty = total.ty_infer as f64 * 100.0  / total.total as f64,
1395                          region = total.region_infer as f64 * 100.0  / total.total as f64,
1396                          both = total.both_infer as f64 * 100.0  / total.total as f64)
1397             }
1398         }
1399
1400         inner::go($ctxt)
1401     }}
1402 }
1403
1404 impl<'a, 'tcx> TyCtxt<'a, 'tcx, 'tcx> {
1405     pub fn print_debug_stats(self) {
1406         sty_debug_print!(
1407             self,
1408             TyAdt, TyArray, TySlice, TyRawPtr, TyRef, TyFnDef, TyFnPtr, TyGenerator,
1409             TyDynamic, TyClosure, TyTuple, TyParam, TyInfer, TyProjection, TyAnon);
1410
1411         println!("Substs interner: #{}", self.interners.substs.borrow().len());
1412         println!("Region interner: #{}", self.interners.region.borrow().len());
1413         println!("Stability interner: #{}", self.stability_interner.borrow().len());
1414         println!("Layout interner: #{}", self.layout_interner.borrow().len());
1415     }
1416 }
1417
1418
1419 /// An entry in an interner.
1420 struct Interned<'tcx, T: 'tcx+?Sized>(&'tcx T);
1421
1422 // NB: An Interned<Ty> compares and hashes as a sty.
1423 impl<'tcx> PartialEq for Interned<'tcx, TyS<'tcx>> {
1424     fn eq(&self, other: &Interned<'tcx, TyS<'tcx>>) -> bool {
1425         self.0.sty == other.0.sty
1426     }
1427 }
1428
1429 impl<'tcx> Eq for Interned<'tcx, TyS<'tcx>> {}
1430
1431 impl<'tcx> Hash for Interned<'tcx, TyS<'tcx>> {
1432     fn hash<H: Hasher>(&self, s: &mut H) {
1433         self.0.sty.hash(s)
1434     }
1435 }
1436
1437 impl<'tcx: 'lcx, 'lcx> Borrow<TypeVariants<'lcx>> for Interned<'tcx, TyS<'tcx>> {
1438     fn borrow<'a>(&'a self) -> &'a TypeVariants<'lcx> {
1439         &self.0.sty
1440     }
1441 }
1442
1443 // NB: An Interned<Slice<T>> compares and hashes as its elements.
1444 impl<'tcx, T: PartialEq> PartialEq for Interned<'tcx, Slice<T>> {
1445     fn eq(&self, other: &Interned<'tcx, Slice<T>>) -> bool {
1446         self.0[..] == other.0[..]
1447     }
1448 }
1449
1450 impl<'tcx, T: Eq> Eq for Interned<'tcx, Slice<T>> {}
1451
1452 impl<'tcx, T: Hash> Hash for Interned<'tcx, Slice<T>> {
1453     fn hash<H: Hasher>(&self, s: &mut H) {
1454         self.0[..].hash(s)
1455     }
1456 }
1457
1458 impl<'tcx: 'lcx, 'lcx> Borrow<[Ty<'lcx>]> for Interned<'tcx, Slice<Ty<'tcx>>> {
1459     fn borrow<'a>(&'a self) -> &'a [Ty<'lcx>] {
1460         &self.0[..]
1461     }
1462 }
1463
1464 impl<'tcx: 'lcx, 'lcx> Borrow<[Kind<'lcx>]> for Interned<'tcx, Substs<'tcx>> {
1465     fn borrow<'a>(&'a self) -> &'a [Kind<'lcx>] {
1466         &self.0[..]
1467     }
1468 }
1469
1470 impl<'tcx> Borrow<RegionKind> for Interned<'tcx, RegionKind> {
1471     fn borrow<'a>(&'a self) -> &'a RegionKind {
1472         &self.0
1473     }
1474 }
1475
1476 impl<'tcx: 'lcx, 'lcx> Borrow<[ExistentialPredicate<'lcx>]>
1477     for Interned<'tcx, Slice<ExistentialPredicate<'tcx>>> {
1478     fn borrow<'a>(&'a self) -> &'a [ExistentialPredicate<'lcx>] {
1479         &self.0[..]
1480     }
1481 }
1482
1483 impl<'tcx: 'lcx, 'lcx> Borrow<[Predicate<'lcx>]>
1484     for Interned<'tcx, Slice<Predicate<'tcx>>> {
1485     fn borrow<'a>(&'a self) -> &'a [Predicate<'lcx>] {
1486         &self.0[..]
1487     }
1488 }
1489
1490 macro_rules! intern_method {
1491     ($lt_tcx:tt, $name:ident: $method:ident($alloc:ty,
1492                                             $alloc_method:ident,
1493                                             $alloc_to_key:expr,
1494                                             $alloc_to_ret:expr,
1495                                             $needs_infer:expr) -> $ty:ty) => {
1496         impl<'a, 'gcx, $lt_tcx> TyCtxt<'a, 'gcx, $lt_tcx> {
1497             pub fn $method(self, v: $alloc) -> &$lt_tcx $ty {
1498                 {
1499                     let key = ($alloc_to_key)(&v);
1500                     if let Some(i) = self.interners.$name.borrow().get(key) {
1501                         return i.0;
1502                     }
1503                     if !self.is_global() {
1504                         if let Some(i) = self.global_interners.$name.borrow().get(key) {
1505                             return i.0;
1506                         }
1507                     }
1508                 }
1509
1510                 // HACK(eddyb) Depend on flags being accurate to
1511                 // determine that all contents are in the global tcx.
1512                 // See comments on Lift for why we can't use that.
1513                 if !($needs_infer)(&v) {
1514                     if !self.is_global() {
1515                         let v = unsafe {
1516                             mem::transmute(v)
1517                         };
1518                         let i = ($alloc_to_ret)(self.global_interners.arena.$alloc_method(v));
1519                         self.global_interners.$name.borrow_mut().insert(Interned(i));
1520                         return i;
1521                     }
1522                 } else {
1523                     // Make sure we don't end up with inference
1524                     // types/regions in the global tcx.
1525                     if self.is_global() {
1526                         bug!("Attempted to intern `{:?}` which contains \
1527                               inference types/regions in the global type context",
1528                              v);
1529                     }
1530                 }
1531
1532                 let i = ($alloc_to_ret)(self.interners.arena.$alloc_method(v));
1533                 self.interners.$name.borrow_mut().insert(Interned(i));
1534                 i
1535             }
1536         }
1537     }
1538 }
1539
1540 macro_rules! direct_interners {
1541     ($lt_tcx:tt, $($name:ident: $method:ident($needs_infer:expr) -> $ty:ty),+) => {
1542         $(impl<$lt_tcx> PartialEq for Interned<$lt_tcx, $ty> {
1543             fn eq(&self, other: &Self) -> bool {
1544                 self.0 == other.0
1545             }
1546         }
1547
1548         impl<$lt_tcx> Eq for Interned<$lt_tcx, $ty> {}
1549
1550         impl<$lt_tcx> Hash for Interned<$lt_tcx, $ty> {
1551             fn hash<H: Hasher>(&self, s: &mut H) {
1552                 self.0.hash(s)
1553             }
1554         }
1555
1556         intern_method!($lt_tcx, $name: $method($ty, alloc, |x| x, |x| x, $needs_infer) -> $ty);)+
1557     }
1558 }
1559
1560 pub fn keep_local<'tcx, T: ty::TypeFoldable<'tcx>>(x: &T) -> bool {
1561     x.has_type_flags(ty::TypeFlags::KEEP_IN_LOCAL_TCX)
1562 }
1563
1564 direct_interners!('tcx,
1565     region: mk_region(|r| {
1566         match r {
1567             &ty::ReVar(_) | &ty::ReSkolemized(..) => true,
1568             _ => false
1569         }
1570     }) -> RegionKind
1571 );
1572
1573 macro_rules! slice_interners {
1574     ($($field:ident: $method:ident($ty:ident)),+) => (
1575         $(intern_method!('tcx, $field: $method(&[$ty<'tcx>], alloc_slice, Deref::deref,
1576                                                |xs: &[$ty]| -> &Slice<$ty> {
1577             unsafe { mem::transmute(xs) }
1578         }, |xs: &[$ty]| xs.iter().any(keep_local)) -> Slice<$ty<'tcx>>);)+
1579     )
1580 }
1581
1582 slice_interners!(
1583     existential_predicates: _intern_existential_predicates(ExistentialPredicate),
1584     predicates: _intern_predicates(Predicate),
1585     type_list: _intern_type_list(Ty),
1586     substs: _intern_substs(Kind)
1587 );
1588
1589 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
1590     /// Create an unsafe fn ty based on a safe fn ty.
1591     pub fn safe_to_unsafe_fn_ty(self, sig: PolyFnSig<'tcx>) -> Ty<'tcx> {
1592         assert_eq!(sig.unsafety(), hir::Unsafety::Normal);
1593         self.mk_fn_ptr(sig.map_bound(|sig| ty::FnSig {
1594             unsafety: hir::Unsafety::Unsafe,
1595             ..sig
1596         }))
1597     }
1598
1599     // Interns a type/name combination, stores the resulting box in cx.interners,
1600     // and returns the box as cast to an unsafe ptr (see comments for Ty above).
1601     pub fn mk_ty(self, st: TypeVariants<'tcx>) -> Ty<'tcx> {
1602         let global_interners = if !self.is_global() {
1603             Some(&self.global_interners)
1604         } else {
1605             None
1606         };
1607         self.interners.intern_ty(st, global_interners)
1608     }
1609
1610     pub fn mk_mach_int(self, tm: ast::IntTy) -> Ty<'tcx> {
1611         match tm {
1612             ast::IntTy::Is   => self.types.isize,
1613             ast::IntTy::I8   => self.types.i8,
1614             ast::IntTy::I16  => self.types.i16,
1615             ast::IntTy::I32  => self.types.i32,
1616             ast::IntTy::I64  => self.types.i64,
1617             ast::IntTy::I128  => self.types.i128,
1618         }
1619     }
1620
1621     pub fn mk_mach_uint(self, tm: ast::UintTy) -> Ty<'tcx> {
1622         match tm {
1623             ast::UintTy::Us   => self.types.usize,
1624             ast::UintTy::U8   => self.types.u8,
1625             ast::UintTy::U16  => self.types.u16,
1626             ast::UintTy::U32  => self.types.u32,
1627             ast::UintTy::U64  => self.types.u64,
1628             ast::UintTy::U128  => self.types.u128,
1629         }
1630     }
1631
1632     pub fn mk_mach_float(self, tm: ast::FloatTy) -> Ty<'tcx> {
1633         match tm {
1634             ast::FloatTy::F32  => self.types.f32,
1635             ast::FloatTy::F64  => self.types.f64,
1636         }
1637     }
1638
1639     pub fn mk_str(self) -> Ty<'tcx> {
1640         self.mk_ty(TyStr)
1641     }
1642
1643     pub fn mk_static_str(self) -> Ty<'tcx> {
1644         self.mk_imm_ref(self.types.re_static, self.mk_str())
1645     }
1646
1647     pub fn mk_adt(self, def: &'tcx AdtDef, substs: &'tcx Substs<'tcx>) -> Ty<'tcx> {
1648         // take a copy of substs so that we own the vectors inside
1649         self.mk_ty(TyAdt(def, substs))
1650     }
1651
1652     pub fn mk_box(self, ty: Ty<'tcx>) -> Ty<'tcx> {
1653         let def_id = self.require_lang_item(lang_items::OwnedBoxLangItem);
1654         let adt_def = self.adt_def(def_id);
1655         let substs = self.mk_substs(iter::once(Kind::from(ty)));
1656         self.mk_ty(TyAdt(adt_def, substs))
1657     }
1658
1659     pub fn mk_ptr(self, tm: TypeAndMut<'tcx>) -> Ty<'tcx> {
1660         self.mk_ty(TyRawPtr(tm))
1661     }
1662
1663     pub fn mk_ref(self, r: Region<'tcx>, tm: TypeAndMut<'tcx>) -> Ty<'tcx> {
1664         self.mk_ty(TyRef(r, tm))
1665     }
1666
1667     pub fn mk_mut_ref(self, r: Region<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
1668         self.mk_ref(r, TypeAndMut {ty: ty, mutbl: hir::MutMutable})
1669     }
1670
1671     pub fn mk_imm_ref(self, r: Region<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
1672         self.mk_ref(r, TypeAndMut {ty: ty, mutbl: hir::MutImmutable})
1673     }
1674
1675     pub fn mk_mut_ptr(self, ty: Ty<'tcx>) -> Ty<'tcx> {
1676         self.mk_ptr(TypeAndMut {ty: ty, mutbl: hir::MutMutable})
1677     }
1678
1679     pub fn mk_imm_ptr(self, ty: Ty<'tcx>) -> Ty<'tcx> {
1680         self.mk_ptr(TypeAndMut {ty: ty, mutbl: hir::MutImmutable})
1681     }
1682
1683     pub fn mk_nil_ptr(self) -> Ty<'tcx> {
1684         self.mk_imm_ptr(self.mk_nil())
1685     }
1686
1687     pub fn mk_array(self, ty: Ty<'tcx>, n: usize) -> Ty<'tcx> {
1688         self.mk_ty(TyArray(ty, n))
1689     }
1690
1691     pub fn mk_slice(self, ty: Ty<'tcx>) -> Ty<'tcx> {
1692         self.mk_ty(TySlice(ty))
1693     }
1694
1695     pub fn intern_tup(self, ts: &[Ty<'tcx>], defaulted: bool) -> Ty<'tcx> {
1696         self.mk_ty(TyTuple(self.intern_type_list(ts), defaulted))
1697     }
1698
1699     pub fn mk_tup<I: InternAs<[Ty<'tcx>], Ty<'tcx>>>(self, iter: I,
1700                                                      defaulted: bool) -> I::Output {
1701         iter.intern_with(|ts| self.mk_ty(TyTuple(self.intern_type_list(ts), defaulted)))
1702     }
1703
1704     pub fn mk_nil(self) -> Ty<'tcx> {
1705         self.intern_tup(&[], false)
1706     }
1707
1708     pub fn mk_diverging_default(self) -> Ty<'tcx> {
1709         if self.sess.features.borrow().never_type {
1710             self.types.never
1711         } else {
1712             self.intern_tup(&[], true)
1713         }
1714     }
1715
1716     pub fn mk_bool(self) -> Ty<'tcx> {
1717         self.mk_ty(TyBool)
1718     }
1719
1720     pub fn mk_fn_def(self, def_id: DefId,
1721                      substs: &'tcx Substs<'tcx>) -> Ty<'tcx> {
1722         self.mk_ty(TyFnDef(def_id, substs))
1723     }
1724
1725     pub fn mk_fn_ptr(self, fty: PolyFnSig<'tcx>) -> Ty<'tcx> {
1726         self.mk_ty(TyFnPtr(fty))
1727     }
1728
1729     pub fn mk_dynamic(
1730         self,
1731         obj: ty::Binder<&'tcx Slice<ExistentialPredicate<'tcx>>>,
1732         reg: ty::Region<'tcx>
1733     ) -> Ty<'tcx> {
1734         self.mk_ty(TyDynamic(obj, reg))
1735     }
1736
1737     pub fn mk_projection(self,
1738                          item_def_id: DefId,
1739                          substs: &'tcx Substs<'tcx>)
1740         -> Ty<'tcx> {
1741             self.mk_ty(TyProjection(ProjectionTy {
1742                 item_def_id,
1743                 substs,
1744             }))
1745         }
1746
1747     pub fn mk_closure(self,
1748                       closure_id: DefId,
1749                       substs: &'tcx Substs<'tcx>)
1750         -> Ty<'tcx> {
1751         self.mk_closure_from_closure_substs(closure_id, ClosureSubsts {
1752             substs,
1753         })
1754     }
1755
1756     pub fn mk_closure_from_closure_substs(self,
1757                                           closure_id: DefId,
1758                                           closure_substs: ClosureSubsts<'tcx>)
1759                                           -> Ty<'tcx> {
1760         self.mk_ty(TyClosure(closure_id, closure_substs))
1761     }
1762
1763     pub fn mk_generator(self,
1764                         id: DefId,
1765                         closure_substs: ClosureSubsts<'tcx>,
1766                         interior: GeneratorInterior<'tcx>)
1767                         -> Ty<'tcx> {
1768         self.mk_ty(TyGenerator(id, closure_substs, interior))
1769     }
1770
1771     pub fn mk_var(self, v: TyVid) -> Ty<'tcx> {
1772         self.mk_infer(TyVar(v))
1773     }
1774
1775     pub fn mk_int_var(self, v: IntVid) -> Ty<'tcx> {
1776         self.mk_infer(IntVar(v))
1777     }
1778
1779     pub fn mk_float_var(self, v: FloatVid) -> Ty<'tcx> {
1780         self.mk_infer(FloatVar(v))
1781     }
1782
1783     pub fn mk_infer(self, it: InferTy) -> Ty<'tcx> {
1784         self.mk_ty(TyInfer(it))
1785     }
1786
1787     pub fn mk_param(self,
1788                     index: u32,
1789                     name: Name) -> Ty<'tcx> {
1790         self.mk_ty(TyParam(ParamTy { idx: index, name: name }))
1791     }
1792
1793     pub fn mk_self_type(self) -> Ty<'tcx> {
1794         self.mk_param(0, keywords::SelfType.name())
1795     }
1796
1797     pub fn mk_param_from_def(self, def: &ty::TypeParameterDef) -> Ty<'tcx> {
1798         self.mk_param(def.index, def.name)
1799     }
1800
1801     pub fn mk_anon(self, def_id: DefId, substs: &'tcx Substs<'tcx>) -> Ty<'tcx> {
1802         self.mk_ty(TyAnon(def_id, substs))
1803     }
1804
1805     pub fn intern_existential_predicates(self, eps: &[ExistentialPredicate<'tcx>])
1806         -> &'tcx Slice<ExistentialPredicate<'tcx>> {
1807         assert!(!eps.is_empty());
1808         assert!(eps.windows(2).all(|w| w[0].cmp(self, &w[1]) != Ordering::Greater));
1809         self._intern_existential_predicates(eps)
1810     }
1811
1812     pub fn intern_predicates(self, preds: &[Predicate<'tcx>])
1813         -> &'tcx Slice<Predicate<'tcx>> {
1814         // FIXME consider asking the input slice to be sorted to avoid
1815         // re-interning permutations, in which case that would be asserted
1816         // here.
1817         if preds.len() == 0 {
1818             // The macro-generated method below asserts we don't intern an empty slice.
1819             Slice::empty()
1820         } else {
1821             self._intern_predicates(preds)
1822         }
1823     }
1824
1825     pub fn intern_type_list(self, ts: &[Ty<'tcx>]) -> &'tcx Slice<Ty<'tcx>> {
1826         if ts.len() == 0 {
1827             Slice::empty()
1828         } else {
1829             self._intern_type_list(ts)
1830         }
1831     }
1832
1833     pub fn intern_substs(self, ts: &[Kind<'tcx>]) -> &'tcx Slice<Kind<'tcx>> {
1834         if ts.len() == 0 {
1835             Slice::empty()
1836         } else {
1837             self._intern_substs(ts)
1838         }
1839     }
1840
1841     pub fn mk_fn_sig<I>(self,
1842                         inputs: I,
1843                         output: I::Item,
1844                         variadic: bool,
1845                         unsafety: hir::Unsafety,
1846                         abi: abi::Abi)
1847         -> <I::Item as InternIteratorElement<Ty<'tcx>, ty::FnSig<'tcx>>>::Output
1848         where I: Iterator,
1849               I::Item: InternIteratorElement<Ty<'tcx>, ty::FnSig<'tcx>>
1850     {
1851         inputs.chain(iter::once(output)).intern_with(|xs| ty::FnSig {
1852             inputs_and_output: self.intern_type_list(xs),
1853             variadic, unsafety, abi
1854         })
1855     }
1856
1857     pub fn mk_existential_predicates<I: InternAs<[ExistentialPredicate<'tcx>],
1858                                      &'tcx Slice<ExistentialPredicate<'tcx>>>>(self, iter: I)
1859                                      -> I::Output {
1860         iter.intern_with(|xs| self.intern_existential_predicates(xs))
1861     }
1862
1863     pub fn mk_predicates<I: InternAs<[Predicate<'tcx>],
1864                                      &'tcx Slice<Predicate<'tcx>>>>(self, iter: I)
1865                                      -> I::Output {
1866         iter.intern_with(|xs| self.intern_predicates(xs))
1867     }
1868
1869     pub fn mk_type_list<I: InternAs<[Ty<'tcx>],
1870                         &'tcx Slice<Ty<'tcx>>>>(self, iter: I) -> I::Output {
1871         iter.intern_with(|xs| self.intern_type_list(xs))
1872     }
1873
1874     pub fn mk_substs<I: InternAs<[Kind<'tcx>],
1875                      &'tcx Slice<Kind<'tcx>>>>(self, iter: I) -> I::Output {
1876         iter.intern_with(|xs| self.intern_substs(xs))
1877     }
1878
1879     pub fn mk_substs_trait(self,
1880                      s: Ty<'tcx>,
1881                      t: &[Ty<'tcx>])
1882                     -> &'tcx Substs<'tcx>
1883     {
1884         self.mk_substs(iter::once(s).chain(t.into_iter().cloned()).map(Kind::from))
1885     }
1886
1887     pub fn lint_node<S: Into<MultiSpan>>(self,
1888                                          lint: &'static Lint,
1889                                          id: NodeId,
1890                                          span: S,
1891                                          msg: &str) {
1892         self.struct_span_lint_node(lint, id, span.into(), msg).emit()
1893     }
1894
1895     pub fn lint_node_note<S: Into<MultiSpan>>(self,
1896                                               lint: &'static Lint,
1897                                               id: NodeId,
1898                                               span: S,
1899                                               msg: &str,
1900                                               note: &str) {
1901         let mut err = self.struct_span_lint_node(lint, id, span.into(), msg);
1902         err.note(note);
1903         err.emit()
1904     }
1905
1906     pub fn lint_level_at_node(self, lint: &'static Lint, mut id: NodeId)
1907         -> (lint::Level, lint::LintSource)
1908     {
1909         // Right now we insert a `with_ignore` node in the dep graph here to
1910         // ignore the fact that `lint_levels` below depends on the entire crate.
1911         // For now this'll prevent false positives of recompiling too much when
1912         // anything changes.
1913         //
1914         // Once red/green incremental compilation lands we should be able to
1915         // remove this because while the crate changes often the lint level map
1916         // will change rarely.
1917         self.dep_graph.with_ignore(|| {
1918             let sets = self.lint_levels(LOCAL_CRATE);
1919             loop {
1920                 let hir_id = self.hir.definitions().node_to_hir_id(id);
1921                 if let Some(pair) = sets.level_and_source(lint, hir_id) {
1922                     return pair
1923                 }
1924                 let next = self.hir.get_parent_node(id);
1925                 if next == id {
1926                     bug!("lint traversal reached the root of the crate");
1927                 }
1928                 id = next;
1929             }
1930         })
1931     }
1932
1933     pub fn struct_span_lint_node<S: Into<MultiSpan>>(self,
1934                                                      lint: &'static Lint,
1935                                                      id: NodeId,
1936                                                      span: S,
1937                                                      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, Some(span.into()), msg)
1942     }
1943
1944     pub fn struct_lint_node(self, lint: &'static Lint, id: NodeId, msg: &str)
1945         -> DiagnosticBuilder<'tcx>
1946     {
1947         let (level, src) = self.lint_level_at_node(lint, id);
1948         lint::struct_lint_level(self.sess, lint, level, src, None, msg)
1949     }
1950 }
1951
1952 pub trait InternAs<T: ?Sized, R> {
1953     type Output;
1954     fn intern_with<F>(self, f: F) -> Self::Output
1955         where F: FnOnce(&T) -> R;
1956 }
1957
1958 impl<I, T, R, E> InternAs<[T], R> for I
1959     where E: InternIteratorElement<T, R>,
1960           I: Iterator<Item=E> {
1961     type Output = E::Output;
1962     fn intern_with<F>(self, f: F) -> Self::Output
1963         where F: FnOnce(&[T]) -> R {
1964         E::intern_with(self, f)
1965     }
1966 }
1967
1968 pub trait InternIteratorElement<T, R>: Sized {
1969     type Output;
1970     fn intern_with<I: Iterator<Item=Self>, F: FnOnce(&[T]) -> R>(iter: I, f: F) -> Self::Output;
1971 }
1972
1973 impl<T, R> InternIteratorElement<T, R> for T {
1974     type Output = R;
1975     fn intern_with<I: Iterator<Item=Self>, F: FnOnce(&[T]) -> R>(iter: I, f: F) -> Self::Output {
1976         f(&iter.collect::<AccumulateVec<[_; 8]>>())
1977     }
1978 }
1979
1980 impl<'a, T, R> InternIteratorElement<T, R> for &'a T
1981     where T: Clone + 'a
1982 {
1983     type Output = R;
1984     fn intern_with<I: Iterator<Item=Self>, F: FnOnce(&[T]) -> R>(iter: I, f: F) -> Self::Output {
1985         f(&iter.cloned().collect::<AccumulateVec<[_; 8]>>())
1986     }
1987 }
1988
1989 impl<T, R, E> InternIteratorElement<T, R> for Result<T, E> {
1990     type Output = Result<R, E>;
1991     fn intern_with<I: Iterator<Item=Self>, F: FnOnce(&[T]) -> R>(iter: I, f: F) -> Self::Output {
1992         Ok(f(&iter.collect::<Result<AccumulateVec<[_; 8]>, _>>()?))
1993     }
1994 }