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