]> git.lizzy.rs Git - rust.git/blob - src/librustc/ty/context.rs
ac7a72e66655f8b8549fccff325f206ec6fce3aa
[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 session::Session;
15 use lint;
16 use middle;
17 use hir::TraitMap;
18 use hir::def::{Def, ExportMap};
19 use hir::def_id::{CrateNum, DefId, LOCAL_CRATE};
20 use hir::map as hir_map;
21 use hir::map::DisambiguatedDefPathData;
22 use middle::free_region::FreeRegionMap;
23 use middle::lang_items;
24 use middle::region::RegionMaps;
25 use middle::resolve_lifetime;
26 use middle::stability;
27 use mir::Mir;
28 use ty::subst::{Kind, Substs};
29 use ty::ReprOptions;
30 use traits;
31 use ty::{self, TraitRef, Ty, TypeAndMut};
32 use ty::{TyS, TypeVariants, Slice};
33 use ty::{AdtKind, AdtDef, ClosureSubsts, Region};
34 use hir::FreevarMap;
35 use ty::{PolyFnSig, InferTy, ParamTy, ProjectionTy, ExistentialPredicate};
36 use ty::{TyVar, TyVid, IntVar, IntVid, FloatVar, FloatVid};
37 use ty::TypeVariants::*;
38 use ty::layout::{Layout, TargetDataLayout};
39 use ty::inhabitedness::DefIdForest;
40 use ty::maps;
41 use util::nodemap::{NodeMap, NodeSet, DefIdMap, DefIdSet};
42 use util::nodemap::{FxHashMap, FxHashSet};
43 use rustc_data_structures::accumulate_vec::AccumulateVec;
44
45 use arena::{TypedArena, DroplessArena};
46 use rustc_data_structures::indexed_vec::IndexVec;
47 use std::borrow::Borrow;
48 use std::cell::{Cell, RefCell};
49 use std::hash::{Hash, Hasher};
50 use std::mem;
51 use std::ops::Deref;
52 use std::iter;
53 use std::cmp::Ordering;
54 use syntax::abi;
55 use syntax::ast::{self, Name, NodeId};
56 use syntax::attr;
57 use syntax::symbol::{Symbol, keywords};
58
59 use hir;
60
61 /// Internal storage
62 pub struct GlobalArenas<'tcx> {
63     // internings
64     layout: TypedArena<Layout>,
65
66     // references
67     generics: TypedArena<ty::Generics>,
68     trait_def: TypedArena<ty::TraitDef>,
69     adt_def: TypedArena<ty::AdtDef>,
70     mir: TypedArena<RefCell<Mir<'tcx>>>,
71     tables: TypedArena<ty::TypeckTables<'tcx>>,
72 }
73
74 impl<'tcx> GlobalArenas<'tcx> {
75     pub fn new() -> GlobalArenas<'tcx> {
76         GlobalArenas {
77             layout: TypedArena::new(),
78             generics: TypedArena::new(),
79             trait_def: TypedArena::new(),
80             adt_def: TypedArena::new(),
81             mir: TypedArena::new(),
82             tables: TypedArena::new(),
83         }
84     }
85 }
86
87 pub struct CtxtInterners<'tcx> {
88     /// The arena that types, regions, etc are allocated from
89     arena: &'tcx DroplessArena,
90
91     /// Specifically use a speedy hash algorithm for these hash sets,
92     /// they're accessed quite often.
93     type_: RefCell<FxHashSet<Interned<'tcx, TyS<'tcx>>>>,
94     type_list: RefCell<FxHashSet<Interned<'tcx, Slice<Ty<'tcx>>>>>,
95     substs: RefCell<FxHashSet<Interned<'tcx, Substs<'tcx>>>>,
96     region: RefCell<FxHashSet<Interned<'tcx, Region>>>,
97     existential_predicates: RefCell<FxHashSet<Interned<'tcx, Slice<ExistentialPredicate<'tcx>>>>>,
98 }
99
100 impl<'gcx: 'tcx, 'tcx> CtxtInterners<'tcx> {
101     fn new(arena: &'tcx DroplessArena) -> CtxtInterners<'tcx> {
102         CtxtInterners {
103             arena: arena,
104             type_: RefCell::new(FxHashSet()),
105             type_list: RefCell::new(FxHashSet()),
106             substs: RefCell::new(FxHashSet()),
107             region: RefCell::new(FxHashSet()),
108             existential_predicates: RefCell::new(FxHashSet()),
109         }
110     }
111
112     /// Intern a type. global_interners is Some only if this is
113     /// a local interner and global_interners is its counterpart.
114     fn intern_ty(&self, st: TypeVariants<'tcx>,
115                  global_interners: Option<&CtxtInterners<'gcx>>)
116                  -> Ty<'tcx> {
117         let ty = {
118             let mut interner = self.type_.borrow_mut();
119             let global_interner = global_interners.map(|interners| {
120                 interners.type_.borrow_mut()
121             });
122             if let Some(&Interned(ty)) = interner.get(&st) {
123                 return ty;
124             }
125             if let Some(ref interner) = global_interner {
126                 if let Some(&Interned(ty)) = interner.get(&st) {
127                     return ty;
128                 }
129             }
130
131             let flags = super::flags::FlagComputation::for_sty(&st);
132             let ty_struct = TyS {
133                 sty: st,
134                 flags: Cell::new(flags.flags),
135                 region_depth: flags.depth,
136             };
137
138             // HACK(eddyb) Depend on flags being accurate to
139             // determine that all contents are in the global tcx.
140             // See comments on Lift for why we can't use that.
141             if !flags.flags.intersects(ty::TypeFlags::KEEP_IN_LOCAL_TCX) {
142                 if let Some(interner) = global_interners {
143                     let ty_struct: TyS<'gcx> = unsafe {
144                         mem::transmute(ty_struct)
145                     };
146                     let ty: Ty<'gcx> = interner.arena.alloc(ty_struct);
147                     global_interner.unwrap().insert(Interned(ty));
148                     return ty;
149                 }
150             } else {
151                 // Make sure we don't end up with inference
152                 // types/regions in the global tcx.
153                 if global_interners.is_none() {
154                     drop(interner);
155                     bug!("Attempted to intern `{:?}` which contains \
156                           inference types/regions in the global type context",
157                          &ty_struct);
158                 }
159             }
160
161             // Don't be &mut TyS.
162             let ty: Ty<'tcx> = self.arena.alloc(ty_struct);
163             interner.insert(Interned(ty));
164             ty
165         };
166
167         debug!("Interned type: {:?} Pointer: {:?}",
168             ty, ty as *const TyS);
169         ty
170     }
171
172 }
173
174 pub struct CommonTypes<'tcx> {
175     pub bool: Ty<'tcx>,
176     pub char: Ty<'tcx>,
177     pub isize: Ty<'tcx>,
178     pub i8: Ty<'tcx>,
179     pub i16: Ty<'tcx>,
180     pub i32: Ty<'tcx>,
181     pub i64: Ty<'tcx>,
182     pub i128: Ty<'tcx>,
183     pub usize: Ty<'tcx>,
184     pub u8: Ty<'tcx>,
185     pub u16: Ty<'tcx>,
186     pub u32: Ty<'tcx>,
187     pub u64: Ty<'tcx>,
188     pub u128: Ty<'tcx>,
189     pub f32: Ty<'tcx>,
190     pub f64: Ty<'tcx>,
191     pub never: Ty<'tcx>,
192     pub err: Ty<'tcx>,
193
194     pub re_empty: &'tcx Region,
195     pub re_static: &'tcx Region,
196     pub re_erased: &'tcx Region,
197 }
198
199 #[derive(RustcEncodable, RustcDecodable)]
200 pub struct TypeckTables<'tcx> {
201     /// Resolved definitions for `<T>::X` associated paths.
202     pub type_relative_path_defs: NodeMap<Def>,
203
204     /// Stores the types for various nodes in the AST.  Note that this table
205     /// is not guaranteed to be populated until after typeck.  See
206     /// typeck::check::fn_ctxt for details.
207     pub node_types: NodeMap<Ty<'tcx>>,
208
209     /// Stores the type parameters which were substituted to obtain the type
210     /// of this node.  This only applies to nodes that refer to entities
211     /// parameterized by type parameters, such as generic fns, types, or
212     /// other items.
213     pub item_substs: NodeMap<ty::ItemSubsts<'tcx>>,
214
215     pub adjustments: NodeMap<ty::adjustment::Adjustment<'tcx>>,
216
217     pub method_map: ty::MethodMap<'tcx>,
218
219     /// Borrows
220     pub upvar_capture_map: ty::UpvarCaptureMap<'tcx>,
221
222     /// Records the type of each closure.
223     pub closure_tys: NodeMap<ty::PolyFnSig<'tcx>>,
224
225     /// Records the kind of each closure.
226     pub closure_kinds: NodeMap<ty::ClosureKind>,
227
228     /// For each fn, records the "liberated" types of its arguments
229     /// and return type. Liberated means that all bound regions
230     /// (including late-bound regions) are replaced with free
231     /// equivalents. This table is not used in trans (since regions
232     /// are erased there) and hence is not serialized to metadata.
233     pub liberated_fn_sigs: NodeMap<ty::FnSig<'tcx>>,
234
235     /// For each FRU expression, record the normalized types of the fields
236     /// of the struct - this is needed because it is non-trivial to
237     /// normalize while preserving regions. This table is used only in
238     /// MIR construction and hence is not serialized to metadata.
239     pub fru_field_types: NodeMap<Vec<Ty<'tcx>>>,
240
241     /// Maps a cast expression to its kind. This is keyed on the
242     /// *from* expression of the cast, not the cast itself.
243     pub cast_kinds: NodeMap<ty::cast::CastKind>,
244
245     /// Lints for the body of this fn generated by typeck.
246     pub lints: lint::LintTable,
247
248     /// Set of trait imports actually used in the method resolution.
249     /// This is used for warning unused imports.
250     pub used_trait_imports: DefIdSet,
251
252     /// If any errors occurred while type-checking this body,
253     /// this field will be set to `true`.
254     pub tainted_by_errors: bool,
255
256     /// Stores the free-region relationships that were deduced from
257     /// its where clauses and parameter types. These are then
258     /// read-again by borrowck.
259     pub free_region_map: FreeRegionMap,
260 }
261
262 impl<'tcx> TypeckTables<'tcx> {
263     pub fn empty() -> TypeckTables<'tcx> {
264         TypeckTables {
265             type_relative_path_defs: NodeMap(),
266             node_types: FxHashMap(),
267             item_substs: NodeMap(),
268             adjustments: NodeMap(),
269             method_map: FxHashMap(),
270             upvar_capture_map: FxHashMap(),
271             closure_tys: NodeMap(),
272             closure_kinds: NodeMap(),
273             liberated_fn_sigs: NodeMap(),
274             fru_field_types: NodeMap(),
275             cast_kinds: NodeMap(),
276             lints: lint::LintTable::new(),
277             used_trait_imports: DefIdSet(),
278             tainted_by_errors: false,
279             free_region_map: FreeRegionMap::new(),
280         }
281     }
282
283     /// Returns the final resolution of a `QPath` in an `Expr` or `Pat` node.
284     pub fn qpath_def(&self, qpath: &hir::QPath, id: NodeId) -> Def {
285         match *qpath {
286             hir::QPath::Resolved(_, ref path) => path.def,
287             hir::QPath::TypeRelative(..) => {
288                 self.type_relative_path_defs.get(&id).cloned().unwrap_or(Def::Err)
289             }
290         }
291     }
292
293     pub fn node_id_to_type(&self, id: NodeId) -> Ty<'tcx> {
294         match self.node_id_to_type_opt(id) {
295             Some(ty) => ty,
296             None => {
297                 bug!("node_id_to_type: no type for node `{}`",
298                      tls::with(|tcx| tcx.hir.node_to_string(id)))
299             }
300         }
301     }
302
303     pub fn node_id_to_type_opt(&self, id: NodeId) -> Option<Ty<'tcx>> {
304         self.node_types.get(&id).cloned()
305     }
306
307     pub fn node_id_item_substs(&self, id: NodeId) -> Option<&'tcx Substs<'tcx>> {
308         self.item_substs.get(&id).map(|ts| ts.substs)
309     }
310
311     // Returns the type of a pattern as a monotype. Like @expr_ty, this function
312     // doesn't provide type parameter substitutions.
313     pub fn pat_ty(&self, pat: &hir::Pat) -> Ty<'tcx> {
314         self.node_id_to_type(pat.id)
315     }
316
317     pub fn pat_ty_opt(&self, pat: &hir::Pat) -> Option<Ty<'tcx>> {
318         self.node_id_to_type_opt(pat.id)
319     }
320
321     // Returns the type of an expression as a monotype.
322     //
323     // NB (1): This is the PRE-ADJUSTMENT TYPE for the expression.  That is, in
324     // some cases, we insert `Adjustment` annotations such as auto-deref or
325     // auto-ref.  The type returned by this function does not consider such
326     // adjustments.  See `expr_ty_adjusted()` instead.
327     //
328     // NB (2): This type doesn't provide type parameter substitutions; e.g. if you
329     // ask for the type of "id" in "id(3)", it will return "fn(&isize) -> isize"
330     // instead of "fn(ty) -> T with T = isize".
331     pub fn expr_ty(&self, expr: &hir::Expr) -> Ty<'tcx> {
332         self.node_id_to_type(expr.id)
333     }
334
335     pub fn expr_ty_opt(&self, expr: &hir::Expr) -> Option<Ty<'tcx>> {
336         self.node_id_to_type_opt(expr.id)
337     }
338
339     /// Returns the type of `expr`, considering any `Adjustment`
340     /// entry recorded for that expression.
341     pub fn expr_ty_adjusted(&self, expr: &hir::Expr) -> Ty<'tcx> {
342         self.adjustments.get(&expr.id)
343             .map_or_else(|| self.expr_ty(expr), |adj| adj.target)
344     }
345
346     pub fn expr_ty_adjusted_opt(&self, expr: &hir::Expr) -> Option<Ty<'tcx>> {
347         self.adjustments.get(&expr.id)
348             .map(|adj| adj.target).or_else(|| self.expr_ty_opt(expr))
349     }
350
351     pub fn is_method_call(&self, expr_id: NodeId) -> bool {
352         self.method_map.contains_key(&ty::MethodCall::expr(expr_id))
353     }
354
355     pub fn is_overloaded_autoderef(&self, expr_id: NodeId, autoderefs: u32) -> bool {
356         self.method_map.contains_key(&ty::MethodCall::autoderef(expr_id, autoderefs))
357     }
358
359     pub fn upvar_capture(&self, upvar_id: ty::UpvarId) -> Option<ty::UpvarCapture<'tcx>> {
360         Some(self.upvar_capture_map.get(&upvar_id).unwrap().clone())
361     }
362 }
363
364 impl<'tcx> CommonTypes<'tcx> {
365     fn new(interners: &CtxtInterners<'tcx>) -> CommonTypes<'tcx> {
366         let mk = |sty| interners.intern_ty(sty, None);
367         let mk_region = |r| {
368             if let Some(r) = interners.region.borrow().get(&r) {
369                 return r.0;
370             }
371             let r = interners.arena.alloc(r);
372             interners.region.borrow_mut().insert(Interned(r));
373             &*r
374         };
375         CommonTypes {
376             bool: mk(TyBool),
377             char: mk(TyChar),
378             never: mk(TyNever),
379             err: mk(TyError),
380             isize: mk(TyInt(ast::IntTy::Is)),
381             i8: mk(TyInt(ast::IntTy::I8)),
382             i16: mk(TyInt(ast::IntTy::I16)),
383             i32: mk(TyInt(ast::IntTy::I32)),
384             i64: mk(TyInt(ast::IntTy::I64)),
385             i128: mk(TyInt(ast::IntTy::I128)),
386             usize: mk(TyUint(ast::UintTy::Us)),
387             u8: mk(TyUint(ast::UintTy::U8)),
388             u16: mk(TyUint(ast::UintTy::U16)),
389             u32: mk(TyUint(ast::UintTy::U32)),
390             u64: mk(TyUint(ast::UintTy::U64)),
391             u128: mk(TyUint(ast::UintTy::U128)),
392             f32: mk(TyFloat(ast::FloatTy::F32)),
393             f64: mk(TyFloat(ast::FloatTy::F64)),
394
395             re_empty: mk_region(Region::ReEmpty),
396             re_static: mk_region(Region::ReStatic),
397             re_erased: mk_region(Region::ReErased),
398         }
399     }
400 }
401
402 /// The data structure to keep track of all the information that typechecker
403 /// generates so that so that it can be reused and doesn't have to be redone
404 /// later on.
405 #[derive(Copy, Clone)]
406 pub struct TyCtxt<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
407     gcx: &'a GlobalCtxt<'gcx>,
408     interners: &'a CtxtInterners<'tcx>
409 }
410
411 impl<'a, 'gcx, 'tcx> Deref for TyCtxt<'a, 'gcx, 'tcx> {
412     type Target = &'a GlobalCtxt<'gcx>;
413     fn deref(&self) -> &Self::Target {
414         &self.gcx
415     }
416 }
417
418 pub struct GlobalCtxt<'tcx> {
419     global_arenas: &'tcx GlobalArenas<'tcx>,
420     global_interners: CtxtInterners<'tcx>,
421
422     pub sess: &'tcx Session,
423
424     pub specializes_cache: RefCell<traits::SpecializesCache>,
425
426     pub trans_trait_caches: traits::trans::TransTraitCaches<'tcx>,
427
428     pub dep_graph: DepGraph,
429
430     /// Common types, pre-interned for your convenience.
431     pub types: CommonTypes<'tcx>,
432
433     /// Map indicating what traits are in scope for places where this
434     /// is relevant; generated by resolve.
435     pub trait_map: TraitMap,
436
437     /// Export map produced by name resolution.
438     pub export_map: ExportMap,
439
440     pub named_region_map: resolve_lifetime::NamedRegionMap,
441
442     pub region_maps: RegionMaps,
443
444     pub hir: hir_map::Map<'tcx>,
445     pub maps: maps::Maps<'tcx>,
446
447     // Records the free variables refrenced by every closure
448     // expression. Do not track deps for this, just recompute it from
449     // scratch every time.
450     pub freevars: RefCell<FreevarMap>,
451
452     pub maybe_unused_trait_imports: NodeSet,
453
454     // Internal cache for metadata decoding. No need to track deps on this.
455     pub rcache: RefCell<FxHashMap<ty::CReaderCacheKey, Ty<'tcx>>>,
456
457     // FIXME dep tracking -- should be harmless enough
458     pub normalized_cache: RefCell<FxHashMap<Ty<'tcx>, Ty<'tcx>>>,
459
460     pub inhabitedness_cache: RefCell<FxHashMap<Ty<'tcx>, DefIdForest>>,
461
462     pub lang_items: middle::lang_items::LanguageItems,
463
464     /// True if the variance has been computed yet; false otherwise.
465     pub variance_computed: Cell<bool>,
466
467     /// Set of used unsafe nodes (functions or blocks). Unsafe nodes not
468     /// present in this set can be warned about.
469     pub used_unsafe: RefCell<NodeSet>,
470
471     /// Set of nodes which mark locals as mutable which end up getting used at
472     /// some point. Local variable definitions not in this set can be warned
473     /// about.
474     pub used_mut_nodes: RefCell<NodeSet>,
475
476     /// The set of external nominal types whose implementations have been read.
477     /// This is used for lazy resolution of methods.
478     pub populated_external_types: RefCell<DefIdSet>,
479
480     /// The set of external primitive types whose implementations have been read.
481     /// FIXME(arielb1): why is this separate from populated_external_types?
482     pub populated_external_primitive_impls: RefCell<DefIdSet>,
483
484     /// Maps any item's def-id to its stability index.
485     pub stability: RefCell<stability::Index<'tcx>>,
486
487     /// Caches the results of trait selection. This cache is used
488     /// for things that do not have to do with the parameters in scope.
489     pub selection_cache: traits::SelectionCache<'tcx>,
490
491     /// Caches the results of trait evaluation. This cache is used
492     /// for things that do not have to do with the parameters in scope.
493     /// Merge this with `selection_cache`?
494     pub evaluation_cache: traits::EvaluationCache<'tcx>,
495
496     /// A set of predicates that have been fulfilled *somewhere*.
497     /// This is used to avoid duplicate work. Predicates are only
498     /// added to this set when they mention only "global" names
499     /// (i.e., no type or lifetime parameters).
500     pub fulfilled_predicates: RefCell<traits::GlobalFulfilledPredicates<'tcx>>,
501
502     /// Maps Expr NodeId's to `true` iff `&expr` can have 'static lifetime.
503     pub rvalue_promotable_to_static: RefCell<NodeMap<bool>>,
504
505     /// Maps Fn items to a collection of fragment infos.
506     ///
507     /// The main goal is to identify data (each of which may be moved
508     /// or assigned) whose subparts are not moved nor assigned
509     /// (i.e. their state is *unfragmented*) and corresponding ast
510     /// nodes where the path to that data is moved or assigned.
511     ///
512     /// In the long term, unfragmented values will have their
513     /// destructor entirely driven by a single stack-local drop-flag,
514     /// and their parents, the collections of the unfragmented values
515     /// (or more simply, "fragmented values"), are mapped to the
516     /// corresponding collections of stack-local drop-flags.
517     ///
518     /// (However, in the short term that is not the case; e.g. some
519     /// unfragmented paths still need to be zeroed, namely when they
520     /// reference parent data from an outer scope that was not
521     /// entirely moved, and therefore that needs to be zeroed so that
522     /// we do not get double-drop when we hit the end of the parent
523     /// scope.)
524     ///
525     /// Also: currently the table solely holds keys for node-ids of
526     /// unfragmented values (see `FragmentInfo` enum definition), but
527     /// longer-term we will need to also store mappings from
528     /// fragmented data to the set of unfragmented pieces that
529     /// constitute it.
530     pub fragment_infos: RefCell<DefIdMap<Vec<ty::FragmentInfo>>>,
531
532     /// The definite name of the current crate after taking into account
533     /// attributes, commandline parameters, etc.
534     pub crate_name: Symbol,
535
536     /// Data layout specification for the current target.
537     pub data_layout: TargetDataLayout,
538
539     /// Cache for layouts computed from types.
540     pub layout_cache: RefCell<FxHashMap<Ty<'tcx>, &'tcx Layout>>,
541
542     /// Used to prevent layout from recursing too deeply.
543     pub layout_depth: Cell<usize>,
544
545     /// Map from function to the `#[derive]` mode that it's defining. Only used
546     /// by `proc-macro` crates.
547     pub derive_macros: RefCell<NodeMap<Symbol>>,
548
549     stability_interner: RefCell<FxHashSet<&'tcx attr::Stability>>,
550
551     layout_interner: RefCell<FxHashSet<&'tcx Layout>>,
552
553     /// A vector of every trait accessible in the whole crate
554     /// (i.e. including those from subcrates). This is used only for
555     /// error reporting, and so is lazily initialised and generally
556     /// shouldn't taint the common path (hence the RefCell).
557     pub all_traits: RefCell<Option<Vec<DefId>>>,
558
559     /// HIR Ty -> Ty lowering cache.
560     pub ast_ty_to_ty_cache: RefCell<NodeMap<Ty<'tcx>>>,
561 }
562
563 impl<'tcx> GlobalCtxt<'tcx> {
564     /// Get the global TyCtxt.
565     pub fn global_tcx<'a>(&'a self) -> TyCtxt<'a, 'tcx, 'tcx> {
566         TyCtxt {
567             gcx: self,
568             interners: &self.global_interners
569         }
570     }
571 }
572
573 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
574     pub fn crate_name(self, cnum: CrateNum) -> Symbol {
575         if cnum == LOCAL_CRATE {
576             self.crate_name
577         } else {
578             self.sess.cstore.crate_name(cnum)
579         }
580     }
581
582     pub fn original_crate_name(self, cnum: CrateNum) -> Symbol {
583         if cnum == LOCAL_CRATE {
584             self.crate_name.clone()
585         } else {
586             self.sess.cstore.original_crate_name(cnum)
587         }
588     }
589
590     pub fn crate_disambiguator(self, cnum: CrateNum) -> Symbol {
591         if cnum == LOCAL_CRATE {
592             self.sess.local_crate_disambiguator()
593         } else {
594             self.sess.cstore.crate_disambiguator(cnum)
595         }
596     }
597
598     pub fn retrace_path(self,
599                         krate: CrateNum,
600                         path_data: &[DisambiguatedDefPathData])
601                         -> Option<DefId> {
602         debug!("retrace_path(path={:?}, krate={:?})", path_data, self.crate_name(krate));
603
604         if krate == LOCAL_CRATE {
605             self.hir
606                 .definitions()
607                 .def_path_table()
608                 .retrace_path(path_data)
609                 .map(|def_index| DefId { krate: krate, index: def_index })
610         } else {
611             self.sess.cstore.retrace_path(krate, path_data)
612         }
613     }
614
615     pub fn alloc_generics(self, generics: ty::Generics) -> &'gcx ty::Generics {
616         self.global_arenas.generics.alloc(generics)
617     }
618
619     pub fn alloc_mir(self, mir: Mir<'gcx>) -> &'gcx RefCell<Mir<'gcx>> {
620         self.global_arenas.mir.alloc(RefCell::new(mir))
621     }
622
623     pub fn alloc_tables(self, tables: ty::TypeckTables<'gcx>) -> &'gcx ty::TypeckTables<'gcx> {
624         self.global_arenas.tables.alloc(tables)
625     }
626
627     pub fn alloc_trait_def(self, def: ty::TraitDef) -> &'gcx ty::TraitDef {
628         self.global_arenas.trait_def.alloc(def)
629     }
630
631     pub fn alloc_adt_def(self,
632                          did: DefId,
633                          kind: AdtKind,
634                          variants: Vec<ty::VariantDef>,
635                          repr: ReprOptions)
636                          -> &'gcx ty::AdtDef {
637         let def = ty::AdtDef::new(self, did, kind, variants, repr);
638         self.global_arenas.adt_def.alloc(def)
639     }
640
641     pub fn intern_stability(self, stab: attr::Stability) -> &'gcx attr::Stability {
642         if let Some(st) = self.stability_interner.borrow().get(&stab) {
643             return st;
644         }
645
646         let interned = self.global_interners.arena.alloc(stab);
647         if let Some(prev) = self.stability_interner.borrow_mut().replace(interned) {
648             bug!("Tried to overwrite interned Stability: {:?}", prev)
649         }
650         interned
651     }
652
653     pub fn intern_layout(self, layout: Layout) -> &'gcx Layout {
654         if let Some(layout) = self.layout_interner.borrow().get(&layout) {
655             return layout;
656         }
657
658         let interned = self.global_arenas.layout.alloc(layout);
659         if let Some(prev) = self.layout_interner.borrow_mut().replace(interned) {
660             bug!("Tried to overwrite interned Layout: {:?}", prev)
661         }
662         interned
663     }
664
665     pub fn lift<T: ?Sized + Lift<'tcx>>(self, value: &T) -> Option<T::Lifted> {
666         value.lift_to_tcx(self)
667     }
668
669     /// Like lift, but only tries in the global tcx.
670     pub fn lift_to_global<T: ?Sized + Lift<'gcx>>(self, value: &T) -> Option<T::Lifted> {
671         value.lift_to_tcx(self.global_tcx())
672     }
673
674     /// Returns true if self is the same as self.global_tcx().
675     fn is_global(self) -> bool {
676         let local = self.interners as *const _;
677         let global = &self.global_interners as *const _;
678         local as usize == global as usize
679     }
680
681     /// Create a type context and call the closure with a `TyCtxt` reference
682     /// to the context. The closure enforces that the type context and any interned
683     /// value (types, substs, etc.) can only be used while `ty::tls` has a valid
684     /// reference to the context, to allow formatting values that need it.
685     pub fn create_and_enter<F, R>(s: &'tcx Session,
686                                   local_providers: ty::maps::Providers<'tcx>,
687                                   extern_providers: ty::maps::Providers<'tcx>,
688                                   arenas: &'tcx GlobalArenas<'tcx>,
689                                   arena: &'tcx DroplessArena,
690                                   resolutions: ty::Resolutions,
691                                   named_region_map: resolve_lifetime::NamedRegionMap,
692                                   hir: hir_map::Map<'tcx>,
693                                   region_maps: RegionMaps,
694                                   lang_items: middle::lang_items::LanguageItems,
695                                   stability: stability::Index<'tcx>,
696                                   crate_name: &str,
697                                   f: F) -> R
698                                   where F: for<'b> FnOnce(TyCtxt<'b, 'tcx, 'tcx>) -> R
699     {
700         let data_layout = TargetDataLayout::parse(s);
701         let interners = CtxtInterners::new(arena);
702         let common_types = CommonTypes::new(&interners);
703         let dep_graph = hir.dep_graph.clone();
704         let fulfilled_predicates = traits::GlobalFulfilledPredicates::new(dep_graph.clone());
705         let max_cnum = s.cstore.crates().iter().map(|c| c.as_usize()).max().unwrap_or(0);
706         let mut providers = IndexVec::from_elem_n(extern_providers, max_cnum + 1);
707         providers[LOCAL_CRATE] = local_providers;
708         tls::enter_global(GlobalCtxt {
709             sess: s,
710             trans_trait_caches: traits::trans::TransTraitCaches::new(dep_graph.clone()),
711             specializes_cache: RefCell::new(traits::SpecializesCache::new()),
712             global_arenas: arenas,
713             global_interners: interners,
714             dep_graph: dep_graph.clone(),
715             types: common_types,
716             named_region_map: named_region_map,
717             region_maps: region_maps,
718             variance_computed: Cell::new(false),
719             trait_map: resolutions.trait_map,
720             export_map: resolutions.export_map,
721             fulfilled_predicates: RefCell::new(fulfilled_predicates),
722             hir: hir,
723             maps: maps::Maps::new(dep_graph, providers),
724             freevars: RefCell::new(resolutions.freevars),
725             maybe_unused_trait_imports: resolutions.maybe_unused_trait_imports,
726             rcache: RefCell::new(FxHashMap()),
727             normalized_cache: RefCell::new(FxHashMap()),
728             inhabitedness_cache: RefCell::new(FxHashMap()),
729             lang_items: lang_items,
730             used_unsafe: RefCell::new(NodeSet()),
731             used_mut_nodes: RefCell::new(NodeSet()),
732             populated_external_types: RefCell::new(DefIdSet()),
733             populated_external_primitive_impls: RefCell::new(DefIdSet()),
734             stability: RefCell::new(stability),
735             selection_cache: traits::SelectionCache::new(),
736             evaluation_cache: traits::EvaluationCache::new(),
737             rvalue_promotable_to_static: RefCell::new(NodeMap()),
738             fragment_infos: RefCell::new(DefIdMap()),
739             crate_name: Symbol::intern(crate_name),
740             data_layout: data_layout,
741             layout_cache: RefCell::new(FxHashMap()),
742             layout_interner: RefCell::new(FxHashSet()),
743             layout_depth: Cell::new(0),
744             derive_macros: RefCell::new(NodeMap()),
745             stability_interner: RefCell::new(FxHashSet()),
746             all_traits: RefCell::new(None),
747             ast_ty_to_ty_cache: RefCell::new(NodeMap()),
748        }, f)
749     }
750
751     pub fn consider_optimizing<T: Fn() -> String>(&self, msg: T) -> bool {
752         let cname = self.crate_name(LOCAL_CRATE).as_str();
753         self.sess.consider_optimizing(&cname, msg)
754     }
755 }
756
757 impl<'gcx: 'tcx, 'tcx> GlobalCtxt<'gcx> {
758     /// Call the closure with a local `TyCtxt` using the given arena.
759     pub fn enter_local<F, R>(&self, arena: &'tcx DroplessArena, f: F) -> R
760         where F: for<'a> FnOnce(TyCtxt<'a, 'gcx, 'tcx>) -> R
761     {
762         let interners = CtxtInterners::new(arena);
763         tls::enter(self, &interners, f)
764     }
765 }
766
767 /// A trait implemented for all X<'a> types which can be safely and
768 /// efficiently converted to X<'tcx> as long as they are part of the
769 /// provided TyCtxt<'tcx>.
770 /// This can be done, for example, for Ty<'tcx> or &'tcx Substs<'tcx>
771 /// by looking them up in their respective interners.
772 ///
773 /// However, this is still not the best implementation as it does
774 /// need to compare the components, even for interned values.
775 /// It would be more efficient if TypedArena provided a way to
776 /// determine whether the address is in the allocated range.
777 ///
778 /// None is returned if the value or one of the components is not part
779 /// of the provided context.
780 /// For Ty, None can be returned if either the type interner doesn't
781 /// contain the TypeVariants key or if the address of the interned
782 /// pointer differs. The latter case is possible if a primitive type,
783 /// e.g. `()` or `u8`, was interned in a different context.
784 pub trait Lift<'tcx> {
785     type Lifted;
786     fn lift_to_tcx<'a, 'gcx>(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Option<Self::Lifted>;
787 }
788
789 impl<'a, 'tcx> Lift<'tcx> for Ty<'a> {
790     type Lifted = Ty<'tcx>;
791     fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>) -> Option<Ty<'tcx>> {
792         if tcx.interners.arena.in_arena(*self as *const _) {
793             return Some(unsafe { mem::transmute(*self) });
794         }
795         // Also try in the global tcx if we're not that.
796         if !tcx.is_global() {
797             self.lift_to_tcx(tcx.global_tcx())
798         } else {
799             None
800         }
801     }
802 }
803
804 impl<'a, 'tcx> Lift<'tcx> for &'a Substs<'a> {
805     type Lifted = &'tcx Substs<'tcx>;
806     fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>) -> Option<&'tcx Substs<'tcx>> {
807         if self.len() == 0 {
808             return Some(Slice::empty());
809         }
810         if tcx.interners.arena.in_arena(&self[..] as *const _) {
811             return Some(unsafe { mem::transmute(*self) });
812         }
813         // Also try in the global tcx if we're not that.
814         if !tcx.is_global() {
815             self.lift_to_tcx(tcx.global_tcx())
816         } else {
817             None
818         }
819     }
820 }
821
822 impl<'a, 'tcx> Lift<'tcx> for &'a Region {
823     type Lifted = &'tcx Region;
824     fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>) -> Option<&'tcx Region> {
825         if tcx.interners.arena.in_arena(*self as *const _) {
826             return Some(unsafe { mem::transmute(*self) });
827         }
828         // Also try in the global tcx if we're not that.
829         if !tcx.is_global() {
830             self.lift_to_tcx(tcx.global_tcx())
831         } else {
832             None
833         }
834     }
835 }
836
837 impl<'a, 'tcx> Lift<'tcx> for &'a Slice<Ty<'a>> {
838     type Lifted = &'tcx Slice<Ty<'tcx>>;
839     fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>)
840                              -> Option<&'tcx Slice<Ty<'tcx>>> {
841         if self.len() == 0 {
842             return Some(Slice::empty());
843         }
844         if tcx.interners.arena.in_arena(*self as *const _) {
845             return Some(unsafe { mem::transmute(*self) });
846         }
847         // Also try in the global tcx if we're not that.
848         if !tcx.is_global() {
849             self.lift_to_tcx(tcx.global_tcx())
850         } else {
851             None
852         }
853     }
854 }
855
856 impl<'a, 'tcx> Lift<'tcx> for &'a Slice<ExistentialPredicate<'a>> {
857     type Lifted = &'tcx Slice<ExistentialPredicate<'tcx>>;
858     fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>)
859         -> Option<&'tcx Slice<ExistentialPredicate<'tcx>>> {
860         if self.is_empty() {
861             return Some(Slice::empty());
862         }
863         if tcx.interners.arena.in_arena(*self as *const _) {
864             return Some(unsafe { mem::transmute(*self) });
865         }
866         // Also try in the global tcx if we're not that.
867         if !tcx.is_global() {
868             self.lift_to_tcx(tcx.global_tcx())
869         } else {
870             None
871         }
872     }
873 }
874
875 pub mod tls {
876     use super::{CtxtInterners, GlobalCtxt, TyCtxt};
877
878     use std::cell::Cell;
879     use std::fmt;
880     use syntax_pos;
881
882     /// Marker types used for the scoped TLS slot.
883     /// The type context cannot be used directly because the scoped TLS
884     /// in libstd doesn't allow types generic over lifetimes.
885     enum ThreadLocalGlobalCtxt {}
886     enum ThreadLocalInterners {}
887
888     thread_local! {
889         static TLS_TCX: Cell<Option<(*const ThreadLocalGlobalCtxt,
890                                      *const ThreadLocalInterners)>> = Cell::new(None)
891     }
892
893     fn span_debug(span: syntax_pos::Span, f: &mut fmt::Formatter) -> fmt::Result {
894         with(|tcx| {
895             write!(f, "{}", tcx.sess.codemap().span_to_string(span))
896         })
897     }
898
899     pub fn enter_global<'gcx, F, R>(gcx: GlobalCtxt<'gcx>, f: F) -> R
900         where F: for<'a> FnOnce(TyCtxt<'a, 'gcx, 'gcx>) -> R
901     {
902         syntax_pos::SPAN_DEBUG.with(|span_dbg| {
903             let original_span_debug = span_dbg.get();
904             span_dbg.set(span_debug);
905             let result = enter(&gcx, &gcx.global_interners, f);
906             span_dbg.set(original_span_debug);
907             result
908         })
909     }
910
911     pub fn enter<'a, 'gcx: 'tcx, 'tcx, F, R>(gcx: &'a GlobalCtxt<'gcx>,
912                                              interners: &'a CtxtInterners<'tcx>,
913                                              f: F) -> R
914         where F: FnOnce(TyCtxt<'a, 'gcx, 'tcx>) -> R
915     {
916         let gcx_ptr = gcx as *const _ as *const ThreadLocalGlobalCtxt;
917         let interners_ptr = interners as *const _ as *const ThreadLocalInterners;
918         TLS_TCX.with(|tls| {
919             let prev = tls.get();
920             tls.set(Some((gcx_ptr, interners_ptr)));
921             let ret = f(TyCtxt {
922                 gcx: gcx,
923                 interners: interners
924             });
925             tls.set(prev);
926             ret
927         })
928     }
929
930     pub fn with<F, R>(f: F) -> R
931         where F: for<'a, 'gcx, 'tcx> FnOnce(TyCtxt<'a, 'gcx, 'tcx>) -> R
932     {
933         TLS_TCX.with(|tcx| {
934             let (gcx, interners) = tcx.get().unwrap();
935             let gcx = unsafe { &*(gcx as *const GlobalCtxt) };
936             let interners = unsafe { &*(interners as *const CtxtInterners) };
937             f(TyCtxt {
938                 gcx: gcx,
939                 interners: interners
940             })
941         })
942     }
943
944     pub fn with_opt<F, R>(f: F) -> R
945         where F: for<'a, 'gcx, 'tcx> FnOnce(Option<TyCtxt<'a, 'gcx, 'tcx>>) -> R
946     {
947         if TLS_TCX.with(|tcx| tcx.get().is_some()) {
948             with(|v| f(Some(v)))
949         } else {
950             f(None)
951         }
952     }
953 }
954
955 macro_rules! sty_debug_print {
956     ($ctxt: expr, $($variant: ident),*) => {{
957         // curious inner module to allow variant names to be used as
958         // variable names.
959         #[allow(non_snake_case)]
960         mod inner {
961             use ty::{self, TyCtxt};
962             use ty::context::Interned;
963
964             #[derive(Copy, Clone)]
965             struct DebugStat {
966                 total: usize,
967                 region_infer: usize,
968                 ty_infer: usize,
969                 both_infer: usize,
970             }
971
972             pub fn go(tcx: TyCtxt) {
973                 let mut total = DebugStat {
974                     total: 0,
975                     region_infer: 0, ty_infer: 0, both_infer: 0,
976                 };
977                 $(let mut $variant = total;)*
978
979
980                 for &Interned(t) in tcx.interners.type_.borrow().iter() {
981                     let variant = match t.sty {
982                         ty::TyBool | ty::TyChar | ty::TyInt(..) | ty::TyUint(..) |
983                             ty::TyFloat(..) | ty::TyStr | ty::TyNever => continue,
984                         ty::TyError => /* unimportant */ continue,
985                         $(ty::$variant(..) => &mut $variant,)*
986                     };
987                     let region = t.flags.get().intersects(ty::TypeFlags::HAS_RE_INFER);
988                     let ty = t.flags.get().intersects(ty::TypeFlags::HAS_TY_INFER);
989
990                     variant.total += 1;
991                     total.total += 1;
992                     if region { total.region_infer += 1; variant.region_infer += 1 }
993                     if ty { total.ty_infer += 1; variant.ty_infer += 1 }
994                     if region && ty { total.both_infer += 1; variant.both_infer += 1 }
995                 }
996                 println!("Ty interner             total           ty region  both");
997                 $(println!("    {:18}: {uses:6} {usespc:4.1}%, \
998 {ty:4.1}% {region:5.1}% {both:4.1}%",
999                            stringify!($variant),
1000                            uses = $variant.total,
1001                            usespc = $variant.total as f64 * 100.0 / total.total as f64,
1002                            ty = $variant.ty_infer as f64 * 100.0  / total.total as f64,
1003                            region = $variant.region_infer as f64 * 100.0  / total.total as f64,
1004                            both = $variant.both_infer as f64 * 100.0  / total.total as f64);
1005                   )*
1006                 println!("                  total {uses:6}        \
1007 {ty:4.1}% {region:5.1}% {both:4.1}%",
1008                          uses = total.total,
1009                          ty = total.ty_infer as f64 * 100.0  / total.total as f64,
1010                          region = total.region_infer as f64 * 100.0  / total.total as f64,
1011                          both = total.both_infer as f64 * 100.0  / total.total as f64)
1012             }
1013         }
1014
1015         inner::go($ctxt)
1016     }}
1017 }
1018
1019 impl<'a, 'tcx> TyCtxt<'a, 'tcx, 'tcx> {
1020     pub fn print_debug_stats(self) {
1021         sty_debug_print!(
1022             self,
1023             TyAdt, TyArray, TySlice, TyRawPtr, TyRef, TyFnDef, TyFnPtr,
1024             TyDynamic, TyClosure, TyTuple, TyParam, TyInfer, TyProjection, TyAnon);
1025
1026         println!("Substs interner: #{}", self.interners.substs.borrow().len());
1027         println!("Region interner: #{}", self.interners.region.borrow().len());
1028         println!("Stability interner: #{}", self.stability_interner.borrow().len());
1029         println!("Layout interner: #{}", self.layout_interner.borrow().len());
1030     }
1031 }
1032
1033
1034 /// An entry in an interner.
1035 struct Interned<'tcx, T: 'tcx+?Sized>(&'tcx T);
1036
1037 // NB: An Interned<Ty> compares and hashes as a sty.
1038 impl<'tcx> PartialEq for Interned<'tcx, TyS<'tcx>> {
1039     fn eq(&self, other: &Interned<'tcx, TyS<'tcx>>) -> bool {
1040         self.0.sty == other.0.sty
1041     }
1042 }
1043
1044 impl<'tcx> Eq for Interned<'tcx, TyS<'tcx>> {}
1045
1046 impl<'tcx> Hash for Interned<'tcx, TyS<'tcx>> {
1047     fn hash<H: Hasher>(&self, s: &mut H) {
1048         self.0.sty.hash(s)
1049     }
1050 }
1051
1052 impl<'tcx: 'lcx, 'lcx> Borrow<TypeVariants<'lcx>> for Interned<'tcx, TyS<'tcx>> {
1053     fn borrow<'a>(&'a self) -> &'a TypeVariants<'lcx> {
1054         &self.0.sty
1055     }
1056 }
1057
1058 // NB: An Interned<Slice<T>> compares and hashes as its elements.
1059 impl<'tcx, T: PartialEq> PartialEq for Interned<'tcx, Slice<T>> {
1060     fn eq(&self, other: &Interned<'tcx, Slice<T>>) -> bool {
1061         self.0[..] == other.0[..]
1062     }
1063 }
1064
1065 impl<'tcx, T: Eq> Eq for Interned<'tcx, Slice<T>> {}
1066
1067 impl<'tcx, T: Hash> Hash for Interned<'tcx, Slice<T>> {
1068     fn hash<H: Hasher>(&self, s: &mut H) {
1069         self.0[..].hash(s)
1070     }
1071 }
1072
1073 impl<'tcx: 'lcx, 'lcx> Borrow<[Ty<'lcx>]> for Interned<'tcx, Slice<Ty<'tcx>>> {
1074     fn borrow<'a>(&'a self) -> &'a [Ty<'lcx>] {
1075         &self.0[..]
1076     }
1077 }
1078
1079 impl<'tcx: 'lcx, 'lcx> Borrow<[Kind<'lcx>]> for Interned<'tcx, Substs<'tcx>> {
1080     fn borrow<'a>(&'a self) -> &'a [Kind<'lcx>] {
1081         &self.0[..]
1082     }
1083 }
1084
1085 impl<'tcx> Borrow<Region> for Interned<'tcx, Region> {
1086     fn borrow<'a>(&'a self) -> &'a Region {
1087         self.0
1088     }
1089 }
1090
1091 impl<'tcx: 'lcx, 'lcx> Borrow<[ExistentialPredicate<'lcx>]>
1092     for Interned<'tcx, Slice<ExistentialPredicate<'tcx>>> {
1093     fn borrow<'a>(&'a self) -> &'a [ExistentialPredicate<'lcx>] {
1094         &self.0[..]
1095     }
1096 }
1097
1098 macro_rules! intern_method {
1099     ($lt_tcx:tt, $name:ident: $method:ident($alloc:ty,
1100                                             $alloc_method:ident,
1101                                             $alloc_to_key:expr,
1102                                             $alloc_to_ret:expr,
1103                                             $needs_infer:expr) -> $ty:ty) => {
1104         impl<'a, 'gcx, $lt_tcx> TyCtxt<'a, 'gcx, $lt_tcx> {
1105             pub fn $method(self, v: $alloc) -> &$lt_tcx $ty {
1106                 {
1107                     let key = ($alloc_to_key)(&v);
1108                     if let Some(i) = self.interners.$name.borrow().get(key) {
1109                         return i.0;
1110                     }
1111                     if !self.is_global() {
1112                         if let Some(i) = self.global_interners.$name.borrow().get(key) {
1113                             return i.0;
1114                         }
1115                     }
1116                 }
1117
1118                 // HACK(eddyb) Depend on flags being accurate to
1119                 // determine that all contents are in the global tcx.
1120                 // See comments on Lift for why we can't use that.
1121                 if !($needs_infer)(&v) {
1122                     if !self.is_global() {
1123                         let v = unsafe {
1124                             mem::transmute(v)
1125                         };
1126                         let i = ($alloc_to_ret)(self.global_interners.arena.$alloc_method(v));
1127                         self.global_interners.$name.borrow_mut().insert(Interned(i));
1128                         return i;
1129                     }
1130                 } else {
1131                     // Make sure we don't end up with inference
1132                     // types/regions in the global tcx.
1133                     if self.is_global() {
1134                         bug!("Attempted to intern `{:?}` which contains \
1135                               inference types/regions in the global type context",
1136                              v);
1137                     }
1138                 }
1139
1140                 let i = ($alloc_to_ret)(self.interners.arena.$alloc_method(v));
1141                 self.interners.$name.borrow_mut().insert(Interned(i));
1142                 i
1143             }
1144         }
1145     }
1146 }
1147
1148 macro_rules! direct_interners {
1149     ($lt_tcx:tt, $($name:ident: $method:ident($needs_infer:expr) -> $ty:ty),+) => {
1150         $(impl<$lt_tcx> PartialEq for Interned<$lt_tcx, $ty> {
1151             fn eq(&self, other: &Self) -> bool {
1152                 self.0 == other.0
1153             }
1154         }
1155
1156         impl<$lt_tcx> Eq for Interned<$lt_tcx, $ty> {}
1157
1158         impl<$lt_tcx> Hash for Interned<$lt_tcx, $ty> {
1159             fn hash<H: Hasher>(&self, s: &mut H) {
1160                 self.0.hash(s)
1161             }
1162         }
1163
1164         intern_method!($lt_tcx, $name: $method($ty, alloc, |x| x, |x| x, $needs_infer) -> $ty);)+
1165     }
1166 }
1167
1168 fn keep_local<'tcx, T: ty::TypeFoldable<'tcx>>(x: &T) -> bool {
1169     x.has_type_flags(ty::TypeFlags::KEEP_IN_LOCAL_TCX)
1170 }
1171
1172 direct_interners!('tcx,
1173     region: mk_region(|r| {
1174         match r {
1175             &ty::ReVar(_) | &ty::ReSkolemized(..) => true,
1176             _ => false
1177         }
1178     }) -> Region
1179 );
1180
1181 macro_rules! slice_interners {
1182     ($($field:ident: $method:ident($ty:ident)),+) => (
1183         $(intern_method!('tcx, $field: $method(&[$ty<'tcx>], alloc_slice, Deref::deref,
1184                                                |xs: &[$ty]| -> &Slice<$ty> {
1185             unsafe { mem::transmute(xs) }
1186         }, |xs: &[$ty]| xs.iter().any(keep_local)) -> Slice<$ty<'tcx>>);)+
1187     )
1188 }
1189
1190 slice_interners!(
1191     existential_predicates: _intern_existential_predicates(ExistentialPredicate),
1192     type_list: _intern_type_list(Ty),
1193     substs: _intern_substs(Kind)
1194 );
1195
1196 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
1197     /// Create an unsafe fn ty based on a safe fn ty.
1198     pub fn safe_to_unsafe_fn_ty(self, sig: PolyFnSig<'tcx>) -> Ty<'tcx> {
1199         assert_eq!(sig.unsafety(), hir::Unsafety::Normal);
1200         self.mk_fn_ptr(sig.map_bound(|sig| ty::FnSig {
1201             unsafety: hir::Unsafety::Unsafe,
1202             ..sig
1203         }))
1204     }
1205
1206     // Interns a type/name combination, stores the resulting box in cx.interners,
1207     // and returns the box as cast to an unsafe ptr (see comments for Ty above).
1208     pub fn mk_ty(self, st: TypeVariants<'tcx>) -> Ty<'tcx> {
1209         let global_interners = if !self.is_global() {
1210             Some(&self.global_interners)
1211         } else {
1212             None
1213         };
1214         self.interners.intern_ty(st, global_interners)
1215     }
1216
1217     pub fn mk_mach_int(self, tm: ast::IntTy) -> Ty<'tcx> {
1218         match tm {
1219             ast::IntTy::Is   => self.types.isize,
1220             ast::IntTy::I8   => self.types.i8,
1221             ast::IntTy::I16  => self.types.i16,
1222             ast::IntTy::I32  => self.types.i32,
1223             ast::IntTy::I64  => self.types.i64,
1224             ast::IntTy::I128  => self.types.i128,
1225         }
1226     }
1227
1228     pub fn mk_mach_uint(self, tm: ast::UintTy) -> Ty<'tcx> {
1229         match tm {
1230             ast::UintTy::Us   => self.types.usize,
1231             ast::UintTy::U8   => self.types.u8,
1232             ast::UintTy::U16  => self.types.u16,
1233             ast::UintTy::U32  => self.types.u32,
1234             ast::UintTy::U64  => self.types.u64,
1235             ast::UintTy::U128  => self.types.u128,
1236         }
1237     }
1238
1239     pub fn mk_mach_float(self, tm: ast::FloatTy) -> Ty<'tcx> {
1240         match tm {
1241             ast::FloatTy::F32  => self.types.f32,
1242             ast::FloatTy::F64  => self.types.f64,
1243         }
1244     }
1245
1246     pub fn mk_str(self) -> Ty<'tcx> {
1247         self.mk_ty(TyStr)
1248     }
1249
1250     pub fn mk_static_str(self) -> Ty<'tcx> {
1251         self.mk_imm_ref(self.types.re_static, self.mk_str())
1252     }
1253
1254     pub fn mk_adt(self, def: &'tcx AdtDef, substs: &'tcx Substs<'tcx>) -> Ty<'tcx> {
1255         // take a copy of substs so that we own the vectors inside
1256         self.mk_ty(TyAdt(def, substs))
1257     }
1258
1259     pub fn mk_box(self, ty: Ty<'tcx>) -> Ty<'tcx> {
1260         let def_id = self.require_lang_item(lang_items::OwnedBoxLangItem);
1261         let adt_def = self.adt_def(def_id);
1262         let substs = self.mk_substs(iter::once(Kind::from(ty)));
1263         self.mk_ty(TyAdt(adt_def, substs))
1264     }
1265
1266     pub fn mk_ptr(self, tm: TypeAndMut<'tcx>) -> Ty<'tcx> {
1267         self.mk_ty(TyRawPtr(tm))
1268     }
1269
1270     pub fn mk_ref(self, r: &'tcx Region, tm: TypeAndMut<'tcx>) -> Ty<'tcx> {
1271         self.mk_ty(TyRef(r, tm))
1272     }
1273
1274     pub fn mk_mut_ref(self, r: &'tcx Region, ty: Ty<'tcx>) -> Ty<'tcx> {
1275         self.mk_ref(r, TypeAndMut {ty: ty, mutbl: hir::MutMutable})
1276     }
1277
1278     pub fn mk_imm_ref(self, r: &'tcx Region, ty: Ty<'tcx>) -> Ty<'tcx> {
1279         self.mk_ref(r, TypeAndMut {ty: ty, mutbl: hir::MutImmutable})
1280     }
1281
1282     pub fn mk_mut_ptr(self, ty: Ty<'tcx>) -> Ty<'tcx> {
1283         self.mk_ptr(TypeAndMut {ty: ty, mutbl: hir::MutMutable})
1284     }
1285
1286     pub fn mk_imm_ptr(self, ty: Ty<'tcx>) -> Ty<'tcx> {
1287         self.mk_ptr(TypeAndMut {ty: ty, mutbl: hir::MutImmutable})
1288     }
1289
1290     pub fn mk_nil_ptr(self) -> Ty<'tcx> {
1291         self.mk_imm_ptr(self.mk_nil())
1292     }
1293
1294     pub fn mk_array(self, ty: Ty<'tcx>, n: usize) -> Ty<'tcx> {
1295         self.mk_ty(TyArray(ty, n))
1296     }
1297
1298     pub fn mk_slice(self, ty: Ty<'tcx>) -> Ty<'tcx> {
1299         self.mk_ty(TySlice(ty))
1300     }
1301
1302     pub fn intern_tup(self, ts: &[Ty<'tcx>], defaulted: bool) -> Ty<'tcx> {
1303         self.mk_ty(TyTuple(self.intern_type_list(ts), defaulted))
1304     }
1305
1306     pub fn mk_tup<I: InternAs<[Ty<'tcx>], Ty<'tcx>>>(self, iter: I,
1307                                                      defaulted: bool) -> I::Output {
1308         iter.intern_with(|ts| self.mk_ty(TyTuple(self.intern_type_list(ts), defaulted)))
1309     }
1310
1311     pub fn mk_nil(self) -> Ty<'tcx> {
1312         self.intern_tup(&[], false)
1313     }
1314
1315     pub fn mk_diverging_default(self) -> Ty<'tcx> {
1316         if self.sess.features.borrow().never_type {
1317             self.types.never
1318         } else {
1319             self.intern_tup(&[], true)
1320         }
1321     }
1322
1323     pub fn mk_bool(self) -> Ty<'tcx> {
1324         self.mk_ty(TyBool)
1325     }
1326
1327     pub fn mk_fn_def(self, def_id: DefId,
1328                      substs: &'tcx Substs<'tcx>,
1329                      fty: PolyFnSig<'tcx>) -> Ty<'tcx> {
1330         self.mk_ty(TyFnDef(def_id, substs, fty))
1331     }
1332
1333     pub fn mk_fn_ptr(self, fty: PolyFnSig<'tcx>) -> Ty<'tcx> {
1334         self.mk_ty(TyFnPtr(fty))
1335     }
1336
1337     pub fn mk_dynamic(
1338         self,
1339         obj: ty::Binder<&'tcx Slice<ExistentialPredicate<'tcx>>>,
1340         reg: &'tcx ty::Region
1341     ) -> Ty<'tcx> {
1342         self.mk_ty(TyDynamic(obj, reg))
1343     }
1344
1345     pub fn mk_projection(self,
1346                          trait_ref: TraitRef<'tcx>,
1347                          item_name: Name)
1348         -> Ty<'tcx> {
1349             // take a copy of substs so that we own the vectors inside
1350             let inner = ProjectionTy { trait_ref: trait_ref, item_name: item_name };
1351             self.mk_ty(TyProjection(inner))
1352         }
1353
1354     pub fn mk_closure(self,
1355                       closure_id: DefId,
1356                       substs: &'tcx Substs<'tcx>)
1357         -> Ty<'tcx> {
1358         self.mk_closure_from_closure_substs(closure_id, ClosureSubsts {
1359             substs: substs
1360         })
1361     }
1362
1363     pub fn mk_closure_from_closure_substs(self,
1364                                           closure_id: DefId,
1365                                           closure_substs: ClosureSubsts<'tcx>)
1366                                           -> Ty<'tcx> {
1367         self.mk_ty(TyClosure(closure_id, closure_substs))
1368     }
1369
1370     pub fn mk_var(self, v: TyVid) -> Ty<'tcx> {
1371         self.mk_infer(TyVar(v))
1372     }
1373
1374     pub fn mk_int_var(self, v: IntVid) -> Ty<'tcx> {
1375         self.mk_infer(IntVar(v))
1376     }
1377
1378     pub fn mk_float_var(self, v: FloatVid) -> Ty<'tcx> {
1379         self.mk_infer(FloatVar(v))
1380     }
1381
1382     pub fn mk_infer(self, it: InferTy) -> Ty<'tcx> {
1383         self.mk_ty(TyInfer(it))
1384     }
1385
1386     pub fn mk_param(self,
1387                     index: u32,
1388                     name: Name) -> Ty<'tcx> {
1389         self.mk_ty(TyParam(ParamTy { idx: index, name: name }))
1390     }
1391
1392     pub fn mk_self_type(self) -> Ty<'tcx> {
1393         self.mk_param(0, keywords::SelfType.name())
1394     }
1395
1396     pub fn mk_param_from_def(self, def: &ty::TypeParameterDef) -> Ty<'tcx> {
1397         self.mk_param(def.index, def.name)
1398     }
1399
1400     pub fn mk_anon(self, def_id: DefId, substs: &'tcx Substs<'tcx>) -> Ty<'tcx> {
1401         self.mk_ty(TyAnon(def_id, substs))
1402     }
1403
1404     pub fn intern_existential_predicates(self, eps: &[ExistentialPredicate<'tcx>])
1405         -> &'tcx Slice<ExistentialPredicate<'tcx>> {
1406         assert!(!eps.is_empty());
1407         assert!(eps.windows(2).all(|w| w[0].cmp(self, &w[1]) != Ordering::Greater));
1408         self._intern_existential_predicates(eps)
1409     }
1410
1411     pub fn intern_type_list(self, ts: &[Ty<'tcx>]) -> &'tcx Slice<Ty<'tcx>> {
1412         if ts.len() == 0 {
1413             Slice::empty()
1414         } else {
1415             self._intern_type_list(ts)
1416         }
1417     }
1418
1419     pub fn intern_substs(self, ts: &[Kind<'tcx>]) -> &'tcx Slice<Kind<'tcx>> {
1420         if ts.len() == 0 {
1421             Slice::empty()
1422         } else {
1423             self._intern_substs(ts)
1424         }
1425     }
1426
1427     pub fn mk_fn_sig<I>(self,
1428                         inputs: I,
1429                         output: I::Item,
1430                         variadic: bool,
1431                         unsafety: hir::Unsafety,
1432                         abi: abi::Abi)
1433         -> <I::Item as InternIteratorElement<Ty<'tcx>, ty::FnSig<'tcx>>>::Output
1434         where I: Iterator,
1435               I::Item: InternIteratorElement<Ty<'tcx>, ty::FnSig<'tcx>>
1436     {
1437         inputs.chain(iter::once(output)).intern_with(|xs| ty::FnSig {
1438             inputs_and_output: self.intern_type_list(xs),
1439             variadic, unsafety, abi
1440         })
1441     }
1442
1443     pub fn mk_existential_predicates<I: InternAs<[ExistentialPredicate<'tcx>],
1444                                      &'tcx Slice<ExistentialPredicate<'tcx>>>>(self, iter: I)
1445                                      -> I::Output {
1446         iter.intern_with(|xs| self.intern_existential_predicates(xs))
1447     }
1448
1449     pub fn mk_type_list<I: InternAs<[Ty<'tcx>],
1450                         &'tcx Slice<Ty<'tcx>>>>(self, iter: I) -> I::Output {
1451         iter.intern_with(|xs| self.intern_type_list(xs))
1452     }
1453
1454     pub fn mk_substs<I: InternAs<[Kind<'tcx>],
1455                      &'tcx Slice<Kind<'tcx>>>>(self, iter: I) -> I::Output {
1456         iter.intern_with(|xs| self.intern_substs(xs))
1457     }
1458
1459     pub fn mk_substs_trait(self,
1460                      s: Ty<'tcx>,
1461                      t: &[Ty<'tcx>])
1462                     -> &'tcx Substs<'tcx>
1463     {
1464         self.mk_substs(iter::once(s).chain(t.into_iter().cloned()).map(Kind::from))
1465     }
1466 }
1467
1468 pub trait InternAs<T: ?Sized, R> {
1469     type Output;
1470     fn intern_with<F>(self, F) -> Self::Output
1471         where F: FnOnce(&T) -> R;
1472 }
1473
1474 impl<I, T, R, E> InternAs<[T], R> for I
1475     where E: InternIteratorElement<T, R>,
1476           I: Iterator<Item=E> {
1477     type Output = E::Output;
1478     fn intern_with<F>(self, f: F) -> Self::Output
1479         where F: FnOnce(&[T]) -> R {
1480         E::intern_with(self, f)
1481     }
1482 }
1483
1484 pub trait InternIteratorElement<T, R>: Sized {
1485     type Output;
1486     fn intern_with<I: Iterator<Item=Self>, F: FnOnce(&[T]) -> R>(iter: I, f: F) -> Self::Output;
1487 }
1488
1489 impl<T, R> InternIteratorElement<T, R> for T {
1490     type Output = R;
1491     fn intern_with<I: Iterator<Item=Self>, F: FnOnce(&[T]) -> R>(iter: I, f: F) -> Self::Output {
1492         f(&iter.collect::<AccumulateVec<[_; 8]>>())
1493     }
1494 }
1495
1496 impl<'a, T, R> InternIteratorElement<T, R> for &'a T
1497     where T: Clone + 'a
1498 {
1499     type Output = R;
1500     fn intern_with<I: Iterator<Item=Self>, F: FnOnce(&[T]) -> R>(iter: I, f: F) -> Self::Output {
1501         f(&iter.cloned().collect::<AccumulateVec<[_; 8]>>())
1502     }
1503 }
1504
1505 impl<T, R, E> InternIteratorElement<T, R> for Result<T, E> {
1506     type Output = Result<R, E>;
1507     fn intern_with<I: Iterator<Item=Self>, F: FnOnce(&[T]) -> R>(iter: I, f: F) -> Self::Output {
1508         Ok(f(&iter.collect::<Result<AccumulateVec<[_; 8]>, _>>()?))
1509     }
1510 }