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