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