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