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_owner_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_owner_def_id), var_id.local_id),
730 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 freevars: FxHashMap<HirId, Rc<Vec<hir::Freevar>>>,
842 maybe_unused_trait_imports: FxHashSet<HirId>,
844 maybe_unused_extern_crates: Vec<(HirId, 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 /// Set of nodes which mark locals as mutable which end up getting used at
855 /// some point. Local variable definitions not in this set can be warned
857 pub used_mut_nodes: RefCell<NodeSet>,
859 /// Caches the results of trait selection. This cache is used
860 /// for things that do not have to do with the parameters in scope.
861 pub selection_cache: traits::SelectionCache<'tcx>,
863 /// Caches the results of trait evaluation. This cache is used
864 /// for things that do not have to do with the parameters in scope.
865 /// Merge this with `selection_cache`?
866 pub evaluation_cache: traits::EvaluationCache<'tcx>,
868 /// Maps Expr NodeId's to `true` iff `&expr` can have 'static lifetime.
869 pub rvalue_promotable_to_static: RefCell<NodeMap<bool>>,
871 /// The definite name of the current crate after taking into account
872 /// attributes, commandline parameters, etc.
873 pub crate_name: Symbol,
875 /// Data layout specification for the current target.
876 pub data_layout: TargetDataLayout,
878 /// Used to prevent layout from recursing too deeply.
879 pub layout_depth: Cell<usize>,
881 /// Map from function to the `#[derive]` mode that it's defining. Only used
882 /// by `proc-macro` crates.
883 pub derive_macros: RefCell<NodeMap<Symbol>>,
885 stability_interner: RefCell<FxHashSet<&'tcx attr::Stability>>,
887 layout_interner: RefCell<FxHashSet<&'tcx Layout>>,
889 /// A vector of every trait accessible in the whole crate
890 /// (i.e. including those from subcrates). This is used only for
891 /// error reporting, and so is lazily initialized and generally
892 /// shouldn't taint the common path (hence the RefCell).
893 pub all_traits: RefCell<Option<Vec<DefId>>>,
896 impl<'tcx> GlobalCtxt<'tcx> {
897 /// Get the global TyCtxt.
898 pub fn global_tcx<'a>(&'a self) -> TyCtxt<'a, 'tcx, 'tcx> {
901 interners: &self.global_interners
906 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
907 pub fn alloc_generics(self, generics: ty::Generics) -> &'gcx ty::Generics {
908 self.global_arenas.generics.alloc(generics)
911 pub fn alloc_steal_mir(self, mir: Mir<'gcx>) -> &'gcx Steal<Mir<'gcx>> {
912 self.global_arenas.steal_mir.alloc(Steal::new(mir))
915 pub fn alloc_mir(self, mir: Mir<'gcx>) -> &'gcx Mir<'gcx> {
916 self.global_arenas.mir.alloc(mir)
919 pub fn alloc_tables(self, tables: ty::TypeckTables<'gcx>) -> &'gcx ty::TypeckTables<'gcx> {
920 self.global_arenas.tables.alloc(tables)
923 pub fn alloc_trait_def(self, def: ty::TraitDef) -> &'gcx ty::TraitDef {
924 self.global_arenas.trait_def.alloc(def)
927 pub fn alloc_adt_def(self,
930 variants: Vec<ty::VariantDef>,
932 -> &'gcx ty::AdtDef {
933 let def = ty::AdtDef::new(self, did, kind, variants, repr);
934 self.global_arenas.adt_def.alloc(def)
937 pub fn intern_stability(self, stab: attr::Stability) -> &'gcx attr::Stability {
938 if let Some(st) = self.stability_interner.borrow().get(&stab) {
942 let interned = self.global_interners.arena.alloc(stab);
943 if let Some(prev) = self.stability_interner.borrow_mut().replace(interned) {
944 bug!("Tried to overwrite interned Stability: {:?}", prev)
949 pub fn intern_layout(self, layout: Layout) -> &'gcx Layout {
950 if let Some(layout) = self.layout_interner.borrow().get(&layout) {
954 let interned = self.global_arenas.layout.alloc(layout);
955 if let Some(prev) = self.layout_interner.borrow_mut().replace(interned) {
956 bug!("Tried to overwrite interned Layout: {:?}", prev)
961 pub fn lift<T: ?Sized + Lift<'tcx>>(self, value: &T) -> Option<T::Lifted> {
962 value.lift_to_tcx(self)
965 /// Like lift, but only tries in the global tcx.
966 pub fn lift_to_global<T: ?Sized + Lift<'gcx>>(self, value: &T) -> Option<T::Lifted> {
967 value.lift_to_tcx(self.global_tcx())
970 /// Returns true if self is the same as self.global_tcx().
971 fn is_global(self) -> bool {
972 let local = self.interners as *const _;
973 let global = &self.global_interners as *const _;
974 local as usize == global as usize
977 /// Create a type context and call the closure with a `TyCtxt` reference
978 /// to the context. The closure enforces that the type context and any interned
979 /// value (types, substs, etc.) can only be used while `ty::tls` has a valid
980 /// reference to the context, to allow formatting values that need it.
981 pub fn create_and_enter<F, R>(s: &'tcx Session,
982 local_providers: ty::maps::Providers<'tcx>,
983 extern_providers: ty::maps::Providers<'tcx>,
984 mir_passes: Rc<Passes>,
985 arenas: &'tcx GlobalArenas<'tcx>,
986 arena: &'tcx DroplessArena,
987 resolutions: ty::Resolutions,
988 named_region_map: resolve_lifetime::NamedRegionMap,
989 hir: hir_map::Map<'tcx>,
992 where F: for<'b> FnOnce(TyCtxt<'b, 'tcx, 'tcx>) -> R
994 let data_layout = TargetDataLayout::parse(s);
995 let interners = CtxtInterners::new(arena);
996 let common_types = CommonTypes::new(&interners);
997 let dep_graph = hir.dep_graph.clone();
998 let max_cnum = s.cstore.crates_untracked().iter().map(|c| c.as_usize()).max().unwrap_or(0);
999 let mut providers = IndexVec::from_elem_n(extern_providers, max_cnum + 1);
1000 providers[LOCAL_CRATE] = local_providers;
1002 let def_path_hash_to_def_id = if s.opts.build_dep_graph() {
1003 let upstream_def_path_tables: Vec<(CrateNum, Rc<_>)> = s
1007 .map(|&cnum| (cnum, s.cstore.def_path_table(cnum)))
1010 let def_path_tables = || {
1011 upstream_def_path_tables
1013 .map(|&(cnum, ref rc)| (cnum, &**rc))
1014 .chain(iter::once((LOCAL_CRATE, hir.definitions().def_path_table())))
1017 // Precompute the capacity of the hashmap so we don't have to
1018 // re-allocate when populating it.
1019 let capacity = def_path_tables().map(|(_, t)| t.size()).sum::<usize>();
1021 let mut map: FxHashMap<_, _> = FxHashMap::with_capacity_and_hasher(
1023 ::std::default::Default::default()
1026 for (cnum, def_path_table) in def_path_tables() {
1027 def_path_table.add_def_path_hashes_to(cnum, &mut map);
1035 tls::enter_global(GlobalCtxt {
1037 trans_trait_caches: traits::trans::TransTraitCaches::new(dep_graph.clone()),
1038 global_arenas: arenas,
1039 global_interners: interners,
1040 dep_graph: dep_graph.clone(),
1041 types: common_types,
1042 named_region_map: NamedRegionMap {
1044 named_region_map.defs
1046 .map(|(k, v)| (hir.node_to_hir_id(k), v))
1049 named_region_map.late_bound
1051 .map(|k| hir.node_to_hir_id(k))
1053 object_lifetime_defaults:
1054 named_region_map.object_lifetime_defaults
1056 .map(|(k, v)| (hir.node_to_hir_id(k), Rc::new(v)))
1059 trait_map: resolutions.trait_map.into_iter().map(|(k, v)| {
1060 (hir.node_to_hir_id(k), Rc::new(v))
1062 export_map: resolutions.export_map.into_iter().map(|(k, v)| {
1063 (hir.node_to_hir_id(k), Rc::new(v))
1065 freevars: resolutions.freevars.into_iter().map(|(k, v)| {
1066 (hir.node_to_hir_id(k), Rc::new(v))
1068 maybe_unused_trait_imports:
1069 resolutions.maybe_unused_trait_imports
1071 .map(|id| hir.node_to_hir_id(id))
1073 maybe_unused_extern_crates:
1074 resolutions.maybe_unused_extern_crates
1076 .map(|(id, sp)| (hir.node_to_hir_id(id), sp))
1079 def_path_hash_to_def_id,
1080 maps: maps::Maps::new(providers),
1082 rcache: RefCell::new(FxHashMap()),
1083 normalized_cache: RefCell::new(FxHashMap()),
1084 inhabitedness_cache: RefCell::new(FxHashMap()),
1085 used_mut_nodes: RefCell::new(NodeSet()),
1086 selection_cache: traits::SelectionCache::new(),
1087 evaluation_cache: traits::EvaluationCache::new(),
1088 rvalue_promotable_to_static: RefCell::new(NodeMap()),
1089 crate_name: Symbol::intern(crate_name),
1091 layout_interner: RefCell::new(FxHashSet()),
1092 layout_depth: Cell::new(0),
1093 derive_macros: RefCell::new(NodeMap()),
1094 stability_interner: RefCell::new(FxHashSet()),
1095 all_traits: RefCell::new(None),
1099 pub fn consider_optimizing<T: Fn() -> String>(&self, msg: T) -> bool {
1100 let cname = self.crate_name(LOCAL_CRATE).as_str();
1101 self.sess.consider_optimizing(&cname, msg)
1104 pub fn lang_items(self) -> Rc<middle::lang_items::LanguageItems> {
1105 // FIXME(#42293) Right now we insert a `with_ignore` node in the dep
1106 // graph here to ignore the fact that `get_lang_items` below depends on
1107 // the entire crate. For now this'll prevent false positives of
1108 // recompiling too much when anything changes.
1110 // Once red/green incremental compilation lands we should be able to
1111 // remove this because while the crate changes often the lint level map
1112 // will change rarely.
1113 self.dep_graph.with_ignore(|| {
1114 self.get_lang_items(LOCAL_CRATE)
1118 pub fn stability(self) -> Rc<stability::Index<'tcx>> {
1119 // FIXME(#42293) we should actually track this, but fails too many tests
1121 self.dep_graph.with_ignore(|| {
1122 self.stability_index(LOCAL_CRATE)
1126 pub fn crates(self) -> Rc<Vec<CrateNum>> {
1127 self.all_crate_nums(LOCAL_CRATE)
1131 impl<'gcx: 'tcx, 'tcx> GlobalCtxt<'gcx> {
1132 /// Call the closure with a local `TyCtxt` using the given arena.
1133 pub fn enter_local<F, R>(&self, arena: &'tcx DroplessArena, f: F) -> R
1134 where F: for<'a> FnOnce(TyCtxt<'a, 'gcx, 'tcx>) -> R
1136 let interners = CtxtInterners::new(arena);
1137 tls::enter(self, &interners, f)
1141 /// A trait implemented for all X<'a> types which can be safely and
1142 /// efficiently converted to X<'tcx> as long as they are part of the
1143 /// provided TyCtxt<'tcx>.
1144 /// This can be done, for example, for Ty<'tcx> or &'tcx Substs<'tcx>
1145 /// by looking them up in their respective interners.
1147 /// However, this is still not the best implementation as it does
1148 /// need to compare the components, even for interned values.
1149 /// It would be more efficient if TypedArena provided a way to
1150 /// determine whether the address is in the allocated range.
1152 /// None is returned if the value or one of the components is not part
1153 /// of the provided context.
1154 /// For Ty, None can be returned if either the type interner doesn't
1155 /// contain the TypeVariants key or if the address of the interned
1156 /// pointer differs. The latter case is possible if a primitive type,
1157 /// e.g. `()` or `u8`, was interned in a different context.
1158 pub trait Lift<'tcx> {
1160 fn lift_to_tcx<'a, 'gcx>(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Option<Self::Lifted>;
1163 impl<'a, 'tcx> Lift<'tcx> for ty::ParamEnv<'a> {
1164 type Lifted = ty::ParamEnv<'tcx>;
1165 fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>) -> Option<ty::ParamEnv<'tcx>> {
1166 self.caller_bounds.lift_to_tcx(tcx).and_then(|caller_bounds| {
1168 reveal: self.reveal,
1175 impl<'a, 'tcx> Lift<'tcx> for Ty<'a> {
1176 type Lifted = Ty<'tcx>;
1177 fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>) -> Option<Ty<'tcx>> {
1178 if tcx.interners.arena.in_arena(*self as *const _) {
1179 return Some(unsafe { mem::transmute(*self) });
1181 // Also try in the global tcx if we're not that.
1182 if !tcx.is_global() {
1183 self.lift_to_tcx(tcx.global_tcx())
1190 impl<'a, 'tcx> Lift<'tcx> for &'a Substs<'a> {
1191 type Lifted = &'tcx Substs<'tcx>;
1192 fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>) -> Option<&'tcx Substs<'tcx>> {
1193 if self.len() == 0 {
1194 return Some(Slice::empty());
1196 if tcx.interners.arena.in_arena(&self[..] as *const _) {
1197 return Some(unsafe { mem::transmute(*self) });
1199 // Also try in the global tcx if we're not that.
1200 if !tcx.is_global() {
1201 self.lift_to_tcx(tcx.global_tcx())
1208 impl<'a, 'tcx> Lift<'tcx> for Region<'a> {
1209 type Lifted = Region<'tcx>;
1210 fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>) -> Option<Region<'tcx>> {
1211 if tcx.interners.arena.in_arena(*self as *const _) {
1212 return Some(unsafe { mem::transmute(*self) });
1214 // Also try in the global tcx if we're not that.
1215 if !tcx.is_global() {
1216 self.lift_to_tcx(tcx.global_tcx())
1223 impl<'a, 'tcx> Lift<'tcx> for &'a Slice<Ty<'a>> {
1224 type Lifted = &'tcx Slice<Ty<'tcx>>;
1225 fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>)
1226 -> Option<&'tcx Slice<Ty<'tcx>>> {
1227 if self.len() == 0 {
1228 return Some(Slice::empty());
1230 if tcx.interners.arena.in_arena(*self as *const _) {
1231 return Some(unsafe { mem::transmute(*self) });
1233 // Also try in the global tcx if we're not that.
1234 if !tcx.is_global() {
1235 self.lift_to_tcx(tcx.global_tcx())
1242 impl<'a, 'tcx> Lift<'tcx> for &'a Slice<ExistentialPredicate<'a>> {
1243 type Lifted = &'tcx Slice<ExistentialPredicate<'tcx>>;
1244 fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>)
1245 -> Option<&'tcx Slice<ExistentialPredicate<'tcx>>> {
1246 if self.is_empty() {
1247 return Some(Slice::empty());
1249 if tcx.interners.arena.in_arena(*self as *const _) {
1250 return Some(unsafe { mem::transmute(*self) });
1252 // Also try in the global tcx if we're not that.
1253 if !tcx.is_global() {
1254 self.lift_to_tcx(tcx.global_tcx())
1261 impl<'a, 'tcx> Lift<'tcx> for &'a Slice<Predicate<'a>> {
1262 type Lifted = &'tcx Slice<Predicate<'tcx>>;
1263 fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>)
1264 -> Option<&'tcx Slice<Predicate<'tcx>>> {
1265 if self.is_empty() {
1266 return Some(Slice::empty());
1268 if tcx.interners.arena.in_arena(*self as *const _) {
1269 return Some(unsafe { mem::transmute(*self) });
1271 // Also try in the global tcx if we're not that.
1272 if !tcx.is_global() {
1273 self.lift_to_tcx(tcx.global_tcx())
1281 use super::{CtxtInterners, GlobalCtxt, TyCtxt};
1283 use std::cell::Cell;
1287 /// Marker types used for the scoped TLS slot.
1288 /// The type context cannot be used directly because the scoped TLS
1289 /// in libstd doesn't allow types generic over lifetimes.
1290 enum ThreadLocalGlobalCtxt {}
1291 enum ThreadLocalInterners {}
1294 static TLS_TCX: Cell<Option<(*const ThreadLocalGlobalCtxt,
1295 *const ThreadLocalInterners)>> = Cell::new(None)
1298 fn span_debug(span: syntax_pos::Span, f: &mut fmt::Formatter) -> fmt::Result {
1300 write!(f, "{}", tcx.sess.codemap().span_to_string(span))
1304 pub fn enter_global<'gcx, F, R>(gcx: GlobalCtxt<'gcx>, f: F) -> R
1305 where F: for<'a> FnOnce(TyCtxt<'a, 'gcx, 'gcx>) -> R
1307 syntax_pos::SPAN_DEBUG.with(|span_dbg| {
1308 let original_span_debug = span_dbg.get();
1309 span_dbg.set(span_debug);
1310 let result = enter(&gcx, &gcx.global_interners, f);
1311 span_dbg.set(original_span_debug);
1316 pub fn enter<'a, 'gcx: 'tcx, 'tcx, F, R>(gcx: &'a GlobalCtxt<'gcx>,
1317 interners: &'a CtxtInterners<'tcx>,
1319 where F: FnOnce(TyCtxt<'a, 'gcx, 'tcx>) -> R
1321 let gcx_ptr = gcx as *const _ as *const ThreadLocalGlobalCtxt;
1322 let interners_ptr = interners as *const _ as *const ThreadLocalInterners;
1323 TLS_TCX.with(|tls| {
1324 let prev = tls.get();
1325 tls.set(Some((gcx_ptr, interners_ptr)));
1326 let ret = f(TyCtxt {
1335 pub fn with<F, R>(f: F) -> R
1336 where F: for<'a, 'gcx, 'tcx> FnOnce(TyCtxt<'a, 'gcx, 'tcx>) -> R
1338 TLS_TCX.with(|tcx| {
1339 let (gcx, interners) = tcx.get().unwrap();
1340 let gcx = unsafe { &*(gcx as *const GlobalCtxt) };
1341 let interners = unsafe { &*(interners as *const CtxtInterners) };
1349 pub fn with_opt<F, R>(f: F) -> R
1350 where F: for<'a, 'gcx, 'tcx> FnOnce(Option<TyCtxt<'a, 'gcx, 'tcx>>) -> R
1352 if TLS_TCX.with(|tcx| tcx.get().is_some()) {
1353 with(|v| f(Some(v)))
1360 macro_rules! sty_debug_print {
1361 ($ctxt: expr, $($variant: ident),*) => {{
1362 // curious inner module to allow variant names to be used as
1364 #[allow(non_snake_case)]
1366 use ty::{self, TyCtxt};
1367 use ty::context::Interned;
1369 #[derive(Copy, Clone)]
1372 region_infer: usize,
1377 pub fn go(tcx: TyCtxt) {
1378 let mut total = DebugStat {
1380 region_infer: 0, ty_infer: 0, both_infer: 0,
1382 $(let mut $variant = total;)*
1385 for &Interned(t) in tcx.interners.type_.borrow().iter() {
1386 let variant = match t.sty {
1387 ty::TyBool | ty::TyChar | ty::TyInt(..) | ty::TyUint(..) |
1388 ty::TyFloat(..) | ty::TyStr | ty::TyNever => continue,
1389 ty::TyError => /* unimportant */ continue,
1390 $(ty::$variant(..) => &mut $variant,)*
1392 let region = t.flags.intersects(ty::TypeFlags::HAS_RE_INFER);
1393 let ty = t.flags.intersects(ty::TypeFlags::HAS_TY_INFER);
1397 if region { total.region_infer += 1; variant.region_infer += 1 }
1398 if ty { total.ty_infer += 1; variant.ty_infer += 1 }
1399 if region && ty { total.both_infer += 1; variant.both_infer += 1 }
1401 println!("Ty interner total ty region both");
1402 $(println!(" {:18}: {uses:6} {usespc:4.1}%, \
1403 {ty:4.1}% {region:5.1}% {both:4.1}%",
1404 stringify!($variant),
1405 uses = $variant.total,
1406 usespc = $variant.total as f64 * 100.0 / total.total as f64,
1407 ty = $variant.ty_infer as f64 * 100.0 / total.total as f64,
1408 region = $variant.region_infer as f64 * 100.0 / total.total as f64,
1409 both = $variant.both_infer as f64 * 100.0 / total.total as f64);
1411 println!(" total {uses:6} \
1412 {ty:4.1}% {region:5.1}% {both:4.1}%",
1414 ty = total.ty_infer as f64 * 100.0 / total.total as f64,
1415 region = total.region_infer as f64 * 100.0 / total.total as f64,
1416 both = total.both_infer as f64 * 100.0 / total.total as f64)
1424 impl<'a, 'tcx> TyCtxt<'a, 'tcx, 'tcx> {
1425 pub fn print_debug_stats(self) {
1428 TyAdt, TyArray, TySlice, TyRawPtr, TyRef, TyFnDef, TyFnPtr, TyGenerator,
1429 TyDynamic, TyClosure, TyTuple, TyParam, TyInfer, TyProjection, TyAnon);
1431 println!("Substs interner: #{}", self.interners.substs.borrow().len());
1432 println!("Region interner: #{}", self.interners.region.borrow().len());
1433 println!("Stability interner: #{}", self.stability_interner.borrow().len());
1434 println!("Layout interner: #{}", self.layout_interner.borrow().len());
1439 /// An entry in an interner.
1440 struct Interned<'tcx, T: 'tcx+?Sized>(&'tcx T);
1442 // NB: An Interned<Ty> compares and hashes as a sty.
1443 impl<'tcx> PartialEq for Interned<'tcx, TyS<'tcx>> {
1444 fn eq(&self, other: &Interned<'tcx, TyS<'tcx>>) -> bool {
1445 self.0.sty == other.0.sty
1449 impl<'tcx> Eq for Interned<'tcx, TyS<'tcx>> {}
1451 impl<'tcx> Hash for Interned<'tcx, TyS<'tcx>> {
1452 fn hash<H: Hasher>(&self, s: &mut H) {
1457 impl<'tcx: 'lcx, 'lcx> Borrow<TypeVariants<'lcx>> for Interned<'tcx, TyS<'tcx>> {
1458 fn borrow<'a>(&'a self) -> &'a TypeVariants<'lcx> {
1463 // NB: An Interned<Slice<T>> compares and hashes as its elements.
1464 impl<'tcx, T: PartialEq> PartialEq for Interned<'tcx, Slice<T>> {
1465 fn eq(&self, other: &Interned<'tcx, Slice<T>>) -> bool {
1466 self.0[..] == other.0[..]
1470 impl<'tcx, T: Eq> Eq for Interned<'tcx, Slice<T>> {}
1472 impl<'tcx, T: Hash> Hash for Interned<'tcx, Slice<T>> {
1473 fn hash<H: Hasher>(&self, s: &mut H) {
1478 impl<'tcx: 'lcx, 'lcx> Borrow<[Ty<'lcx>]> for Interned<'tcx, Slice<Ty<'tcx>>> {
1479 fn borrow<'a>(&'a self) -> &'a [Ty<'lcx>] {
1484 impl<'tcx: 'lcx, 'lcx> Borrow<[Kind<'lcx>]> for Interned<'tcx, Substs<'tcx>> {
1485 fn borrow<'a>(&'a self) -> &'a [Kind<'lcx>] {
1490 impl<'tcx> Borrow<RegionKind> for Interned<'tcx, RegionKind> {
1491 fn borrow<'a>(&'a self) -> &'a RegionKind {
1496 impl<'tcx: 'lcx, 'lcx> Borrow<[ExistentialPredicate<'lcx>]>
1497 for Interned<'tcx, Slice<ExistentialPredicate<'tcx>>> {
1498 fn borrow<'a>(&'a self) -> &'a [ExistentialPredicate<'lcx>] {
1503 impl<'tcx: 'lcx, 'lcx> Borrow<[Predicate<'lcx>]>
1504 for Interned<'tcx, Slice<Predicate<'tcx>>> {
1505 fn borrow<'a>(&'a self) -> &'a [Predicate<'lcx>] {
1510 macro_rules! intern_method {
1511 ($lt_tcx:tt, $name:ident: $method:ident($alloc:ty,
1512 $alloc_method:ident,
1515 $needs_infer:expr) -> $ty:ty) => {
1516 impl<'a, 'gcx, $lt_tcx> TyCtxt<'a, 'gcx, $lt_tcx> {
1517 pub fn $method(self, v: $alloc) -> &$lt_tcx $ty {
1519 let key = ($alloc_to_key)(&v);
1520 if let Some(i) = self.interners.$name.borrow().get(key) {
1523 if !self.is_global() {
1524 if let Some(i) = self.global_interners.$name.borrow().get(key) {
1530 // HACK(eddyb) Depend on flags being accurate to
1531 // determine that all contents are in the global tcx.
1532 // See comments on Lift for why we can't use that.
1533 if !($needs_infer)(&v) {
1534 if !self.is_global() {
1538 let i = ($alloc_to_ret)(self.global_interners.arena.$alloc_method(v));
1539 self.global_interners.$name.borrow_mut().insert(Interned(i));
1543 // Make sure we don't end up with inference
1544 // types/regions in the global tcx.
1545 if self.is_global() {
1546 bug!("Attempted to intern `{:?}` which contains \
1547 inference types/regions in the global type context",
1552 let i = ($alloc_to_ret)(self.interners.arena.$alloc_method(v));
1553 self.interners.$name.borrow_mut().insert(Interned(i));
1560 macro_rules! direct_interners {
1561 ($lt_tcx:tt, $($name:ident: $method:ident($needs_infer:expr) -> $ty:ty),+) => {
1562 $(impl<$lt_tcx> PartialEq for Interned<$lt_tcx, $ty> {
1563 fn eq(&self, other: &Self) -> bool {
1568 impl<$lt_tcx> Eq for Interned<$lt_tcx, $ty> {}
1570 impl<$lt_tcx> Hash for Interned<$lt_tcx, $ty> {
1571 fn hash<H: Hasher>(&self, s: &mut H) {
1576 intern_method!($lt_tcx, $name: $method($ty, alloc, |x| x, |x| x, $needs_infer) -> $ty);)+
1580 pub fn keep_local<'tcx, T: ty::TypeFoldable<'tcx>>(x: &T) -> bool {
1581 x.has_type_flags(ty::TypeFlags::KEEP_IN_LOCAL_TCX)
1584 direct_interners!('tcx,
1585 region: mk_region(|r| {
1587 &ty::ReVar(_) | &ty::ReSkolemized(..) => true,
1593 macro_rules! slice_interners {
1594 ($($field:ident: $method:ident($ty:ident)),+) => (
1595 $(intern_method!('tcx, $field: $method(&[$ty<'tcx>], alloc_slice, Deref::deref,
1596 |xs: &[$ty]| -> &Slice<$ty> {
1597 unsafe { mem::transmute(xs) }
1598 }, |xs: &[$ty]| xs.iter().any(keep_local)) -> Slice<$ty<'tcx>>);)+
1603 existential_predicates: _intern_existential_predicates(ExistentialPredicate),
1604 predicates: _intern_predicates(Predicate),
1605 type_list: _intern_type_list(Ty),
1606 substs: _intern_substs(Kind)
1609 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
1610 /// Create an unsafe fn ty based on a safe fn ty.
1611 pub fn safe_to_unsafe_fn_ty(self, sig: PolyFnSig<'tcx>) -> Ty<'tcx> {
1612 assert_eq!(sig.unsafety(), hir::Unsafety::Normal);
1613 self.mk_fn_ptr(sig.map_bound(|sig| ty::FnSig {
1614 unsafety: hir::Unsafety::Unsafe,
1619 // Interns a type/name combination, stores the resulting box in cx.interners,
1620 // and returns the box as cast to an unsafe ptr (see comments for Ty above).
1621 pub fn mk_ty(self, st: TypeVariants<'tcx>) -> Ty<'tcx> {
1622 let global_interners = if !self.is_global() {
1623 Some(&self.global_interners)
1627 self.interners.intern_ty(st, global_interners)
1630 pub fn mk_mach_int(self, tm: ast::IntTy) -> Ty<'tcx> {
1632 ast::IntTy::Is => self.types.isize,
1633 ast::IntTy::I8 => self.types.i8,
1634 ast::IntTy::I16 => self.types.i16,
1635 ast::IntTy::I32 => self.types.i32,
1636 ast::IntTy::I64 => self.types.i64,
1637 ast::IntTy::I128 => self.types.i128,
1641 pub fn mk_mach_uint(self, tm: ast::UintTy) -> Ty<'tcx> {
1643 ast::UintTy::Us => self.types.usize,
1644 ast::UintTy::U8 => self.types.u8,
1645 ast::UintTy::U16 => self.types.u16,
1646 ast::UintTy::U32 => self.types.u32,
1647 ast::UintTy::U64 => self.types.u64,
1648 ast::UintTy::U128 => self.types.u128,
1652 pub fn mk_mach_float(self, tm: ast::FloatTy) -> Ty<'tcx> {
1654 ast::FloatTy::F32 => self.types.f32,
1655 ast::FloatTy::F64 => self.types.f64,
1659 pub fn mk_str(self) -> Ty<'tcx> {
1663 pub fn mk_static_str(self) -> Ty<'tcx> {
1664 self.mk_imm_ref(self.types.re_static, self.mk_str())
1667 pub fn mk_adt(self, def: &'tcx AdtDef, substs: &'tcx Substs<'tcx>) -> Ty<'tcx> {
1668 // take a copy of substs so that we own the vectors inside
1669 self.mk_ty(TyAdt(def, substs))
1672 pub fn mk_box(self, ty: Ty<'tcx>) -> Ty<'tcx> {
1673 let def_id = self.require_lang_item(lang_items::OwnedBoxLangItem);
1674 let adt_def = self.adt_def(def_id);
1675 let substs = self.mk_substs(iter::once(Kind::from(ty)));
1676 self.mk_ty(TyAdt(adt_def, substs))
1679 pub fn mk_ptr(self, tm: TypeAndMut<'tcx>) -> Ty<'tcx> {
1680 self.mk_ty(TyRawPtr(tm))
1683 pub fn mk_ref(self, r: Region<'tcx>, tm: TypeAndMut<'tcx>) -> Ty<'tcx> {
1684 self.mk_ty(TyRef(r, tm))
1687 pub fn mk_mut_ref(self, r: Region<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
1688 self.mk_ref(r, TypeAndMut {ty: ty, mutbl: hir::MutMutable})
1691 pub fn mk_imm_ref(self, r: Region<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
1692 self.mk_ref(r, TypeAndMut {ty: ty, mutbl: hir::MutImmutable})
1695 pub fn mk_mut_ptr(self, ty: Ty<'tcx>) -> Ty<'tcx> {
1696 self.mk_ptr(TypeAndMut {ty: ty, mutbl: hir::MutMutable})
1699 pub fn mk_imm_ptr(self, ty: Ty<'tcx>) -> Ty<'tcx> {
1700 self.mk_ptr(TypeAndMut {ty: ty, mutbl: hir::MutImmutable})
1703 pub fn mk_nil_ptr(self) -> Ty<'tcx> {
1704 self.mk_imm_ptr(self.mk_nil())
1707 pub fn mk_array(self, ty: Ty<'tcx>, n: usize) -> Ty<'tcx> {
1708 self.mk_ty(TyArray(ty, n))
1711 pub fn mk_slice(self, ty: Ty<'tcx>) -> Ty<'tcx> {
1712 self.mk_ty(TySlice(ty))
1715 pub fn intern_tup(self, ts: &[Ty<'tcx>], defaulted: bool) -> Ty<'tcx> {
1716 self.mk_ty(TyTuple(self.intern_type_list(ts), defaulted))
1719 pub fn mk_tup<I: InternAs<[Ty<'tcx>], Ty<'tcx>>>(self, iter: I,
1720 defaulted: bool) -> I::Output {
1721 iter.intern_with(|ts| self.mk_ty(TyTuple(self.intern_type_list(ts), defaulted)))
1724 pub fn mk_nil(self) -> Ty<'tcx> {
1725 self.intern_tup(&[], false)
1728 pub fn mk_diverging_default(self) -> Ty<'tcx> {
1729 if self.sess.features.borrow().never_type {
1732 self.intern_tup(&[], true)
1736 pub fn mk_bool(self) -> Ty<'tcx> {
1740 pub fn mk_fn_def(self, def_id: DefId,
1741 substs: &'tcx Substs<'tcx>) -> Ty<'tcx> {
1742 self.mk_ty(TyFnDef(def_id, substs))
1745 pub fn mk_fn_ptr(self, fty: PolyFnSig<'tcx>) -> Ty<'tcx> {
1746 self.mk_ty(TyFnPtr(fty))
1751 obj: ty::Binder<&'tcx Slice<ExistentialPredicate<'tcx>>>,
1752 reg: ty::Region<'tcx>
1754 self.mk_ty(TyDynamic(obj, reg))
1757 pub fn mk_projection(self,
1759 substs: &'tcx Substs<'tcx>)
1761 self.mk_ty(TyProjection(ProjectionTy {
1767 pub fn mk_closure(self,
1769 substs: &'tcx Substs<'tcx>)
1771 self.mk_closure_from_closure_substs(closure_id, ClosureSubsts {
1776 pub fn mk_closure_from_closure_substs(self,
1778 closure_substs: ClosureSubsts<'tcx>)
1780 self.mk_ty(TyClosure(closure_id, closure_substs))
1783 pub fn mk_generator(self,
1785 closure_substs: ClosureSubsts<'tcx>,
1786 interior: GeneratorInterior<'tcx>)
1788 self.mk_ty(TyGenerator(id, closure_substs, interior))
1791 pub fn mk_var(self, v: TyVid) -> Ty<'tcx> {
1792 self.mk_infer(TyVar(v))
1795 pub fn mk_int_var(self, v: IntVid) -> Ty<'tcx> {
1796 self.mk_infer(IntVar(v))
1799 pub fn mk_float_var(self, v: FloatVid) -> Ty<'tcx> {
1800 self.mk_infer(FloatVar(v))
1803 pub fn mk_infer(self, it: InferTy) -> Ty<'tcx> {
1804 self.mk_ty(TyInfer(it))
1807 pub fn mk_param(self,
1809 name: Name) -> Ty<'tcx> {
1810 self.mk_ty(TyParam(ParamTy { idx: index, name: name }))
1813 pub fn mk_self_type(self) -> Ty<'tcx> {
1814 self.mk_param(0, keywords::SelfType.name())
1817 pub fn mk_param_from_def(self, def: &ty::TypeParameterDef) -> Ty<'tcx> {
1818 self.mk_param(def.index, def.name)
1821 pub fn mk_anon(self, def_id: DefId, substs: &'tcx Substs<'tcx>) -> Ty<'tcx> {
1822 self.mk_ty(TyAnon(def_id, substs))
1825 pub fn intern_existential_predicates(self, eps: &[ExistentialPredicate<'tcx>])
1826 -> &'tcx Slice<ExistentialPredicate<'tcx>> {
1827 assert!(!eps.is_empty());
1828 assert!(eps.windows(2).all(|w| w[0].cmp(self, &w[1]) != Ordering::Greater));
1829 self._intern_existential_predicates(eps)
1832 pub fn intern_predicates(self, preds: &[Predicate<'tcx>])
1833 -> &'tcx Slice<Predicate<'tcx>> {
1834 // FIXME consider asking the input slice to be sorted to avoid
1835 // re-interning permutations, in which case that would be asserted
1837 if preds.len() == 0 {
1838 // The macro-generated method below asserts we don't intern an empty slice.
1841 self._intern_predicates(preds)
1845 pub fn intern_type_list(self, ts: &[Ty<'tcx>]) -> &'tcx Slice<Ty<'tcx>> {
1849 self._intern_type_list(ts)
1853 pub fn intern_substs(self, ts: &[Kind<'tcx>]) -> &'tcx Slice<Kind<'tcx>> {
1857 self._intern_substs(ts)
1861 pub fn mk_fn_sig<I>(self,
1865 unsafety: hir::Unsafety,
1867 -> <I::Item as InternIteratorElement<Ty<'tcx>, ty::FnSig<'tcx>>>::Output
1869 I::Item: InternIteratorElement<Ty<'tcx>, ty::FnSig<'tcx>>
1871 inputs.chain(iter::once(output)).intern_with(|xs| ty::FnSig {
1872 inputs_and_output: self.intern_type_list(xs),
1873 variadic, unsafety, abi
1877 pub fn mk_existential_predicates<I: InternAs<[ExistentialPredicate<'tcx>],
1878 &'tcx Slice<ExistentialPredicate<'tcx>>>>(self, iter: I)
1880 iter.intern_with(|xs| self.intern_existential_predicates(xs))
1883 pub fn mk_predicates<I: InternAs<[Predicate<'tcx>],
1884 &'tcx Slice<Predicate<'tcx>>>>(self, iter: I)
1886 iter.intern_with(|xs| self.intern_predicates(xs))
1889 pub fn mk_type_list<I: InternAs<[Ty<'tcx>],
1890 &'tcx Slice<Ty<'tcx>>>>(self, iter: I) -> I::Output {
1891 iter.intern_with(|xs| self.intern_type_list(xs))
1894 pub fn mk_substs<I: InternAs<[Kind<'tcx>],
1895 &'tcx Slice<Kind<'tcx>>>>(self, iter: I) -> I::Output {
1896 iter.intern_with(|xs| self.intern_substs(xs))
1899 pub fn mk_substs_trait(self,
1902 -> &'tcx Substs<'tcx>
1904 self.mk_substs(iter::once(s).chain(t.into_iter().cloned()).map(Kind::from))
1907 pub fn lint_node<S: Into<MultiSpan>>(self,
1908 lint: &'static Lint,
1912 self.struct_span_lint_node(lint, id, span.into(), msg).emit()
1915 pub fn lint_node_note<S: Into<MultiSpan>>(self,
1916 lint: &'static Lint,
1921 let mut err = self.struct_span_lint_node(lint, id, span.into(), msg);
1926 pub fn lint_level_at_node(self, lint: &'static Lint, mut id: NodeId)
1927 -> (lint::Level, lint::LintSource)
1929 // Right now we insert a `with_ignore` node in the dep graph here to
1930 // ignore the fact that `lint_levels` below depends on the entire crate.
1931 // For now this'll prevent false positives of recompiling too much when
1932 // anything changes.
1934 // Once red/green incremental compilation lands we should be able to
1935 // remove this because while the crate changes often the lint level map
1936 // will change rarely.
1937 self.dep_graph.with_ignore(|| {
1938 let sets = self.lint_levels(LOCAL_CRATE);
1940 let hir_id = self.hir.definitions().node_to_hir_id(id);
1941 if let Some(pair) = sets.level_and_source(lint, hir_id) {
1944 let next = self.hir.get_parent_node(id);
1946 bug!("lint traversal reached the root of the crate");
1953 pub fn struct_span_lint_node<S: Into<MultiSpan>>(self,
1954 lint: &'static Lint,
1958 -> DiagnosticBuilder<'tcx>
1960 let (level, src) = self.lint_level_at_node(lint, id);
1961 lint::struct_lint_level(self.sess, lint, level, src, Some(span.into()), msg)
1964 pub fn struct_lint_node(self, lint: &'static Lint, id: NodeId, msg: &str)
1965 -> DiagnosticBuilder<'tcx>
1967 let (level, src) = self.lint_level_at_node(lint, id);
1968 lint::struct_lint_level(self.sess, lint, level, src, None, msg)
1972 pub trait InternAs<T: ?Sized, R> {
1974 fn intern_with<F>(self, f: F) -> Self::Output
1975 where F: FnOnce(&T) -> R;
1978 impl<I, T, R, E> InternAs<[T], R> for I
1979 where E: InternIteratorElement<T, R>,
1980 I: Iterator<Item=E> {
1981 type Output = E::Output;
1982 fn intern_with<F>(self, f: F) -> Self::Output
1983 where F: FnOnce(&[T]) -> R {
1984 E::intern_with(self, f)
1988 pub trait InternIteratorElement<T, R>: Sized {
1990 fn intern_with<I: Iterator<Item=Self>, F: FnOnce(&[T]) -> R>(iter: I, f: F) -> Self::Output;
1993 impl<T, R> InternIteratorElement<T, R> for T {
1995 fn intern_with<I: Iterator<Item=Self>, F: FnOnce(&[T]) -> R>(iter: I, f: F) -> Self::Output {
1996 f(&iter.collect::<AccumulateVec<[_; 8]>>())
2000 impl<'a, T, R> InternIteratorElement<T, R> for &'a T
2004 fn intern_with<I: Iterator<Item=Self>, F: FnOnce(&[T]) -> R>(iter: I, f: F) -> Self::Output {
2005 f(&iter.cloned().collect::<AccumulateVec<[_; 8]>>())
2009 impl<T, R, E> InternIteratorElement<T, R> for Result<T, E> {
2010 type Output = Result<R, E>;
2011 fn intern_with<I: Iterator<Item=Self>, F: FnOnce(&[T]) -> R>(iter: I, f: F) -> Self::Output {
2012 Ok(f(&iter.collect::<Result<AccumulateVec<[_; 8]>, _>>()?))
2016 struct NamedRegionMap {
2017 defs: FxHashMap<HirId, resolve_lifetime::Region>,
2018 late_bound: FxHashSet<HirId>,
2019 object_lifetime_defaults: FxHashMap<HirId, Rc<Vec<ObjectLifetimeDefault>>>,
2022 pub fn provide(providers: &mut ty::maps::Providers) {
2023 // FIXME(#44234) - almost all of these queries have no sub-queries and
2024 // therefore no actual inputs, they're just reading tables calculated in
2025 // resolve! Does this work? Unsure! That's what the issue is about
2026 providers.in_scope_traits = |tcx, id| tcx.gcx.trait_map.get(&id).cloned();
2027 providers.module_exports = |tcx, id| tcx.gcx.export_map.get(&id).cloned();
2028 providers.named_region = |tcx, id| tcx.gcx.named_region_map.defs.get(&id).cloned();
2029 providers.is_late_bound = |tcx, id| tcx.gcx.named_region_map.late_bound.contains(&id);
2030 providers.object_lifetime_defaults = |tcx, id| {
2031 tcx.gcx.named_region_map.object_lifetime_defaults.get(&id).cloned()
2033 providers.crate_name = |tcx, id| {
2034 assert_eq!(id, LOCAL_CRATE);
2037 providers.get_lang_items = |tcx, id| {
2038 assert_eq!(id, LOCAL_CRATE);
2039 Rc::new(middle::lang_items::collect(tcx))
2041 providers.freevars = |tcx, id| tcx.gcx.freevars.get(&id).cloned();
2042 providers.maybe_unused_trait_import = |tcx, id| {
2043 tcx.maybe_unused_trait_imports.contains(&id)
2045 providers.maybe_unused_extern_crates = |tcx, cnum| {
2046 assert_eq!(cnum, LOCAL_CRATE);
2047 Rc::new(tcx.maybe_unused_extern_crates.clone())
2050 providers.stability_index = |tcx, cnum| {
2051 assert_eq!(cnum, LOCAL_CRATE);
2052 Rc::new(stability::Index::new(tcx))
2054 providers.lookup_stability = |tcx, id| {
2055 assert_eq!(id.krate, LOCAL_CRATE);
2056 let id = tcx.hir.definitions().def_index_to_hir_id(id.index);
2057 tcx.stability().local_stability(id)
2059 providers.lookup_deprecation_entry = |tcx, id| {
2060 assert_eq!(id.krate, LOCAL_CRATE);
2061 let id = tcx.hir.definitions().def_index_to_hir_id(id.index);
2062 tcx.stability().local_deprecation_entry(id)