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};
18 use hir::def_id::{CrateNum, DefId, LOCAL_CRATE};
19 use hir::map as ast_map;
20 use hir::map::DisambiguatedDefPathData;
21 use middle::free_region::FreeRegionMap;
22 use middle::region::RegionMaps;
23 use middle::resolve_lifetime;
24 use middle::stability;
26 use ty::subst::{Kind, Substs};
28 use ty::{self, TraitRef, Ty, TypeAndMut};
29 use ty::{TyS, TypeVariants, Slice};
30 use ty::{AdtKind, AdtDef, ClosureSubsts, Region};
32 use ty::{BareFnTy, InferTy, ParamTy, ProjectionTy, ExistentialPredicate};
33 use ty::{TyVar, TyVid, IntVar, IntVid, FloatVar, FloatVid};
34 use ty::TypeVariants::*;
35 use ty::layout::{Layout, TargetDataLayout};
37 use util::common::MemoizationMap;
38 use util::nodemap::{NodeMap, NodeSet, DefIdMap, DefIdSet};
39 use util::nodemap::{FxHashMap, FxHashSet};
40 use rustc_data_structures::accumulate_vec::AccumulateVec;
42 use arena::TypedArena;
43 use std::borrow::Borrow;
44 use std::cell::{Cell, RefCell};
45 use std::hash::{Hash, Hasher};
50 use std::cmp::Ordering;
51 use syntax::ast::{self, Name, NodeId};
53 use syntax::symbol::{Symbol, keywords};
58 pub struct CtxtArenas<'tcx> {
60 type_: TypedArena<TyS<'tcx>>,
61 type_list: TypedArena<Ty<'tcx>>,
62 substs: TypedArena<Kind<'tcx>>,
63 bare_fn: TypedArena<BareFnTy<'tcx>>,
64 region: TypedArena<Region>,
65 stability: TypedArena<attr::Stability>,
66 layout: TypedArena<Layout>,
67 existential_predicates: TypedArena<ExistentialPredicate<'tcx>>,
70 generics: TypedArena<ty::Generics<'tcx>>,
71 trait_def: TypedArena<ty::TraitDef>,
72 adt_def: TypedArena<ty::AdtDef>,
73 mir: TypedArena<RefCell<Mir<'tcx>>>,
76 impl<'tcx> CtxtArenas<'tcx> {
77 pub fn new() -> CtxtArenas<'tcx> {
79 type_: TypedArena::new(),
80 type_list: TypedArena::new(),
81 substs: TypedArena::new(),
82 bare_fn: TypedArena::new(),
83 region: TypedArena::new(),
84 stability: TypedArena::new(),
85 layout: TypedArena::new(),
86 existential_predicates: TypedArena::new(),
88 generics: TypedArena::new(),
89 trait_def: TypedArena::new(),
90 adt_def: TypedArena::new(),
91 mir: TypedArena::new()
96 pub struct CtxtInterners<'tcx> {
97 /// The arenas that types etc are allocated from.
98 arenas: &'tcx CtxtArenas<'tcx>,
100 /// Specifically use a speedy hash algorithm for these hash sets,
101 /// they're accessed quite often.
102 type_: RefCell<FxHashSet<Interned<'tcx, TyS<'tcx>>>>,
103 type_list: RefCell<FxHashSet<Interned<'tcx, Slice<Ty<'tcx>>>>>,
104 substs: RefCell<FxHashSet<Interned<'tcx, Substs<'tcx>>>>,
105 bare_fn: RefCell<FxHashSet<Interned<'tcx, BareFnTy<'tcx>>>>,
106 region: RefCell<FxHashSet<Interned<'tcx, Region>>>,
107 stability: RefCell<FxHashSet<&'tcx attr::Stability>>,
108 layout: RefCell<FxHashSet<&'tcx Layout>>,
109 existential_predicates: RefCell<FxHashSet<Interned<'tcx, Slice<ExistentialPredicate<'tcx>>>>>,
112 impl<'gcx: 'tcx, 'tcx> CtxtInterners<'tcx> {
113 fn new(arenas: &'tcx CtxtArenas<'tcx>) -> CtxtInterners<'tcx> {
116 type_: RefCell::new(FxHashSet()),
117 type_list: RefCell::new(FxHashSet()),
118 substs: RefCell::new(FxHashSet()),
119 bare_fn: RefCell::new(FxHashSet()),
120 region: RefCell::new(FxHashSet()),
121 stability: RefCell::new(FxHashSet()),
122 layout: RefCell::new(FxHashSet()),
123 existential_predicates: RefCell::new(FxHashSet()),
127 /// Intern a type. global_interners is Some only if this is
128 /// a local interner and global_interners is its counterpart.
129 fn intern_ty(&self, st: TypeVariants<'tcx>,
130 global_interners: Option<&CtxtInterners<'gcx>>)
133 let mut interner = self.type_.borrow_mut();
134 let global_interner = global_interners.map(|interners| {
135 interners.type_.borrow_mut()
137 if let Some(&Interned(ty)) = interner.get(&st) {
140 if let Some(ref interner) = global_interner {
141 if let Some(&Interned(ty)) = interner.get(&st) {
146 let flags = super::flags::FlagComputation::for_sty(&st);
147 let ty_struct = TyS {
149 flags: Cell::new(flags.flags),
150 region_depth: flags.depth,
153 // HACK(eddyb) Depend on flags being accurate to
154 // determine that all contents are in the global tcx.
155 // See comments on Lift for why we can't use that.
156 if !flags.flags.intersects(ty::TypeFlags::KEEP_IN_LOCAL_TCX) {
157 if let Some(interner) = global_interners {
158 let ty_struct: TyS<'gcx> = unsafe {
159 mem::transmute(ty_struct)
161 let ty: Ty<'gcx> = interner.arenas.type_.alloc(ty_struct);
162 global_interner.unwrap().insert(Interned(ty));
166 // Make sure we don't end up with inference
167 // types/regions in the global tcx.
168 if global_interners.is_none() {
170 bug!("Attempted to intern `{:?}` which contains \
171 inference types/regions in the global type context",
176 // Don't be &mut TyS.
177 let ty: Ty<'tcx> = self.arenas.type_.alloc(ty_struct);
178 interner.insert(Interned(ty));
182 debug!("Interned type: {:?} Pointer: {:?}",
183 ty, ty as *const TyS);
189 pub struct CommonTypes<'tcx> {
208 pub struct Tables<'tcx> {
209 /// Resolved definitions for `<T>::X` associated paths.
210 pub type_relative_path_defs: NodeMap<Def>,
212 /// Stores the types for various nodes in the AST. Note that this table
213 /// is not guaranteed to be populated until after typeck. See
214 /// typeck::check::fn_ctxt for details.
215 pub node_types: NodeMap<Ty<'tcx>>,
217 /// Stores the type parameters which were substituted to obtain the type
218 /// of this node. This only applies to nodes that refer to entities
219 /// parameterized by type parameters, such as generic fns, types, or
221 pub item_substs: NodeMap<ty::ItemSubsts<'tcx>>,
223 pub adjustments: NodeMap<ty::adjustment::Adjustment<'tcx>>,
225 pub method_map: ty::MethodMap<'tcx>,
228 pub upvar_capture_map: ty::UpvarCaptureMap<'tcx>,
230 /// Records the type of each closure. The def ID is the ID of the
231 /// expression defining the closure.
232 pub closure_tys: DefIdMap<ty::ClosureTy<'tcx>>,
234 /// Records the type of each closure. The def ID is the ID of the
235 /// expression defining the closure.
236 pub closure_kinds: DefIdMap<ty::ClosureKind>,
238 /// For each fn, records the "liberated" types of its arguments
239 /// and return type. Liberated means that all bound regions
240 /// (including late-bound regions) are replaced with free
241 /// equivalents. This table is not used in trans (since regions
242 /// are erased there) and hence is not serialized to metadata.
243 pub liberated_fn_sigs: NodeMap<ty::FnSig<'tcx>>,
245 /// For each FRU expression, record the normalized types of the fields
246 /// of the struct - this is needed because it is non-trivial to
247 /// normalize while preserving regions. This table is used only in
248 /// MIR construction and hence is not serialized to metadata.
249 pub fru_field_types: NodeMap<Vec<Ty<'tcx>>>
252 impl<'a, 'gcx, 'tcx> Tables<'tcx> {
253 pub fn empty() -> Tables<'tcx> {
255 type_relative_path_defs: NodeMap(),
256 node_types: FxHashMap(),
257 item_substs: NodeMap(),
258 adjustments: NodeMap(),
259 method_map: FxHashMap(),
260 upvar_capture_map: FxHashMap(),
261 closure_tys: DefIdMap(),
262 closure_kinds: DefIdMap(),
263 liberated_fn_sigs: NodeMap(),
264 fru_field_types: NodeMap()
268 /// Returns the final resolution of a `QPath` in an `Expr` or `Pat` node.
269 pub fn qpath_def(&self, qpath: &hir::QPath, id: NodeId) -> Def {
271 hir::QPath::Resolved(_, ref path) => path.def,
272 hir::QPath::TypeRelative(..) => {
273 self.type_relative_path_defs.get(&id).cloned().unwrap_or(Def::Err)
278 pub fn node_id_to_type(&self, id: NodeId) -> Ty<'tcx> {
279 match self.node_id_to_type_opt(id) {
282 bug!("node_id_to_type: no type for node `{}`",
283 tls::with(|tcx| tcx.map.node_to_string(id)))
288 pub fn node_id_to_type_opt(&self, id: NodeId) -> Option<Ty<'tcx>> {
289 self.node_types.get(&id).cloned()
292 pub fn node_id_item_substs(&self, id: NodeId) -> Option<&'tcx Substs<'tcx>> {
293 self.item_substs.get(&id).map(|ts| ts.substs)
296 // Returns the type of a pattern as a monotype. Like @expr_ty, this function
297 // doesn't provide type parameter substitutions.
298 pub fn pat_ty(&self, pat: &hir::Pat) -> Ty<'tcx> {
299 self.node_id_to_type(pat.id)
302 pub fn pat_ty_opt(&self, pat: &hir::Pat) -> Option<Ty<'tcx>> {
303 self.node_id_to_type_opt(pat.id)
306 // Returns the type of an expression as a monotype.
308 // NB (1): This is the PRE-ADJUSTMENT TYPE for the expression. That is, in
309 // some cases, we insert `Adjustment` annotations such as auto-deref or
310 // auto-ref. The type returned by this function does not consider such
311 // adjustments. See `expr_ty_adjusted()` instead.
313 // NB (2): This type doesn't provide type parameter substitutions; e.g. if you
314 // ask for the type of "id" in "id(3)", it will return "fn(&isize) -> isize"
315 // instead of "fn(ty) -> T with T = isize".
316 pub fn expr_ty(&self, expr: &hir::Expr) -> Ty<'tcx> {
317 self.node_id_to_type(expr.id)
320 pub fn expr_ty_opt(&self, expr: &hir::Expr) -> Option<Ty<'tcx>> {
321 self.node_id_to_type_opt(expr.id)
324 /// Returns the type of `expr`, considering any `Adjustment`
325 /// entry recorded for that expression.
326 pub fn expr_ty_adjusted(&self, expr: &hir::Expr) -> Ty<'tcx> {
327 self.adjustments.get(&expr.id)
328 .map_or_else(|| self.expr_ty(expr), |adj| adj.target)
331 pub fn expr_ty_adjusted_opt(&self, expr: &hir::Expr) -> Option<Ty<'tcx>> {
332 self.adjustments.get(&expr.id)
333 .map(|adj| adj.target).or_else(|| self.expr_ty_opt(expr))
336 pub fn is_method_call(&self, expr_id: NodeId) -> bool {
337 self.method_map.contains_key(&ty::MethodCall::expr(expr_id))
340 pub fn is_overloaded_autoderef(&self, expr_id: NodeId, autoderefs: u32) -> bool {
341 self.method_map.contains_key(&ty::MethodCall::autoderef(expr_id, autoderefs))
344 pub fn upvar_capture(&self, upvar_id: ty::UpvarId) -> Option<ty::UpvarCapture<'tcx>> {
345 Some(self.upvar_capture_map.get(&upvar_id).unwrap().clone())
349 impl<'tcx> CommonTypes<'tcx> {
350 fn new(interners: &CtxtInterners<'tcx>) -> CommonTypes<'tcx> {
351 let mk = |sty| interners.intern_ty(sty, None);
357 isize: mk(TyInt(ast::IntTy::Is)),
358 i8: mk(TyInt(ast::IntTy::I8)),
359 i16: mk(TyInt(ast::IntTy::I16)),
360 i32: mk(TyInt(ast::IntTy::I32)),
361 i64: mk(TyInt(ast::IntTy::I64)),
362 usize: mk(TyUint(ast::UintTy::Us)),
363 u8: mk(TyUint(ast::UintTy::U8)),
364 u16: mk(TyUint(ast::UintTy::U16)),
365 u32: mk(TyUint(ast::UintTy::U32)),
366 u64: mk(TyUint(ast::UintTy::U64)),
367 f32: mk(TyFloat(ast::FloatTy::F32)),
368 f64: mk(TyFloat(ast::FloatTy::F64)),
373 /// The data structure to keep track of all the information that typechecker
374 /// generates so that so that it can be reused and doesn't have to be redone
376 #[derive(Copy, Clone)]
377 pub struct TyCtxt<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
378 gcx: &'a GlobalCtxt<'gcx>,
379 interners: &'a CtxtInterners<'tcx>
382 impl<'a, 'gcx, 'tcx> Deref for TyCtxt<'a, 'gcx, 'tcx> {
383 type Target = &'a GlobalCtxt<'gcx>;
384 fn deref(&self) -> &Self::Target {
389 pub struct GlobalCtxt<'tcx> {
390 global_interners: CtxtInterners<'tcx>,
392 pub specializes_cache: RefCell<traits::SpecializesCache>,
394 pub dep_graph: DepGraph,
396 /// Common types, pre-interned for your convenience.
397 pub types: CommonTypes<'tcx>,
399 pub sess: &'tcx Session,
401 /// Map indicating what traits are in scope for places where this
402 /// is relevant; generated by resolve.
403 pub trait_map: TraitMap,
405 pub named_region_map: resolve_lifetime::NamedRegionMap,
407 pub region_maps: RegionMaps,
409 // For each fn declared in the local crate, type check stores the
410 // free-region relationships that were deduced from its where
411 // clauses and parameter types. These are then read-again by
412 // borrowck. (They are not used during trans, and hence are not
413 // serialized or needed for cross-crate fns.)
414 free_region_maps: RefCell<NodeMap<FreeRegionMap>>,
415 // FIXME: jroesch make this a refcell
417 pub tables: RefCell<Tables<'tcx>>,
419 /// Maps from a trait item to the trait item "descriptor"
420 pub associated_items: RefCell<DepTrackingMap<maps::AssociatedItems<'tcx>>>,
422 /// Maps from an impl/trait def-id to a list of the def-ids of its items
423 pub associated_item_def_ids: RefCell<DepTrackingMap<maps::AssociatedItemDefIds<'tcx>>>,
425 pub impl_trait_refs: RefCell<DepTrackingMap<maps::ImplTraitRefs<'tcx>>>,
426 pub trait_defs: RefCell<DepTrackingMap<maps::TraitDefs<'tcx>>>,
427 pub adt_defs: RefCell<DepTrackingMap<maps::AdtDefs<'tcx>>>,
428 pub adt_sized_constraint: RefCell<DepTrackingMap<maps::AdtSizedConstraint<'tcx>>>,
430 /// Maps from the def-id of an item (trait/struct/enum/fn) to its
431 /// associated generics and predicates.
432 pub generics: RefCell<DepTrackingMap<maps::Generics<'tcx>>>,
433 pub predicates: RefCell<DepTrackingMap<maps::Predicates<'tcx>>>,
435 /// Maps from the def-id of a trait to the list of
436 /// super-predicates. This is a subset of the full list of
437 /// predicates. We store these in a separate map because we must
438 /// evaluate them even during type conversion, often before the
439 /// full predicates are available (note that supertraits have
440 /// additional acyclicity requirements).
441 pub super_predicates: RefCell<DepTrackingMap<maps::Predicates<'tcx>>>,
443 pub map: ast_map::Map<'tcx>,
445 /// Maps from the def-id of a function/method or const/static
446 /// to its MIR. Mutation is done at an item granularity to
447 /// allow MIR optimization passes to function and still
448 /// access cross-crate MIR (e.g. inlining or const eval).
450 /// Note that cross-crate MIR appears to be always borrowed
451 /// (in the `RefCell` sense) to prevent accidental mutation.
452 pub mir_map: RefCell<DepTrackingMap<maps::Mir<'tcx>>>,
454 // Records the free variables refrenced by every closure
455 // expression. Do not track deps for this, just recompute it from
456 // scratch every time.
457 pub freevars: RefCell<FreevarMap>,
459 pub maybe_unused_trait_imports: NodeSet,
461 // Records the type of every item.
462 pub item_types: RefCell<DepTrackingMap<maps::Types<'tcx>>>,
464 // Internal cache for metadata decoding. No need to track deps on this.
465 pub rcache: RefCell<FxHashMap<ty::CReaderCacheKey, Ty<'tcx>>>,
467 // Cache for the type-contents routine. FIXME -- track deps?
468 pub tc_cache: RefCell<FxHashMap<Ty<'tcx>, ty::contents::TypeContents>>,
470 // FIXME no dep tracking, but we should be able to remove this
471 pub ty_param_defs: RefCell<NodeMap<ty::TypeParameterDef<'tcx>>>,
473 // FIXME dep tracking -- should be harmless enough
474 pub normalized_cache: RefCell<FxHashMap<Ty<'tcx>, Ty<'tcx>>>,
476 pub lang_items: middle::lang_items::LanguageItems,
478 /// Maps from def-id of a type or region parameter to its
479 /// (inferred) variance.
480 pub item_variance_map: RefCell<DepTrackingMap<maps::ItemVariances<'tcx>>>,
482 /// True if the variance has been computed yet; false otherwise.
483 pub variance_computed: Cell<bool>,
485 /// Maps a DefId of a type to a list of its inherent impls.
486 /// Contains implementations of methods that are inherent to a type.
487 /// Methods in these implementations don't need to be exported.
488 pub inherent_impls: RefCell<DepTrackingMap<maps::InherentImpls<'tcx>>>,
490 /// Set of used unsafe nodes (functions or blocks). Unsafe nodes not
491 /// present in this set can be warned about.
492 pub used_unsafe: RefCell<NodeSet>,
494 /// Set of nodes which mark locals as mutable which end up getting used at
495 /// some point. Local variable definitions not in this set can be warned
497 pub used_mut_nodes: RefCell<NodeSet>,
499 /// Set of trait imports actually used in the method resolution.
500 /// This is used for warning unused imports.
501 pub used_trait_imports: RefCell<NodeSet>,
503 /// The set of external nominal types whose implementations have been read.
504 /// This is used for lazy resolution of methods.
505 pub populated_external_types: RefCell<DefIdSet>,
507 /// The set of external primitive types whose implementations have been read.
508 /// FIXME(arielb1): why is this separate from populated_external_types?
509 pub populated_external_primitive_impls: RefCell<DefIdSet>,
511 /// Cache used by const_eval when decoding external constants.
512 /// Contains `None` when the constant has been fetched but doesn't exist.
513 /// Constains `Some(expr_id, type)` otherwise.
514 /// `type` is `None` in case it's not a primitive type
515 pub extern_const_statics: RefCell<DefIdMap<Option<(NodeId, Option<Ty<'tcx>>)>>>,
516 /// Cache used by const_eval when decoding extern const fns
517 pub extern_const_fns: RefCell<DefIdMap<NodeId>>,
519 /// Maps any item's def-id to its stability index.
520 pub stability: RefCell<stability::Index<'tcx>>,
522 /// Caches the results of trait selection. This cache is used
523 /// for things that do not have to do with the parameters in scope.
524 pub selection_cache: traits::SelectionCache<'tcx>,
526 /// Caches the results of trait evaluation. This cache is used
527 /// for things that do not have to do with the parameters in scope.
528 /// Merge this with `selection_cache`?
529 pub evaluation_cache: traits::EvaluationCache<'tcx>,
531 /// A set of predicates that have been fulfilled *somewhere*.
532 /// This is used to avoid duplicate work. Predicates are only
533 /// added to this set when they mention only "global" names
534 /// (i.e., no type or lifetime parameters).
535 pub fulfilled_predicates: RefCell<traits::GlobalFulfilledPredicates<'tcx>>,
537 /// Caches the representation hints for struct definitions.
538 repr_hint_cache: RefCell<DepTrackingMap<maps::ReprHints<'tcx>>>,
540 /// Maps Expr NodeId's to their constant qualification.
541 pub const_qualif_map: RefCell<NodeMap<middle::const_qualif::ConstQualif>>,
543 /// Caches CoerceUnsized kinds for impls on custom types.
544 pub custom_coerce_unsized_kinds: RefCell<DefIdMap<ty::adjustment::CustomCoerceUnsized>>,
546 /// Maps a cast expression to its kind. This is keyed on the
547 /// *from* expression of the cast, not the cast itself.
548 pub cast_kinds: RefCell<NodeMap<ty::cast::CastKind>>,
550 /// Maps Fn items to a collection of fragment infos.
552 /// The main goal is to identify data (each of which may be moved
553 /// or assigned) whose subparts are not moved nor assigned
554 /// (i.e. their state is *unfragmented*) and corresponding ast
555 /// nodes where the path to that data is moved or assigned.
557 /// In the long term, unfragmented values will have their
558 /// destructor entirely driven by a single stack-local drop-flag,
559 /// and their parents, the collections of the unfragmented values
560 /// (or more simply, "fragmented values"), are mapped to the
561 /// corresponding collections of stack-local drop-flags.
563 /// (However, in the short term that is not the case; e.g. some
564 /// unfragmented paths still need to be zeroed, namely when they
565 /// reference parent data from an outer scope that was not
566 /// entirely moved, and therefore that needs to be zeroed so that
567 /// we do not get double-drop when we hit the end of the parent
570 /// Also: currently the table solely holds keys for node-ids of
571 /// unfragmented values (see `FragmentInfo` enum definition), but
572 /// longer-term we will need to also store mappings from
573 /// fragmented data to the set of unfragmented pieces that
575 pub fragment_infos: RefCell<DefIdMap<Vec<ty::FragmentInfo>>>,
577 /// The definite name of the current crate after taking into account
578 /// attributes, commandline parameters, etc.
579 pub crate_name: Symbol,
581 /// Data layout specification for the current target.
582 pub data_layout: TargetDataLayout,
584 /// Cache for layouts computed from types.
585 pub layout_cache: RefCell<FxHashMap<Ty<'tcx>, &'tcx Layout>>,
587 /// Used to prevent layout from recursing too deeply.
588 pub layout_depth: Cell<usize>,
590 /// Map from function to the `#[derive]` mode that it's defining. Only used
591 /// by `proc-macro` crates.
592 pub derive_macros: RefCell<NodeMap<Symbol>>,
595 impl<'tcx> GlobalCtxt<'tcx> {
596 /// Get the global TyCtxt.
597 pub fn global_tcx<'a>(&'a self) -> TyCtxt<'a, 'tcx, 'tcx> {
600 interners: &self.global_interners
605 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
606 pub fn crate_name(self, cnum: CrateNum) -> Symbol {
607 if cnum == LOCAL_CRATE {
610 self.sess.cstore.crate_name(cnum)
614 pub fn original_crate_name(self, cnum: CrateNum) -> Symbol {
615 if cnum == LOCAL_CRATE {
616 self.crate_name.clone()
618 self.sess.cstore.original_crate_name(cnum)
622 pub fn crate_disambiguator(self, cnum: CrateNum) -> Symbol {
623 if cnum == LOCAL_CRATE {
624 self.sess.local_crate_disambiguator()
626 self.sess.cstore.crate_disambiguator(cnum)
630 pub fn retrace_path(self,
632 path_data: &[DisambiguatedDefPathData])
634 debug!("retrace_path(path={:?}, krate={:?})", path_data, self.crate_name(krate));
636 if krate == LOCAL_CRATE {
640 .retrace_path(path_data)
641 .map(|def_index| DefId { krate: krate, index: def_index })
643 self.sess.cstore.retrace_path(krate, path_data)
647 pub fn type_parameter_def(self,
649 -> ty::TypeParameterDef<'tcx>
651 self.ty_param_defs.borrow().get(&node_id).unwrap().clone()
654 pub fn alloc_generics(self, generics: ty::Generics<'gcx>)
655 -> &'gcx ty::Generics<'gcx> {
656 self.global_interners.arenas.generics.alloc(generics)
659 pub fn alloc_mir(self, mir: Mir<'gcx>) -> &'gcx RefCell<Mir<'gcx>> {
660 self.global_interners.arenas.mir.alloc(RefCell::new(mir))
663 pub fn alloc_trait_def(self, def: ty::TraitDef) -> &'gcx ty::TraitDef {
664 self.global_interners.arenas.trait_def.alloc(def)
667 pub fn alloc_adt_def(self,
670 variants: Vec<ty::VariantDef>)
671 -> &'gcx ty::AdtDef {
672 let def = ty::AdtDef::new(self, did, kind, variants);
673 self.global_interners.arenas.adt_def.alloc(def)
676 pub fn intern_stability(self, stab: attr::Stability) -> &'gcx attr::Stability {
677 if let Some(st) = self.global_interners.stability.borrow().get(&stab) {
681 let interned = self.global_interners.arenas.stability.alloc(stab);
682 if let Some(prev) = self.global_interners.stability
685 bug!("Tried to overwrite interned Stability: {:?}", prev)
690 pub fn intern_layout(self, layout: Layout) -> &'gcx Layout {
691 if let Some(layout) = self.global_interners.layout.borrow().get(&layout) {
695 let interned = self.global_interners.arenas.layout.alloc(layout);
696 if let Some(prev) = self.global_interners.layout
699 bug!("Tried to overwrite interned Layout: {:?}", prev)
704 pub fn store_free_region_map(self, id: NodeId, map: FreeRegionMap) {
705 if self.free_region_maps.borrow_mut().insert(id, map).is_some() {
706 bug!("Tried to overwrite interned FreeRegionMap for NodeId {:?}", id)
710 pub fn free_region_map(self, id: NodeId) -> FreeRegionMap {
711 self.free_region_maps.borrow()[&id].clone()
714 pub fn lift<T: ?Sized + Lift<'tcx>>(self, value: &T) -> Option<T::Lifted> {
715 value.lift_to_tcx(self)
718 /// Like lift, but only tries in the global tcx.
719 pub fn lift_to_global<T: ?Sized + Lift<'gcx>>(self, value: &T) -> Option<T::Lifted> {
720 value.lift_to_tcx(self.global_tcx())
723 /// Returns true if self is the same as self.global_tcx().
724 fn is_global(self) -> bool {
725 let local = self.interners as *const _;
726 let global = &self.global_interners as *const _;
727 local as usize == global as usize
730 /// Create a type context and call the closure with a `TyCtxt` reference
731 /// to the context. The closure enforces that the type context and any interned
732 /// value (types, substs, etc.) can only be used while `ty::tls` has a valid
733 /// reference to the context, to allow formatting values that need it.
734 pub fn create_and_enter<F, R>(s: &'tcx Session,
735 arenas: &'tcx CtxtArenas<'tcx>,
737 named_region_map: resolve_lifetime::NamedRegionMap,
738 map: ast_map::Map<'tcx>,
739 freevars: FreevarMap,
740 maybe_unused_trait_imports: NodeSet,
741 region_maps: RegionMaps,
742 lang_items: middle::lang_items::LanguageItems,
743 stability: stability::Index<'tcx>,
746 where F: for<'b> FnOnce(TyCtxt<'b, 'tcx, 'tcx>) -> R
748 let data_layout = TargetDataLayout::parse(s);
749 let interners = CtxtInterners::new(arenas);
750 let common_types = CommonTypes::new(&interners);
751 let dep_graph = map.dep_graph.clone();
752 let fulfilled_predicates = traits::GlobalFulfilledPredicates::new(dep_graph.clone());
753 tls::enter_global(GlobalCtxt {
754 specializes_cache: RefCell::new(traits::SpecializesCache::new()),
755 global_interners: interners,
756 dep_graph: dep_graph.clone(),
758 named_region_map: named_region_map,
759 region_maps: region_maps,
760 free_region_maps: RefCell::new(FxHashMap()),
761 item_variance_map: RefCell::new(DepTrackingMap::new(dep_graph.clone())),
762 variance_computed: Cell::new(false),
764 trait_map: trait_map,
765 tables: RefCell::new(Tables::empty()),
766 impl_trait_refs: RefCell::new(DepTrackingMap::new(dep_graph.clone())),
767 trait_defs: RefCell::new(DepTrackingMap::new(dep_graph.clone())),
768 adt_defs: RefCell::new(DepTrackingMap::new(dep_graph.clone())),
769 adt_sized_constraint: RefCell::new(DepTrackingMap::new(dep_graph.clone())),
770 generics: RefCell::new(DepTrackingMap::new(dep_graph.clone())),
771 predicates: RefCell::new(DepTrackingMap::new(dep_graph.clone())),
772 super_predicates: RefCell::new(DepTrackingMap::new(dep_graph.clone())),
773 fulfilled_predicates: RefCell::new(fulfilled_predicates),
775 mir_map: RefCell::new(DepTrackingMap::new(dep_graph.clone())),
776 freevars: RefCell::new(freevars),
777 maybe_unused_trait_imports: maybe_unused_trait_imports,
778 item_types: RefCell::new(DepTrackingMap::new(dep_graph.clone())),
779 rcache: RefCell::new(FxHashMap()),
780 tc_cache: RefCell::new(FxHashMap()),
781 associated_items: RefCell::new(DepTrackingMap::new(dep_graph.clone())),
782 associated_item_def_ids: RefCell::new(DepTrackingMap::new(dep_graph.clone())),
783 ty_param_defs: RefCell::new(NodeMap()),
784 normalized_cache: RefCell::new(FxHashMap()),
785 lang_items: lang_items,
786 inherent_impls: RefCell::new(DepTrackingMap::new(dep_graph.clone())),
787 used_unsafe: RefCell::new(NodeSet()),
788 used_mut_nodes: RefCell::new(NodeSet()),
789 used_trait_imports: RefCell::new(NodeSet()),
790 populated_external_types: RefCell::new(DefIdSet()),
791 populated_external_primitive_impls: RefCell::new(DefIdSet()),
792 extern_const_statics: RefCell::new(DefIdMap()),
793 extern_const_fns: RefCell::new(DefIdMap()),
794 stability: RefCell::new(stability),
795 selection_cache: traits::SelectionCache::new(),
796 evaluation_cache: traits::EvaluationCache::new(),
797 repr_hint_cache: RefCell::new(DepTrackingMap::new(dep_graph.clone())),
798 const_qualif_map: RefCell::new(NodeMap()),
799 custom_coerce_unsized_kinds: RefCell::new(DefIdMap()),
800 cast_kinds: RefCell::new(NodeMap()),
801 fragment_infos: RefCell::new(DefIdMap()),
802 crate_name: Symbol::intern(crate_name),
803 data_layout: data_layout,
804 layout_cache: RefCell::new(FxHashMap()),
805 layout_depth: Cell::new(0),
806 derive_macros: RefCell::new(NodeMap()),
811 impl<'gcx: 'tcx, 'tcx> GlobalCtxt<'gcx> {
812 /// Call the closure with a local `TyCtxt` using the given arenas.
813 pub fn enter_local<F, R>(&self, arenas: &'tcx CtxtArenas<'tcx>, f: F) -> R
814 where F: for<'a> FnOnce(TyCtxt<'a, 'gcx, 'tcx>) -> R
816 let interners = CtxtInterners::new(arenas);
817 tls::enter(self, &interners, f)
821 /// A trait implemented for all X<'a> types which can be safely and
822 /// efficiently converted to X<'tcx> as long as they are part of the
823 /// provided TyCtxt<'tcx>.
824 /// This can be done, for example, for Ty<'tcx> or &'tcx Substs<'tcx>
825 /// by looking them up in their respective interners.
827 /// However, this is still not the best implementation as it does
828 /// need to compare the components, even for interned values.
829 /// It would be more efficient if TypedArena provided a way to
830 /// determine whether the address is in the allocated range.
832 /// None is returned if the value or one of the components is not part
833 /// of the provided context.
834 /// For Ty, None can be returned if either the type interner doesn't
835 /// contain the TypeVariants key or if the address of the interned
836 /// pointer differs. The latter case is possible if a primitive type,
837 /// e.g. `()` or `u8`, was interned in a different context.
838 pub trait Lift<'tcx> {
840 fn lift_to_tcx<'a, 'gcx>(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Option<Self::Lifted>;
843 impl<'a, 'tcx> Lift<'tcx> for Ty<'a> {
844 type Lifted = Ty<'tcx>;
845 fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>) -> Option<Ty<'tcx>> {
846 if let Some(&Interned(ty)) = tcx.interners.type_.borrow().get(&self.sty) {
847 if *self as *const _ == ty as *const _ {
851 // Also try in the global tcx if we're not that.
852 if !tcx.is_global() {
853 self.lift_to_tcx(tcx.global_tcx())
860 impl<'a, 'tcx> Lift<'tcx> for &'a Substs<'a> {
861 type Lifted = &'tcx Substs<'tcx>;
862 fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>) -> Option<&'tcx Substs<'tcx>> {
864 return Some(Slice::empty());
866 if let Some(&Interned(substs)) = tcx.interners.substs.borrow().get(&self[..]) {
867 if *self as *const _ == substs as *const _ {
871 // Also try in the global tcx if we're not that.
872 if !tcx.is_global() {
873 self.lift_to_tcx(tcx.global_tcx())
880 impl<'a, 'tcx> Lift<'tcx> for &'a Region {
881 type Lifted = &'tcx Region;
882 fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>) -> Option<&'tcx Region> {
883 if let Some(&Interned(region)) = tcx.interners.region.borrow().get(*self) {
884 if *self as *const _ == region as *const _ {
888 // Also try in the global tcx if we're not that.
889 if !tcx.is_global() {
890 self.lift_to_tcx(tcx.global_tcx())
897 impl<'a, 'tcx> Lift<'tcx> for &'a Slice<Ty<'a>> {
898 type Lifted = &'tcx Slice<Ty<'tcx>>;
899 fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>)
900 -> Option<&'tcx Slice<Ty<'tcx>>> {
902 return Some(Slice::empty());
904 if let Some(&Interned(list)) = tcx.interners.type_list.borrow().get(&self[..]) {
905 if *self as *const _ == list as *const _ {
909 // Also try in the global tcx if we're not that.
910 if !tcx.is_global() {
911 self.lift_to_tcx(tcx.global_tcx())
918 impl<'a, 'tcx> Lift<'tcx> for &'a Slice<ExistentialPredicate<'a>> {
919 type Lifted = &'tcx Slice<ExistentialPredicate<'tcx>>;
920 fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>)
921 -> Option<&'tcx Slice<ExistentialPredicate<'tcx>>> {
923 return Some(Slice::empty());
925 if let Some(&Interned(eps)) = tcx.interners.existential_predicates.borrow().get(&self[..]) {
926 if *self as *const _ == eps as *const _ {
930 // Also try in the global tcx if we're not that.
931 if !tcx.is_global() {
932 self.lift_to_tcx(tcx.global_tcx())
939 impl<'a, 'tcx> Lift<'tcx> for &'a BareFnTy<'a> {
940 type Lifted = &'tcx BareFnTy<'tcx>;
941 fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>)
942 -> Option<&'tcx BareFnTy<'tcx>> {
943 if let Some(&Interned(fty)) = tcx.interners.bare_fn.borrow().get(*self) {
944 if *self as *const _ == fty as *const _ {
948 // Also try in the global tcx if we're not that.
949 if !tcx.is_global() {
950 self.lift_to_tcx(tcx.global_tcx())
959 use super::{CtxtInterners, GlobalCtxt, TyCtxt};
965 /// Marker types used for the scoped TLS slot.
966 /// The type context cannot be used directly because the scoped TLS
967 /// in libstd doesn't allow types generic over lifetimes.
968 enum ThreadLocalGlobalCtxt {}
969 enum ThreadLocalInterners {}
972 static TLS_TCX: Cell<Option<(*const ThreadLocalGlobalCtxt,
973 *const ThreadLocalInterners)>> = Cell::new(None)
976 fn span_debug(span: syntax_pos::Span, f: &mut fmt::Formatter) -> fmt::Result {
978 write!(f, "{}", tcx.sess.codemap().span_to_string(span))
982 pub fn enter_global<'gcx, F, R>(gcx: GlobalCtxt<'gcx>, f: F) -> R
983 where F: for<'a> FnOnce(TyCtxt<'a, 'gcx, 'gcx>) -> R
985 syntax_pos::SPAN_DEBUG.with(|span_dbg| {
986 let original_span_debug = span_dbg.get();
987 span_dbg.set(span_debug);
988 let result = enter(&gcx, &gcx.global_interners, f);
989 span_dbg.set(original_span_debug);
994 pub fn enter<'a, 'gcx: 'tcx, 'tcx, F, R>(gcx: &'a GlobalCtxt<'gcx>,
995 interners: &'a CtxtInterners<'tcx>,
997 where F: FnOnce(TyCtxt<'a, 'gcx, 'tcx>) -> R
999 let gcx_ptr = gcx as *const _ as *const ThreadLocalGlobalCtxt;
1000 let interners_ptr = interners as *const _ as *const ThreadLocalInterners;
1001 TLS_TCX.with(|tls| {
1002 let prev = tls.get();
1003 tls.set(Some((gcx_ptr, interners_ptr)));
1004 let ret = f(TyCtxt {
1006 interners: interners
1013 pub fn with<F, R>(f: F) -> R
1014 where F: for<'a, 'gcx, 'tcx> FnOnce(TyCtxt<'a, 'gcx, 'tcx>) -> R
1016 TLS_TCX.with(|tcx| {
1017 let (gcx, interners) = tcx.get().unwrap();
1018 let gcx = unsafe { &*(gcx as *const GlobalCtxt) };
1019 let interners = unsafe { &*(interners as *const CtxtInterners) };
1022 interners: interners
1027 pub fn with_opt<F, R>(f: F) -> R
1028 where F: for<'a, 'gcx, 'tcx> FnOnce(Option<TyCtxt<'a, 'gcx, 'tcx>>) -> R
1030 if TLS_TCX.with(|tcx| tcx.get().is_some()) {
1031 with(|v| f(Some(v)))
1038 macro_rules! sty_debug_print {
1039 ($ctxt: expr, $($variant: ident),*) => {{
1040 // curious inner module to allow variant names to be used as
1042 #[allow(non_snake_case)]
1044 use ty::{self, TyCtxt};
1045 use ty::context::Interned;
1047 #[derive(Copy, Clone)]
1050 region_infer: usize,
1055 pub fn go(tcx: TyCtxt) {
1056 let mut total = DebugStat {
1058 region_infer: 0, ty_infer: 0, both_infer: 0,
1060 $(let mut $variant = total;)*
1063 for &Interned(t) in tcx.interners.type_.borrow().iter() {
1064 let variant = match t.sty {
1065 ty::TyBool | ty::TyChar | ty::TyInt(..) | ty::TyUint(..) |
1066 ty::TyFloat(..) | ty::TyStr | ty::TyNever => continue,
1067 ty::TyError => /* unimportant */ continue,
1068 $(ty::$variant(..) => &mut $variant,)*
1070 let region = t.flags.get().intersects(ty::TypeFlags::HAS_RE_INFER);
1071 let ty = t.flags.get().intersects(ty::TypeFlags::HAS_TY_INFER);
1075 if region { total.region_infer += 1; variant.region_infer += 1 }
1076 if ty { total.ty_infer += 1; variant.ty_infer += 1 }
1077 if region && ty { total.both_infer += 1; variant.both_infer += 1 }
1079 println!("Ty interner total ty region both");
1080 $(println!(" {:18}: {uses:6} {usespc:4.1}%, \
1081 {ty:4.1}% {region:5.1}% {both:4.1}%",
1082 stringify!($variant),
1083 uses = $variant.total,
1084 usespc = $variant.total as f64 * 100.0 / total.total as f64,
1085 ty = $variant.ty_infer as f64 * 100.0 / total.total as f64,
1086 region = $variant.region_infer as f64 * 100.0 / total.total as f64,
1087 both = $variant.both_infer as f64 * 100.0 / total.total as f64);
1089 println!(" total {uses:6} \
1090 {ty:4.1}% {region:5.1}% {both:4.1}%",
1092 ty = total.ty_infer as f64 * 100.0 / total.total as f64,
1093 region = total.region_infer as f64 * 100.0 / total.total as f64,
1094 both = total.both_infer as f64 * 100.0 / total.total as f64)
1102 impl<'a, 'tcx> TyCtxt<'a, 'tcx, 'tcx> {
1103 pub fn print_debug_stats(self) {
1106 TyAdt, TyBox, TyArray, TySlice, TyRawPtr, TyRef, TyFnDef, TyFnPtr,
1107 TyDynamic, TyClosure, TyTuple, TyParam, TyInfer, TyProjection, TyAnon);
1109 println!("Substs interner: #{}", self.interners.substs.borrow().len());
1110 println!("BareFnTy interner: #{}", self.interners.bare_fn.borrow().len());
1111 println!("Region interner: #{}", self.interners.region.borrow().len());
1112 println!("Stability interner: #{}", self.interners.stability.borrow().len());
1113 println!("Layout interner: #{}", self.interners.layout.borrow().len());
1118 /// An entry in an interner.
1119 struct Interned<'tcx, T: 'tcx+?Sized>(&'tcx T);
1121 // NB: An Interned<Ty> compares and hashes as a sty.
1122 impl<'tcx> PartialEq for Interned<'tcx, TyS<'tcx>> {
1123 fn eq(&self, other: &Interned<'tcx, TyS<'tcx>>) -> bool {
1124 self.0.sty == other.0.sty
1128 impl<'tcx> Eq for Interned<'tcx, TyS<'tcx>> {}
1130 impl<'tcx> Hash for Interned<'tcx, TyS<'tcx>> {
1131 fn hash<H: Hasher>(&self, s: &mut H) {
1136 impl<'tcx: 'lcx, 'lcx> Borrow<TypeVariants<'lcx>> for Interned<'tcx, TyS<'tcx>> {
1137 fn borrow<'a>(&'a self) -> &'a TypeVariants<'lcx> {
1142 // NB: An Interned<Slice<T>> compares and hashes as its elements.
1143 impl<'tcx, T: PartialEq> PartialEq for Interned<'tcx, Slice<T>> {
1144 fn eq(&self, other: &Interned<'tcx, Slice<T>>) -> bool {
1145 self.0[..] == other.0[..]
1149 impl<'tcx, T: Eq> Eq for Interned<'tcx, Slice<T>> {}
1151 impl<'tcx, T: Hash> Hash for Interned<'tcx, Slice<T>> {
1152 fn hash<H: Hasher>(&self, s: &mut H) {
1157 impl<'tcx: 'lcx, 'lcx> Borrow<[Ty<'lcx>]> for Interned<'tcx, Slice<Ty<'tcx>>> {
1158 fn borrow<'a>(&'a self) -> &'a [Ty<'lcx>] {
1163 impl<'tcx: 'lcx, 'lcx> Borrow<[Kind<'lcx>]> for Interned<'tcx, Substs<'tcx>> {
1164 fn borrow<'a>(&'a self) -> &'a [Kind<'lcx>] {
1169 impl<'tcx: 'lcx, 'lcx> Borrow<BareFnTy<'lcx>> for Interned<'tcx, BareFnTy<'tcx>> {
1170 fn borrow<'a>(&'a self) -> &'a BareFnTy<'lcx> {
1175 impl<'tcx> Borrow<Region> for Interned<'tcx, Region> {
1176 fn borrow<'a>(&'a self) -> &'a Region {
1181 impl<'tcx: 'lcx, 'lcx> Borrow<[ExistentialPredicate<'lcx>]>
1182 for Interned<'tcx, Slice<ExistentialPredicate<'tcx>>> {
1183 fn borrow<'a>(&'a self) -> &'a [ExistentialPredicate<'lcx>] {
1188 macro_rules! intern_method {
1189 ($lt_tcx:tt, $name:ident: $method:ident($alloc:ty,
1190 $alloc_method:ident,
1193 $needs_infer:expr) -> $ty:ty) => {
1194 impl<'a, 'gcx, $lt_tcx> TyCtxt<'a, 'gcx, $lt_tcx> {
1195 pub fn $method(self, v: $alloc) -> &$lt_tcx $ty {
1197 let key = ($alloc_to_key)(&v);
1198 if let Some(i) = self.interners.$name.borrow().get(key) {
1201 if !self.is_global() {
1202 if let Some(i) = self.global_interners.$name.borrow().get(key) {
1208 // HACK(eddyb) Depend on flags being accurate to
1209 // determine that all contents are in the global tcx.
1210 // See comments on Lift for why we can't use that.
1211 if !($needs_infer)(&v) {
1212 if !self.is_global() {
1216 let i = ($alloc_to_ret)(self.global_interners.arenas.$name
1218 self.global_interners.$name.borrow_mut().insert(Interned(i));
1222 // Make sure we don't end up with inference
1223 // types/regions in the global tcx.
1224 if self.is_global() {
1225 bug!("Attempted to intern `{:?}` which contains \
1226 inference types/regions in the global type context",
1231 let i = ($alloc_to_ret)(self.interners.arenas.$name.$alloc_method(v));
1232 self.interners.$name.borrow_mut().insert(Interned(i));
1239 macro_rules! direct_interners {
1240 ($lt_tcx:tt, $($name:ident: $method:ident($needs_infer:expr) -> $ty:ty),+) => {
1241 $(impl<$lt_tcx> PartialEq for Interned<$lt_tcx, $ty> {
1242 fn eq(&self, other: &Self) -> bool {
1247 impl<$lt_tcx> Eq for Interned<$lt_tcx, $ty> {}
1249 impl<$lt_tcx> Hash for Interned<$lt_tcx, $ty> {
1250 fn hash<H: Hasher>(&self, s: &mut H) {
1255 intern_method!($lt_tcx, $name: $method($ty, alloc, |x| x, |x| x, $needs_infer) -> $ty);)+
1259 fn keep_local<'tcx, T: ty::TypeFoldable<'tcx>>(x: &T) -> bool {
1260 x.has_type_flags(ty::TypeFlags::KEEP_IN_LOCAL_TCX)
1263 direct_interners!('tcx,
1264 bare_fn: mk_bare_fn(|fty: &BareFnTy| {
1265 keep_local(&fty.sig)
1266 }) -> BareFnTy<'tcx>,
1267 region: mk_region(|r| {
1269 &ty::ReVar(_) | &ty::ReSkolemized(..) => true,
1275 macro_rules! slice_interners {
1276 ($($field:ident: $method:ident($ty:ident)),+) => (
1277 $(intern_method!('tcx, $field: $method(&[$ty<'tcx>], alloc_slice, Deref::deref,
1278 |xs: &[$ty]| -> &Slice<$ty> {
1279 unsafe { mem::transmute(xs) }
1280 }, |xs: &[$ty]| xs.iter().any(keep_local)) -> Slice<$ty<'tcx>>);)+
1285 existential_predicates: _intern_existential_predicates(ExistentialPredicate),
1286 type_list: _intern_type_list(Ty),
1287 substs: _intern_substs(Kind)
1290 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
1291 /// Create an unsafe fn ty based on a safe fn ty.
1292 pub fn safe_to_unsafe_fn_ty(self, bare_fn: &BareFnTy<'tcx>) -> Ty<'tcx> {
1293 assert_eq!(bare_fn.unsafety, hir::Unsafety::Normal);
1294 self.mk_fn_ptr(self.mk_bare_fn(ty::BareFnTy {
1295 unsafety: hir::Unsafety::Unsafe,
1297 sig: bare_fn.sig.clone()
1301 // Interns a type/name combination, stores the resulting box in cx.interners,
1302 // and returns the box as cast to an unsafe ptr (see comments for Ty above).
1303 pub fn mk_ty(self, st: TypeVariants<'tcx>) -> Ty<'tcx> {
1304 let global_interners = if !self.is_global() {
1305 Some(&self.global_interners)
1309 self.interners.intern_ty(st, global_interners)
1312 pub fn mk_mach_int(self, tm: ast::IntTy) -> Ty<'tcx> {
1314 ast::IntTy::Is => self.types.isize,
1315 ast::IntTy::I8 => self.types.i8,
1316 ast::IntTy::I16 => self.types.i16,
1317 ast::IntTy::I32 => self.types.i32,
1318 ast::IntTy::I64 => self.types.i64,
1322 pub fn mk_mach_uint(self, tm: ast::UintTy) -> Ty<'tcx> {
1324 ast::UintTy::Us => self.types.usize,
1325 ast::UintTy::U8 => self.types.u8,
1326 ast::UintTy::U16 => self.types.u16,
1327 ast::UintTy::U32 => self.types.u32,
1328 ast::UintTy::U64 => self.types.u64,
1332 pub fn mk_mach_float(self, tm: ast::FloatTy) -> Ty<'tcx> {
1334 ast::FloatTy::F32 => self.types.f32,
1335 ast::FloatTy::F64 => self.types.f64,
1339 pub fn mk_str(self) -> Ty<'tcx> {
1343 pub fn mk_static_str(self) -> Ty<'tcx> {
1344 self.mk_imm_ref(self.mk_region(ty::ReStatic), self.mk_str())
1347 pub fn mk_adt(self, def: &'tcx AdtDef, substs: &'tcx Substs<'tcx>) -> Ty<'tcx> {
1348 // take a copy of substs so that we own the vectors inside
1349 self.mk_ty(TyAdt(def, substs))
1352 pub fn mk_box(self, ty: Ty<'tcx>) -> Ty<'tcx> {
1353 self.mk_ty(TyBox(ty))
1356 pub fn mk_ptr(self, tm: TypeAndMut<'tcx>) -> Ty<'tcx> {
1357 self.mk_ty(TyRawPtr(tm))
1360 pub fn mk_ref(self, r: &'tcx Region, tm: TypeAndMut<'tcx>) -> Ty<'tcx> {
1361 self.mk_ty(TyRef(r, tm))
1364 pub fn mk_mut_ref(self, r: &'tcx Region, ty: Ty<'tcx>) -> Ty<'tcx> {
1365 self.mk_ref(r, TypeAndMut {ty: ty, mutbl: hir::MutMutable})
1368 pub fn mk_imm_ref(self, r: &'tcx Region, ty: Ty<'tcx>) -> Ty<'tcx> {
1369 self.mk_ref(r, TypeAndMut {ty: ty, mutbl: hir::MutImmutable})
1372 pub fn mk_mut_ptr(self, ty: Ty<'tcx>) -> Ty<'tcx> {
1373 self.mk_ptr(TypeAndMut {ty: ty, mutbl: hir::MutMutable})
1376 pub fn mk_imm_ptr(self, ty: Ty<'tcx>) -> Ty<'tcx> {
1377 self.mk_ptr(TypeAndMut {ty: ty, mutbl: hir::MutImmutable})
1380 pub fn mk_nil_ptr(self) -> Ty<'tcx> {
1381 self.mk_imm_ptr(self.mk_nil())
1384 pub fn mk_array(self, ty: Ty<'tcx>, n: usize) -> Ty<'tcx> {
1385 self.mk_ty(TyArray(ty, n))
1388 pub fn mk_slice(self, ty: Ty<'tcx>) -> Ty<'tcx> {
1389 self.mk_ty(TySlice(ty))
1392 pub fn intern_tup(self, ts: &[Ty<'tcx>]) -> Ty<'tcx> {
1393 self.mk_ty(TyTuple(self.intern_type_list(ts)))
1396 pub fn mk_tup<I: InternAs<[Ty<'tcx>], Ty<'tcx>>>(self, iter: I) -> I::Output {
1397 iter.intern_with(|ts| self.mk_ty(TyTuple(self.intern_type_list(ts))))
1400 pub fn mk_nil(self) -> Ty<'tcx> {
1401 self.intern_tup(&[])
1404 pub fn mk_diverging_default(self) -> Ty<'tcx> {
1405 if self.sess.features.borrow().never_type {
1412 pub fn mk_bool(self) -> Ty<'tcx> {
1416 pub fn mk_fn_def(self, def_id: DefId,
1417 substs: &'tcx Substs<'tcx>,
1418 fty: &'tcx BareFnTy<'tcx>) -> Ty<'tcx> {
1419 self.mk_ty(TyFnDef(def_id, substs, fty))
1422 pub fn mk_fn_ptr(self, fty: &'tcx BareFnTy<'tcx>) -> Ty<'tcx> {
1423 self.mk_ty(TyFnPtr(fty))
1428 obj: ty::Binder<&'tcx Slice<ExistentialPredicate<'tcx>>>,
1429 reg: &'tcx ty::Region
1431 self.mk_ty(TyDynamic(obj, reg))
1434 pub fn mk_projection(self,
1435 trait_ref: TraitRef<'tcx>,
1438 // take a copy of substs so that we own the vectors inside
1439 let inner = ProjectionTy { trait_ref: trait_ref, item_name: item_name };
1440 self.mk_ty(TyProjection(inner))
1443 pub fn mk_closure(self,
1445 substs: &'tcx Substs<'tcx>)
1447 self.mk_closure_from_closure_substs(closure_id, ClosureSubsts {
1452 pub fn mk_closure_from_closure_substs(self,
1454 closure_substs: ClosureSubsts<'tcx>)
1456 self.mk_ty(TyClosure(closure_id, closure_substs))
1459 pub fn mk_var(self, v: TyVid) -> Ty<'tcx> {
1460 self.mk_infer(TyVar(v))
1463 pub fn mk_int_var(self, v: IntVid) -> Ty<'tcx> {
1464 self.mk_infer(IntVar(v))
1467 pub fn mk_float_var(self, v: FloatVid) -> Ty<'tcx> {
1468 self.mk_infer(FloatVar(v))
1471 pub fn mk_infer(self, it: InferTy) -> Ty<'tcx> {
1472 self.mk_ty(TyInfer(it))
1475 pub fn mk_param(self,
1477 name: Name) -> Ty<'tcx> {
1478 self.mk_ty(TyParam(ParamTy { idx: index, name: name }))
1481 pub fn mk_self_type(self) -> Ty<'tcx> {
1482 self.mk_param(0, keywords::SelfType.name())
1485 pub fn mk_param_from_def(self, def: &ty::TypeParameterDef) -> Ty<'tcx> {
1486 self.mk_param(def.index, def.name)
1489 pub fn mk_anon(self, def_id: DefId, substs: &'tcx Substs<'tcx>) -> Ty<'tcx> {
1490 self.mk_ty(TyAnon(def_id, substs))
1493 pub fn intern_existential_predicates(self, eps: &[ExistentialPredicate<'tcx>])
1494 -> &'tcx Slice<ExistentialPredicate<'tcx>> {
1495 assert!(!eps.is_empty());
1496 assert!(eps.windows(2).all(|w| w[0].cmp(self, &w[1]) != Ordering::Greater));
1497 self._intern_existential_predicates(eps)
1500 pub fn intern_type_list(self, ts: &[Ty<'tcx>]) -> &'tcx Slice<Ty<'tcx>> {
1504 self._intern_type_list(ts)
1508 pub fn intern_substs(self, ts: &[Kind<'tcx>]) -> &'tcx Slice<Kind<'tcx>> {
1512 self._intern_substs(ts)
1516 pub fn mk_fn_sig<I>(self, inputs: I, output: I::Item, variadic: bool)
1517 -> <I::Item as InternIteratorElement<Ty<'tcx>, ty::FnSig<'tcx>>>::Output
1519 I::Item: InternIteratorElement<Ty<'tcx>, ty::FnSig<'tcx>>
1521 inputs.chain(iter::once(output)).intern_with(|xs| ty::FnSig {
1522 inputs_and_output: self.intern_type_list(xs),
1527 pub fn mk_existential_predicates<I: InternAs<[ExistentialPredicate<'tcx>],
1528 &'tcx Slice<ExistentialPredicate<'tcx>>>>(self, iter: I)
1530 iter.intern_with(|xs| self.intern_existential_predicates(xs))
1533 pub fn mk_type_list<I: InternAs<[Ty<'tcx>],
1534 &'tcx Slice<Ty<'tcx>>>>(self, iter: I) -> I::Output {
1535 iter.intern_with(|xs| self.intern_type_list(xs))
1538 pub fn mk_substs<I: InternAs<[Kind<'tcx>],
1539 &'tcx Slice<Kind<'tcx>>>>(self, iter: I) -> I::Output {
1540 iter.intern_with(|xs| self.intern_substs(xs))
1543 pub fn mk_substs_trait(self,
1546 -> &'tcx Substs<'tcx>
1548 self.mk_substs(iter::once(s).chain(t.into_iter().cloned()).map(Kind::from))
1551 /// Obtain the representation annotation for a struct definition.
1552 pub fn lookup_repr_hints(self, did: DefId) -> Rc<Vec<attr::ReprAttr>> {
1553 self.repr_hint_cache.memoize(did, || {
1554 Rc::new(self.get_attrs(did).iter().flat_map(|meta| {
1555 attr::find_repr_attrs(self.sess.diagnostic(), meta).into_iter()
1561 pub trait InternAs<T: ?Sized, R> {
1563 fn intern_with<F>(self, F) -> Self::Output
1564 where F: FnOnce(&T) -> R;
1567 impl<I, T, R, E> InternAs<[T], R> for I
1568 where E: InternIteratorElement<T, R>,
1569 I: Iterator<Item=E> {
1570 type Output = E::Output;
1571 fn intern_with<F>(self, f: F) -> Self::Output
1572 where F: FnOnce(&[T]) -> R {
1573 E::intern_with(self, f)
1577 pub trait InternIteratorElement<T, R>: Sized {
1579 fn intern_with<I: Iterator<Item=Self>, F: FnOnce(&[T]) -> R>(iter: I, f: F) -> Self::Output;
1582 impl<T, R> InternIteratorElement<T, R> for T {
1584 fn intern_with<I: Iterator<Item=Self>, F: FnOnce(&[T]) -> R>(iter: I, f: F) -> Self::Output {
1585 f(&iter.collect::<AccumulateVec<[_; 8]>>())
1589 impl<T, R, E> InternIteratorElement<T, R> for Result<T, E> {
1590 type Output = Result<R, E>;
1591 fn intern_with<I: Iterator<Item=Self>, F: FnOnce(&[T]) -> R>(iter: I, f: F) -> Self::Output {
1592 Ok(f(&iter.collect::<Result<AccumulateVec<[_; 8]>, _>>()?))