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, ItemLocalId};
18 use hir::def::{Def, Export};
19 use hir::def_id::{CrateNum, DefId, DefIndex, 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::const_val::ConstVal;
25 use middle::cstore::{CrateStore, LinkMeta, EncodedMetadataHashes};
26 use middle::cstore::EncodedMetadata;
27 use middle::free_region::FreeRegionMap;
28 use middle::lang_items;
29 use middle::resolve_lifetime::{self, ObjectLifetimeDefault};
30 use middle::stability;
32 use mir::transform::Passes;
33 use ty::subst::{Kind, Substs};
36 use ty::{self, Ty, TypeAndMut};
37 use ty::{TyS, TypeVariants, Slice};
38 use ty::{AdtKind, AdtDef, ClosureSubsts, GeneratorInterior, Region, Const};
39 use ty::{PolyFnSig, InferTy, ParamTy, ProjectionTy, ExistentialPredicate, Predicate};
41 use ty::{TyVar, TyVid, IntVar, IntVid, FloatVar, FloatVid};
42 use ty::TypeVariants::*;
43 use ty::layout::{Layout, TargetDataLayout};
44 use ty::inhabitedness::DefIdForest;
48 use util::nodemap::{NodeMap, NodeSet, DefIdSet, ItemLocalMap};
49 use util::nodemap::{FxHashMap, FxHashSet};
50 use rustc_data_structures::accumulate_vec::AccumulateVec;
51 use rustc_data_structures::stable_hasher::{HashStable, StableHasher,
54 use arena::{TypedArena, DroplessArena};
55 use rustc_const_math::{ConstInt, ConstUsize};
56 use rustc_data_structures::indexed_vec::IndexVec;
58 use std::borrow::Borrow;
59 use std::cell::{Cell, RefCell};
60 use std::cmp::Ordering;
61 use std::collections::hash_map::{self, Entry};
62 use std::hash::{Hash, Hasher};
68 use syntax::ast::{self, Name, NodeId};
70 use syntax::codemap::MultiSpan;
71 use syntax::symbol::{Symbol, keywords};
77 pub struct GlobalArenas<'tcx> {
79 layout: TypedArena<Layout>,
82 generics: TypedArena<ty::Generics>,
83 trait_def: TypedArena<ty::TraitDef>,
84 adt_def: TypedArena<ty::AdtDef>,
85 steal_mir: TypedArena<Steal<Mir<'tcx>>>,
86 mir: TypedArena<Mir<'tcx>>,
87 tables: TypedArena<ty::TypeckTables<'tcx>>,
90 impl<'tcx> GlobalArenas<'tcx> {
91 pub fn new() -> GlobalArenas<'tcx> {
93 layout: TypedArena::new(),
94 generics: TypedArena::new(),
95 trait_def: TypedArena::new(),
96 adt_def: TypedArena::new(),
97 steal_mir: TypedArena::new(),
98 mir: TypedArena::new(),
99 tables: TypedArena::new(),
104 pub struct CtxtInterners<'tcx> {
105 /// The arena that types, regions, etc are allocated from
106 arena: &'tcx DroplessArena,
108 /// Specifically use a speedy hash algorithm for these hash sets,
109 /// they're accessed quite often.
110 type_: RefCell<FxHashSet<Interned<'tcx, TyS<'tcx>>>>,
111 type_list: RefCell<FxHashSet<Interned<'tcx, Slice<Ty<'tcx>>>>>,
112 substs: RefCell<FxHashSet<Interned<'tcx, Substs<'tcx>>>>,
113 region: RefCell<FxHashSet<Interned<'tcx, RegionKind>>>,
114 existential_predicates: RefCell<FxHashSet<Interned<'tcx, Slice<ExistentialPredicate<'tcx>>>>>,
115 predicates: RefCell<FxHashSet<Interned<'tcx, Slice<Predicate<'tcx>>>>>,
116 const_: RefCell<FxHashSet<Interned<'tcx, Const<'tcx>>>>,
119 impl<'gcx: 'tcx, 'tcx> CtxtInterners<'tcx> {
120 fn new(arena: &'tcx DroplessArena) -> CtxtInterners<'tcx> {
123 type_: RefCell::new(FxHashSet()),
124 type_list: RefCell::new(FxHashSet()),
125 substs: RefCell::new(FxHashSet()),
126 region: RefCell::new(FxHashSet()),
127 existential_predicates: RefCell::new(FxHashSet()),
128 predicates: RefCell::new(FxHashSet()),
129 const_: RefCell::new(FxHashSet()),
133 /// Intern a type. global_interners is Some only if this is
134 /// a local interner and global_interners is its counterpart.
135 fn intern_ty(&self, st: TypeVariants<'tcx>,
136 global_interners: Option<&CtxtInterners<'gcx>>)
139 let mut interner = self.type_.borrow_mut();
140 let global_interner = global_interners.map(|interners| {
141 interners.type_.borrow_mut()
143 if let Some(&Interned(ty)) = interner.get(&st) {
146 if let Some(ref interner) = global_interner {
147 if let Some(&Interned(ty)) = interner.get(&st) {
152 let flags = super::flags::FlagComputation::for_sty(&st);
153 let ty_struct = TyS {
156 region_depth: flags.depth,
159 // HACK(eddyb) Depend on flags being accurate to
160 // determine that all contents are in the global tcx.
161 // See comments on Lift for why we can't use that.
162 if !flags.flags.intersects(ty::TypeFlags::KEEP_IN_LOCAL_TCX) {
163 if let Some(interner) = global_interners {
164 let ty_struct: TyS<'gcx> = unsafe {
165 mem::transmute(ty_struct)
167 let ty: Ty<'gcx> = interner.arena.alloc(ty_struct);
168 global_interner.unwrap().insert(Interned(ty));
172 // Make sure we don't end up with inference
173 // types/regions in the global tcx.
174 if global_interners.is_none() {
176 bug!("Attempted to intern `{:?}` which contains \
177 inference types/regions in the global type context",
182 // Don't be &mut TyS.
183 let ty: Ty<'tcx> = self.arena.alloc(ty_struct);
184 interner.insert(Interned(ty));
188 debug!("Interned type: {:?} Pointer: {:?}",
189 ty, ty as *const TyS);
195 pub struct CommonTypes<'tcx> {
215 pub re_empty: Region<'tcx>,
216 pub re_static: Region<'tcx>,
217 pub re_erased: Region<'tcx>,
220 pub struct LocalTableInContext<'a, V: 'a> {
221 local_id_root: Option<DefId>,
222 data: &'a ItemLocalMap<V>
225 /// Validate that the given HirId (respectively its `local_id` part) can be
226 /// safely used as a key in the tables of a TypeckTable. For that to be
227 /// the case, the HirId must have the same `owner` as all the other IDs in
228 /// this table (signified by `local_id_root`). Otherwise the HirId
229 /// would be in a different frame of reference and using its `local_id`
230 /// would result in lookup errors, or worse, in silently wrong data being
232 fn validate_hir_id_for_typeck_tables(local_id_root: Option<DefId>,
235 if cfg!(debug_assertions) {
236 if let Some(local_id_root) = local_id_root {
237 if hir_id.owner != local_id_root.index {
238 ty::tls::with(|tcx| {
239 let node_id = tcx.hir
241 .find_node_for_hir_id(hir_id);
243 bug!("node {} with HirId::owner {:?} cannot be placed in \
244 TypeckTables with local_id_root {:?}",
245 tcx.hir.node_to_string(node_id),
246 DefId::local(hir_id.owner),
251 // We use "Null Object" TypeckTables in some of the analysis passes.
252 // These are just expected to be empty and their `local_id_root` is
253 // `None`. Therefore we cannot verify whether a given `HirId` would
254 // be a valid key for the given table. Instead we make sure that
255 // nobody tries to write to such a Null Object table.
257 bug!("access to invalid TypeckTables")
263 impl<'a, V> LocalTableInContext<'a, V> {
264 pub fn contains_key(&self, id: hir::HirId) -> bool {
265 validate_hir_id_for_typeck_tables(self.local_id_root, id, false);
266 self.data.contains_key(&id.local_id)
269 pub fn get(&self, id: hir::HirId) -> Option<&V> {
270 validate_hir_id_for_typeck_tables(self.local_id_root, id, false);
271 self.data.get(&id.local_id)
274 pub fn iter(&self) -> hash_map::Iter<hir::ItemLocalId, V> {
279 impl<'a, V> ::std::ops::Index<hir::HirId> for LocalTableInContext<'a, V> {
282 fn index(&self, key: hir::HirId) -> &V {
283 self.get(key).expect("LocalTableInContext: key not found")
287 pub struct LocalTableInContextMut<'a, V: 'a> {
288 local_id_root: Option<DefId>,
289 data: &'a mut ItemLocalMap<V>
292 impl<'a, V> LocalTableInContextMut<'a, V> {
293 pub fn get_mut(&mut self, id: hir::HirId) -> Option<&mut V> {
294 validate_hir_id_for_typeck_tables(self.local_id_root, id, true);
295 self.data.get_mut(&id.local_id)
298 pub fn entry(&mut self, id: hir::HirId) -> Entry<hir::ItemLocalId, V> {
299 validate_hir_id_for_typeck_tables(self.local_id_root, id, true);
300 self.data.entry(id.local_id)
303 pub fn insert(&mut self, id: hir::HirId, val: V) -> Option<V> {
304 validate_hir_id_for_typeck_tables(self.local_id_root, id, true);
305 self.data.insert(id.local_id, val)
308 pub fn remove(&mut self, id: hir::HirId) -> Option<V> {
309 validate_hir_id_for_typeck_tables(self.local_id_root, id, true);
310 self.data.remove(&id.local_id)
314 #[derive(RustcEncodable, RustcDecodable)]
315 pub struct TypeckTables<'tcx> {
316 /// The HirId::owner all ItemLocalIds in this table are relative to.
317 pub local_id_root: Option<DefId>,
319 /// Resolved definitions for `<T>::X` associated paths and
320 /// method calls, including those of overloaded operators.
321 type_dependent_defs: ItemLocalMap<Def>,
323 /// Stores the types for various nodes in the AST. Note that this table
324 /// is not guaranteed to be populated until after typeck. See
325 /// typeck::check::fn_ctxt for details.
326 node_types: ItemLocalMap<Ty<'tcx>>,
328 /// Stores the type parameters which were substituted to obtain the type
329 /// of this node. This only applies to nodes that refer to entities
330 /// parameterized by type parameters, such as generic fns, types, or
332 node_substs: ItemLocalMap<&'tcx Substs<'tcx>>,
334 adjustments: ItemLocalMap<Vec<ty::adjustment::Adjustment<'tcx>>>,
336 // Stores the actual binding mode for all instances of hir::BindingAnnotation.
337 pat_binding_modes: ItemLocalMap<BindingMode>,
340 pub upvar_capture_map: ty::UpvarCaptureMap<'tcx>,
342 /// Records the type of each closure.
343 closure_tys: ItemLocalMap<ty::PolyFnSig<'tcx>>,
345 /// Records the kind of each closure and the span and name of the variable
346 /// that caused the closure to be this kind.
347 closure_kinds: ItemLocalMap<(ty::ClosureKind, Option<(Span, ast::Name)>)>,
349 generator_sigs: ItemLocalMap<Option<ty::GenSig<'tcx>>>,
351 generator_interiors: ItemLocalMap<ty::GeneratorInterior<'tcx>>,
353 /// For each fn, records the "liberated" types of its arguments
354 /// and return type. Liberated means that all bound regions
355 /// (including late-bound regions) are replaced with free
356 /// equivalents. This table is not used in trans (since regions
357 /// are erased there) and hence is not serialized to metadata.
358 liberated_fn_sigs: ItemLocalMap<ty::FnSig<'tcx>>,
360 /// For each FRU expression, record the normalized types of the fields
361 /// of the struct - this is needed because it is non-trivial to
362 /// normalize while preserving regions. This table is used only in
363 /// MIR construction and hence is not serialized to metadata.
364 fru_field_types: ItemLocalMap<Vec<Ty<'tcx>>>,
366 /// Maps a cast expression to its kind. This is keyed on the
367 /// *from* expression of the cast, not the cast itself.
368 cast_kinds: ItemLocalMap<ty::cast::CastKind>,
370 /// Set of trait imports actually used in the method resolution.
371 /// This is used for warning unused imports.
372 pub used_trait_imports: DefIdSet,
374 /// If any errors occurred while type-checking this body,
375 /// this field will be set to `true`.
376 pub tainted_by_errors: bool,
378 /// Stores the free-region relationships that were deduced from
379 /// its where clauses and parameter types. These are then
380 /// read-again by borrowck.
381 pub free_region_map: FreeRegionMap<'tcx>,
384 impl<'tcx> TypeckTables<'tcx> {
385 pub fn empty(local_id_root: Option<DefId>) -> TypeckTables<'tcx> {
388 type_dependent_defs: ItemLocalMap(),
389 node_types: ItemLocalMap(),
390 node_substs: ItemLocalMap(),
391 adjustments: ItemLocalMap(),
392 pat_binding_modes: ItemLocalMap(),
393 upvar_capture_map: FxHashMap(),
394 generator_sigs: ItemLocalMap(),
395 generator_interiors: ItemLocalMap(),
396 closure_tys: ItemLocalMap(),
397 closure_kinds: ItemLocalMap(),
398 liberated_fn_sigs: ItemLocalMap(),
399 fru_field_types: ItemLocalMap(),
400 cast_kinds: ItemLocalMap(),
401 used_trait_imports: DefIdSet(),
402 tainted_by_errors: false,
403 free_region_map: FreeRegionMap::new(),
407 /// Returns the final resolution of a `QPath` in an `Expr` or `Pat` node.
408 pub fn qpath_def(&self, qpath: &hir::QPath, id: hir::HirId) -> Def {
410 hir::QPath::Resolved(_, ref path) => path.def,
411 hir::QPath::TypeRelative(..) => {
412 validate_hir_id_for_typeck_tables(self.local_id_root, id, false);
413 self.type_dependent_defs.get(&id.local_id).cloned().unwrap_or(Def::Err)
418 pub fn type_dependent_defs(&self) -> LocalTableInContext<Def> {
419 LocalTableInContext {
420 local_id_root: self.local_id_root,
421 data: &self.type_dependent_defs
425 pub fn type_dependent_defs_mut(&mut self) -> LocalTableInContextMut<Def> {
426 LocalTableInContextMut {
427 local_id_root: self.local_id_root,
428 data: &mut self.type_dependent_defs
432 pub fn node_types(&self) -> LocalTableInContext<Ty<'tcx>> {
433 LocalTableInContext {
434 local_id_root: self.local_id_root,
435 data: &self.node_types
439 pub fn node_types_mut(&mut self) -> LocalTableInContextMut<Ty<'tcx>> {
440 LocalTableInContextMut {
441 local_id_root: self.local_id_root,
442 data: &mut self.node_types
446 pub fn node_id_to_type(&self, id: hir::HirId) -> Ty<'tcx> {
447 match self.node_id_to_type_opt(id) {
450 bug!("node_id_to_type: no type for node `{}`",
452 let id = tcx.hir.definitions().find_node_for_hir_id(id);
453 tcx.hir.node_to_string(id)
459 pub fn node_id_to_type_opt(&self, id: hir::HirId) -> Option<Ty<'tcx>> {
460 validate_hir_id_for_typeck_tables(self.local_id_root, id, false);
461 self.node_types.get(&id.local_id).cloned()
464 pub fn node_substs_mut(&mut self) -> LocalTableInContextMut<&'tcx Substs<'tcx>> {
465 LocalTableInContextMut {
466 local_id_root: self.local_id_root,
467 data: &mut self.node_substs
471 pub fn node_substs(&self, id: hir::HirId) -> &'tcx Substs<'tcx> {
472 validate_hir_id_for_typeck_tables(self.local_id_root, id, false);
473 self.node_substs.get(&id.local_id).cloned().unwrap_or(Substs::empty())
476 pub fn node_substs_opt(&self, id: hir::HirId) -> Option<&'tcx Substs<'tcx>> {
477 validate_hir_id_for_typeck_tables(self.local_id_root, id, false);
478 self.node_substs.get(&id.local_id).cloned()
481 // Returns the type of a pattern as a monotype. Like @expr_ty, this function
482 // doesn't provide type parameter substitutions.
483 pub fn pat_ty(&self, pat: &hir::Pat) -> Ty<'tcx> {
484 self.node_id_to_type(pat.hir_id)
487 pub fn pat_ty_opt(&self, pat: &hir::Pat) -> Option<Ty<'tcx>> {
488 self.node_id_to_type_opt(pat.hir_id)
491 // Returns the type of an expression as a monotype.
493 // NB (1): This is the PRE-ADJUSTMENT TYPE for the expression. That is, in
494 // some cases, we insert `Adjustment` annotations such as auto-deref or
495 // auto-ref. The type returned by this function does not consider such
496 // adjustments. See `expr_ty_adjusted()` instead.
498 // NB (2): This type doesn't provide type parameter substitutions; e.g. if you
499 // ask for the type of "id" in "id(3)", it will return "fn(&isize) -> isize"
500 // instead of "fn(ty) -> T with T = isize".
501 pub fn expr_ty(&self, expr: &hir::Expr) -> Ty<'tcx> {
502 self.node_id_to_type(expr.hir_id)
505 pub fn expr_ty_opt(&self, expr: &hir::Expr) -> Option<Ty<'tcx>> {
506 self.node_id_to_type_opt(expr.hir_id)
509 pub fn adjustments(&self) -> LocalTableInContext<Vec<ty::adjustment::Adjustment<'tcx>>> {
510 LocalTableInContext {
511 local_id_root: self.local_id_root,
512 data: &self.adjustments
516 pub fn adjustments_mut(&mut self)
517 -> LocalTableInContextMut<Vec<ty::adjustment::Adjustment<'tcx>>> {
518 LocalTableInContextMut {
519 local_id_root: self.local_id_root,
520 data: &mut self.adjustments
524 pub fn expr_adjustments(&self, expr: &hir::Expr)
525 -> &[ty::adjustment::Adjustment<'tcx>] {
526 validate_hir_id_for_typeck_tables(self.local_id_root, expr.hir_id, false);
527 self.adjustments.get(&expr.hir_id.local_id).map_or(&[], |a| &a[..])
530 /// Returns the type of `expr`, considering any `Adjustment`
531 /// entry recorded for that expression.
532 pub fn expr_ty_adjusted(&self, expr: &hir::Expr) -> Ty<'tcx> {
533 self.expr_adjustments(expr)
535 .map_or_else(|| self.expr_ty(expr), |adj| adj.target)
538 pub fn expr_ty_adjusted_opt(&self, expr: &hir::Expr) -> Option<Ty<'tcx>> {
539 self.expr_adjustments(expr)
541 .map(|adj| adj.target)
542 .or_else(|| self.expr_ty_opt(expr))
545 pub fn is_method_call(&self, expr: &hir::Expr) -> bool {
546 // Only paths and method calls/overloaded operators have
547 // entries in type_dependent_defs, ignore the former here.
548 if let hir::ExprPath(_) = expr.node {
552 match self.type_dependent_defs().get(expr.hir_id) {
553 Some(&Def::Method(_)) => true,
558 pub fn pat_binding_modes(&self) -> LocalTableInContext<BindingMode> {
559 LocalTableInContext {
560 local_id_root: self.local_id_root,
561 data: &self.pat_binding_modes
565 pub fn pat_binding_modes_mut(&mut self)
566 -> LocalTableInContextMut<BindingMode> {
567 LocalTableInContextMut {
568 local_id_root: self.local_id_root,
569 data: &mut self.pat_binding_modes
573 pub fn upvar_capture(&self, upvar_id: ty::UpvarId) -> ty::UpvarCapture<'tcx> {
574 self.upvar_capture_map[&upvar_id]
577 pub fn closure_tys(&self) -> LocalTableInContext<ty::PolyFnSig<'tcx>> {
578 LocalTableInContext {
579 local_id_root: self.local_id_root,
580 data: &self.closure_tys
584 pub fn closure_tys_mut(&mut self)
585 -> LocalTableInContextMut<ty::PolyFnSig<'tcx>> {
586 LocalTableInContextMut {
587 local_id_root: self.local_id_root,
588 data: &mut self.closure_tys
592 pub fn closure_kinds(&self) -> LocalTableInContext<(ty::ClosureKind,
593 Option<(Span, ast::Name)>)> {
594 LocalTableInContext {
595 local_id_root: self.local_id_root,
596 data: &self.closure_kinds
600 pub fn closure_kinds_mut(&mut self)
601 -> LocalTableInContextMut<(ty::ClosureKind, Option<(Span, ast::Name)>)> {
602 LocalTableInContextMut {
603 local_id_root: self.local_id_root,
604 data: &mut self.closure_kinds
608 pub fn liberated_fn_sigs(&self) -> LocalTableInContext<ty::FnSig<'tcx>> {
609 LocalTableInContext {
610 local_id_root: self.local_id_root,
611 data: &self.liberated_fn_sigs
615 pub fn liberated_fn_sigs_mut(&mut self) -> LocalTableInContextMut<ty::FnSig<'tcx>> {
616 LocalTableInContextMut {
617 local_id_root: self.local_id_root,
618 data: &mut self.liberated_fn_sigs
622 pub fn fru_field_types(&self) -> LocalTableInContext<Vec<Ty<'tcx>>> {
623 LocalTableInContext {
624 local_id_root: self.local_id_root,
625 data: &self.fru_field_types
629 pub fn fru_field_types_mut(&mut self) -> LocalTableInContextMut<Vec<Ty<'tcx>>> {
630 LocalTableInContextMut {
631 local_id_root: self.local_id_root,
632 data: &mut self.fru_field_types
636 pub fn cast_kinds(&self) -> LocalTableInContext<ty::cast::CastKind> {
637 LocalTableInContext {
638 local_id_root: self.local_id_root,
639 data: &self.cast_kinds
643 pub fn cast_kinds_mut(&mut self) -> LocalTableInContextMut<ty::cast::CastKind> {
644 LocalTableInContextMut {
645 local_id_root: self.local_id_root,
646 data: &mut self.cast_kinds
650 pub fn generator_sigs(&self)
651 -> LocalTableInContext<Option<ty::GenSig<'tcx>>>
653 LocalTableInContext {
654 local_id_root: self.local_id_root,
655 data: &self.generator_sigs,
659 pub fn generator_sigs_mut(&mut self)
660 -> LocalTableInContextMut<Option<ty::GenSig<'tcx>>>
662 LocalTableInContextMut {
663 local_id_root: self.local_id_root,
664 data: &mut self.generator_sigs,
668 pub fn generator_interiors(&self)
669 -> LocalTableInContext<ty::GeneratorInterior<'tcx>>
671 LocalTableInContext {
672 local_id_root: self.local_id_root,
673 data: &self.generator_interiors,
677 pub fn generator_interiors_mut(&mut self)
678 -> LocalTableInContextMut<ty::GeneratorInterior<'tcx>>
680 LocalTableInContextMut {
681 local_id_root: self.local_id_root,
682 data: &mut self.generator_interiors,
687 impl<'a, 'gcx, 'tcx> HashStable<StableHashingContext<'a, 'gcx, 'tcx>> for TypeckTables<'gcx> {
688 fn hash_stable<W: StableHasherResult>(&self,
689 hcx: &mut StableHashingContext<'a, 'gcx, 'tcx>,
690 hasher: &mut StableHasher<W>) {
691 let ty::TypeckTables {
693 ref type_dependent_defs,
697 ref pat_binding_modes,
698 ref upvar_capture_map,
701 ref liberated_fn_sigs,
706 ref used_trait_imports,
710 ref generator_interiors,
713 hcx.with_node_id_hashing_mode(NodeIdHashingMode::HashDefPath, |hcx| {
714 ich::hash_stable_itemlocalmap(hcx, hasher, type_dependent_defs);
715 ich::hash_stable_itemlocalmap(hcx, hasher, node_types);
716 ich::hash_stable_itemlocalmap(hcx, hasher, node_substs);
717 ich::hash_stable_itemlocalmap(hcx, hasher, adjustments);
718 ich::hash_stable_itemlocalmap(hcx, hasher, pat_binding_modes);
719 ich::hash_stable_hashmap(hcx, hasher, upvar_capture_map, |hcx, up_var_id| {
726 local_id_root.expect("trying to hash invalid TypeckTables");
728 let var_owner_def_id = DefId {
729 krate: local_id_root.krate,
732 let closure_def_id = DefId {
733 krate: local_id_root.krate,
734 index: closure_expr_id,
736 ((hcx.def_path_hash(var_owner_def_id), var_id.local_id),
737 hcx.def_path_hash(closure_def_id))
740 ich::hash_stable_itemlocalmap(hcx, hasher, closure_tys);
741 ich::hash_stable_itemlocalmap(hcx, hasher, closure_kinds);
742 ich::hash_stable_itemlocalmap(hcx, hasher, liberated_fn_sigs);
743 ich::hash_stable_itemlocalmap(hcx, hasher, fru_field_types);
744 ich::hash_stable_itemlocalmap(hcx, hasher, cast_kinds);
745 ich::hash_stable_itemlocalmap(hcx, hasher, generator_sigs);
746 ich::hash_stable_itemlocalmap(hcx, hasher, generator_interiors);
748 ich::hash_stable_hashset(hcx, hasher, used_trait_imports, |hcx, def_id| {
749 hcx.def_path_hash(*def_id)
752 tainted_by_errors.hash_stable(hcx, hasher);
753 free_region_map.hash_stable(hcx, hasher);
758 impl<'tcx> CommonTypes<'tcx> {
759 fn new(interners: &CtxtInterners<'tcx>) -> CommonTypes<'tcx> {
760 let mk = |sty| interners.intern_ty(sty, None);
761 let mk_region = |r| {
762 if let Some(r) = interners.region.borrow().get(&r) {
765 let r = interners.arena.alloc(r);
766 interners.region.borrow_mut().insert(Interned(r));
774 isize: mk(TyInt(ast::IntTy::Is)),
775 i8: mk(TyInt(ast::IntTy::I8)),
776 i16: mk(TyInt(ast::IntTy::I16)),
777 i32: mk(TyInt(ast::IntTy::I32)),
778 i64: mk(TyInt(ast::IntTy::I64)),
779 i128: mk(TyInt(ast::IntTy::I128)),
780 usize: mk(TyUint(ast::UintTy::Us)),
781 u8: mk(TyUint(ast::UintTy::U8)),
782 u16: mk(TyUint(ast::UintTy::U16)),
783 u32: mk(TyUint(ast::UintTy::U32)),
784 u64: mk(TyUint(ast::UintTy::U64)),
785 u128: mk(TyUint(ast::UintTy::U128)),
786 f32: mk(TyFloat(ast::FloatTy::F32)),
787 f64: mk(TyFloat(ast::FloatTy::F64)),
789 re_empty: mk_region(RegionKind::ReEmpty),
790 re_static: mk_region(RegionKind::ReStatic),
791 re_erased: mk_region(RegionKind::ReErased),
796 /// The data structure to keep track of all the information that typechecker
797 /// generates so that so that it can be reused and doesn't have to be redone
799 #[derive(Copy, Clone)]
800 pub struct TyCtxt<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
801 gcx: &'a GlobalCtxt<'gcx>,
802 interners: &'a CtxtInterners<'tcx>
805 impl<'a, 'gcx, 'tcx> Deref for TyCtxt<'a, 'gcx, 'tcx> {
806 type Target = &'a GlobalCtxt<'gcx>;
807 fn deref(&self) -> &Self::Target {
812 pub struct GlobalCtxt<'tcx> {
813 global_arenas: &'tcx GlobalArenas<'tcx>,
814 global_interners: CtxtInterners<'tcx>,
816 cstore: &'tcx CrateStore,
818 pub sess: &'tcx Session,
821 pub trans_trait_caches: traits::trans::TransTraitCaches<'tcx>,
823 pub dep_graph: DepGraph,
825 /// Common types, pre-interned for your convenience.
826 pub types: CommonTypes<'tcx>,
828 /// Map indicating what traits are in scope for places where this
829 /// is relevant; generated by resolve.
830 trait_map: FxHashMap<DefIndex, Rc<FxHashMap<ItemLocalId, Rc<Vec<TraitCandidate>>>>>,
832 /// Export map produced by name resolution.
833 export_map: FxHashMap<DefId, Rc<Vec<Export>>>,
835 named_region_map: NamedRegionMap,
837 pub hir: hir_map::Map<'tcx>,
839 /// A map from DefPathHash -> DefId. Includes DefIds from the local crate
840 /// as well as all upstream crates. Only populated in incremental mode.
841 pub def_path_hash_to_def_id: Option<FxHashMap<DefPathHash, DefId>>,
843 pub maps: maps::Maps<'tcx>,
845 pub mir_passes: Rc<Passes>,
847 // Records the free variables refrenced by every closure
848 // expression. Do not track deps for this, just recompute it from
849 // scratch every time.
850 freevars: FxHashMap<DefId, Rc<Vec<hir::Freevar>>>,
852 maybe_unused_trait_imports: FxHashSet<DefId>,
854 maybe_unused_extern_crates: Vec<(DefId, Span)>,
856 // Internal cache for metadata decoding. No need to track deps on this.
857 pub rcache: RefCell<FxHashMap<ty::CReaderCacheKey, Ty<'tcx>>>,
859 // FIXME dep tracking -- should be harmless enough
860 pub normalized_cache: RefCell<FxHashMap<Ty<'tcx>, Ty<'tcx>>>,
862 pub inhabitedness_cache: RefCell<FxHashMap<Ty<'tcx>, DefIdForest>>,
864 /// Set of nodes which mark locals as mutable which end up getting used at
865 /// some point. Local variable definitions not in this set can be warned
867 pub used_mut_nodes: RefCell<NodeSet>,
869 /// Caches the results of trait selection. This cache is used
870 /// for things that do not have to do with the parameters in scope.
871 pub selection_cache: traits::SelectionCache<'tcx>,
873 /// Caches the results of trait evaluation. This cache is used
874 /// for things that do not have to do with the parameters in scope.
875 /// Merge this with `selection_cache`?
876 pub evaluation_cache: traits::EvaluationCache<'tcx>,
878 /// Maps Expr NodeId's to `true` iff `&expr` can have 'static lifetime.
879 pub rvalue_promotable_to_static: RefCell<NodeMap<bool>>,
881 /// The definite name of the current crate after taking into account
882 /// attributes, commandline parameters, etc.
883 pub crate_name: Symbol,
885 /// Data layout specification for the current target.
886 pub data_layout: TargetDataLayout,
888 /// Used to prevent layout from recursing too deeply.
889 pub layout_depth: Cell<usize>,
891 /// Map from function to the `#[derive]` mode that it's defining. Only used
892 /// by `proc-macro` crates.
893 pub derive_macros: RefCell<NodeMap<Symbol>>,
895 stability_interner: RefCell<FxHashSet<&'tcx attr::Stability>>,
897 layout_interner: RefCell<FxHashSet<&'tcx Layout>>,
899 /// A vector of every trait accessible in the whole crate
900 /// (i.e. including those from subcrates). This is used only for
901 /// error reporting, and so is lazily initialized and generally
902 /// shouldn't taint the common path (hence the RefCell).
903 pub all_traits: RefCell<Option<Vec<DefId>>>,
906 impl<'tcx> GlobalCtxt<'tcx> {
907 /// Get the global TyCtxt.
908 pub fn global_tcx<'a>(&'a self) -> TyCtxt<'a, 'tcx, 'tcx> {
911 interners: &self.global_interners
916 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
917 pub fn alloc_generics(self, generics: ty::Generics) -> &'gcx ty::Generics {
918 self.global_arenas.generics.alloc(generics)
921 pub fn alloc_steal_mir(self, mir: Mir<'gcx>) -> &'gcx Steal<Mir<'gcx>> {
922 self.global_arenas.steal_mir.alloc(Steal::new(mir))
925 pub fn alloc_mir(self, mir: Mir<'gcx>) -> &'gcx Mir<'gcx> {
926 self.global_arenas.mir.alloc(mir)
929 pub fn alloc_tables(self, tables: ty::TypeckTables<'gcx>) -> &'gcx ty::TypeckTables<'gcx> {
930 self.global_arenas.tables.alloc(tables)
933 pub fn alloc_trait_def(self, def: ty::TraitDef) -> &'gcx ty::TraitDef {
934 self.global_arenas.trait_def.alloc(def)
937 pub fn alloc_adt_def(self,
940 variants: Vec<ty::VariantDef>,
942 -> &'gcx ty::AdtDef {
943 let def = ty::AdtDef::new(self, did, kind, variants, repr);
944 self.global_arenas.adt_def.alloc(def)
947 pub fn alloc_byte_array(self, bytes: &[u8]) -> &'gcx [u8] {
948 if bytes.is_empty() {
951 self.global_interners.arena.alloc_slice(bytes)
955 pub fn alloc_const_slice(self, values: &[&'tcx ty::Const<'tcx>])
956 -> &'tcx [&'tcx ty::Const<'tcx>] {
957 if values.is_empty() {
960 self.interners.arena.alloc_slice(values)
964 pub fn alloc_name_const_slice(self, values: &[(ast::Name, &'tcx ty::Const<'tcx>)])
965 -> &'tcx [(ast::Name, &'tcx ty::Const<'tcx>)] {
966 if values.is_empty() {
969 self.interners.arena.alloc_slice(values)
973 pub fn intern_stability(self, stab: attr::Stability) -> &'gcx attr::Stability {
974 if let Some(st) = self.stability_interner.borrow().get(&stab) {
978 let interned = self.global_interners.arena.alloc(stab);
979 if let Some(prev) = self.stability_interner.borrow_mut().replace(interned) {
980 bug!("Tried to overwrite interned Stability: {:?}", prev)
985 pub fn intern_layout(self, layout: Layout) -> &'gcx Layout {
986 if let Some(layout) = self.layout_interner.borrow().get(&layout) {
990 let interned = self.global_arenas.layout.alloc(layout);
991 if let Some(prev) = self.layout_interner.borrow_mut().replace(interned) {
992 bug!("Tried to overwrite interned Layout: {:?}", prev)
997 pub fn lift<T: ?Sized + Lift<'tcx>>(self, value: &T) -> Option<T::Lifted> {
998 value.lift_to_tcx(self)
1001 /// Like lift, but only tries in the global tcx.
1002 pub fn lift_to_global<T: ?Sized + Lift<'gcx>>(self, value: &T) -> Option<T::Lifted> {
1003 value.lift_to_tcx(self.global_tcx())
1006 /// Returns true if self is the same as self.global_tcx().
1007 fn is_global(self) -> bool {
1008 let local = self.interners as *const _;
1009 let global = &self.global_interners as *const _;
1010 local as usize == global as usize
1013 /// Create a type context and call the closure with a `TyCtxt` reference
1014 /// to the context. The closure enforces that the type context and any interned
1015 /// value (types, substs, etc.) can only be used while `ty::tls` has a valid
1016 /// reference to the context, to allow formatting values that need it.
1017 pub fn create_and_enter<F, R>(s: &'tcx Session,
1018 cstore: &'tcx CrateStore,
1019 local_providers: ty::maps::Providers<'tcx>,
1020 extern_providers: ty::maps::Providers<'tcx>,
1021 mir_passes: Rc<Passes>,
1022 arenas: &'tcx GlobalArenas<'tcx>,
1023 arena: &'tcx DroplessArena,
1024 resolutions: ty::Resolutions,
1025 named_region_map: resolve_lifetime::NamedRegionMap,
1026 hir: hir_map::Map<'tcx>,
1029 where F: for<'b> FnOnce(TyCtxt<'b, 'tcx, 'tcx>) -> R
1031 let data_layout = TargetDataLayout::parse(s);
1032 let interners = CtxtInterners::new(arena);
1033 let common_types = CommonTypes::new(&interners);
1034 let dep_graph = hir.dep_graph.clone();
1035 let max_cnum = cstore.crates_untracked().iter().map(|c| c.as_usize()).max().unwrap_or(0);
1036 let mut providers = IndexVec::from_elem_n(extern_providers, max_cnum + 1);
1037 providers[LOCAL_CRATE] = local_providers;
1039 let def_path_hash_to_def_id = if s.opts.build_dep_graph() {
1040 let upstream_def_path_tables: Vec<(CrateNum, Rc<_>)> = cstore
1043 .map(|&cnum| (cnum, cstore.def_path_table(cnum)))
1046 let def_path_tables = || {
1047 upstream_def_path_tables
1049 .map(|&(cnum, ref rc)| (cnum, &**rc))
1050 .chain(iter::once((LOCAL_CRATE, hir.definitions().def_path_table())))
1053 // Precompute the capacity of the hashmap so we don't have to
1054 // re-allocate when populating it.
1055 let capacity = def_path_tables().map(|(_, t)| t.size()).sum::<usize>();
1057 let mut map: FxHashMap<_, _> = FxHashMap::with_capacity_and_hasher(
1059 ::std::default::Default::default()
1062 for (cnum, def_path_table) in def_path_tables() {
1063 def_path_table.add_def_path_hashes_to(cnum, &mut map);
1071 let mut trait_map = FxHashMap();
1072 for (k, v) in resolutions.trait_map {
1073 let hir_id = hir.node_to_hir_id(k);
1074 let map = trait_map.entry(hir_id.owner)
1075 .or_insert_with(|| Rc::new(FxHashMap()));
1076 Rc::get_mut(map).unwrap().insert(hir_id.local_id, Rc::new(v));
1078 let mut defs = FxHashMap();
1079 for (k, v) in named_region_map.defs {
1080 let hir_id = hir.node_to_hir_id(k);
1081 let map = defs.entry(hir_id.owner)
1082 .or_insert_with(|| Rc::new(FxHashMap()));
1083 Rc::get_mut(map).unwrap().insert(hir_id.local_id, v);
1085 let mut late_bound = FxHashMap();
1086 for k in named_region_map.late_bound {
1087 let hir_id = hir.node_to_hir_id(k);
1088 let map = late_bound.entry(hir_id.owner)
1089 .or_insert_with(|| Rc::new(FxHashSet()));
1090 Rc::get_mut(map).unwrap().insert(hir_id.local_id);
1092 let mut object_lifetime_defaults = FxHashMap();
1093 for (k, v) in named_region_map.object_lifetime_defaults {
1094 let hir_id = hir.node_to_hir_id(k);
1095 let map = object_lifetime_defaults.entry(hir_id.owner)
1096 .or_insert_with(|| Rc::new(FxHashMap()));
1097 Rc::get_mut(map).unwrap().insert(hir_id.local_id, Rc::new(v));
1100 tls::enter_global(GlobalCtxt {
1103 trans_trait_caches: traits::trans::TransTraitCaches::new(dep_graph.clone()),
1104 global_arenas: arenas,
1105 global_interners: interners,
1106 dep_graph: dep_graph.clone(),
1107 types: common_types,
1108 named_region_map: NamedRegionMap {
1111 object_lifetime_defaults,
1114 export_map: resolutions.export_map.into_iter().map(|(k, v)| {
1117 freevars: resolutions.freevars.into_iter().map(|(k, v)| {
1118 (hir.local_def_id(k), Rc::new(v))
1120 maybe_unused_trait_imports:
1121 resolutions.maybe_unused_trait_imports
1123 .map(|id| hir.local_def_id(id))
1125 maybe_unused_extern_crates:
1126 resolutions.maybe_unused_extern_crates
1128 .map(|(id, sp)| (hir.local_def_id(id), sp))
1131 def_path_hash_to_def_id,
1132 maps: maps::Maps::new(providers),
1134 rcache: RefCell::new(FxHashMap()),
1135 normalized_cache: RefCell::new(FxHashMap()),
1136 inhabitedness_cache: RefCell::new(FxHashMap()),
1137 used_mut_nodes: RefCell::new(NodeSet()),
1138 selection_cache: traits::SelectionCache::new(),
1139 evaluation_cache: traits::EvaluationCache::new(),
1140 rvalue_promotable_to_static: RefCell::new(NodeMap()),
1141 crate_name: Symbol::intern(crate_name),
1143 layout_interner: RefCell::new(FxHashSet()),
1144 layout_depth: Cell::new(0),
1145 derive_macros: RefCell::new(NodeMap()),
1146 stability_interner: RefCell::new(FxHashSet()),
1147 all_traits: RefCell::new(None),
1151 pub fn consider_optimizing<T: Fn() -> String>(&self, msg: T) -> bool {
1152 let cname = self.crate_name(LOCAL_CRATE).as_str();
1153 self.sess.consider_optimizing(&cname, msg)
1156 pub fn lang_items(self) -> Rc<middle::lang_items::LanguageItems> {
1157 // FIXME(#42293) Right now we insert a `with_ignore` node in the dep
1158 // graph here to ignore the fact that `get_lang_items` below depends on
1159 // the entire crate. For now this'll prevent false positives of
1160 // recompiling too much when anything changes.
1162 // Once red/green incremental compilation lands we should be able to
1163 // remove this because while the crate changes often the lint level map
1164 // will change rarely.
1165 self.dep_graph.with_ignore(|| {
1166 self.get_lang_items(LOCAL_CRATE)
1170 pub fn stability(self) -> Rc<stability::Index<'tcx>> {
1171 // FIXME(#42293) we should actually track this, but fails too many tests
1173 self.dep_graph.with_ignore(|| {
1174 self.stability_index(LOCAL_CRATE)
1178 pub fn crates(self) -> Rc<Vec<CrateNum>> {
1179 self.all_crate_nums(LOCAL_CRATE)
1182 pub fn def_key(self, id: DefId) -> hir_map::DefKey {
1184 self.hir.def_key(id)
1186 self.cstore.def_key(id)
1190 /// Convert a `DefId` into its fully expanded `DefPath` (every
1191 /// `DefId` is really just an interned def-path).
1193 /// Note that if `id` is not local to this crate, the result will
1194 /// be a non-local `DefPath`.
1195 pub fn def_path(self, id: DefId) -> hir_map::DefPath {
1197 self.hir.def_path(id)
1199 self.cstore.def_path(id)
1204 pub fn def_path_hash(self, def_id: DefId) -> hir_map::DefPathHash {
1205 if def_id.is_local() {
1206 self.hir.definitions().def_path_hash(def_id.index)
1208 self.cstore.def_path_hash(def_id)
1212 pub fn metadata_encoding_version(self) -> Vec<u8> {
1213 self.cstore.metadata_encoding_version().to_vec()
1216 // Note that this is *untracked* and should only be used within the query
1217 // system if the result is otherwise tracked through queries
1218 pub fn crate_data_as_rc_any(self, cnum: CrateNum) -> Rc<Any> {
1219 self.cstore.crate_data_as_rc_any(cnum)
1223 impl<'a, 'tcx> TyCtxt<'a, 'tcx, 'tcx> {
1224 pub fn encode_metadata(self, link_meta: &LinkMeta, reachable: &NodeSet)
1225 -> (EncodedMetadata, EncodedMetadataHashes)
1227 self.cstore.encode_metadata(self, link_meta, reachable)
1231 impl<'gcx: 'tcx, 'tcx> GlobalCtxt<'gcx> {
1232 /// Call the closure with a local `TyCtxt` using the given arena.
1233 pub fn enter_local<F, R>(&self, arena: &'tcx DroplessArena, f: F) -> R
1234 where F: for<'a> FnOnce(TyCtxt<'a, 'gcx, 'tcx>) -> R
1236 let interners = CtxtInterners::new(arena);
1237 tls::enter(self, &interners, f)
1241 /// A trait implemented for all X<'a> types which can be safely and
1242 /// efficiently converted to X<'tcx> as long as they are part of the
1243 /// provided TyCtxt<'tcx>.
1244 /// This can be done, for example, for Ty<'tcx> or &'tcx Substs<'tcx>
1245 /// by looking them up in their respective interners.
1247 /// However, this is still not the best implementation as it does
1248 /// need to compare the components, even for interned values.
1249 /// It would be more efficient if TypedArena provided a way to
1250 /// determine whether the address is in the allocated range.
1252 /// None is returned if the value or one of the components is not part
1253 /// of the provided context.
1254 /// For Ty, None can be returned if either the type interner doesn't
1255 /// contain the TypeVariants key or if the address of the interned
1256 /// pointer differs. The latter case is possible if a primitive type,
1257 /// e.g. `()` or `u8`, was interned in a different context.
1258 pub trait Lift<'tcx> {
1260 fn lift_to_tcx<'a, 'gcx>(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Option<Self::Lifted>;
1263 impl<'a, 'tcx> Lift<'tcx> for Ty<'a> {
1264 type Lifted = Ty<'tcx>;
1265 fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>) -> Option<Ty<'tcx>> {
1266 if tcx.interners.arena.in_arena(*self as *const _) {
1267 return Some(unsafe { mem::transmute(*self) });
1269 // Also try in the global tcx if we're not that.
1270 if !tcx.is_global() {
1271 self.lift_to_tcx(tcx.global_tcx())
1278 impl<'a, 'tcx> Lift<'tcx> for Region<'a> {
1279 type Lifted = Region<'tcx>;
1280 fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>) -> Option<Region<'tcx>> {
1281 if tcx.interners.arena.in_arena(*self as *const _) {
1282 return Some(unsafe { mem::transmute(*self) });
1284 // Also try in the global tcx if we're not that.
1285 if !tcx.is_global() {
1286 self.lift_to_tcx(tcx.global_tcx())
1293 impl<'a, 'tcx> Lift<'tcx> for &'a Const<'a> {
1294 type Lifted = &'tcx Const<'tcx>;
1295 fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>) -> Option<&'tcx Const<'tcx>> {
1296 if tcx.interners.arena.in_arena(*self as *const _) {
1297 return Some(unsafe { mem::transmute(*self) });
1299 // Also try in the global tcx if we're not that.
1300 if !tcx.is_global() {
1301 self.lift_to_tcx(tcx.global_tcx())
1308 impl<'a, 'tcx> Lift<'tcx> for &'a Substs<'a> {
1309 type Lifted = &'tcx Substs<'tcx>;
1310 fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>) -> Option<&'tcx Substs<'tcx>> {
1311 if self.len() == 0 {
1312 return Some(Slice::empty());
1314 if tcx.interners.arena.in_arena(&self[..] as *const _) {
1315 return Some(unsafe { mem::transmute(*self) });
1317 // Also try in the global tcx if we're not that.
1318 if !tcx.is_global() {
1319 self.lift_to_tcx(tcx.global_tcx())
1326 impl<'a, 'tcx> Lift<'tcx> for &'a Slice<Ty<'a>> {
1327 type Lifted = &'tcx Slice<Ty<'tcx>>;
1328 fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>)
1329 -> Option<&'tcx Slice<Ty<'tcx>>> {
1330 if self.len() == 0 {
1331 return Some(Slice::empty());
1333 if tcx.interners.arena.in_arena(*self as *const _) {
1334 return Some(unsafe { mem::transmute(*self) });
1336 // Also try in the global tcx if we're not that.
1337 if !tcx.is_global() {
1338 self.lift_to_tcx(tcx.global_tcx())
1345 impl<'a, 'tcx> Lift<'tcx> for &'a Slice<ExistentialPredicate<'a>> {
1346 type Lifted = &'tcx Slice<ExistentialPredicate<'tcx>>;
1347 fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>)
1348 -> Option<&'tcx Slice<ExistentialPredicate<'tcx>>> {
1349 if self.is_empty() {
1350 return Some(Slice::empty());
1352 if tcx.interners.arena.in_arena(*self as *const _) {
1353 return Some(unsafe { mem::transmute(*self) });
1355 // Also try in the global tcx if we're not that.
1356 if !tcx.is_global() {
1357 self.lift_to_tcx(tcx.global_tcx())
1364 impl<'a, 'tcx> Lift<'tcx> for &'a Slice<Predicate<'a>> {
1365 type Lifted = &'tcx Slice<Predicate<'tcx>>;
1366 fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>)
1367 -> Option<&'tcx Slice<Predicate<'tcx>>> {
1368 if self.is_empty() {
1369 return Some(Slice::empty());
1371 if tcx.interners.arena.in_arena(*self as *const _) {
1372 return Some(unsafe { mem::transmute(*self) });
1374 // Also try in the global tcx if we're not that.
1375 if !tcx.is_global() {
1376 self.lift_to_tcx(tcx.global_tcx())
1384 use super::{CtxtInterners, GlobalCtxt, TyCtxt};
1386 use std::cell::Cell;
1390 /// Marker types used for the scoped TLS slot.
1391 /// The type context cannot be used directly because the scoped TLS
1392 /// in libstd doesn't allow types generic over lifetimes.
1393 enum ThreadLocalGlobalCtxt {}
1394 enum ThreadLocalInterners {}
1397 static TLS_TCX: Cell<Option<(*const ThreadLocalGlobalCtxt,
1398 *const ThreadLocalInterners)>> = Cell::new(None)
1401 fn span_debug(span: syntax_pos::Span, f: &mut fmt::Formatter) -> fmt::Result {
1403 write!(f, "{}", tcx.sess.codemap().span_to_string(span))
1407 pub fn enter_global<'gcx, F, R>(gcx: GlobalCtxt<'gcx>, f: F) -> R
1408 where F: for<'a> FnOnce(TyCtxt<'a, 'gcx, 'gcx>) -> R
1410 syntax_pos::SPAN_DEBUG.with(|span_dbg| {
1411 let original_span_debug = span_dbg.get();
1412 span_dbg.set(span_debug);
1413 let result = enter(&gcx, &gcx.global_interners, f);
1414 span_dbg.set(original_span_debug);
1419 pub fn enter<'a, 'gcx: 'tcx, 'tcx, F, R>(gcx: &'a GlobalCtxt<'gcx>,
1420 interners: &'a CtxtInterners<'tcx>,
1422 where F: FnOnce(TyCtxt<'a, 'gcx, 'tcx>) -> R
1424 let gcx_ptr = gcx as *const _ as *const ThreadLocalGlobalCtxt;
1425 let interners_ptr = interners as *const _ as *const ThreadLocalInterners;
1426 TLS_TCX.with(|tls| {
1427 let prev = tls.get();
1428 tls.set(Some((gcx_ptr, interners_ptr)));
1429 let ret = f(TyCtxt {
1438 pub fn with<F, R>(f: F) -> R
1439 where F: for<'a, 'gcx, 'tcx> FnOnce(TyCtxt<'a, 'gcx, 'tcx>) -> R
1441 TLS_TCX.with(|tcx| {
1442 let (gcx, interners) = tcx.get().unwrap();
1443 let gcx = unsafe { &*(gcx as *const GlobalCtxt) };
1444 let interners = unsafe { &*(interners as *const CtxtInterners) };
1452 pub fn with_opt<F, R>(f: F) -> R
1453 where F: for<'a, 'gcx, 'tcx> FnOnce(Option<TyCtxt<'a, 'gcx, 'tcx>>) -> R
1455 if TLS_TCX.with(|tcx| tcx.get().is_some()) {
1456 with(|v| f(Some(v)))
1463 macro_rules! sty_debug_print {
1464 ($ctxt: expr, $($variant: ident),*) => {{
1465 // curious inner module to allow variant names to be used as
1467 #[allow(non_snake_case)]
1469 use ty::{self, TyCtxt};
1470 use ty::context::Interned;
1472 #[derive(Copy, Clone)]
1475 region_infer: usize,
1480 pub fn go(tcx: TyCtxt) {
1481 let mut total = DebugStat {
1483 region_infer: 0, ty_infer: 0, both_infer: 0,
1485 $(let mut $variant = total;)*
1488 for &Interned(t) in tcx.interners.type_.borrow().iter() {
1489 let variant = match t.sty {
1490 ty::TyBool | ty::TyChar | ty::TyInt(..) | ty::TyUint(..) |
1491 ty::TyFloat(..) | ty::TyStr | ty::TyNever => continue,
1492 ty::TyError => /* unimportant */ continue,
1493 $(ty::$variant(..) => &mut $variant,)*
1495 let region = t.flags.intersects(ty::TypeFlags::HAS_RE_INFER);
1496 let ty = t.flags.intersects(ty::TypeFlags::HAS_TY_INFER);
1500 if region { total.region_infer += 1; variant.region_infer += 1 }
1501 if ty { total.ty_infer += 1; variant.ty_infer += 1 }
1502 if region && ty { total.both_infer += 1; variant.both_infer += 1 }
1504 println!("Ty interner total ty region both");
1505 $(println!(" {:18}: {uses:6} {usespc:4.1}%, \
1506 {ty:4.1}% {region:5.1}% {both:4.1}%",
1507 stringify!($variant),
1508 uses = $variant.total,
1509 usespc = $variant.total as f64 * 100.0 / total.total as f64,
1510 ty = $variant.ty_infer as f64 * 100.0 / total.total as f64,
1511 region = $variant.region_infer as f64 * 100.0 / total.total as f64,
1512 both = $variant.both_infer as f64 * 100.0 / total.total as f64);
1514 println!(" total {uses:6} \
1515 {ty:4.1}% {region:5.1}% {both:4.1}%",
1517 ty = total.ty_infer as f64 * 100.0 / total.total as f64,
1518 region = total.region_infer as f64 * 100.0 / total.total as f64,
1519 both = total.both_infer as f64 * 100.0 / total.total as f64)
1527 impl<'a, 'tcx> TyCtxt<'a, 'tcx, 'tcx> {
1528 pub fn print_debug_stats(self) {
1531 TyAdt, TyArray, TySlice, TyRawPtr, TyRef, TyFnDef, TyFnPtr, TyGenerator,
1532 TyDynamic, TyClosure, TyTuple, TyParam, TyInfer, TyProjection, TyAnon);
1534 println!("Substs interner: #{}", self.interners.substs.borrow().len());
1535 println!("Region interner: #{}", self.interners.region.borrow().len());
1536 println!("Stability interner: #{}", self.stability_interner.borrow().len());
1537 println!("Layout interner: #{}", self.layout_interner.borrow().len());
1542 /// An entry in an interner.
1543 struct Interned<'tcx, T: 'tcx+?Sized>(&'tcx T);
1545 // NB: An Interned<Ty> compares and hashes as a sty.
1546 impl<'tcx> PartialEq for Interned<'tcx, TyS<'tcx>> {
1547 fn eq(&self, other: &Interned<'tcx, TyS<'tcx>>) -> bool {
1548 self.0.sty == other.0.sty
1552 impl<'tcx> Eq for Interned<'tcx, TyS<'tcx>> {}
1554 impl<'tcx> Hash for Interned<'tcx, TyS<'tcx>> {
1555 fn hash<H: Hasher>(&self, s: &mut H) {
1560 impl<'tcx: 'lcx, 'lcx> Borrow<TypeVariants<'lcx>> for Interned<'tcx, TyS<'tcx>> {
1561 fn borrow<'a>(&'a self) -> &'a TypeVariants<'lcx> {
1566 // NB: An Interned<Slice<T>> compares and hashes as its elements.
1567 impl<'tcx, T: PartialEq> PartialEq for Interned<'tcx, Slice<T>> {
1568 fn eq(&self, other: &Interned<'tcx, Slice<T>>) -> bool {
1569 self.0[..] == other.0[..]
1573 impl<'tcx, T: Eq> Eq for Interned<'tcx, Slice<T>> {}
1575 impl<'tcx, T: Hash> Hash for Interned<'tcx, Slice<T>> {
1576 fn hash<H: Hasher>(&self, s: &mut H) {
1581 impl<'tcx: 'lcx, 'lcx> Borrow<[Ty<'lcx>]> for Interned<'tcx, Slice<Ty<'tcx>>> {
1582 fn borrow<'a>(&'a self) -> &'a [Ty<'lcx>] {
1587 impl<'tcx: 'lcx, 'lcx> Borrow<[Kind<'lcx>]> for Interned<'tcx, Substs<'tcx>> {
1588 fn borrow<'a>(&'a self) -> &'a [Kind<'lcx>] {
1593 impl<'tcx> Borrow<RegionKind> for Interned<'tcx, RegionKind> {
1594 fn borrow<'a>(&'a self) -> &'a RegionKind {
1599 impl<'tcx: 'lcx, 'lcx> Borrow<[ExistentialPredicate<'lcx>]>
1600 for Interned<'tcx, Slice<ExistentialPredicate<'tcx>>> {
1601 fn borrow<'a>(&'a self) -> &'a [ExistentialPredicate<'lcx>] {
1606 impl<'tcx: 'lcx, 'lcx> Borrow<[Predicate<'lcx>]>
1607 for Interned<'tcx, Slice<Predicate<'tcx>>> {
1608 fn borrow<'a>(&'a self) -> &'a [Predicate<'lcx>] {
1613 impl<'tcx: 'lcx, 'lcx> Borrow<Const<'lcx>> for Interned<'tcx, Const<'tcx>> {
1614 fn borrow<'a>(&'a self) -> &'a Const<'lcx> {
1619 macro_rules! intern_method {
1620 ($lt_tcx:tt, $name:ident: $method:ident($alloc:ty,
1621 $alloc_method:ident,
1624 $needs_infer:expr) -> $ty:ty) => {
1625 impl<'a, 'gcx, $lt_tcx> TyCtxt<'a, 'gcx, $lt_tcx> {
1626 pub fn $method(self, v: $alloc) -> &$lt_tcx $ty {
1628 let key = ($alloc_to_key)(&v);
1629 if let Some(i) = self.interners.$name.borrow().get(key) {
1632 if !self.is_global() {
1633 if let Some(i) = self.global_interners.$name.borrow().get(key) {
1639 // HACK(eddyb) Depend on flags being accurate to
1640 // determine that all contents are in the global tcx.
1641 // See comments on Lift for why we can't use that.
1642 if !($needs_infer)(&v) {
1643 if !self.is_global() {
1647 let i = ($alloc_to_ret)(self.global_interners.arena.$alloc_method(v));
1648 self.global_interners.$name.borrow_mut().insert(Interned(i));
1652 // Make sure we don't end up with inference
1653 // types/regions in the global tcx.
1654 if self.is_global() {
1655 bug!("Attempted to intern `{:?}` which contains \
1656 inference types/regions in the global type context",
1661 let i = ($alloc_to_ret)(self.interners.arena.$alloc_method(v));
1662 self.interners.$name.borrow_mut().insert(Interned(i));
1669 macro_rules! direct_interners {
1670 ($lt_tcx:tt, $($name:ident: $method:ident($needs_infer:expr) -> $ty:ty),+) => {
1671 $(impl<$lt_tcx> PartialEq for Interned<$lt_tcx, $ty> {
1672 fn eq(&self, other: &Self) -> bool {
1677 impl<$lt_tcx> Eq for Interned<$lt_tcx, $ty> {}
1679 impl<$lt_tcx> Hash for Interned<$lt_tcx, $ty> {
1680 fn hash<H: Hasher>(&self, s: &mut H) {
1685 intern_method!($lt_tcx, $name: $method($ty, alloc, |x| x, |x| x, $needs_infer) -> $ty);)+
1689 pub fn keep_local<'tcx, T: ty::TypeFoldable<'tcx>>(x: &T) -> bool {
1690 x.has_type_flags(ty::TypeFlags::KEEP_IN_LOCAL_TCX)
1693 direct_interners!('tcx,
1694 region: mk_region(|r| {
1696 &ty::ReVar(_) | &ty::ReSkolemized(..) => true,
1700 const_: mk_const(|c: &Const| keep_local(&c.ty) || keep_local(&c.val)) -> Const<'tcx>
1703 macro_rules! slice_interners {
1704 ($($field:ident: $method:ident($ty:ident)),+) => (
1705 $(intern_method!('tcx, $field: $method(&[$ty<'tcx>], alloc_slice, Deref::deref,
1706 |xs: &[$ty]| -> &Slice<$ty> {
1707 unsafe { mem::transmute(xs) }
1708 }, |xs: &[$ty]| xs.iter().any(keep_local)) -> Slice<$ty<'tcx>>);)+
1713 existential_predicates: _intern_existential_predicates(ExistentialPredicate),
1714 predicates: _intern_predicates(Predicate),
1715 type_list: _intern_type_list(Ty),
1716 substs: _intern_substs(Kind)
1719 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
1720 /// Create an unsafe fn ty based on a safe fn ty.
1721 pub fn safe_to_unsafe_fn_ty(self, sig: PolyFnSig<'tcx>) -> Ty<'tcx> {
1722 assert_eq!(sig.unsafety(), hir::Unsafety::Normal);
1723 self.mk_fn_ptr(sig.map_bound(|sig| ty::FnSig {
1724 unsafety: hir::Unsafety::Unsafe,
1729 // Interns a type/name combination, stores the resulting box in cx.interners,
1730 // and returns the box as cast to an unsafe ptr (see comments for Ty above).
1731 pub fn mk_ty(self, st: TypeVariants<'tcx>) -> Ty<'tcx> {
1732 let global_interners = if !self.is_global() {
1733 Some(&self.global_interners)
1737 self.interners.intern_ty(st, global_interners)
1740 pub fn mk_mach_int(self, tm: ast::IntTy) -> Ty<'tcx> {
1742 ast::IntTy::Is => self.types.isize,
1743 ast::IntTy::I8 => self.types.i8,
1744 ast::IntTy::I16 => self.types.i16,
1745 ast::IntTy::I32 => self.types.i32,
1746 ast::IntTy::I64 => self.types.i64,
1747 ast::IntTy::I128 => self.types.i128,
1751 pub fn mk_mach_uint(self, tm: ast::UintTy) -> Ty<'tcx> {
1753 ast::UintTy::Us => self.types.usize,
1754 ast::UintTy::U8 => self.types.u8,
1755 ast::UintTy::U16 => self.types.u16,
1756 ast::UintTy::U32 => self.types.u32,
1757 ast::UintTy::U64 => self.types.u64,
1758 ast::UintTy::U128 => self.types.u128,
1762 pub fn mk_mach_float(self, tm: ast::FloatTy) -> Ty<'tcx> {
1764 ast::FloatTy::F32 => self.types.f32,
1765 ast::FloatTy::F64 => self.types.f64,
1769 pub fn mk_str(self) -> Ty<'tcx> {
1773 pub fn mk_static_str(self) -> Ty<'tcx> {
1774 self.mk_imm_ref(self.types.re_static, self.mk_str())
1777 pub fn mk_adt(self, def: &'tcx AdtDef, substs: &'tcx Substs<'tcx>) -> Ty<'tcx> {
1778 // take a copy of substs so that we own the vectors inside
1779 self.mk_ty(TyAdt(def, substs))
1782 pub fn mk_box(self, ty: Ty<'tcx>) -> Ty<'tcx> {
1783 let def_id = self.require_lang_item(lang_items::OwnedBoxLangItem);
1784 let adt_def = self.adt_def(def_id);
1785 let substs = self.mk_substs(iter::once(Kind::from(ty)));
1786 self.mk_ty(TyAdt(adt_def, substs))
1789 pub fn mk_ptr(self, tm: TypeAndMut<'tcx>) -> Ty<'tcx> {
1790 self.mk_ty(TyRawPtr(tm))
1793 pub fn mk_ref(self, r: Region<'tcx>, tm: TypeAndMut<'tcx>) -> Ty<'tcx> {
1794 self.mk_ty(TyRef(r, tm))
1797 pub fn mk_mut_ref(self, r: Region<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
1798 self.mk_ref(r, TypeAndMut {ty: ty, mutbl: hir::MutMutable})
1801 pub fn mk_imm_ref(self, r: Region<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
1802 self.mk_ref(r, TypeAndMut {ty: ty, mutbl: hir::MutImmutable})
1805 pub fn mk_mut_ptr(self, ty: Ty<'tcx>) -> Ty<'tcx> {
1806 self.mk_ptr(TypeAndMut {ty: ty, mutbl: hir::MutMutable})
1809 pub fn mk_imm_ptr(self, ty: Ty<'tcx>) -> Ty<'tcx> {
1810 self.mk_ptr(TypeAndMut {ty: ty, mutbl: hir::MutImmutable})
1813 pub fn mk_nil_ptr(self) -> Ty<'tcx> {
1814 self.mk_imm_ptr(self.mk_nil())
1817 pub fn mk_array(self, ty: Ty<'tcx>, n: u64) -> Ty<'tcx> {
1818 let n = ConstUsize::new(n, self.sess.target.usize_ty).unwrap();
1819 self.mk_array_const_usize(ty, n)
1822 pub fn mk_array_const_usize(self, ty: Ty<'tcx>, n: ConstUsize) -> Ty<'tcx> {
1823 self.mk_ty(TyArray(ty, self.mk_const(ty::Const {
1824 val: ConstVal::Integral(ConstInt::Usize(n)),
1825 ty: self.types.usize
1829 pub fn mk_slice(self, ty: Ty<'tcx>) -> Ty<'tcx> {
1830 self.mk_ty(TySlice(ty))
1833 pub fn intern_tup(self, ts: &[Ty<'tcx>], defaulted: bool) -> Ty<'tcx> {
1834 self.mk_ty(TyTuple(self.intern_type_list(ts), defaulted))
1837 pub fn mk_tup<I: InternAs<[Ty<'tcx>], Ty<'tcx>>>(self, iter: I,
1838 defaulted: bool) -> I::Output {
1839 iter.intern_with(|ts| self.mk_ty(TyTuple(self.intern_type_list(ts), defaulted)))
1842 pub fn mk_nil(self) -> Ty<'tcx> {
1843 self.intern_tup(&[], false)
1846 pub fn mk_diverging_default(self) -> Ty<'tcx> {
1847 if self.sess.features.borrow().never_type {
1850 self.intern_tup(&[], true)
1854 pub fn mk_bool(self) -> Ty<'tcx> {
1858 pub fn mk_fn_def(self, def_id: DefId,
1859 substs: &'tcx Substs<'tcx>) -> Ty<'tcx> {
1860 self.mk_ty(TyFnDef(def_id, substs))
1863 pub fn mk_fn_ptr(self, fty: PolyFnSig<'tcx>) -> Ty<'tcx> {
1864 self.mk_ty(TyFnPtr(fty))
1869 obj: ty::Binder<&'tcx Slice<ExistentialPredicate<'tcx>>>,
1870 reg: ty::Region<'tcx>
1872 self.mk_ty(TyDynamic(obj, reg))
1875 pub fn mk_projection(self,
1877 substs: &'tcx Substs<'tcx>)
1879 self.mk_ty(TyProjection(ProjectionTy {
1885 pub fn mk_closure(self,
1887 substs: &'tcx Substs<'tcx>)
1889 self.mk_closure_from_closure_substs(closure_id, ClosureSubsts {
1894 pub fn mk_closure_from_closure_substs(self,
1896 closure_substs: ClosureSubsts<'tcx>)
1898 self.mk_ty(TyClosure(closure_id, closure_substs))
1901 pub fn mk_generator(self,
1903 closure_substs: ClosureSubsts<'tcx>,
1904 interior: GeneratorInterior<'tcx>)
1906 self.mk_ty(TyGenerator(id, closure_substs, interior))
1909 pub fn mk_var(self, v: TyVid) -> Ty<'tcx> {
1910 self.mk_infer(TyVar(v))
1913 pub fn mk_int_var(self, v: IntVid) -> Ty<'tcx> {
1914 self.mk_infer(IntVar(v))
1917 pub fn mk_float_var(self, v: FloatVid) -> Ty<'tcx> {
1918 self.mk_infer(FloatVar(v))
1921 pub fn mk_infer(self, it: InferTy) -> Ty<'tcx> {
1922 self.mk_ty(TyInfer(it))
1925 pub fn mk_param(self,
1927 name: Name) -> Ty<'tcx> {
1928 self.mk_ty(TyParam(ParamTy { idx: index, name: name }))
1931 pub fn mk_self_type(self) -> Ty<'tcx> {
1932 self.mk_param(0, keywords::SelfType.name())
1935 pub fn mk_param_from_def(self, def: &ty::TypeParameterDef) -> Ty<'tcx> {
1936 self.mk_param(def.index, def.name)
1939 pub fn mk_anon(self, def_id: DefId, substs: &'tcx Substs<'tcx>) -> Ty<'tcx> {
1940 self.mk_ty(TyAnon(def_id, substs))
1943 pub fn intern_existential_predicates(self, eps: &[ExistentialPredicate<'tcx>])
1944 -> &'tcx Slice<ExistentialPredicate<'tcx>> {
1945 assert!(!eps.is_empty());
1946 assert!(eps.windows(2).all(|w| w[0].cmp(self, &w[1]) != Ordering::Greater));
1947 self._intern_existential_predicates(eps)
1950 pub fn intern_predicates(self, preds: &[Predicate<'tcx>])
1951 -> &'tcx Slice<Predicate<'tcx>> {
1952 // FIXME consider asking the input slice to be sorted to avoid
1953 // re-interning permutations, in which case that would be asserted
1955 if preds.len() == 0 {
1956 // The macro-generated method below asserts we don't intern an empty slice.
1959 self._intern_predicates(preds)
1963 pub fn intern_type_list(self, ts: &[Ty<'tcx>]) -> &'tcx Slice<Ty<'tcx>> {
1967 self._intern_type_list(ts)
1971 pub fn intern_substs(self, ts: &[Kind<'tcx>]) -> &'tcx Slice<Kind<'tcx>> {
1975 self._intern_substs(ts)
1979 pub fn mk_fn_sig<I>(self,
1983 unsafety: hir::Unsafety,
1985 -> <I::Item as InternIteratorElement<Ty<'tcx>, ty::FnSig<'tcx>>>::Output
1987 I::Item: InternIteratorElement<Ty<'tcx>, ty::FnSig<'tcx>>
1989 inputs.chain(iter::once(output)).intern_with(|xs| ty::FnSig {
1990 inputs_and_output: self.intern_type_list(xs),
1991 variadic, unsafety, abi
1995 pub fn mk_existential_predicates<I: InternAs<[ExistentialPredicate<'tcx>],
1996 &'tcx Slice<ExistentialPredicate<'tcx>>>>(self, iter: I)
1998 iter.intern_with(|xs| self.intern_existential_predicates(xs))
2001 pub fn mk_predicates<I: InternAs<[Predicate<'tcx>],
2002 &'tcx Slice<Predicate<'tcx>>>>(self, iter: I)
2004 iter.intern_with(|xs| self.intern_predicates(xs))
2007 pub fn mk_type_list<I: InternAs<[Ty<'tcx>],
2008 &'tcx Slice<Ty<'tcx>>>>(self, iter: I) -> I::Output {
2009 iter.intern_with(|xs| self.intern_type_list(xs))
2012 pub fn mk_substs<I: InternAs<[Kind<'tcx>],
2013 &'tcx Slice<Kind<'tcx>>>>(self, iter: I) -> I::Output {
2014 iter.intern_with(|xs| self.intern_substs(xs))
2017 pub fn mk_substs_trait(self,
2020 -> &'tcx Substs<'tcx>
2022 self.mk_substs(iter::once(s).chain(t.into_iter().cloned()).map(Kind::from))
2025 pub fn lint_node<S: Into<MultiSpan>>(self,
2026 lint: &'static Lint,
2030 self.struct_span_lint_node(lint, id, span.into(), msg).emit()
2033 pub fn lint_node_note<S: Into<MultiSpan>>(self,
2034 lint: &'static Lint,
2039 let mut err = self.struct_span_lint_node(lint, id, span.into(), msg);
2044 pub fn lint_level_at_node(self, lint: &'static Lint, mut id: NodeId)
2045 -> (lint::Level, lint::LintSource)
2047 // Right now we insert a `with_ignore` node in the dep graph here to
2048 // ignore the fact that `lint_levels` below depends on the entire crate.
2049 // For now this'll prevent false positives of recompiling too much when
2050 // anything changes.
2052 // Once red/green incremental compilation lands we should be able to
2053 // remove this because while the crate changes often the lint level map
2054 // will change rarely.
2055 self.dep_graph.with_ignore(|| {
2056 let sets = self.lint_levels(LOCAL_CRATE);
2058 let hir_id = self.hir.definitions().node_to_hir_id(id);
2059 if let Some(pair) = sets.level_and_source(lint, hir_id) {
2062 let next = self.hir.get_parent_node(id);
2064 bug!("lint traversal reached the root of the crate");
2071 pub fn struct_span_lint_node<S: Into<MultiSpan>>(self,
2072 lint: &'static Lint,
2076 -> DiagnosticBuilder<'tcx>
2078 let (level, src) = self.lint_level_at_node(lint, id);
2079 lint::struct_lint_level(self.sess, lint, level, src, Some(span.into()), msg)
2082 pub fn struct_lint_node(self, lint: &'static Lint, id: NodeId, msg: &str)
2083 -> DiagnosticBuilder<'tcx>
2085 let (level, src) = self.lint_level_at_node(lint, id);
2086 lint::struct_lint_level(self.sess, lint, level, src, None, msg)
2089 pub fn in_scope_traits(self, id: HirId) -> Option<Rc<Vec<TraitCandidate>>> {
2090 self.in_scope_traits_map(id.owner)
2091 .and_then(|map| map.get(&id.local_id).cloned())
2094 pub fn named_region(self, id: HirId) -> Option<resolve_lifetime::Region> {
2095 self.named_region_map(id.owner)
2096 .and_then(|map| map.get(&id.local_id).cloned())
2099 pub fn is_late_bound(self, id: HirId) -> bool {
2100 self.is_late_bound_map(id.owner)
2101 .map(|set| set.contains(&id.local_id))
2105 pub fn object_lifetime_defaults(self, id: HirId)
2106 -> Option<Rc<Vec<ObjectLifetimeDefault>>>
2108 self.object_lifetime_defaults_map(id.owner)
2109 .and_then(|map| map.get(&id.local_id).cloned())
2113 pub trait InternAs<T: ?Sized, R> {
2115 fn intern_with<F>(self, f: F) -> Self::Output
2116 where F: FnOnce(&T) -> R;
2119 impl<I, T, R, E> InternAs<[T], R> for I
2120 where E: InternIteratorElement<T, R>,
2121 I: Iterator<Item=E> {
2122 type Output = E::Output;
2123 fn intern_with<F>(self, f: F) -> Self::Output
2124 where F: FnOnce(&[T]) -> R {
2125 E::intern_with(self, f)
2129 pub trait InternIteratorElement<T, R>: Sized {
2131 fn intern_with<I: Iterator<Item=Self>, F: FnOnce(&[T]) -> R>(iter: I, f: F) -> Self::Output;
2134 impl<T, R> InternIteratorElement<T, R> for T {
2136 fn intern_with<I: Iterator<Item=Self>, F: FnOnce(&[T]) -> R>(iter: I, f: F) -> Self::Output {
2137 f(&iter.collect::<AccumulateVec<[_; 8]>>())
2141 impl<'a, T, R> InternIteratorElement<T, R> for &'a T
2145 fn intern_with<I: Iterator<Item=Self>, F: FnOnce(&[T]) -> R>(iter: I, f: F) -> Self::Output {
2146 f(&iter.cloned().collect::<AccumulateVec<[_; 8]>>())
2150 impl<T, R, E> InternIteratorElement<T, R> for Result<T, E> {
2151 type Output = Result<R, E>;
2152 fn intern_with<I: Iterator<Item=Self>, F: FnOnce(&[T]) -> R>(iter: I, f: F) -> Self::Output {
2153 Ok(f(&iter.collect::<Result<AccumulateVec<[_; 8]>, _>>()?))
2157 struct NamedRegionMap {
2158 defs: FxHashMap<DefIndex, Rc<FxHashMap<ItemLocalId, resolve_lifetime::Region>>>,
2159 late_bound: FxHashMap<DefIndex, Rc<FxHashSet<ItemLocalId>>>,
2160 object_lifetime_defaults:
2163 Rc<FxHashMap<ItemLocalId, Rc<Vec<ObjectLifetimeDefault>>>>,
2167 pub fn provide(providers: &mut ty::maps::Providers) {
2168 // FIXME(#44234) - almost all of these queries have no sub-queries and
2169 // therefore no actual inputs, they're just reading tables calculated in
2170 // resolve! Does this work? Unsure! That's what the issue is about
2171 providers.in_scope_traits_map = |tcx, id| tcx.gcx.trait_map.get(&id).cloned();
2172 providers.module_exports = |tcx, id| tcx.gcx.export_map.get(&id).cloned();
2173 providers.named_region_map = |tcx, id| tcx.gcx.named_region_map.defs.get(&id).cloned();
2174 providers.is_late_bound_map = |tcx, id| tcx.gcx.named_region_map.late_bound.get(&id).cloned();
2175 providers.object_lifetime_defaults_map = |tcx, id| {
2176 tcx.gcx.named_region_map.object_lifetime_defaults.get(&id).cloned()
2178 providers.crate_name = |tcx, id| {
2179 assert_eq!(id, LOCAL_CRATE);
2182 providers.get_lang_items = |tcx, id| {
2183 assert_eq!(id, LOCAL_CRATE);
2184 Rc::new(middle::lang_items::collect(tcx))
2186 providers.freevars = |tcx, id| tcx.gcx.freevars.get(&id).cloned();
2187 providers.maybe_unused_trait_import = |tcx, id| {
2188 tcx.maybe_unused_trait_imports.contains(&id)
2190 providers.maybe_unused_extern_crates = |tcx, cnum| {
2191 assert_eq!(cnum, LOCAL_CRATE);
2192 Rc::new(tcx.maybe_unused_extern_crates.clone())
2195 providers.stability_index = |tcx, cnum| {
2196 assert_eq!(cnum, LOCAL_CRATE);
2197 Rc::new(stability::Index::new(tcx))
2199 providers.lookup_stability = |tcx, id| {
2200 assert_eq!(id.krate, LOCAL_CRATE);
2201 let id = tcx.hir.definitions().def_index_to_hir_id(id.index);
2202 tcx.stability().local_stability(id)
2204 providers.lookup_deprecation_entry = |tcx, id| {
2205 assert_eq!(id.krate, LOCAL_CRATE);
2206 let id = tcx.hir.definitions().def_index_to_hir_id(id.index);
2207 tcx.stability().local_deprecation_entry(id)
2209 providers.extern_mod_stmt_cnum = |tcx, id| {
2210 let id = tcx.hir.as_local_node_id(id).unwrap();
2211 tcx.cstore.extern_mod_stmt_cnum_untracked(id)
2213 providers.all_crate_nums = |tcx, cnum| {
2214 assert_eq!(cnum, LOCAL_CRATE);
2215 Rc::new(tcx.cstore.crates_untracked())
2217 providers.postorder_cnums = |tcx, cnum| {
2218 assert_eq!(cnum, LOCAL_CRATE);
2219 Rc::new(tcx.cstore.postorder_cnums_untracked())