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