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, DepTrackingMap};
16 use middle::cstore::LOCAL_CRATE;
18 use hir::def_id::{DefId, DefIndex};
19 use hir::map as ast_map;
20 use hir::map::{DefKey, DefPath, DefPathData, DisambiguatedDefPathData};
21 use middle::free_region::FreeRegionMap;
22 use middle::region::RegionMaps;
23 use middle::resolve_lifetime;
24 use middle::stability;
25 use ty::subst::{self, Substs};
27 use ty::{self, TraitRef, Ty, TypeAndMut};
28 use ty::{TyS, TypeVariants};
29 use ty::{AdtDef, ClosureSubsts, ExistentialBounds, Region};
31 use ty::{BareFnTy, InferTy, ParamTy, ProjectionTy, TraitTy};
32 use ty::{TyVar, TyVid, IntVar, IntVid, FloatVar, FloatVid};
33 use ty::TypeVariants::*;
34 use ty::layout::{Layout, TargetDataLayout};
36 use util::common::MemoizationMap;
37 use util::nodemap::{NodeMap, NodeSet, DefIdMap, DefIdSet};
38 use util::nodemap::{FnvHashMap, FnvHashSet};
40 use arena::TypedArena;
41 use std::borrow::Borrow;
42 use std::cell::{Cell, RefCell, Ref};
43 use std::hash::{Hash, Hasher};
47 use syntax::ast::{self, Name, NodeId};
49 use syntax::parse::token::{self, keywords};
54 pub struct CtxtArenas<'tcx> {
56 type_: TypedArena<TyS<'tcx>>,
57 type_list: TypedArena<Vec<Ty<'tcx>>>,
58 substs: TypedArena<Substs<'tcx>>,
59 bare_fn: TypedArena<BareFnTy<'tcx>>,
60 region: TypedArena<Region>,
61 stability: TypedArena<attr::Stability>,
62 layout: TypedArena<Layout>,
65 trait_defs: TypedArena<ty::TraitDef<'tcx>>,
66 adt_defs: TypedArena<ty::AdtDefData<'tcx, 'tcx>>,
69 impl<'tcx> CtxtArenas<'tcx> {
70 pub fn new() -> CtxtArenas<'tcx> {
72 type_: TypedArena::new(),
73 type_list: TypedArena::new(),
74 substs: TypedArena::new(),
75 bare_fn: TypedArena::new(),
76 region: TypedArena::new(),
77 stability: TypedArena::new(),
78 layout: TypedArena::new(),
80 trait_defs: TypedArena::new(),
81 adt_defs: TypedArena::new()
86 pub struct CtxtInterners<'tcx> {
87 /// The arenas that types etc are allocated from.
88 arenas: &'tcx CtxtArenas<'tcx>,
90 /// Specifically use a speedy hash algorithm for these hash sets,
91 /// they're accessed quite often.
92 type_: RefCell<FnvHashSet<Interned<'tcx, TyS<'tcx>>>>,
93 type_list: RefCell<FnvHashSet<Interned<'tcx, [Ty<'tcx>]>>>,
94 substs: RefCell<FnvHashSet<Interned<'tcx, Substs<'tcx>>>>,
95 bare_fn: RefCell<FnvHashSet<Interned<'tcx, BareFnTy<'tcx>>>>,
96 region: RefCell<FnvHashSet<Interned<'tcx, Region>>>,
97 stability: RefCell<FnvHashSet<&'tcx attr::Stability>>,
98 layout: RefCell<FnvHashSet<&'tcx Layout>>,
101 impl<'gcx: 'tcx, 'tcx> CtxtInterners<'tcx> {
102 fn new(arenas: &'tcx CtxtArenas<'tcx>) -> CtxtInterners<'tcx> {
105 type_: RefCell::new(FnvHashSet()),
106 type_list: RefCell::new(FnvHashSet()),
107 substs: RefCell::new(FnvHashSet()),
108 bare_fn: RefCell::new(FnvHashSet()),
109 region: RefCell::new(FnvHashSet()),
110 stability: RefCell::new(FnvHashSet()),
111 layout: RefCell::new(FnvHashSet())
115 /// Intern a type. global_interners is Some only if this is
116 /// a local interner and global_interners is its counterpart.
117 fn intern_ty(&self, st: TypeVariants<'tcx>,
118 global_interners: Option<&CtxtInterners<'gcx>>)
121 let mut interner = self.type_.borrow_mut();
122 let global_interner = global_interners.map(|interners| {
123 interners.type_.borrow_mut()
125 if let Some(&Interned(ty)) = interner.get(&st) {
128 if let Some(ref interner) = global_interner {
129 if let Some(&Interned(ty)) = interner.get(&st) {
134 let flags = super::flags::FlagComputation::for_sty(&st);
135 let ty_struct = TyS {
137 flags: Cell::new(flags.flags),
138 region_depth: flags.depth,
141 // HACK(eddyb) Depend on flags being accurate to
142 // determine that all contents are in the global tcx.
143 // See comments on Lift for why we can't use that.
144 if !flags.flags.intersects(ty::TypeFlags::KEEP_IN_LOCAL_TCX) {
145 if let Some(interner) = global_interners {
146 let ty_struct: TyS<'gcx> = unsafe {
147 mem::transmute(ty_struct)
149 let ty: Ty<'gcx> = interner.arenas.type_.alloc(ty_struct);
150 global_interner.unwrap().insert(Interned(ty));
154 // Make sure we don't end up with inference
155 // types/regions in the global tcx.
156 if global_interners.is_none() {
158 bug!("Attempted to intern `{:?}` which contains \
159 inference types/regions in the global type context",
164 // Don't be &mut TyS.
165 let ty: Ty<'tcx> = self.arenas.type_.alloc(ty_struct);
166 interner.insert(Interned(ty));
170 debug!("Interned type: {:?} Pointer: {:?}",
171 ty, ty as *const TyS);
177 pub struct CommonTypes<'tcx> {
195 pub struct Tables<'tcx> {
196 /// Stores the types for various nodes in the AST. Note that this table
197 /// is not guaranteed to be populated until after typeck. See
198 /// typeck::check::fn_ctxt for details.
199 pub node_types: NodeMap<Ty<'tcx>>,
201 /// Stores the type parameters which were substituted to obtain the type
202 /// of this node. This only applies to nodes that refer to entities
203 /// parameterized by type parameters, such as generic fns, types, or
205 pub item_substs: NodeMap<ty::ItemSubsts<'tcx>>,
207 pub adjustments: NodeMap<ty::adjustment::AutoAdjustment<'tcx>>,
209 pub method_map: ty::MethodMap<'tcx>,
212 pub upvar_capture_map: ty::UpvarCaptureMap,
214 /// Records the type of each closure. The def ID is the ID of the
215 /// expression defining the closure.
216 pub closure_tys: DefIdMap<ty::ClosureTy<'tcx>>,
218 /// Records the type of each closure. The def ID is the ID of the
219 /// expression defining the closure.
220 pub closure_kinds: DefIdMap<ty::ClosureKind>,
222 /// For each fn, records the "liberated" types of its arguments
223 /// and return type. Liberated means that all bound regions
224 /// (including late-bound regions) are replaced with free
225 /// equivalents. This table is not used in trans (since regions
226 /// are erased there) and hence is not serialized to metadata.
227 pub liberated_fn_sigs: NodeMap<ty::FnSig<'tcx>>,
229 /// For each FRU expression, record the normalized types of the fields
230 /// of the struct - this is needed because it is non-trivial to
231 /// normalize while preserving regions. This table is used only in
232 /// MIR construction and hence is not serialized to metadata.
233 pub fru_field_types: NodeMap<Vec<Ty<'tcx>>>
236 impl<'a, 'gcx, 'tcx> Tables<'tcx> {
237 pub fn empty() -> Tables<'tcx> {
239 node_types: FnvHashMap(),
240 item_substs: NodeMap(),
241 adjustments: NodeMap(),
242 method_map: FnvHashMap(),
243 upvar_capture_map: FnvHashMap(),
244 closure_tys: DefIdMap(),
245 closure_kinds: DefIdMap(),
246 liberated_fn_sigs: NodeMap(),
247 fru_field_types: NodeMap()
252 impl<'tcx> CommonTypes<'tcx> {
253 fn new(interners: &CtxtInterners<'tcx>) -> CommonTypes<'tcx> {
254 let mk = |sty| interners.intern_ty(sty, None);
259 isize: mk(TyInt(ast::IntTy::Is)),
260 i8: mk(TyInt(ast::IntTy::I8)),
261 i16: mk(TyInt(ast::IntTy::I16)),
262 i32: mk(TyInt(ast::IntTy::I32)),
263 i64: mk(TyInt(ast::IntTy::I64)),
264 usize: mk(TyUint(ast::UintTy::Us)),
265 u8: mk(TyUint(ast::UintTy::U8)),
266 u16: mk(TyUint(ast::UintTy::U16)),
267 u32: mk(TyUint(ast::UintTy::U32)),
268 u64: mk(TyUint(ast::UintTy::U64)),
269 f32: mk(TyFloat(ast::FloatTy::F32)),
270 f64: mk(TyFloat(ast::FloatTy::F64)),
275 /// The data structure to keep track of all the information that typechecker
276 /// generates so that so that it can be reused and doesn't have to be redone
278 #[derive(Copy, Clone)]
279 pub struct TyCtxt<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
280 gcx: &'a GlobalCtxt<'gcx>,
281 interners: &'a CtxtInterners<'tcx>
284 impl<'a, 'gcx, 'tcx> Deref for TyCtxt<'a, 'gcx, 'tcx> {
285 type Target = &'a GlobalCtxt<'gcx>;
286 fn deref(&self) -> &Self::Target {
291 pub struct GlobalCtxt<'tcx> {
292 global_interners: CtxtInterners<'tcx>,
294 pub specializes_cache: RefCell<traits::SpecializesCache>,
296 pub dep_graph: DepGraph,
298 /// Common types, pre-interned for your convenience.
299 pub types: CommonTypes<'tcx>,
301 pub sess: &'tcx Session,
302 pub def_map: RefCell<DefMap>,
304 pub named_region_map: resolve_lifetime::NamedRegionMap,
306 pub region_maps: RegionMaps,
308 // For each fn declared in the local crate, type check stores the
309 // free-region relationships that were deduced from its where
310 // clauses and parameter types. These are then read-again by
311 // borrowck. (They are not used during trans, and hence are not
312 // serialized or needed for cross-crate fns.)
313 free_region_maps: RefCell<NodeMap<FreeRegionMap>>,
314 // FIXME: jroesch make this a refcell
316 pub tables: RefCell<Tables<'tcx>>,
318 /// Maps from a trait item to the trait item "descriptor"
319 pub impl_or_trait_items: RefCell<DepTrackingMap<maps::ImplOrTraitItems<'tcx>>>,
321 /// Maps from a trait def-id to a list of the def-ids of its trait items
322 pub trait_item_def_ids: RefCell<DepTrackingMap<maps::TraitItemDefIds<'tcx>>>,
324 /// A cache for the trait_items() routine; note that the routine
325 /// itself pushes the `TraitItems` dependency node.
326 trait_items_cache: RefCell<DepTrackingMap<maps::TraitItems<'tcx>>>,
328 pub impl_trait_refs: RefCell<DepTrackingMap<maps::ImplTraitRefs<'tcx>>>,
329 pub trait_defs: RefCell<DepTrackingMap<maps::TraitDefs<'tcx>>>,
330 pub adt_defs: RefCell<DepTrackingMap<maps::AdtDefs<'tcx>>>,
332 /// Maps from the def-id of an item (trait/struct/enum/fn) to its
333 /// associated predicates.
334 pub predicates: RefCell<DepTrackingMap<maps::Predicates<'tcx>>>,
336 /// Maps from the def-id of a trait to the list of
337 /// super-predicates. This is a subset of the full list of
338 /// predicates. We store these in a separate map because we must
339 /// evaluate them even during type conversion, often before the
340 /// full predicates are available (note that supertraits have
341 /// additional acyclicity requirements).
342 pub super_predicates: RefCell<DepTrackingMap<maps::Predicates<'tcx>>>,
344 pub map: ast_map::Map<'tcx>,
346 // Records the free variables refrenced by every closure
347 // expression. Do not track deps for this, just recompute it from
348 // scratch every time.
349 pub freevars: RefCell<FreevarMap>,
351 pub maybe_unused_trait_imports: NodeSet,
353 // Records the type of every item.
354 pub tcache: RefCell<DepTrackingMap<maps::Tcache<'tcx>>>,
356 // Internal cache for metadata decoding. No need to track deps on this.
357 pub rcache: RefCell<FnvHashMap<ty::CReaderCacheKey, Ty<'tcx>>>,
359 // Cache for the type-contents routine. FIXME -- track deps?
360 pub tc_cache: RefCell<FnvHashMap<Ty<'tcx>, ty::contents::TypeContents>>,
362 // FIXME no dep tracking, but we should be able to remove this
363 pub ty_param_defs: RefCell<NodeMap<ty::TypeParameterDef<'tcx>>>,
365 // FIXME dep tracking -- should be harmless enough
366 pub normalized_cache: RefCell<FnvHashMap<Ty<'tcx>, Ty<'tcx>>>,
368 pub lang_items: middle::lang_items::LanguageItems,
370 /// Maps from def-id of a type or region parameter to its
371 /// (inferred) variance.
372 pub item_variance_map: RefCell<DepTrackingMap<maps::ItemVariances<'tcx>>>,
374 /// True if the variance has been computed yet; false otherwise.
375 pub variance_computed: Cell<bool>,
377 /// Maps a DefId of a type to a list of its inherent impls.
378 /// Contains implementations of methods that are inherent to a type.
379 /// Methods in these implementations don't need to be exported.
380 pub inherent_impls: RefCell<DepTrackingMap<maps::InherentImpls<'tcx>>>,
382 /// Maps a DefId of an impl to a list of its items.
383 /// Note that this contains all of the impls that we know about,
384 /// including ones in other crates. It's not clear that this is the best
386 pub impl_items: RefCell<DepTrackingMap<maps::ImplItems<'tcx>>>,
388 /// Set of used unsafe nodes (functions or blocks). Unsafe nodes not
389 /// present in this set can be warned about.
390 pub used_unsafe: RefCell<NodeSet>,
392 /// Set of nodes which mark locals as mutable which end up getting used at
393 /// some point. Local variable definitions not in this set can be warned
395 pub used_mut_nodes: RefCell<NodeSet>,
397 /// Set of trait imports actually used in the method resolution.
398 /// This is used for warning unused imports.
399 pub used_trait_imports: RefCell<NodeSet>,
401 /// The set of external nominal types whose implementations have been read.
402 /// This is used for lazy resolution of methods.
403 pub populated_external_types: RefCell<DefIdSet>,
405 /// The set of external primitive types whose implementations have been read.
406 /// FIXME(arielb1): why is this separate from populated_external_types?
407 pub populated_external_primitive_impls: RefCell<DefIdSet>,
409 /// Cache used by const_eval when decoding external constants.
410 /// Contains `None` when the constant has been fetched but doesn't exist.
411 /// Constains `Some(expr_id, type)` otherwise.
412 /// `type` is `None` in case it's not a primitive type
413 pub extern_const_statics: RefCell<DefIdMap<Option<(NodeId, Option<Ty<'tcx>>)>>>,
414 /// Cache used by const_eval when decoding extern const fns
415 pub extern_const_fns: RefCell<DefIdMap<NodeId>>,
417 /// Maps any item's def-id to its stability index.
418 pub stability: RefCell<stability::Index<'tcx>>,
420 /// Caches the results of trait selection. This cache is used
421 /// for things that do not have to do with the parameters in scope.
422 pub selection_cache: traits::SelectionCache<'tcx>,
424 /// Caches the results of trait evaluation. This cache is used
425 /// for things that do not have to do with the parameters in scope.
426 /// Merge this with `selection_cache`?
427 pub evaluation_cache: traits::EvaluationCache<'tcx>,
429 /// A set of predicates that have been fulfilled *somewhere*.
430 /// This is used to avoid duplicate work. Predicates are only
431 /// added to this set when they mention only "global" names
432 /// (i.e., no type or lifetime parameters).
433 pub fulfilled_predicates: RefCell<traits::GlobalFulfilledPredicates<'tcx>>,
435 /// Caches the representation hints for struct definitions.
436 repr_hint_cache: RefCell<DepTrackingMap<maps::ReprHints<'tcx>>>,
438 /// Maps Expr NodeId's to their constant qualification.
439 pub const_qualif_map: RefCell<NodeMap<middle::const_qualif::ConstQualif>>,
441 /// Caches CoerceUnsized kinds for impls on custom types.
442 pub custom_coerce_unsized_kinds: RefCell<DefIdMap<ty::adjustment::CustomCoerceUnsized>>,
444 /// Maps a cast expression to its kind. This is keyed on the
445 /// *from* expression of the cast, not the cast itself.
446 pub cast_kinds: RefCell<NodeMap<ty::cast::CastKind>>,
448 /// Maps Fn items to a collection of fragment infos.
450 /// The main goal is to identify data (each of which may be moved
451 /// or assigned) whose subparts are not moved nor assigned
452 /// (i.e. their state is *unfragmented*) and corresponding ast
453 /// nodes where the path to that data is moved or assigned.
455 /// In the long term, unfragmented values will have their
456 /// destructor entirely driven by a single stack-local drop-flag,
457 /// and their parents, the collections of the unfragmented values
458 /// (or more simply, "fragmented values"), are mapped to the
459 /// corresponding collections of stack-local drop-flags.
461 /// (However, in the short term that is not the case; e.g. some
462 /// unfragmented paths still need to be zeroed, namely when they
463 /// reference parent data from an outer scope that was not
464 /// entirely moved, and therefore that needs to be zeroed so that
465 /// we do not get double-drop when we hit the end of the parent
468 /// Also: currently the table solely holds keys for node-ids of
469 /// unfragmented values (see `FragmentInfo` enum definition), but
470 /// longer-term we will need to also store mappings from
471 /// fragmented data to the set of unfragmented pieces that
473 pub fragment_infos: RefCell<DefIdMap<Vec<ty::FragmentInfo>>>,
475 /// The definite name of the current crate after taking into account
476 /// attributes, commandline parameters, etc.
477 pub crate_name: token::InternedString,
479 /// Data layout specification for the current target.
480 pub data_layout: TargetDataLayout,
482 /// Cache for layouts computed from types.
483 pub layout_cache: RefCell<FnvHashMap<Ty<'tcx>, &'tcx Layout>>,
486 impl<'tcx> GlobalCtxt<'tcx> {
487 /// Get the global TyCtxt.
488 pub fn global_tcx<'a>(&'a self) -> TyCtxt<'a, 'tcx, 'tcx> {
491 interners: &self.global_interners
496 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
497 pub fn crate_name(self, cnum: ast::CrateNum) -> token::InternedString {
498 if cnum == LOCAL_CRATE {
499 self.crate_name.clone()
501 self.sess.cstore.crate_name(cnum)
505 pub fn crate_disambiguator(self, cnum: ast::CrateNum) -> token::InternedString {
506 if cnum == LOCAL_CRATE {
507 self.sess.local_crate_disambiguator()
509 self.sess.cstore.crate_disambiguator(cnum)
513 /// Given a def-key `key` and a crate `krate`, finds the def-index
514 /// that `krate` assigned to `key`. This `DefIndex` will always be
515 /// relative to `krate`.
517 /// Returns `None` if there is no `DefIndex` with that key.
518 pub fn def_index_for_def_key(self, krate: ast::CrateNum, key: DefKey)
519 -> Option<DefIndex> {
520 if krate == LOCAL_CRATE {
521 self.map.def_index_for_def_key(key)
523 self.sess.cstore.def_index_for_def_key(krate, key)
527 pub fn retrace_path(self, path: &DefPath) -> Option<DefId> {
528 debug!("retrace_path(path={:?})", path);
530 let root_key = DefKey {
532 disambiguated_data: DisambiguatedDefPathData {
533 data: DefPathData::CrateRoot,
538 let root_index = self.def_index_for_def_key(path.krate, root_key)
539 .expect("no root key?");
541 debug!("retrace_path: root_index={:?}", root_index);
543 let mut index = root_index;
544 for data in &path.data {
545 let key = DefKey { parent: Some(index), disambiguated_data: data.clone() };
546 debug!("retrace_path: key={:?}", key);
547 match self.def_index_for_def_key(path.krate, key) {
548 Some(i) => index = i,
553 Some(DefId { krate: path.krate, index: index })
556 pub fn type_parameter_def(self,
558 -> ty::TypeParameterDef<'tcx>
560 self.ty_param_defs.borrow().get(&node_id).unwrap().clone()
563 pub fn node_types(self) -> Ref<'a, NodeMap<Ty<'tcx>>> {
564 fn projection<'a, 'tcx>(tables: &'a Tables<'tcx>) -> &'a NodeMap<Ty<'tcx>> {
568 Ref::map(self.tables.borrow(), projection)
571 pub fn node_type_insert(self, id: NodeId, ty: Ty<'gcx>) {
572 self.tables.borrow_mut().node_types.insert(id, ty);
575 pub fn intern_trait_def(self, def: ty::TraitDef<'gcx>)
576 -> &'gcx ty::TraitDef<'gcx> {
577 let did = def.trait_ref.def_id;
578 let interned = self.global_interners.arenas.trait_defs.alloc(def);
579 if let Some(prev) = self.trait_defs.borrow_mut().insert(did, interned) {
580 bug!("Tried to overwrite interned TraitDef: {:?}", prev)
585 pub fn alloc_trait_def(self, def: ty::TraitDef<'gcx>)
586 -> &'gcx ty::TraitDef<'gcx> {
587 self.global_interners.arenas.trait_defs.alloc(def)
590 pub fn insert_adt_def(self, did: DefId, adt_def: ty::AdtDefMaster<'gcx>) {
591 // this will need a transmute when reverse-variance is removed
592 if let Some(prev) = self.adt_defs.borrow_mut().insert(did, adt_def) {
593 bug!("Tried to overwrite interned AdtDef: {:?}", prev)
597 pub fn intern_adt_def(self,
600 variants: Vec<ty::VariantDefData<'gcx, 'gcx>>)
601 -> ty::AdtDefMaster<'gcx> {
602 let def = ty::AdtDefData::new(self, did, kind, variants);
603 let interned = self.global_interners.arenas.adt_defs.alloc(def);
604 self.insert_adt_def(did, interned);
608 pub fn intern_stability(self, stab: attr::Stability) -> &'gcx attr::Stability {
609 if let Some(st) = self.global_interners.stability.borrow().get(&stab) {
613 let interned = self.global_interners.arenas.stability.alloc(stab);
614 if let Some(prev) = self.global_interners.stability
617 bug!("Tried to overwrite interned Stability: {:?}", prev)
622 pub fn intern_layout(self, layout: Layout) -> &'gcx Layout {
623 if let Some(layout) = self.global_interners.layout.borrow().get(&layout) {
627 let interned = self.global_interners.arenas.layout.alloc(layout);
628 if let Some(prev) = self.global_interners.layout
631 bug!("Tried to overwrite interned Layout: {:?}", prev)
636 pub fn store_free_region_map(self, id: NodeId, map: FreeRegionMap) {
637 if self.free_region_maps.borrow_mut().insert(id, map).is_some() {
638 bug!("Tried to overwrite interned FreeRegionMap for NodeId {:?}", id)
642 pub fn free_region_map(self, id: NodeId) -> FreeRegionMap {
643 self.free_region_maps.borrow()[&id].clone()
646 pub fn lift<T: ?Sized + Lift<'tcx>>(self, value: &T) -> Option<T::Lifted> {
647 value.lift_to_tcx(self)
650 /// Like lift, but only tries in the global tcx.
651 pub fn lift_to_global<T: ?Sized + Lift<'gcx>>(self, value: &T) -> Option<T::Lifted> {
652 value.lift_to_tcx(self.global_tcx())
655 /// Returns true if self is the same as self.global_tcx().
656 fn is_global(self) -> bool {
657 let local = self.interners as *const _;
658 let global = &self.global_interners as *const _;
659 local as usize == global as usize
662 /// Create a type context and call the closure with a `TyCtxt` reference
663 /// to the context. The closure enforces that the type context and any interned
664 /// value (types, substs, etc.) can only be used while `ty::tls` has a valid
665 /// reference to the context, to allow formatting values that need it.
666 pub fn create_and_enter<F, R>(s: &'tcx Session,
667 arenas: &'tcx CtxtArenas<'tcx>,
669 named_region_map: resolve_lifetime::NamedRegionMap,
670 map: ast_map::Map<'tcx>,
671 freevars: FreevarMap,
672 maybe_unused_trait_imports: NodeSet,
673 region_maps: RegionMaps,
674 lang_items: middle::lang_items::LanguageItems,
675 stability: stability::Index<'tcx>,
678 where F: for<'b> FnOnce(TyCtxt<'b, 'tcx, 'tcx>) -> R
680 let data_layout = TargetDataLayout::parse(s);
681 let interners = CtxtInterners::new(arenas);
682 let common_types = CommonTypes::new(&interners);
683 let dep_graph = map.dep_graph.clone();
684 let fulfilled_predicates = traits::GlobalFulfilledPredicates::new(dep_graph.clone());
685 tls::enter_global(GlobalCtxt {
686 specializes_cache: RefCell::new(traits::SpecializesCache::new()),
687 global_interners: interners,
688 dep_graph: dep_graph.clone(),
690 named_region_map: named_region_map,
691 region_maps: region_maps,
692 free_region_maps: RefCell::new(FnvHashMap()),
693 item_variance_map: RefCell::new(DepTrackingMap::new(dep_graph.clone())),
694 variance_computed: Cell::new(false),
696 def_map: RefCell::new(def_map),
697 tables: RefCell::new(Tables::empty()),
698 impl_trait_refs: RefCell::new(DepTrackingMap::new(dep_graph.clone())),
699 trait_defs: RefCell::new(DepTrackingMap::new(dep_graph.clone())),
700 adt_defs: RefCell::new(DepTrackingMap::new(dep_graph.clone())),
701 predicates: RefCell::new(DepTrackingMap::new(dep_graph.clone())),
702 super_predicates: RefCell::new(DepTrackingMap::new(dep_graph.clone())),
703 fulfilled_predicates: RefCell::new(fulfilled_predicates),
705 freevars: RefCell::new(freevars),
706 maybe_unused_trait_imports: maybe_unused_trait_imports,
707 tcache: RefCell::new(DepTrackingMap::new(dep_graph.clone())),
708 rcache: RefCell::new(FnvHashMap()),
709 tc_cache: RefCell::new(FnvHashMap()),
710 impl_or_trait_items: RefCell::new(DepTrackingMap::new(dep_graph.clone())),
711 trait_item_def_ids: RefCell::new(DepTrackingMap::new(dep_graph.clone())),
712 trait_items_cache: RefCell::new(DepTrackingMap::new(dep_graph.clone())),
713 ty_param_defs: RefCell::new(NodeMap()),
714 normalized_cache: RefCell::new(FnvHashMap()),
715 lang_items: lang_items,
716 inherent_impls: RefCell::new(DepTrackingMap::new(dep_graph.clone())),
717 impl_items: RefCell::new(DepTrackingMap::new(dep_graph.clone())),
718 used_unsafe: RefCell::new(NodeSet()),
719 used_mut_nodes: RefCell::new(NodeSet()),
720 used_trait_imports: RefCell::new(NodeSet()),
721 populated_external_types: RefCell::new(DefIdSet()),
722 populated_external_primitive_impls: RefCell::new(DefIdSet()),
723 extern_const_statics: RefCell::new(DefIdMap()),
724 extern_const_fns: RefCell::new(DefIdMap()),
725 stability: RefCell::new(stability),
726 selection_cache: traits::SelectionCache::new(),
727 evaluation_cache: traits::EvaluationCache::new(),
728 repr_hint_cache: RefCell::new(DepTrackingMap::new(dep_graph.clone())),
729 const_qualif_map: RefCell::new(NodeMap()),
730 custom_coerce_unsized_kinds: RefCell::new(DefIdMap()),
731 cast_kinds: RefCell::new(NodeMap()),
732 fragment_infos: RefCell::new(DefIdMap()),
733 crate_name: token::intern_and_get_ident(crate_name),
734 data_layout: data_layout,
735 layout_cache: RefCell::new(FnvHashMap()),
740 impl<'gcx: 'tcx, 'tcx> GlobalCtxt<'gcx> {
741 /// Call the closure with a local `TyCtxt` using the given arenas.
742 pub fn enter_local<F, R>(&self, arenas: &'tcx CtxtArenas<'tcx>, f: F) -> R
743 where F: for<'a> FnOnce(TyCtxt<'a, 'gcx, 'tcx>) -> R
745 let interners = CtxtInterners::new(arenas);
746 tls::enter(self, &interners, f)
750 /// A trait implemented for all X<'a> types which can be safely and
751 /// efficiently converted to X<'tcx> as long as they are part of the
752 /// provided TyCtxt<'tcx>.
753 /// This can be done, for example, for Ty<'tcx> or &'tcx Substs<'tcx>
754 /// by looking them up in their respective interners.
756 /// However, this is still not the best implementation as it does
757 /// need to compare the components, even for interned values.
758 /// It would be more efficient if TypedArena provided a way to
759 /// determine whether the address is in the allocated range.
761 /// None is returned if the value or one of the components is not part
762 /// of the provided context.
763 /// For Ty, None can be returned if either the type interner doesn't
764 /// contain the TypeVariants key or if the address of the interned
765 /// pointer differs. The latter case is possible if a primitive type,
766 /// e.g. `()` or `u8`, was interned in a different context.
767 pub trait Lift<'tcx> {
769 fn lift_to_tcx<'a, 'gcx>(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Option<Self::Lifted>;
772 impl<'a, 'tcx> Lift<'tcx> for Ty<'a> {
773 type Lifted = Ty<'tcx>;
774 fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>) -> Option<Ty<'tcx>> {
775 if let Some(&Interned(ty)) = tcx.interners.type_.borrow().get(&self.sty) {
776 if *self as *const _ == ty as *const _ {
780 // Also try in the global tcx if we're not that.
781 if !tcx.is_global() {
782 self.lift_to_tcx(tcx.global_tcx())
789 impl<'a, 'tcx> Lift<'tcx> for &'a Substs<'a> {
790 type Lifted = &'tcx Substs<'tcx>;
791 fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>) -> Option<&'tcx Substs<'tcx>> {
792 if let Some(&Interned(substs)) = tcx.interners.substs.borrow().get(*self) {
793 if *self as *const _ == substs as *const _ {
797 // Also try in the global tcx if we're not that.
798 if !tcx.is_global() {
799 self.lift_to_tcx(tcx.global_tcx())
806 impl<'a, 'tcx> Lift<'tcx> for &'a Region {
807 type Lifted = &'tcx Region;
808 fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>) -> Option<&'tcx Region> {
809 if let Some(&Interned(region)) = tcx.interners.region.borrow().get(*self) {
810 if *self as *const _ == region as *const _ {
814 // Also try in the global tcx if we're not that.
815 if !tcx.is_global() {
816 self.lift_to_tcx(tcx.global_tcx())
823 impl<'a, 'tcx> Lift<'tcx> for &'a [Ty<'a>] {
824 type Lifted = &'tcx [Ty<'tcx>];
825 fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>) -> Option<&'tcx [Ty<'tcx>]> {
826 if let Some(&Interned(list)) = tcx.interners.type_list.borrow().get(*self) {
827 if *self as *const _ == list as *const _ {
831 // Also try in the global tcx if we're not that.
832 if !tcx.is_global() {
833 self.lift_to_tcx(tcx.global_tcx())
840 impl<'a, 'tcx> Lift<'tcx> for &'a BareFnTy<'a> {
841 type Lifted = &'tcx BareFnTy<'tcx>;
842 fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>)
843 -> Option<&'tcx BareFnTy<'tcx>> {
844 if let Some(&Interned(fty)) = tcx.interners.bare_fn.borrow().get(*self) {
845 if *self as *const _ == fty as *const _ {
849 // Also try in the global tcx if we're not that.
850 if !tcx.is_global() {
851 self.lift_to_tcx(tcx.global_tcx())
860 use super::{CtxtInterners, GlobalCtxt, TyCtxt};
866 /// Marker types used for the scoped TLS slot.
867 /// The type context cannot be used directly because the scoped TLS
868 /// in libstd doesn't allow types generic over lifetimes.
869 enum ThreadLocalGlobalCtxt {}
870 enum ThreadLocalInterners {}
873 static TLS_TCX: Cell<Option<(*const ThreadLocalGlobalCtxt,
874 *const ThreadLocalInterners)>> = Cell::new(None)
877 fn span_debug(span: syntax_pos::Span, f: &mut fmt::Formatter) -> fmt::Result {
879 write!(f, "{}", tcx.sess.codemap().span_to_string(span))
883 pub fn enter_global<'gcx, F, R>(gcx: GlobalCtxt<'gcx>, f: F) -> R
884 where F: for<'a> FnOnce(TyCtxt<'a, 'gcx, 'gcx>) -> R
886 syntax_pos::SPAN_DEBUG.with(|span_dbg| {
887 let original_span_debug = span_dbg.get();
888 span_dbg.set(span_debug);
889 let result = enter(&gcx, &gcx.global_interners, f);
890 span_dbg.set(original_span_debug);
895 pub fn enter<'a, 'gcx: 'tcx, 'tcx, F, R>(gcx: &'a GlobalCtxt<'gcx>,
896 interners: &'a CtxtInterners<'tcx>,
898 where F: FnOnce(TyCtxt<'a, 'gcx, 'tcx>) -> R
900 let gcx_ptr = gcx as *const _ as *const ThreadLocalGlobalCtxt;
901 let interners_ptr = interners as *const _ as *const ThreadLocalInterners;
903 let prev = tls.get();
904 tls.set(Some((gcx_ptr, interners_ptr)));
914 pub fn with<F, R>(f: F) -> R
915 where F: for<'a, 'gcx, 'tcx> FnOnce(TyCtxt<'a, 'gcx, 'tcx>) -> R
918 let (gcx, interners) = tcx.get().unwrap();
919 let gcx = unsafe { &*(gcx as *const GlobalCtxt) };
920 let interners = unsafe { &*(interners as *const CtxtInterners) };
928 pub fn with_opt<F, R>(f: F) -> R
929 where F: for<'a, 'gcx, 'tcx> FnOnce(Option<TyCtxt<'a, 'gcx, 'tcx>>) -> R
931 if TLS_TCX.with(|tcx| tcx.get().is_some()) {
939 macro_rules! sty_debug_print {
940 ($ctxt: expr, $($variant: ident),*) => {{
941 // curious inner module to allow variant names to be used as
943 #[allow(non_snake_case)]
945 use ty::{self, TyCtxt};
946 use ty::context::Interned;
948 #[derive(Copy, Clone)]
956 pub fn go(tcx: TyCtxt) {
957 let mut total = DebugStat {
959 region_infer: 0, ty_infer: 0, both_infer: 0,
961 $(let mut $variant = total;)*
964 for &Interned(t) in tcx.interners.type_.borrow().iter() {
965 let variant = match t.sty {
966 ty::TyBool | ty::TyChar | ty::TyInt(..) | ty::TyUint(..) |
967 ty::TyFloat(..) | ty::TyStr => continue,
968 ty::TyError => /* unimportant */ continue,
969 $(ty::$variant(..) => &mut $variant,)*
971 let region = t.flags.get().intersects(ty::TypeFlags::HAS_RE_INFER);
972 let ty = t.flags.get().intersects(ty::TypeFlags::HAS_TY_INFER);
976 if region { total.region_infer += 1; variant.region_infer += 1 }
977 if ty { total.ty_infer += 1; variant.ty_infer += 1 }
978 if region && ty { total.both_infer += 1; variant.both_infer += 1 }
980 println!("Ty interner total ty region both");
981 $(println!(" {:18}: {uses:6} {usespc:4.1}%, \
982 {ty:4.1}% {region:5.1}% {both:4.1}%",
983 stringify!($variant),
984 uses = $variant.total,
985 usespc = $variant.total as f64 * 100.0 / total.total as f64,
986 ty = $variant.ty_infer as f64 * 100.0 / total.total as f64,
987 region = $variant.region_infer as f64 * 100.0 / total.total as f64,
988 both = $variant.both_infer as f64 * 100.0 / total.total as f64);
990 println!(" total {uses:6} \
991 {ty:4.1}% {region:5.1}% {both:4.1}%",
993 ty = total.ty_infer as f64 * 100.0 / total.total as f64,
994 region = total.region_infer as f64 * 100.0 / total.total as f64,
995 both = total.both_infer as f64 * 100.0 / total.total as f64)
1003 impl<'a, 'tcx> TyCtxt<'a, 'tcx, 'tcx> {
1004 pub fn print_debug_stats(self) {
1007 TyEnum, TyBox, TyArray, TySlice, TyRawPtr, TyRef, TyFnDef, TyFnPtr,
1008 TyTrait, TyStruct, TyClosure, TyTuple, TyParam, TyInfer, TyProjection);
1010 println!("Substs interner: #{}", self.interners.substs.borrow().len());
1011 println!("BareFnTy interner: #{}", self.interners.bare_fn.borrow().len());
1012 println!("Region interner: #{}", self.interners.region.borrow().len());
1013 println!("Stability interner: #{}", self.interners.stability.borrow().len());
1014 println!("Layout interner: #{}", self.interners.layout.borrow().len());
1019 /// An entry in an interner.
1020 struct Interned<'tcx, T: 'tcx+?Sized>(&'tcx T);
1022 // NB: An Interned<Ty> compares and hashes as a sty.
1023 impl<'tcx> PartialEq for Interned<'tcx, TyS<'tcx>> {
1024 fn eq(&self, other: &Interned<'tcx, TyS<'tcx>>) -> bool {
1025 self.0.sty == other.0.sty
1029 impl<'tcx> Eq for Interned<'tcx, TyS<'tcx>> {}
1031 impl<'tcx> Hash for Interned<'tcx, TyS<'tcx>> {
1032 fn hash<H: Hasher>(&self, s: &mut H) {
1037 impl<'tcx: 'lcx, 'lcx> Borrow<TypeVariants<'lcx>> for Interned<'tcx, TyS<'tcx>> {
1038 fn borrow<'a>(&'a self) -> &'a TypeVariants<'lcx> {
1043 impl<'tcx: 'lcx, 'lcx> Borrow<[Ty<'lcx>]> for Interned<'tcx, [Ty<'tcx>]> {
1044 fn borrow<'a>(&'a self) -> &'a [Ty<'lcx>] {
1049 impl<'tcx: 'lcx, 'lcx> Borrow<Substs<'lcx>> for Interned<'tcx, Substs<'tcx>> {
1050 fn borrow<'a>(&'a self) -> &'a Substs<'lcx> {
1055 impl<'tcx: 'lcx, 'lcx> Borrow<BareFnTy<'lcx>> for Interned<'tcx, BareFnTy<'tcx>> {
1056 fn borrow<'a>(&'a self) -> &'a BareFnTy<'lcx> {
1061 impl<'tcx> Borrow<Region> for Interned<'tcx, Region> {
1062 fn borrow<'a>(&'a self) -> &'a Region {
1067 macro_rules! items { ($($item:item)+) => ($($item)+) }
1068 macro_rules! impl_interners {
1069 ($lt_tcx:tt, $($name:ident: $method:ident($alloc:ty, $needs_infer:expr)-> $ty:ty),+) => {
1070 items!($(impl<$lt_tcx> PartialEq for Interned<$lt_tcx, $ty> {
1071 fn eq(&self, other: &Self) -> bool {
1076 impl<$lt_tcx> Eq for Interned<$lt_tcx, $ty> {}
1078 impl<$lt_tcx> Hash for Interned<$lt_tcx, $ty> {
1079 fn hash<H: Hasher>(&self, s: &mut H) {
1084 impl<'a, 'gcx, $lt_tcx> TyCtxt<'a, 'gcx, $lt_tcx> {
1085 pub fn $method(self, v: $alloc) -> &$lt_tcx $ty {
1086 if let Some(i) = self.interners.$name.borrow().get::<$ty>(&v) {
1089 if !self.is_global() {
1090 if let Some(i) = self.global_interners.$name.borrow().get::<$ty>(&v) {
1095 // HACK(eddyb) Depend on flags being accurate to
1096 // determine that all contents are in the global tcx.
1097 // See comments on Lift for why we can't use that.
1098 if !($needs_infer)(&v) {
1099 if !self.is_global() {
1103 let i = self.global_interners.arenas.$name.alloc(v);
1104 self.global_interners.$name.borrow_mut().insert(Interned(i));
1108 // Make sure we don't end up with inference
1109 // types/regions in the global tcx.
1110 if self.is_global() {
1111 bug!("Attempted to intern `{:?}` which contains \
1112 inference types/regions in the global type context",
1117 let i = self.interners.arenas.$name.alloc(v);
1118 self.interners.$name.borrow_mut().insert(Interned(i));
1125 fn keep_local<'tcx, T: ty::TypeFoldable<'tcx>>(x: &T) -> bool {
1126 x.has_type_flags(ty::TypeFlags::KEEP_IN_LOCAL_TCX)
1129 impl_interners!('tcx,
1130 type_list: mk_type_list(Vec<Ty<'tcx>>, keep_local) -> [Ty<'tcx>],
1131 substs: mk_substs(Substs<'tcx>, |substs: &Substs| {
1132 keep_local(&substs.types) || keep_local(&substs.regions)
1134 bare_fn: mk_bare_fn(BareFnTy<'tcx>, |fty: &BareFnTy| {
1135 keep_local(&fty.sig)
1136 }) -> BareFnTy<'tcx>,
1137 region: mk_region(Region, keep_local) -> Region
1140 fn bound_list_is_sorted(bounds: &[ty::PolyProjectionPredicate]) -> bool {
1141 bounds.is_empty() ||
1142 bounds[1..].iter().enumerate().all(
1143 |(index, bound)| bounds[index].sort_key() <= bound.sort_key())
1146 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
1147 /// Create an unsafe fn ty based on a safe fn ty.
1148 pub fn safe_to_unsafe_fn_ty(self, bare_fn: &BareFnTy<'tcx>) -> Ty<'tcx> {
1149 assert_eq!(bare_fn.unsafety, hir::Unsafety::Normal);
1150 self.mk_fn_ptr(self.mk_bare_fn(ty::BareFnTy {
1151 unsafety: hir::Unsafety::Unsafe,
1153 sig: bare_fn.sig.clone()
1157 // Interns a type/name combination, stores the resulting box in cx.interners,
1158 // and returns the box as cast to an unsafe ptr (see comments for Ty above).
1159 pub fn mk_ty(self, st: TypeVariants<'tcx>) -> Ty<'tcx> {
1160 let global_interners = if !self.is_global() {
1161 Some(&self.global_interners)
1165 self.interners.intern_ty(st, global_interners)
1168 pub fn mk_mach_int(self, tm: ast::IntTy) -> Ty<'tcx> {
1170 ast::IntTy::Is => self.types.isize,
1171 ast::IntTy::I8 => self.types.i8,
1172 ast::IntTy::I16 => self.types.i16,
1173 ast::IntTy::I32 => self.types.i32,
1174 ast::IntTy::I64 => self.types.i64,
1178 pub fn mk_mach_uint(self, tm: ast::UintTy) -> Ty<'tcx> {
1180 ast::UintTy::Us => self.types.usize,
1181 ast::UintTy::U8 => self.types.u8,
1182 ast::UintTy::U16 => self.types.u16,
1183 ast::UintTy::U32 => self.types.u32,
1184 ast::UintTy::U64 => self.types.u64,
1188 pub fn mk_mach_float(self, tm: ast::FloatTy) -> Ty<'tcx> {
1190 ast::FloatTy::F32 => self.types.f32,
1191 ast::FloatTy::F64 => self.types.f64,
1195 pub fn mk_str(self) -> Ty<'tcx> {
1199 pub fn mk_static_str(self) -> Ty<'tcx> {
1200 self.mk_imm_ref(self.mk_region(ty::ReStatic), self.mk_str())
1203 pub fn mk_enum(self, def: AdtDef<'tcx>, substs: &'tcx Substs<'tcx>) -> Ty<'tcx> {
1204 // take a copy of substs so that we own the vectors inside
1205 self.mk_ty(TyEnum(def, substs))
1208 pub fn mk_box(self, ty: Ty<'tcx>) -> Ty<'tcx> {
1209 self.mk_ty(TyBox(ty))
1212 pub fn mk_ptr(self, tm: TypeAndMut<'tcx>) -> Ty<'tcx> {
1213 self.mk_ty(TyRawPtr(tm))
1216 pub fn mk_ref(self, r: &'tcx Region, tm: TypeAndMut<'tcx>) -> Ty<'tcx> {
1217 self.mk_ty(TyRef(r, tm))
1220 pub fn mk_mut_ref(self, r: &'tcx Region, ty: Ty<'tcx>) -> Ty<'tcx> {
1221 self.mk_ref(r, TypeAndMut {ty: ty, mutbl: hir::MutMutable})
1224 pub fn mk_imm_ref(self, r: &'tcx Region, ty: Ty<'tcx>) -> Ty<'tcx> {
1225 self.mk_ref(r, TypeAndMut {ty: ty, mutbl: hir::MutImmutable})
1228 pub fn mk_mut_ptr(self, ty: Ty<'tcx>) -> Ty<'tcx> {
1229 self.mk_ptr(TypeAndMut {ty: ty, mutbl: hir::MutMutable})
1232 pub fn mk_imm_ptr(self, ty: Ty<'tcx>) -> Ty<'tcx> {
1233 self.mk_ptr(TypeAndMut {ty: ty, mutbl: hir::MutImmutable})
1236 pub fn mk_nil_ptr(self) -> Ty<'tcx> {
1237 self.mk_imm_ptr(self.mk_nil())
1240 pub fn mk_array(self, ty: Ty<'tcx>, n: usize) -> Ty<'tcx> {
1241 self.mk_ty(TyArray(ty, n))
1244 pub fn mk_slice(self, ty: Ty<'tcx>) -> Ty<'tcx> {
1245 self.mk_ty(TySlice(ty))
1248 pub fn mk_tup(self, ts: Vec<Ty<'tcx>>) -> Ty<'tcx> {
1249 self.mk_ty(TyTuple(self.mk_type_list(ts)))
1252 pub fn mk_nil(self) -> Ty<'tcx> {
1253 self.mk_tup(Vec::new())
1256 pub fn mk_bool(self) -> Ty<'tcx> {
1260 pub fn mk_fn_def(self, def_id: DefId,
1261 substs: &'tcx Substs<'tcx>,
1262 fty: &'tcx BareFnTy<'tcx>) -> Ty<'tcx> {
1263 self.mk_ty(TyFnDef(def_id, substs, fty))
1266 pub fn mk_fn_ptr(self, fty: &'tcx BareFnTy<'tcx>) -> Ty<'tcx> {
1267 self.mk_ty(TyFnPtr(fty))
1270 pub fn mk_trait(self,
1271 principal: ty::PolyTraitRef<'tcx>,
1272 bounds: ExistentialBounds<'tcx>)
1275 assert!(bound_list_is_sorted(&bounds.projection_bounds));
1277 let inner = box TraitTy {
1278 principal: principal,
1281 self.mk_ty(TyTrait(inner))
1284 pub fn mk_projection(self,
1285 trait_ref: TraitRef<'tcx>,
1288 // take a copy of substs so that we own the vectors inside
1289 let inner = ProjectionTy { trait_ref: trait_ref, item_name: item_name };
1290 self.mk_ty(TyProjection(inner))
1293 pub fn mk_struct(self, def: AdtDef<'tcx>, substs: &'tcx Substs<'tcx>) -> Ty<'tcx> {
1294 // take a copy of substs so that we own the vectors inside
1295 self.mk_ty(TyStruct(def, substs))
1298 pub fn mk_closure(self,
1300 substs: &'tcx Substs<'tcx>,
1303 self.mk_closure_from_closure_substs(closure_id, ClosureSubsts {
1304 func_substs: substs,
1305 upvar_tys: self.mk_type_list(tys)
1309 pub fn mk_closure_from_closure_substs(self,
1311 closure_substs: ClosureSubsts<'tcx>)
1313 self.mk_ty(TyClosure(closure_id, closure_substs))
1316 pub fn mk_var(self, v: TyVid) -> Ty<'tcx> {
1317 self.mk_infer(TyVar(v))
1320 pub fn mk_int_var(self, v: IntVid) -> Ty<'tcx> {
1321 self.mk_infer(IntVar(v))
1324 pub fn mk_float_var(self, v: FloatVid) -> Ty<'tcx> {
1325 self.mk_infer(FloatVar(v))
1328 pub fn mk_infer(self, it: InferTy) -> Ty<'tcx> {
1329 self.mk_ty(TyInfer(it))
1332 pub fn mk_param(self,
1333 space: subst::ParamSpace,
1335 name: Name) -> Ty<'tcx> {
1336 self.mk_ty(TyParam(ParamTy { space: space, idx: index, name: name }))
1339 pub fn mk_self_type(self) -> Ty<'tcx> {
1340 self.mk_param(subst::SelfSpace, 0, keywords::SelfType.name())
1343 pub fn mk_param_from_def(self, def: &ty::TypeParameterDef) -> Ty<'tcx> {
1344 self.mk_param(def.space, def.index, def.name)
1347 pub fn trait_items(self, trait_did: DefId) -> Rc<Vec<ty::ImplOrTraitItem<'gcx>>> {
1348 self.trait_items_cache.memoize(trait_did, || {
1349 let def_ids = self.trait_item_def_ids(trait_did);
1350 Rc::new(def_ids.iter()
1351 .map(|d| self.impl_or_trait_item(d.def_id()))
1356 /// Obtain the representation annotation for a struct definition.
1357 pub fn lookup_repr_hints(self, did: DefId) -> Rc<Vec<attr::ReprAttr>> {
1358 self.repr_hint_cache.memoize(did, || {
1359 Rc::new(if did.is_local() {
1360 self.get_attrs(did).iter().flat_map(|meta| {
1361 attr::find_repr_attrs(self.sess.diagnostic(), meta).into_iter()
1364 self.sess.cstore.repr_attrs(did)