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 dep_graph::{DepNode, DepConstructor};
15 use errors::DiagnosticBuilder;
17 use session::config::{BorrowckMode, OutputFilenames};
19 use hir::{TraitCandidate, HirId, ItemLocalId};
20 use hir::def::{Def, Export};
21 use hir::def_id::{CrateNum, DefId, DefIndex, LOCAL_CRATE};
22 use hir::map as hir_map;
23 use hir::map::DefPathHash;
24 use lint::{self, Lint};
25 use ich::{StableHashingContext, NodeIdHashingMode};
26 use infer::outlives::free_region_map::FreeRegionMap;
27 use middle::const_val::ConstVal;
28 use middle::cstore::{CrateStore, LinkMeta};
29 use middle::cstore::EncodedMetadata;
30 use middle::lang_items;
31 use middle::resolve_lifetime::{self, ObjectLifetimeDefault};
32 use middle::stability;
33 use mir::{Mir, interpret};
34 use ty::subst::{Kind, Substs};
38 use ty::{self, Ty, TypeAndMut};
39 use ty::{TyS, TypeVariants, Slice};
40 use ty::{AdtKind, AdtDef, ClosureSubsts, GeneratorInterior, Region, Const};
41 use ty::{PolyFnSig, InferTy, ParamTy, ProjectionTy, ExistentialPredicate, Predicate};
43 use ty::{TyVar, TyVid, IntVar, IntVid, FloatVar, FloatVid};
44 use ty::TypeVariants::*;
45 use ty::layout::{LayoutDetails, TargetDataLayout};
49 use util::nodemap::{NodeMap, DefIdSet, ItemLocalMap};
50 use util::nodemap::{FxHashMap, FxHashSet};
51 use rustc_data_structures::accumulate_vec::AccumulateVec;
52 use rustc_data_structures::stable_hasher::{HashStable, hash_stable_hashmap,
53 StableHasher, StableHasherResult,
55 use arena::{TypedArena, DroplessArena};
56 use rustc_const_math::{ConstInt, ConstUsize};
57 use rustc_data_structures::indexed_vec::IndexVec;
58 use rustc_data_structures::sync::Lrc;
60 use std::borrow::Borrow;
61 use std::cell::{Cell, RefCell};
62 use std::cmp::Ordering;
63 use std::collections::hash_map::{self, Entry};
64 use std::hash::{Hash, Hasher};
71 use syntax::ast::{self, Name, NodeId};
73 use syntax::codemap::MultiSpan;
74 use syntax::feature_gate;
75 use syntax::symbol::{Symbol, keywords};
80 pub struct AllArenas<'tcx> {
81 pub global: GlobalArenas<'tcx>,
82 pub interner: DroplessArena,
85 impl<'tcx> AllArenas<'tcx> {
86 pub fn new() -> Self {
88 global: GlobalArenas::new(),
89 interner: DroplessArena::new(),
95 pub struct GlobalArenas<'tcx> {
97 layout: TypedArena<LayoutDetails>,
100 generics: TypedArena<ty::Generics>,
101 trait_def: TypedArena<ty::TraitDef>,
102 adt_def: TypedArena<ty::AdtDef>,
103 steal_mir: TypedArena<Steal<Mir<'tcx>>>,
104 mir: TypedArena<Mir<'tcx>>,
105 tables: TypedArena<ty::TypeckTables<'tcx>>,
107 const_allocs: TypedArena<interpret::Allocation>,
110 impl<'tcx> GlobalArenas<'tcx> {
111 pub fn new() -> GlobalArenas<'tcx> {
113 layout: TypedArena::new(),
114 generics: TypedArena::new(),
115 trait_def: TypedArena::new(),
116 adt_def: TypedArena::new(),
117 steal_mir: TypedArena::new(),
118 mir: TypedArena::new(),
119 tables: TypedArena::new(),
120 const_allocs: TypedArena::new(),
125 pub struct CtxtInterners<'tcx> {
126 /// The arena that types, regions, etc are allocated from
127 arena: &'tcx DroplessArena,
129 /// Specifically use a speedy hash algorithm for these hash sets,
130 /// they're accessed quite often.
131 type_: RefCell<FxHashSet<Interned<'tcx, TyS<'tcx>>>>,
132 type_list: RefCell<FxHashSet<Interned<'tcx, Slice<Ty<'tcx>>>>>,
133 substs: RefCell<FxHashSet<Interned<'tcx, Substs<'tcx>>>>,
134 region: RefCell<FxHashSet<Interned<'tcx, RegionKind>>>,
135 existential_predicates: RefCell<FxHashSet<Interned<'tcx, Slice<ExistentialPredicate<'tcx>>>>>,
136 predicates: RefCell<FxHashSet<Interned<'tcx, Slice<Predicate<'tcx>>>>>,
137 const_: RefCell<FxHashSet<Interned<'tcx, Const<'tcx>>>>,
140 impl<'gcx: 'tcx, 'tcx> CtxtInterners<'tcx> {
141 fn new(arena: &'tcx DroplessArena) -> CtxtInterners<'tcx> {
144 type_: RefCell::new(FxHashSet()),
145 type_list: RefCell::new(FxHashSet()),
146 substs: RefCell::new(FxHashSet()),
147 region: RefCell::new(FxHashSet()),
148 existential_predicates: RefCell::new(FxHashSet()),
149 predicates: RefCell::new(FxHashSet()),
150 const_: RefCell::new(FxHashSet()),
154 /// Intern a type. global_interners is Some only if this is
155 /// a local interner and global_interners is its counterpart.
156 fn intern_ty(&self, st: TypeVariants<'tcx>,
157 global_interners: Option<&CtxtInterners<'gcx>>)
160 let mut interner = self.type_.borrow_mut();
161 let global_interner = global_interners.map(|interners| {
162 interners.type_.borrow_mut()
164 if let Some(&Interned(ty)) = interner.get(&st) {
167 if let Some(ref interner) = global_interner {
168 if let Some(&Interned(ty)) = interner.get(&st) {
173 let flags = super::flags::FlagComputation::for_sty(&st);
174 let ty_struct = TyS {
177 region_depth: flags.depth,
180 // HACK(eddyb) Depend on flags being accurate to
181 // determine that all contents are in the global tcx.
182 // See comments on Lift for why we can't use that.
183 if !flags.flags.intersects(ty::TypeFlags::KEEP_IN_LOCAL_TCX) {
184 if let Some(interner) = global_interners {
185 let ty_struct: TyS<'gcx> = unsafe {
186 mem::transmute(ty_struct)
188 let ty: Ty<'gcx> = interner.arena.alloc(ty_struct);
189 global_interner.unwrap().insert(Interned(ty));
193 // Make sure we don't end up with inference
194 // types/regions in the global tcx.
195 if global_interners.is_none() {
197 bug!("Attempted to intern `{:?}` which contains \
198 inference types/regions in the global type context",
203 // Don't be &mut TyS.
204 let ty: Ty<'tcx> = self.arena.alloc(ty_struct);
205 interner.insert(Interned(ty));
209 debug!("Interned type: {:?} Pointer: {:?}",
210 ty, ty as *const TyS);
216 pub struct CommonTypes<'tcx> {
236 pub re_empty: Region<'tcx>,
237 pub re_static: Region<'tcx>,
238 pub re_erased: Region<'tcx>,
241 pub struct LocalTableInContext<'a, V: 'a> {
242 local_id_root: Option<DefId>,
243 data: &'a ItemLocalMap<V>
246 /// Validate that the given HirId (respectively its `local_id` part) can be
247 /// safely used as a key in the tables of a TypeckTable. For that to be
248 /// the case, the HirId must have the same `owner` as all the other IDs in
249 /// this table (signified by `local_id_root`). Otherwise the HirId
250 /// would be in a different frame of reference and using its `local_id`
251 /// would result in lookup errors, or worse, in silently wrong data being
253 fn validate_hir_id_for_typeck_tables(local_id_root: Option<DefId>,
256 if cfg!(debug_assertions) {
257 if let Some(local_id_root) = local_id_root {
258 if hir_id.owner != local_id_root.index {
259 ty::tls::with(|tcx| {
260 let node_id = tcx.hir
262 .find_node_for_hir_id(hir_id);
264 bug!("node {} with HirId::owner {:?} cannot be placed in \
265 TypeckTables with local_id_root {:?}",
266 tcx.hir.node_to_string(node_id),
267 DefId::local(hir_id.owner),
272 // We use "Null Object" TypeckTables in some of the analysis passes.
273 // These are just expected to be empty and their `local_id_root` is
274 // `None`. Therefore we cannot verify whether a given `HirId` would
275 // be a valid key for the given table. Instead we make sure that
276 // nobody tries to write to such a Null Object table.
278 bug!("access to invalid TypeckTables")
284 impl<'a, V> LocalTableInContext<'a, V> {
285 pub fn contains_key(&self, id: hir::HirId) -> bool {
286 validate_hir_id_for_typeck_tables(self.local_id_root, id, false);
287 self.data.contains_key(&id.local_id)
290 pub fn get(&self, id: hir::HirId) -> Option<&V> {
291 validate_hir_id_for_typeck_tables(self.local_id_root, id, false);
292 self.data.get(&id.local_id)
295 pub fn iter(&self) -> hash_map::Iter<hir::ItemLocalId, V> {
300 impl<'a, V> ::std::ops::Index<hir::HirId> for LocalTableInContext<'a, V> {
303 fn index(&self, key: hir::HirId) -> &V {
304 self.get(key).expect("LocalTableInContext: key not found")
308 pub struct LocalTableInContextMut<'a, V: 'a> {
309 local_id_root: Option<DefId>,
310 data: &'a mut ItemLocalMap<V>
313 impl<'a, V> LocalTableInContextMut<'a, V> {
314 pub fn get_mut(&mut self, id: hir::HirId) -> Option<&mut V> {
315 validate_hir_id_for_typeck_tables(self.local_id_root, id, true);
316 self.data.get_mut(&id.local_id)
319 pub fn entry(&mut self, id: hir::HirId) -> Entry<hir::ItemLocalId, V> {
320 validate_hir_id_for_typeck_tables(self.local_id_root, id, true);
321 self.data.entry(id.local_id)
324 pub fn insert(&mut self, id: hir::HirId, val: V) -> Option<V> {
325 validate_hir_id_for_typeck_tables(self.local_id_root, id, true);
326 self.data.insert(id.local_id, val)
329 pub fn remove(&mut self, id: hir::HirId) -> Option<V> {
330 validate_hir_id_for_typeck_tables(self.local_id_root, id, true);
331 self.data.remove(&id.local_id)
335 #[derive(RustcEncodable, RustcDecodable, Debug)]
336 pub struct TypeckTables<'tcx> {
337 /// The HirId::owner all ItemLocalIds in this table are relative to.
338 pub local_id_root: Option<DefId>,
340 /// Resolved definitions for `<T>::X` associated paths and
341 /// method calls, including those of overloaded operators.
342 type_dependent_defs: ItemLocalMap<Def>,
344 /// Stores the types for various nodes in the AST. Note that this table
345 /// is not guaranteed to be populated until after typeck. See
346 /// typeck::check::fn_ctxt for details.
347 node_types: ItemLocalMap<Ty<'tcx>>,
349 /// Stores the type parameters which were substituted to obtain the type
350 /// of this node. This only applies to nodes that refer to entities
351 /// parameterized by type parameters, such as generic fns, types, or
353 node_substs: ItemLocalMap<&'tcx Substs<'tcx>>,
355 adjustments: ItemLocalMap<Vec<ty::adjustment::Adjustment<'tcx>>>,
357 /// Stores the actual binding mode for all instances of hir::BindingAnnotation.
358 pat_binding_modes: ItemLocalMap<BindingMode>,
360 /// Stores the types which were implicitly dereferenced in pattern binding modes
361 /// for later usage in HAIR lowering. For example,
364 /// match &&Some(5i32) {
369 /// leads to a `vec![&&Option<i32>, &Option<i32>]`. Empty vectors are not stored.
372 /// https://github.com/rust-lang/rfcs/blob/master/text/2005-match-ergonomics.md#definitions
373 pat_adjustments: ItemLocalMap<Vec<Ty<'tcx>>>,
376 pub upvar_capture_map: ty::UpvarCaptureMap<'tcx>,
378 /// Records the reasons that we picked the kind of each closure;
379 /// not all closures are present in the map.
380 closure_kind_origins: ItemLocalMap<(Span, ast::Name)>,
382 /// For each fn, records the "liberated" types of its arguments
383 /// and return type. Liberated means that all bound regions
384 /// (including late-bound regions) are replaced with free
385 /// equivalents. This table is not used in trans (since regions
386 /// are erased there) and hence is not serialized to metadata.
387 liberated_fn_sigs: ItemLocalMap<ty::FnSig<'tcx>>,
389 /// For each FRU expression, record the normalized types of the fields
390 /// of the struct - this is needed because it is non-trivial to
391 /// normalize while preserving regions. This table is used only in
392 /// MIR construction and hence is not serialized to metadata.
393 fru_field_types: ItemLocalMap<Vec<Ty<'tcx>>>,
395 /// Maps a cast expression to its kind. This is keyed on the
396 /// *from* expression of the cast, not the cast itself.
397 cast_kinds: ItemLocalMap<ty::cast::CastKind>,
399 /// Set of trait imports actually used in the method resolution.
400 /// This is used for warning unused imports. During type
401 /// checking, this `Lrc` should not be cloned: it must have a ref-count
402 /// of 1 so that we can insert things into the set mutably.
403 pub used_trait_imports: Lrc<DefIdSet>,
405 /// If any errors occurred while type-checking this body,
406 /// this field will be set to `true`.
407 pub tainted_by_errors: bool,
409 /// Stores the free-region relationships that were deduced from
410 /// its where clauses and parameter types. These are then
411 /// read-again by borrowck.
412 pub free_region_map: FreeRegionMap<'tcx>,
415 impl<'tcx> TypeckTables<'tcx> {
416 pub fn empty(local_id_root: Option<DefId>) -> TypeckTables<'tcx> {
419 type_dependent_defs: ItemLocalMap(),
420 node_types: ItemLocalMap(),
421 node_substs: ItemLocalMap(),
422 adjustments: ItemLocalMap(),
423 pat_binding_modes: ItemLocalMap(),
424 pat_adjustments: ItemLocalMap(),
425 upvar_capture_map: FxHashMap(),
426 closure_kind_origins: ItemLocalMap(),
427 liberated_fn_sigs: ItemLocalMap(),
428 fru_field_types: ItemLocalMap(),
429 cast_kinds: ItemLocalMap(),
430 used_trait_imports: Lrc::new(DefIdSet()),
431 tainted_by_errors: false,
432 free_region_map: FreeRegionMap::new(),
436 /// Returns the final resolution of a `QPath` in an `Expr` or `Pat` node.
437 pub fn qpath_def(&self, qpath: &hir::QPath, id: hir::HirId) -> Def {
439 hir::QPath::Resolved(_, ref path) => path.def,
440 hir::QPath::TypeRelative(..) => {
441 validate_hir_id_for_typeck_tables(self.local_id_root, id, false);
442 self.type_dependent_defs.get(&id.local_id).cloned().unwrap_or(Def::Err)
447 pub fn type_dependent_defs(&self) -> LocalTableInContext<Def> {
448 LocalTableInContext {
449 local_id_root: self.local_id_root,
450 data: &self.type_dependent_defs
454 pub fn type_dependent_defs_mut(&mut self) -> LocalTableInContextMut<Def> {
455 LocalTableInContextMut {
456 local_id_root: self.local_id_root,
457 data: &mut self.type_dependent_defs
461 pub fn node_types(&self) -> LocalTableInContext<Ty<'tcx>> {
462 LocalTableInContext {
463 local_id_root: self.local_id_root,
464 data: &self.node_types
468 pub fn node_types_mut(&mut self) -> LocalTableInContextMut<Ty<'tcx>> {
469 LocalTableInContextMut {
470 local_id_root: self.local_id_root,
471 data: &mut self.node_types
475 pub fn node_id_to_type(&self, id: hir::HirId) -> Ty<'tcx> {
476 match self.node_id_to_type_opt(id) {
479 bug!("node_id_to_type: no type for node `{}`",
481 let id = tcx.hir.definitions().find_node_for_hir_id(id);
482 tcx.hir.node_to_string(id)
488 pub fn node_id_to_type_opt(&self, id: hir::HirId) -> Option<Ty<'tcx>> {
489 validate_hir_id_for_typeck_tables(self.local_id_root, id, false);
490 self.node_types.get(&id.local_id).cloned()
493 pub fn node_substs_mut(&mut self) -> LocalTableInContextMut<&'tcx Substs<'tcx>> {
494 LocalTableInContextMut {
495 local_id_root: self.local_id_root,
496 data: &mut self.node_substs
500 pub fn node_substs(&self, id: hir::HirId) -> &'tcx Substs<'tcx> {
501 validate_hir_id_for_typeck_tables(self.local_id_root, id, false);
502 self.node_substs.get(&id.local_id).cloned().unwrap_or(Substs::empty())
505 pub fn node_substs_opt(&self, id: hir::HirId) -> Option<&'tcx Substs<'tcx>> {
506 validate_hir_id_for_typeck_tables(self.local_id_root, id, false);
507 self.node_substs.get(&id.local_id).cloned()
510 // Returns the type of a pattern as a monotype. Like @expr_ty, this function
511 // doesn't provide type parameter substitutions.
512 pub fn pat_ty(&self, pat: &hir::Pat) -> Ty<'tcx> {
513 self.node_id_to_type(pat.hir_id)
516 pub fn pat_ty_opt(&self, pat: &hir::Pat) -> Option<Ty<'tcx>> {
517 self.node_id_to_type_opt(pat.hir_id)
520 // Returns the type of an expression as a monotype.
522 // NB (1): This is the PRE-ADJUSTMENT TYPE for the expression. That is, in
523 // some cases, we insert `Adjustment` annotations such as auto-deref or
524 // auto-ref. The type returned by this function does not consider such
525 // adjustments. See `expr_ty_adjusted()` instead.
527 // NB (2): This type doesn't provide type parameter substitutions; e.g. if you
528 // ask for the type of "id" in "id(3)", it will return "fn(&isize) -> isize"
529 // instead of "fn(ty) -> T with T = isize".
530 pub fn expr_ty(&self, expr: &hir::Expr) -> Ty<'tcx> {
531 self.node_id_to_type(expr.hir_id)
534 pub fn expr_ty_opt(&self, expr: &hir::Expr) -> Option<Ty<'tcx>> {
535 self.node_id_to_type_opt(expr.hir_id)
538 pub fn adjustments(&self) -> LocalTableInContext<Vec<ty::adjustment::Adjustment<'tcx>>> {
539 LocalTableInContext {
540 local_id_root: self.local_id_root,
541 data: &self.adjustments
545 pub fn adjustments_mut(&mut self)
546 -> LocalTableInContextMut<Vec<ty::adjustment::Adjustment<'tcx>>> {
547 LocalTableInContextMut {
548 local_id_root: self.local_id_root,
549 data: &mut self.adjustments
553 pub fn expr_adjustments(&self, expr: &hir::Expr)
554 -> &[ty::adjustment::Adjustment<'tcx>] {
555 validate_hir_id_for_typeck_tables(self.local_id_root, expr.hir_id, false);
556 self.adjustments.get(&expr.hir_id.local_id).map_or(&[], |a| &a[..])
559 /// Returns the type of `expr`, considering any `Adjustment`
560 /// entry recorded for that expression.
561 pub fn expr_ty_adjusted(&self, expr: &hir::Expr) -> Ty<'tcx> {
562 self.expr_adjustments(expr)
564 .map_or_else(|| self.expr_ty(expr), |adj| adj.target)
567 pub fn expr_ty_adjusted_opt(&self, expr: &hir::Expr) -> Option<Ty<'tcx>> {
568 self.expr_adjustments(expr)
570 .map(|adj| adj.target)
571 .or_else(|| self.expr_ty_opt(expr))
574 pub fn is_method_call(&self, expr: &hir::Expr) -> bool {
575 // Only paths and method calls/overloaded operators have
576 // entries in type_dependent_defs, ignore the former here.
577 if let hir::ExprPath(_) = expr.node {
581 match self.type_dependent_defs().get(expr.hir_id) {
582 Some(&Def::Method(_)) => true,
587 pub fn pat_binding_modes(&self) -> LocalTableInContext<BindingMode> {
588 LocalTableInContext {
589 local_id_root: self.local_id_root,
590 data: &self.pat_binding_modes
594 pub fn pat_binding_modes_mut(&mut self)
595 -> LocalTableInContextMut<BindingMode> {
596 LocalTableInContextMut {
597 local_id_root: self.local_id_root,
598 data: &mut self.pat_binding_modes
602 pub fn pat_adjustments(&self) -> LocalTableInContext<Vec<Ty<'tcx>>> {
603 LocalTableInContext {
604 local_id_root: self.local_id_root,
605 data: &self.pat_adjustments,
609 pub fn pat_adjustments_mut(&mut self)
610 -> LocalTableInContextMut<Vec<Ty<'tcx>>> {
611 LocalTableInContextMut {
612 local_id_root: self.local_id_root,
613 data: &mut self.pat_adjustments,
617 pub fn upvar_capture(&self, upvar_id: ty::UpvarId) -> ty::UpvarCapture<'tcx> {
618 self.upvar_capture_map[&upvar_id]
621 pub fn closure_kind_origins(&self) -> LocalTableInContext<(Span, ast::Name)> {
622 LocalTableInContext {
623 local_id_root: self.local_id_root,
624 data: &self.closure_kind_origins
628 pub fn closure_kind_origins_mut(&mut self) -> LocalTableInContextMut<(Span, ast::Name)> {
629 LocalTableInContextMut {
630 local_id_root: self.local_id_root,
631 data: &mut self.closure_kind_origins
635 pub fn liberated_fn_sigs(&self) -> LocalTableInContext<ty::FnSig<'tcx>> {
636 LocalTableInContext {
637 local_id_root: self.local_id_root,
638 data: &self.liberated_fn_sigs
642 pub fn liberated_fn_sigs_mut(&mut self) -> LocalTableInContextMut<ty::FnSig<'tcx>> {
643 LocalTableInContextMut {
644 local_id_root: self.local_id_root,
645 data: &mut self.liberated_fn_sigs
649 pub fn fru_field_types(&self) -> LocalTableInContext<Vec<Ty<'tcx>>> {
650 LocalTableInContext {
651 local_id_root: self.local_id_root,
652 data: &self.fru_field_types
656 pub fn fru_field_types_mut(&mut self) -> LocalTableInContextMut<Vec<Ty<'tcx>>> {
657 LocalTableInContextMut {
658 local_id_root: self.local_id_root,
659 data: &mut self.fru_field_types
663 pub fn cast_kinds(&self) -> LocalTableInContext<ty::cast::CastKind> {
664 LocalTableInContext {
665 local_id_root: self.local_id_root,
666 data: &self.cast_kinds
670 pub fn cast_kinds_mut(&mut self) -> LocalTableInContextMut<ty::cast::CastKind> {
671 LocalTableInContextMut {
672 local_id_root: self.local_id_root,
673 data: &mut self.cast_kinds
678 impl<'gcx> HashStable<StableHashingContext<'gcx>> for TypeckTables<'gcx> {
679 fn hash_stable<W: StableHasherResult>(&self,
680 hcx: &mut StableHashingContext<'gcx>,
681 hasher: &mut StableHasher<W>) {
682 let ty::TypeckTables {
684 ref type_dependent_defs,
688 ref pat_binding_modes,
690 ref upvar_capture_map,
691 ref closure_kind_origins,
692 ref liberated_fn_sigs,
697 ref used_trait_imports,
702 hcx.with_node_id_hashing_mode(NodeIdHashingMode::HashDefPath, |hcx| {
703 type_dependent_defs.hash_stable(hcx, hasher);
704 node_types.hash_stable(hcx, hasher);
705 node_substs.hash_stable(hcx, hasher);
706 adjustments.hash_stable(hcx, hasher);
707 pat_binding_modes.hash_stable(hcx, hasher);
708 pat_adjustments.hash_stable(hcx, hasher);
709 hash_stable_hashmap(hcx, hasher, upvar_capture_map, |up_var_id, hcx| {
716 local_id_root.expect("trying to hash invalid TypeckTables");
718 let var_owner_def_id = DefId {
719 krate: local_id_root.krate,
722 let closure_def_id = DefId {
723 krate: local_id_root.krate,
724 index: closure_expr_id.to_def_id().index,
726 (hcx.def_path_hash(var_owner_def_id),
728 hcx.def_path_hash(closure_def_id))
731 closure_kind_origins.hash_stable(hcx, hasher);
732 liberated_fn_sigs.hash_stable(hcx, hasher);
733 fru_field_types.hash_stable(hcx, hasher);
734 cast_kinds.hash_stable(hcx, hasher);
735 used_trait_imports.hash_stable(hcx, hasher);
736 tainted_by_errors.hash_stable(hcx, hasher);
737 free_region_map.hash_stable(hcx, hasher);
742 impl<'tcx> CommonTypes<'tcx> {
743 fn new(interners: &CtxtInterners<'tcx>) -> CommonTypes<'tcx> {
744 let mk = |sty| interners.intern_ty(sty, None);
745 let mk_region = |r| {
746 if let Some(r) = interners.region.borrow().get(&r) {
749 let r = interners.arena.alloc(r);
750 interners.region.borrow_mut().insert(Interned(r));
758 isize: mk(TyInt(ast::IntTy::Isize)),
759 i8: mk(TyInt(ast::IntTy::I8)),
760 i16: mk(TyInt(ast::IntTy::I16)),
761 i32: mk(TyInt(ast::IntTy::I32)),
762 i64: mk(TyInt(ast::IntTy::I64)),
763 i128: mk(TyInt(ast::IntTy::I128)),
764 usize: mk(TyUint(ast::UintTy::Usize)),
765 u8: mk(TyUint(ast::UintTy::U8)),
766 u16: mk(TyUint(ast::UintTy::U16)),
767 u32: mk(TyUint(ast::UintTy::U32)),
768 u64: mk(TyUint(ast::UintTy::U64)),
769 u128: mk(TyUint(ast::UintTy::U128)),
770 f32: mk(TyFloat(ast::FloatTy::F32)),
771 f64: mk(TyFloat(ast::FloatTy::F64)),
773 re_empty: mk_region(RegionKind::ReEmpty),
774 re_static: mk_region(RegionKind::ReStatic),
775 re_erased: mk_region(RegionKind::ReErased),
780 /// The central data structure of the compiler. It stores references
781 /// to the various **arenas** and also houses the results of the
782 /// various **compiler queries** that have been performed. See the
783 /// [rustc guide] for more details.
785 /// [rustc guide]: https://rust-lang-nursery.github.io/rustc-guide/ty.html
786 #[derive(Copy, Clone)]
787 pub struct TyCtxt<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
788 gcx: &'a GlobalCtxt<'gcx>,
789 interners: &'a CtxtInterners<'tcx>
792 impl<'a, 'gcx, 'tcx> Deref for TyCtxt<'a, 'gcx, 'tcx> {
793 type Target = &'a GlobalCtxt<'gcx>;
794 fn deref(&self) -> &Self::Target {
799 pub struct GlobalCtxt<'tcx> {
800 global_arenas: &'tcx GlobalArenas<'tcx>,
801 global_interners: CtxtInterners<'tcx>,
803 cstore: &'tcx dyn CrateStore,
805 pub sess: &'tcx Session,
807 pub dep_graph: DepGraph,
809 /// This provides access to the incr. comp. on-disk cache for query results.
810 /// Do not access this directly. It is only meant to be used by
811 /// `DepGraph::try_mark_green()` and the query infrastructure in `ty::maps`.
812 pub(crate) on_disk_query_result_cache: maps::OnDiskCache<'tcx>,
814 /// Common types, pre-interned for your convenience.
815 pub types: CommonTypes<'tcx>,
817 /// Map indicating what traits are in scope for places where this
818 /// is relevant; generated by resolve.
819 trait_map: FxHashMap<DefIndex,
820 Lrc<FxHashMap<ItemLocalId,
821 Lrc<StableVec<TraitCandidate>>>>>,
823 /// Export map produced by name resolution.
824 export_map: FxHashMap<DefId, Lrc<Vec<Export>>>,
826 pub hir: hir_map::Map<'tcx>,
828 /// A map from DefPathHash -> DefId. Includes DefIds from the local crate
829 /// as well as all upstream crates. Only populated in incremental mode.
830 pub def_path_hash_to_def_id: Option<FxHashMap<DefPathHash, DefId>>,
832 pub maps: maps::Maps<'tcx>,
834 // Records the free variables refrenced by every closure
835 // expression. Do not track deps for this, just recompute it from
836 // scratch every time.
837 freevars: FxHashMap<DefId, Lrc<Vec<hir::Freevar>>>,
839 maybe_unused_trait_imports: FxHashSet<DefId>,
841 maybe_unused_extern_crates: Vec<(DefId, Span)>,
843 // Internal cache for metadata decoding. No need to track deps on this.
844 pub rcache: RefCell<FxHashMap<ty::CReaderCacheKey, Ty<'tcx>>>,
846 /// Caches the results of trait selection. This cache is used
847 /// for things that do not have to do with the parameters in scope.
848 pub selection_cache: traits::SelectionCache<'tcx>,
850 /// Caches the results of trait evaluation. This cache is used
851 /// for things that do not have to do with the parameters in scope.
852 /// Merge this with `selection_cache`?
853 pub evaluation_cache: traits::EvaluationCache<'tcx>,
855 /// The definite name of the current crate after taking into account
856 /// attributes, commandline parameters, etc.
857 pub crate_name: Symbol,
859 /// Data layout specification for the current target.
860 pub data_layout: TargetDataLayout,
862 /// Used to prevent layout from recursing too deeply.
863 pub layout_depth: Cell<usize>,
865 /// Map from function to the `#[derive]` mode that it's defining. Only used
866 /// by `proc-macro` crates.
867 pub derive_macros: RefCell<NodeMap<Symbol>>,
869 stability_interner: RefCell<FxHashSet<&'tcx attr::Stability>>,
871 pub interpret_interner: RefCell<InterpretInterner<'tcx>>,
873 layout_interner: RefCell<FxHashSet<&'tcx LayoutDetails>>,
875 /// A vector of every trait accessible in the whole crate
876 /// (i.e. including those from subcrates). This is used only for
877 /// error reporting, and so is lazily initialized and generally
878 /// shouldn't taint the common path (hence the RefCell).
879 pub all_traits: RefCell<Option<Vec<DefId>>>,
881 /// A general purpose channel to throw data out the back towards LLVM worker
884 /// This is intended to only get used during the trans phase of the compiler
885 /// when satisfying the query for a particular codegen unit. Internally in
886 /// the query it'll send data along this channel to get processed later.
887 pub tx_to_llvm_workers: mpsc::Sender<Box<dyn Any + Send>>,
889 output_filenames: Arc<OutputFilenames>,
892 /// Everything needed to efficiently work with interned allocations
893 #[derive(Debug, Default)]
894 pub struct InterpretInterner<'tcx> {
895 /// Stores the value of constants (and deduplicates the actual memory)
896 allocs: FxHashSet<&'tcx interpret::Allocation>,
898 /// Allows obtaining function instance handles via a unique identifier
899 functions: FxHashMap<interpret::AllocId, Instance<'tcx>>,
901 /// Inverse map of `interpret_functions`.
902 /// Used so we don't allocate a new pointer every time we need one
903 function_cache: FxHashMap<Instance<'tcx>, interpret::AllocId>,
905 /// Allows obtaining const allocs via a unique identifier
906 alloc_by_id: FxHashMap<interpret::AllocId, &'tcx interpret::Allocation>,
908 /// The AllocId to assign to the next new regular allocation.
909 /// Always incremented, never gets smaller.
910 next_id: interpret::AllocId,
912 /// Allows checking whether a constant already has an allocation
913 alloc_cache: FxHashMap<interpret::GlobalId<'tcx>, interpret::AllocId>,
915 /// A cache for basic byte allocations keyed by their contents. This is used to deduplicate
916 /// allocations for string and bytestring literals.
917 literal_alloc_cache: FxHashMap<Vec<u8>, interpret::AllocId>,
920 impl<'tcx> InterpretInterner<'tcx> {
921 pub fn create_fn_alloc(&mut self, instance: Instance<'tcx>) -> interpret::AllocId {
922 if let Some(&alloc_id) = self.function_cache.get(&instance) {
925 let id = self.reserve();
926 debug!("creating fn ptr: {}", id);
927 self.functions.insert(id, instance);
928 self.function_cache.insert(instance, id);
934 id: interpret::AllocId,
935 ) -> Option<Instance<'tcx>> {
936 self.functions.get(&id).cloned()
941 id: interpret::AllocId,
942 ) -> Option<&'tcx interpret::Allocation> {
943 self.alloc_by_id.get(&id).cloned()
948 global_id: interpret::GlobalId<'tcx>,
949 ) -> Option<interpret::AllocId> {
950 self.alloc_cache.get(&global_id).cloned()
955 global_id: interpret::GlobalId<'tcx>,
956 ptr: interpret::AllocId,
958 if let Some(old) = self.alloc_cache.insert(global_id, ptr) {
959 bug!("tried to cache {:?}, but was already existing as {:#?}", global_id, old);
963 pub fn intern_at_reserved(
965 id: interpret::AllocId,
966 alloc: &'tcx interpret::Allocation,
968 if let Some(old) = self.alloc_by_id.insert(id, alloc) {
969 bug!("tried to intern allocation at {}, but was already existing as {:#?}", id, old);
973 /// obtains a new allocation ID that can be referenced but does not
974 /// yet have an allocation backing it.
977 ) -> interpret::AllocId {
978 let next = self.next_id;
979 self.next_id.0 = self.next_id.0
981 .expect("You overflowed a u64 by incrementing by 1... \
982 You've just earned yourself a free drink if we ever meet. \
983 Seriously, how did you do that?!");
988 impl<'tcx> GlobalCtxt<'tcx> {
989 /// Get the global TyCtxt.
990 pub fn global_tcx<'a>(&'a self) -> TyCtxt<'a, 'tcx, 'tcx> {
993 interners: &self.global_interners
998 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
999 pub fn alloc_generics(self, generics: ty::Generics) -> &'gcx ty::Generics {
1000 self.global_arenas.generics.alloc(generics)
1003 pub fn alloc_steal_mir(self, mir: Mir<'gcx>) -> &'gcx Steal<Mir<'gcx>> {
1004 self.global_arenas.steal_mir.alloc(Steal::new(mir))
1007 pub fn alloc_mir(self, mir: Mir<'gcx>) -> &'gcx Mir<'gcx> {
1008 self.global_arenas.mir.alloc(mir)
1011 pub fn alloc_tables(self, tables: ty::TypeckTables<'gcx>) -> &'gcx ty::TypeckTables<'gcx> {
1012 self.global_arenas.tables.alloc(tables)
1015 pub fn alloc_trait_def(self, def: ty::TraitDef) -> &'gcx ty::TraitDef {
1016 self.global_arenas.trait_def.alloc(def)
1019 pub fn alloc_adt_def(self,
1022 variants: Vec<ty::VariantDef>,
1024 -> &'gcx ty::AdtDef {
1025 let def = ty::AdtDef::new(self, did, kind, variants, repr);
1026 self.global_arenas.adt_def.alloc(def)
1029 pub fn alloc_byte_array(self, bytes: &[u8]) -> &'gcx [u8] {
1030 if bytes.is_empty() {
1033 self.global_interners.arena.alloc_slice(bytes)
1037 pub fn alloc_const_slice(self, values: &[&'tcx ty::Const<'tcx>])
1038 -> &'tcx [&'tcx ty::Const<'tcx>] {
1039 if values.is_empty() {
1042 self.interners.arena.alloc_slice(values)
1046 pub fn alloc_name_const_slice(self, values: &[(ast::Name, &'tcx ty::Const<'tcx>)])
1047 -> &'tcx [(ast::Name, &'tcx ty::Const<'tcx>)] {
1048 if values.is_empty() {
1051 self.interners.arena.alloc_slice(values)
1055 pub fn intern_const_alloc(
1057 alloc: interpret::Allocation,
1058 ) -> &'gcx interpret::Allocation {
1059 if let Some(alloc) = self.interpret_interner.borrow().allocs.get(&alloc) {
1063 let interned = self.global_arenas.const_allocs.alloc(alloc);
1064 if let Some(prev) = self.interpret_interner.borrow_mut().allocs.replace(interned) {
1065 bug!("Tried to overwrite interned Allocation: {:#?}", prev)
1070 /// Allocates a byte or string literal for `mir::interpret`
1071 pub fn allocate_cached(self, bytes: &[u8]) -> interpret::AllocId {
1072 // check whether we already allocated this literal or a constant with the same memory
1073 if let Some(&alloc_id) = self.interpret_interner.borrow().literal_alloc_cache.get(bytes) {
1076 // create an allocation that just contains these bytes
1077 let alloc = interpret::Allocation::from_bytes(bytes);
1078 let alloc = self.intern_const_alloc(alloc);
1080 let mut int = self.interpret_interner.borrow_mut();
1081 // the next unique id
1082 let id = int.reserve();
1083 // make the allocation identifiable
1084 int.alloc_by_id.insert(id, alloc);
1085 // cache it for the future
1086 int.literal_alloc_cache.insert(bytes.to_owned(), id);
1090 pub fn intern_stability(self, stab: attr::Stability) -> &'gcx attr::Stability {
1091 if let Some(st) = self.stability_interner.borrow().get(&stab) {
1095 let interned = self.global_interners.arena.alloc(stab);
1096 if let Some(prev) = self.stability_interner.borrow_mut().replace(interned) {
1097 bug!("Tried to overwrite interned Stability: {:?}", prev)
1102 pub fn intern_layout(self, layout: LayoutDetails) -> &'gcx LayoutDetails {
1103 if let Some(layout) = self.layout_interner.borrow().get(&layout) {
1107 let interned = self.global_arenas.layout.alloc(layout);
1108 if let Some(prev) = self.layout_interner.borrow_mut().replace(interned) {
1109 bug!("Tried to overwrite interned Layout: {:?}", prev)
1114 pub fn lift<T: ?Sized + Lift<'tcx>>(self, value: &T) -> Option<T::Lifted> {
1115 value.lift_to_tcx(self)
1118 /// Like lift, but only tries in the global tcx.
1119 pub fn lift_to_global<T: ?Sized + Lift<'gcx>>(self, value: &T) -> Option<T::Lifted> {
1120 value.lift_to_tcx(self.global_tcx())
1123 /// Returns true if self is the same as self.global_tcx().
1124 fn is_global(self) -> bool {
1125 let local = self.interners as *const _;
1126 let global = &self.global_interners as *const _;
1127 local as usize == global as usize
1130 /// Create a type context and call the closure with a `TyCtxt` reference
1131 /// to the context. The closure enforces that the type context and any interned
1132 /// value (types, substs, etc.) can only be used while `ty::tls` has a valid
1133 /// reference to the context, to allow formatting values that need it.
1134 pub fn create_and_enter<F, R>(s: &'tcx Session,
1135 cstore: &'tcx dyn CrateStore,
1136 local_providers: ty::maps::Providers<'tcx>,
1137 extern_providers: ty::maps::Providers<'tcx>,
1138 arenas: &'tcx AllArenas<'tcx>,
1139 resolutions: ty::Resolutions,
1140 hir: hir_map::Map<'tcx>,
1141 on_disk_query_result_cache: maps::OnDiskCache<'tcx>,
1143 tx: mpsc::Sender<Box<dyn Any + Send>>,
1144 output_filenames: &OutputFilenames,
1146 where F: for<'b> FnOnce(TyCtxt<'b, 'tcx, 'tcx>) -> R
1148 let data_layout = TargetDataLayout::parse(s);
1149 let interners = CtxtInterners::new(&arenas.interner);
1150 let common_types = CommonTypes::new(&interners);
1151 let dep_graph = hir.dep_graph.clone();
1152 let max_cnum = cstore.crates_untracked().iter().map(|c| c.as_usize()).max().unwrap_or(0);
1153 let mut providers = IndexVec::from_elem_n(extern_providers, max_cnum + 1);
1154 providers[LOCAL_CRATE] = local_providers;
1156 let def_path_hash_to_def_id = if s.opts.build_dep_graph() {
1157 let upstream_def_path_tables: Vec<(CrateNum, Lrc<_>)> = cstore
1160 .map(|&cnum| (cnum, cstore.def_path_table(cnum)))
1163 let def_path_tables = || {
1164 upstream_def_path_tables
1166 .map(|&(cnum, ref rc)| (cnum, &**rc))
1167 .chain(iter::once((LOCAL_CRATE, hir.definitions().def_path_table())))
1170 // Precompute the capacity of the hashmap so we don't have to
1171 // re-allocate when populating it.
1172 let capacity = def_path_tables().map(|(_, t)| t.size()).sum::<usize>();
1174 let mut map: FxHashMap<_, _> = FxHashMap::with_capacity_and_hasher(
1176 ::std::default::Default::default()
1179 for (cnum, def_path_table) in def_path_tables() {
1180 def_path_table.add_def_path_hashes_to(cnum, &mut map);
1188 let mut trait_map = FxHashMap();
1189 for (k, v) in resolutions.trait_map {
1190 let hir_id = hir.node_to_hir_id(k);
1191 let map = trait_map.entry(hir_id.owner)
1192 .or_insert_with(|| Lrc::new(FxHashMap()));
1193 Lrc::get_mut(map).unwrap()
1194 .insert(hir_id.local_id,
1195 Lrc::new(StableVec::new(v)));
1198 tls::enter_global(GlobalCtxt {
1201 global_arenas: &arenas.global,
1202 global_interners: interners,
1203 dep_graph: dep_graph.clone(),
1204 on_disk_query_result_cache,
1205 types: common_types,
1207 export_map: resolutions.export_map.into_iter().map(|(k, v)| {
1210 freevars: resolutions.freevars.into_iter().map(|(k, v)| {
1211 (hir.local_def_id(k), Lrc::new(v))
1213 maybe_unused_trait_imports:
1214 resolutions.maybe_unused_trait_imports
1216 .map(|id| hir.local_def_id(id))
1218 maybe_unused_extern_crates:
1219 resolutions.maybe_unused_extern_crates
1221 .map(|(id, sp)| (hir.local_def_id(id), sp))
1224 def_path_hash_to_def_id,
1225 maps: maps::Maps::new(providers),
1226 rcache: RefCell::new(FxHashMap()),
1227 selection_cache: traits::SelectionCache::new(),
1228 evaluation_cache: traits::EvaluationCache::new(),
1229 crate_name: Symbol::intern(crate_name),
1231 layout_interner: RefCell::new(FxHashSet()),
1232 layout_depth: Cell::new(0),
1233 derive_macros: RefCell::new(NodeMap()),
1234 stability_interner: RefCell::new(FxHashSet()),
1235 interpret_interner: Default::default(),
1236 all_traits: RefCell::new(None),
1237 tx_to_llvm_workers: tx,
1238 output_filenames: Arc::new(output_filenames.clone()),
1242 pub fn consider_optimizing<T: Fn() -> String>(&self, msg: T) -> bool {
1243 let cname = self.crate_name(LOCAL_CRATE).as_str();
1244 self.sess.consider_optimizing(&cname, msg)
1247 pub fn lang_items(self) -> Lrc<middle::lang_items::LanguageItems> {
1248 self.get_lang_items(LOCAL_CRATE)
1251 pub fn stability(self) -> Lrc<stability::Index<'tcx>> {
1252 self.stability_index(LOCAL_CRATE)
1255 pub fn crates(self) -> Lrc<Vec<CrateNum>> {
1256 self.all_crate_nums(LOCAL_CRATE)
1259 pub fn features(self) -> Lrc<feature_gate::Features> {
1260 self.features_query(LOCAL_CRATE)
1263 pub fn def_key(self, id: DefId) -> hir_map::DefKey {
1265 self.hir.def_key(id)
1267 self.cstore.def_key(id)
1271 /// Convert a `DefId` into its fully expanded `DefPath` (every
1272 /// `DefId` is really just an interned def-path).
1274 /// Note that if `id` is not local to this crate, the result will
1275 /// be a non-local `DefPath`.
1276 pub fn def_path(self, id: DefId) -> hir_map::DefPath {
1278 self.hir.def_path(id)
1280 self.cstore.def_path(id)
1285 pub fn def_path_hash(self, def_id: DefId) -> hir_map::DefPathHash {
1286 if def_id.is_local() {
1287 self.hir.definitions().def_path_hash(def_id.index)
1289 self.cstore.def_path_hash(def_id)
1293 pub fn def_path_debug_str(self, def_id: DefId) -> String {
1294 // We are explicitly not going through queries here in order to get
1295 // crate name and disambiguator since this code is called from debug!()
1296 // statements within the query system and we'd run into endless
1297 // recursion otherwise.
1298 let (crate_name, crate_disambiguator) = if def_id.is_local() {
1299 (self.crate_name.clone(),
1300 self.sess.local_crate_disambiguator())
1302 (self.cstore.crate_name_untracked(def_id.krate),
1303 self.cstore.crate_disambiguator_untracked(def_id.krate))
1308 // Don't print the whole crate disambiguator. That's just
1309 // annoying in debug output.
1310 &(crate_disambiguator.to_fingerprint().to_hex())[..4],
1311 self.def_path(def_id).to_string_no_crate())
1314 pub fn metadata_encoding_version(self) -> Vec<u8> {
1315 self.cstore.metadata_encoding_version().to_vec()
1318 // Note that this is *untracked* and should only be used within the query
1319 // system if the result is otherwise tracked through queries
1320 pub fn crate_data_as_rc_any(self, cnum: CrateNum) -> Lrc<dyn Any> {
1321 self.cstore.crate_data_as_rc_any(cnum)
1324 pub fn create_stable_hashing_context(self) -> StableHashingContext<'gcx> {
1325 let krate = self.dep_graph.with_ignore(|| self.gcx.hir.krate());
1327 StableHashingContext::new(self.sess,
1329 self.hir.definitions(),
1333 // This method makes sure that we have a DepNode and a Fingerprint for
1334 // every upstream crate. It needs to be called once right after the tcx is
1336 // With full-fledged red/green, the method will probably become unnecessary
1337 // as this will be done on-demand.
1338 pub fn allocate_metadata_dep_nodes(self) {
1339 // We cannot use the query versions of crates() and crate_hash(), since
1340 // those would need the DepNodes that we are allocating here.
1341 for cnum in self.cstore.crates_untracked() {
1342 let dep_node = DepNode::new(self, DepConstructor::CrateMetadata(cnum));
1343 let crate_hash = self.cstore.crate_hash_untracked(cnum);
1344 self.dep_graph.with_task(dep_node,
1347 |_, x| x // No transformation needed
1352 // This method exercises the `in_scope_traits_map` query for all possible
1353 // values so that we have their fingerprints available in the DepGraph.
1354 // This is only required as long as we still use the old dependency tracking
1355 // which needs to have the fingerprints of all input nodes beforehand.
1356 pub fn precompute_in_scope_traits_hashes(self) {
1357 for &def_index in self.trait_map.keys() {
1358 self.in_scope_traits_map(def_index);
1362 pub fn serialize_query_result_cache<E>(self,
1364 -> Result<(), E::Error>
1365 where E: ty::codec::TyEncoder
1367 self.on_disk_query_result_cache.serialize(self.global_tcx(), encoder)
1370 /// If true, we should use NLL-style region checking instead of
1372 pub fn nll(self) -> bool {
1373 self.features().nll || self.sess.opts.debugging_opts.nll
1376 /// If true, we should use the MIR-based borrowck (we may *also* use
1377 /// the AST-based borrowck).
1378 pub fn use_mir(self) -> bool {
1379 self.borrowck_mode().use_mir()
1382 /// If true, we should enable two-phase borrows checks. This is
1383 /// done with either `-Ztwo-phase-borrows` or with
1384 /// `#![feature(nll)]`.
1385 pub fn two_phase_borrows(self) -> bool {
1386 self.features().nll || self.sess.opts.debugging_opts.two_phase_borrows
1389 /// What mode(s) of borrowck should we run? AST? MIR? both?
1390 /// (Also considers the `#![feature(nll)]` setting.)
1391 pub fn borrowck_mode(&self) -> BorrowckMode {
1392 match self.sess.opts.borrowck_mode {
1393 mode @ BorrowckMode::Mir |
1394 mode @ BorrowckMode::Compare => mode,
1396 mode @ BorrowckMode::Ast => {
1407 /// Should we emit EndRegion MIR statements? These are consumed by
1408 /// MIR borrowck, but not when NLL is used. They are also consumed
1409 /// by the validation stuff.
1410 pub fn emit_end_regions(self) -> bool {
1411 // FIXME(#46875) -- we should not emit end regions when NLL is enabled,
1412 // but for now we can't stop doing so because it causes false positives
1413 self.sess.opts.debugging_opts.emit_end_regions ||
1414 self.sess.opts.debugging_opts.mir_emit_validate > 0 ||
1419 impl<'a, 'tcx> TyCtxt<'a, 'tcx, 'tcx> {
1420 pub fn encode_metadata(self, link_meta: &LinkMeta)
1423 self.cstore.encode_metadata(self, link_meta)
1427 impl<'gcx: 'tcx, 'tcx> GlobalCtxt<'gcx> {
1428 /// Call the closure with a local `TyCtxt` using the given arena.
1429 pub fn enter_local<F, R>(&self, arena: &'tcx DroplessArena, f: F) -> R
1430 where F: for<'a> FnOnce(TyCtxt<'a, 'gcx, 'tcx>) -> R
1432 let interners = CtxtInterners::new(arena);
1433 tls::enter(self, &interners, f)
1437 /// A trait implemented for all X<'a> types which can be safely and
1438 /// efficiently converted to X<'tcx> as long as they are part of the
1439 /// provided TyCtxt<'tcx>.
1440 /// This can be done, for example, for Ty<'tcx> or &'tcx Substs<'tcx>
1441 /// by looking them up in their respective interners.
1443 /// However, this is still not the best implementation as it does
1444 /// need to compare the components, even for interned values.
1445 /// It would be more efficient if TypedArena provided a way to
1446 /// determine whether the address is in the allocated range.
1448 /// None is returned if the value or one of the components is not part
1449 /// of the provided context.
1450 /// For Ty, None can be returned if either the type interner doesn't
1451 /// contain the TypeVariants key or if the address of the interned
1452 /// pointer differs. The latter case is possible if a primitive type,
1453 /// e.g. `()` or `u8`, was interned in a different context.
1454 pub trait Lift<'tcx> {
1456 fn lift_to_tcx<'a, 'gcx>(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Option<Self::Lifted>;
1459 impl<'a, 'tcx> Lift<'tcx> for Ty<'a> {
1460 type Lifted = Ty<'tcx>;
1461 fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>) -> Option<Ty<'tcx>> {
1462 if tcx.interners.arena.in_arena(*self as *const _) {
1463 return Some(unsafe { mem::transmute(*self) });
1465 // Also try in the global tcx if we're not that.
1466 if !tcx.is_global() {
1467 self.lift_to_tcx(tcx.global_tcx())
1474 impl<'a, 'tcx> Lift<'tcx> for Region<'a> {
1475 type Lifted = Region<'tcx>;
1476 fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>) -> Option<Region<'tcx>> {
1477 if tcx.interners.arena.in_arena(*self as *const _) {
1478 return Some(unsafe { mem::transmute(*self) });
1480 // Also try in the global tcx if we're not that.
1481 if !tcx.is_global() {
1482 self.lift_to_tcx(tcx.global_tcx())
1489 impl<'a, 'tcx> Lift<'tcx> for &'a Const<'a> {
1490 type Lifted = &'tcx Const<'tcx>;
1491 fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>) -> Option<&'tcx Const<'tcx>> {
1492 if tcx.interners.arena.in_arena(*self as *const _) {
1493 return Some(unsafe { mem::transmute(*self) });
1495 // Also try in the global tcx if we're not that.
1496 if !tcx.is_global() {
1497 self.lift_to_tcx(tcx.global_tcx())
1504 impl<'a, 'tcx> Lift<'tcx> for &'a Substs<'a> {
1505 type Lifted = &'tcx Substs<'tcx>;
1506 fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>) -> Option<&'tcx Substs<'tcx>> {
1507 if self.len() == 0 {
1508 return Some(Slice::empty());
1510 if tcx.interners.arena.in_arena(&self[..] as *const _) {
1511 return Some(unsafe { mem::transmute(*self) });
1513 // Also try in the global tcx if we're not that.
1514 if !tcx.is_global() {
1515 self.lift_to_tcx(tcx.global_tcx())
1522 impl<'a, 'tcx> Lift<'tcx> for &'a Slice<Ty<'a>> {
1523 type Lifted = &'tcx Slice<Ty<'tcx>>;
1524 fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>)
1525 -> Option<&'tcx Slice<Ty<'tcx>>> {
1526 if self.len() == 0 {
1527 return Some(Slice::empty());
1529 if tcx.interners.arena.in_arena(*self as *const _) {
1530 return Some(unsafe { mem::transmute(*self) });
1532 // Also try in the global tcx if we're not that.
1533 if !tcx.is_global() {
1534 self.lift_to_tcx(tcx.global_tcx())
1541 impl<'a, 'tcx> Lift<'tcx> for &'a Slice<ExistentialPredicate<'a>> {
1542 type Lifted = &'tcx Slice<ExistentialPredicate<'tcx>>;
1543 fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>)
1544 -> Option<&'tcx Slice<ExistentialPredicate<'tcx>>> {
1545 if self.is_empty() {
1546 return Some(Slice::empty());
1548 if tcx.interners.arena.in_arena(*self as *const _) {
1549 return Some(unsafe { mem::transmute(*self) });
1551 // Also try in the global tcx if we're not that.
1552 if !tcx.is_global() {
1553 self.lift_to_tcx(tcx.global_tcx())
1560 impl<'a, 'tcx> Lift<'tcx> for &'a Slice<Predicate<'a>> {
1561 type Lifted = &'tcx Slice<Predicate<'tcx>>;
1562 fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>)
1563 -> Option<&'tcx Slice<Predicate<'tcx>>> {
1564 if self.is_empty() {
1565 return Some(Slice::empty());
1567 if tcx.interners.arena.in_arena(*self as *const _) {
1568 return Some(unsafe { mem::transmute(*self) });
1570 // Also try in the global tcx if we're not that.
1571 if !tcx.is_global() {
1572 self.lift_to_tcx(tcx.global_tcx())
1580 use super::{CtxtInterners, GlobalCtxt, TyCtxt};
1582 use std::cell::Cell;
1586 /// Marker types used for the scoped TLS slot.
1587 /// The type context cannot be used directly because the scoped TLS
1588 /// in libstd doesn't allow types generic over lifetimes.
1589 enum ThreadLocalGlobalCtxt {}
1590 enum ThreadLocalInterners {}
1593 static TLS_TCX: Cell<Option<(*const ThreadLocalGlobalCtxt,
1594 *const ThreadLocalInterners)>> = Cell::new(None)
1597 fn span_debug(span: syntax_pos::Span, f: &mut fmt::Formatter) -> fmt::Result {
1599 write!(f, "{}", tcx.sess.codemap().span_to_string(span))
1603 pub fn enter_global<'gcx, F, R>(gcx: GlobalCtxt<'gcx>, f: F) -> R
1604 where F: for<'a> FnOnce(TyCtxt<'a, 'gcx, 'gcx>) -> R
1606 syntax_pos::SPAN_DEBUG.with(|span_dbg| {
1607 let original_span_debug = span_dbg.get();
1608 span_dbg.set(span_debug);
1609 let result = enter(&gcx, &gcx.global_interners, f);
1610 span_dbg.set(original_span_debug);
1615 pub fn enter<'a, 'gcx: 'tcx, 'tcx, F, R>(gcx: &'a GlobalCtxt<'gcx>,
1616 interners: &'a CtxtInterners<'tcx>,
1618 where F: FnOnce(TyCtxt<'a, 'gcx, 'tcx>) -> R
1620 let gcx_ptr = gcx as *const _ as *const ThreadLocalGlobalCtxt;
1621 let interners_ptr = interners as *const _ as *const ThreadLocalInterners;
1622 TLS_TCX.with(|tls| {
1623 let prev = tls.get();
1624 tls.set(Some((gcx_ptr, interners_ptr)));
1625 let ret = f(TyCtxt {
1634 pub fn with<F, R>(f: F) -> R
1635 where F: for<'a, 'gcx, 'tcx> FnOnce(TyCtxt<'a, 'gcx, 'tcx>) -> R
1637 TLS_TCX.with(|tcx| {
1638 let (gcx, interners) = tcx.get().unwrap();
1639 let gcx = unsafe { &*(gcx as *const GlobalCtxt) };
1640 let interners = unsafe { &*(interners as *const CtxtInterners) };
1648 pub fn with_opt<F, R>(f: F) -> R
1649 where F: for<'a, 'gcx, 'tcx> FnOnce(Option<TyCtxt<'a, 'gcx, 'tcx>>) -> R
1651 if TLS_TCX.with(|tcx| tcx.get().is_some()) {
1652 with(|v| f(Some(v)))
1659 macro_rules! sty_debug_print {
1660 ($ctxt: expr, $($variant: ident),*) => {{
1661 // curious inner module to allow variant names to be used as
1663 #[allow(non_snake_case)]
1665 use ty::{self, TyCtxt};
1666 use ty::context::Interned;
1668 #[derive(Copy, Clone)]
1671 region_infer: usize,
1676 pub fn go(tcx: TyCtxt) {
1677 let mut total = DebugStat {
1679 region_infer: 0, ty_infer: 0, both_infer: 0,
1681 $(let mut $variant = total;)*
1684 for &Interned(t) in tcx.interners.type_.borrow().iter() {
1685 let variant = match t.sty {
1686 ty::TyBool | ty::TyChar | ty::TyInt(..) | ty::TyUint(..) |
1687 ty::TyFloat(..) | ty::TyStr | ty::TyNever => continue,
1688 ty::TyError => /* unimportant */ continue,
1689 $(ty::$variant(..) => &mut $variant,)*
1691 let region = t.flags.intersects(ty::TypeFlags::HAS_RE_INFER);
1692 let ty = t.flags.intersects(ty::TypeFlags::HAS_TY_INFER);
1696 if region { total.region_infer += 1; variant.region_infer += 1 }
1697 if ty { total.ty_infer += 1; variant.ty_infer += 1 }
1698 if region && ty { total.both_infer += 1; variant.both_infer += 1 }
1700 println!("Ty interner total ty region both");
1701 $(println!(" {:18}: {uses:6} {usespc:4.1}%, \
1702 {ty:4.1}% {region:5.1}% {both:4.1}%",
1703 stringify!($variant),
1704 uses = $variant.total,
1705 usespc = $variant.total as f64 * 100.0 / total.total as f64,
1706 ty = $variant.ty_infer as f64 * 100.0 / total.total as f64,
1707 region = $variant.region_infer as f64 * 100.0 / total.total as f64,
1708 both = $variant.both_infer as f64 * 100.0 / total.total as f64);
1710 println!(" total {uses:6} \
1711 {ty:4.1}% {region:5.1}% {both:4.1}%",
1713 ty = total.ty_infer as f64 * 100.0 / total.total as f64,
1714 region = total.region_infer as f64 * 100.0 / total.total as f64,
1715 both = total.both_infer as f64 * 100.0 / total.total as f64)
1723 impl<'a, 'tcx> TyCtxt<'a, 'tcx, 'tcx> {
1724 pub fn print_debug_stats(self) {
1727 TyAdt, TyArray, TySlice, TyRawPtr, TyRef, TyFnDef, TyFnPtr,
1728 TyGenerator, TyGeneratorWitness, TyDynamic, TyClosure, TyTuple,
1729 TyParam, TyInfer, TyProjection, TyAnon, TyForeign);
1731 println!("Substs interner: #{}", self.interners.substs.borrow().len());
1732 println!("Region interner: #{}", self.interners.region.borrow().len());
1733 println!("Stability interner: #{}", self.stability_interner.borrow().len());
1734 println!("Interpret interner: #{}", self.interpret_interner.borrow().allocs.len());
1735 println!("Layout interner: #{}", self.layout_interner.borrow().len());
1740 /// An entry in an interner.
1741 struct Interned<'tcx, T: 'tcx+?Sized>(&'tcx T);
1743 // NB: An Interned<Ty> compares and hashes as a sty.
1744 impl<'tcx> PartialEq for Interned<'tcx, TyS<'tcx>> {
1745 fn eq(&self, other: &Interned<'tcx, TyS<'tcx>>) -> bool {
1746 self.0.sty == other.0.sty
1750 impl<'tcx> Eq for Interned<'tcx, TyS<'tcx>> {}
1752 impl<'tcx> Hash for Interned<'tcx, TyS<'tcx>> {
1753 fn hash<H: Hasher>(&self, s: &mut H) {
1758 impl<'tcx: 'lcx, 'lcx> Borrow<TypeVariants<'lcx>> for Interned<'tcx, TyS<'tcx>> {
1759 fn borrow<'a>(&'a self) -> &'a TypeVariants<'lcx> {
1764 // NB: An Interned<Slice<T>> compares and hashes as its elements.
1765 impl<'tcx, T: PartialEq> PartialEq for Interned<'tcx, Slice<T>> {
1766 fn eq(&self, other: &Interned<'tcx, Slice<T>>) -> bool {
1767 self.0[..] == other.0[..]
1771 impl<'tcx, T: Eq> Eq for Interned<'tcx, Slice<T>> {}
1773 impl<'tcx, T: Hash> Hash for Interned<'tcx, Slice<T>> {
1774 fn hash<H: Hasher>(&self, s: &mut H) {
1779 impl<'tcx: 'lcx, 'lcx> Borrow<[Ty<'lcx>]> for Interned<'tcx, Slice<Ty<'tcx>>> {
1780 fn borrow<'a>(&'a self) -> &'a [Ty<'lcx>] {
1785 impl<'tcx: 'lcx, 'lcx> Borrow<[Kind<'lcx>]> for Interned<'tcx, Substs<'tcx>> {
1786 fn borrow<'a>(&'a self) -> &'a [Kind<'lcx>] {
1791 impl<'tcx> Borrow<RegionKind> for Interned<'tcx, RegionKind> {
1792 fn borrow<'a>(&'a self) -> &'a RegionKind {
1797 impl<'tcx: 'lcx, 'lcx> Borrow<[ExistentialPredicate<'lcx>]>
1798 for Interned<'tcx, Slice<ExistentialPredicate<'tcx>>> {
1799 fn borrow<'a>(&'a self) -> &'a [ExistentialPredicate<'lcx>] {
1804 impl<'tcx: 'lcx, 'lcx> Borrow<[Predicate<'lcx>]>
1805 for Interned<'tcx, Slice<Predicate<'tcx>>> {
1806 fn borrow<'a>(&'a self) -> &'a [Predicate<'lcx>] {
1811 impl<'tcx: 'lcx, 'lcx> Borrow<Const<'lcx>> for Interned<'tcx, Const<'tcx>> {
1812 fn borrow<'a>(&'a self) -> &'a Const<'lcx> {
1817 macro_rules! intern_method {
1818 ($lt_tcx:tt, $name:ident: $method:ident($alloc:ty,
1819 $alloc_method:ident,
1822 $needs_infer:expr) -> $ty:ty) => {
1823 impl<'a, 'gcx, $lt_tcx> TyCtxt<'a, 'gcx, $lt_tcx> {
1824 pub fn $method(self, v: $alloc) -> &$lt_tcx $ty {
1826 let key = ($alloc_to_key)(&v);
1827 if let Some(i) = self.interners.$name.borrow().get(key) {
1830 if !self.is_global() {
1831 if let Some(i) = self.global_interners.$name.borrow().get(key) {
1837 // HACK(eddyb) Depend on flags being accurate to
1838 // determine that all contents are in the global tcx.
1839 // See comments on Lift for why we can't use that.
1840 if !($needs_infer)(&v) {
1841 if !self.is_global() {
1845 let i = ($alloc_to_ret)(self.global_interners.arena.$alloc_method(v));
1846 self.global_interners.$name.borrow_mut().insert(Interned(i));
1850 // Make sure we don't end up with inference
1851 // types/regions in the global tcx.
1852 if self.is_global() {
1853 bug!("Attempted to intern `{:?}` which contains \
1854 inference types/regions in the global type context",
1859 let i = ($alloc_to_ret)(self.interners.arena.$alloc_method(v));
1860 self.interners.$name.borrow_mut().insert(Interned(i));
1867 macro_rules! direct_interners {
1868 ($lt_tcx:tt, $($name:ident: $method:ident($needs_infer:expr) -> $ty:ty),+) => {
1869 $(impl<$lt_tcx> PartialEq for Interned<$lt_tcx, $ty> {
1870 fn eq(&self, other: &Self) -> bool {
1875 impl<$lt_tcx> Eq for Interned<$lt_tcx, $ty> {}
1877 impl<$lt_tcx> Hash for Interned<$lt_tcx, $ty> {
1878 fn hash<H: Hasher>(&self, s: &mut H) {
1883 intern_method!($lt_tcx, $name: $method($ty, alloc, |x| x, |x| x, $needs_infer) -> $ty);)+
1887 pub fn keep_local<'tcx, T: ty::TypeFoldable<'tcx>>(x: &T) -> bool {
1888 x.has_type_flags(ty::TypeFlags::KEEP_IN_LOCAL_TCX)
1891 direct_interners!('tcx,
1892 region: mk_region(|r| {
1894 &ty::ReVar(_) | &ty::ReSkolemized(..) => true,
1898 const_: mk_const(|c: &Const| keep_local(&c.ty) || keep_local(&c.val)) -> Const<'tcx>
1901 macro_rules! slice_interners {
1902 ($($field:ident: $method:ident($ty:ident)),+) => (
1903 $(intern_method!('tcx, $field: $method(&[$ty<'tcx>], alloc_slice, Deref::deref,
1904 |xs: &[$ty]| -> &Slice<$ty> {
1905 unsafe { mem::transmute(xs) }
1906 }, |xs: &[$ty]| xs.iter().any(keep_local)) -> Slice<$ty<'tcx>>);)+
1911 existential_predicates: _intern_existential_predicates(ExistentialPredicate),
1912 predicates: _intern_predicates(Predicate),
1913 type_list: _intern_type_list(Ty),
1914 substs: _intern_substs(Kind)
1917 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
1918 /// Given a `fn` type, returns an equivalent `unsafe fn` type;
1919 /// that is, a `fn` type that is equivalent in every way for being
1921 pub fn safe_to_unsafe_fn_ty(self, sig: PolyFnSig<'tcx>) -> Ty<'tcx> {
1922 assert_eq!(sig.unsafety(), hir::Unsafety::Normal);
1923 self.mk_fn_ptr(sig.map_bound(|sig| ty::FnSig {
1924 unsafety: hir::Unsafety::Unsafe,
1929 /// Given a closure signature `sig`, returns an equivalent `fn`
1930 /// type with the same signature. Detuples and so forth -- so
1931 /// e.g. if we have a sig with `Fn<(u32, i32)>` then you would get
1932 /// a `fn(u32, i32)`.
1933 pub fn coerce_closure_fn_ty(self, sig: PolyFnSig<'tcx>) -> Ty<'tcx> {
1934 let converted_sig = sig.map_bound(|s| {
1935 let params_iter = match s.inputs()[0].sty {
1936 ty::TyTuple(params, _) => {
1937 params.into_iter().cloned()
1945 hir::Unsafety::Normal,
1950 self.mk_fn_ptr(converted_sig)
1953 // Interns a type/name combination, stores the resulting box in cx.interners,
1954 // and returns the box as cast to an unsafe ptr (see comments for Ty above).
1955 pub fn mk_ty(self, st: TypeVariants<'tcx>) -> Ty<'tcx> {
1956 let global_interners = if !self.is_global() {
1957 Some(&self.global_interners)
1961 self.interners.intern_ty(st, global_interners)
1964 pub fn mk_mach_int(self, tm: ast::IntTy) -> Ty<'tcx> {
1966 ast::IntTy::Isize => self.types.isize,
1967 ast::IntTy::I8 => self.types.i8,
1968 ast::IntTy::I16 => self.types.i16,
1969 ast::IntTy::I32 => self.types.i32,
1970 ast::IntTy::I64 => self.types.i64,
1971 ast::IntTy::I128 => self.types.i128,
1975 pub fn mk_mach_uint(self, tm: ast::UintTy) -> Ty<'tcx> {
1977 ast::UintTy::Usize => self.types.usize,
1978 ast::UintTy::U8 => self.types.u8,
1979 ast::UintTy::U16 => self.types.u16,
1980 ast::UintTy::U32 => self.types.u32,
1981 ast::UintTy::U64 => self.types.u64,
1982 ast::UintTy::U128 => self.types.u128,
1986 pub fn mk_mach_float(self, tm: ast::FloatTy) -> Ty<'tcx> {
1988 ast::FloatTy::F32 => self.types.f32,
1989 ast::FloatTy::F64 => self.types.f64,
1993 pub fn mk_str(self) -> Ty<'tcx> {
1997 pub fn mk_static_str(self) -> Ty<'tcx> {
1998 self.mk_imm_ref(self.types.re_static, self.mk_str())
2001 pub fn mk_adt(self, def: &'tcx AdtDef, substs: &'tcx Substs<'tcx>) -> Ty<'tcx> {
2002 // take a copy of substs so that we own the vectors inside
2003 self.mk_ty(TyAdt(def, substs))
2006 pub fn mk_foreign(self, def_id: DefId) -> Ty<'tcx> {
2007 self.mk_ty(TyForeign(def_id))
2010 pub fn mk_box(self, ty: Ty<'tcx>) -> Ty<'tcx> {
2011 let def_id = self.require_lang_item(lang_items::OwnedBoxLangItem);
2012 let adt_def = self.adt_def(def_id);
2013 let substs = self.mk_substs(iter::once(Kind::from(ty)));
2014 self.mk_ty(TyAdt(adt_def, substs))
2017 pub fn mk_ptr(self, tm: TypeAndMut<'tcx>) -> Ty<'tcx> {
2018 self.mk_ty(TyRawPtr(tm))
2021 pub fn mk_ref(self, r: Region<'tcx>, tm: TypeAndMut<'tcx>) -> Ty<'tcx> {
2022 self.mk_ty(TyRef(r, tm))
2025 pub fn mk_mut_ref(self, r: Region<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
2026 self.mk_ref(r, TypeAndMut {ty: ty, mutbl: hir::MutMutable})
2029 pub fn mk_imm_ref(self, r: Region<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
2030 self.mk_ref(r, TypeAndMut {ty: ty, mutbl: hir::MutImmutable})
2033 pub fn mk_mut_ptr(self, ty: Ty<'tcx>) -> Ty<'tcx> {
2034 self.mk_ptr(TypeAndMut {ty: ty, mutbl: hir::MutMutable})
2037 pub fn mk_imm_ptr(self, ty: Ty<'tcx>) -> Ty<'tcx> {
2038 self.mk_ptr(TypeAndMut {ty: ty, mutbl: hir::MutImmutable})
2041 pub fn mk_nil_ptr(self) -> Ty<'tcx> {
2042 self.mk_imm_ptr(self.mk_nil())
2045 pub fn mk_array(self, ty: Ty<'tcx>, n: u64) -> Ty<'tcx> {
2046 let n = ConstUsize::new(n, self.sess.target.usize_ty).unwrap();
2047 self.mk_array_const_usize(ty, n)
2050 pub fn mk_array_const_usize(self, ty: Ty<'tcx>, n: ConstUsize) -> Ty<'tcx> {
2051 self.mk_ty(TyArray(ty, self.mk_const(ty::Const {
2052 val: ConstVal::Integral(ConstInt::Usize(n)),
2053 ty: self.types.usize
2057 pub fn mk_slice(self, ty: Ty<'tcx>) -> Ty<'tcx> {
2058 self.mk_ty(TySlice(ty))
2061 pub fn intern_tup(self, ts: &[Ty<'tcx>], defaulted: bool) -> Ty<'tcx> {
2062 self.mk_ty(TyTuple(self.intern_type_list(ts), defaulted))
2065 pub fn mk_tup<I: InternAs<[Ty<'tcx>], Ty<'tcx>>>(self, iter: I,
2066 defaulted: bool) -> I::Output {
2067 iter.intern_with(|ts| self.mk_ty(TyTuple(self.intern_type_list(ts), defaulted)))
2070 pub fn mk_nil(self) -> Ty<'tcx> {
2071 self.intern_tup(&[], false)
2074 pub fn mk_diverging_default(self) -> Ty<'tcx> {
2075 if self.features().never_type {
2078 self.intern_tup(&[], true)
2082 pub fn mk_bool(self) -> Ty<'tcx> {
2086 pub fn mk_fn_def(self, def_id: DefId,
2087 substs: &'tcx Substs<'tcx>) -> Ty<'tcx> {
2088 self.mk_ty(TyFnDef(def_id, substs))
2091 pub fn mk_fn_ptr(self, fty: PolyFnSig<'tcx>) -> Ty<'tcx> {
2092 self.mk_ty(TyFnPtr(fty))
2097 obj: ty::Binder<&'tcx Slice<ExistentialPredicate<'tcx>>>,
2098 reg: ty::Region<'tcx>
2100 self.mk_ty(TyDynamic(obj, reg))
2103 pub fn mk_projection(self,
2105 substs: &'tcx Substs<'tcx>)
2107 self.mk_ty(TyProjection(ProjectionTy {
2113 pub fn mk_closure(self,
2115 substs: ClosureSubsts<'tcx>)
2117 self.mk_closure_from_closure_substs(closure_id, substs)
2120 pub fn mk_closure_from_closure_substs(self,
2122 closure_substs: ClosureSubsts<'tcx>)
2124 self.mk_ty(TyClosure(closure_id, closure_substs))
2127 pub fn mk_generator(self,
2129 closure_substs: ClosureSubsts<'tcx>,
2130 interior: GeneratorInterior<'tcx>)
2132 self.mk_ty(TyGenerator(id, closure_substs, interior))
2135 pub fn mk_generator_witness(self, types: ty::Binder<&'tcx Slice<Ty<'tcx>>>) -> Ty<'tcx> {
2136 self.mk_ty(TyGeneratorWitness(types))
2139 pub fn mk_var(self, v: TyVid) -> Ty<'tcx> {
2140 self.mk_infer(TyVar(v))
2143 pub fn mk_int_var(self, v: IntVid) -> Ty<'tcx> {
2144 self.mk_infer(IntVar(v))
2147 pub fn mk_float_var(self, v: FloatVid) -> Ty<'tcx> {
2148 self.mk_infer(FloatVar(v))
2151 pub fn mk_infer(self, it: InferTy) -> Ty<'tcx> {
2152 self.mk_ty(TyInfer(it))
2155 pub fn mk_param(self,
2157 name: Name) -> Ty<'tcx> {
2158 self.mk_ty(TyParam(ParamTy { idx: index, name: name }))
2161 pub fn mk_self_type(self) -> Ty<'tcx> {
2162 self.mk_param(0, keywords::SelfType.name())
2165 pub fn mk_param_from_def(self, def: &ty::TypeParameterDef) -> Ty<'tcx> {
2166 self.mk_param(def.index, def.name)
2169 pub fn mk_anon(self, def_id: DefId, substs: &'tcx Substs<'tcx>) -> Ty<'tcx> {
2170 self.mk_ty(TyAnon(def_id, substs))
2173 pub fn intern_existential_predicates(self, eps: &[ExistentialPredicate<'tcx>])
2174 -> &'tcx Slice<ExistentialPredicate<'tcx>> {
2175 assert!(!eps.is_empty());
2176 assert!(eps.windows(2).all(|w| w[0].cmp(self, &w[1]) != Ordering::Greater));
2177 self._intern_existential_predicates(eps)
2180 pub fn intern_predicates(self, preds: &[Predicate<'tcx>])
2181 -> &'tcx Slice<Predicate<'tcx>> {
2182 // FIXME consider asking the input slice to be sorted to avoid
2183 // re-interning permutations, in which case that would be asserted
2185 if preds.len() == 0 {
2186 // The macro-generated method below asserts we don't intern an empty slice.
2189 self._intern_predicates(preds)
2193 pub fn intern_type_list(self, ts: &[Ty<'tcx>]) -> &'tcx Slice<Ty<'tcx>> {
2197 self._intern_type_list(ts)
2201 pub fn intern_substs(self, ts: &[Kind<'tcx>]) -> &'tcx Slice<Kind<'tcx>> {
2205 self._intern_substs(ts)
2209 pub fn mk_fn_sig<I>(self,
2213 unsafety: hir::Unsafety,
2215 -> <I::Item as InternIteratorElement<Ty<'tcx>, ty::FnSig<'tcx>>>::Output
2217 I::Item: InternIteratorElement<Ty<'tcx>, ty::FnSig<'tcx>>
2219 inputs.chain(iter::once(output)).intern_with(|xs| ty::FnSig {
2220 inputs_and_output: self.intern_type_list(xs),
2221 variadic, unsafety, abi
2225 pub fn mk_existential_predicates<I: InternAs<[ExistentialPredicate<'tcx>],
2226 &'tcx Slice<ExistentialPredicate<'tcx>>>>(self, iter: I)
2228 iter.intern_with(|xs| self.intern_existential_predicates(xs))
2231 pub fn mk_predicates<I: InternAs<[Predicate<'tcx>],
2232 &'tcx Slice<Predicate<'tcx>>>>(self, iter: I)
2234 iter.intern_with(|xs| self.intern_predicates(xs))
2237 pub fn mk_type_list<I: InternAs<[Ty<'tcx>],
2238 &'tcx Slice<Ty<'tcx>>>>(self, iter: I) -> I::Output {
2239 iter.intern_with(|xs| self.intern_type_list(xs))
2242 pub fn mk_substs<I: InternAs<[Kind<'tcx>],
2243 &'tcx Slice<Kind<'tcx>>>>(self, iter: I) -> I::Output {
2244 iter.intern_with(|xs| self.intern_substs(xs))
2247 pub fn mk_substs_trait(self,
2250 -> &'tcx Substs<'tcx>
2252 self.mk_substs(iter::once(s).chain(t.into_iter().cloned()).map(Kind::from))
2255 pub fn lint_node<S: Into<MultiSpan>>(self,
2256 lint: &'static Lint,
2260 self.struct_span_lint_node(lint, id, span.into(), msg).emit()
2263 pub fn lint_node_note<S: Into<MultiSpan>>(self,
2264 lint: &'static Lint,
2269 let mut err = self.struct_span_lint_node(lint, id, span.into(), msg);
2274 pub fn lint_level_at_node(self, lint: &'static Lint, mut id: NodeId)
2275 -> (lint::Level, lint::LintSource)
2277 // Right now we insert a `with_ignore` node in the dep graph here to
2278 // ignore the fact that `lint_levels` below depends on the entire crate.
2279 // For now this'll prevent false positives of recompiling too much when
2280 // anything changes.
2282 // Once red/green incremental compilation lands we should be able to
2283 // remove this because while the crate changes often the lint level map
2284 // will change rarely.
2285 self.dep_graph.with_ignore(|| {
2286 let sets = self.lint_levels(LOCAL_CRATE);
2288 let hir_id = self.hir.definitions().node_to_hir_id(id);
2289 if let Some(pair) = sets.level_and_source(lint, hir_id, self.sess) {
2292 let next = self.hir.get_parent_node(id);
2294 bug!("lint traversal reached the root of the crate");
2301 pub fn struct_span_lint_node<S: Into<MultiSpan>>(self,
2302 lint: &'static Lint,
2306 -> DiagnosticBuilder<'tcx>
2308 let (level, src) = self.lint_level_at_node(lint, id);
2309 lint::struct_lint_level(self.sess, lint, level, src, Some(span.into()), msg)
2312 pub fn struct_lint_node(self, lint: &'static Lint, id: NodeId, msg: &str)
2313 -> DiagnosticBuilder<'tcx>
2315 let (level, src) = self.lint_level_at_node(lint, id);
2316 lint::struct_lint_level(self.sess, lint, level, src, None, msg)
2319 pub fn in_scope_traits(self, id: HirId) -> Option<Lrc<StableVec<TraitCandidate>>> {
2320 self.in_scope_traits_map(id.owner)
2321 .and_then(|map| map.get(&id.local_id).cloned())
2324 pub fn named_region(self, id: HirId) -> Option<resolve_lifetime::Region> {
2325 self.named_region_map(id.owner)
2326 .and_then(|map| map.get(&id.local_id).cloned())
2329 pub fn is_late_bound(self, id: HirId) -> bool {
2330 self.is_late_bound_map(id.owner)
2331 .map(|set| set.contains(&id.local_id))
2335 pub fn object_lifetime_defaults(self, id: HirId)
2336 -> Option<Lrc<Vec<ObjectLifetimeDefault>>>
2338 self.object_lifetime_defaults_map(id.owner)
2339 .and_then(|map| map.get(&id.local_id).cloned())
2343 pub trait InternAs<T: ?Sized, R> {
2345 fn intern_with<F>(self, f: F) -> Self::Output
2346 where F: FnOnce(&T) -> R;
2349 impl<I, T, R, E> InternAs<[T], R> for I
2350 where E: InternIteratorElement<T, R>,
2351 I: Iterator<Item=E> {
2352 type Output = E::Output;
2353 fn intern_with<F>(self, f: F) -> Self::Output
2354 where F: FnOnce(&[T]) -> R {
2355 E::intern_with(self, f)
2359 pub trait InternIteratorElement<T, R>: Sized {
2361 fn intern_with<I: Iterator<Item=Self>, F: FnOnce(&[T]) -> R>(iter: I, f: F) -> Self::Output;
2364 impl<T, R> InternIteratorElement<T, R> for T {
2366 fn intern_with<I: Iterator<Item=Self>, F: FnOnce(&[T]) -> R>(iter: I, f: F) -> Self::Output {
2367 f(&iter.collect::<AccumulateVec<[_; 8]>>())
2371 impl<'a, T, R> InternIteratorElement<T, R> for &'a T
2375 fn intern_with<I: Iterator<Item=Self>, F: FnOnce(&[T]) -> R>(iter: I, f: F) -> Self::Output {
2376 f(&iter.cloned().collect::<AccumulateVec<[_; 8]>>())
2380 impl<T, R, E> InternIteratorElement<T, R> for Result<T, E> {
2381 type Output = Result<R, E>;
2382 fn intern_with<I: Iterator<Item=Self>, F: FnOnce(&[T]) -> R>(iter: I, f: F) -> Self::Output {
2383 Ok(f(&iter.collect::<Result<AccumulateVec<[_; 8]>, _>>()?))
2387 pub fn provide(providers: &mut ty::maps::Providers) {
2388 // FIXME(#44234) - almost all of these queries have no sub-queries and
2389 // therefore no actual inputs, they're just reading tables calculated in
2390 // resolve! Does this work? Unsure! That's what the issue is about
2391 providers.in_scope_traits_map = |tcx, id| tcx.gcx.trait_map.get(&id).cloned();
2392 providers.module_exports = |tcx, id| tcx.gcx.export_map.get(&id).cloned();
2393 providers.crate_name = |tcx, id| {
2394 assert_eq!(id, LOCAL_CRATE);
2397 providers.get_lang_items = |tcx, id| {
2398 assert_eq!(id, LOCAL_CRATE);
2399 // FIXME(#42293) Right now we insert a `with_ignore` node in the dep
2400 // graph here to ignore the fact that `get_lang_items` below depends on
2401 // the entire crate. For now this'll prevent false positives of
2402 // recompiling too much when anything changes.
2404 // Once red/green incremental compilation lands we should be able to
2405 // remove this because while the crate changes often the lint level map
2406 // will change rarely.
2407 tcx.dep_graph.with_ignore(|| Lrc::new(middle::lang_items::collect(tcx)))
2409 providers.freevars = |tcx, id| tcx.gcx.freevars.get(&id).cloned();
2410 providers.maybe_unused_trait_import = |tcx, id| {
2411 tcx.maybe_unused_trait_imports.contains(&id)
2413 providers.maybe_unused_extern_crates = |tcx, cnum| {
2414 assert_eq!(cnum, LOCAL_CRATE);
2415 Lrc::new(tcx.maybe_unused_extern_crates.clone())
2418 providers.stability_index = |tcx, cnum| {
2419 assert_eq!(cnum, LOCAL_CRATE);
2420 Lrc::new(stability::Index::new(tcx))
2422 providers.lookup_stability = |tcx, id| {
2423 assert_eq!(id.krate, LOCAL_CRATE);
2424 let id = tcx.hir.definitions().def_index_to_hir_id(id.index);
2425 tcx.stability().local_stability(id)
2427 providers.lookup_deprecation_entry = |tcx, id| {
2428 assert_eq!(id.krate, LOCAL_CRATE);
2429 let id = tcx.hir.definitions().def_index_to_hir_id(id.index);
2430 tcx.stability().local_deprecation_entry(id)
2432 providers.extern_mod_stmt_cnum = |tcx, id| {
2433 let id = tcx.hir.as_local_node_id(id).unwrap();
2434 tcx.cstore.extern_mod_stmt_cnum_untracked(id)
2436 providers.all_crate_nums = |tcx, cnum| {
2437 assert_eq!(cnum, LOCAL_CRATE);
2438 Lrc::new(tcx.cstore.crates_untracked())
2440 providers.postorder_cnums = |tcx, cnum| {
2441 assert_eq!(cnum, LOCAL_CRATE);
2442 Lrc::new(tcx.cstore.postorder_cnums_untracked())
2444 providers.output_filenames = |tcx, cnum| {
2445 assert_eq!(cnum, LOCAL_CRATE);
2446 tcx.output_filenames.clone()
2448 providers.has_copy_closures = |tcx, cnum| {
2449 assert_eq!(cnum, LOCAL_CRATE);
2450 tcx.features().copy_closures
2452 providers.has_clone_closures = |tcx, cnum| {
2453 assert_eq!(cnum, LOCAL_CRATE);
2454 tcx.features().clone_closures
2456 providers.fully_normalize_monormophic_ty = |tcx, ty| {
2457 tcx.fully_normalize_associated_types_in(&ty)
2459 providers.features_query = |tcx, cnum| {
2460 assert_eq!(cnum, LOCAL_CRATE);
2461 Lrc::new(tcx.sess.features_untracked().clone())
2463 providers.is_panic_runtime = |tcx, cnum| {
2464 assert_eq!(cnum, LOCAL_CRATE);
2465 attr::contains_name(tcx.hir.krate_attrs(), "panic_runtime")
2467 providers.is_compiler_builtins = |tcx, cnum| {
2468 assert_eq!(cnum, LOCAL_CRATE);
2469 attr::contains_name(tcx.hir.krate_attrs(), "compiler_builtins")