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.
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.
11 //! type context book-keeping
13 use dep_graph::DepGraph;
14 use errors::DiagnosticBuilder;
18 use hir::def::{Def, ExportMap};
19 use hir::def_id::{CrateNum, DefId, LOCAL_CRATE};
20 use hir::map as hir_map;
21 use hir::map::DefPathHash;
22 use lint::{self, Lint};
23 use ich::{self, StableHashingContext, NodeIdHashingMode};
24 use middle::free_region::FreeRegionMap;
25 use middle::lang_items;
26 use middle::resolve_lifetime;
27 use middle::stability;
29 use mir::transform::Passes;
30 use ty::subst::{Kind, Substs};
33 use ty::{self, Ty, TypeAndMut};
34 use ty::{TyS, TypeVariants, Slice};
35 use ty::{AdtKind, AdtDef, ClosureSubsts, Region};
37 use ty::{PolyFnSig, InferTy, ParamTy, ProjectionTy, ExistentialPredicate, Predicate};
39 use ty::{TyVar, TyVid, IntVar, IntVid, FloatVar, FloatVid};
40 use ty::TypeVariants::*;
41 use ty::layout::{Layout, TargetDataLayout};
42 use ty::inhabitedness::DefIdForest;
46 use util::nodemap::{NodeMap, NodeSet, DefIdSet, ItemLocalMap};
47 use util::nodemap::{FxHashMap, FxHashSet};
48 use rustc_data_structures::accumulate_vec::AccumulateVec;
49 use rustc_data_structures::stable_hasher::{HashStable, StableHasher,
52 use arena::{TypedArena, DroplessArena};
53 use rustc_data_structures::indexed_vec::IndexVec;
54 use std::borrow::Borrow;
55 use std::cell::{Cell, RefCell};
56 use std::cmp::Ordering;
57 use std::collections::hash_map::{self, Entry};
58 use std::hash::{Hash, Hasher};
64 use syntax::ast::{self, Name, NodeId};
66 use syntax::codemap::MultiSpan;
67 use syntax::symbol::{Symbol, keywords};
73 pub struct GlobalArenas<'tcx> {
75 layout: TypedArena<Layout>,
78 generics: TypedArena<ty::Generics>,
79 trait_def: TypedArena<ty::TraitDef>,
80 adt_def: TypedArena<ty::AdtDef>,
81 steal_mir: TypedArena<Steal<Mir<'tcx>>>,
82 mir: TypedArena<Mir<'tcx>>,
83 tables: TypedArena<ty::TypeckTables<'tcx>>,
86 impl<'tcx> GlobalArenas<'tcx> {
87 pub fn new() -> GlobalArenas<'tcx> {
89 layout: TypedArena::new(),
90 generics: TypedArena::new(),
91 trait_def: TypedArena::new(),
92 adt_def: TypedArena::new(),
93 steal_mir: TypedArena::new(),
94 mir: TypedArena::new(),
95 tables: TypedArena::new(),
100 pub struct CtxtInterners<'tcx> {
101 /// The arena that types, regions, etc are allocated from
102 arena: &'tcx DroplessArena,
104 /// Specifically use a speedy hash algorithm for these hash sets,
105 /// they're accessed quite often.
106 type_: RefCell<FxHashSet<Interned<'tcx, TyS<'tcx>>>>,
107 type_list: RefCell<FxHashSet<Interned<'tcx, Slice<Ty<'tcx>>>>>,
108 substs: RefCell<FxHashSet<Interned<'tcx, Substs<'tcx>>>>,
109 region: RefCell<FxHashSet<Interned<'tcx, RegionKind>>>,
110 existential_predicates: RefCell<FxHashSet<Interned<'tcx, Slice<ExistentialPredicate<'tcx>>>>>,
111 predicates: RefCell<FxHashSet<Interned<'tcx, Slice<Predicate<'tcx>>>>>,
114 impl<'gcx: 'tcx, 'tcx> CtxtInterners<'tcx> {
115 fn new(arena: &'tcx DroplessArena) -> CtxtInterners<'tcx> {
118 type_: RefCell::new(FxHashSet()),
119 type_list: RefCell::new(FxHashSet()),
120 substs: RefCell::new(FxHashSet()),
121 region: RefCell::new(FxHashSet()),
122 existential_predicates: RefCell::new(FxHashSet()),
123 predicates: RefCell::new(FxHashSet()),
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>>)
133 let mut interner = self.type_.borrow_mut();
134 let global_interner = global_interners.map(|interners| {
135 interners.type_.borrow_mut()
137 if let Some(&Interned(ty)) = interner.get(&st) {
140 if let Some(ref interner) = global_interner {
141 if let Some(&Interned(ty)) = interner.get(&st) {
146 let flags = super::flags::FlagComputation::for_sty(&st);
147 let ty_struct = TyS {
150 region_depth: flags.depth,
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)
161 let ty: Ty<'gcx> = interner.arena.alloc(ty_struct);
162 global_interner.unwrap().insert(Interned(ty));
166 // Make sure we don't end up with inference
167 // types/regions in the global tcx.
168 if global_interners.is_none() {
170 bug!("Attempted to intern `{:?}` which contains \
171 inference types/regions in the global type context",
176 // Don't be &mut TyS.
177 let ty: Ty<'tcx> = self.arena.alloc(ty_struct);
178 interner.insert(Interned(ty));
182 debug!("Interned type: {:?} Pointer: {:?}",
183 ty, ty as *const TyS);
189 pub struct CommonTypes<'tcx> {
209 pub re_empty: Region<'tcx>,
210 pub re_static: Region<'tcx>,
211 pub re_erased: Region<'tcx>,
214 pub struct LocalTableInContext<'a, V: 'a> {
215 local_id_root: Option<DefId>,
216 data: &'a ItemLocalMap<V>
219 /// Validate that the given HirId (respectively its `local_id` part) can be
220 /// safely used as a key in the tables of a TypeckTable. For that to be
221 /// the case, the HirId must have the same `owner` as all the other IDs in
222 /// this table (signified by `local_id_root`). Otherwise the HirId
223 /// would be in a different frame of reference and using its `local_id`
224 /// would result in lookup errors, or worse, in silently wrong data being
226 fn validate_hir_id_for_typeck_tables(local_id_root: Option<DefId>,
229 if cfg!(debug_assertions) {
230 if let Some(local_id_root) = local_id_root {
231 if hir_id.owner != local_id_root.index {
232 ty::tls::with(|tcx| {
233 let node_id = tcx.hir
235 .find_node_for_hir_id(hir_id);
237 bug!("node {} with HirId::owner {:?} cannot be placed in \
238 TypeckTables with local_id_root {:?}",
239 tcx.hir.node_to_string(node_id),
240 DefId::local(hir_id.owner),
245 // We use "Null Object" TypeckTables in some of the analysis passes.
246 // These are just expected to be empty and their `local_id_root` is
247 // `None`. Therefore we cannot verify whether a given `HirId` would
248 // be a valid key for the given table. Instead we make sure that
249 // nobody tries to write to such a Null Object table.
251 bug!("access to invalid TypeckTables")
257 impl<'a, V> LocalTableInContext<'a, V> {
258 pub fn contains_key(&self, id: hir::HirId) -> bool {
259 validate_hir_id_for_typeck_tables(self.local_id_root, id, false);
260 self.data.contains_key(&id.local_id)
263 pub fn get(&self, id: hir::HirId) -> Option<&V> {
264 validate_hir_id_for_typeck_tables(self.local_id_root, id, false);
265 self.data.get(&id.local_id)
268 pub fn iter(&self) -> hash_map::Iter<hir::ItemLocalId, V> {
273 impl<'a, V> ::std::ops::Index<hir::HirId> for LocalTableInContext<'a, V> {
276 fn index(&self, key: hir::HirId) -> &V {
277 self.get(key).expect("LocalTableInContext: key not found")
281 pub struct LocalTableInContextMut<'a, V: 'a> {
282 local_id_root: Option<DefId>,
283 data: &'a mut ItemLocalMap<V>
286 impl<'a, V> LocalTableInContextMut<'a, V> {
287 pub fn get_mut(&mut self, id: hir::HirId) -> Option<&mut V> {
288 validate_hir_id_for_typeck_tables(self.local_id_root, id, true);
289 self.data.get_mut(&id.local_id)
292 pub fn entry(&mut self, id: hir::HirId) -> Entry<hir::ItemLocalId, V> {
293 validate_hir_id_for_typeck_tables(self.local_id_root, id, true);
294 self.data.entry(id.local_id)
297 pub fn insert(&mut self, id: hir::HirId, val: V) -> Option<V> {
298 validate_hir_id_for_typeck_tables(self.local_id_root, id, true);
299 self.data.insert(id.local_id, val)
302 pub fn remove(&mut self, id: hir::HirId) -> Option<V> {
303 validate_hir_id_for_typeck_tables(self.local_id_root, id, true);
304 self.data.remove(&id.local_id)
308 #[derive(RustcEncodable, RustcDecodable)]
309 pub struct TypeckTables<'tcx> {
310 /// The HirId::owner all ItemLocalIds in this table are relative to.
311 pub local_id_root: Option<DefId>,
313 /// Resolved definitions for `<T>::X` associated paths and
314 /// method calls, including those of overloaded operators.
315 type_dependent_defs: ItemLocalMap<Def>,
317 /// Stores the types for various nodes in the AST. Note that this table
318 /// is not guaranteed to be populated until after typeck. See
319 /// typeck::check::fn_ctxt for details.
320 node_types: ItemLocalMap<Ty<'tcx>>,
322 /// Stores the type parameters which were substituted to obtain the type
323 /// of this node. This only applies to nodes that refer to entities
324 /// parameterized by type parameters, such as generic fns, types, or
326 node_substs: ItemLocalMap<&'tcx Substs<'tcx>>,
328 adjustments: ItemLocalMap<Vec<ty::adjustment::Adjustment<'tcx>>>,
330 // Stores the actual binding mode for all instances of hir::BindingAnnotation.
331 pat_binding_modes: ItemLocalMap<BindingMode>,
334 pub upvar_capture_map: ty::UpvarCaptureMap<'tcx>,
336 /// Records the type of each closure.
337 closure_tys: ItemLocalMap<ty::PolyFnSig<'tcx>>,
339 /// Records the kind of each closure and the span and name of the variable
340 /// that caused the closure to be this kind.
341 closure_kinds: ItemLocalMap<(ty::ClosureKind, Option<(Span, ast::Name)>)>,
343 /// For each fn, records the "liberated" types of its arguments
344 /// and return type. Liberated means that all bound regions
345 /// (including late-bound regions) are replaced with free
346 /// equivalents. This table is not used in trans (since regions
347 /// are erased there) and hence is not serialized to metadata.
348 liberated_fn_sigs: ItemLocalMap<ty::FnSig<'tcx>>,
350 /// For each FRU expression, record the normalized types of the fields
351 /// of the struct - this is needed because it is non-trivial to
352 /// normalize while preserving regions. This table is used only in
353 /// MIR construction and hence is not serialized to metadata.
354 fru_field_types: ItemLocalMap<Vec<Ty<'tcx>>>,
356 /// Maps a cast expression to its kind. This is keyed on the
357 /// *from* expression of the cast, not the cast itself.
358 cast_kinds: ItemLocalMap<ty::cast::CastKind>,
360 /// Set of trait imports actually used in the method resolution.
361 /// This is used for warning unused imports.
362 pub used_trait_imports: DefIdSet,
364 /// If any errors occurred while type-checking this body,
365 /// this field will be set to `true`.
366 pub tainted_by_errors: bool,
368 /// Stores the free-region relationships that were deduced from
369 /// its where clauses and parameter types. These are then
370 /// read-again by borrowck.
371 pub free_region_map: FreeRegionMap<'tcx>,
374 impl<'tcx> TypeckTables<'tcx> {
375 pub fn empty(local_id_root: Option<DefId>) -> TypeckTables<'tcx> {
378 type_dependent_defs: ItemLocalMap(),
379 node_types: ItemLocalMap(),
380 node_substs: ItemLocalMap(),
381 adjustments: ItemLocalMap(),
382 pat_binding_modes: ItemLocalMap(),
383 upvar_capture_map: FxHashMap(),
384 closure_tys: ItemLocalMap(),
385 closure_kinds: ItemLocalMap(),
386 liberated_fn_sigs: ItemLocalMap(),
387 fru_field_types: ItemLocalMap(),
388 cast_kinds: ItemLocalMap(),
389 used_trait_imports: DefIdSet(),
390 tainted_by_errors: false,
391 free_region_map: FreeRegionMap::new(),
395 /// Returns the final resolution of a `QPath` in an `Expr` or `Pat` node.
396 pub fn qpath_def(&self, qpath: &hir::QPath, id: hir::HirId) -> Def {
398 hir::QPath::Resolved(_, ref path) => path.def,
399 hir::QPath::TypeRelative(..) => {
400 validate_hir_id_for_typeck_tables(self.local_id_root, id, false);
401 self.type_dependent_defs.get(&id.local_id).cloned().unwrap_or(Def::Err)
406 pub fn type_dependent_defs(&self) -> LocalTableInContext<Def> {
407 LocalTableInContext {
408 local_id_root: self.local_id_root,
409 data: &self.type_dependent_defs
413 pub fn type_dependent_defs_mut(&mut self) -> LocalTableInContextMut<Def> {
414 LocalTableInContextMut {
415 local_id_root: self.local_id_root,
416 data: &mut self.type_dependent_defs
420 pub fn node_types(&self) -> LocalTableInContext<Ty<'tcx>> {
421 LocalTableInContext {
422 local_id_root: self.local_id_root,
423 data: &self.node_types
427 pub fn node_types_mut(&mut self) -> LocalTableInContextMut<Ty<'tcx>> {
428 LocalTableInContextMut {
429 local_id_root: self.local_id_root,
430 data: &mut self.node_types
434 pub fn node_id_to_type(&self, id: hir::HirId) -> Ty<'tcx> {
435 match self.node_id_to_type_opt(id) {
438 bug!("node_id_to_type: no type for node `{}`",
440 let id = tcx.hir.definitions().find_node_for_hir_id(id);
441 tcx.hir.node_to_string(id)
447 pub fn node_id_to_type_opt(&self, id: hir::HirId) -> Option<Ty<'tcx>> {
448 validate_hir_id_for_typeck_tables(self.local_id_root, id, false);
449 self.node_types.get(&id.local_id).cloned()
452 pub fn node_substs_mut(&mut self) -> LocalTableInContextMut<&'tcx Substs<'tcx>> {
453 LocalTableInContextMut {
454 local_id_root: self.local_id_root,
455 data: &mut self.node_substs
459 pub fn node_substs(&self, id: hir::HirId) -> &'tcx Substs<'tcx> {
460 validate_hir_id_for_typeck_tables(self.local_id_root, id, false);
461 self.node_substs.get(&id.local_id).cloned().unwrap_or(Substs::empty())
464 pub fn node_substs_opt(&self, id: hir::HirId) -> Option<&'tcx Substs<'tcx>> {
465 validate_hir_id_for_typeck_tables(self.local_id_root, id, false);
466 self.node_substs.get(&id.local_id).cloned()
469 // Returns the type of a pattern as a monotype. Like @expr_ty, this function
470 // doesn't provide type parameter substitutions.
471 pub fn pat_ty(&self, pat: &hir::Pat) -> Ty<'tcx> {
472 self.node_id_to_type(pat.hir_id)
475 pub fn pat_ty_opt(&self, pat: &hir::Pat) -> Option<Ty<'tcx>> {
476 self.node_id_to_type_opt(pat.hir_id)
479 // Returns the type of an expression as a monotype.
481 // NB (1): This is the PRE-ADJUSTMENT TYPE for the expression. That is, in
482 // some cases, we insert `Adjustment` annotations such as auto-deref or
483 // auto-ref. The type returned by this function does not consider such
484 // adjustments. See `expr_ty_adjusted()` instead.
486 // NB (2): This type doesn't provide type parameter substitutions; e.g. if you
487 // ask for the type of "id" in "id(3)", it will return "fn(&isize) -> isize"
488 // instead of "fn(ty) -> T with T = isize".
489 pub fn expr_ty(&self, expr: &hir::Expr) -> Ty<'tcx> {
490 self.node_id_to_type(expr.hir_id)
493 pub fn expr_ty_opt(&self, expr: &hir::Expr) -> Option<Ty<'tcx>> {
494 self.node_id_to_type_opt(expr.hir_id)
497 pub fn adjustments(&self) -> LocalTableInContext<Vec<ty::adjustment::Adjustment<'tcx>>> {
498 LocalTableInContext {
499 local_id_root: self.local_id_root,
500 data: &self.adjustments
504 pub fn adjustments_mut(&mut self)
505 -> LocalTableInContextMut<Vec<ty::adjustment::Adjustment<'tcx>>> {
506 LocalTableInContextMut {
507 local_id_root: self.local_id_root,
508 data: &mut self.adjustments
512 pub fn expr_adjustments(&self, expr: &hir::Expr)
513 -> &[ty::adjustment::Adjustment<'tcx>] {
514 validate_hir_id_for_typeck_tables(self.local_id_root, expr.hir_id, false);
515 self.adjustments.get(&expr.hir_id.local_id).map_or(&[], |a| &a[..])
518 /// Returns the type of `expr`, considering any `Adjustment`
519 /// entry recorded for that expression.
520 pub fn expr_ty_adjusted(&self, expr: &hir::Expr) -> Ty<'tcx> {
521 self.expr_adjustments(expr)
523 .map_or_else(|| self.expr_ty(expr), |adj| adj.target)
526 pub fn expr_ty_adjusted_opt(&self, expr: &hir::Expr) -> Option<Ty<'tcx>> {
527 self.expr_adjustments(expr)
529 .map(|adj| adj.target)
530 .or_else(|| self.expr_ty_opt(expr))
533 pub fn is_method_call(&self, expr: &hir::Expr) -> bool {
534 // Only paths and method calls/overloaded operators have
535 // entries in type_dependent_defs, ignore the former here.
536 if let hir::ExprPath(_) = expr.node {
540 match self.type_dependent_defs().get(expr.hir_id) {
541 Some(&Def::Method(_)) => true,
546 pub fn pat_binding_modes(&self) -> LocalTableInContext<BindingMode> {
547 LocalTableInContext {
548 local_id_root: self.local_id_root,
549 data: &self.pat_binding_modes
553 pub fn pat_binding_modes_mut(&mut self)
554 -> LocalTableInContextMut<BindingMode> {
555 LocalTableInContextMut {
556 local_id_root: self.local_id_root,
557 data: &mut self.pat_binding_modes
561 pub fn upvar_capture(&self, upvar_id: ty::UpvarId) -> ty::UpvarCapture<'tcx> {
562 self.upvar_capture_map[&upvar_id]
565 pub fn closure_tys(&self) -> LocalTableInContext<ty::PolyFnSig<'tcx>> {
566 LocalTableInContext {
567 local_id_root: self.local_id_root,
568 data: &self.closure_tys
572 pub fn closure_tys_mut(&mut self)
573 -> LocalTableInContextMut<ty::PolyFnSig<'tcx>> {
574 LocalTableInContextMut {
575 local_id_root: self.local_id_root,
576 data: &mut self.closure_tys
580 pub fn closure_kinds(&self) -> LocalTableInContext<(ty::ClosureKind,
581 Option<(Span, ast::Name)>)> {
582 LocalTableInContext {
583 local_id_root: self.local_id_root,
584 data: &self.closure_kinds
588 pub fn closure_kinds_mut(&mut self)
589 -> LocalTableInContextMut<(ty::ClosureKind, Option<(Span, ast::Name)>)> {
590 LocalTableInContextMut {
591 local_id_root: self.local_id_root,
592 data: &mut self.closure_kinds
596 pub fn liberated_fn_sigs(&self) -> LocalTableInContext<ty::FnSig<'tcx>> {
597 LocalTableInContext {
598 local_id_root: self.local_id_root,
599 data: &self.liberated_fn_sigs
603 pub fn liberated_fn_sigs_mut(&mut self) -> LocalTableInContextMut<ty::FnSig<'tcx>> {
604 LocalTableInContextMut {
605 local_id_root: self.local_id_root,
606 data: &mut self.liberated_fn_sigs
610 pub fn fru_field_types(&self) -> LocalTableInContext<Vec<Ty<'tcx>>> {
611 LocalTableInContext {
612 local_id_root: self.local_id_root,
613 data: &self.fru_field_types
617 pub fn fru_field_types_mut(&mut self) -> LocalTableInContextMut<Vec<Ty<'tcx>>> {
618 LocalTableInContextMut {
619 local_id_root: self.local_id_root,
620 data: &mut self.fru_field_types
624 pub fn cast_kinds(&self) -> LocalTableInContext<ty::cast::CastKind> {
625 LocalTableInContext {
626 local_id_root: self.local_id_root,
627 data: &self.cast_kinds
631 pub fn cast_kinds_mut(&mut self) -> LocalTableInContextMut<ty::cast::CastKind> {
632 LocalTableInContextMut {
633 local_id_root: self.local_id_root,
634 data: &mut self.cast_kinds
639 impl<'a, 'gcx, 'tcx> HashStable<StableHashingContext<'a, 'gcx, 'tcx>> for TypeckTables<'gcx> {
640 fn hash_stable<W: StableHasherResult>(&self,
641 hcx: &mut StableHashingContext<'a, 'gcx, 'tcx>,
642 hasher: &mut StableHasher<W>) {
643 let ty::TypeckTables {
645 ref type_dependent_defs,
649 ref pat_binding_modes,
650 ref upvar_capture_map,
653 ref liberated_fn_sigs,
658 ref used_trait_imports,
663 hcx.with_node_id_hashing_mode(NodeIdHashingMode::HashDefPath, |hcx| {
664 ich::hash_stable_itemlocalmap(hcx, hasher, type_dependent_defs);
665 ich::hash_stable_itemlocalmap(hcx, hasher, node_types);
666 ich::hash_stable_itemlocalmap(hcx, hasher, node_substs);
667 ich::hash_stable_itemlocalmap(hcx, hasher, adjustments);
668 ich::hash_stable_itemlocalmap(hcx, hasher, pat_binding_modes);
669 ich::hash_stable_hashmap(hcx, hasher, upvar_capture_map, |hcx, up_var_id| {
676 local_id_root.expect("trying to hash invalid TypeckTables");
678 let var_def_id = DefId {
679 krate: local_id_root.krate,
682 let closure_def_id = DefId {
683 krate: local_id_root.krate,
684 index: closure_expr_id,
686 (hcx.def_path_hash(var_def_id), hcx.def_path_hash(closure_def_id))
689 ich::hash_stable_itemlocalmap(hcx, hasher, closure_tys);
690 ich::hash_stable_itemlocalmap(hcx, hasher, closure_kinds);
691 ich::hash_stable_itemlocalmap(hcx, hasher, liberated_fn_sigs);
692 ich::hash_stable_itemlocalmap(hcx, hasher, fru_field_types);
693 ich::hash_stable_itemlocalmap(hcx, hasher, cast_kinds);
695 ich::hash_stable_hashset(hcx, hasher, used_trait_imports, |hcx, def_id| {
696 hcx.def_path_hash(*def_id)
699 tainted_by_errors.hash_stable(hcx, hasher);
700 free_region_map.hash_stable(hcx, hasher);
705 impl<'tcx> CommonTypes<'tcx> {
706 fn new(interners: &CtxtInterners<'tcx>) -> CommonTypes<'tcx> {
707 let mk = |sty| interners.intern_ty(sty, None);
708 let mk_region = |r| {
709 if let Some(r) = interners.region.borrow().get(&r) {
712 let r = interners.arena.alloc(r);
713 interners.region.borrow_mut().insert(Interned(r));
721 isize: mk(TyInt(ast::IntTy::Is)),
722 i8: mk(TyInt(ast::IntTy::I8)),
723 i16: mk(TyInt(ast::IntTy::I16)),
724 i32: mk(TyInt(ast::IntTy::I32)),
725 i64: mk(TyInt(ast::IntTy::I64)),
726 i128: mk(TyInt(ast::IntTy::I128)),
727 usize: mk(TyUint(ast::UintTy::Us)),
728 u8: mk(TyUint(ast::UintTy::U8)),
729 u16: mk(TyUint(ast::UintTy::U16)),
730 u32: mk(TyUint(ast::UintTy::U32)),
731 u64: mk(TyUint(ast::UintTy::U64)),
732 u128: mk(TyUint(ast::UintTy::U128)),
733 f32: mk(TyFloat(ast::FloatTy::F32)),
734 f64: mk(TyFloat(ast::FloatTy::F64)),
736 re_empty: mk_region(RegionKind::ReEmpty),
737 re_static: mk_region(RegionKind::ReStatic),
738 re_erased: mk_region(RegionKind::ReErased),
743 /// The data structure to keep track of all the information that typechecker
744 /// generates so that so that it can be reused and doesn't have to be redone
746 #[derive(Copy, Clone)]
747 pub struct TyCtxt<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
748 gcx: &'a GlobalCtxt<'gcx>,
749 interners: &'a CtxtInterners<'tcx>
752 impl<'a, 'gcx, 'tcx> Deref for TyCtxt<'a, 'gcx, 'tcx> {
753 type Target = &'a GlobalCtxt<'gcx>;
754 fn deref(&self) -> &Self::Target {
759 pub struct GlobalCtxt<'tcx> {
760 global_arenas: &'tcx GlobalArenas<'tcx>,
761 global_interners: CtxtInterners<'tcx>,
763 pub sess: &'tcx Session,
765 pub specializes_cache: RefCell<traits::SpecializesCache>,
767 pub trans_trait_caches: traits::trans::TransTraitCaches<'tcx>,
769 pub dep_graph: DepGraph,
771 /// Common types, pre-interned for your convenience.
772 pub types: CommonTypes<'tcx>,
774 /// Map indicating what traits are in scope for places where this
775 /// is relevant; generated by resolve.
776 pub trait_map: TraitMap,
778 /// Export map produced by name resolution.
779 pub export_map: ExportMap,
781 pub named_region_map: resolve_lifetime::NamedRegionMap,
783 pub hir: hir_map::Map<'tcx>,
785 /// A map from DefPathHash -> DefId. Includes DefIds from the local crate
786 /// as well as all upstream crates. Only populated in incremental mode.
787 pub def_path_hash_to_def_id: Option<FxHashMap<DefPathHash, DefId>>,
789 pub maps: maps::Maps<'tcx>,
791 pub mir_passes: Rc<Passes>,
793 // Records the free variables refrenced by every closure
794 // expression. Do not track deps for this, just recompute it from
795 // scratch every time.
796 pub freevars: RefCell<FreevarMap>,
798 pub maybe_unused_trait_imports: NodeSet,
800 pub maybe_unused_extern_crates: Vec<(NodeId, Span, CrateNum)>,
802 // Internal cache for metadata decoding. No need to track deps on this.
803 pub rcache: RefCell<FxHashMap<ty::CReaderCacheKey, Ty<'tcx>>>,
805 // FIXME dep tracking -- should be harmless enough
806 pub normalized_cache: RefCell<FxHashMap<Ty<'tcx>, Ty<'tcx>>>,
808 pub inhabitedness_cache: RefCell<FxHashMap<Ty<'tcx>, DefIdForest>>,
810 pub lang_items: middle::lang_items::LanguageItems,
812 /// Set of used unsafe nodes (functions or blocks). Unsafe nodes not
813 /// present in this set can be warned about.
814 pub used_unsafe: RefCell<NodeSet>,
816 /// Set of nodes which mark locals as mutable which end up getting used at
817 /// some point. Local variable definitions not in this set can be warned
819 pub used_mut_nodes: RefCell<NodeSet>,
821 /// Maps any item's def-id to its stability index.
822 pub stability: RefCell<stability::Index<'tcx>>,
824 /// Caches the results of trait selection. This cache is used
825 /// for things that do not have to do with the parameters in scope.
826 pub selection_cache: traits::SelectionCache<'tcx>,
828 /// Caches the results of trait evaluation. This cache is used
829 /// for things that do not have to do with the parameters in scope.
830 /// Merge this with `selection_cache`?
831 pub evaluation_cache: traits::EvaluationCache<'tcx>,
833 /// Maps Expr NodeId's to `true` iff `&expr` can have 'static lifetime.
834 pub rvalue_promotable_to_static: RefCell<NodeMap<bool>>,
836 /// The definite name of the current crate after taking into account
837 /// attributes, commandline parameters, etc.
838 pub crate_name: Symbol,
840 /// Data layout specification for the current target.
841 pub data_layout: TargetDataLayout,
843 /// Used to prevent layout from recursing too deeply.
844 pub layout_depth: Cell<usize>,
846 /// Map from function to the `#[derive]` mode that it's defining. Only used
847 /// by `proc-macro` crates.
848 pub derive_macros: RefCell<NodeMap<Symbol>>,
850 stability_interner: RefCell<FxHashSet<&'tcx attr::Stability>>,
852 layout_interner: RefCell<FxHashSet<&'tcx Layout>>,
854 /// A vector of every trait accessible in the whole crate
855 /// (i.e. including those from subcrates). This is used only for
856 /// error reporting, and so is lazily initialized and generally
857 /// shouldn't taint the common path (hence the RefCell).
858 pub all_traits: RefCell<Option<Vec<DefId>>>,
861 impl<'tcx> GlobalCtxt<'tcx> {
862 /// Get the global TyCtxt.
863 pub fn global_tcx<'a>(&'a self) -> TyCtxt<'a, 'tcx, 'tcx> {
866 interners: &self.global_interners
871 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
872 pub fn crate_name(self, cnum: CrateNum) -> Symbol {
873 if cnum == LOCAL_CRATE {
876 self.sess.cstore.crate_name(cnum)
880 pub fn original_crate_name(self, cnum: CrateNum) -> Symbol {
881 if cnum == LOCAL_CRATE {
882 self.crate_name.clone()
884 self.sess.cstore.original_crate_name(cnum)
888 pub fn crate_disambiguator(self, cnum: CrateNum) -> Symbol {
889 if cnum == LOCAL_CRATE {
890 self.sess.local_crate_disambiguator()
892 self.sess.cstore.crate_disambiguator(cnum)
896 pub fn alloc_generics(self, generics: ty::Generics) -> &'gcx ty::Generics {
897 self.global_arenas.generics.alloc(generics)
900 pub fn alloc_steal_mir(self, mir: Mir<'gcx>) -> &'gcx Steal<Mir<'gcx>> {
901 self.global_arenas.steal_mir.alloc(Steal::new(mir))
904 pub fn alloc_mir(self, mir: Mir<'gcx>) -> &'gcx Mir<'gcx> {
905 self.global_arenas.mir.alloc(mir)
908 pub fn alloc_tables(self, tables: ty::TypeckTables<'gcx>) -> &'gcx ty::TypeckTables<'gcx> {
909 self.global_arenas.tables.alloc(tables)
912 pub fn alloc_trait_def(self, def: ty::TraitDef) -> &'gcx ty::TraitDef {
913 self.global_arenas.trait_def.alloc(def)
916 pub fn alloc_adt_def(self,
919 variants: Vec<ty::VariantDef>,
921 -> &'gcx ty::AdtDef {
922 let def = ty::AdtDef::new(self, did, kind, variants, repr);
923 self.global_arenas.adt_def.alloc(def)
926 pub fn intern_stability(self, stab: attr::Stability) -> &'gcx attr::Stability {
927 if let Some(st) = self.stability_interner.borrow().get(&stab) {
931 let interned = self.global_interners.arena.alloc(stab);
932 if let Some(prev) = self.stability_interner.borrow_mut().replace(interned) {
933 bug!("Tried to overwrite interned Stability: {:?}", prev)
938 pub fn intern_layout(self, layout: Layout) -> &'gcx Layout {
939 if let Some(layout) = self.layout_interner.borrow().get(&layout) {
943 let interned = self.global_arenas.layout.alloc(layout);
944 if let Some(prev) = self.layout_interner.borrow_mut().replace(interned) {
945 bug!("Tried to overwrite interned Layout: {:?}", prev)
950 pub fn lift<T: ?Sized + Lift<'tcx>>(self, value: &T) -> Option<T::Lifted> {
951 value.lift_to_tcx(self)
954 /// Like lift, but only tries in the global tcx.
955 pub fn lift_to_global<T: ?Sized + Lift<'gcx>>(self, value: &T) -> Option<T::Lifted> {
956 value.lift_to_tcx(self.global_tcx())
959 /// Returns true if self is the same as self.global_tcx().
960 fn is_global(self) -> bool {
961 let local = self.interners as *const _;
962 let global = &self.global_interners as *const _;
963 local as usize == global as usize
966 /// Create a type context and call the closure with a `TyCtxt` reference
967 /// to the context. The closure enforces that the type context and any interned
968 /// value (types, substs, etc.) can only be used while `ty::tls` has a valid
969 /// reference to the context, to allow formatting values that need it.
970 pub fn create_and_enter<F, R>(s: &'tcx Session,
971 local_providers: ty::maps::Providers<'tcx>,
972 extern_providers: ty::maps::Providers<'tcx>,
973 mir_passes: Rc<Passes>,
974 arenas: &'tcx GlobalArenas<'tcx>,
975 arena: &'tcx DroplessArena,
976 resolutions: ty::Resolutions,
977 named_region_map: resolve_lifetime::NamedRegionMap,
978 hir: hir_map::Map<'tcx>,
979 lang_items: middle::lang_items::LanguageItems,
980 stability: stability::Index<'tcx>,
983 where F: for<'b> FnOnce(TyCtxt<'b, 'tcx, 'tcx>) -> R
985 let data_layout = TargetDataLayout::parse(s);
986 let interners = CtxtInterners::new(arena);
987 let common_types = CommonTypes::new(&interners);
988 let dep_graph = hir.dep_graph.clone();
989 let max_cnum = s.cstore.crates().iter().map(|c| c.as_usize()).max().unwrap_or(0);
990 let mut providers = IndexVec::from_elem_n(extern_providers, max_cnum + 1);
991 providers[LOCAL_CRATE] = local_providers;
993 let def_path_hash_to_def_id = if s.opts.build_dep_graph() {
994 let upstream_def_path_tables: Vec<(CrateNum, Rc<_>)> = s
998 .map(|&cnum| (cnum, s.cstore.def_path_table(cnum)))
1001 let def_path_tables = || {
1002 upstream_def_path_tables
1004 .map(|&(cnum, ref rc)| (cnum, &**rc))
1005 .chain(iter::once((LOCAL_CRATE, hir.definitions().def_path_table())))
1008 // Precompute the capacity of the hashmap so we don't have to
1009 // re-allocate when populating it.
1010 let capacity = def_path_tables().map(|(_, t)| t.size()).sum::<usize>();
1012 let mut map: FxHashMap<_, _> = FxHashMap::with_capacity_and_hasher(
1014 ::std::default::Default::default()
1017 for (cnum, def_path_table) in def_path_tables() {
1018 def_path_table.add_def_path_hashes_to(cnum, &mut map);
1026 tls::enter_global(GlobalCtxt {
1028 trans_trait_caches: traits::trans::TransTraitCaches::new(dep_graph.clone()),
1029 specializes_cache: RefCell::new(traits::SpecializesCache::new()),
1030 global_arenas: arenas,
1031 global_interners: interners,
1032 dep_graph: dep_graph.clone(),
1033 types: common_types,
1035 trait_map: resolutions.trait_map,
1036 export_map: resolutions.export_map,
1038 def_path_hash_to_def_id,
1039 maps: maps::Maps::new(providers),
1041 freevars: RefCell::new(resolutions.freevars),
1042 maybe_unused_trait_imports: resolutions.maybe_unused_trait_imports,
1043 maybe_unused_extern_crates: resolutions.maybe_unused_extern_crates,
1044 rcache: RefCell::new(FxHashMap()),
1045 normalized_cache: RefCell::new(FxHashMap()),
1046 inhabitedness_cache: RefCell::new(FxHashMap()),
1048 used_unsafe: RefCell::new(NodeSet()),
1049 used_mut_nodes: RefCell::new(NodeSet()),
1050 stability: RefCell::new(stability),
1051 selection_cache: traits::SelectionCache::new(),
1052 evaluation_cache: traits::EvaluationCache::new(),
1053 rvalue_promotable_to_static: RefCell::new(NodeMap()),
1054 crate_name: Symbol::intern(crate_name),
1056 layout_interner: RefCell::new(FxHashSet()),
1057 layout_depth: Cell::new(0),
1058 derive_macros: RefCell::new(NodeMap()),
1059 stability_interner: RefCell::new(FxHashSet()),
1060 all_traits: RefCell::new(None),
1064 pub fn consider_optimizing<T: Fn() -> String>(&self, msg: T) -> bool {
1065 let cname = self.crate_name(LOCAL_CRATE).as_str();
1066 self.sess.consider_optimizing(&cname, msg)
1070 impl<'gcx: 'tcx, 'tcx> GlobalCtxt<'gcx> {
1071 /// Call the closure with a local `TyCtxt` using the given arena.
1072 pub fn enter_local<F, R>(&self, arena: &'tcx DroplessArena, f: F) -> R
1073 where F: for<'a> FnOnce(TyCtxt<'a, 'gcx, 'tcx>) -> R
1075 let interners = CtxtInterners::new(arena);
1076 tls::enter(self, &interners, f)
1080 /// A trait implemented for all X<'a> types which can be safely and
1081 /// efficiently converted to X<'tcx> as long as they are part of the
1082 /// provided TyCtxt<'tcx>.
1083 /// This can be done, for example, for Ty<'tcx> or &'tcx Substs<'tcx>
1084 /// by looking them up in their respective interners.
1086 /// However, this is still not the best implementation as it does
1087 /// need to compare the components, even for interned values.
1088 /// It would be more efficient if TypedArena provided a way to
1089 /// determine whether the address is in the allocated range.
1091 /// None is returned if the value or one of the components is not part
1092 /// of the provided context.
1093 /// For Ty, None can be returned if either the type interner doesn't
1094 /// contain the TypeVariants key or if the address of the interned
1095 /// pointer differs. The latter case is possible if a primitive type,
1096 /// e.g. `()` or `u8`, was interned in a different context.
1097 pub trait Lift<'tcx> {
1099 fn lift_to_tcx<'a, 'gcx>(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Option<Self::Lifted>;
1102 impl<'a, 'tcx> Lift<'tcx> for ty::ParamEnv<'a> {
1103 type Lifted = ty::ParamEnv<'tcx>;
1104 fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>) -> Option<ty::ParamEnv<'tcx>> {
1105 self.caller_bounds.lift_to_tcx(tcx).and_then(|caller_bounds| {
1107 reveal: self.reveal,
1114 impl<'a, 'tcx> Lift<'tcx> for Ty<'a> {
1115 type Lifted = Ty<'tcx>;
1116 fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>) -> Option<Ty<'tcx>> {
1117 if tcx.interners.arena.in_arena(*self as *const _) {
1118 return Some(unsafe { mem::transmute(*self) });
1120 // Also try in the global tcx if we're not that.
1121 if !tcx.is_global() {
1122 self.lift_to_tcx(tcx.global_tcx())
1129 impl<'a, 'tcx> Lift<'tcx> for &'a Substs<'a> {
1130 type Lifted = &'tcx Substs<'tcx>;
1131 fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>) -> Option<&'tcx Substs<'tcx>> {
1132 if self.len() == 0 {
1133 return Some(Slice::empty());
1135 if tcx.interners.arena.in_arena(&self[..] as *const _) {
1136 return Some(unsafe { mem::transmute(*self) });
1138 // Also try in the global tcx if we're not that.
1139 if !tcx.is_global() {
1140 self.lift_to_tcx(tcx.global_tcx())
1147 impl<'a, 'tcx> Lift<'tcx> for Region<'a> {
1148 type Lifted = Region<'tcx>;
1149 fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>) -> Option<Region<'tcx>> {
1150 if tcx.interners.arena.in_arena(*self as *const _) {
1151 return Some(unsafe { mem::transmute(*self) });
1153 // Also try in the global tcx if we're not that.
1154 if !tcx.is_global() {
1155 self.lift_to_tcx(tcx.global_tcx())
1162 impl<'a, 'tcx> Lift<'tcx> for &'a Slice<Ty<'a>> {
1163 type Lifted = &'tcx Slice<Ty<'tcx>>;
1164 fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>)
1165 -> Option<&'tcx Slice<Ty<'tcx>>> {
1166 if self.len() == 0 {
1167 return Some(Slice::empty());
1169 if tcx.interners.arena.in_arena(*self as *const _) {
1170 return Some(unsafe { mem::transmute(*self) });
1172 // Also try in the global tcx if we're not that.
1173 if !tcx.is_global() {
1174 self.lift_to_tcx(tcx.global_tcx())
1181 impl<'a, 'tcx> Lift<'tcx> for &'a Slice<ExistentialPredicate<'a>> {
1182 type Lifted = &'tcx Slice<ExistentialPredicate<'tcx>>;
1183 fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>)
1184 -> Option<&'tcx Slice<ExistentialPredicate<'tcx>>> {
1185 if self.is_empty() {
1186 return Some(Slice::empty());
1188 if tcx.interners.arena.in_arena(*self as *const _) {
1189 return Some(unsafe { mem::transmute(*self) });
1191 // Also try in the global tcx if we're not that.
1192 if !tcx.is_global() {
1193 self.lift_to_tcx(tcx.global_tcx())
1200 impl<'a, 'tcx> Lift<'tcx> for &'a Slice<Predicate<'a>> {
1201 type Lifted = &'tcx Slice<Predicate<'tcx>>;
1202 fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>)
1203 -> Option<&'tcx Slice<Predicate<'tcx>>> {
1204 if self.is_empty() {
1205 return Some(Slice::empty());
1207 if tcx.interners.arena.in_arena(*self as *const _) {
1208 return Some(unsafe { mem::transmute(*self) });
1210 // Also try in the global tcx if we're not that.
1211 if !tcx.is_global() {
1212 self.lift_to_tcx(tcx.global_tcx())
1220 use super::{CtxtInterners, GlobalCtxt, TyCtxt};
1222 use std::cell::Cell;
1226 /// Marker types used for the scoped TLS slot.
1227 /// The type context cannot be used directly because the scoped TLS
1228 /// in libstd doesn't allow types generic over lifetimes.
1229 enum ThreadLocalGlobalCtxt {}
1230 enum ThreadLocalInterners {}
1233 static TLS_TCX: Cell<Option<(*const ThreadLocalGlobalCtxt,
1234 *const ThreadLocalInterners)>> = Cell::new(None)
1237 fn span_debug(span: syntax_pos::Span, f: &mut fmt::Formatter) -> fmt::Result {
1239 write!(f, "{}", tcx.sess.codemap().span_to_string(span))
1243 pub fn enter_global<'gcx, F, R>(gcx: GlobalCtxt<'gcx>, f: F) -> R
1244 where F: for<'a> FnOnce(TyCtxt<'a, 'gcx, 'gcx>) -> R
1246 syntax_pos::SPAN_DEBUG.with(|span_dbg| {
1247 let original_span_debug = span_dbg.get();
1248 span_dbg.set(span_debug);
1249 let result = enter(&gcx, &gcx.global_interners, f);
1250 span_dbg.set(original_span_debug);
1255 pub fn enter<'a, 'gcx: 'tcx, 'tcx, F, R>(gcx: &'a GlobalCtxt<'gcx>,
1256 interners: &'a CtxtInterners<'tcx>,
1258 where F: FnOnce(TyCtxt<'a, 'gcx, 'tcx>) -> R
1260 let gcx_ptr = gcx as *const _ as *const ThreadLocalGlobalCtxt;
1261 let interners_ptr = interners as *const _ as *const ThreadLocalInterners;
1262 TLS_TCX.with(|tls| {
1263 let prev = tls.get();
1264 tls.set(Some((gcx_ptr, interners_ptr)));
1265 let ret = f(TyCtxt {
1274 pub fn with<F, R>(f: F) -> R
1275 where F: for<'a, 'gcx, 'tcx> FnOnce(TyCtxt<'a, 'gcx, 'tcx>) -> R
1277 TLS_TCX.with(|tcx| {
1278 let (gcx, interners) = tcx.get().unwrap();
1279 let gcx = unsafe { &*(gcx as *const GlobalCtxt) };
1280 let interners = unsafe { &*(interners as *const CtxtInterners) };
1288 pub fn with_opt<F, R>(f: F) -> R
1289 where F: for<'a, 'gcx, 'tcx> FnOnce(Option<TyCtxt<'a, 'gcx, 'tcx>>) -> R
1291 if TLS_TCX.with(|tcx| tcx.get().is_some()) {
1292 with(|v| f(Some(v)))
1299 macro_rules! sty_debug_print {
1300 ($ctxt: expr, $($variant: ident),*) => {{
1301 // curious inner module to allow variant names to be used as
1303 #[allow(non_snake_case)]
1305 use ty::{self, TyCtxt};
1306 use ty::context::Interned;
1308 #[derive(Copy, Clone)]
1311 region_infer: usize,
1316 pub fn go(tcx: TyCtxt) {
1317 let mut total = DebugStat {
1319 region_infer: 0, ty_infer: 0, both_infer: 0,
1321 $(let mut $variant = total;)*
1324 for &Interned(t) in tcx.interners.type_.borrow().iter() {
1325 let variant = match t.sty {
1326 ty::TyBool | ty::TyChar | ty::TyInt(..) | ty::TyUint(..) |
1327 ty::TyFloat(..) | ty::TyStr | ty::TyNever => continue,
1328 ty::TyError => /* unimportant */ continue,
1329 $(ty::$variant(..) => &mut $variant,)*
1331 let region = t.flags.intersects(ty::TypeFlags::HAS_RE_INFER);
1332 let ty = t.flags.intersects(ty::TypeFlags::HAS_TY_INFER);
1336 if region { total.region_infer += 1; variant.region_infer += 1 }
1337 if ty { total.ty_infer += 1; variant.ty_infer += 1 }
1338 if region && ty { total.both_infer += 1; variant.both_infer += 1 }
1340 println!("Ty interner total ty region both");
1341 $(println!(" {:18}: {uses:6} {usespc:4.1}%, \
1342 {ty:4.1}% {region:5.1}% {both:4.1}%",
1343 stringify!($variant),
1344 uses = $variant.total,
1345 usespc = $variant.total as f64 * 100.0 / total.total as f64,
1346 ty = $variant.ty_infer as f64 * 100.0 / total.total as f64,
1347 region = $variant.region_infer as f64 * 100.0 / total.total as f64,
1348 both = $variant.both_infer as f64 * 100.0 / total.total as f64);
1350 println!(" total {uses:6} \
1351 {ty:4.1}% {region:5.1}% {both:4.1}%",
1353 ty = total.ty_infer as f64 * 100.0 / total.total as f64,
1354 region = total.region_infer as f64 * 100.0 / total.total as f64,
1355 both = total.both_infer as f64 * 100.0 / total.total as f64)
1363 impl<'a, 'tcx> TyCtxt<'a, 'tcx, 'tcx> {
1364 pub fn print_debug_stats(self) {
1367 TyAdt, TyArray, TySlice, TyRawPtr, TyRef, TyFnDef, TyFnPtr,
1368 TyDynamic, TyClosure, TyTuple, TyParam, TyInfer, TyProjection, TyAnon);
1370 println!("Substs interner: #{}", self.interners.substs.borrow().len());
1371 println!("Region interner: #{}", self.interners.region.borrow().len());
1372 println!("Stability interner: #{}", self.stability_interner.borrow().len());
1373 println!("Layout interner: #{}", self.layout_interner.borrow().len());
1378 /// An entry in an interner.
1379 struct Interned<'tcx, T: 'tcx+?Sized>(&'tcx T);
1381 // NB: An Interned<Ty> compares and hashes as a sty.
1382 impl<'tcx> PartialEq for Interned<'tcx, TyS<'tcx>> {
1383 fn eq(&self, other: &Interned<'tcx, TyS<'tcx>>) -> bool {
1384 self.0.sty == other.0.sty
1388 impl<'tcx> Eq for Interned<'tcx, TyS<'tcx>> {}
1390 impl<'tcx> Hash for Interned<'tcx, TyS<'tcx>> {
1391 fn hash<H: Hasher>(&self, s: &mut H) {
1396 impl<'tcx: 'lcx, 'lcx> Borrow<TypeVariants<'lcx>> for Interned<'tcx, TyS<'tcx>> {
1397 fn borrow<'a>(&'a self) -> &'a TypeVariants<'lcx> {
1402 // NB: An Interned<Slice<T>> compares and hashes as its elements.
1403 impl<'tcx, T: PartialEq> PartialEq for Interned<'tcx, Slice<T>> {
1404 fn eq(&self, other: &Interned<'tcx, Slice<T>>) -> bool {
1405 self.0[..] == other.0[..]
1409 impl<'tcx, T: Eq> Eq for Interned<'tcx, Slice<T>> {}
1411 impl<'tcx, T: Hash> Hash for Interned<'tcx, Slice<T>> {
1412 fn hash<H: Hasher>(&self, s: &mut H) {
1417 impl<'tcx: 'lcx, 'lcx> Borrow<[Ty<'lcx>]> for Interned<'tcx, Slice<Ty<'tcx>>> {
1418 fn borrow<'a>(&'a self) -> &'a [Ty<'lcx>] {
1423 impl<'tcx: 'lcx, 'lcx> Borrow<[Kind<'lcx>]> for Interned<'tcx, Substs<'tcx>> {
1424 fn borrow<'a>(&'a self) -> &'a [Kind<'lcx>] {
1429 impl<'tcx> Borrow<RegionKind> for Interned<'tcx, RegionKind> {
1430 fn borrow<'a>(&'a self) -> &'a RegionKind {
1435 impl<'tcx: 'lcx, 'lcx> Borrow<[ExistentialPredicate<'lcx>]>
1436 for Interned<'tcx, Slice<ExistentialPredicate<'tcx>>> {
1437 fn borrow<'a>(&'a self) -> &'a [ExistentialPredicate<'lcx>] {
1442 impl<'tcx: 'lcx, 'lcx> Borrow<[Predicate<'lcx>]>
1443 for Interned<'tcx, Slice<Predicate<'tcx>>> {
1444 fn borrow<'a>(&'a self) -> &'a [Predicate<'lcx>] {
1449 macro_rules! intern_method {
1450 ($lt_tcx:tt, $name:ident: $method:ident($alloc:ty,
1451 $alloc_method:ident,
1454 $needs_infer:expr) -> $ty:ty) => {
1455 impl<'a, 'gcx, $lt_tcx> TyCtxt<'a, 'gcx, $lt_tcx> {
1456 pub fn $method(self, v: $alloc) -> &$lt_tcx $ty {
1458 let key = ($alloc_to_key)(&v);
1459 if let Some(i) = self.interners.$name.borrow().get(key) {
1462 if !self.is_global() {
1463 if let Some(i) = self.global_interners.$name.borrow().get(key) {
1469 // HACK(eddyb) Depend on flags being accurate to
1470 // determine that all contents are in the global tcx.
1471 // See comments on Lift for why we can't use that.
1472 if !($needs_infer)(&v) {
1473 if !self.is_global() {
1477 let i = ($alloc_to_ret)(self.global_interners.arena.$alloc_method(v));
1478 self.global_interners.$name.borrow_mut().insert(Interned(i));
1482 // Make sure we don't end up with inference
1483 // types/regions in the global tcx.
1484 if self.is_global() {
1485 bug!("Attempted to intern `{:?}` which contains \
1486 inference types/regions in the global type context",
1491 let i = ($alloc_to_ret)(self.interners.arena.$alloc_method(v));
1492 self.interners.$name.borrow_mut().insert(Interned(i));
1499 macro_rules! direct_interners {
1500 ($lt_tcx:tt, $($name:ident: $method:ident($needs_infer:expr) -> $ty:ty),+) => {
1501 $(impl<$lt_tcx> PartialEq for Interned<$lt_tcx, $ty> {
1502 fn eq(&self, other: &Self) -> bool {
1507 impl<$lt_tcx> Eq for Interned<$lt_tcx, $ty> {}
1509 impl<$lt_tcx> Hash for Interned<$lt_tcx, $ty> {
1510 fn hash<H: Hasher>(&self, s: &mut H) {
1515 intern_method!($lt_tcx, $name: $method($ty, alloc, |x| x, |x| x, $needs_infer) -> $ty);)+
1519 pub fn keep_local<'tcx, T: ty::TypeFoldable<'tcx>>(x: &T) -> bool {
1520 x.has_type_flags(ty::TypeFlags::KEEP_IN_LOCAL_TCX)
1523 direct_interners!('tcx,
1524 region: mk_region(|r| {
1526 &ty::ReVar(_) | &ty::ReSkolemized(..) => true,
1532 macro_rules! slice_interners {
1533 ($($field:ident: $method:ident($ty:ident)),+) => (
1534 $(intern_method!('tcx, $field: $method(&[$ty<'tcx>], alloc_slice, Deref::deref,
1535 |xs: &[$ty]| -> &Slice<$ty> {
1536 unsafe { mem::transmute(xs) }
1537 }, |xs: &[$ty]| xs.iter().any(keep_local)) -> Slice<$ty<'tcx>>);)+
1542 existential_predicates: _intern_existential_predicates(ExistentialPredicate),
1543 predicates: _intern_predicates(Predicate),
1544 type_list: _intern_type_list(Ty),
1545 substs: _intern_substs(Kind)
1548 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
1549 /// Create an unsafe fn ty based on a safe fn ty.
1550 pub fn safe_to_unsafe_fn_ty(self, sig: PolyFnSig<'tcx>) -> Ty<'tcx> {
1551 assert_eq!(sig.unsafety(), hir::Unsafety::Normal);
1552 self.mk_fn_ptr(sig.map_bound(|sig| ty::FnSig {
1553 unsafety: hir::Unsafety::Unsafe,
1558 // Interns a type/name combination, stores the resulting box in cx.interners,
1559 // and returns the box as cast to an unsafe ptr (see comments for Ty above).
1560 pub fn mk_ty(self, st: TypeVariants<'tcx>) -> Ty<'tcx> {
1561 let global_interners = if !self.is_global() {
1562 Some(&self.global_interners)
1566 self.interners.intern_ty(st, global_interners)
1569 pub fn mk_mach_int(self, tm: ast::IntTy) -> Ty<'tcx> {
1571 ast::IntTy::Is => self.types.isize,
1572 ast::IntTy::I8 => self.types.i8,
1573 ast::IntTy::I16 => self.types.i16,
1574 ast::IntTy::I32 => self.types.i32,
1575 ast::IntTy::I64 => self.types.i64,
1576 ast::IntTy::I128 => self.types.i128,
1580 pub fn mk_mach_uint(self, tm: ast::UintTy) -> Ty<'tcx> {
1582 ast::UintTy::Us => self.types.usize,
1583 ast::UintTy::U8 => self.types.u8,
1584 ast::UintTy::U16 => self.types.u16,
1585 ast::UintTy::U32 => self.types.u32,
1586 ast::UintTy::U64 => self.types.u64,
1587 ast::UintTy::U128 => self.types.u128,
1591 pub fn mk_mach_float(self, tm: ast::FloatTy) -> Ty<'tcx> {
1593 ast::FloatTy::F32 => self.types.f32,
1594 ast::FloatTy::F64 => self.types.f64,
1598 pub fn mk_str(self) -> Ty<'tcx> {
1602 pub fn mk_static_str(self) -> Ty<'tcx> {
1603 self.mk_imm_ref(self.types.re_static, self.mk_str())
1606 pub fn mk_adt(self, def: &'tcx AdtDef, substs: &'tcx Substs<'tcx>) -> Ty<'tcx> {
1607 // take a copy of substs so that we own the vectors inside
1608 self.mk_ty(TyAdt(def, substs))
1611 pub fn mk_box(self, ty: Ty<'tcx>) -> Ty<'tcx> {
1612 let def_id = self.require_lang_item(lang_items::OwnedBoxLangItem);
1613 let adt_def = self.adt_def(def_id);
1614 let substs = self.mk_substs(iter::once(Kind::from(ty)));
1615 self.mk_ty(TyAdt(adt_def, substs))
1618 pub fn mk_ptr(self, tm: TypeAndMut<'tcx>) -> Ty<'tcx> {
1619 self.mk_ty(TyRawPtr(tm))
1622 pub fn mk_ref(self, r: Region<'tcx>, tm: TypeAndMut<'tcx>) -> Ty<'tcx> {
1623 self.mk_ty(TyRef(r, tm))
1626 pub fn mk_mut_ref(self, r: Region<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
1627 self.mk_ref(r, TypeAndMut {ty: ty, mutbl: hir::MutMutable})
1630 pub fn mk_imm_ref(self, r: Region<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
1631 self.mk_ref(r, TypeAndMut {ty: ty, mutbl: hir::MutImmutable})
1634 pub fn mk_mut_ptr(self, ty: Ty<'tcx>) -> Ty<'tcx> {
1635 self.mk_ptr(TypeAndMut {ty: ty, mutbl: hir::MutMutable})
1638 pub fn mk_imm_ptr(self, ty: Ty<'tcx>) -> Ty<'tcx> {
1639 self.mk_ptr(TypeAndMut {ty: ty, mutbl: hir::MutImmutable})
1642 pub fn mk_nil_ptr(self) -> Ty<'tcx> {
1643 self.mk_imm_ptr(self.mk_nil())
1646 pub fn mk_array(self, ty: Ty<'tcx>, n: usize) -> Ty<'tcx> {
1647 self.mk_ty(TyArray(ty, n))
1650 pub fn mk_slice(self, ty: Ty<'tcx>) -> Ty<'tcx> {
1651 self.mk_ty(TySlice(ty))
1654 pub fn intern_tup(self, ts: &[Ty<'tcx>], defaulted: bool) -> Ty<'tcx> {
1655 self.mk_ty(TyTuple(self.intern_type_list(ts), defaulted))
1658 pub fn mk_tup<I: InternAs<[Ty<'tcx>], Ty<'tcx>>>(self, iter: I,
1659 defaulted: bool) -> I::Output {
1660 iter.intern_with(|ts| self.mk_ty(TyTuple(self.intern_type_list(ts), defaulted)))
1663 pub fn mk_nil(self) -> Ty<'tcx> {
1664 self.intern_tup(&[], false)
1667 pub fn mk_diverging_default(self) -> Ty<'tcx> {
1668 if self.sess.features.borrow().never_type {
1671 self.intern_tup(&[], true)
1675 pub fn mk_bool(self) -> Ty<'tcx> {
1679 pub fn mk_fn_def(self, def_id: DefId,
1680 substs: &'tcx Substs<'tcx>) -> Ty<'tcx> {
1681 self.mk_ty(TyFnDef(def_id, substs))
1684 pub fn mk_fn_ptr(self, fty: PolyFnSig<'tcx>) -> Ty<'tcx> {
1685 self.mk_ty(TyFnPtr(fty))
1690 obj: ty::Binder<&'tcx Slice<ExistentialPredicate<'tcx>>>,
1691 reg: ty::Region<'tcx>
1693 self.mk_ty(TyDynamic(obj, reg))
1696 pub fn mk_projection(self,
1698 substs: &'tcx Substs<'tcx>)
1700 self.mk_ty(TyProjection(ProjectionTy {
1706 pub fn mk_closure(self,
1708 substs: &'tcx Substs<'tcx>)
1710 self.mk_closure_from_closure_substs(closure_id, ClosureSubsts {
1715 pub fn mk_closure_from_closure_substs(self,
1717 closure_substs: ClosureSubsts<'tcx>)
1719 self.mk_ty(TyClosure(closure_id, closure_substs))
1722 pub fn mk_var(self, v: TyVid) -> Ty<'tcx> {
1723 self.mk_infer(TyVar(v))
1726 pub fn mk_int_var(self, v: IntVid) -> Ty<'tcx> {
1727 self.mk_infer(IntVar(v))
1730 pub fn mk_float_var(self, v: FloatVid) -> Ty<'tcx> {
1731 self.mk_infer(FloatVar(v))
1734 pub fn mk_infer(self, it: InferTy) -> Ty<'tcx> {
1735 self.mk_ty(TyInfer(it))
1738 pub fn mk_param(self,
1740 name: Name) -> Ty<'tcx> {
1741 self.mk_ty(TyParam(ParamTy { idx: index, name: name }))
1744 pub fn mk_self_type(self) -> Ty<'tcx> {
1745 self.mk_param(0, keywords::SelfType.name())
1748 pub fn mk_param_from_def(self, def: &ty::TypeParameterDef) -> Ty<'tcx> {
1749 self.mk_param(def.index, def.name)
1752 pub fn mk_anon(self, def_id: DefId, substs: &'tcx Substs<'tcx>) -> Ty<'tcx> {
1753 self.mk_ty(TyAnon(def_id, substs))
1756 pub fn intern_existential_predicates(self, eps: &[ExistentialPredicate<'tcx>])
1757 -> &'tcx Slice<ExistentialPredicate<'tcx>> {
1758 assert!(!eps.is_empty());
1759 assert!(eps.windows(2).all(|w| w[0].cmp(self, &w[1]) != Ordering::Greater));
1760 self._intern_existential_predicates(eps)
1763 pub fn intern_predicates(self, preds: &[Predicate<'tcx>])
1764 -> &'tcx Slice<Predicate<'tcx>> {
1765 // FIXME consider asking the input slice to be sorted to avoid
1766 // re-interning permutations, in which case that would be asserted
1768 if preds.len() == 0 {
1769 // The macro-generated method below asserts we don't intern an empty slice.
1772 self._intern_predicates(preds)
1776 pub fn intern_type_list(self, ts: &[Ty<'tcx>]) -> &'tcx Slice<Ty<'tcx>> {
1780 self._intern_type_list(ts)
1784 pub fn intern_substs(self, ts: &[Kind<'tcx>]) -> &'tcx Slice<Kind<'tcx>> {
1788 self._intern_substs(ts)
1792 pub fn mk_fn_sig<I>(self,
1796 unsafety: hir::Unsafety,
1798 -> <I::Item as InternIteratorElement<Ty<'tcx>, ty::FnSig<'tcx>>>::Output
1800 I::Item: InternIteratorElement<Ty<'tcx>, ty::FnSig<'tcx>>
1802 inputs.chain(iter::once(output)).intern_with(|xs| ty::FnSig {
1803 inputs_and_output: self.intern_type_list(xs),
1804 variadic, unsafety, abi
1808 pub fn mk_existential_predicates<I: InternAs<[ExistentialPredicate<'tcx>],
1809 &'tcx Slice<ExistentialPredicate<'tcx>>>>(self, iter: I)
1811 iter.intern_with(|xs| self.intern_existential_predicates(xs))
1814 pub fn mk_predicates<I: InternAs<[Predicate<'tcx>],
1815 &'tcx Slice<Predicate<'tcx>>>>(self, iter: I)
1817 iter.intern_with(|xs| self.intern_predicates(xs))
1820 pub fn mk_type_list<I: InternAs<[Ty<'tcx>],
1821 &'tcx Slice<Ty<'tcx>>>>(self, iter: I) -> I::Output {
1822 iter.intern_with(|xs| self.intern_type_list(xs))
1825 pub fn mk_substs<I: InternAs<[Kind<'tcx>],
1826 &'tcx Slice<Kind<'tcx>>>>(self, iter: I) -> I::Output {
1827 iter.intern_with(|xs| self.intern_substs(xs))
1830 pub fn mk_substs_trait(self,
1833 -> &'tcx Substs<'tcx>
1835 self.mk_substs(iter::once(s).chain(t.into_iter().cloned()).map(Kind::from))
1838 pub fn lint_node<S: Into<MultiSpan>>(self,
1839 lint: &'static Lint,
1843 self.struct_span_lint_node(lint, id, span.into(), msg).emit()
1846 pub fn lint_node_note<S: Into<MultiSpan>>(self,
1847 lint: &'static Lint,
1852 let mut err = self.struct_span_lint_node(lint, id, span.into(), msg);
1857 pub fn lint_level_at_node(self, lint: &'static Lint, mut id: NodeId)
1858 -> (lint::Level, lint::LintSource)
1860 // Right now we insert a `with_ignore` node in the dep graph here to
1861 // ignore the fact that `lint_levels` below depends on the entire crate.
1862 // For now this'll prevent false positives of recompiling too much when
1863 // anything changes.
1865 // Once red/green incremental compilation lands we should be able to
1866 // remove this because while the crate changes often the lint level map
1867 // will change rarely.
1868 self.dep_graph.with_ignore(|| {
1869 let sets = self.lint_levels(LOCAL_CRATE);
1871 let hir_id = self.hir.definitions().node_to_hir_id(id);
1872 if let Some(pair) = sets.level_and_source(lint, hir_id) {
1875 let next = self.hir.get_parent_node(id);
1877 bug!("lint traversal reached the root of the crate");
1884 pub fn struct_span_lint_node<S: Into<MultiSpan>>(self,
1885 lint: &'static Lint,
1889 -> DiagnosticBuilder<'tcx>
1891 let (level, src) = self.lint_level_at_node(lint, id);
1892 lint::struct_lint_level(self.sess, lint, level, src, Some(span.into()), msg)
1895 pub fn struct_lint_node(self, lint: &'static Lint, id: NodeId, msg: &str)
1896 -> DiagnosticBuilder<'tcx>
1898 let (level, src) = self.lint_level_at_node(lint, id);
1899 lint::struct_lint_level(self.sess, lint, level, src, None, msg)
1903 pub trait InternAs<T: ?Sized, R> {
1905 fn intern_with<F>(self, f: F) -> Self::Output
1906 where F: FnOnce(&T) -> R;
1909 impl<I, T, R, E> InternAs<[T], R> for I
1910 where E: InternIteratorElement<T, R>,
1911 I: Iterator<Item=E> {
1912 type Output = E::Output;
1913 fn intern_with<F>(self, f: F) -> Self::Output
1914 where F: FnOnce(&[T]) -> R {
1915 E::intern_with(self, f)
1919 pub trait InternIteratorElement<T, R>: Sized {
1921 fn intern_with<I: Iterator<Item=Self>, F: FnOnce(&[T]) -> R>(iter: I, f: F) -> Self::Output;
1924 impl<T, R> InternIteratorElement<T, R> for T {
1926 fn intern_with<I: Iterator<Item=Self>, F: FnOnce(&[T]) -> R>(iter: I, f: F) -> Self::Output {
1927 f(&iter.collect::<AccumulateVec<[_; 8]>>())
1931 impl<'a, T, R> InternIteratorElement<T, R> for &'a T
1935 fn intern_with<I: Iterator<Item=Self>, F: FnOnce(&[T]) -> R>(iter: I, f: F) -> Self::Output {
1936 f(&iter.cloned().collect::<AccumulateVec<[_; 8]>>())
1940 impl<T, R, E> InternIteratorElement<T, R> for Result<T, E> {
1941 type Output = Result<R, E>;
1942 fn intern_with<I: Iterator<Item=Self>, F: FnOnce(&[T]) -> R>(iter: I, f: F) -> Self::Output {
1943 Ok(f(&iter.collect::<Result<AccumulateVec<[_; 8]>, _>>()?))