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;
17 use hir::{TraitCandidate, HirId};
18 use hir::def::{Def, Export};
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::{self, ObjectLifetimeDefault};
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 trans_trait_caches: traits::trans::TransTraitCaches<'tcx>,
813 pub dep_graph: DepGraph,
815 /// Common types, pre-interned for your convenience.
816 pub types: CommonTypes<'tcx>,
818 /// Map indicating what traits are in scope for places where this
819 /// is relevant; generated by resolve.
820 trait_map: FxHashMap<HirId, Rc<Vec<TraitCandidate>>>,
822 /// Export map produced by name resolution.
823 export_map: FxHashMap<HirId, Rc<Vec<Export>>>,
825 named_region_map: NamedRegionMap,
827 pub hir: hir_map::Map<'tcx>,
829 /// A map from DefPathHash -> DefId. Includes DefIds from the local crate
830 /// as well as all upstream crates. Only populated in incremental mode.
831 pub def_path_hash_to_def_id: Option<FxHashMap<DefPathHash, DefId>>,
833 pub maps: maps::Maps<'tcx>,
835 pub mir_passes: Rc<Passes>,
837 // Records the free variables refrenced by every closure
838 // expression. Do not track deps for this, just recompute it from
839 // scratch every time.
840 pub freevars: RefCell<FreevarMap>,
842 pub maybe_unused_trait_imports: NodeSet,
844 pub maybe_unused_extern_crates: Vec<(NodeId, Span)>,
846 // Internal cache for metadata decoding. No need to track deps on this.
847 pub rcache: RefCell<FxHashMap<ty::CReaderCacheKey, Ty<'tcx>>>,
849 // FIXME dep tracking -- should be harmless enough
850 pub normalized_cache: RefCell<FxHashMap<Ty<'tcx>, Ty<'tcx>>>,
852 pub inhabitedness_cache: RefCell<FxHashMap<Ty<'tcx>, DefIdForest>>,
854 pub lang_items: middle::lang_items::LanguageItems,
856 /// Set of nodes which mark locals as mutable which end up getting used at
857 /// some point. Local variable definitions not in this set can be warned
859 pub used_mut_nodes: RefCell<NodeSet>,
861 /// Maps any item's def-id to its stability index.
862 pub stability: RefCell<stability::Index<'tcx>>,
864 /// Caches the results of trait selection. This cache is used
865 /// for things that do not have to do with the parameters in scope.
866 pub selection_cache: traits::SelectionCache<'tcx>,
868 /// Caches the results of trait evaluation. This cache is used
869 /// for things that do not have to do with the parameters in scope.
870 /// Merge this with `selection_cache`?
871 pub evaluation_cache: traits::EvaluationCache<'tcx>,
873 /// Maps Expr NodeId's to `true` iff `&expr` can have 'static lifetime.
874 pub rvalue_promotable_to_static: RefCell<NodeMap<bool>>,
876 /// The definite name of the current crate after taking into account
877 /// attributes, commandline parameters, etc.
878 pub crate_name: Symbol,
880 /// Data layout specification for the current target.
881 pub data_layout: TargetDataLayout,
883 /// Used to prevent layout from recursing too deeply.
884 pub layout_depth: Cell<usize>,
886 /// Map from function to the `#[derive]` mode that it's defining. Only used
887 /// by `proc-macro` crates.
888 pub derive_macros: RefCell<NodeMap<Symbol>>,
890 stability_interner: RefCell<FxHashSet<&'tcx attr::Stability>>,
892 layout_interner: RefCell<FxHashSet<&'tcx Layout>>,
894 /// A vector of every trait accessible in the whole crate
895 /// (i.e. including those from subcrates). This is used only for
896 /// error reporting, and so is lazily initialized and generally
897 /// shouldn't taint the common path (hence the RefCell).
898 pub all_traits: RefCell<Option<Vec<DefId>>>,
901 impl<'tcx> GlobalCtxt<'tcx> {
902 /// Get the global TyCtxt.
903 pub fn global_tcx<'a>(&'a self) -> TyCtxt<'a, 'tcx, 'tcx> {
906 interners: &self.global_interners
911 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
912 pub fn alloc_generics(self, generics: ty::Generics) -> &'gcx ty::Generics {
913 self.global_arenas.generics.alloc(generics)
916 pub fn alloc_steal_mir(self, mir: Mir<'gcx>) -> &'gcx Steal<Mir<'gcx>> {
917 self.global_arenas.steal_mir.alloc(Steal::new(mir))
920 pub fn alloc_mir(self, mir: Mir<'gcx>) -> &'gcx Mir<'gcx> {
921 self.global_arenas.mir.alloc(mir)
924 pub fn alloc_tables(self, tables: ty::TypeckTables<'gcx>) -> &'gcx ty::TypeckTables<'gcx> {
925 self.global_arenas.tables.alloc(tables)
928 pub fn alloc_trait_def(self, def: ty::TraitDef) -> &'gcx ty::TraitDef {
929 self.global_arenas.trait_def.alloc(def)
932 pub fn alloc_adt_def(self,
935 variants: Vec<ty::VariantDef>,
937 -> &'gcx ty::AdtDef {
938 let def = ty::AdtDef::new(self, did, kind, variants, repr);
939 self.global_arenas.adt_def.alloc(def)
942 pub fn intern_stability(self, stab: attr::Stability) -> &'gcx attr::Stability {
943 if let Some(st) = self.stability_interner.borrow().get(&stab) {
947 let interned = self.global_interners.arena.alloc(stab);
948 if let Some(prev) = self.stability_interner.borrow_mut().replace(interned) {
949 bug!("Tried to overwrite interned Stability: {:?}", prev)
954 pub fn intern_layout(self, layout: Layout) -> &'gcx Layout {
955 if let Some(layout) = self.layout_interner.borrow().get(&layout) {
959 let interned = self.global_arenas.layout.alloc(layout);
960 if let Some(prev) = self.layout_interner.borrow_mut().replace(interned) {
961 bug!("Tried to overwrite interned Layout: {:?}", prev)
966 pub fn lift<T: ?Sized + Lift<'tcx>>(self, value: &T) -> Option<T::Lifted> {
967 value.lift_to_tcx(self)
970 /// Like lift, but only tries in the global tcx.
971 pub fn lift_to_global<T: ?Sized + Lift<'gcx>>(self, value: &T) -> Option<T::Lifted> {
972 value.lift_to_tcx(self.global_tcx())
975 /// Returns true if self is the same as self.global_tcx().
976 fn is_global(self) -> bool {
977 let local = self.interners as *const _;
978 let global = &self.global_interners as *const _;
979 local as usize == global as usize
982 /// Create a type context and call the closure with a `TyCtxt` reference
983 /// to the context. The closure enforces that the type context and any interned
984 /// value (types, substs, etc.) can only be used while `ty::tls` has a valid
985 /// reference to the context, to allow formatting values that need it.
986 pub fn create_and_enter<F, R>(s: &'tcx Session,
987 local_providers: ty::maps::Providers<'tcx>,
988 extern_providers: ty::maps::Providers<'tcx>,
989 mir_passes: Rc<Passes>,
990 arenas: &'tcx GlobalArenas<'tcx>,
991 arena: &'tcx DroplessArena,
992 resolutions: ty::Resolutions,
993 named_region_map: resolve_lifetime::NamedRegionMap,
994 hir: hir_map::Map<'tcx>,
995 lang_items: middle::lang_items::LanguageItems,
996 stability: stability::Index<'tcx>,
999 where F: for<'b> FnOnce(TyCtxt<'b, 'tcx, 'tcx>) -> R
1001 let data_layout = TargetDataLayout::parse(s);
1002 let interners = CtxtInterners::new(arena);
1003 let common_types = CommonTypes::new(&interners);
1004 let dep_graph = hir.dep_graph.clone();
1005 let max_cnum = s.cstore.crates().iter().map(|c| c.as_usize()).max().unwrap_or(0);
1006 let mut providers = IndexVec::from_elem_n(extern_providers, max_cnum + 1);
1007 providers[LOCAL_CRATE] = local_providers;
1009 let def_path_hash_to_def_id = if s.opts.build_dep_graph() {
1010 let upstream_def_path_tables: Vec<(CrateNum, Rc<_>)> = s
1014 .map(|&cnum| (cnum, s.cstore.def_path_table(cnum)))
1017 let def_path_tables = || {
1018 upstream_def_path_tables
1020 .map(|&(cnum, ref rc)| (cnum, &**rc))
1021 .chain(iter::once((LOCAL_CRATE, hir.definitions().def_path_table())))
1024 // Precompute the capacity of the hashmap so we don't have to
1025 // re-allocate when populating it.
1026 let capacity = def_path_tables().map(|(_, t)| t.size()).sum::<usize>();
1028 let mut map: FxHashMap<_, _> = FxHashMap::with_capacity_and_hasher(
1030 ::std::default::Default::default()
1033 for (cnum, def_path_table) in def_path_tables() {
1034 def_path_table.add_def_path_hashes_to(cnum, &mut map);
1042 tls::enter_global(GlobalCtxt {
1044 trans_trait_caches: traits::trans::TransTraitCaches::new(dep_graph.clone()),
1045 global_arenas: arenas,
1046 global_interners: interners,
1047 dep_graph: dep_graph.clone(),
1048 types: common_types,
1049 named_region_map: NamedRegionMap {
1051 named_region_map.defs
1053 .map(|(k, v)| (hir.node_to_hir_id(k), v))
1056 named_region_map.late_bound
1058 .map(|k| hir.node_to_hir_id(k))
1060 object_lifetime_defaults:
1061 named_region_map.object_lifetime_defaults
1063 .map(|(k, v)| (hir.node_to_hir_id(k), Rc::new(v)))
1066 trait_map: resolutions.trait_map.into_iter().map(|(k, v)| {
1067 (hir.node_to_hir_id(k), Rc::new(v))
1069 export_map: resolutions.export_map.into_iter().map(|(k, v)| {
1070 (hir.node_to_hir_id(k), Rc::new(v))
1073 def_path_hash_to_def_id,
1074 maps: maps::Maps::new(providers),
1076 freevars: RefCell::new(resolutions.freevars),
1077 maybe_unused_trait_imports: resolutions.maybe_unused_trait_imports,
1078 maybe_unused_extern_crates: resolutions.maybe_unused_extern_crates,
1079 rcache: RefCell::new(FxHashMap()),
1080 normalized_cache: RefCell::new(FxHashMap()),
1081 inhabitedness_cache: RefCell::new(FxHashMap()),
1083 used_mut_nodes: RefCell::new(NodeSet()),
1084 stability: RefCell::new(stability),
1085 selection_cache: traits::SelectionCache::new(),
1086 evaluation_cache: traits::EvaluationCache::new(),
1087 rvalue_promotable_to_static: RefCell::new(NodeMap()),
1088 crate_name: Symbol::intern(crate_name),
1090 layout_interner: RefCell::new(FxHashSet()),
1091 layout_depth: Cell::new(0),
1092 derive_macros: RefCell::new(NodeMap()),
1093 stability_interner: RefCell::new(FxHashSet()),
1094 all_traits: RefCell::new(None),
1098 pub fn consider_optimizing<T: Fn() -> String>(&self, msg: T) -> bool {
1099 let cname = self.crate_name(LOCAL_CRATE).as_str();
1100 self.sess.consider_optimizing(&cname, msg)
1104 impl<'gcx: 'tcx, 'tcx> GlobalCtxt<'gcx> {
1105 /// Call the closure with a local `TyCtxt` using the given arena.
1106 pub fn enter_local<F, R>(&self, arena: &'tcx DroplessArena, f: F) -> R
1107 where F: for<'a> FnOnce(TyCtxt<'a, 'gcx, 'tcx>) -> R
1109 let interners = CtxtInterners::new(arena);
1110 tls::enter(self, &interners, f)
1114 /// A trait implemented for all X<'a> types which can be safely and
1115 /// efficiently converted to X<'tcx> as long as they are part of the
1116 /// provided TyCtxt<'tcx>.
1117 /// This can be done, for example, for Ty<'tcx> or &'tcx Substs<'tcx>
1118 /// by looking them up in their respective interners.
1120 /// However, this is still not the best implementation as it does
1121 /// need to compare the components, even for interned values.
1122 /// It would be more efficient if TypedArena provided a way to
1123 /// determine whether the address is in the allocated range.
1125 /// None is returned if the value or one of the components is not part
1126 /// of the provided context.
1127 /// For Ty, None can be returned if either the type interner doesn't
1128 /// contain the TypeVariants key or if the address of the interned
1129 /// pointer differs. The latter case is possible if a primitive type,
1130 /// e.g. `()` or `u8`, was interned in a different context.
1131 pub trait Lift<'tcx> {
1133 fn lift_to_tcx<'a, 'gcx>(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Option<Self::Lifted>;
1136 impl<'a, 'tcx> Lift<'tcx> for ty::ParamEnv<'a> {
1137 type Lifted = ty::ParamEnv<'tcx>;
1138 fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>) -> Option<ty::ParamEnv<'tcx>> {
1139 self.caller_bounds.lift_to_tcx(tcx).and_then(|caller_bounds| {
1141 reveal: self.reveal,
1148 impl<'a, 'tcx> Lift<'tcx> for Ty<'a> {
1149 type Lifted = Ty<'tcx>;
1150 fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>) -> Option<Ty<'tcx>> {
1151 if tcx.interners.arena.in_arena(*self as *const _) {
1152 return Some(unsafe { mem::transmute(*self) });
1154 // Also try in the global tcx if we're not that.
1155 if !tcx.is_global() {
1156 self.lift_to_tcx(tcx.global_tcx())
1163 impl<'a, 'tcx> Lift<'tcx> for &'a Substs<'a> {
1164 type Lifted = &'tcx Substs<'tcx>;
1165 fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>) -> Option<&'tcx Substs<'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 Region<'a> {
1182 type Lifted = Region<'tcx>;
1183 fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>) -> Option<Region<'tcx>> {
1184 if tcx.interners.arena.in_arena(*self as *const _) {
1185 return Some(unsafe { mem::transmute(*self) });
1187 // Also try in the global tcx if we're not that.
1188 if !tcx.is_global() {
1189 self.lift_to_tcx(tcx.global_tcx())
1196 impl<'a, 'tcx> Lift<'tcx> for &'a Slice<Ty<'a>> {
1197 type Lifted = &'tcx Slice<Ty<'tcx>>;
1198 fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>)
1199 -> Option<&'tcx Slice<Ty<'tcx>>> {
1200 if self.len() == 0 {
1201 return Some(Slice::empty());
1203 if tcx.interners.arena.in_arena(*self as *const _) {
1204 return Some(unsafe { mem::transmute(*self) });
1206 // Also try in the global tcx if we're not that.
1207 if !tcx.is_global() {
1208 self.lift_to_tcx(tcx.global_tcx())
1215 impl<'a, 'tcx> Lift<'tcx> for &'a Slice<ExistentialPredicate<'a>> {
1216 type Lifted = &'tcx Slice<ExistentialPredicate<'tcx>>;
1217 fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>)
1218 -> Option<&'tcx Slice<ExistentialPredicate<'tcx>>> {
1219 if self.is_empty() {
1220 return Some(Slice::empty());
1222 if tcx.interners.arena.in_arena(*self as *const _) {
1223 return Some(unsafe { mem::transmute(*self) });
1225 // Also try in the global tcx if we're not that.
1226 if !tcx.is_global() {
1227 self.lift_to_tcx(tcx.global_tcx())
1234 impl<'a, 'tcx> Lift<'tcx> for &'a Slice<Predicate<'a>> {
1235 type Lifted = &'tcx Slice<Predicate<'tcx>>;
1236 fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>)
1237 -> Option<&'tcx Slice<Predicate<'tcx>>> {
1238 if self.is_empty() {
1239 return Some(Slice::empty());
1241 if tcx.interners.arena.in_arena(*self as *const _) {
1242 return Some(unsafe { mem::transmute(*self) });
1244 // Also try in the global tcx if we're not that.
1245 if !tcx.is_global() {
1246 self.lift_to_tcx(tcx.global_tcx())
1254 use super::{CtxtInterners, GlobalCtxt, TyCtxt};
1256 use std::cell::Cell;
1260 /// Marker types used for the scoped TLS slot.
1261 /// The type context cannot be used directly because the scoped TLS
1262 /// in libstd doesn't allow types generic over lifetimes.
1263 enum ThreadLocalGlobalCtxt {}
1264 enum ThreadLocalInterners {}
1267 static TLS_TCX: Cell<Option<(*const ThreadLocalGlobalCtxt,
1268 *const ThreadLocalInterners)>> = Cell::new(None)
1271 fn span_debug(span: syntax_pos::Span, f: &mut fmt::Formatter) -> fmt::Result {
1273 write!(f, "{}", tcx.sess.codemap().span_to_string(span))
1277 pub fn enter_global<'gcx, F, R>(gcx: GlobalCtxt<'gcx>, f: F) -> R
1278 where F: for<'a> FnOnce(TyCtxt<'a, 'gcx, 'gcx>) -> R
1280 syntax_pos::SPAN_DEBUG.with(|span_dbg| {
1281 let original_span_debug = span_dbg.get();
1282 span_dbg.set(span_debug);
1283 let result = enter(&gcx, &gcx.global_interners, f);
1284 span_dbg.set(original_span_debug);
1289 pub fn enter<'a, 'gcx: 'tcx, 'tcx, F, R>(gcx: &'a GlobalCtxt<'gcx>,
1290 interners: &'a CtxtInterners<'tcx>,
1292 where F: FnOnce(TyCtxt<'a, 'gcx, 'tcx>) -> R
1294 let gcx_ptr = gcx as *const _ as *const ThreadLocalGlobalCtxt;
1295 let interners_ptr = interners as *const _ as *const ThreadLocalInterners;
1296 TLS_TCX.with(|tls| {
1297 let prev = tls.get();
1298 tls.set(Some((gcx_ptr, interners_ptr)));
1299 let ret = f(TyCtxt {
1308 pub fn with<F, R>(f: F) -> R
1309 where F: for<'a, 'gcx, 'tcx> FnOnce(TyCtxt<'a, 'gcx, 'tcx>) -> R
1311 TLS_TCX.with(|tcx| {
1312 let (gcx, interners) = tcx.get().unwrap();
1313 let gcx = unsafe { &*(gcx as *const GlobalCtxt) };
1314 let interners = unsafe { &*(interners as *const CtxtInterners) };
1322 pub fn with_opt<F, R>(f: F) -> R
1323 where F: for<'a, 'gcx, 'tcx> FnOnce(Option<TyCtxt<'a, 'gcx, 'tcx>>) -> R
1325 if TLS_TCX.with(|tcx| tcx.get().is_some()) {
1326 with(|v| f(Some(v)))
1333 macro_rules! sty_debug_print {
1334 ($ctxt: expr, $($variant: ident),*) => {{
1335 // curious inner module to allow variant names to be used as
1337 #[allow(non_snake_case)]
1339 use ty::{self, TyCtxt};
1340 use ty::context::Interned;
1342 #[derive(Copy, Clone)]
1345 region_infer: usize,
1350 pub fn go(tcx: TyCtxt) {
1351 let mut total = DebugStat {
1353 region_infer: 0, ty_infer: 0, both_infer: 0,
1355 $(let mut $variant = total;)*
1358 for &Interned(t) in tcx.interners.type_.borrow().iter() {
1359 let variant = match t.sty {
1360 ty::TyBool | ty::TyChar | ty::TyInt(..) | ty::TyUint(..) |
1361 ty::TyFloat(..) | ty::TyStr | ty::TyNever => continue,
1362 ty::TyError => /* unimportant */ continue,
1363 $(ty::$variant(..) => &mut $variant,)*
1365 let region = t.flags.intersects(ty::TypeFlags::HAS_RE_INFER);
1366 let ty = t.flags.intersects(ty::TypeFlags::HAS_TY_INFER);
1370 if region { total.region_infer += 1; variant.region_infer += 1 }
1371 if ty { total.ty_infer += 1; variant.ty_infer += 1 }
1372 if region && ty { total.both_infer += 1; variant.both_infer += 1 }
1374 println!("Ty interner total ty region both");
1375 $(println!(" {:18}: {uses:6} {usespc:4.1}%, \
1376 {ty:4.1}% {region:5.1}% {both:4.1}%",
1377 stringify!($variant),
1378 uses = $variant.total,
1379 usespc = $variant.total as f64 * 100.0 / total.total as f64,
1380 ty = $variant.ty_infer as f64 * 100.0 / total.total as f64,
1381 region = $variant.region_infer as f64 * 100.0 / total.total as f64,
1382 both = $variant.both_infer as f64 * 100.0 / total.total as f64);
1384 println!(" total {uses:6} \
1385 {ty:4.1}% {region:5.1}% {both:4.1}%",
1387 ty = total.ty_infer as f64 * 100.0 / total.total as f64,
1388 region = total.region_infer as f64 * 100.0 / total.total as f64,
1389 both = total.both_infer as f64 * 100.0 / total.total as f64)
1397 impl<'a, 'tcx> TyCtxt<'a, 'tcx, 'tcx> {
1398 pub fn print_debug_stats(self) {
1401 TyAdt, TyArray, TySlice, TyRawPtr, TyRef, TyFnDef, TyFnPtr, TyGenerator,
1402 TyDynamic, TyClosure, TyTuple, TyParam, TyInfer, TyProjection, TyAnon);
1404 println!("Substs interner: #{}", self.interners.substs.borrow().len());
1405 println!("Region interner: #{}", self.interners.region.borrow().len());
1406 println!("Stability interner: #{}", self.stability_interner.borrow().len());
1407 println!("Layout interner: #{}", self.layout_interner.borrow().len());
1412 /// An entry in an interner.
1413 struct Interned<'tcx, T: 'tcx+?Sized>(&'tcx T);
1415 // NB: An Interned<Ty> compares and hashes as a sty.
1416 impl<'tcx> PartialEq for Interned<'tcx, TyS<'tcx>> {
1417 fn eq(&self, other: &Interned<'tcx, TyS<'tcx>>) -> bool {
1418 self.0.sty == other.0.sty
1422 impl<'tcx> Eq for Interned<'tcx, TyS<'tcx>> {}
1424 impl<'tcx> Hash for Interned<'tcx, TyS<'tcx>> {
1425 fn hash<H: Hasher>(&self, s: &mut H) {
1430 impl<'tcx: 'lcx, 'lcx> Borrow<TypeVariants<'lcx>> for Interned<'tcx, TyS<'tcx>> {
1431 fn borrow<'a>(&'a self) -> &'a TypeVariants<'lcx> {
1436 // NB: An Interned<Slice<T>> compares and hashes as its elements.
1437 impl<'tcx, T: PartialEq> PartialEq for Interned<'tcx, Slice<T>> {
1438 fn eq(&self, other: &Interned<'tcx, Slice<T>>) -> bool {
1439 self.0[..] == other.0[..]
1443 impl<'tcx, T: Eq> Eq for Interned<'tcx, Slice<T>> {}
1445 impl<'tcx, T: Hash> Hash for Interned<'tcx, Slice<T>> {
1446 fn hash<H: Hasher>(&self, s: &mut H) {
1451 impl<'tcx: 'lcx, 'lcx> Borrow<[Ty<'lcx>]> for Interned<'tcx, Slice<Ty<'tcx>>> {
1452 fn borrow<'a>(&'a self) -> &'a [Ty<'lcx>] {
1457 impl<'tcx: 'lcx, 'lcx> Borrow<[Kind<'lcx>]> for Interned<'tcx, Substs<'tcx>> {
1458 fn borrow<'a>(&'a self) -> &'a [Kind<'lcx>] {
1463 impl<'tcx> Borrow<RegionKind> for Interned<'tcx, RegionKind> {
1464 fn borrow<'a>(&'a self) -> &'a RegionKind {
1469 impl<'tcx: 'lcx, 'lcx> Borrow<[ExistentialPredicate<'lcx>]>
1470 for Interned<'tcx, Slice<ExistentialPredicate<'tcx>>> {
1471 fn borrow<'a>(&'a self) -> &'a [ExistentialPredicate<'lcx>] {
1476 impl<'tcx: 'lcx, 'lcx> Borrow<[Predicate<'lcx>]>
1477 for Interned<'tcx, Slice<Predicate<'tcx>>> {
1478 fn borrow<'a>(&'a self) -> &'a [Predicate<'lcx>] {
1483 macro_rules! intern_method {
1484 ($lt_tcx:tt, $name:ident: $method:ident($alloc:ty,
1485 $alloc_method:ident,
1488 $needs_infer:expr) -> $ty:ty) => {
1489 impl<'a, 'gcx, $lt_tcx> TyCtxt<'a, 'gcx, $lt_tcx> {
1490 pub fn $method(self, v: $alloc) -> &$lt_tcx $ty {
1492 let key = ($alloc_to_key)(&v);
1493 if let Some(i) = self.interners.$name.borrow().get(key) {
1496 if !self.is_global() {
1497 if let Some(i) = self.global_interners.$name.borrow().get(key) {
1503 // HACK(eddyb) Depend on flags being accurate to
1504 // determine that all contents are in the global tcx.
1505 // See comments on Lift for why we can't use that.
1506 if !($needs_infer)(&v) {
1507 if !self.is_global() {
1511 let i = ($alloc_to_ret)(self.global_interners.arena.$alloc_method(v));
1512 self.global_interners.$name.borrow_mut().insert(Interned(i));
1516 // Make sure we don't end up with inference
1517 // types/regions in the global tcx.
1518 if self.is_global() {
1519 bug!("Attempted to intern `{:?}` which contains \
1520 inference types/regions in the global type context",
1525 let i = ($alloc_to_ret)(self.interners.arena.$alloc_method(v));
1526 self.interners.$name.borrow_mut().insert(Interned(i));
1533 macro_rules! direct_interners {
1534 ($lt_tcx:tt, $($name:ident: $method:ident($needs_infer:expr) -> $ty:ty),+) => {
1535 $(impl<$lt_tcx> PartialEq for Interned<$lt_tcx, $ty> {
1536 fn eq(&self, other: &Self) -> bool {
1541 impl<$lt_tcx> Eq for Interned<$lt_tcx, $ty> {}
1543 impl<$lt_tcx> Hash for Interned<$lt_tcx, $ty> {
1544 fn hash<H: Hasher>(&self, s: &mut H) {
1549 intern_method!($lt_tcx, $name: $method($ty, alloc, |x| x, |x| x, $needs_infer) -> $ty);)+
1553 pub fn keep_local<'tcx, T: ty::TypeFoldable<'tcx>>(x: &T) -> bool {
1554 x.has_type_flags(ty::TypeFlags::KEEP_IN_LOCAL_TCX)
1557 direct_interners!('tcx,
1558 region: mk_region(|r| {
1560 &ty::ReVar(_) | &ty::ReSkolemized(..) => true,
1566 macro_rules! slice_interners {
1567 ($($field:ident: $method:ident($ty:ident)),+) => (
1568 $(intern_method!('tcx, $field: $method(&[$ty<'tcx>], alloc_slice, Deref::deref,
1569 |xs: &[$ty]| -> &Slice<$ty> {
1570 unsafe { mem::transmute(xs) }
1571 }, |xs: &[$ty]| xs.iter().any(keep_local)) -> Slice<$ty<'tcx>>);)+
1576 existential_predicates: _intern_existential_predicates(ExistentialPredicate),
1577 predicates: _intern_predicates(Predicate),
1578 type_list: _intern_type_list(Ty),
1579 substs: _intern_substs(Kind)
1582 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
1583 /// Create an unsafe fn ty based on a safe fn ty.
1584 pub fn safe_to_unsafe_fn_ty(self, sig: PolyFnSig<'tcx>) -> Ty<'tcx> {
1585 assert_eq!(sig.unsafety(), hir::Unsafety::Normal);
1586 self.mk_fn_ptr(sig.map_bound(|sig| ty::FnSig {
1587 unsafety: hir::Unsafety::Unsafe,
1592 // Interns a type/name combination, stores the resulting box in cx.interners,
1593 // and returns the box as cast to an unsafe ptr (see comments for Ty above).
1594 pub fn mk_ty(self, st: TypeVariants<'tcx>) -> Ty<'tcx> {
1595 let global_interners = if !self.is_global() {
1596 Some(&self.global_interners)
1600 self.interners.intern_ty(st, global_interners)
1603 pub fn mk_mach_int(self, tm: ast::IntTy) -> Ty<'tcx> {
1605 ast::IntTy::Is => self.types.isize,
1606 ast::IntTy::I8 => self.types.i8,
1607 ast::IntTy::I16 => self.types.i16,
1608 ast::IntTy::I32 => self.types.i32,
1609 ast::IntTy::I64 => self.types.i64,
1610 ast::IntTy::I128 => self.types.i128,
1614 pub fn mk_mach_uint(self, tm: ast::UintTy) -> Ty<'tcx> {
1616 ast::UintTy::Us => self.types.usize,
1617 ast::UintTy::U8 => self.types.u8,
1618 ast::UintTy::U16 => self.types.u16,
1619 ast::UintTy::U32 => self.types.u32,
1620 ast::UintTy::U64 => self.types.u64,
1621 ast::UintTy::U128 => self.types.u128,
1625 pub fn mk_mach_float(self, tm: ast::FloatTy) -> Ty<'tcx> {
1627 ast::FloatTy::F32 => self.types.f32,
1628 ast::FloatTy::F64 => self.types.f64,
1632 pub fn mk_str(self) -> Ty<'tcx> {
1636 pub fn mk_static_str(self) -> Ty<'tcx> {
1637 self.mk_imm_ref(self.types.re_static, self.mk_str())
1640 pub fn mk_adt(self, def: &'tcx AdtDef, substs: &'tcx Substs<'tcx>) -> Ty<'tcx> {
1641 // take a copy of substs so that we own the vectors inside
1642 self.mk_ty(TyAdt(def, substs))
1645 pub fn mk_box(self, ty: Ty<'tcx>) -> Ty<'tcx> {
1646 let def_id = self.require_lang_item(lang_items::OwnedBoxLangItem);
1647 let adt_def = self.adt_def(def_id);
1648 let substs = self.mk_substs(iter::once(Kind::from(ty)));
1649 self.mk_ty(TyAdt(adt_def, substs))
1652 pub fn mk_ptr(self, tm: TypeAndMut<'tcx>) -> Ty<'tcx> {
1653 self.mk_ty(TyRawPtr(tm))
1656 pub fn mk_ref(self, r: Region<'tcx>, tm: TypeAndMut<'tcx>) -> Ty<'tcx> {
1657 self.mk_ty(TyRef(r, tm))
1660 pub fn mk_mut_ref(self, r: Region<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
1661 self.mk_ref(r, TypeAndMut {ty: ty, mutbl: hir::MutMutable})
1664 pub fn mk_imm_ref(self, r: Region<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
1665 self.mk_ref(r, TypeAndMut {ty: ty, mutbl: hir::MutImmutable})
1668 pub fn mk_mut_ptr(self, ty: Ty<'tcx>) -> Ty<'tcx> {
1669 self.mk_ptr(TypeAndMut {ty: ty, mutbl: hir::MutMutable})
1672 pub fn mk_imm_ptr(self, ty: Ty<'tcx>) -> Ty<'tcx> {
1673 self.mk_ptr(TypeAndMut {ty: ty, mutbl: hir::MutImmutable})
1676 pub fn mk_nil_ptr(self) -> Ty<'tcx> {
1677 self.mk_imm_ptr(self.mk_nil())
1680 pub fn mk_array(self, ty: Ty<'tcx>, n: usize) -> Ty<'tcx> {
1681 self.mk_ty(TyArray(ty, n))
1684 pub fn mk_slice(self, ty: Ty<'tcx>) -> Ty<'tcx> {
1685 self.mk_ty(TySlice(ty))
1688 pub fn intern_tup(self, ts: &[Ty<'tcx>], defaulted: bool) -> Ty<'tcx> {
1689 self.mk_ty(TyTuple(self.intern_type_list(ts), defaulted))
1692 pub fn mk_tup<I: InternAs<[Ty<'tcx>], Ty<'tcx>>>(self, iter: I,
1693 defaulted: bool) -> I::Output {
1694 iter.intern_with(|ts| self.mk_ty(TyTuple(self.intern_type_list(ts), defaulted)))
1697 pub fn mk_nil(self) -> Ty<'tcx> {
1698 self.intern_tup(&[], false)
1701 pub fn mk_diverging_default(self) -> Ty<'tcx> {
1702 if self.sess.features.borrow().never_type {
1705 self.intern_tup(&[], true)
1709 pub fn mk_bool(self) -> Ty<'tcx> {
1713 pub fn mk_fn_def(self, def_id: DefId,
1714 substs: &'tcx Substs<'tcx>) -> Ty<'tcx> {
1715 self.mk_ty(TyFnDef(def_id, substs))
1718 pub fn mk_fn_ptr(self, fty: PolyFnSig<'tcx>) -> Ty<'tcx> {
1719 self.mk_ty(TyFnPtr(fty))
1724 obj: ty::Binder<&'tcx Slice<ExistentialPredicate<'tcx>>>,
1725 reg: ty::Region<'tcx>
1727 self.mk_ty(TyDynamic(obj, reg))
1730 pub fn mk_projection(self,
1732 substs: &'tcx Substs<'tcx>)
1734 self.mk_ty(TyProjection(ProjectionTy {
1740 pub fn mk_closure(self,
1742 substs: &'tcx Substs<'tcx>)
1744 self.mk_closure_from_closure_substs(closure_id, ClosureSubsts {
1749 pub fn mk_closure_from_closure_substs(self,
1751 closure_substs: ClosureSubsts<'tcx>)
1753 self.mk_ty(TyClosure(closure_id, closure_substs))
1756 pub fn mk_generator(self,
1758 closure_substs: ClosureSubsts<'tcx>,
1759 interior: GeneratorInterior<'tcx>)
1761 self.mk_ty(TyGenerator(id, closure_substs, interior))
1764 pub fn mk_var(self, v: TyVid) -> Ty<'tcx> {
1765 self.mk_infer(TyVar(v))
1768 pub fn mk_int_var(self, v: IntVid) -> Ty<'tcx> {
1769 self.mk_infer(IntVar(v))
1772 pub fn mk_float_var(self, v: FloatVid) -> Ty<'tcx> {
1773 self.mk_infer(FloatVar(v))
1776 pub fn mk_infer(self, it: InferTy) -> Ty<'tcx> {
1777 self.mk_ty(TyInfer(it))
1780 pub fn mk_param(self,
1782 name: Name) -> Ty<'tcx> {
1783 self.mk_ty(TyParam(ParamTy { idx: index, name: name }))
1786 pub fn mk_self_type(self) -> Ty<'tcx> {
1787 self.mk_param(0, keywords::SelfType.name())
1790 pub fn mk_param_from_def(self, def: &ty::TypeParameterDef) -> Ty<'tcx> {
1791 self.mk_param(def.index, def.name)
1794 pub fn mk_anon(self, def_id: DefId, substs: &'tcx Substs<'tcx>) -> Ty<'tcx> {
1795 self.mk_ty(TyAnon(def_id, substs))
1798 pub fn intern_existential_predicates(self, eps: &[ExistentialPredicate<'tcx>])
1799 -> &'tcx Slice<ExistentialPredicate<'tcx>> {
1800 assert!(!eps.is_empty());
1801 assert!(eps.windows(2).all(|w| w[0].cmp(self, &w[1]) != Ordering::Greater));
1802 self._intern_existential_predicates(eps)
1805 pub fn intern_predicates(self, preds: &[Predicate<'tcx>])
1806 -> &'tcx Slice<Predicate<'tcx>> {
1807 // FIXME consider asking the input slice to be sorted to avoid
1808 // re-interning permutations, in which case that would be asserted
1810 if preds.len() == 0 {
1811 // The macro-generated method below asserts we don't intern an empty slice.
1814 self._intern_predicates(preds)
1818 pub fn intern_type_list(self, ts: &[Ty<'tcx>]) -> &'tcx Slice<Ty<'tcx>> {
1822 self._intern_type_list(ts)
1826 pub fn intern_substs(self, ts: &[Kind<'tcx>]) -> &'tcx Slice<Kind<'tcx>> {
1830 self._intern_substs(ts)
1834 pub fn mk_fn_sig<I>(self,
1838 unsafety: hir::Unsafety,
1840 -> <I::Item as InternIteratorElement<Ty<'tcx>, ty::FnSig<'tcx>>>::Output
1842 I::Item: InternIteratorElement<Ty<'tcx>, ty::FnSig<'tcx>>
1844 inputs.chain(iter::once(output)).intern_with(|xs| ty::FnSig {
1845 inputs_and_output: self.intern_type_list(xs),
1846 variadic, unsafety, abi
1850 pub fn mk_existential_predicates<I: InternAs<[ExistentialPredicate<'tcx>],
1851 &'tcx Slice<ExistentialPredicate<'tcx>>>>(self, iter: I)
1853 iter.intern_with(|xs| self.intern_existential_predicates(xs))
1856 pub fn mk_predicates<I: InternAs<[Predicate<'tcx>],
1857 &'tcx Slice<Predicate<'tcx>>>>(self, iter: I)
1859 iter.intern_with(|xs| self.intern_predicates(xs))
1862 pub fn mk_type_list<I: InternAs<[Ty<'tcx>],
1863 &'tcx Slice<Ty<'tcx>>>>(self, iter: I) -> I::Output {
1864 iter.intern_with(|xs| self.intern_type_list(xs))
1867 pub fn mk_substs<I: InternAs<[Kind<'tcx>],
1868 &'tcx Slice<Kind<'tcx>>>>(self, iter: I) -> I::Output {
1869 iter.intern_with(|xs| self.intern_substs(xs))
1872 pub fn mk_substs_trait(self,
1875 -> &'tcx Substs<'tcx>
1877 self.mk_substs(iter::once(s).chain(t.into_iter().cloned()).map(Kind::from))
1880 pub fn lint_node<S: Into<MultiSpan>>(self,
1881 lint: &'static Lint,
1885 self.struct_span_lint_node(lint, id, span.into(), msg).emit()
1888 pub fn lint_node_note<S: Into<MultiSpan>>(self,
1889 lint: &'static Lint,
1894 let mut err = self.struct_span_lint_node(lint, id, span.into(), msg);
1899 pub fn lint_level_at_node(self, lint: &'static Lint, mut id: NodeId)
1900 -> (lint::Level, lint::LintSource)
1902 // Right now we insert a `with_ignore` node in the dep graph here to
1903 // ignore the fact that `lint_levels` below depends on the entire crate.
1904 // For now this'll prevent false positives of recompiling too much when
1905 // anything changes.
1907 // Once red/green incremental compilation lands we should be able to
1908 // remove this because while the crate changes often the lint level map
1909 // will change rarely.
1910 self.dep_graph.with_ignore(|| {
1911 let sets = self.lint_levels(LOCAL_CRATE);
1913 let hir_id = self.hir.definitions().node_to_hir_id(id);
1914 if let Some(pair) = sets.level_and_source(lint, hir_id) {
1917 let next = self.hir.get_parent_node(id);
1919 bug!("lint traversal reached the root of the crate");
1926 pub fn struct_span_lint_node<S: Into<MultiSpan>>(self,
1927 lint: &'static Lint,
1931 -> DiagnosticBuilder<'tcx>
1933 let (level, src) = self.lint_level_at_node(lint, id);
1934 lint::struct_lint_level(self.sess, lint, level, src, Some(span.into()), msg)
1937 pub fn struct_lint_node(self, lint: &'static Lint, id: NodeId, msg: &str)
1938 -> DiagnosticBuilder<'tcx>
1940 let (level, src) = self.lint_level_at_node(lint, id);
1941 lint::struct_lint_level(self.sess, lint, level, src, None, msg)
1945 pub trait InternAs<T: ?Sized, R> {
1947 fn intern_with<F>(self, f: F) -> Self::Output
1948 where F: FnOnce(&T) -> R;
1951 impl<I, T, R, E> InternAs<[T], R> for I
1952 where E: InternIteratorElement<T, R>,
1953 I: Iterator<Item=E> {
1954 type Output = E::Output;
1955 fn intern_with<F>(self, f: F) -> Self::Output
1956 where F: FnOnce(&[T]) -> R {
1957 E::intern_with(self, f)
1961 pub trait InternIteratorElement<T, R>: Sized {
1963 fn intern_with<I: Iterator<Item=Self>, F: FnOnce(&[T]) -> R>(iter: I, f: F) -> Self::Output;
1966 impl<T, R> InternIteratorElement<T, R> for T {
1968 fn intern_with<I: Iterator<Item=Self>, F: FnOnce(&[T]) -> R>(iter: I, f: F) -> Self::Output {
1969 f(&iter.collect::<AccumulateVec<[_; 8]>>())
1973 impl<'a, T, R> InternIteratorElement<T, R> for &'a T
1977 fn intern_with<I: Iterator<Item=Self>, F: FnOnce(&[T]) -> R>(iter: I, f: F) -> Self::Output {
1978 f(&iter.cloned().collect::<AccumulateVec<[_; 8]>>())
1982 impl<T, R, E> InternIteratorElement<T, R> for Result<T, E> {
1983 type Output = Result<R, E>;
1984 fn intern_with<I: Iterator<Item=Self>, F: FnOnce(&[T]) -> R>(iter: I, f: F) -> Self::Output {
1985 Ok(f(&iter.collect::<Result<AccumulateVec<[_; 8]>, _>>()?))
1989 struct NamedRegionMap {
1990 defs: FxHashMap<HirId, resolve_lifetime::Region>,
1991 late_bound: FxHashSet<HirId>,
1992 object_lifetime_defaults: FxHashMap<HirId, Rc<Vec<ObjectLifetimeDefault>>>,
1995 pub fn provide(providers: &mut ty::maps::Providers) {
1996 providers.in_scope_traits = |tcx, id| tcx.gcx.trait_map.get(&id).cloned();
1997 providers.module_exports = |tcx, id| tcx.gcx.export_map.get(&id).cloned();
1998 providers.named_region = |tcx, id| tcx.gcx.named_region_map.defs.get(&id).cloned();
1999 providers.is_late_bound = |tcx, id| tcx.gcx.named_region_map.late_bound.contains(&id);
2000 providers.object_lifetime_defaults = |tcx, id| {
2001 tcx.gcx.named_region_map.object_lifetime_defaults.get(&id).cloned()
2003 providers.crate_name = |tcx, id| {
2004 assert_eq!(id, LOCAL_CRATE);