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