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, GeneratorInterior, 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 generator_sigs: ItemLocalMap<Option<ty::GenSig<'tcx>>>,
345 generator_interiors: ItemLocalMap<ty::GeneratorInterior<'tcx>>,
347 /// For each fn, records the "liberated" types of its arguments
348 /// and return type. Liberated means that all bound regions
349 /// (including late-bound regions) are replaced with free
350 /// equivalents. This table is not used in trans (since regions
351 /// are erased there) and hence is not serialized to metadata.
352 liberated_fn_sigs: ItemLocalMap<ty::FnSig<'tcx>>,
354 /// For each FRU expression, record the normalized types of the fields
355 /// of the struct - this is needed because it is non-trivial to
356 /// normalize while preserving regions. This table is used only in
357 /// MIR construction and hence is not serialized to metadata.
358 fru_field_types: ItemLocalMap<Vec<Ty<'tcx>>>,
360 /// Maps a cast expression to its kind. This is keyed on the
361 /// *from* expression of the cast, not the cast itself.
362 cast_kinds: ItemLocalMap<ty::cast::CastKind>,
364 /// Set of trait imports actually used in the method resolution.
365 /// This is used for warning unused imports.
366 pub used_trait_imports: DefIdSet,
368 /// If any errors occurred while type-checking this body,
369 /// this field will be set to `true`.
370 pub tainted_by_errors: bool,
372 /// Stores the free-region relationships that were deduced from
373 /// its where clauses and parameter types. These are then
374 /// read-again by borrowck.
375 pub free_region_map: FreeRegionMap<'tcx>,
378 impl<'tcx> TypeckTables<'tcx> {
379 pub fn empty(local_id_root: Option<DefId>) -> TypeckTables<'tcx> {
382 type_dependent_defs: ItemLocalMap(),
383 node_types: ItemLocalMap(),
384 node_substs: ItemLocalMap(),
385 adjustments: ItemLocalMap(),
386 pat_binding_modes: ItemLocalMap(),
387 upvar_capture_map: FxHashMap(),
388 generator_sigs: ItemLocalMap(),
389 generator_interiors: ItemLocalMap(),
390 closure_tys: ItemLocalMap(),
391 closure_kinds: ItemLocalMap(),
392 liberated_fn_sigs: ItemLocalMap(),
393 fru_field_types: ItemLocalMap(),
394 cast_kinds: ItemLocalMap(),
395 used_trait_imports: DefIdSet(),
396 tainted_by_errors: false,
397 free_region_map: FreeRegionMap::new(),
401 /// Returns the final resolution of a `QPath` in an `Expr` or `Pat` node.
402 pub fn qpath_def(&self, qpath: &hir::QPath, id: hir::HirId) -> Def {
404 hir::QPath::Resolved(_, ref path) => path.def,
405 hir::QPath::TypeRelative(..) => {
406 validate_hir_id_for_typeck_tables(self.local_id_root, id, false);
407 self.type_dependent_defs.get(&id.local_id).cloned().unwrap_or(Def::Err)
412 pub fn type_dependent_defs(&self) -> LocalTableInContext<Def> {
413 LocalTableInContext {
414 local_id_root: self.local_id_root,
415 data: &self.type_dependent_defs
419 pub fn type_dependent_defs_mut(&mut self) -> LocalTableInContextMut<Def> {
420 LocalTableInContextMut {
421 local_id_root: self.local_id_root,
422 data: &mut self.type_dependent_defs
426 pub fn node_types(&self) -> LocalTableInContext<Ty<'tcx>> {
427 LocalTableInContext {
428 local_id_root: self.local_id_root,
429 data: &self.node_types
433 pub fn node_types_mut(&mut self) -> LocalTableInContextMut<Ty<'tcx>> {
434 LocalTableInContextMut {
435 local_id_root: self.local_id_root,
436 data: &mut self.node_types
440 pub fn node_id_to_type(&self, id: hir::HirId) -> Ty<'tcx> {
441 match self.node_id_to_type_opt(id) {
444 bug!("node_id_to_type: no type for node `{}`",
446 let id = tcx.hir.definitions().find_node_for_hir_id(id);
447 tcx.hir.node_to_string(id)
453 pub fn node_id_to_type_opt(&self, id: hir::HirId) -> Option<Ty<'tcx>> {
454 validate_hir_id_for_typeck_tables(self.local_id_root, id, false);
455 self.node_types.get(&id.local_id).cloned()
458 pub fn node_substs_mut(&mut self) -> LocalTableInContextMut<&'tcx Substs<'tcx>> {
459 LocalTableInContextMut {
460 local_id_root: self.local_id_root,
461 data: &mut self.node_substs
465 pub fn node_substs(&self, id: hir::HirId) -> &'tcx Substs<'tcx> {
466 validate_hir_id_for_typeck_tables(self.local_id_root, id, false);
467 self.node_substs.get(&id.local_id).cloned().unwrap_or(Substs::empty())
470 pub fn node_substs_opt(&self, id: hir::HirId) -> Option<&'tcx Substs<'tcx>> {
471 validate_hir_id_for_typeck_tables(self.local_id_root, id, false);
472 self.node_substs.get(&id.local_id).cloned()
475 // Returns the type of a pattern as a monotype. Like @expr_ty, this function
476 // doesn't provide type parameter substitutions.
477 pub fn pat_ty(&self, pat: &hir::Pat) -> Ty<'tcx> {
478 self.node_id_to_type(pat.hir_id)
481 pub fn pat_ty_opt(&self, pat: &hir::Pat) -> Option<Ty<'tcx>> {
482 self.node_id_to_type_opt(pat.hir_id)
485 // Returns the type of an expression as a monotype.
487 // NB (1): This is the PRE-ADJUSTMENT TYPE for the expression. That is, in
488 // some cases, we insert `Adjustment` annotations such as auto-deref or
489 // auto-ref. The type returned by this function does not consider such
490 // adjustments. See `expr_ty_adjusted()` instead.
492 // NB (2): This type doesn't provide type parameter substitutions; e.g. if you
493 // ask for the type of "id" in "id(3)", it will return "fn(&isize) -> isize"
494 // instead of "fn(ty) -> T with T = isize".
495 pub fn expr_ty(&self, expr: &hir::Expr) -> Ty<'tcx> {
496 self.node_id_to_type(expr.hir_id)
499 pub fn expr_ty_opt(&self, expr: &hir::Expr) -> Option<Ty<'tcx>> {
500 self.node_id_to_type_opt(expr.hir_id)
503 pub fn adjustments(&self) -> LocalTableInContext<Vec<ty::adjustment::Adjustment<'tcx>>> {
504 LocalTableInContext {
505 local_id_root: self.local_id_root,
506 data: &self.adjustments
510 pub fn adjustments_mut(&mut self)
511 -> LocalTableInContextMut<Vec<ty::adjustment::Adjustment<'tcx>>> {
512 LocalTableInContextMut {
513 local_id_root: self.local_id_root,
514 data: &mut self.adjustments
518 pub fn expr_adjustments(&self, expr: &hir::Expr)
519 -> &[ty::adjustment::Adjustment<'tcx>] {
520 validate_hir_id_for_typeck_tables(self.local_id_root, expr.hir_id, false);
521 self.adjustments.get(&expr.hir_id.local_id).map_or(&[], |a| &a[..])
524 /// Returns the type of `expr`, considering any `Adjustment`
525 /// entry recorded for that expression.
526 pub fn expr_ty_adjusted(&self, expr: &hir::Expr) -> Ty<'tcx> {
527 self.expr_adjustments(expr)
529 .map_or_else(|| self.expr_ty(expr), |adj| adj.target)
532 pub fn expr_ty_adjusted_opt(&self, expr: &hir::Expr) -> Option<Ty<'tcx>> {
533 self.expr_adjustments(expr)
535 .map(|adj| adj.target)
536 .or_else(|| self.expr_ty_opt(expr))
539 pub fn is_method_call(&self, expr: &hir::Expr) -> bool {
540 // Only paths and method calls/overloaded operators have
541 // entries in type_dependent_defs, ignore the former here.
542 if let hir::ExprPath(_) = expr.node {
546 match self.type_dependent_defs().get(expr.hir_id) {
547 Some(&Def::Method(_)) => true,
552 pub fn pat_binding_modes(&self) -> LocalTableInContext<BindingMode> {
553 LocalTableInContext {
554 local_id_root: self.local_id_root,
555 data: &self.pat_binding_modes
559 pub fn pat_binding_modes_mut(&mut self)
560 -> LocalTableInContextMut<BindingMode> {
561 LocalTableInContextMut {
562 local_id_root: self.local_id_root,
563 data: &mut self.pat_binding_modes
567 pub fn upvar_capture(&self, upvar_id: ty::UpvarId) -> ty::UpvarCapture<'tcx> {
568 self.upvar_capture_map[&upvar_id]
571 pub fn closure_tys(&self) -> LocalTableInContext<ty::PolyFnSig<'tcx>> {
572 LocalTableInContext {
573 local_id_root: self.local_id_root,
574 data: &self.closure_tys
578 pub fn closure_tys_mut(&mut self)
579 -> LocalTableInContextMut<ty::PolyFnSig<'tcx>> {
580 LocalTableInContextMut {
581 local_id_root: self.local_id_root,
582 data: &mut self.closure_tys
586 pub fn closure_kinds(&self) -> LocalTableInContext<(ty::ClosureKind,
587 Option<(Span, ast::Name)>)> {
588 LocalTableInContext {
589 local_id_root: self.local_id_root,
590 data: &self.closure_kinds
594 pub fn closure_kinds_mut(&mut self)
595 -> LocalTableInContextMut<(ty::ClosureKind, Option<(Span, ast::Name)>)> {
596 LocalTableInContextMut {
597 local_id_root: self.local_id_root,
598 data: &mut self.closure_kinds
602 pub fn liberated_fn_sigs(&self) -> LocalTableInContext<ty::FnSig<'tcx>> {
603 LocalTableInContext {
604 local_id_root: self.local_id_root,
605 data: &self.liberated_fn_sigs
609 pub fn liberated_fn_sigs_mut(&mut self) -> LocalTableInContextMut<ty::FnSig<'tcx>> {
610 LocalTableInContextMut {
611 local_id_root: self.local_id_root,
612 data: &mut self.liberated_fn_sigs
616 pub fn fru_field_types(&self) -> LocalTableInContext<Vec<Ty<'tcx>>> {
617 LocalTableInContext {
618 local_id_root: self.local_id_root,
619 data: &self.fru_field_types
623 pub fn fru_field_types_mut(&mut self) -> LocalTableInContextMut<Vec<Ty<'tcx>>> {
624 LocalTableInContextMut {
625 local_id_root: self.local_id_root,
626 data: &mut self.fru_field_types
630 pub fn cast_kinds(&self) -> LocalTableInContext<ty::cast::CastKind> {
631 LocalTableInContext {
632 local_id_root: self.local_id_root,
633 data: &self.cast_kinds
637 pub fn cast_kinds_mut(&mut self) -> LocalTableInContextMut<ty::cast::CastKind> {
638 LocalTableInContextMut {
639 local_id_root: self.local_id_root,
640 data: &mut self.cast_kinds
644 pub fn generator_sigs(&self)
645 -> LocalTableInContext<Option<ty::GenSig<'tcx>>>
647 LocalTableInContext {
648 local_id_root: self.local_id_root,
649 data: &self.generator_sigs,
653 pub fn generator_sigs_mut(&mut self)
654 -> LocalTableInContextMut<Option<ty::GenSig<'tcx>>>
656 LocalTableInContextMut {
657 local_id_root: self.local_id_root,
658 data: &mut self.generator_sigs,
662 pub fn generator_interiors(&self)
663 -> LocalTableInContext<ty::GeneratorInterior<'tcx>>
665 LocalTableInContext {
666 local_id_root: self.local_id_root,
667 data: &self.generator_interiors,
671 pub fn generator_interiors_mut(&mut self)
672 -> LocalTableInContextMut<ty::GeneratorInterior<'tcx>>
674 LocalTableInContextMut {
675 local_id_root: self.local_id_root,
676 data: &mut self.generator_interiors,
681 impl<'a, 'gcx, 'tcx> HashStable<StableHashingContext<'a, 'gcx, 'tcx>> for TypeckTables<'gcx> {
682 fn hash_stable<W: StableHasherResult>(&self,
683 hcx: &mut StableHashingContext<'a, 'gcx, 'tcx>,
684 hasher: &mut StableHasher<W>) {
685 let ty::TypeckTables {
687 ref type_dependent_defs,
691 ref pat_binding_modes,
692 ref upvar_capture_map,
695 ref liberated_fn_sigs,
700 ref used_trait_imports,
704 ref generator_interiors,
707 hcx.with_node_id_hashing_mode(NodeIdHashingMode::HashDefPath, |hcx| {
708 ich::hash_stable_itemlocalmap(hcx, hasher, type_dependent_defs);
709 ich::hash_stable_itemlocalmap(hcx, hasher, node_types);
710 ich::hash_stable_itemlocalmap(hcx, hasher, node_substs);
711 ich::hash_stable_itemlocalmap(hcx, hasher, adjustments);
712 ich::hash_stable_itemlocalmap(hcx, hasher, pat_binding_modes);
713 ich::hash_stable_hashmap(hcx, hasher, upvar_capture_map, |hcx, up_var_id| {
720 local_id_root.expect("trying to hash invalid TypeckTables");
722 let var_def_id = DefId {
723 krate: local_id_root.krate,
726 let closure_def_id = DefId {
727 krate: local_id_root.krate,
728 index: closure_expr_id,
730 (hcx.def_path_hash(var_def_id), hcx.def_path_hash(closure_def_id))
733 ich::hash_stable_itemlocalmap(hcx, hasher, closure_tys);
734 ich::hash_stable_itemlocalmap(hcx, hasher, closure_kinds);
735 ich::hash_stable_itemlocalmap(hcx, hasher, liberated_fn_sigs);
736 ich::hash_stable_itemlocalmap(hcx, hasher, fru_field_types);
737 ich::hash_stable_itemlocalmap(hcx, hasher, cast_kinds);
738 ich::hash_stable_itemlocalmap(hcx, hasher, generator_sigs);
739 ich::hash_stable_itemlocalmap(hcx, hasher, generator_interiors);
741 ich::hash_stable_hashset(hcx, hasher, used_trait_imports, |hcx, def_id| {
742 hcx.def_path_hash(*def_id)
745 tainted_by_errors.hash_stable(hcx, hasher);
746 free_region_map.hash_stable(hcx, hasher);
751 impl<'tcx> CommonTypes<'tcx> {
752 fn new(interners: &CtxtInterners<'tcx>) -> CommonTypes<'tcx> {
753 let mk = |sty| interners.intern_ty(sty, None);
754 let mk_region = |r| {
755 if let Some(r) = interners.region.borrow().get(&r) {
758 let r = interners.arena.alloc(r);
759 interners.region.borrow_mut().insert(Interned(r));
767 isize: mk(TyInt(ast::IntTy::Is)),
768 i8: mk(TyInt(ast::IntTy::I8)),
769 i16: mk(TyInt(ast::IntTy::I16)),
770 i32: mk(TyInt(ast::IntTy::I32)),
771 i64: mk(TyInt(ast::IntTy::I64)),
772 i128: mk(TyInt(ast::IntTy::I128)),
773 usize: mk(TyUint(ast::UintTy::Us)),
774 u8: mk(TyUint(ast::UintTy::U8)),
775 u16: mk(TyUint(ast::UintTy::U16)),
776 u32: mk(TyUint(ast::UintTy::U32)),
777 u64: mk(TyUint(ast::UintTy::U64)),
778 u128: mk(TyUint(ast::UintTy::U128)),
779 f32: mk(TyFloat(ast::FloatTy::F32)),
780 f64: mk(TyFloat(ast::FloatTy::F64)),
782 re_empty: mk_region(RegionKind::ReEmpty),
783 re_static: mk_region(RegionKind::ReStatic),
784 re_erased: mk_region(RegionKind::ReErased),
789 /// The data structure to keep track of all the information that typechecker
790 /// generates so that so that it can be reused and doesn't have to be redone
792 #[derive(Copy, Clone)]
793 pub struct TyCtxt<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
794 gcx: &'a GlobalCtxt<'gcx>,
795 interners: &'a CtxtInterners<'tcx>
798 impl<'a, 'gcx, 'tcx> Deref for TyCtxt<'a, 'gcx, 'tcx> {
799 type Target = &'a GlobalCtxt<'gcx>;
800 fn deref(&self) -> &Self::Target {
805 pub struct GlobalCtxt<'tcx> {
806 global_arenas: &'tcx GlobalArenas<'tcx>,
807 global_interners: CtxtInterners<'tcx>,
809 pub sess: &'tcx Session,
811 pub specializes_cache: RefCell<traits::SpecializesCache>,
813 pub trans_trait_caches: traits::trans::TransTraitCaches<'tcx>,
815 pub dep_graph: DepGraph,
817 /// Common types, pre-interned for your convenience.
818 pub types: CommonTypes<'tcx>,
820 /// Map indicating what traits are in scope for places where this
821 /// is relevant; generated by resolve.
822 pub trait_map: TraitMap,
824 /// Export map produced by name resolution.
825 pub export_map: ExportMap,
827 pub named_region_map: resolve_lifetime::NamedRegionMap,
829 pub hir: hir_map::Map<'tcx>,
831 /// A map from DefPathHash -> DefId. Includes DefIds from the local crate
832 /// as well as all upstream crates. Only populated in incremental mode.
833 pub def_path_hash_to_def_id: Option<FxHashMap<DefPathHash, DefId>>,
835 pub maps: maps::Maps<'tcx>,
837 pub mir_passes: Rc<Passes>,
839 // Records the free variables refrenced by every closure
840 // expression. Do not track deps for this, just recompute it from
841 // scratch every time.
842 pub freevars: RefCell<FreevarMap>,
844 pub maybe_unused_trait_imports: NodeSet,
846 pub maybe_unused_extern_crates: Vec<(NodeId, Span)>,
848 // Internal cache for metadata decoding. No need to track deps on this.
849 pub rcache: RefCell<FxHashMap<ty::CReaderCacheKey, Ty<'tcx>>>,
851 // FIXME dep tracking -- should be harmless enough
852 pub normalized_cache: RefCell<FxHashMap<Ty<'tcx>, Ty<'tcx>>>,
854 pub inhabitedness_cache: RefCell<FxHashMap<Ty<'tcx>, DefIdForest>>,
856 pub lang_items: middle::lang_items::LanguageItems,
858 /// Set of nodes which mark locals as mutable which end up getting used at
859 /// some point. Local variable definitions not in this set can be warned
861 pub used_mut_nodes: RefCell<NodeSet>,
863 /// Maps any item's def-id to its stability index.
864 pub stability: RefCell<stability::Index<'tcx>>,
866 /// Caches the results of trait selection. This cache is used
867 /// for things that do not have to do with the parameters in scope.
868 pub selection_cache: traits::SelectionCache<'tcx>,
870 /// Caches the results of trait evaluation. This cache is used
871 /// for things that do not have to do with the parameters in scope.
872 /// Merge this with `selection_cache`?
873 pub evaluation_cache: traits::EvaluationCache<'tcx>,
875 /// Maps Expr NodeId's to `true` iff `&expr` can have 'static lifetime.
876 pub rvalue_promotable_to_static: RefCell<NodeMap<bool>>,
878 /// The definite name of the current crate after taking into account
879 /// attributes, commandline parameters, etc.
880 pub crate_name: Symbol,
882 /// Data layout specification for the current target.
883 pub data_layout: TargetDataLayout,
885 /// Used to prevent layout from recursing too deeply.
886 pub layout_depth: Cell<usize>,
888 /// Map from function to the `#[derive]` mode that it's defining. Only used
889 /// by `proc-macro` crates.
890 pub derive_macros: RefCell<NodeMap<Symbol>>,
892 stability_interner: RefCell<FxHashSet<&'tcx attr::Stability>>,
894 layout_interner: RefCell<FxHashSet<&'tcx Layout>>,
896 /// A vector of every trait accessible in the whole crate
897 /// (i.e. including those from subcrates). This is used only for
898 /// error reporting, and so is lazily initialized and generally
899 /// shouldn't taint the common path (hence the RefCell).
900 pub all_traits: RefCell<Option<Vec<DefId>>>,
903 impl<'tcx> GlobalCtxt<'tcx> {
904 /// Get the global TyCtxt.
905 pub fn global_tcx<'a>(&'a self) -> TyCtxt<'a, 'tcx, 'tcx> {
908 interners: &self.global_interners
913 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
914 pub fn crate_name(self, cnum: CrateNum) -> Symbol {
915 if cnum == LOCAL_CRATE {
918 self.sess.cstore.crate_name(cnum)
922 pub fn original_crate_name(self, cnum: CrateNum) -> Symbol {
923 if cnum == LOCAL_CRATE {
924 self.crate_name.clone()
926 self.sess.cstore.original_crate_name(cnum)
930 pub fn crate_disambiguator(self, cnum: CrateNum) -> Symbol {
931 if cnum == LOCAL_CRATE {
932 self.sess.local_crate_disambiguator()
934 self.sess.cstore.crate_disambiguator(cnum)
938 pub fn alloc_generics(self, generics: ty::Generics) -> &'gcx ty::Generics {
939 self.global_arenas.generics.alloc(generics)
942 pub fn alloc_steal_mir(self, mir: Mir<'gcx>) -> &'gcx Steal<Mir<'gcx>> {
943 self.global_arenas.steal_mir.alloc(Steal::new(mir))
946 pub fn alloc_mir(self, mir: Mir<'gcx>) -> &'gcx Mir<'gcx> {
947 self.global_arenas.mir.alloc(mir)
950 pub fn alloc_tables(self, tables: ty::TypeckTables<'gcx>) -> &'gcx ty::TypeckTables<'gcx> {
951 self.global_arenas.tables.alloc(tables)
954 pub fn alloc_trait_def(self, def: ty::TraitDef) -> &'gcx ty::TraitDef {
955 self.global_arenas.trait_def.alloc(def)
958 pub fn alloc_adt_def(self,
961 variants: Vec<ty::VariantDef>,
963 -> &'gcx ty::AdtDef {
964 let def = ty::AdtDef::new(self, did, kind, variants, repr);
965 self.global_arenas.adt_def.alloc(def)
968 pub fn intern_stability(self, stab: attr::Stability) -> &'gcx attr::Stability {
969 if let Some(st) = self.stability_interner.borrow().get(&stab) {
973 let interned = self.global_interners.arena.alloc(stab);
974 if let Some(prev) = self.stability_interner.borrow_mut().replace(interned) {
975 bug!("Tried to overwrite interned Stability: {:?}", prev)
980 pub fn intern_layout(self, layout: Layout) -> &'gcx Layout {
981 if let Some(layout) = self.layout_interner.borrow().get(&layout) {
985 let interned = self.global_arenas.layout.alloc(layout);
986 if let Some(prev) = self.layout_interner.borrow_mut().replace(interned) {
987 bug!("Tried to overwrite interned Layout: {:?}", prev)
992 pub fn lift<T: ?Sized + Lift<'tcx>>(self, value: &T) -> Option<T::Lifted> {
993 value.lift_to_tcx(self)
996 /// Like lift, but only tries in the global tcx.
997 pub fn lift_to_global<T: ?Sized + Lift<'gcx>>(self, value: &T) -> Option<T::Lifted> {
998 value.lift_to_tcx(self.global_tcx())
1001 /// Returns true if self is the same as self.global_tcx().
1002 fn is_global(self) -> bool {
1003 let local = self.interners as *const _;
1004 let global = &self.global_interners as *const _;
1005 local as usize == global as usize
1008 /// Create a type context and call the closure with a `TyCtxt` reference
1009 /// to the context. The closure enforces that the type context and any interned
1010 /// value (types, substs, etc.) can only be used while `ty::tls` has a valid
1011 /// reference to the context, to allow formatting values that need it.
1012 pub fn create_and_enter<F, R>(s: &'tcx Session,
1013 local_providers: ty::maps::Providers<'tcx>,
1014 extern_providers: ty::maps::Providers<'tcx>,
1015 mir_passes: Rc<Passes>,
1016 arenas: &'tcx GlobalArenas<'tcx>,
1017 arena: &'tcx DroplessArena,
1018 resolutions: ty::Resolutions,
1019 named_region_map: resolve_lifetime::NamedRegionMap,
1020 hir: hir_map::Map<'tcx>,
1021 lang_items: middle::lang_items::LanguageItems,
1022 stability: stability::Index<'tcx>,
1025 where F: for<'b> FnOnce(TyCtxt<'b, 'tcx, 'tcx>) -> R
1027 let data_layout = TargetDataLayout::parse(s);
1028 let interners = CtxtInterners::new(arena);
1029 let common_types = CommonTypes::new(&interners);
1030 let dep_graph = hir.dep_graph.clone();
1031 let max_cnum = s.cstore.crates().iter().map(|c| c.as_usize()).max().unwrap_or(0);
1032 let mut providers = IndexVec::from_elem_n(extern_providers, max_cnum + 1);
1033 providers[LOCAL_CRATE] = local_providers;
1035 let def_path_hash_to_def_id = if s.opts.build_dep_graph() {
1036 let upstream_def_path_tables: Vec<(CrateNum, Rc<_>)> = s
1040 .map(|&cnum| (cnum, s.cstore.def_path_table(cnum)))
1043 let def_path_tables = || {
1044 upstream_def_path_tables
1046 .map(|&(cnum, ref rc)| (cnum, &**rc))
1047 .chain(iter::once((LOCAL_CRATE, hir.definitions().def_path_table())))
1050 // Precompute the capacity of the hashmap so we don't have to
1051 // re-allocate when populating it.
1052 let capacity = def_path_tables().map(|(_, t)| t.size()).sum::<usize>();
1054 let mut map: FxHashMap<_, _> = FxHashMap::with_capacity_and_hasher(
1056 ::std::default::Default::default()
1059 for (cnum, def_path_table) in def_path_tables() {
1060 def_path_table.add_def_path_hashes_to(cnum, &mut map);
1068 tls::enter_global(GlobalCtxt {
1070 trans_trait_caches: traits::trans::TransTraitCaches::new(dep_graph.clone()),
1071 specializes_cache: RefCell::new(traits::SpecializesCache::new()),
1072 global_arenas: arenas,
1073 global_interners: interners,
1074 dep_graph: dep_graph.clone(),
1075 types: common_types,
1077 trait_map: resolutions.trait_map,
1078 export_map: resolutions.export_map,
1080 def_path_hash_to_def_id,
1081 maps: maps::Maps::new(providers),
1083 freevars: RefCell::new(resolutions.freevars),
1084 maybe_unused_trait_imports: resolutions.maybe_unused_trait_imports,
1085 maybe_unused_extern_crates: resolutions.maybe_unused_extern_crates,
1086 rcache: RefCell::new(FxHashMap()),
1087 normalized_cache: RefCell::new(FxHashMap()),
1088 inhabitedness_cache: RefCell::new(FxHashMap()),
1090 used_mut_nodes: RefCell::new(NodeSet()),
1091 stability: RefCell::new(stability),
1092 selection_cache: traits::SelectionCache::new(),
1093 evaluation_cache: traits::EvaluationCache::new(),
1094 rvalue_promotable_to_static: RefCell::new(NodeMap()),
1095 crate_name: Symbol::intern(crate_name),
1097 layout_interner: RefCell::new(FxHashSet()),
1098 layout_depth: Cell::new(0),
1099 derive_macros: RefCell::new(NodeMap()),
1100 stability_interner: RefCell::new(FxHashSet()),
1101 all_traits: RefCell::new(None),
1105 pub fn consider_optimizing<T: Fn() -> String>(&self, msg: T) -> bool {
1106 let cname = self.crate_name(LOCAL_CRATE).as_str();
1107 self.sess.consider_optimizing(&cname, msg)
1111 impl<'gcx: 'tcx, 'tcx> GlobalCtxt<'gcx> {
1112 /// Call the closure with a local `TyCtxt` using the given arena.
1113 pub fn enter_local<F, R>(&self, arena: &'tcx DroplessArena, f: F) -> R
1114 where F: for<'a> FnOnce(TyCtxt<'a, 'gcx, 'tcx>) -> R
1116 let interners = CtxtInterners::new(arena);
1117 tls::enter(self, &interners, f)
1121 /// A trait implemented for all X<'a> types which can be safely and
1122 /// efficiently converted to X<'tcx> as long as they are part of the
1123 /// provided TyCtxt<'tcx>.
1124 /// This can be done, for example, for Ty<'tcx> or &'tcx Substs<'tcx>
1125 /// by looking them up in their respective interners.
1127 /// However, this is still not the best implementation as it does
1128 /// need to compare the components, even for interned values.
1129 /// It would be more efficient if TypedArena provided a way to
1130 /// determine whether the address is in the allocated range.
1132 /// None is returned if the value or one of the components is not part
1133 /// of the provided context.
1134 /// For Ty, None can be returned if either the type interner doesn't
1135 /// contain the TypeVariants key or if the address of the interned
1136 /// pointer differs. The latter case is possible if a primitive type,
1137 /// e.g. `()` or `u8`, was interned in a different context.
1138 pub trait Lift<'tcx> {
1140 fn lift_to_tcx<'a, 'gcx>(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Option<Self::Lifted>;
1143 impl<'a, 'tcx> Lift<'tcx> for ty::ParamEnv<'a> {
1144 type Lifted = ty::ParamEnv<'tcx>;
1145 fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>) -> Option<ty::ParamEnv<'tcx>> {
1146 self.caller_bounds.lift_to_tcx(tcx).and_then(|caller_bounds| {
1148 reveal: self.reveal,
1155 impl<'a, 'tcx> Lift<'tcx> for Ty<'a> {
1156 type Lifted = Ty<'tcx>;
1157 fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>) -> Option<Ty<'tcx>> {
1158 if tcx.interners.arena.in_arena(*self as *const _) {
1159 return Some(unsafe { mem::transmute(*self) });
1161 // Also try in the global tcx if we're not that.
1162 if !tcx.is_global() {
1163 self.lift_to_tcx(tcx.global_tcx())
1170 impl<'a, 'tcx> Lift<'tcx> for &'a Substs<'a> {
1171 type Lifted = &'tcx Substs<'tcx>;
1172 fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>) -> Option<&'tcx Substs<'tcx>> {
1173 if self.len() == 0 {
1174 return Some(Slice::empty());
1176 if tcx.interners.arena.in_arena(&self[..] as *const _) {
1177 return Some(unsafe { mem::transmute(*self) });
1179 // Also try in the global tcx if we're not that.
1180 if !tcx.is_global() {
1181 self.lift_to_tcx(tcx.global_tcx())
1188 impl<'a, 'tcx> Lift<'tcx> for Region<'a> {
1189 type Lifted = Region<'tcx>;
1190 fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>) -> Option<Region<'tcx>> {
1191 if tcx.interners.arena.in_arena(*self as *const _) {
1192 return Some(unsafe { mem::transmute(*self) });
1194 // Also try in the global tcx if we're not that.
1195 if !tcx.is_global() {
1196 self.lift_to_tcx(tcx.global_tcx())
1203 impl<'a, 'tcx> Lift<'tcx> for &'a Slice<Ty<'a>> {
1204 type Lifted = &'tcx Slice<Ty<'tcx>>;
1205 fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>)
1206 -> Option<&'tcx Slice<Ty<'tcx>>> {
1207 if self.len() == 0 {
1208 return Some(Slice::empty());
1210 if tcx.interners.arena.in_arena(*self as *const _) {
1211 return Some(unsafe { mem::transmute(*self) });
1213 // Also try in the global tcx if we're not that.
1214 if !tcx.is_global() {
1215 self.lift_to_tcx(tcx.global_tcx())
1222 impl<'a, 'tcx> Lift<'tcx> for &'a Slice<ExistentialPredicate<'a>> {
1223 type Lifted = &'tcx Slice<ExistentialPredicate<'tcx>>;
1224 fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>)
1225 -> Option<&'tcx Slice<ExistentialPredicate<'tcx>>> {
1226 if self.is_empty() {
1227 return Some(Slice::empty());
1229 if tcx.interners.arena.in_arena(*self as *const _) {
1230 return Some(unsafe { mem::transmute(*self) });
1232 // Also try in the global tcx if we're not that.
1233 if !tcx.is_global() {
1234 self.lift_to_tcx(tcx.global_tcx())
1241 impl<'a, 'tcx> Lift<'tcx> for &'a Slice<Predicate<'a>> {
1242 type Lifted = &'tcx Slice<Predicate<'tcx>>;
1243 fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>)
1244 -> Option<&'tcx Slice<Predicate<'tcx>>> {
1245 if self.is_empty() {
1246 return Some(Slice::empty());
1248 if tcx.interners.arena.in_arena(*self as *const _) {
1249 return Some(unsafe { mem::transmute(*self) });
1251 // Also try in the global tcx if we're not that.
1252 if !tcx.is_global() {
1253 self.lift_to_tcx(tcx.global_tcx())
1261 use super::{CtxtInterners, GlobalCtxt, TyCtxt};
1263 use std::cell::Cell;
1267 /// Marker types used for the scoped TLS slot.
1268 /// The type context cannot be used directly because the scoped TLS
1269 /// in libstd doesn't allow types generic over lifetimes.
1270 enum ThreadLocalGlobalCtxt {}
1271 enum ThreadLocalInterners {}
1274 static TLS_TCX: Cell<Option<(*const ThreadLocalGlobalCtxt,
1275 *const ThreadLocalInterners)>> = Cell::new(None)
1278 fn span_debug(span: syntax_pos::Span, f: &mut fmt::Formatter) -> fmt::Result {
1280 write!(f, "{}", tcx.sess.codemap().span_to_string(span))
1284 pub fn enter_global<'gcx, F, R>(gcx: GlobalCtxt<'gcx>, f: F) -> R
1285 where F: for<'a> FnOnce(TyCtxt<'a, 'gcx, 'gcx>) -> R
1287 syntax_pos::SPAN_DEBUG.with(|span_dbg| {
1288 let original_span_debug = span_dbg.get();
1289 span_dbg.set(span_debug);
1290 let result = enter(&gcx, &gcx.global_interners, f);
1291 span_dbg.set(original_span_debug);
1296 pub fn enter<'a, 'gcx: 'tcx, 'tcx, F, R>(gcx: &'a GlobalCtxt<'gcx>,
1297 interners: &'a CtxtInterners<'tcx>,
1299 where F: FnOnce(TyCtxt<'a, 'gcx, 'tcx>) -> R
1301 let gcx_ptr = gcx as *const _ as *const ThreadLocalGlobalCtxt;
1302 let interners_ptr = interners as *const _ as *const ThreadLocalInterners;
1303 TLS_TCX.with(|tls| {
1304 let prev = tls.get();
1305 tls.set(Some((gcx_ptr, interners_ptr)));
1306 let ret = f(TyCtxt {
1315 pub fn with<F, R>(f: F) -> R
1316 where F: for<'a, 'gcx, 'tcx> FnOnce(TyCtxt<'a, 'gcx, 'tcx>) -> R
1318 TLS_TCX.with(|tcx| {
1319 let (gcx, interners) = tcx.get().unwrap();
1320 let gcx = unsafe { &*(gcx as *const GlobalCtxt) };
1321 let interners = unsafe { &*(interners as *const CtxtInterners) };
1329 pub fn with_opt<F, R>(f: F) -> R
1330 where F: for<'a, 'gcx, 'tcx> FnOnce(Option<TyCtxt<'a, 'gcx, 'tcx>>) -> R
1332 if TLS_TCX.with(|tcx| tcx.get().is_some()) {
1333 with(|v| f(Some(v)))
1340 macro_rules! sty_debug_print {
1341 ($ctxt: expr, $($variant: ident),*) => {{
1342 // curious inner module to allow variant names to be used as
1344 #[allow(non_snake_case)]
1346 use ty::{self, TyCtxt};
1347 use ty::context::Interned;
1349 #[derive(Copy, Clone)]
1352 region_infer: usize,
1357 pub fn go(tcx: TyCtxt) {
1358 let mut total = DebugStat {
1360 region_infer: 0, ty_infer: 0, both_infer: 0,
1362 $(let mut $variant = total;)*
1365 for &Interned(t) in tcx.interners.type_.borrow().iter() {
1366 let variant = match t.sty {
1367 ty::TyBool | ty::TyChar | ty::TyInt(..) | ty::TyUint(..) |
1368 ty::TyFloat(..) | ty::TyStr | ty::TyNever => continue,
1369 ty::TyError => /* unimportant */ continue,
1370 $(ty::$variant(..) => &mut $variant,)*
1372 let region = t.flags.intersects(ty::TypeFlags::HAS_RE_INFER);
1373 let ty = t.flags.intersects(ty::TypeFlags::HAS_TY_INFER);
1377 if region { total.region_infer += 1; variant.region_infer += 1 }
1378 if ty { total.ty_infer += 1; variant.ty_infer += 1 }
1379 if region && ty { total.both_infer += 1; variant.both_infer += 1 }
1381 println!("Ty interner total ty region both");
1382 $(println!(" {:18}: {uses:6} {usespc:4.1}%, \
1383 {ty:4.1}% {region:5.1}% {both:4.1}%",
1384 stringify!($variant),
1385 uses = $variant.total,
1386 usespc = $variant.total as f64 * 100.0 / total.total as f64,
1387 ty = $variant.ty_infer as f64 * 100.0 / total.total as f64,
1388 region = $variant.region_infer as f64 * 100.0 / total.total as f64,
1389 both = $variant.both_infer as f64 * 100.0 / total.total as f64);
1391 println!(" total {uses:6} \
1392 {ty:4.1}% {region:5.1}% {both:4.1}%",
1394 ty = total.ty_infer as f64 * 100.0 / total.total as f64,
1395 region = total.region_infer as f64 * 100.0 / total.total as f64,
1396 both = total.both_infer as f64 * 100.0 / total.total as f64)
1404 impl<'a, 'tcx> TyCtxt<'a, 'tcx, 'tcx> {
1405 pub fn print_debug_stats(self) {
1408 TyAdt, TyArray, TySlice, TyRawPtr, TyRef, TyFnDef, TyFnPtr, TyGenerator,
1409 TyDynamic, TyClosure, TyTuple, TyParam, TyInfer, TyProjection, TyAnon);
1411 println!("Substs interner: #{}", self.interners.substs.borrow().len());
1412 println!("Region interner: #{}", self.interners.region.borrow().len());
1413 println!("Stability interner: #{}", self.stability_interner.borrow().len());
1414 println!("Layout interner: #{}", self.layout_interner.borrow().len());
1419 /// An entry in an interner.
1420 struct Interned<'tcx, T: 'tcx+?Sized>(&'tcx T);
1422 // NB: An Interned<Ty> compares and hashes as a sty.
1423 impl<'tcx> PartialEq for Interned<'tcx, TyS<'tcx>> {
1424 fn eq(&self, other: &Interned<'tcx, TyS<'tcx>>) -> bool {
1425 self.0.sty == other.0.sty
1429 impl<'tcx> Eq for Interned<'tcx, TyS<'tcx>> {}
1431 impl<'tcx> Hash for Interned<'tcx, TyS<'tcx>> {
1432 fn hash<H: Hasher>(&self, s: &mut H) {
1437 impl<'tcx: 'lcx, 'lcx> Borrow<TypeVariants<'lcx>> for Interned<'tcx, TyS<'tcx>> {
1438 fn borrow<'a>(&'a self) -> &'a TypeVariants<'lcx> {
1443 // NB: An Interned<Slice<T>> compares and hashes as its elements.
1444 impl<'tcx, T: PartialEq> PartialEq for Interned<'tcx, Slice<T>> {
1445 fn eq(&self, other: &Interned<'tcx, Slice<T>>) -> bool {
1446 self.0[..] == other.0[..]
1450 impl<'tcx, T: Eq> Eq for Interned<'tcx, Slice<T>> {}
1452 impl<'tcx, T: Hash> Hash for Interned<'tcx, Slice<T>> {
1453 fn hash<H: Hasher>(&self, s: &mut H) {
1458 impl<'tcx: 'lcx, 'lcx> Borrow<[Ty<'lcx>]> for Interned<'tcx, Slice<Ty<'tcx>>> {
1459 fn borrow<'a>(&'a self) -> &'a [Ty<'lcx>] {
1464 impl<'tcx: 'lcx, 'lcx> Borrow<[Kind<'lcx>]> for Interned<'tcx, Substs<'tcx>> {
1465 fn borrow<'a>(&'a self) -> &'a [Kind<'lcx>] {
1470 impl<'tcx> Borrow<RegionKind> for Interned<'tcx, RegionKind> {
1471 fn borrow<'a>(&'a self) -> &'a RegionKind {
1476 impl<'tcx: 'lcx, 'lcx> Borrow<[ExistentialPredicate<'lcx>]>
1477 for Interned<'tcx, Slice<ExistentialPredicate<'tcx>>> {
1478 fn borrow<'a>(&'a self) -> &'a [ExistentialPredicate<'lcx>] {
1483 impl<'tcx: 'lcx, 'lcx> Borrow<[Predicate<'lcx>]>
1484 for Interned<'tcx, Slice<Predicate<'tcx>>> {
1485 fn borrow<'a>(&'a self) -> &'a [Predicate<'lcx>] {
1490 macro_rules! intern_method {
1491 ($lt_tcx:tt, $name:ident: $method:ident($alloc:ty,
1492 $alloc_method:ident,
1495 $needs_infer:expr) -> $ty:ty) => {
1496 impl<'a, 'gcx, $lt_tcx> TyCtxt<'a, 'gcx, $lt_tcx> {
1497 pub fn $method(self, v: $alloc) -> &$lt_tcx $ty {
1499 let key = ($alloc_to_key)(&v);
1500 if let Some(i) = self.interners.$name.borrow().get(key) {
1503 if !self.is_global() {
1504 if let Some(i) = self.global_interners.$name.borrow().get(key) {
1510 // HACK(eddyb) Depend on flags being accurate to
1511 // determine that all contents are in the global tcx.
1512 // See comments on Lift for why we can't use that.
1513 if !($needs_infer)(&v) {
1514 if !self.is_global() {
1518 let i = ($alloc_to_ret)(self.global_interners.arena.$alloc_method(v));
1519 self.global_interners.$name.borrow_mut().insert(Interned(i));
1523 // Make sure we don't end up with inference
1524 // types/regions in the global tcx.
1525 if self.is_global() {
1526 bug!("Attempted to intern `{:?}` which contains \
1527 inference types/regions in the global type context",
1532 let i = ($alloc_to_ret)(self.interners.arena.$alloc_method(v));
1533 self.interners.$name.borrow_mut().insert(Interned(i));
1540 macro_rules! direct_interners {
1541 ($lt_tcx:tt, $($name:ident: $method:ident($needs_infer:expr) -> $ty:ty),+) => {
1542 $(impl<$lt_tcx> PartialEq for Interned<$lt_tcx, $ty> {
1543 fn eq(&self, other: &Self) -> bool {
1548 impl<$lt_tcx> Eq for Interned<$lt_tcx, $ty> {}
1550 impl<$lt_tcx> Hash for Interned<$lt_tcx, $ty> {
1551 fn hash<H: Hasher>(&self, s: &mut H) {
1556 intern_method!($lt_tcx, $name: $method($ty, alloc, |x| x, |x| x, $needs_infer) -> $ty);)+
1560 pub fn keep_local<'tcx, T: ty::TypeFoldable<'tcx>>(x: &T) -> bool {
1561 x.has_type_flags(ty::TypeFlags::KEEP_IN_LOCAL_TCX)
1564 direct_interners!('tcx,
1565 region: mk_region(|r| {
1567 &ty::ReVar(_) | &ty::ReSkolemized(..) => true,
1573 macro_rules! slice_interners {
1574 ($($field:ident: $method:ident($ty:ident)),+) => (
1575 $(intern_method!('tcx, $field: $method(&[$ty<'tcx>], alloc_slice, Deref::deref,
1576 |xs: &[$ty]| -> &Slice<$ty> {
1577 unsafe { mem::transmute(xs) }
1578 }, |xs: &[$ty]| xs.iter().any(keep_local)) -> Slice<$ty<'tcx>>);)+
1583 existential_predicates: _intern_existential_predicates(ExistentialPredicate),
1584 predicates: _intern_predicates(Predicate),
1585 type_list: _intern_type_list(Ty),
1586 substs: _intern_substs(Kind)
1589 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
1590 /// Create an unsafe fn ty based on a safe fn ty.
1591 pub fn safe_to_unsafe_fn_ty(self, sig: PolyFnSig<'tcx>) -> Ty<'tcx> {
1592 assert_eq!(sig.unsafety(), hir::Unsafety::Normal);
1593 self.mk_fn_ptr(sig.map_bound(|sig| ty::FnSig {
1594 unsafety: hir::Unsafety::Unsafe,
1599 // Interns a type/name combination, stores the resulting box in cx.interners,
1600 // and returns the box as cast to an unsafe ptr (see comments for Ty above).
1601 pub fn mk_ty(self, st: TypeVariants<'tcx>) -> Ty<'tcx> {
1602 let global_interners = if !self.is_global() {
1603 Some(&self.global_interners)
1607 self.interners.intern_ty(st, global_interners)
1610 pub fn mk_mach_int(self, tm: ast::IntTy) -> Ty<'tcx> {
1612 ast::IntTy::Is => self.types.isize,
1613 ast::IntTy::I8 => self.types.i8,
1614 ast::IntTy::I16 => self.types.i16,
1615 ast::IntTy::I32 => self.types.i32,
1616 ast::IntTy::I64 => self.types.i64,
1617 ast::IntTy::I128 => self.types.i128,
1621 pub fn mk_mach_uint(self, tm: ast::UintTy) -> Ty<'tcx> {
1623 ast::UintTy::Us => self.types.usize,
1624 ast::UintTy::U8 => self.types.u8,
1625 ast::UintTy::U16 => self.types.u16,
1626 ast::UintTy::U32 => self.types.u32,
1627 ast::UintTy::U64 => self.types.u64,
1628 ast::UintTy::U128 => self.types.u128,
1632 pub fn mk_mach_float(self, tm: ast::FloatTy) -> Ty<'tcx> {
1634 ast::FloatTy::F32 => self.types.f32,
1635 ast::FloatTy::F64 => self.types.f64,
1639 pub fn mk_str(self) -> Ty<'tcx> {
1643 pub fn mk_static_str(self) -> Ty<'tcx> {
1644 self.mk_imm_ref(self.types.re_static, self.mk_str())
1647 pub fn mk_adt(self, def: &'tcx AdtDef, substs: &'tcx Substs<'tcx>) -> Ty<'tcx> {
1648 // take a copy of substs so that we own the vectors inside
1649 self.mk_ty(TyAdt(def, substs))
1652 pub fn mk_box(self, ty: Ty<'tcx>) -> Ty<'tcx> {
1653 let def_id = self.require_lang_item(lang_items::OwnedBoxLangItem);
1654 let adt_def = self.adt_def(def_id);
1655 let substs = self.mk_substs(iter::once(Kind::from(ty)));
1656 self.mk_ty(TyAdt(adt_def, substs))
1659 pub fn mk_ptr(self, tm: TypeAndMut<'tcx>) -> Ty<'tcx> {
1660 self.mk_ty(TyRawPtr(tm))
1663 pub fn mk_ref(self, r: Region<'tcx>, tm: TypeAndMut<'tcx>) -> Ty<'tcx> {
1664 self.mk_ty(TyRef(r, tm))
1667 pub fn mk_mut_ref(self, r: Region<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
1668 self.mk_ref(r, TypeAndMut {ty: ty, mutbl: hir::MutMutable})
1671 pub fn mk_imm_ref(self, r: Region<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
1672 self.mk_ref(r, TypeAndMut {ty: ty, mutbl: hir::MutImmutable})
1675 pub fn mk_mut_ptr(self, ty: Ty<'tcx>) -> Ty<'tcx> {
1676 self.mk_ptr(TypeAndMut {ty: ty, mutbl: hir::MutMutable})
1679 pub fn mk_imm_ptr(self, ty: Ty<'tcx>) -> Ty<'tcx> {
1680 self.mk_ptr(TypeAndMut {ty: ty, mutbl: hir::MutImmutable})
1683 pub fn mk_nil_ptr(self) -> Ty<'tcx> {
1684 self.mk_imm_ptr(self.mk_nil())
1687 pub fn mk_array(self, ty: Ty<'tcx>, n: usize) -> Ty<'tcx> {
1688 self.mk_ty(TyArray(ty, n))
1691 pub fn mk_slice(self, ty: Ty<'tcx>) -> Ty<'tcx> {
1692 self.mk_ty(TySlice(ty))
1695 pub fn intern_tup(self, ts: &[Ty<'tcx>], defaulted: bool) -> Ty<'tcx> {
1696 self.mk_ty(TyTuple(self.intern_type_list(ts), defaulted))
1699 pub fn mk_tup<I: InternAs<[Ty<'tcx>], Ty<'tcx>>>(self, iter: I,
1700 defaulted: bool) -> I::Output {
1701 iter.intern_with(|ts| self.mk_ty(TyTuple(self.intern_type_list(ts), defaulted)))
1704 pub fn mk_nil(self) -> Ty<'tcx> {
1705 self.intern_tup(&[], false)
1708 pub fn mk_diverging_default(self) -> Ty<'tcx> {
1709 if self.sess.features.borrow().never_type {
1712 self.intern_tup(&[], true)
1716 pub fn mk_bool(self) -> Ty<'tcx> {
1720 pub fn mk_fn_def(self, def_id: DefId,
1721 substs: &'tcx Substs<'tcx>) -> Ty<'tcx> {
1722 self.mk_ty(TyFnDef(def_id, substs))
1725 pub fn mk_fn_ptr(self, fty: PolyFnSig<'tcx>) -> Ty<'tcx> {
1726 self.mk_ty(TyFnPtr(fty))
1731 obj: ty::Binder<&'tcx Slice<ExistentialPredicate<'tcx>>>,
1732 reg: ty::Region<'tcx>
1734 self.mk_ty(TyDynamic(obj, reg))
1737 pub fn mk_projection(self,
1739 substs: &'tcx Substs<'tcx>)
1741 self.mk_ty(TyProjection(ProjectionTy {
1747 pub fn mk_closure(self,
1749 substs: &'tcx Substs<'tcx>)
1751 self.mk_closure_from_closure_substs(closure_id, ClosureSubsts {
1756 pub fn mk_closure_from_closure_substs(self,
1758 closure_substs: ClosureSubsts<'tcx>)
1760 self.mk_ty(TyClosure(closure_id, closure_substs))
1763 pub fn mk_generator(self,
1765 closure_substs: ClosureSubsts<'tcx>,
1766 interior: GeneratorInterior<'tcx>)
1768 self.mk_ty(TyGenerator(id, closure_substs, interior))
1771 pub fn mk_var(self, v: TyVid) -> Ty<'tcx> {
1772 self.mk_infer(TyVar(v))
1775 pub fn mk_int_var(self, v: IntVid) -> Ty<'tcx> {
1776 self.mk_infer(IntVar(v))
1779 pub fn mk_float_var(self, v: FloatVid) -> Ty<'tcx> {
1780 self.mk_infer(FloatVar(v))
1783 pub fn mk_infer(self, it: InferTy) -> Ty<'tcx> {
1784 self.mk_ty(TyInfer(it))
1787 pub fn mk_param(self,
1789 name: Name) -> Ty<'tcx> {
1790 self.mk_ty(TyParam(ParamTy { idx: index, name: name }))
1793 pub fn mk_self_type(self) -> Ty<'tcx> {
1794 self.mk_param(0, keywords::SelfType.name())
1797 pub fn mk_param_from_def(self, def: &ty::TypeParameterDef) -> Ty<'tcx> {
1798 self.mk_param(def.index, def.name)
1801 pub fn mk_anon(self, def_id: DefId, substs: &'tcx Substs<'tcx>) -> Ty<'tcx> {
1802 self.mk_ty(TyAnon(def_id, substs))
1805 pub fn intern_existential_predicates(self, eps: &[ExistentialPredicate<'tcx>])
1806 -> &'tcx Slice<ExistentialPredicate<'tcx>> {
1807 assert!(!eps.is_empty());
1808 assert!(eps.windows(2).all(|w| w[0].cmp(self, &w[1]) != Ordering::Greater));
1809 self._intern_existential_predicates(eps)
1812 pub fn intern_predicates(self, preds: &[Predicate<'tcx>])
1813 -> &'tcx Slice<Predicate<'tcx>> {
1814 // FIXME consider asking the input slice to be sorted to avoid
1815 // re-interning permutations, in which case that would be asserted
1817 if preds.len() == 0 {
1818 // The macro-generated method below asserts we don't intern an empty slice.
1821 self._intern_predicates(preds)
1825 pub fn intern_type_list(self, ts: &[Ty<'tcx>]) -> &'tcx Slice<Ty<'tcx>> {
1829 self._intern_type_list(ts)
1833 pub fn intern_substs(self, ts: &[Kind<'tcx>]) -> &'tcx Slice<Kind<'tcx>> {
1837 self._intern_substs(ts)
1841 pub fn mk_fn_sig<I>(self,
1845 unsafety: hir::Unsafety,
1847 -> <I::Item as InternIteratorElement<Ty<'tcx>, ty::FnSig<'tcx>>>::Output
1849 I::Item: InternIteratorElement<Ty<'tcx>, ty::FnSig<'tcx>>
1851 inputs.chain(iter::once(output)).intern_with(|xs| ty::FnSig {
1852 inputs_and_output: self.intern_type_list(xs),
1853 variadic, unsafety, abi
1857 pub fn mk_existential_predicates<I: InternAs<[ExistentialPredicate<'tcx>],
1858 &'tcx Slice<ExistentialPredicate<'tcx>>>>(self, iter: I)
1860 iter.intern_with(|xs| self.intern_existential_predicates(xs))
1863 pub fn mk_predicates<I: InternAs<[Predicate<'tcx>],
1864 &'tcx Slice<Predicate<'tcx>>>>(self, iter: I)
1866 iter.intern_with(|xs| self.intern_predicates(xs))
1869 pub fn mk_type_list<I: InternAs<[Ty<'tcx>],
1870 &'tcx Slice<Ty<'tcx>>>>(self, iter: I) -> I::Output {
1871 iter.intern_with(|xs| self.intern_type_list(xs))
1874 pub fn mk_substs<I: InternAs<[Kind<'tcx>],
1875 &'tcx Slice<Kind<'tcx>>>>(self, iter: I) -> I::Output {
1876 iter.intern_with(|xs| self.intern_substs(xs))
1879 pub fn mk_substs_trait(self,
1882 -> &'tcx Substs<'tcx>
1884 self.mk_substs(iter::once(s).chain(t.into_iter().cloned()).map(Kind::from))
1887 pub fn lint_node<S: Into<MultiSpan>>(self,
1888 lint: &'static Lint,
1892 self.struct_span_lint_node(lint, id, span.into(), msg).emit()
1895 pub fn lint_node_note<S: Into<MultiSpan>>(self,
1896 lint: &'static Lint,
1901 let mut err = self.struct_span_lint_node(lint, id, span.into(), msg);
1906 pub fn lint_level_at_node(self, lint: &'static Lint, mut id: NodeId)
1907 -> (lint::Level, lint::LintSource)
1909 // Right now we insert a `with_ignore` node in the dep graph here to
1910 // ignore the fact that `lint_levels` below depends on the entire crate.
1911 // For now this'll prevent false positives of recompiling too much when
1912 // anything changes.
1914 // Once red/green incremental compilation lands we should be able to
1915 // remove this because while the crate changes often the lint level map
1916 // will change rarely.
1917 self.dep_graph.with_ignore(|| {
1918 let sets = self.lint_levels(LOCAL_CRATE);
1920 let hir_id = self.hir.definitions().node_to_hir_id(id);
1921 if let Some(pair) = sets.level_and_source(lint, hir_id) {
1924 let next = self.hir.get_parent_node(id);
1926 bug!("lint traversal reached the root of the crate");
1933 pub fn struct_span_lint_node<S: Into<MultiSpan>>(self,
1934 lint: &'static Lint,
1938 -> DiagnosticBuilder<'tcx>
1940 let (level, src) = self.lint_level_at_node(lint, id);
1941 lint::struct_lint_level(self.sess, lint, level, src, Some(span.into()), msg)
1944 pub fn struct_lint_node(self, lint: &'static Lint, id: NodeId, msg: &str)
1945 -> DiagnosticBuilder<'tcx>
1947 let (level, src) = self.lint_level_at_node(lint, id);
1948 lint::struct_lint_level(self.sess, lint, level, src, None, msg)
1952 pub trait InternAs<T: ?Sized, R> {
1954 fn intern_with<F>(self, f: F) -> Self::Output
1955 where F: FnOnce(&T) -> R;
1958 impl<I, T, R, E> InternAs<[T], R> for I
1959 where E: InternIteratorElement<T, R>,
1960 I: Iterator<Item=E> {
1961 type Output = E::Output;
1962 fn intern_with<F>(self, f: F) -> Self::Output
1963 where F: FnOnce(&[T]) -> R {
1964 E::intern_with(self, f)
1968 pub trait InternIteratorElement<T, R>: Sized {
1970 fn intern_with<I: Iterator<Item=Self>, F: FnOnce(&[T]) -> R>(iter: I, f: F) -> Self::Output;
1973 impl<T, R> InternIteratorElement<T, R> for T {
1975 fn intern_with<I: Iterator<Item=Self>, F: FnOnce(&[T]) -> R>(iter: I, f: F) -> Self::Output {
1976 f(&iter.collect::<AccumulateVec<[_; 8]>>())
1980 impl<'a, T, R> InternIteratorElement<T, R> for &'a T
1984 fn intern_with<I: Iterator<Item=Self>, F: FnOnce(&[T]) -> R>(iter: I, f: F) -> Self::Output {
1985 f(&iter.cloned().collect::<AccumulateVec<[_; 8]>>())
1989 impl<T, R, E> InternIteratorElement<T, R> for Result<T, E> {
1990 type Output = Result<R, E>;
1991 fn intern_with<I: Iterator<Item=Self>, F: FnOnce(&[T]) -> R>(iter: I, f: F) -> Self::Output {
1992 Ok(f(&iter.collect::<Result<AccumulateVec<[_; 8]>, _>>()?))