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