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};
36 use ty::{PolyFnSig, InferTy, ParamTy, ProjectionTy, ExistentialPredicate, Predicate};
38 use ty::{TyVar, TyVid, IntVar, IntVid, FloatVar, FloatVid};
39 use ty::TypeVariants::*;
40 use ty::layout::{Layout, TargetDataLayout};
41 use ty::inhabitedness::DefIdForest;
45 use util::nodemap::{NodeMap, NodeSet, DefIdSet, ItemLocalMap};
46 use util::nodemap::{FxHashMap, FxHashSet};
47 use rustc_data_structures::accumulate_vec::AccumulateVec;
48 use rustc_data_structures::stable_hasher::{HashStable, StableHasher,
51 use arena::{TypedArena, DroplessArena};
52 use rustc_data_structures::indexed_vec::IndexVec;
53 use std::borrow::Borrow;
54 use std::cell::{Cell, RefCell};
55 use std::cmp::Ordering;
56 use std::collections::hash_map::{self, Entry};
57 use std::hash::{Hash, Hasher};
63 use syntax::ast::{self, Name, NodeId};
65 use syntax::codemap::MultiSpan;
66 use syntax::symbol::{Symbol, keywords};
72 pub struct GlobalArenas<'tcx> {
74 layout: TypedArena<Layout>,
77 generics: TypedArena<ty::Generics>,
78 trait_def: TypedArena<ty::TraitDef>,
79 adt_def: TypedArena<ty::AdtDef>,
80 steal_mir: TypedArena<Steal<Mir<'tcx>>>,
81 mir: TypedArena<Mir<'tcx>>,
82 tables: TypedArena<ty::TypeckTables<'tcx>>,
85 impl<'tcx> GlobalArenas<'tcx> {
86 pub fn new() -> GlobalArenas<'tcx> {
88 layout: TypedArena::new(),
89 generics: TypedArena::new(),
90 trait_def: TypedArena::new(),
91 adt_def: TypedArena::new(),
92 steal_mir: TypedArena::new(),
93 mir: TypedArena::new(),
94 tables: TypedArena::new(),
99 pub struct CtxtInterners<'tcx> {
100 /// The arena that types, regions, etc are allocated from
101 arena: &'tcx DroplessArena,
103 /// Specifically use a speedy hash algorithm for these hash sets,
104 /// they're accessed quite often.
105 type_: RefCell<FxHashSet<Interned<'tcx, TyS<'tcx>>>>,
106 type_list: RefCell<FxHashSet<Interned<'tcx, Slice<Ty<'tcx>>>>>,
107 substs: RefCell<FxHashSet<Interned<'tcx, Substs<'tcx>>>>,
108 region: RefCell<FxHashSet<Interned<'tcx, RegionKind>>>,
109 existential_predicates: RefCell<FxHashSet<Interned<'tcx, Slice<ExistentialPredicate<'tcx>>>>>,
110 predicates: RefCell<FxHashSet<Interned<'tcx, Slice<Predicate<'tcx>>>>>,
113 impl<'gcx: 'tcx, 'tcx> CtxtInterners<'tcx> {
114 fn new(arena: &'tcx DroplessArena) -> CtxtInterners<'tcx> {
117 type_: RefCell::new(FxHashSet()),
118 type_list: RefCell::new(FxHashSet()),
119 substs: RefCell::new(FxHashSet()),
120 region: RefCell::new(FxHashSet()),
121 existential_predicates: RefCell::new(FxHashSet()),
122 predicates: RefCell::new(FxHashSet()),
126 /// Intern a type. global_interners is Some only if this is
127 /// a local interner and global_interners is its counterpart.
128 fn intern_ty(&self, st: TypeVariants<'tcx>,
129 global_interners: Option<&CtxtInterners<'gcx>>)
132 let mut interner = self.type_.borrow_mut();
133 let global_interner = global_interners.map(|interners| {
134 interners.type_.borrow_mut()
136 if let Some(&Interned(ty)) = interner.get(&st) {
139 if let Some(ref interner) = global_interner {
140 if let Some(&Interned(ty)) = interner.get(&st) {
145 let flags = super::flags::FlagComputation::for_sty(&st);
146 let ty_struct = TyS {
149 region_depth: flags.depth,
152 // HACK(eddyb) Depend on flags being accurate to
153 // determine that all contents are in the global tcx.
154 // See comments on Lift for why we can't use that.
155 if !flags.flags.intersects(ty::TypeFlags::KEEP_IN_LOCAL_TCX) {
156 if let Some(interner) = global_interners {
157 let ty_struct: TyS<'gcx> = unsafe {
158 mem::transmute(ty_struct)
160 let ty: Ty<'gcx> = interner.arena.alloc(ty_struct);
161 global_interner.unwrap().insert(Interned(ty));
165 // Make sure we don't end up with inference
166 // types/regions in the global tcx.
167 if global_interners.is_none() {
169 bug!("Attempted to intern `{:?}` which contains \
170 inference types/regions in the global type context",
175 // Don't be &mut TyS.
176 let ty: Ty<'tcx> = self.arena.alloc(ty_struct);
177 interner.insert(Interned(ty));
181 debug!("Interned type: {:?} Pointer: {:?}",
182 ty, ty as *const TyS);
188 pub struct CommonTypes<'tcx> {
208 pub re_empty: Region<'tcx>,
209 pub re_static: Region<'tcx>,
210 pub re_erased: Region<'tcx>,
213 pub struct LocalTableInContext<'a, V: 'a> {
214 local_id_root: Option<DefId>,
215 data: &'a ItemLocalMap<V>
218 /// Validate that the given HirId (respectively its `local_id` part) can be
219 /// safely used as a key in the tables of a TypeckTable. For that to be
220 /// the case, the HirId must have the same `owner` as all the other IDs in
221 /// this table (signified by `local_id_root`). Otherwise the HirId
222 /// would be in a different frame of reference and using its `local_id`
223 /// would result in lookup errors, or worse, in silently wrong data being
225 fn validate_hir_id_for_typeck_tables(local_id_root: Option<DefId>,
228 if cfg!(debug_assertions) {
229 if let Some(local_id_root) = local_id_root {
230 if hir_id.owner != local_id_root.index {
231 ty::tls::with(|tcx| {
232 let node_id = tcx.hir
234 .find_node_for_hir_id(hir_id);
236 bug!("node {} with HirId::owner {:?} cannot be placed in \
237 TypeckTables with local_id_root {:?}",
238 tcx.hir.node_to_string(node_id),
239 DefId::local(hir_id.owner),
244 // We use "Null Object" TypeckTables in some of the analysis passes.
245 // These are just expected to be empty and their `local_id_root` is
246 // `None`. Therefore we cannot verify whether a given `HirId` would
247 // be a valid key for the given table. Instead we make sure that
248 // nobody tries to write to such a Null Object table.
250 bug!("access to invalid TypeckTables")
256 impl<'a, V> LocalTableInContext<'a, V> {
257 pub fn contains_key(&self, id: hir::HirId) -> bool {
258 validate_hir_id_for_typeck_tables(self.local_id_root, id, false);
259 self.data.contains_key(&id.local_id)
262 pub fn get(&self, id: hir::HirId) -> Option<&V> {
263 validate_hir_id_for_typeck_tables(self.local_id_root, id, false);
264 self.data.get(&id.local_id)
267 pub fn iter(&self) -> hash_map::Iter<hir::ItemLocalId, V> {
272 impl<'a, V> ::std::ops::Index<hir::HirId> for LocalTableInContext<'a, V> {
275 fn index(&self, key: hir::HirId) -> &V {
276 self.get(key).expect("LocalTableInContext: key not found")
280 pub struct LocalTableInContextMut<'a, V: 'a> {
281 local_id_root: Option<DefId>,
282 data: &'a mut ItemLocalMap<V>
285 impl<'a, V> LocalTableInContextMut<'a, V> {
286 pub fn get_mut(&mut self, id: hir::HirId) -> Option<&mut V> {
287 validate_hir_id_for_typeck_tables(self.local_id_root, id, true);
288 self.data.get_mut(&id.local_id)
291 pub fn entry(&mut self, id: hir::HirId) -> Entry<hir::ItemLocalId, V> {
292 validate_hir_id_for_typeck_tables(self.local_id_root, id, true);
293 self.data.entry(id.local_id)
296 pub fn insert(&mut self, id: hir::HirId, val: V) -> Option<V> {
297 validate_hir_id_for_typeck_tables(self.local_id_root, id, true);
298 self.data.insert(id.local_id, val)
301 pub fn remove(&mut self, id: hir::HirId) -> Option<V> {
302 validate_hir_id_for_typeck_tables(self.local_id_root, id, true);
303 self.data.remove(&id.local_id)
307 #[derive(RustcEncodable, RustcDecodable)]
308 pub struct TypeckTables<'tcx> {
309 /// The HirId::owner all ItemLocalIds in this table are relative to.
310 pub local_id_root: Option<DefId>,
312 /// Resolved definitions for `<T>::X` associated paths and
313 /// method calls, including those of overloaded operators.
314 type_dependent_defs: ItemLocalMap<Def>,
316 /// Stores the types for various nodes in the AST. Note that this table
317 /// is not guaranteed to be populated until after typeck. See
318 /// typeck::check::fn_ctxt for details.
319 node_types: ItemLocalMap<Ty<'tcx>>,
321 /// Stores the type parameters which were substituted to obtain the type
322 /// of this node. This only applies to nodes that refer to entities
323 /// parameterized by type parameters, such as generic fns, types, or
325 node_substs: ItemLocalMap<&'tcx Substs<'tcx>>,
327 adjustments: ItemLocalMap<Vec<ty::adjustment::Adjustment<'tcx>>>,
329 // Stores the actual binding mode for all instances of hir::BindingAnnotation.
330 pat_binding_modes: ItemLocalMap<BindingMode>,
333 pub upvar_capture_map: ty::UpvarCaptureMap<'tcx>,
335 /// Records the type of each closure.
336 closure_tys: ItemLocalMap<ty::PolyFnSig<'tcx>>,
338 /// Records the kind of each closure and the span and name of the variable
339 /// that caused the closure to be this kind.
340 closure_kinds: ItemLocalMap<(ty::ClosureKind, Option<(Span, ast::Name)>)>,
342 generator_sigs: ItemLocalMap<Option<ty::GenSig<'tcx>>>,
344 generator_interiors: ItemLocalMap<ty::GeneratorInterior<'tcx>>,
346 /// For each fn, records the "liberated" types of its arguments
347 /// and return type. Liberated means that all bound regions
348 /// (including late-bound regions) are replaced with free
349 /// equivalents. This table is not used in trans (since regions
350 /// are erased there) and hence is not serialized to metadata.
351 liberated_fn_sigs: ItemLocalMap<ty::FnSig<'tcx>>,
353 /// For each FRU expression, record the normalized types of the fields
354 /// of the struct - this is needed because it is non-trivial to
355 /// normalize while preserving regions. This table is used only in
356 /// MIR construction and hence is not serialized to metadata.
357 fru_field_types: ItemLocalMap<Vec<Ty<'tcx>>>,
359 /// Maps a cast expression to its kind. This is keyed on the
360 /// *from* expression of the cast, not the cast itself.
361 cast_kinds: ItemLocalMap<ty::cast::CastKind>,
363 /// Set of trait imports actually used in the method resolution.
364 /// This is used for warning unused imports.
365 pub used_trait_imports: DefIdSet,
367 /// If any errors occurred while type-checking this body,
368 /// this field will be set to `true`.
369 pub tainted_by_errors: bool,
371 /// Stores the free-region relationships that were deduced from
372 /// its where clauses and parameter types. These are then
373 /// read-again by borrowck.
374 pub free_region_map: FreeRegionMap<'tcx>,
377 impl<'tcx> TypeckTables<'tcx> {
378 pub fn empty(local_id_root: Option<DefId>) -> TypeckTables<'tcx> {
381 type_dependent_defs: ItemLocalMap(),
382 node_types: ItemLocalMap(),
383 node_substs: ItemLocalMap(),
384 adjustments: ItemLocalMap(),
385 pat_binding_modes: ItemLocalMap(),
386 upvar_capture_map: FxHashMap(),
387 generator_sigs: ItemLocalMap(),
388 generator_interiors: ItemLocalMap(),
389 closure_tys: ItemLocalMap(),
390 closure_kinds: ItemLocalMap(),
391 liberated_fn_sigs: ItemLocalMap(),
392 fru_field_types: ItemLocalMap(),
393 cast_kinds: ItemLocalMap(),
394 used_trait_imports: DefIdSet(),
395 tainted_by_errors: false,
396 free_region_map: FreeRegionMap::new(),
400 /// Returns the final resolution of a `QPath` in an `Expr` or `Pat` node.
401 pub fn qpath_def(&self, qpath: &hir::QPath, id: hir::HirId) -> Def {
403 hir::QPath::Resolved(_, ref path) => path.def,
404 hir::QPath::TypeRelative(..) => {
405 validate_hir_id_for_typeck_tables(self.local_id_root, id, false);
406 self.type_dependent_defs.get(&id.local_id).cloned().unwrap_or(Def::Err)
411 pub fn type_dependent_defs(&self) -> LocalTableInContext<Def> {
412 LocalTableInContext {
413 local_id_root: self.local_id_root,
414 data: &self.type_dependent_defs
418 pub fn type_dependent_defs_mut(&mut self) -> LocalTableInContextMut<Def> {
419 LocalTableInContextMut {
420 local_id_root: self.local_id_root,
421 data: &mut self.type_dependent_defs
425 pub fn node_types(&self) -> LocalTableInContext<Ty<'tcx>> {
426 LocalTableInContext {
427 local_id_root: self.local_id_root,
428 data: &self.node_types
432 pub fn node_types_mut(&mut self) -> LocalTableInContextMut<Ty<'tcx>> {
433 LocalTableInContextMut {
434 local_id_root: self.local_id_root,
435 data: &mut self.node_types
439 pub fn node_id_to_type(&self, id: hir::HirId) -> Ty<'tcx> {
440 match self.node_id_to_type_opt(id) {
443 bug!("node_id_to_type: no type for node `{}`",
445 let id = tcx.hir.definitions().find_node_for_hir_id(id);
446 tcx.hir.node_to_string(id)
452 pub fn node_id_to_type_opt(&self, id: hir::HirId) -> Option<Ty<'tcx>> {
453 validate_hir_id_for_typeck_tables(self.local_id_root, id, false);
454 self.node_types.get(&id.local_id).cloned()
457 pub fn node_substs_mut(&mut self) -> LocalTableInContextMut<&'tcx Substs<'tcx>> {
458 LocalTableInContextMut {
459 local_id_root: self.local_id_root,
460 data: &mut self.node_substs
464 pub fn node_substs(&self, id: hir::HirId) -> &'tcx Substs<'tcx> {
465 validate_hir_id_for_typeck_tables(self.local_id_root, id, false);
466 self.node_substs.get(&id.local_id).cloned().unwrap_or(Substs::empty())
469 pub fn node_substs_opt(&self, id: hir::HirId) -> Option<&'tcx Substs<'tcx>> {
470 validate_hir_id_for_typeck_tables(self.local_id_root, id, false);
471 self.node_substs.get(&id.local_id).cloned()
474 // Returns the type of a pattern as a monotype. Like @expr_ty, this function
475 // doesn't provide type parameter substitutions.
476 pub fn pat_ty(&self, pat: &hir::Pat) -> Ty<'tcx> {
477 self.node_id_to_type(pat.hir_id)
480 pub fn pat_ty_opt(&self, pat: &hir::Pat) -> Option<Ty<'tcx>> {
481 self.node_id_to_type_opt(pat.hir_id)
484 // Returns the type of an expression as a monotype.
486 // NB (1): This is the PRE-ADJUSTMENT TYPE for the expression. That is, in
487 // some cases, we insert `Adjustment` annotations such as auto-deref or
488 // auto-ref. The type returned by this function does not consider such
489 // adjustments. See `expr_ty_adjusted()` instead.
491 // NB (2): This type doesn't provide type parameter substitutions; e.g. if you
492 // ask for the type of "id" in "id(3)", it will return "fn(&isize) -> isize"
493 // instead of "fn(ty) -> T with T = isize".
494 pub fn expr_ty(&self, expr: &hir::Expr) -> Ty<'tcx> {
495 self.node_id_to_type(expr.hir_id)
498 pub fn expr_ty_opt(&self, expr: &hir::Expr) -> Option<Ty<'tcx>> {
499 self.node_id_to_type_opt(expr.hir_id)
502 pub fn adjustments(&self) -> LocalTableInContext<Vec<ty::adjustment::Adjustment<'tcx>>> {
503 LocalTableInContext {
504 local_id_root: self.local_id_root,
505 data: &self.adjustments
509 pub fn adjustments_mut(&mut self)
510 -> LocalTableInContextMut<Vec<ty::adjustment::Adjustment<'tcx>>> {
511 LocalTableInContextMut {
512 local_id_root: self.local_id_root,
513 data: &mut self.adjustments
517 pub fn expr_adjustments(&self, expr: &hir::Expr)
518 -> &[ty::adjustment::Adjustment<'tcx>] {
519 validate_hir_id_for_typeck_tables(self.local_id_root, expr.hir_id, false);
520 self.adjustments.get(&expr.hir_id.local_id).map_or(&[], |a| &a[..])
523 /// Returns the type of `expr`, considering any `Adjustment`
524 /// entry recorded for that expression.
525 pub fn expr_ty_adjusted(&self, expr: &hir::Expr) -> Ty<'tcx> {
526 self.expr_adjustments(expr)
528 .map_or_else(|| self.expr_ty(expr), |adj| adj.target)
531 pub fn expr_ty_adjusted_opt(&self, expr: &hir::Expr) -> Option<Ty<'tcx>> {
532 self.expr_adjustments(expr)
534 .map(|adj| adj.target)
535 .or_else(|| self.expr_ty_opt(expr))
538 pub fn is_method_call(&self, expr: &hir::Expr) -> bool {
539 // Only paths and method calls/overloaded operators have
540 // entries in type_dependent_defs, ignore the former here.
541 if let hir::ExprPath(_) = expr.node {
545 match self.type_dependent_defs().get(expr.hir_id) {
546 Some(&Def::Method(_)) => true,
551 pub fn pat_binding_modes(&self) -> LocalTableInContext<BindingMode> {
552 LocalTableInContext {
553 local_id_root: self.local_id_root,
554 data: &self.pat_binding_modes
558 pub fn pat_binding_modes_mut(&mut self)
559 -> LocalTableInContextMut<BindingMode> {
560 LocalTableInContextMut {
561 local_id_root: self.local_id_root,
562 data: &mut self.pat_binding_modes
566 pub fn upvar_capture(&self, upvar_id: ty::UpvarId) -> ty::UpvarCapture<'tcx> {
567 self.upvar_capture_map[&upvar_id]
570 pub fn closure_tys(&self) -> LocalTableInContext<ty::PolyFnSig<'tcx>> {
571 LocalTableInContext {
572 local_id_root: self.local_id_root,
573 data: &self.closure_tys
577 pub fn closure_tys_mut(&mut self)
578 -> LocalTableInContextMut<ty::PolyFnSig<'tcx>> {
579 LocalTableInContextMut {
580 local_id_root: self.local_id_root,
581 data: &mut self.closure_tys
585 pub fn closure_kinds(&self) -> LocalTableInContext<(ty::ClosureKind,
586 Option<(Span, ast::Name)>)> {
587 LocalTableInContext {
588 local_id_root: self.local_id_root,
589 data: &self.closure_kinds
593 pub fn closure_kinds_mut(&mut self)
594 -> LocalTableInContextMut<(ty::ClosureKind, Option<(Span, ast::Name)>)> {
595 LocalTableInContextMut {
596 local_id_root: self.local_id_root,
597 data: &mut self.closure_kinds
601 pub fn liberated_fn_sigs(&self) -> LocalTableInContext<ty::FnSig<'tcx>> {
602 LocalTableInContext {
603 local_id_root: self.local_id_root,
604 data: &self.liberated_fn_sigs
608 pub fn liberated_fn_sigs_mut(&mut self) -> LocalTableInContextMut<ty::FnSig<'tcx>> {
609 LocalTableInContextMut {
610 local_id_root: self.local_id_root,
611 data: &mut self.liberated_fn_sigs
615 pub fn fru_field_types(&self) -> LocalTableInContext<Vec<Ty<'tcx>>> {
616 LocalTableInContext {
617 local_id_root: self.local_id_root,
618 data: &self.fru_field_types
622 pub fn fru_field_types_mut(&mut self) -> LocalTableInContextMut<Vec<Ty<'tcx>>> {
623 LocalTableInContextMut {
624 local_id_root: self.local_id_root,
625 data: &mut self.fru_field_types
629 pub fn cast_kinds(&self) -> LocalTableInContext<ty::cast::CastKind> {
630 LocalTableInContext {
631 local_id_root: self.local_id_root,
632 data: &self.cast_kinds
636 pub fn cast_kinds_mut(&mut self) -> LocalTableInContextMut<ty::cast::CastKind> {
637 LocalTableInContextMut {
638 local_id_root: self.local_id_root,
639 data: &mut self.cast_kinds
643 pub fn generator_sigs(&self)
644 -> LocalTableInContext<Option<ty::GenSig<'tcx>>>
646 LocalTableInContext {
647 local_id_root: self.local_id_root,
648 data: &self.generator_sigs,
652 pub fn generator_sigs_mut(&mut self)
653 -> LocalTableInContextMut<Option<ty::GenSig<'tcx>>>
655 LocalTableInContextMut {
656 local_id_root: self.local_id_root,
657 data: &mut self.generator_sigs,
661 pub fn generator_interiors(&self)
662 -> LocalTableInContext<ty::GeneratorInterior<'tcx>>
664 LocalTableInContext {
665 local_id_root: self.local_id_root,
666 data: &self.generator_interiors,
670 pub fn generator_interiors_mut(&mut self)
671 -> LocalTableInContextMut<ty::GeneratorInterior<'tcx>>
673 LocalTableInContextMut {
674 local_id_root: self.local_id_root,
675 data: &mut self.generator_interiors,
680 impl<'a, 'gcx, 'tcx> HashStable<StableHashingContext<'a, 'gcx, 'tcx>> for TypeckTables<'gcx> {
681 fn hash_stable<W: StableHasherResult>(&self,
682 hcx: &mut StableHashingContext<'a, 'gcx, 'tcx>,
683 hasher: &mut StableHasher<W>) {
684 let ty::TypeckTables {
686 ref type_dependent_defs,
690 ref pat_binding_modes,
691 ref upvar_capture_map,
694 ref liberated_fn_sigs,
699 ref used_trait_imports,
703 ref generator_interiors,
706 hcx.with_node_id_hashing_mode(NodeIdHashingMode::HashDefPath, |hcx| {
707 ich::hash_stable_itemlocalmap(hcx, hasher, type_dependent_defs);
708 ich::hash_stable_itemlocalmap(hcx, hasher, node_types);
709 ich::hash_stable_itemlocalmap(hcx, hasher, node_substs);
710 ich::hash_stable_itemlocalmap(hcx, hasher, adjustments);
711 ich::hash_stable_itemlocalmap(hcx, hasher, pat_binding_modes);
712 ich::hash_stable_hashmap(hcx, hasher, upvar_capture_map, |hcx, up_var_id| {
719 local_id_root.expect("trying to hash invalid TypeckTables");
721 let var_def_id = DefId {
722 krate: local_id_root.krate,
725 let closure_def_id = DefId {
726 krate: local_id_root.krate,
727 index: closure_expr_id,
729 (hcx.def_path_hash(var_def_id), hcx.def_path_hash(closure_def_id))
732 ich::hash_stable_itemlocalmap(hcx, hasher, closure_tys);
733 ich::hash_stable_itemlocalmap(hcx, hasher, closure_kinds);
734 ich::hash_stable_itemlocalmap(hcx, hasher, liberated_fn_sigs);
735 ich::hash_stable_itemlocalmap(hcx, hasher, fru_field_types);
736 ich::hash_stable_itemlocalmap(hcx, hasher, cast_kinds);
737 ich::hash_stable_itemlocalmap(hcx, hasher, generator_sigs);
738 ich::hash_stable_itemlocalmap(hcx, hasher, generator_interiors);
740 ich::hash_stable_hashset(hcx, hasher, used_trait_imports, |hcx, def_id| {
741 hcx.def_path_hash(*def_id)
744 tainted_by_errors.hash_stable(hcx, hasher);
745 free_region_map.hash_stable(hcx, hasher);
750 impl<'tcx> CommonTypes<'tcx> {
751 fn new(interners: &CtxtInterners<'tcx>) -> CommonTypes<'tcx> {
752 let mk = |sty| interners.intern_ty(sty, None);
753 let mk_region = |r| {
754 if let Some(r) = interners.region.borrow().get(&r) {
757 let r = interners.arena.alloc(r);
758 interners.region.borrow_mut().insert(Interned(r));
766 isize: mk(TyInt(ast::IntTy::Is)),
767 i8: mk(TyInt(ast::IntTy::I8)),
768 i16: mk(TyInt(ast::IntTy::I16)),
769 i32: mk(TyInt(ast::IntTy::I32)),
770 i64: mk(TyInt(ast::IntTy::I64)),
771 i128: mk(TyInt(ast::IntTy::I128)),
772 usize: mk(TyUint(ast::UintTy::Us)),
773 u8: mk(TyUint(ast::UintTy::U8)),
774 u16: mk(TyUint(ast::UintTy::U16)),
775 u32: mk(TyUint(ast::UintTy::U32)),
776 u64: mk(TyUint(ast::UintTy::U64)),
777 u128: mk(TyUint(ast::UintTy::U128)),
778 f32: mk(TyFloat(ast::FloatTy::F32)),
779 f64: mk(TyFloat(ast::FloatTy::F64)),
781 re_empty: mk_region(RegionKind::ReEmpty),
782 re_static: mk_region(RegionKind::ReStatic),
783 re_erased: mk_region(RegionKind::ReErased),
788 /// The data structure to keep track of all the information that typechecker
789 /// generates so that so that it can be reused and doesn't have to be redone
791 #[derive(Copy, Clone)]
792 pub struct TyCtxt<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
793 gcx: &'a GlobalCtxt<'gcx>,
794 interners: &'a CtxtInterners<'tcx>
797 impl<'a, 'gcx, 'tcx> Deref for TyCtxt<'a, 'gcx, 'tcx> {
798 type Target = &'a GlobalCtxt<'gcx>;
799 fn deref(&self) -> &Self::Target {
804 pub struct GlobalCtxt<'tcx> {
805 global_arenas: &'tcx GlobalArenas<'tcx>,
806 global_interners: CtxtInterners<'tcx>,
808 pub sess: &'tcx Session,
810 pub trans_trait_caches: traits::trans::TransTraitCaches<'tcx>,
812 pub dep_graph: DepGraph,
814 /// Common types, pre-interned for your convenience.
815 pub types: CommonTypes<'tcx>,
817 /// Map indicating what traits are in scope for places where this
818 /// is relevant; generated by resolve.
819 trait_map: FxHashMap<HirId, Rc<Vec<TraitCandidate>>>,
821 /// Export map produced by name resolution.
822 export_map: FxHashMap<HirId, Rc<Vec<Export>>>,
824 named_region_map: NamedRegionMap,
826 pub hir: hir_map::Map<'tcx>,
828 /// A map from DefPathHash -> DefId. Includes DefIds from the local crate
829 /// as well as all upstream crates. Only populated in incremental mode.
830 pub def_path_hash_to_def_id: Option<FxHashMap<DefPathHash, DefId>>,
832 pub maps: maps::Maps<'tcx>,
834 pub mir_passes: Rc<Passes>,
836 // Records the free variables refrenced by every closure
837 // expression. Do not track deps for this, just recompute it from
838 // scratch every time.
839 freevars: FxHashMap<HirId, Rc<Vec<hir::Freevar>>>,
841 maybe_unused_trait_imports: FxHashSet<HirId>,
843 maybe_unused_extern_crates: Vec<(HirId, Span)>,
845 // Internal cache for metadata decoding. No need to track deps on this.
846 pub rcache: RefCell<FxHashMap<ty::CReaderCacheKey, Ty<'tcx>>>,
848 // FIXME dep tracking -- should be harmless enough
849 pub normalized_cache: RefCell<FxHashMap<Ty<'tcx>, Ty<'tcx>>>,
851 pub inhabitedness_cache: RefCell<FxHashMap<Ty<'tcx>, DefIdForest>>,
853 /// Set of nodes which mark locals as mutable which end up getting used at
854 /// some point. Local variable definitions not in this set can be warned
856 pub used_mut_nodes: RefCell<NodeSet>,
858 /// Caches the results of trait selection. This cache is used
859 /// for things that do not have to do with the parameters in scope.
860 pub selection_cache: traits::SelectionCache<'tcx>,
862 /// Caches the results of trait evaluation. This cache is used
863 /// for things that do not have to do with the parameters in scope.
864 /// Merge this with `selection_cache`?
865 pub evaluation_cache: traits::EvaluationCache<'tcx>,
867 /// Maps Expr NodeId's to `true` iff `&expr` can have 'static lifetime.
868 pub rvalue_promotable_to_static: RefCell<NodeMap<bool>>,
870 /// The definite name of the current crate after taking into account
871 /// attributes, commandline parameters, etc.
872 pub crate_name: Symbol,
874 /// Data layout specification for the current target.
875 pub data_layout: TargetDataLayout,
877 /// Used to prevent layout from recursing too deeply.
878 pub layout_depth: Cell<usize>,
880 /// Map from function to the `#[derive]` mode that it's defining. Only used
881 /// by `proc-macro` crates.
882 pub derive_macros: RefCell<NodeMap<Symbol>>,
884 stability_interner: RefCell<FxHashSet<&'tcx attr::Stability>>,
886 layout_interner: RefCell<FxHashSet<&'tcx Layout>>,
888 /// A vector of every trait accessible in the whole crate
889 /// (i.e. including those from subcrates). This is used only for
890 /// error reporting, and so is lazily initialized and generally
891 /// shouldn't taint the common path (hence the RefCell).
892 pub all_traits: RefCell<Option<Vec<DefId>>>,
895 impl<'tcx> GlobalCtxt<'tcx> {
896 /// Get the global TyCtxt.
897 pub fn global_tcx<'a>(&'a self) -> TyCtxt<'a, 'tcx, 'tcx> {
900 interners: &self.global_interners
905 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
906 pub fn alloc_generics(self, generics: ty::Generics) -> &'gcx ty::Generics {
907 self.global_arenas.generics.alloc(generics)
910 pub fn alloc_steal_mir(self, mir: Mir<'gcx>) -> &'gcx Steal<Mir<'gcx>> {
911 self.global_arenas.steal_mir.alloc(Steal::new(mir))
914 pub fn alloc_mir(self, mir: Mir<'gcx>) -> &'gcx Mir<'gcx> {
915 self.global_arenas.mir.alloc(mir)
918 pub fn alloc_tables(self, tables: ty::TypeckTables<'gcx>) -> &'gcx ty::TypeckTables<'gcx> {
919 self.global_arenas.tables.alloc(tables)
922 pub fn alloc_trait_def(self, def: ty::TraitDef) -> &'gcx ty::TraitDef {
923 self.global_arenas.trait_def.alloc(def)
926 pub fn alloc_adt_def(self,
929 variants: Vec<ty::VariantDef>,
931 -> &'gcx ty::AdtDef {
932 let def = ty::AdtDef::new(self, did, kind, variants, repr);
933 self.global_arenas.adt_def.alloc(def)
936 pub fn intern_stability(self, stab: attr::Stability) -> &'gcx attr::Stability {
937 if let Some(st) = self.stability_interner.borrow().get(&stab) {
941 let interned = self.global_interners.arena.alloc(stab);
942 if let Some(prev) = self.stability_interner.borrow_mut().replace(interned) {
943 bug!("Tried to overwrite interned Stability: {:?}", prev)
948 pub fn intern_layout(self, layout: Layout) -> &'gcx Layout {
949 if let Some(layout) = self.layout_interner.borrow().get(&layout) {
953 let interned = self.global_arenas.layout.alloc(layout);
954 if let Some(prev) = self.layout_interner.borrow_mut().replace(interned) {
955 bug!("Tried to overwrite interned Layout: {:?}", prev)
960 pub fn lift<T: ?Sized + Lift<'tcx>>(self, value: &T) -> Option<T::Lifted> {
961 value.lift_to_tcx(self)
964 /// Like lift, but only tries in the global tcx.
965 pub fn lift_to_global<T: ?Sized + Lift<'gcx>>(self, value: &T) -> Option<T::Lifted> {
966 value.lift_to_tcx(self.global_tcx())
969 /// Returns true if self is the same as self.global_tcx().
970 fn is_global(self) -> bool {
971 let local = self.interners as *const _;
972 let global = &self.global_interners as *const _;
973 local as usize == global as usize
976 /// Create a type context and call the closure with a `TyCtxt` reference
977 /// to the context. The closure enforces that the type context and any interned
978 /// value (types, substs, etc.) can only be used while `ty::tls` has a valid
979 /// reference to the context, to allow formatting values that need it.
980 pub fn create_and_enter<F, R>(s: &'tcx Session,
981 local_providers: ty::maps::Providers<'tcx>,
982 extern_providers: ty::maps::Providers<'tcx>,
983 mir_passes: Rc<Passes>,
984 arenas: &'tcx GlobalArenas<'tcx>,
985 arena: &'tcx DroplessArena,
986 resolutions: ty::Resolutions,
987 named_region_map: resolve_lifetime::NamedRegionMap,
988 hir: hir_map::Map<'tcx>,
991 where F: for<'b> FnOnce(TyCtxt<'b, 'tcx, 'tcx>) -> R
993 let data_layout = TargetDataLayout::parse(s);
994 let interners = CtxtInterners::new(arena);
995 let common_types = CommonTypes::new(&interners);
996 let dep_graph = hir.dep_graph.clone();
997 let max_cnum = s.cstore.crates_untracked().iter().map(|c| c.as_usize()).max().unwrap_or(0);
998 let mut providers = IndexVec::from_elem_n(extern_providers, max_cnum + 1);
999 providers[LOCAL_CRATE] = local_providers;
1001 let def_path_hash_to_def_id = if s.opts.build_dep_graph() {
1002 let upstream_def_path_tables: Vec<(CrateNum, Rc<_>)> = s
1006 .map(|&cnum| (cnum, s.cstore.def_path_table(cnum)))
1009 let def_path_tables = || {
1010 upstream_def_path_tables
1012 .map(|&(cnum, ref rc)| (cnum, &**rc))
1013 .chain(iter::once((LOCAL_CRATE, hir.definitions().def_path_table())))
1016 // Precompute the capacity of the hashmap so we don't have to
1017 // re-allocate when populating it.
1018 let capacity = def_path_tables().map(|(_, t)| t.size()).sum::<usize>();
1020 let mut map: FxHashMap<_, _> = FxHashMap::with_capacity_and_hasher(
1022 ::std::default::Default::default()
1025 for (cnum, def_path_table) in def_path_tables() {
1026 def_path_table.add_def_path_hashes_to(cnum, &mut map);
1034 tls::enter_global(GlobalCtxt {
1036 trans_trait_caches: traits::trans::TransTraitCaches::new(dep_graph.clone()),
1037 global_arenas: arenas,
1038 global_interners: interners,
1039 dep_graph: dep_graph.clone(),
1040 types: common_types,
1041 named_region_map: NamedRegionMap {
1043 named_region_map.defs
1045 .map(|(k, v)| (hir.node_to_hir_id(k), v))
1048 named_region_map.late_bound
1050 .map(|k| hir.node_to_hir_id(k))
1052 object_lifetime_defaults:
1053 named_region_map.object_lifetime_defaults
1055 .map(|(k, v)| (hir.node_to_hir_id(k), Rc::new(v)))
1058 trait_map: resolutions.trait_map.into_iter().map(|(k, v)| {
1059 (hir.node_to_hir_id(k), Rc::new(v))
1061 export_map: resolutions.export_map.into_iter().map(|(k, v)| {
1062 (hir.node_to_hir_id(k), Rc::new(v))
1064 freevars: resolutions.freevars.into_iter().map(|(k, v)| {
1065 (hir.node_to_hir_id(k), Rc::new(v))
1067 maybe_unused_trait_imports:
1068 resolutions.maybe_unused_trait_imports
1070 .map(|id| hir.node_to_hir_id(id))
1072 maybe_unused_extern_crates:
1073 resolutions.maybe_unused_extern_crates
1075 .map(|(id, sp)| (hir.node_to_hir_id(id), sp))
1078 def_path_hash_to_def_id,
1079 maps: maps::Maps::new(providers),
1081 rcache: RefCell::new(FxHashMap()),
1082 normalized_cache: RefCell::new(FxHashMap()),
1083 inhabitedness_cache: RefCell::new(FxHashMap()),
1084 used_mut_nodes: RefCell::new(NodeSet()),
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)
1103 pub fn lang_items(self) -> Rc<middle::lang_items::LanguageItems> {
1104 // FIXME(#42293) Right now we insert a `with_ignore` node in the dep
1105 // graph here to ignore the fact that `get_lang_items` below depends on
1106 // the entire crate. For now this'll prevent false positives of
1107 // recompiling too much when anything changes.
1109 // Once red/green incremental compilation lands we should be able to
1110 // remove this because while the crate changes often the lint level map
1111 // will change rarely.
1112 self.dep_graph.with_ignore(|| {
1113 self.get_lang_items(LOCAL_CRATE)
1117 pub fn stability(self) -> Rc<stability::Index<'tcx>> {
1118 // FIXME(#42293) we should actually track this, but fails too many tests
1120 self.dep_graph.with_ignore(|| {
1121 self.stability_index(LOCAL_CRATE)
1125 pub fn crates(self) -> Rc<Vec<CrateNum>> {
1126 self.all_crate_nums(LOCAL_CRATE)
1130 impl<'gcx: 'tcx, 'tcx> GlobalCtxt<'gcx> {
1131 /// Call the closure with a local `TyCtxt` using the given arena.
1132 pub fn enter_local<F, R>(&self, arena: &'tcx DroplessArena, f: F) -> R
1133 where F: for<'a> FnOnce(TyCtxt<'a, 'gcx, 'tcx>) -> R
1135 let interners = CtxtInterners::new(arena);
1136 tls::enter(self, &interners, f)
1140 /// A trait implemented for all X<'a> types which can be safely and
1141 /// efficiently converted to X<'tcx> as long as they are part of the
1142 /// provided TyCtxt<'tcx>.
1143 /// This can be done, for example, for Ty<'tcx> or &'tcx Substs<'tcx>
1144 /// by looking them up in their respective interners.
1146 /// However, this is still not the best implementation as it does
1147 /// need to compare the components, even for interned values.
1148 /// It would be more efficient if TypedArena provided a way to
1149 /// determine whether the address is in the allocated range.
1151 /// None is returned if the value or one of the components is not part
1152 /// of the provided context.
1153 /// For Ty, None can be returned if either the type interner doesn't
1154 /// contain the TypeVariants key or if the address of the interned
1155 /// pointer differs. The latter case is possible if a primitive type,
1156 /// e.g. `()` or `u8`, was interned in a different context.
1157 pub trait Lift<'tcx> {
1159 fn lift_to_tcx<'a, 'gcx>(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Option<Self::Lifted>;
1162 impl<'a, 'tcx> Lift<'tcx> for ty::ParamEnv<'a> {
1163 type Lifted = ty::ParamEnv<'tcx>;
1164 fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>) -> Option<ty::ParamEnv<'tcx>> {
1165 self.caller_bounds.lift_to_tcx(tcx).and_then(|caller_bounds| {
1167 reveal: self.reveal,
1174 impl<'a, 'tcx> Lift<'tcx> for Ty<'a> {
1175 type Lifted = Ty<'tcx>;
1176 fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>) -> Option<Ty<'tcx>> {
1177 if tcx.interners.arena.in_arena(*self as *const _) {
1178 return Some(unsafe { mem::transmute(*self) });
1180 // Also try in the global tcx if we're not that.
1181 if !tcx.is_global() {
1182 self.lift_to_tcx(tcx.global_tcx())
1189 impl<'a, 'tcx> Lift<'tcx> for &'a Substs<'a> {
1190 type Lifted = &'tcx Substs<'tcx>;
1191 fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>) -> Option<&'tcx Substs<'tcx>> {
1192 if self.len() == 0 {
1193 return Some(Slice::empty());
1195 if tcx.interners.arena.in_arena(&self[..] as *const _) {
1196 return Some(unsafe { mem::transmute(*self) });
1198 // Also try in the global tcx if we're not that.
1199 if !tcx.is_global() {
1200 self.lift_to_tcx(tcx.global_tcx())
1207 impl<'a, 'tcx> Lift<'tcx> for Region<'a> {
1208 type Lifted = Region<'tcx>;
1209 fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>) -> Option<Region<'tcx>> {
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<Ty<'a>> {
1223 type Lifted = &'tcx Slice<Ty<'tcx>>;
1224 fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>)
1225 -> Option<&'tcx Slice<Ty<'tcx>>> {
1226 if self.len() == 0 {
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<ExistentialPredicate<'a>> {
1242 type Lifted = &'tcx Slice<ExistentialPredicate<'tcx>>;
1243 fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>)
1244 -> Option<&'tcx Slice<ExistentialPredicate<'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())
1260 impl<'a, 'tcx> Lift<'tcx> for &'a Slice<Predicate<'a>> {
1261 type Lifted = &'tcx Slice<Predicate<'tcx>>;
1262 fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>)
1263 -> Option<&'tcx Slice<Predicate<'tcx>>> {
1264 if self.is_empty() {
1265 return Some(Slice::empty());
1267 if tcx.interners.arena.in_arena(*self as *const _) {
1268 return Some(unsafe { mem::transmute(*self) });
1270 // Also try in the global tcx if we're not that.
1271 if !tcx.is_global() {
1272 self.lift_to_tcx(tcx.global_tcx())
1280 use super::{CtxtInterners, GlobalCtxt, TyCtxt};
1282 use std::cell::Cell;
1286 /// Marker types used for the scoped TLS slot.
1287 /// The type context cannot be used directly because the scoped TLS
1288 /// in libstd doesn't allow types generic over lifetimes.
1289 enum ThreadLocalGlobalCtxt {}
1290 enum ThreadLocalInterners {}
1293 static TLS_TCX: Cell<Option<(*const ThreadLocalGlobalCtxt,
1294 *const ThreadLocalInterners)>> = Cell::new(None)
1297 fn span_debug(span: syntax_pos::Span, f: &mut fmt::Formatter) -> fmt::Result {
1299 write!(f, "{}", tcx.sess.codemap().span_to_string(span))
1303 pub fn enter_global<'gcx, F, R>(gcx: GlobalCtxt<'gcx>, f: F) -> R
1304 where F: for<'a> FnOnce(TyCtxt<'a, 'gcx, 'gcx>) -> R
1306 syntax_pos::SPAN_DEBUG.with(|span_dbg| {
1307 let original_span_debug = span_dbg.get();
1308 span_dbg.set(span_debug);
1309 let result = enter(&gcx, &gcx.global_interners, f);
1310 span_dbg.set(original_span_debug);
1315 pub fn enter<'a, 'gcx: 'tcx, 'tcx, F, R>(gcx: &'a GlobalCtxt<'gcx>,
1316 interners: &'a CtxtInterners<'tcx>,
1318 where F: FnOnce(TyCtxt<'a, 'gcx, 'tcx>) -> R
1320 let gcx_ptr = gcx as *const _ as *const ThreadLocalGlobalCtxt;
1321 let interners_ptr = interners as *const _ as *const ThreadLocalInterners;
1322 TLS_TCX.with(|tls| {
1323 let prev = tls.get();
1324 tls.set(Some((gcx_ptr, interners_ptr)));
1325 let ret = f(TyCtxt {
1334 pub fn with<F, R>(f: F) -> R
1335 where F: for<'a, 'gcx, 'tcx> FnOnce(TyCtxt<'a, 'gcx, 'tcx>) -> R
1337 TLS_TCX.with(|tcx| {
1338 let (gcx, interners) = tcx.get().unwrap();
1339 let gcx = unsafe { &*(gcx as *const GlobalCtxt) };
1340 let interners = unsafe { &*(interners as *const CtxtInterners) };
1348 pub fn with_opt<F, R>(f: F) -> R
1349 where F: for<'a, 'gcx, 'tcx> FnOnce(Option<TyCtxt<'a, 'gcx, 'tcx>>) -> R
1351 if TLS_TCX.with(|tcx| tcx.get().is_some()) {
1352 with(|v| f(Some(v)))
1359 macro_rules! sty_debug_print {
1360 ($ctxt: expr, $($variant: ident),*) => {{
1361 // curious inner module to allow variant names to be used as
1363 #[allow(non_snake_case)]
1365 use ty::{self, TyCtxt};
1366 use ty::context::Interned;
1368 #[derive(Copy, Clone)]
1371 region_infer: usize,
1376 pub fn go(tcx: TyCtxt) {
1377 let mut total = DebugStat {
1379 region_infer: 0, ty_infer: 0, both_infer: 0,
1381 $(let mut $variant = total;)*
1384 for &Interned(t) in tcx.interners.type_.borrow().iter() {
1385 let variant = match t.sty {
1386 ty::TyBool | ty::TyChar | ty::TyInt(..) | ty::TyUint(..) |
1387 ty::TyFloat(..) | ty::TyStr | ty::TyNever => continue,
1388 ty::TyError => /* unimportant */ continue,
1389 $(ty::$variant(..) => &mut $variant,)*
1391 let region = t.flags.intersects(ty::TypeFlags::HAS_RE_INFER);
1392 let ty = t.flags.intersects(ty::TypeFlags::HAS_TY_INFER);
1396 if region { total.region_infer += 1; variant.region_infer += 1 }
1397 if ty { total.ty_infer += 1; variant.ty_infer += 1 }
1398 if region && ty { total.both_infer += 1; variant.both_infer += 1 }
1400 println!("Ty interner total ty region both");
1401 $(println!(" {:18}: {uses:6} {usespc:4.1}%, \
1402 {ty:4.1}% {region:5.1}% {both:4.1}%",
1403 stringify!($variant),
1404 uses = $variant.total,
1405 usespc = $variant.total as f64 * 100.0 / total.total as f64,
1406 ty = $variant.ty_infer as f64 * 100.0 / total.total as f64,
1407 region = $variant.region_infer as f64 * 100.0 / total.total as f64,
1408 both = $variant.both_infer as f64 * 100.0 / total.total as f64);
1410 println!(" total {uses:6} \
1411 {ty:4.1}% {region:5.1}% {both:4.1}%",
1413 ty = total.ty_infer as f64 * 100.0 / total.total as f64,
1414 region = total.region_infer as f64 * 100.0 / total.total as f64,
1415 both = total.both_infer as f64 * 100.0 / total.total as f64)
1423 impl<'a, 'tcx> TyCtxt<'a, 'tcx, 'tcx> {
1424 pub fn print_debug_stats(self) {
1427 TyAdt, TyArray, TySlice, TyRawPtr, TyRef, TyFnDef, TyFnPtr, TyGenerator,
1428 TyDynamic, TyClosure, TyTuple, TyParam, TyInfer, TyProjection, TyAnon);
1430 println!("Substs interner: #{}", self.interners.substs.borrow().len());
1431 println!("Region interner: #{}", self.interners.region.borrow().len());
1432 println!("Stability interner: #{}", self.stability_interner.borrow().len());
1433 println!("Layout interner: #{}", self.layout_interner.borrow().len());
1438 /// An entry in an interner.
1439 struct Interned<'tcx, T: 'tcx+?Sized>(&'tcx T);
1441 // NB: An Interned<Ty> compares and hashes as a sty.
1442 impl<'tcx> PartialEq for Interned<'tcx, TyS<'tcx>> {
1443 fn eq(&self, other: &Interned<'tcx, TyS<'tcx>>) -> bool {
1444 self.0.sty == other.0.sty
1448 impl<'tcx> Eq for Interned<'tcx, TyS<'tcx>> {}
1450 impl<'tcx> Hash for Interned<'tcx, TyS<'tcx>> {
1451 fn hash<H: Hasher>(&self, s: &mut H) {
1456 impl<'tcx: 'lcx, 'lcx> Borrow<TypeVariants<'lcx>> for Interned<'tcx, TyS<'tcx>> {
1457 fn borrow<'a>(&'a self) -> &'a TypeVariants<'lcx> {
1462 // NB: An Interned<Slice<T>> compares and hashes as its elements.
1463 impl<'tcx, T: PartialEq> PartialEq for Interned<'tcx, Slice<T>> {
1464 fn eq(&self, other: &Interned<'tcx, Slice<T>>) -> bool {
1465 self.0[..] == other.0[..]
1469 impl<'tcx, T: Eq> Eq for Interned<'tcx, Slice<T>> {}
1471 impl<'tcx, T: Hash> Hash for Interned<'tcx, Slice<T>> {
1472 fn hash<H: Hasher>(&self, s: &mut H) {
1477 impl<'tcx: 'lcx, 'lcx> Borrow<[Ty<'lcx>]> for Interned<'tcx, Slice<Ty<'tcx>>> {
1478 fn borrow<'a>(&'a self) -> &'a [Ty<'lcx>] {
1483 impl<'tcx: 'lcx, 'lcx> Borrow<[Kind<'lcx>]> for Interned<'tcx, Substs<'tcx>> {
1484 fn borrow<'a>(&'a self) -> &'a [Kind<'lcx>] {
1489 impl<'tcx> Borrow<RegionKind> for Interned<'tcx, RegionKind> {
1490 fn borrow<'a>(&'a self) -> &'a RegionKind {
1495 impl<'tcx: 'lcx, 'lcx> Borrow<[ExistentialPredicate<'lcx>]>
1496 for Interned<'tcx, Slice<ExistentialPredicate<'tcx>>> {
1497 fn borrow<'a>(&'a self) -> &'a [ExistentialPredicate<'lcx>] {
1502 impl<'tcx: 'lcx, 'lcx> Borrow<[Predicate<'lcx>]>
1503 for Interned<'tcx, Slice<Predicate<'tcx>>> {
1504 fn borrow<'a>(&'a self) -> &'a [Predicate<'lcx>] {
1509 macro_rules! intern_method {
1510 ($lt_tcx:tt, $name:ident: $method:ident($alloc:ty,
1511 $alloc_method:ident,
1514 $needs_infer:expr) -> $ty:ty) => {
1515 impl<'a, 'gcx, $lt_tcx> TyCtxt<'a, 'gcx, $lt_tcx> {
1516 pub fn $method(self, v: $alloc) -> &$lt_tcx $ty {
1518 let key = ($alloc_to_key)(&v);
1519 if let Some(i) = self.interners.$name.borrow().get(key) {
1522 if !self.is_global() {
1523 if let Some(i) = self.global_interners.$name.borrow().get(key) {
1529 // HACK(eddyb) Depend on flags being accurate to
1530 // determine that all contents are in the global tcx.
1531 // See comments on Lift for why we can't use that.
1532 if !($needs_infer)(&v) {
1533 if !self.is_global() {
1537 let i = ($alloc_to_ret)(self.global_interners.arena.$alloc_method(v));
1538 self.global_interners.$name.borrow_mut().insert(Interned(i));
1542 // Make sure we don't end up with inference
1543 // types/regions in the global tcx.
1544 if self.is_global() {
1545 bug!("Attempted to intern `{:?}` which contains \
1546 inference types/regions in the global type context",
1551 let i = ($alloc_to_ret)(self.interners.arena.$alloc_method(v));
1552 self.interners.$name.borrow_mut().insert(Interned(i));
1559 macro_rules! direct_interners {
1560 ($lt_tcx:tt, $($name:ident: $method:ident($needs_infer:expr) -> $ty:ty),+) => {
1561 $(impl<$lt_tcx> PartialEq for Interned<$lt_tcx, $ty> {
1562 fn eq(&self, other: &Self) -> bool {
1567 impl<$lt_tcx> Eq for Interned<$lt_tcx, $ty> {}
1569 impl<$lt_tcx> Hash for Interned<$lt_tcx, $ty> {
1570 fn hash<H: Hasher>(&self, s: &mut H) {
1575 intern_method!($lt_tcx, $name: $method($ty, alloc, |x| x, |x| x, $needs_infer) -> $ty);)+
1579 pub fn keep_local<'tcx, T: ty::TypeFoldable<'tcx>>(x: &T) -> bool {
1580 x.has_type_flags(ty::TypeFlags::KEEP_IN_LOCAL_TCX)
1583 direct_interners!('tcx,
1584 region: mk_region(|r| {
1586 &ty::ReVar(_) | &ty::ReSkolemized(..) => true,
1592 macro_rules! slice_interners {
1593 ($($field:ident: $method:ident($ty:ident)),+) => (
1594 $(intern_method!('tcx, $field: $method(&[$ty<'tcx>], alloc_slice, Deref::deref,
1595 |xs: &[$ty]| -> &Slice<$ty> {
1596 unsafe { mem::transmute(xs) }
1597 }, |xs: &[$ty]| xs.iter().any(keep_local)) -> Slice<$ty<'tcx>>);)+
1602 existential_predicates: _intern_existential_predicates(ExistentialPredicate),
1603 predicates: _intern_predicates(Predicate),
1604 type_list: _intern_type_list(Ty),
1605 substs: _intern_substs(Kind)
1608 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
1609 /// Create an unsafe fn ty based on a safe fn ty.
1610 pub fn safe_to_unsafe_fn_ty(self, sig: PolyFnSig<'tcx>) -> Ty<'tcx> {
1611 assert_eq!(sig.unsafety(), hir::Unsafety::Normal);
1612 self.mk_fn_ptr(sig.map_bound(|sig| ty::FnSig {
1613 unsafety: hir::Unsafety::Unsafe,
1618 // Interns a type/name combination, stores the resulting box in cx.interners,
1619 // and returns the box as cast to an unsafe ptr (see comments for Ty above).
1620 pub fn mk_ty(self, st: TypeVariants<'tcx>) -> Ty<'tcx> {
1621 let global_interners = if !self.is_global() {
1622 Some(&self.global_interners)
1626 self.interners.intern_ty(st, global_interners)
1629 pub fn mk_mach_int(self, tm: ast::IntTy) -> Ty<'tcx> {
1631 ast::IntTy::Is => self.types.isize,
1632 ast::IntTy::I8 => self.types.i8,
1633 ast::IntTy::I16 => self.types.i16,
1634 ast::IntTy::I32 => self.types.i32,
1635 ast::IntTy::I64 => self.types.i64,
1636 ast::IntTy::I128 => self.types.i128,
1640 pub fn mk_mach_uint(self, tm: ast::UintTy) -> Ty<'tcx> {
1642 ast::UintTy::Us => self.types.usize,
1643 ast::UintTy::U8 => self.types.u8,
1644 ast::UintTy::U16 => self.types.u16,
1645 ast::UintTy::U32 => self.types.u32,
1646 ast::UintTy::U64 => self.types.u64,
1647 ast::UintTy::U128 => self.types.u128,
1651 pub fn mk_mach_float(self, tm: ast::FloatTy) -> Ty<'tcx> {
1653 ast::FloatTy::F32 => self.types.f32,
1654 ast::FloatTy::F64 => self.types.f64,
1658 pub fn mk_str(self) -> Ty<'tcx> {
1662 pub fn mk_static_str(self) -> Ty<'tcx> {
1663 self.mk_imm_ref(self.types.re_static, self.mk_str())
1666 pub fn mk_adt(self, def: &'tcx AdtDef, substs: &'tcx Substs<'tcx>) -> Ty<'tcx> {
1667 // take a copy of substs so that we own the vectors inside
1668 self.mk_ty(TyAdt(def, substs))
1671 pub fn mk_box(self, ty: Ty<'tcx>) -> Ty<'tcx> {
1672 let def_id = self.require_lang_item(lang_items::OwnedBoxLangItem);
1673 let adt_def = self.adt_def(def_id);
1674 let substs = self.mk_substs(iter::once(Kind::from(ty)));
1675 self.mk_ty(TyAdt(adt_def, substs))
1678 pub fn mk_ptr(self, tm: TypeAndMut<'tcx>) -> Ty<'tcx> {
1679 self.mk_ty(TyRawPtr(tm))
1682 pub fn mk_ref(self, r: Region<'tcx>, tm: TypeAndMut<'tcx>) -> Ty<'tcx> {
1683 self.mk_ty(TyRef(r, tm))
1686 pub fn mk_mut_ref(self, r: Region<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
1687 self.mk_ref(r, TypeAndMut {ty: ty, mutbl: hir::MutMutable})
1690 pub fn mk_imm_ref(self, r: Region<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
1691 self.mk_ref(r, TypeAndMut {ty: ty, mutbl: hir::MutImmutable})
1694 pub fn mk_mut_ptr(self, ty: Ty<'tcx>) -> Ty<'tcx> {
1695 self.mk_ptr(TypeAndMut {ty: ty, mutbl: hir::MutMutable})
1698 pub fn mk_imm_ptr(self, ty: Ty<'tcx>) -> Ty<'tcx> {
1699 self.mk_ptr(TypeAndMut {ty: ty, mutbl: hir::MutImmutable})
1702 pub fn mk_nil_ptr(self) -> Ty<'tcx> {
1703 self.mk_imm_ptr(self.mk_nil())
1706 pub fn mk_array(self, ty: Ty<'tcx>, n: usize) -> Ty<'tcx> {
1707 self.mk_ty(TyArray(ty, n))
1710 pub fn mk_slice(self, ty: Ty<'tcx>) -> Ty<'tcx> {
1711 self.mk_ty(TySlice(ty))
1714 pub fn intern_tup(self, ts: &[Ty<'tcx>], defaulted: bool) -> Ty<'tcx> {
1715 self.mk_ty(TyTuple(self.intern_type_list(ts), defaulted))
1718 pub fn mk_tup<I: InternAs<[Ty<'tcx>], Ty<'tcx>>>(self, iter: I,
1719 defaulted: bool) -> I::Output {
1720 iter.intern_with(|ts| self.mk_ty(TyTuple(self.intern_type_list(ts), defaulted)))
1723 pub fn mk_nil(self) -> Ty<'tcx> {
1724 self.intern_tup(&[], false)
1727 pub fn mk_diverging_default(self) -> Ty<'tcx> {
1728 if self.sess.features.borrow().never_type {
1731 self.intern_tup(&[], true)
1735 pub fn mk_bool(self) -> Ty<'tcx> {
1739 pub fn mk_fn_def(self, def_id: DefId,
1740 substs: &'tcx Substs<'tcx>) -> Ty<'tcx> {
1741 self.mk_ty(TyFnDef(def_id, substs))
1744 pub fn mk_fn_ptr(self, fty: PolyFnSig<'tcx>) -> Ty<'tcx> {
1745 self.mk_ty(TyFnPtr(fty))
1750 obj: ty::Binder<&'tcx Slice<ExistentialPredicate<'tcx>>>,
1751 reg: ty::Region<'tcx>
1753 self.mk_ty(TyDynamic(obj, reg))
1756 pub fn mk_projection(self,
1758 substs: &'tcx Substs<'tcx>)
1760 self.mk_ty(TyProjection(ProjectionTy {
1766 pub fn mk_closure(self,
1768 substs: &'tcx Substs<'tcx>)
1770 self.mk_closure_from_closure_substs(closure_id, ClosureSubsts {
1775 pub fn mk_closure_from_closure_substs(self,
1777 closure_substs: ClosureSubsts<'tcx>)
1779 self.mk_ty(TyClosure(closure_id, closure_substs))
1782 pub fn mk_generator(self,
1784 closure_substs: ClosureSubsts<'tcx>,
1785 interior: GeneratorInterior<'tcx>)
1787 self.mk_ty(TyGenerator(id, closure_substs, interior))
1790 pub fn mk_var(self, v: TyVid) -> Ty<'tcx> {
1791 self.mk_infer(TyVar(v))
1794 pub fn mk_int_var(self, v: IntVid) -> Ty<'tcx> {
1795 self.mk_infer(IntVar(v))
1798 pub fn mk_float_var(self, v: FloatVid) -> Ty<'tcx> {
1799 self.mk_infer(FloatVar(v))
1802 pub fn mk_infer(self, it: InferTy) -> Ty<'tcx> {
1803 self.mk_ty(TyInfer(it))
1806 pub fn mk_param(self,
1808 name: Name) -> Ty<'tcx> {
1809 self.mk_ty(TyParam(ParamTy { idx: index, name: name }))
1812 pub fn mk_self_type(self) -> Ty<'tcx> {
1813 self.mk_param(0, keywords::SelfType.name())
1816 pub fn mk_param_from_def(self, def: &ty::TypeParameterDef) -> Ty<'tcx> {
1817 self.mk_param(def.index, def.name)
1820 pub fn mk_anon(self, def_id: DefId, substs: &'tcx Substs<'tcx>) -> Ty<'tcx> {
1821 self.mk_ty(TyAnon(def_id, substs))
1824 pub fn intern_existential_predicates(self, eps: &[ExistentialPredicate<'tcx>])
1825 -> &'tcx Slice<ExistentialPredicate<'tcx>> {
1826 assert!(!eps.is_empty());
1827 assert!(eps.windows(2).all(|w| w[0].cmp(self, &w[1]) != Ordering::Greater));
1828 self._intern_existential_predicates(eps)
1831 pub fn intern_predicates(self, preds: &[Predicate<'tcx>])
1832 -> &'tcx Slice<Predicate<'tcx>> {
1833 // FIXME consider asking the input slice to be sorted to avoid
1834 // re-interning permutations, in which case that would be asserted
1836 if preds.len() == 0 {
1837 // The macro-generated method below asserts we don't intern an empty slice.
1840 self._intern_predicates(preds)
1844 pub fn intern_type_list(self, ts: &[Ty<'tcx>]) -> &'tcx Slice<Ty<'tcx>> {
1848 self._intern_type_list(ts)
1852 pub fn intern_substs(self, ts: &[Kind<'tcx>]) -> &'tcx Slice<Kind<'tcx>> {
1856 self._intern_substs(ts)
1860 pub fn mk_fn_sig<I>(self,
1864 unsafety: hir::Unsafety,
1866 -> <I::Item as InternIteratorElement<Ty<'tcx>, ty::FnSig<'tcx>>>::Output
1868 I::Item: InternIteratorElement<Ty<'tcx>, ty::FnSig<'tcx>>
1870 inputs.chain(iter::once(output)).intern_with(|xs| ty::FnSig {
1871 inputs_and_output: self.intern_type_list(xs),
1872 variadic, unsafety, abi
1876 pub fn mk_existential_predicates<I: InternAs<[ExistentialPredicate<'tcx>],
1877 &'tcx Slice<ExistentialPredicate<'tcx>>>>(self, iter: I)
1879 iter.intern_with(|xs| self.intern_existential_predicates(xs))
1882 pub fn mk_predicates<I: InternAs<[Predicate<'tcx>],
1883 &'tcx Slice<Predicate<'tcx>>>>(self, iter: I)
1885 iter.intern_with(|xs| self.intern_predicates(xs))
1888 pub fn mk_type_list<I: InternAs<[Ty<'tcx>],
1889 &'tcx Slice<Ty<'tcx>>>>(self, iter: I) -> I::Output {
1890 iter.intern_with(|xs| self.intern_type_list(xs))
1893 pub fn mk_substs<I: InternAs<[Kind<'tcx>],
1894 &'tcx Slice<Kind<'tcx>>>>(self, iter: I) -> I::Output {
1895 iter.intern_with(|xs| self.intern_substs(xs))
1898 pub fn mk_substs_trait(self,
1901 -> &'tcx Substs<'tcx>
1903 self.mk_substs(iter::once(s).chain(t.into_iter().cloned()).map(Kind::from))
1906 pub fn lint_node<S: Into<MultiSpan>>(self,
1907 lint: &'static Lint,
1911 self.struct_span_lint_node(lint, id, span.into(), msg).emit()
1914 pub fn lint_node_note<S: Into<MultiSpan>>(self,
1915 lint: &'static Lint,
1920 let mut err = self.struct_span_lint_node(lint, id, span.into(), msg);
1925 pub fn lint_level_at_node(self, lint: &'static Lint, mut id: NodeId)
1926 -> (lint::Level, lint::LintSource)
1928 // Right now we insert a `with_ignore` node in the dep graph here to
1929 // ignore the fact that `lint_levels` below depends on the entire crate.
1930 // For now this'll prevent false positives of recompiling too much when
1931 // anything changes.
1933 // Once red/green incremental compilation lands we should be able to
1934 // remove this because while the crate changes often the lint level map
1935 // will change rarely.
1936 self.dep_graph.with_ignore(|| {
1937 let sets = self.lint_levels(LOCAL_CRATE);
1939 let hir_id = self.hir.definitions().node_to_hir_id(id);
1940 if let Some(pair) = sets.level_and_source(lint, hir_id) {
1943 let next = self.hir.get_parent_node(id);
1945 bug!("lint traversal reached the root of the crate");
1952 pub fn struct_span_lint_node<S: Into<MultiSpan>>(self,
1953 lint: &'static Lint,
1957 -> DiagnosticBuilder<'tcx>
1959 let (level, src) = self.lint_level_at_node(lint, id);
1960 lint::struct_lint_level(self.sess, lint, level, src, Some(span.into()), msg)
1963 pub fn struct_lint_node(self, lint: &'static Lint, id: NodeId, msg: &str)
1964 -> DiagnosticBuilder<'tcx>
1966 let (level, src) = self.lint_level_at_node(lint, id);
1967 lint::struct_lint_level(self.sess, lint, level, src, None, msg)
1971 pub trait InternAs<T: ?Sized, R> {
1973 fn intern_with<F>(self, f: F) -> Self::Output
1974 where F: FnOnce(&T) -> R;
1977 impl<I, T, R, E> InternAs<[T], R> for I
1978 where E: InternIteratorElement<T, R>,
1979 I: Iterator<Item=E> {
1980 type Output = E::Output;
1981 fn intern_with<F>(self, f: F) -> Self::Output
1982 where F: FnOnce(&[T]) -> R {
1983 E::intern_with(self, f)
1987 pub trait InternIteratorElement<T, R>: Sized {
1989 fn intern_with<I: Iterator<Item=Self>, F: FnOnce(&[T]) -> R>(iter: I, f: F) -> Self::Output;
1992 impl<T, R> InternIteratorElement<T, R> for T {
1994 fn intern_with<I: Iterator<Item=Self>, F: FnOnce(&[T]) -> R>(iter: I, f: F) -> Self::Output {
1995 f(&iter.collect::<AccumulateVec<[_; 8]>>())
1999 impl<'a, T, R> InternIteratorElement<T, R> for &'a T
2003 fn intern_with<I: Iterator<Item=Self>, F: FnOnce(&[T]) -> R>(iter: I, f: F) -> Self::Output {
2004 f(&iter.cloned().collect::<AccumulateVec<[_; 8]>>())
2008 impl<T, R, E> InternIteratorElement<T, R> for Result<T, E> {
2009 type Output = Result<R, E>;
2010 fn intern_with<I: Iterator<Item=Self>, F: FnOnce(&[T]) -> R>(iter: I, f: F) -> Self::Output {
2011 Ok(f(&iter.collect::<Result<AccumulateVec<[_; 8]>, _>>()?))
2015 struct NamedRegionMap {
2016 defs: FxHashMap<HirId, resolve_lifetime::Region>,
2017 late_bound: FxHashSet<HirId>,
2018 object_lifetime_defaults: FxHashMap<HirId, Rc<Vec<ObjectLifetimeDefault>>>,
2021 pub fn provide(providers: &mut ty::maps::Providers) {
2022 // FIXME(#44234) - almost all of these queries have no sub-queries and
2023 // therefore no actual inputs, they're just reading tables calculated in
2024 // resolve! Does this work? Unsure! That's what the issue is about
2025 providers.in_scope_traits = |tcx, id| tcx.gcx.trait_map.get(&id).cloned();
2026 providers.module_exports = |tcx, id| tcx.gcx.export_map.get(&id).cloned();
2027 providers.named_region = |tcx, id| tcx.gcx.named_region_map.defs.get(&id).cloned();
2028 providers.is_late_bound = |tcx, id| tcx.gcx.named_region_map.late_bound.contains(&id);
2029 providers.object_lifetime_defaults = |tcx, id| {
2030 tcx.gcx.named_region_map.object_lifetime_defaults.get(&id).cloned()
2032 providers.crate_name = |tcx, id| {
2033 assert_eq!(id, LOCAL_CRATE);
2036 providers.get_lang_items = |tcx, id| {
2037 assert_eq!(id, LOCAL_CRATE);
2038 Rc::new(middle::lang_items::collect(tcx))
2040 providers.freevars = |tcx, id| tcx.gcx.freevars.get(&id).cloned();
2041 providers.maybe_unused_trait_import = |tcx, id| {
2042 tcx.maybe_unused_trait_imports.contains(&id)
2044 providers.maybe_unused_extern_crates = |tcx, cnum| {
2045 assert_eq!(cnum, LOCAL_CRATE);
2046 Rc::new(tcx.maybe_unused_extern_crates.clone())
2049 providers.stability_index = |tcx, cnum| {
2050 assert_eq!(cnum, LOCAL_CRATE);
2051 Rc::new(stability::Index::new(tcx))
2053 providers.lookup_stability = |tcx, id| {
2054 assert_eq!(id.krate, LOCAL_CRATE);
2055 let id = tcx.hir.definitions().def_index_to_hir_id(id.index);
2056 tcx.stability().local_stability(id)
2058 providers.lookup_deprecation_entry = |tcx, id| {
2059 assert_eq!(id.krate, LOCAL_CRATE);
2060 let id = tcx.hir.definitions().def_index_to_hir_id(id.index);
2061 tcx.stability().local_deprecation_entry(id)