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