1 //! Type context book-keeping.
3 use crate::arena::Arena;
4 use crate::dep_graph::DepGraph;
5 use crate::dep_graph::{self, DepNode, DepConstructor};
6 use crate::session::Session;
7 use crate::session::config::{BorrowckMode, OutputFilenames};
8 use crate::session::config::CrateType;
10 use crate::hir::{self, TraitCandidate, HirId, ItemKind, ItemLocalId, Node};
11 use crate::hir::def::{Res, DefKind, Export};
12 use crate::hir::def_id::{CrateNum, DefId, DefIndex, LOCAL_CRATE};
13 use crate::hir::map as hir_map;
14 use crate::hir::map::DefPathHash;
15 use crate::lint::{self, Lint};
16 use crate::ich::{StableHashingContext, NodeIdHashingMode};
17 use crate::infer::canonical::{Canonical, CanonicalVarInfo, CanonicalVarInfos};
18 use crate::infer::outlives::free_region_map::FreeRegionMap;
19 use crate::middle::cstore::CrateStoreDyn;
20 use crate::middle::cstore::EncodedMetadata;
21 use crate::middle::lang_items;
22 use crate::middle::resolve_lifetime::{self, ObjectLifetimeDefault};
23 use crate::middle::stability;
24 use crate::mir::{Body, interpret, ProjectionKind, Promoted};
25 use crate::mir::interpret::{ConstValue, Allocation, Scalar};
26 use crate::ty::subst::{GenericArg, InternalSubsts, SubstsRef, Subst};
27 use crate::ty::ReprOptions;
29 use crate::traits::{Clause, Clauses, GoalKind, Goal, Goals};
30 use crate::ty::{self, DefIdTree, Ty, TypeAndMut};
31 use crate::ty::{TyS, TyKind, List};
32 use crate::ty::{AdtKind, AdtDef, ClosureSubsts, GeneratorSubsts, Region, Const};
33 use crate::ty::{PolyFnSig, InferTy, ParamTy, ProjectionTy, ExistentialPredicate, Predicate};
34 use crate::ty::RegionKind;
35 use crate::ty::{TyVar, TyVid, IntVar, IntVid, FloatVar, FloatVid, ConstVid};
36 use crate::ty::TyKind::*;
37 use crate::ty::{InferConst, ParamConst};
38 use crate::ty::GenericParamDefKind;
39 use crate::ty::layout::{LayoutDetails, TargetDataLayout, VariantIdx};
41 use crate::ty::steal::Steal;
42 use crate::ty::subst::{UserSubsts, GenericArgKind};
43 use crate::ty::{BoundVar, BindingMode};
44 use crate::ty::CanonicalPolyFnSig;
45 use crate::util::common::ErrorReported;
46 use crate::util::nodemap::{DefIdMap, DefIdSet, ItemLocalMap, ItemLocalSet};
47 use crate::util::nodemap::{FxHashMap, FxHashSet};
49 use errors::DiagnosticBuilder;
50 use arena::SyncDroplessArena;
51 use smallvec::SmallVec;
52 use rustc_data_structures::stable_hasher::{
53 HashStable, StableHasher, StableVec, hash_stable_hashmap,
55 use rustc_data_structures::indexed_vec::{Idx, IndexVec};
56 use rustc_data_structures::sharded::ShardedHashMap;
57 use rustc_data_structures::sync::{Lrc, Lock, WorkerLocal};
59 use std::borrow::Borrow;
60 use std::cmp::Ordering;
61 use std::collections::hash_map::{self, Entry};
62 use std::hash::{Hash, Hasher};
65 use std::ops::{Deref, Bound};
68 use rustc_target::spec::abi;
69 use rustc_macros::HashStable;
72 use syntax::source_map::MultiSpan;
73 use syntax::feature_gate;
74 use syntax::symbol::{Symbol, InternedString, kw, sym};
77 pub struct AllArenas {
78 pub interner: SyncDroplessArena,
82 pub fn new() -> Self {
84 interner: SyncDroplessArena::default(),
89 type InternedSet<'tcx, T> = ShardedHashMap<Interned<'tcx, T>, ()>;
91 pub struct CtxtInterners<'tcx> {
92 /// The arena that types, regions, etc. are allocated from.
93 arena: &'tcx SyncDroplessArena,
95 /// Specifically use a speedy hash algorithm for these hash sets, since
96 /// they're accessed quite often.
97 type_: InternedSet<'tcx, TyS<'tcx>>,
98 type_list: InternedSet<'tcx, List<Ty<'tcx>>>,
99 substs: InternedSet<'tcx, InternalSubsts<'tcx>>,
100 canonical_var_infos: InternedSet<'tcx, List<CanonicalVarInfo>>,
101 region: InternedSet<'tcx, RegionKind>,
102 existential_predicates: InternedSet<'tcx, List<ExistentialPredicate<'tcx>>>,
103 predicates: InternedSet<'tcx, List<Predicate<'tcx>>>,
104 clauses: InternedSet<'tcx, List<Clause<'tcx>>>,
105 goal: InternedSet<'tcx, GoalKind<'tcx>>,
106 goal_list: InternedSet<'tcx, List<Goal<'tcx>>>,
107 projs: InternedSet<'tcx, List<ProjectionKind>>,
108 const_: InternedSet<'tcx, Const<'tcx>>,
111 impl<'tcx> CtxtInterners<'tcx> {
112 fn new(arena: &'tcx SyncDroplessArena) -> CtxtInterners<'tcx> {
115 type_: Default::default(),
116 type_list: Default::default(),
117 substs: Default::default(),
118 region: Default::default(),
119 existential_predicates: Default::default(),
120 canonical_var_infos: Default::default(),
121 predicates: Default::default(),
122 clauses: Default::default(),
123 goal: Default::default(),
124 goal_list: Default::default(),
125 projs: Default::default(),
126 const_: Default::default(),
131 #[allow(rustc::usage_of_ty_tykind)]
136 self.type_.intern(kind, |kind| {
137 let flags = super::flags::FlagComputation::for_kind(&kind);
139 let ty_struct = TyS {
142 outer_exclusive_binder: flags.outer_exclusive_binder,
145 Interned(self.arena.alloc(ty_struct))
150 pub struct Common<'tcx> {
151 pub empty_predicates: ty::GenericPredicates<'tcx>,
154 pub struct CommonTypes<'tcx> {
173 pub self_param: Ty<'tcx>,
176 /// Dummy type used for the `Self` of a `TraitRef` created for converting
177 /// a trait object, and which gets removed in `ExistentialTraitRef`.
178 /// This type must not appear anywhere in other converted types.
179 pub trait_object_dummy_self: Ty<'tcx>,
182 pub struct CommonLifetimes<'tcx> {
183 pub re_empty: Region<'tcx>,
184 pub re_static: Region<'tcx>,
185 pub re_erased: Region<'tcx>,
188 pub struct CommonConsts<'tcx> {
189 pub err: &'tcx Const<'tcx>,
192 pub struct LocalTableInContext<'a, V> {
193 local_id_root: Option<DefId>,
194 data: &'a ItemLocalMap<V>
197 /// Validate that the given HirId (respectively its `local_id` part) can be
198 /// safely used as a key in the tables of a TypeckTable. For that to be
199 /// the case, the HirId must have the same `owner` as all the other IDs in
200 /// this table (signified by `local_id_root`). Otherwise the HirId
201 /// would be in a different frame of reference and using its `local_id`
202 /// would result in lookup errors, or worse, in silently wrong data being
204 fn validate_hir_id_for_typeck_tables(local_id_root: Option<DefId>,
207 if let Some(local_id_root) = local_id_root {
208 if hir_id.owner != local_id_root.index {
209 ty::tls::with(|tcx| {
210 bug!("node {} with HirId::owner {:?} cannot be placed in \
211 TypeckTables with local_id_root {:?}",
212 tcx.hir().node_to_string(hir_id),
213 DefId::local(hir_id.owner),
218 // We use "Null Object" TypeckTables in some of the analysis passes.
219 // These are just expected to be empty and their `local_id_root` is
220 // `None`. Therefore we cannot verify whether a given `HirId` would
221 // be a valid key for the given table. Instead we make sure that
222 // nobody tries to write to such a Null Object table.
224 bug!("access to invalid TypeckTables")
229 impl<'a, V> LocalTableInContext<'a, V> {
230 pub fn contains_key(&self, id: hir::HirId) -> bool {
231 validate_hir_id_for_typeck_tables(self.local_id_root, id, false);
232 self.data.contains_key(&id.local_id)
235 pub fn get(&self, id: hir::HirId) -> Option<&V> {
236 validate_hir_id_for_typeck_tables(self.local_id_root, id, false);
237 self.data.get(&id.local_id)
240 pub fn iter(&self) -> hash_map::Iter<'_, hir::ItemLocalId, V> {
245 impl<'a, V> ::std::ops::Index<hir::HirId> for LocalTableInContext<'a, V> {
248 fn index(&self, key: hir::HirId) -> &V {
249 self.get(key).expect("LocalTableInContext: key not found")
253 pub struct LocalTableInContextMut<'a, V> {
254 local_id_root: Option<DefId>,
255 data: &'a mut ItemLocalMap<V>
258 impl<'a, V> LocalTableInContextMut<'a, V> {
259 pub fn get_mut(&mut self, id: hir::HirId) -> Option<&mut V> {
260 validate_hir_id_for_typeck_tables(self.local_id_root, id, true);
261 self.data.get_mut(&id.local_id)
264 pub fn entry(&mut self, id: hir::HirId) -> Entry<'_, hir::ItemLocalId, V> {
265 validate_hir_id_for_typeck_tables(self.local_id_root, id, true);
266 self.data.entry(id.local_id)
269 pub fn insert(&mut self, id: hir::HirId, val: V) -> Option<V> {
270 validate_hir_id_for_typeck_tables(self.local_id_root, id, true);
271 self.data.insert(id.local_id, val)
274 pub fn remove(&mut self, id: hir::HirId) -> Option<V> {
275 validate_hir_id_for_typeck_tables(self.local_id_root, id, true);
276 self.data.remove(&id.local_id)
280 /// All information necessary to validate and reveal an `impl Trait`.
281 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
282 pub struct ResolvedOpaqueTy<'tcx> {
283 /// The revealed type as seen by this function.
284 pub concrete_type: Ty<'tcx>,
285 /// Generic parameters on the opaque type as passed by this function.
286 /// For `type Foo<A, B> = impl Bar<A, B>; fn foo<T, U>() -> Foo<T, U> { .. }`
287 /// this is `[T, U]`, not `[A, B]`.
288 pub substs: SubstsRef<'tcx>,
291 #[derive(RustcEncodable, RustcDecodable, Debug)]
292 pub struct TypeckTables<'tcx> {
293 /// The HirId::owner all ItemLocalIds in this table are relative to.
294 pub local_id_root: Option<DefId>,
296 /// Resolved definitions for `<T>::X` associated paths and
297 /// method calls, including those of overloaded operators.
298 type_dependent_defs: ItemLocalMap<Result<(DefKind, DefId), ErrorReported>>,
300 /// Resolved field indices for field accesses in expressions (`S { field }`, `obj.field`)
301 /// or patterns (`S { field }`). The index is often useful by itself, but to learn more
302 /// about the field you also need definition of the variant to which the field
303 /// belongs, but it may not exist if it's a tuple field (`tuple.0`).
304 field_indices: ItemLocalMap<usize>,
306 /// Stores the types for various nodes in the AST. Note that this table
307 /// is not guaranteed to be populated until after typeck. See
308 /// typeck::check::fn_ctxt for details.
309 node_types: ItemLocalMap<Ty<'tcx>>,
311 /// Stores the type parameters which were substituted to obtain the type
312 /// of this node. This only applies to nodes that refer to entities
313 /// parameterized by type parameters, such as generic fns, types, or
315 node_substs: ItemLocalMap<SubstsRef<'tcx>>,
317 /// This will either store the canonicalized types provided by the user
318 /// or the substitutions that the user explicitly gave (if any) attached
319 /// to `id`. These will not include any inferred values. The canonical form
320 /// is used to capture things like `_` or other unspecified values.
322 /// For example, if the user wrote `foo.collect::<Vec<_>>()`, then the
323 /// canonical substitutions would include only `for<X> { Vec<X> }`.
325 /// See also `AscribeUserType` statement in MIR.
326 user_provided_types: ItemLocalMap<CanonicalUserType<'tcx>>,
328 /// Stores the canonicalized types provided by the user. See also
329 /// `AscribeUserType` statement in MIR.
330 pub user_provided_sigs: DefIdMap<CanonicalPolyFnSig<'tcx>>,
332 adjustments: ItemLocalMap<Vec<ty::adjustment::Adjustment<'tcx>>>,
334 /// Stores the actual binding mode for all instances of hir::BindingAnnotation.
335 pat_binding_modes: ItemLocalMap<BindingMode>,
337 /// Stores the types which were implicitly dereferenced in pattern binding modes
338 /// for later usage in HAIR lowering. For example,
341 /// match &&Some(5i32) {
346 /// leads to a `vec![&&Option<i32>, &Option<i32>]`. Empty vectors are not stored.
349 /// https://github.com/rust-lang/rfcs/blob/master/text/2005-match-ergonomics.md#definitions
350 pat_adjustments: ItemLocalMap<Vec<Ty<'tcx>>>,
353 pub upvar_capture_map: ty::UpvarCaptureMap<'tcx>,
355 /// Records the reasons that we picked the kind of each closure;
356 /// not all closures are present in the map.
357 closure_kind_origins: ItemLocalMap<(Span, ast::Name)>,
359 /// For each fn, records the "liberated" types of its arguments
360 /// and return type. Liberated means that all bound regions
361 /// (including late-bound regions) are replaced with free
362 /// equivalents. This table is not used in codegen (since regions
363 /// are erased there) and hence is not serialized to metadata.
364 liberated_fn_sigs: ItemLocalMap<ty::FnSig<'tcx>>,
366 /// For each FRU expression, record the normalized types of the fields
367 /// of the struct - this is needed because it is non-trivial to
368 /// normalize while preserving regions. This table is used only in
369 /// MIR construction and hence is not serialized to metadata.
370 fru_field_types: ItemLocalMap<Vec<Ty<'tcx>>>,
372 /// For every coercion cast we add the HIR node ID of the cast
373 /// expression to this set.
374 coercion_casts: ItemLocalSet,
376 /// Set of trait imports actually used in the method resolution.
377 /// This is used for warning unused imports. During type
378 /// checking, this `Lrc` should not be cloned: it must have a ref-count
379 /// of 1 so that we can insert things into the set mutably.
380 pub used_trait_imports: Lrc<DefIdSet>,
382 /// If any errors occurred while type-checking this body,
383 /// this field will be set to `true`.
384 pub tainted_by_errors: bool,
386 /// Stores the free-region relationships that were deduced from
387 /// its where-clauses and parameter types. These are then
388 /// read-again by borrowck.
389 pub free_region_map: FreeRegionMap<'tcx>,
391 /// All the opaque types that are restricted to concrete types
392 /// by this function.
393 pub concrete_opaque_types: FxHashMap<DefId, ResolvedOpaqueTy<'tcx>>,
395 /// Given the closure ID this map provides the list of UpvarIDs used by it.
396 /// The upvarID contains the HIR node ID and it also contains the full path
397 /// leading to the member of the struct or tuple that is used instead of the
399 pub upvar_list: ty::UpvarListMap,
402 impl<'tcx> TypeckTables<'tcx> {
403 pub fn empty(local_id_root: Option<DefId>) -> TypeckTables<'tcx> {
406 type_dependent_defs: Default::default(),
407 field_indices: Default::default(),
408 user_provided_types: Default::default(),
409 user_provided_sigs: Default::default(),
410 node_types: Default::default(),
411 node_substs: Default::default(),
412 adjustments: Default::default(),
413 pat_binding_modes: Default::default(),
414 pat_adjustments: Default::default(),
415 upvar_capture_map: Default::default(),
416 closure_kind_origins: Default::default(),
417 liberated_fn_sigs: Default::default(),
418 fru_field_types: Default::default(),
419 coercion_casts: Default::default(),
420 used_trait_imports: Lrc::new(Default::default()),
421 tainted_by_errors: false,
422 free_region_map: Default::default(),
423 concrete_opaque_types: Default::default(),
424 upvar_list: Default::default(),
428 /// Returns the final resolution of a `QPath` in an `Expr` or `Pat` node.
429 pub fn qpath_res(&self, qpath: &hir::QPath, id: hir::HirId) -> Res {
431 hir::QPath::Resolved(_, ref path) => path.res,
432 hir::QPath::TypeRelative(..) => self.type_dependent_def(id)
433 .map_or(Res::Err, |(kind, def_id)| Res::Def(kind, def_id)),
437 pub fn type_dependent_defs(
439 ) -> LocalTableInContext<'_, Result<(DefKind, DefId), ErrorReported>> {
440 LocalTableInContext {
441 local_id_root: self.local_id_root,
442 data: &self.type_dependent_defs
446 pub fn type_dependent_def(&self, id: HirId) -> Option<(DefKind, DefId)> {
447 validate_hir_id_for_typeck_tables(self.local_id_root, id, false);
448 self.type_dependent_defs.get(&id.local_id).cloned().and_then(|r| r.ok())
451 pub fn type_dependent_def_id(&self, id: HirId) -> Option<DefId> {
452 self.type_dependent_def(id).map(|(_, def_id)| def_id)
455 pub fn type_dependent_defs_mut(
457 ) -> LocalTableInContextMut<'_, Result<(DefKind, DefId), ErrorReported>> {
458 LocalTableInContextMut {
459 local_id_root: self.local_id_root,
460 data: &mut self.type_dependent_defs
464 pub fn field_indices(&self) -> LocalTableInContext<'_, usize> {
465 LocalTableInContext {
466 local_id_root: self.local_id_root,
467 data: &self.field_indices
471 pub fn field_indices_mut(&mut self) -> LocalTableInContextMut<'_, usize> {
472 LocalTableInContextMut {
473 local_id_root: self.local_id_root,
474 data: &mut self.field_indices
478 pub fn user_provided_types(
480 ) -> LocalTableInContext<'_, CanonicalUserType<'tcx>> {
481 LocalTableInContext {
482 local_id_root: self.local_id_root,
483 data: &self.user_provided_types
487 pub fn user_provided_types_mut(
489 ) -> LocalTableInContextMut<'_, CanonicalUserType<'tcx>> {
490 LocalTableInContextMut {
491 local_id_root: self.local_id_root,
492 data: &mut self.user_provided_types
496 pub fn node_types(&self) -> LocalTableInContext<'_, Ty<'tcx>> {
497 LocalTableInContext {
498 local_id_root: self.local_id_root,
499 data: &self.node_types
503 pub fn node_types_mut(&mut self) -> LocalTableInContextMut<'_, Ty<'tcx>> {
504 LocalTableInContextMut {
505 local_id_root: self.local_id_root,
506 data: &mut self.node_types
510 pub fn node_type(&self, id: hir::HirId) -> Ty<'tcx> {
511 self.node_type_opt(id).unwrap_or_else(||
512 bug!("node_type: no type for node `{}`",
513 tls::with(|tcx| tcx.hir().node_to_string(id)))
517 pub fn node_type_opt(&self, id: hir::HirId) -> Option<Ty<'tcx>> {
518 validate_hir_id_for_typeck_tables(self.local_id_root, id, false);
519 self.node_types.get(&id.local_id).cloned()
522 pub fn node_substs_mut(&mut self) -> LocalTableInContextMut<'_, SubstsRef<'tcx>> {
523 LocalTableInContextMut {
524 local_id_root: self.local_id_root,
525 data: &mut self.node_substs
529 pub fn node_substs(&self, id: hir::HirId) -> SubstsRef<'tcx> {
530 validate_hir_id_for_typeck_tables(self.local_id_root, id, false);
531 self.node_substs.get(&id.local_id).cloned().unwrap_or_else(|| InternalSubsts::empty())
534 pub fn node_substs_opt(&self, id: hir::HirId) -> Option<SubstsRef<'tcx>> {
535 validate_hir_id_for_typeck_tables(self.local_id_root, id, false);
536 self.node_substs.get(&id.local_id).cloned()
539 // Returns the type of a pattern as a monotype. Like @expr_ty, this function
540 // doesn't provide type parameter substitutions.
541 pub fn pat_ty(&self, pat: &hir::Pat) -> Ty<'tcx> {
542 self.node_type(pat.hir_id)
545 pub fn pat_ty_opt(&self, pat: &hir::Pat) -> Option<Ty<'tcx>> {
546 self.node_type_opt(pat.hir_id)
549 // Returns the type of an expression as a monotype.
551 // NB (1): This is the PRE-ADJUSTMENT TYPE for the expression. That is, in
552 // some cases, we insert `Adjustment` annotations such as auto-deref or
553 // auto-ref. The type returned by this function does not consider such
554 // adjustments. See `expr_ty_adjusted()` instead.
556 // NB (2): This type doesn't provide type parameter substitutions; e.g., if you
557 // ask for the type of "id" in "id(3)", it will return "fn(&isize) -> isize"
558 // instead of "fn(ty) -> T with T = isize".
559 pub fn expr_ty(&self, expr: &hir::Expr) -> Ty<'tcx> {
560 self.node_type(expr.hir_id)
563 pub fn expr_ty_opt(&self, expr: &hir::Expr) -> Option<Ty<'tcx>> {
564 self.node_type_opt(expr.hir_id)
567 pub fn adjustments(&self) -> LocalTableInContext<'_, Vec<ty::adjustment::Adjustment<'tcx>>> {
568 LocalTableInContext {
569 local_id_root: self.local_id_root,
570 data: &self.adjustments
574 pub fn adjustments_mut(&mut self)
575 -> LocalTableInContextMut<'_, Vec<ty::adjustment::Adjustment<'tcx>>> {
576 LocalTableInContextMut {
577 local_id_root: self.local_id_root,
578 data: &mut self.adjustments
582 pub fn expr_adjustments(&self, expr: &hir::Expr)
583 -> &[ty::adjustment::Adjustment<'tcx>] {
584 validate_hir_id_for_typeck_tables(self.local_id_root, expr.hir_id, false);
585 self.adjustments.get(&expr.hir_id.local_id).map_or(&[], |a| &a[..])
588 /// Returns the type of `expr`, considering any `Adjustment`
589 /// entry recorded for that expression.
590 pub fn expr_ty_adjusted(&self, expr: &hir::Expr) -> Ty<'tcx> {
591 self.expr_adjustments(expr)
593 .map_or_else(|| self.expr_ty(expr), |adj| adj.target)
596 pub fn expr_ty_adjusted_opt(&self, expr: &hir::Expr) -> Option<Ty<'tcx>> {
597 self.expr_adjustments(expr)
599 .map(|adj| adj.target)
600 .or_else(|| self.expr_ty_opt(expr))
603 pub fn is_method_call(&self, expr: &hir::Expr) -> bool {
604 // Only paths and method calls/overloaded operators have
605 // entries in type_dependent_defs, ignore the former here.
606 if let hir::ExprKind::Path(_) = expr.kind {
610 match self.type_dependent_defs().get(expr.hir_id) {
611 Some(Ok((DefKind::Method, _))) => true,
616 pub fn pat_binding_modes(&self) -> LocalTableInContext<'_, BindingMode> {
617 LocalTableInContext {
618 local_id_root: self.local_id_root,
619 data: &self.pat_binding_modes
623 pub fn pat_binding_modes_mut(&mut self)
624 -> LocalTableInContextMut<'_, BindingMode> {
625 LocalTableInContextMut {
626 local_id_root: self.local_id_root,
627 data: &mut self.pat_binding_modes
631 pub fn pat_adjustments(&self) -> LocalTableInContext<'_, Vec<Ty<'tcx>>> {
632 LocalTableInContext {
633 local_id_root: self.local_id_root,
634 data: &self.pat_adjustments,
638 pub fn pat_adjustments_mut(&mut self)
639 -> LocalTableInContextMut<'_, Vec<Ty<'tcx>>> {
640 LocalTableInContextMut {
641 local_id_root: self.local_id_root,
642 data: &mut self.pat_adjustments,
646 pub fn upvar_capture(&self, upvar_id: ty::UpvarId) -> ty::UpvarCapture<'tcx> {
647 self.upvar_capture_map[&upvar_id]
650 pub fn closure_kind_origins(&self) -> LocalTableInContext<'_, (Span, ast::Name)> {
651 LocalTableInContext {
652 local_id_root: self.local_id_root,
653 data: &self.closure_kind_origins
657 pub fn closure_kind_origins_mut(&mut self) -> LocalTableInContextMut<'_, (Span, ast::Name)> {
658 LocalTableInContextMut {
659 local_id_root: self.local_id_root,
660 data: &mut self.closure_kind_origins
664 pub fn liberated_fn_sigs(&self) -> LocalTableInContext<'_, ty::FnSig<'tcx>> {
665 LocalTableInContext {
666 local_id_root: self.local_id_root,
667 data: &self.liberated_fn_sigs
671 pub fn liberated_fn_sigs_mut(&mut self) -> LocalTableInContextMut<'_, ty::FnSig<'tcx>> {
672 LocalTableInContextMut {
673 local_id_root: self.local_id_root,
674 data: &mut self.liberated_fn_sigs
678 pub fn fru_field_types(&self) -> LocalTableInContext<'_, Vec<Ty<'tcx>>> {
679 LocalTableInContext {
680 local_id_root: self.local_id_root,
681 data: &self.fru_field_types
685 pub fn fru_field_types_mut(&mut self) -> LocalTableInContextMut<'_, Vec<Ty<'tcx>>> {
686 LocalTableInContextMut {
687 local_id_root: self.local_id_root,
688 data: &mut self.fru_field_types
692 pub fn is_coercion_cast(&self, hir_id: hir::HirId) -> bool {
693 validate_hir_id_for_typeck_tables(self.local_id_root, hir_id, true);
694 self.coercion_casts.contains(&hir_id.local_id)
697 pub fn set_coercion_cast(&mut self, id: ItemLocalId) {
698 self.coercion_casts.insert(id);
701 pub fn coercion_casts(&self) -> &ItemLocalSet {
707 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for TypeckTables<'tcx> {
708 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
709 let ty::TypeckTables {
711 ref type_dependent_defs,
713 ref user_provided_types,
714 ref user_provided_sigs,
718 ref pat_binding_modes,
720 ref upvar_capture_map,
721 ref closure_kind_origins,
722 ref liberated_fn_sigs,
727 ref used_trait_imports,
730 ref concrete_opaque_types,
735 hcx.with_node_id_hashing_mode(NodeIdHashingMode::HashDefPath, |hcx| {
736 type_dependent_defs.hash_stable(hcx, hasher);
737 field_indices.hash_stable(hcx, hasher);
738 user_provided_types.hash_stable(hcx, hasher);
739 user_provided_sigs.hash_stable(hcx, hasher);
740 node_types.hash_stable(hcx, hasher);
741 node_substs.hash_stable(hcx, hasher);
742 adjustments.hash_stable(hcx, hasher);
743 pat_binding_modes.hash_stable(hcx, hasher);
744 pat_adjustments.hash_stable(hcx, hasher);
745 hash_stable_hashmap(hcx, hasher, upvar_capture_map, |up_var_id, hcx| {
752 local_id_root.expect("trying to hash invalid TypeckTables");
754 let var_owner_def_id = DefId {
755 krate: local_id_root.krate,
756 index: var_path.hir_id.owner,
758 let closure_def_id = DefId {
759 krate: local_id_root.krate,
760 index: closure_expr_id.to_def_id().index,
762 (hcx.def_path_hash(var_owner_def_id),
763 var_path.hir_id.local_id,
764 hcx.def_path_hash(closure_def_id))
767 closure_kind_origins.hash_stable(hcx, hasher);
768 liberated_fn_sigs.hash_stable(hcx, hasher);
769 fru_field_types.hash_stable(hcx, hasher);
770 coercion_casts.hash_stable(hcx, hasher);
771 used_trait_imports.hash_stable(hcx, hasher);
772 tainted_by_errors.hash_stable(hcx, hasher);
773 free_region_map.hash_stable(hcx, hasher);
774 concrete_opaque_types.hash_stable(hcx, hasher);
775 upvar_list.hash_stable(hcx, hasher);
781 pub struct UserTypeAnnotationIndex {
783 DEBUG_FORMAT = "UserType({})",
784 const START_INDEX = 0,
788 /// Mapping of type annotation indices to canonical user type annotations.
789 pub type CanonicalUserTypeAnnotations<'tcx> =
790 IndexVec<UserTypeAnnotationIndex, CanonicalUserTypeAnnotation<'tcx>>;
792 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
793 pub struct CanonicalUserTypeAnnotation<'tcx> {
794 pub user_ty: CanonicalUserType<'tcx>,
796 pub inferred_ty: Ty<'tcx>,
799 BraceStructTypeFoldableImpl! {
800 impl<'tcx> TypeFoldable<'tcx> for CanonicalUserTypeAnnotation<'tcx> {
801 user_ty, span, inferred_ty
805 BraceStructLiftImpl! {
806 impl<'a, 'tcx> Lift<'tcx> for CanonicalUserTypeAnnotation<'a> {
807 type Lifted = CanonicalUserTypeAnnotation<'tcx>;
808 user_ty, span, inferred_ty
812 /// Canonicalized user type annotation.
813 pub type CanonicalUserType<'tcx> = Canonical<'tcx, UserType<'tcx>>;
815 impl CanonicalUserType<'tcx> {
816 /// Returns `true` if this represents a substitution of the form `[?0, ?1, ?2]`,
817 /// i.e., each thing is mapped to a canonical variable with the same index.
818 pub fn is_identity(&self) -> bool {
820 UserType::Ty(_) => false,
821 UserType::TypeOf(_, user_substs) => {
822 if user_substs.user_self_ty.is_some() {
826 user_substs.substs.iter().zip(BoundVar::new(0)..).all(|(kind, cvar)| {
827 match kind.unpack() {
828 GenericArgKind::Type(ty) => match ty.kind {
829 ty::Bound(debruijn, b) => {
830 // We only allow a `ty::INNERMOST` index in substitutions.
831 assert_eq!(debruijn, ty::INNERMOST);
837 GenericArgKind::Lifetime(r) => match r {
838 ty::ReLateBound(debruijn, br) => {
839 // We only allow a `ty::INNERMOST` index in substitutions.
840 assert_eq!(*debruijn, ty::INNERMOST);
841 cvar == br.assert_bound_var()
846 GenericArgKind::Const(ct) => match ct.val {
847 ConstValue::Infer(InferConst::Canonical(debruijn, b)) => {
848 // We only allow a `ty::INNERMOST` index in substitutions.
849 assert_eq!(debruijn, ty::INNERMOST);
861 /// A user-given type annotation attached to a constant. These arise
862 /// from constants that are named via paths, like `Foo::<A>::new` and
864 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
865 pub enum UserType<'tcx> {
868 /// The canonical type is the result of `type_of(def_id)` with the
869 /// given substitutions applied.
870 TypeOf(DefId, UserSubsts<'tcx>),
873 EnumTypeFoldableImpl! {
874 impl<'tcx> TypeFoldable<'tcx> for UserType<'tcx> {
876 (UserType::TypeOf)(def, substs),
881 impl<'a, 'tcx> Lift<'tcx> for UserType<'a> {
882 type Lifted = UserType<'tcx>;
884 (UserType::TypeOf)(def, substs),
888 impl<'tcx> CommonTypes<'tcx> {
889 fn new(interners: &CtxtInterners<'tcx>) -> CommonTypes<'tcx> {
890 let mk = |ty| interners.intern_ty(ty);
893 unit: mk(Tuple(List::empty())),
898 isize: mk(Int(ast::IntTy::Isize)),
899 i8: mk(Int(ast::IntTy::I8)),
900 i16: mk(Int(ast::IntTy::I16)),
901 i32: mk(Int(ast::IntTy::I32)),
902 i64: mk(Int(ast::IntTy::I64)),
903 i128: mk(Int(ast::IntTy::I128)),
904 usize: mk(Uint(ast::UintTy::Usize)),
905 u8: mk(Uint(ast::UintTy::U8)),
906 u16: mk(Uint(ast::UintTy::U16)),
907 u32: mk(Uint(ast::UintTy::U32)),
908 u64: mk(Uint(ast::UintTy::U64)),
909 u128: mk(Uint(ast::UintTy::U128)),
910 f32: mk(Float(ast::FloatTy::F32)),
911 f64: mk(Float(ast::FloatTy::F64)),
912 self_param: mk(ty::Param(ty::ParamTy {
914 name: kw::SelfUpper.as_interned_str(),
917 trait_object_dummy_self: mk(Infer(ty::FreshTy(0))),
922 impl<'tcx> CommonLifetimes<'tcx> {
923 fn new(interners: &CtxtInterners<'tcx>) -> CommonLifetimes<'tcx> {
925 interners.region.intern(r, |r| {
926 Interned(interners.arena.alloc(r))
931 re_empty: mk(RegionKind::ReEmpty),
932 re_static: mk(RegionKind::ReStatic),
933 re_erased: mk(RegionKind::ReErased),
938 impl<'tcx> CommonConsts<'tcx> {
939 fn new(interners: &CtxtInterners<'tcx>, types: &CommonTypes<'tcx>) -> CommonConsts<'tcx> {
941 interners.const_.intern(c, |c| {
942 Interned(interners.arena.alloc(c))
947 err: mk_const(ty::Const {
948 val: ConstValue::Scalar(Scalar::zst()),
955 // This struct contains information regarding the `ReFree(FreeRegion)` corresponding to a lifetime
958 pub struct FreeRegionInfo {
959 // def id corresponding to FreeRegion
961 // the bound region corresponding to FreeRegion
962 pub boundregion: ty::BoundRegion,
963 // checks if bound region is in Impl Item
964 pub is_impl_item: bool,
967 /// The central data structure of the compiler. It stores references
968 /// to the various **arenas** and also houses the results of the
969 /// various **compiler queries** that have been performed. See the
970 /// [rustc guide] for more details.
972 /// [rustc guide]: https://rust-lang.github.io/rustc-guide/ty.html
973 #[derive(Copy, Clone)]
974 #[rustc_diagnostic_item = "TyCtxt"]
975 pub struct TyCtxt<'tcx> {
976 gcx: &'tcx GlobalCtxt<'tcx>,
979 impl<'tcx> Deref for TyCtxt<'tcx> {
980 type Target = &'tcx GlobalCtxt<'tcx>;
982 fn deref(&self) -> &Self::Target {
987 pub struct GlobalCtxt<'tcx> {
988 pub arena: WorkerLocal<Arena<'tcx>>,
990 interners: CtxtInterners<'tcx>,
992 cstore: &'tcx CrateStoreDyn,
994 pub sess: &'tcx Session,
996 pub dep_graph: DepGraph,
999 pub common: Common<'tcx>,
1001 /// Common types, pre-interned for your convenience.
1002 pub types: CommonTypes<'tcx>,
1004 /// Common lifetimes, pre-interned for your convenience.
1005 pub lifetimes: CommonLifetimes<'tcx>,
1007 /// Common consts, pre-interned for your convenience.
1008 pub consts: CommonConsts<'tcx>,
1010 /// Map indicating what traits are in scope for places where this
1011 /// is relevant; generated by resolve.
1012 trait_map: FxHashMap<DefIndex,
1013 FxHashMap<ItemLocalId,
1014 StableVec<TraitCandidate>>>,
1016 /// Export map produced by name resolution.
1017 export_map: FxHashMap<DefId, Vec<Export<hir::HirId>>>,
1019 hir_map: hir_map::Map<'tcx>,
1021 /// A map from `DefPathHash` -> `DefId`. Includes `DefId`s from the local crate
1022 /// as well as all upstream crates. Only populated in incremental mode.
1023 pub def_path_hash_to_def_id: Option<FxHashMap<DefPathHash, DefId>>,
1025 pub queries: query::Queries<'tcx>,
1027 maybe_unused_trait_imports: FxHashSet<DefId>,
1028 maybe_unused_extern_crates: Vec<(DefId, Span)>,
1029 /// A map of glob use to a set of names it actually imports. Currently only
1030 /// used in save-analysis.
1031 glob_map: FxHashMap<DefId, FxHashSet<ast::Name>>,
1032 /// Extern prelude entries. The value is `true` if the entry was introduced
1033 /// via `extern crate` item and not `--extern` option or compiler built-in.
1034 pub extern_prelude: FxHashMap<ast::Name, bool>,
1036 // Internal cache for metadata decoding. No need to track deps on this.
1037 pub rcache: Lock<FxHashMap<ty::CReaderCacheKey, Ty<'tcx>>>,
1039 /// Caches the results of trait selection. This cache is used
1040 /// for things that do not have to do with the parameters in scope.
1041 pub selection_cache: traits::SelectionCache<'tcx>,
1043 /// Caches the results of trait evaluation. This cache is used
1044 /// for things that do not have to do with the parameters in scope.
1045 /// Merge this with `selection_cache`?
1046 pub evaluation_cache: traits::EvaluationCache<'tcx>,
1048 /// The definite name of the current crate after taking into account
1049 /// attributes, commandline parameters, etc.
1050 pub crate_name: Symbol,
1052 /// Data layout specification for the current target.
1053 pub data_layout: TargetDataLayout,
1055 stability_interner: ShardedHashMap<&'tcx attr::Stability, ()>,
1057 /// Stores the value of constants (and deduplicates the actual memory)
1058 allocation_interner: ShardedHashMap<&'tcx Allocation, ()>,
1060 pub alloc_map: Lock<interpret::AllocMap<'tcx>>,
1062 layout_interner: ShardedHashMap<&'tcx LayoutDetails, ()>,
1064 output_filenames: Arc<OutputFilenames>,
1067 impl<'tcx> TyCtxt<'tcx> {
1069 pub fn hir(self) -> &'tcx hir_map::Map<'tcx> {
1073 pub fn alloc_steal_mir(self, mir: Body<'tcx>) -> &'tcx Steal<Body<'tcx>> {
1074 self.arena.alloc(Steal::new(mir))
1077 pub fn alloc_steal_promoted(self, promoted: IndexVec<Promoted, Body<'tcx>>) ->
1078 &'tcx Steal<IndexVec<Promoted, Body<'tcx>>> {
1079 self.arena.alloc(Steal::new(promoted))
1082 pub fn intern_promoted(self, promoted: IndexVec<Promoted, Body<'tcx>>) ->
1083 &'tcx IndexVec<Promoted, Body<'tcx>> {
1084 self.arena.alloc(promoted)
1087 pub fn alloc_adt_def(
1091 variants: IndexVec<VariantIdx, ty::VariantDef>,
1093 ) -> &'tcx ty::AdtDef {
1094 let def = ty::AdtDef::new(self, did, kind, variants, repr);
1095 self.arena.alloc(def)
1098 pub fn intern_const_alloc(self, alloc: Allocation) -> &'tcx Allocation {
1099 self.allocation_interner.intern(alloc, |alloc| {
1100 self.arena.alloc(alloc)
1104 /// Allocates a read-only byte or string literal for `mir::interpret`.
1105 pub fn allocate_bytes(self, bytes: &[u8]) -> interpret::AllocId {
1106 // Create an allocation that just contains these bytes.
1107 let alloc = interpret::Allocation::from_byte_aligned_bytes(bytes);
1108 let alloc = self.intern_const_alloc(alloc);
1109 self.alloc_map.lock().create_memory_alloc(alloc)
1112 pub fn intern_stability(self, stab: attr::Stability) -> &'tcx attr::Stability {
1113 self.stability_interner.intern(stab, |stab| {
1114 self.arena.alloc(stab)
1118 pub fn intern_layout(self, layout: LayoutDetails) -> &'tcx LayoutDetails {
1119 self.layout_interner.intern(layout, |layout| {
1120 self.arena.alloc(layout)
1124 /// Returns a range of the start/end indices specified with the
1125 /// `rustc_layout_scalar_valid_range` attribute.
1126 pub fn layout_scalar_valid_range(self, def_id: DefId) -> (Bound<u128>, Bound<u128>) {
1127 let attrs = self.get_attrs(def_id);
1129 let attr = match attrs.iter().find(|a| a.check_name(name)) {
1131 None => return Bound::Unbounded,
1133 for meta in attr.meta_item_list().expect("rustc_layout_scalar_valid_range takes args") {
1134 match meta.literal().expect("attribute takes lit").kind {
1135 ast::LitKind::Int(a, _) => return Bound::Included(a),
1136 _ => span_bug!(attr.span, "rustc_layout_scalar_valid_range expects int arg"),
1139 span_bug!(attr.span, "no arguments to `rustc_layout_scalar_valid_range` attribute");
1141 (get(sym::rustc_layout_scalar_valid_range_start),
1142 get(sym::rustc_layout_scalar_valid_range_end))
1145 pub fn lift<T: ?Sized + Lift<'tcx>>(self, value: &T) -> Option<T::Lifted> {
1146 value.lift_to_tcx(self)
1149 /// Creates a type context and call the closure with a `TyCtxt` reference
1150 /// to the context. The closure enforces that the type context and any interned
1151 /// value (types, substs, etc.) can only be used while `ty::tls` has a valid
1152 /// reference to the context, to allow formatting values that need it.
1153 pub fn create_global_ctxt(
1155 cstore: &'tcx CrateStoreDyn,
1156 local_providers: ty::query::Providers<'tcx>,
1157 extern_providers: ty::query::Providers<'tcx>,
1158 arenas: &'tcx AllArenas,
1159 resolutions: ty::Resolutions,
1160 hir: hir_map::Map<'tcx>,
1161 on_disk_query_result_cache: query::OnDiskCache<'tcx>,
1163 output_filenames: &OutputFilenames,
1164 ) -> GlobalCtxt<'tcx> {
1165 let data_layout = TargetDataLayout::parse(&s.target.target).unwrap_or_else(|err| {
1168 let interners = CtxtInterners::new(&arenas.interner);
1169 let common = Common {
1170 empty_predicates: ty::GenericPredicates {
1175 let common_types = CommonTypes::new(&interners);
1176 let common_lifetimes = CommonLifetimes::new(&interners);
1177 let common_consts = CommonConsts::new(&interners, &common_types);
1178 let dep_graph = hir.dep_graph.clone();
1179 let max_cnum = cstore.crates_untracked().iter().map(|c| c.as_usize()).max().unwrap_or(0);
1180 let mut providers = IndexVec::from_elem_n(extern_providers, max_cnum + 1);
1181 providers[LOCAL_CRATE] = local_providers;
1183 let def_path_hash_to_def_id = if s.opts.build_dep_graph() {
1184 let upstream_def_path_tables: Vec<(CrateNum, Lrc<_>)> = cstore
1187 .map(|&cnum| (cnum, cstore.def_path_table(cnum)))
1190 let def_path_tables = || {
1191 upstream_def_path_tables
1193 .map(|&(cnum, ref rc)| (cnum, &**rc))
1194 .chain(iter::once((LOCAL_CRATE, hir.definitions().def_path_table())))
1197 // Precompute the capacity of the hashmap so we don't have to
1198 // re-allocate when populating it.
1199 let capacity = def_path_tables().map(|(_, t)| t.size()).sum::<usize>();
1201 let mut map: FxHashMap<_, _> = FxHashMap::with_capacity_and_hasher(
1203 ::std::default::Default::default()
1206 for (cnum, def_path_table) in def_path_tables() {
1207 def_path_table.add_def_path_hashes_to(cnum, &mut map);
1215 let mut trait_map: FxHashMap<_, FxHashMap<_, _>> = FxHashMap::default();
1216 for (k, v) in resolutions.trait_map {
1217 let hir_id = hir.node_to_hir_id(k);
1218 let map = trait_map.entry(hir_id.owner).or_default();
1219 map.insert(hir_id.local_id, StableVec::new(v));
1225 arena: WorkerLocal::new(|_| Arena::default()),
1229 types: common_types,
1230 lifetimes: common_lifetimes,
1231 consts: common_consts,
1233 export_map: resolutions.export_map.into_iter().map(|(k, v)| {
1234 let exports: Vec<_> = v.into_iter().map(|e| {
1235 e.map_id(|id| hir.node_to_hir_id(id))
1239 maybe_unused_trait_imports:
1240 resolutions.maybe_unused_trait_imports
1242 .map(|id| hir.local_def_id_from_node_id(id))
1244 maybe_unused_extern_crates:
1245 resolutions.maybe_unused_extern_crates
1247 .map(|(id, sp)| (hir.local_def_id_from_node_id(id), sp))
1249 glob_map: resolutions.glob_map.into_iter().map(|(id, names)| {
1250 (hir.local_def_id_from_node_id(id), names)
1252 extern_prelude: resolutions.extern_prelude,
1254 def_path_hash_to_def_id,
1255 queries: query::Queries::new(
1258 on_disk_query_result_cache,
1260 rcache: Default::default(),
1261 selection_cache: Default::default(),
1262 evaluation_cache: Default::default(),
1263 crate_name: Symbol::intern(crate_name),
1265 layout_interner: Default::default(),
1266 stability_interner: Default::default(),
1267 allocation_interner: Default::default(),
1268 alloc_map: Lock::new(interpret::AllocMap::new()),
1269 output_filenames: Arc::new(output_filenames.clone()),
1273 pub fn consider_optimizing<T: Fn() -> String>(&self, msg: T) -> bool {
1274 let cname = self.crate_name(LOCAL_CRATE).as_str();
1275 self.sess.consider_optimizing(&cname, msg)
1278 pub fn lib_features(self) -> &'tcx middle::lib_features::LibFeatures {
1279 self.get_lib_features(LOCAL_CRATE)
1282 /// Obtain all lang items of this crate and all dependencies (recursively)
1283 pub fn lang_items(self) -> &'tcx middle::lang_items::LanguageItems {
1284 self.get_lang_items(LOCAL_CRATE)
1287 /// Obtain the given diagnostic item's `DefId`. Use `is_diagnostic_item` if you just want to
1288 /// compare against another `DefId`, since `is_diagnostic_item` is cheaper.
1289 pub fn get_diagnostic_item(self, name: Symbol) -> Option<DefId> {
1290 self.all_diagnostic_items(LOCAL_CRATE).get(&name).copied()
1293 /// Check whether the diagnostic item with the given `name` has the given `DefId`.
1294 pub fn is_diagnostic_item(self, name: Symbol, did: DefId) -> bool {
1295 self.diagnostic_items(did.krate).get(&name) == Some(&did)
1298 pub fn stability(self) -> &'tcx stability::Index<'tcx> {
1299 self.stability_index(LOCAL_CRATE)
1302 pub fn crates(self) -> &'tcx [CrateNum] {
1303 self.all_crate_nums(LOCAL_CRATE)
1306 pub fn features(self) -> &'tcx feature_gate::Features {
1307 self.features_query(LOCAL_CRATE)
1310 pub fn def_key(self, id: DefId) -> hir_map::DefKey {
1312 self.hir().def_key(id)
1314 self.cstore.def_key(id)
1318 /// Converts a `DefId` into its fully expanded `DefPath` (every
1319 /// `DefId` is really just an interned `DefPath`).
1321 /// Note that if `id` is not local to this crate, the result will
1322 /// be a non-local `DefPath`.
1323 pub fn def_path(self, id: DefId) -> hir_map::DefPath {
1325 self.hir().def_path(id)
1327 self.cstore.def_path(id)
1331 /// Returns whether or not the crate with CrateNum 'cnum'
1332 /// is marked as a private dependency
1333 pub fn is_private_dep(self, cnum: CrateNum) -> bool {
1334 if cnum == LOCAL_CRATE {
1337 self.cstore.crate_is_private_dep_untracked(cnum)
1342 pub fn def_path_hash(self, def_id: DefId) -> hir_map::DefPathHash {
1343 if def_id.is_local() {
1344 self.hir().definitions().def_path_hash(def_id.index)
1346 self.cstore.def_path_hash(def_id)
1350 pub fn def_path_debug_str(self, def_id: DefId) -> String {
1351 // We are explicitly not going through queries here in order to get
1352 // crate name and disambiguator since this code is called from debug!()
1353 // statements within the query system and we'd run into endless
1354 // recursion otherwise.
1355 let (crate_name, crate_disambiguator) = if def_id.is_local() {
1356 (self.crate_name.clone(),
1357 self.sess.local_crate_disambiguator())
1359 (self.cstore.crate_name_untracked(def_id.krate),
1360 self.cstore.crate_disambiguator_untracked(def_id.krate))
1365 // Don't print the whole crate disambiguator. That's just
1366 // annoying in debug output.
1367 &(crate_disambiguator.to_fingerprint().to_hex())[..4],
1368 self.def_path(def_id).to_string_no_crate())
1371 pub fn metadata_encoding_version(self) -> Vec<u8> {
1372 self.cstore.metadata_encoding_version().to_vec()
1375 pub fn encode_metadata(self)-> EncodedMetadata {
1376 self.cstore.encode_metadata(self)
1379 // Note that this is *untracked* and should only be used within the query
1380 // system if the result is otherwise tracked through queries
1381 pub fn crate_data_as_rc_any(self, cnum: CrateNum) -> Lrc<dyn Any> {
1382 self.cstore.crate_data_as_rc_any(cnum)
1386 pub fn create_stable_hashing_context(self) -> StableHashingContext<'tcx> {
1387 let krate = self.gcx.hir_map.forest.untracked_krate();
1389 StableHashingContext::new(self.sess,
1391 self.hir().definitions(),
1395 // This method makes sure that we have a DepNode and a Fingerprint for
1396 // every upstream crate. It needs to be called once right after the tcx is
1398 // With full-fledged red/green, the method will probably become unnecessary
1399 // as this will be done on-demand.
1400 pub fn allocate_metadata_dep_nodes(self) {
1401 // We cannot use the query versions of crates() and crate_hash(), since
1402 // those would need the DepNodes that we are allocating here.
1403 for cnum in self.cstore.crates_untracked() {
1404 let dep_node = DepNode::new(self, DepConstructor::CrateMetadata(cnum));
1405 let crate_hash = self.cstore.crate_hash_untracked(cnum);
1406 self.dep_graph.with_task(dep_node,
1409 |_, x| x, // No transformation needed
1410 dep_graph::hash_result,
1415 pub fn serialize_query_result_cache<E>(self,
1417 -> Result<(), E::Error>
1418 where E: ty::codec::TyEncoder
1420 self.queries.on_disk_cache.serialize(self, encoder)
1423 /// If `true`, we should use the MIR-based borrowck, but also
1424 /// fall back on the AST borrowck if the MIR-based one errors.
1425 pub fn migrate_borrowck(self) -> bool {
1426 self.borrowck_mode().migrate()
1429 /// If `true`, make MIR codegen for `match` emit a temp that holds a
1430 /// borrow of the input to the match expression.
1431 pub fn generate_borrow_of_any_match_input(&self) -> bool {
1432 self.emit_read_for_match()
1435 /// If `true`, make MIR codegen for `match` emit FakeRead
1436 /// statements (which simulate the maximal effect of executing the
1437 /// patterns in a match arm).
1438 pub fn emit_read_for_match(&self) -> bool {
1439 !self.sess.opts.debugging_opts.nll_dont_emit_read_for_match
1442 /// What mode(s) of borrowck should we run? AST? MIR? both?
1443 /// (Also considers the `#![feature(nll)]` setting.)
1444 pub fn borrowck_mode(&self) -> BorrowckMode {
1445 // Here are the main constraints we need to deal with:
1447 // 1. An opts.borrowck_mode of `BorrowckMode::Migrate` is
1448 // synonymous with no `-Z borrowck=...` flag at all.
1450 // 2. We want to allow developers on the Nightly channel
1451 // to opt back into the "hard error" mode for NLL,
1452 // (which they can do via specifying `#![feature(nll)]`
1453 // explicitly in their crate).
1455 // So, this precedence list is how pnkfelix chose to work with
1456 // the above constraints:
1458 // * `#![feature(nll)]` *always* means use NLL with hard
1459 // errors. (To simplify the code here, it now even overrides
1460 // a user's attempt to specify `-Z borrowck=compare`, which
1461 // we arguably do not need anymore and should remove.)
1463 // * Otherwise, if no `-Z borrowck=...` then use migrate mode
1465 // * Otherwise, use the behavior requested via `-Z borrowck=...`
1467 if self.features().nll { return BorrowckMode::Mir; }
1469 self.sess.opts.borrowck_mode
1473 pub fn local_crate_exports_generics(self) -> bool {
1474 debug_assert!(self.sess.opts.share_generics());
1476 self.sess.crate_types.borrow().iter().any(|crate_type| {
1478 CrateType::Executable |
1479 CrateType::Staticlib |
1480 CrateType::ProcMacro |
1482 CrateType::Cdylib => false,
1483 CrateType::Rlib => true,
1488 // Returns the `DefId` and the `BoundRegion` corresponding to the given region.
1489 pub fn is_suitable_region(&self, region: Region<'tcx>) -> Option<FreeRegionInfo> {
1490 let (suitable_region_binding_scope, bound_region) = match *region {
1491 ty::ReFree(ref free_region) => (free_region.scope, free_region.bound_region),
1492 ty::ReEarlyBound(ref ebr) => (
1493 self.parent(ebr.def_id).unwrap(),
1494 ty::BoundRegion::BrNamed(ebr.def_id, ebr.name),
1496 _ => return None, // not a free region
1499 let hir_id = self.hir()
1500 .as_local_hir_id(suitable_region_binding_scope)
1502 let is_impl_item = match self.hir().find(hir_id) {
1503 Some(Node::Item(..)) | Some(Node::TraitItem(..)) => false,
1504 Some(Node::ImplItem(..)) => {
1505 self.is_bound_region_in_impl_item(suitable_region_binding_scope)
1510 return Some(FreeRegionInfo {
1511 def_id: suitable_region_binding_scope,
1512 boundregion: bound_region,
1513 is_impl_item: is_impl_item,
1517 pub fn return_type_impl_trait(
1519 scope_def_id: DefId,
1520 ) -> Option<Ty<'tcx>> {
1521 // HACK: `type_of_def_id()` will fail on these (#55796), so return `None`.
1522 let hir_id = self.hir().as_local_hir_id(scope_def_id).unwrap();
1523 match self.hir().get(hir_id) {
1524 Node::Item(item) => {
1526 ItemKind::Fn(..) => { /* `type_of_def_id()` will work */ }
1532 _ => { /* `type_of_def_id()` will work or panic */ }
1535 let ret_ty = self.type_of(scope_def_id);
1537 ty::FnDef(_, _) => {
1538 let sig = ret_ty.fn_sig(*self);
1539 let output = self.erase_late_bound_regions(&sig.output());
1540 if output.is_impl_trait() {
1550 // Checks if the bound region is in Impl Item.
1551 pub fn is_bound_region_in_impl_item(
1553 suitable_region_binding_scope: DefId,
1555 let container_id = self.associated_item(suitable_region_binding_scope)
1558 if self.impl_trait_ref(container_id).is_some() {
1559 // For now, we do not try to target impls of traits. This is
1560 // because this message is going to suggest that the user
1561 // change the fn signature, but they may not be free to do so,
1562 // since the signature must match the trait.
1564 // FIXME(#42706) -- in some cases, we could do better here.
1570 /// Determines whether identifiers in the assembly have strict naming rules.
1571 /// Currently, only NVPTX* targets need it.
1572 pub fn has_strict_asm_symbol_naming(&self) -> bool {
1573 self.sess.target.target.arch.contains("nvptx")
1577 impl<'tcx> GlobalCtxt<'tcx> {
1578 /// Calls the closure with a local `TyCtxt` using the given arena.
1579 /// `interners` is a slot passed so we can create a CtxtInterners
1580 /// with the same lifetime as `arena`.
1581 pub fn enter_local<F, R>(&'tcx self, f: F) -> R
1583 F: FnOnce(TyCtxt<'tcx>) -> R,
1588 ty::tls::with_related_context(tcx, |icx| {
1589 let new_icx = ty::tls::ImplicitCtxt {
1591 query: icx.query.clone(),
1592 diagnostics: icx.diagnostics,
1593 layout_depth: icx.layout_depth,
1594 task_deps: icx.task_deps,
1596 ty::tls::enter_context(&new_icx, |_| {
1603 /// A trait implemented for all `X<'a>` types that can be safely and
1604 /// efficiently converted to `X<'tcx>` as long as they are part of the
1605 /// provided `TyCtxt<'tcx>`.
1606 /// This can be done, for example, for `Ty<'tcx>` or `SubstsRef<'tcx>`
1607 /// by looking them up in their respective interners.
1609 /// However, this is still not the best implementation as it does
1610 /// need to compare the components, even for interned values.
1611 /// It would be more efficient if `TypedArena` provided a way to
1612 /// determine whether the address is in the allocated range.
1614 /// `None` is returned if the value or one of the components is not part
1615 /// of the provided context.
1616 /// For `Ty`, `None` can be returned if either the type interner doesn't
1617 /// contain the `TyKind` key or if the address of the interned
1618 /// pointer differs. The latter case is possible if a primitive type,
1619 /// e.g., `()` or `u8`, was interned in a different context.
1620 pub trait Lift<'tcx>: fmt::Debug {
1621 type Lifted: fmt::Debug + 'tcx;
1622 fn lift_to_tcx(&self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted>;
1625 macro_rules! nop_lift {
1626 ($ty:ty => $lifted:ty) => {
1627 impl<'a, 'tcx> Lift<'tcx> for $ty {
1628 type Lifted = $lifted;
1629 fn lift_to_tcx(&self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
1630 if tcx.interners.arena.in_arena(*self as *const _) {
1631 Some(unsafe { mem::transmute(*self) })
1640 macro_rules! nop_list_lift {
1641 ($ty:ty => $lifted:ty) => {
1642 impl<'a, 'tcx> Lift<'tcx> for &'a List<$ty> {
1643 type Lifted = &'tcx List<$lifted>;
1644 fn lift_to_tcx(&self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
1645 if self.is_empty() {
1646 return Some(List::empty());
1648 if tcx.interners.arena.in_arena(*self as *const _) {
1649 Some(unsafe { mem::transmute(*self) })
1658 nop_lift!{Ty<'a> => Ty<'tcx>}
1659 nop_lift!{Region<'a> => Region<'tcx>}
1660 nop_lift!{Goal<'a> => Goal<'tcx>}
1661 nop_lift!{&'a Const<'a> => &'tcx Const<'tcx>}
1663 nop_list_lift!{Goal<'a> => Goal<'tcx>}
1664 nop_list_lift!{Clause<'a> => Clause<'tcx>}
1665 nop_list_lift!{Ty<'a> => Ty<'tcx>}
1666 nop_list_lift!{ExistentialPredicate<'a> => ExistentialPredicate<'tcx>}
1667 nop_list_lift!{Predicate<'a> => Predicate<'tcx>}
1668 nop_list_lift!{CanonicalVarInfo => CanonicalVarInfo}
1669 nop_list_lift!{ProjectionKind => ProjectionKind}
1671 // This is the impl for `&'a InternalSubsts<'a>`.
1672 nop_list_lift!{GenericArg<'a> => GenericArg<'tcx>}
1675 use super::{GlobalCtxt, TyCtxt, ptr_eq};
1680 use crate::ty::query;
1681 use errors::{Diagnostic, TRACK_DIAGNOSTICS};
1682 use rustc_data_structures::OnDrop;
1683 use rustc_data_structures::sync::{self, Lrc, Lock};
1684 use rustc_data_structures::thin_vec::ThinVec;
1685 use crate::dep_graph::TaskDeps;
1687 #[cfg(not(parallel_compiler))]
1688 use std::cell::Cell;
1690 #[cfg(parallel_compiler)]
1691 use rustc_rayon_core as rayon_core;
1693 /// This is the implicit state of rustc. It contains the current
1694 /// `TyCtxt` and query. It is updated when creating a local interner or
1695 /// executing a new query. Whenever there's a `TyCtxt` value available
1696 /// you should also have access to an `ImplicitCtxt` through the functions
1699 pub struct ImplicitCtxt<'a, 'tcx> {
1700 /// The current `TyCtxt`. Initially created by `enter_global` and updated
1701 /// by `enter_local` with a new local interner.
1702 pub tcx: TyCtxt<'tcx>,
1704 /// The current query job, if any. This is updated by `JobOwner::start` in
1705 /// `ty::query::plumbing` when executing a query.
1706 pub query: Option<Lrc<query::QueryJob<'tcx>>>,
1708 /// Where to store diagnostics for the current query job, if any.
1709 /// This is updated by `JobOwner::start` in `ty::query::plumbing` when executing a query.
1710 pub diagnostics: Option<&'a Lock<ThinVec<Diagnostic>>>,
1712 /// Used to prevent layout from recursing too deeply.
1713 pub layout_depth: usize,
1715 /// The current dep graph task. This is used to add dependencies to queries
1716 /// when executing them.
1717 pub task_deps: Option<&'a Lock<TaskDeps>>,
1720 /// Sets Rayon's thread-local variable, which is preserved for Rayon jobs
1721 /// to `value` during the call to `f`. It is restored to its previous value after.
1722 /// This is used to set the pointer to the new `ImplicitCtxt`.
1723 #[cfg(parallel_compiler)]
1725 fn set_tlv<F: FnOnce() -> R, R>(value: usize, f: F) -> R {
1726 rayon_core::tlv::with(value, f)
1729 /// Gets Rayon's thread-local variable, which is preserved for Rayon jobs.
1730 /// This is used to get the pointer to the current `ImplicitCtxt`.
1731 #[cfg(parallel_compiler)]
1733 fn get_tlv() -> usize {
1734 rayon_core::tlv::get()
1737 #[cfg(not(parallel_compiler))]
1739 /// A thread local variable that stores a pointer to the current `ImplicitCtxt`.
1740 static TLV: Cell<usize> = Cell::new(0);
1743 /// Sets TLV to `value` during the call to `f`.
1744 /// It is restored to its previous value after.
1745 /// This is used to set the pointer to the new `ImplicitCtxt`.
1746 #[cfg(not(parallel_compiler))]
1748 fn set_tlv<F: FnOnce() -> R, R>(value: usize, f: F) -> R {
1749 let old = get_tlv();
1750 let _reset = OnDrop(move || TLV.with(|tlv| tlv.set(old)));
1751 TLV.with(|tlv| tlv.set(value));
1755 /// Gets the pointer to the current `ImplicitCtxt`.
1756 #[cfg(not(parallel_compiler))]
1757 fn get_tlv() -> usize {
1758 TLV.with(|tlv| tlv.get())
1761 /// This is a callback from libsyntax as it cannot access the implicit state
1762 /// in librustc otherwise.
1763 fn span_debug(span: syntax_pos::Span, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1765 if let Some(tcx) = tcx {
1766 write!(f, "{}", tcx.sess.source_map().span_to_string(span))
1768 syntax_pos::default_span_debug(span, f)
1773 /// This is a callback from libsyntax as it cannot access the implicit state
1774 /// in librustc otherwise. It is used to when diagnostic messages are
1775 /// emitted and stores them in the current query, if there is one.
1776 fn track_diagnostic(diagnostic: &Diagnostic) {
1777 with_context_opt(|icx| {
1778 if let Some(icx) = icx {
1779 if let Some(ref diagnostics) = icx.diagnostics {
1780 let mut diagnostics = diagnostics.lock();
1781 diagnostics.extend(Some(diagnostic.clone()));
1787 /// Sets up the callbacks from libsyntax on the current thread.
1788 pub fn with_thread_locals<F, R>(f: F) -> R
1789 where F: FnOnce() -> R
1791 syntax_pos::SPAN_DEBUG.with(|span_dbg| {
1792 let original_span_debug = span_dbg.get();
1793 span_dbg.set(span_debug);
1795 let _on_drop = OnDrop(move || {
1796 span_dbg.set(original_span_debug);
1799 TRACK_DIAGNOSTICS.with(|current| {
1800 let original = current.get();
1801 current.set(track_diagnostic);
1803 let _on_drop = OnDrop(move || {
1804 current.set(original);
1812 /// Sets `context` as the new current `ImplicitCtxt` for the duration of the function `f`.
1814 pub fn enter_context<'a, 'tcx, F, R>(context: &ImplicitCtxt<'a, 'tcx>, f: F) -> R
1816 F: FnOnce(&ImplicitCtxt<'a, 'tcx>) -> R,
1818 set_tlv(context as *const _ as usize, || {
1823 /// Enters `GlobalCtxt` by setting up libsyntax callbacks and
1824 /// creating a initial `TyCtxt` and `ImplicitCtxt`.
1825 /// This happens once per rustc session and `TyCtxt`s only exists
1826 /// inside the `f` function.
1827 pub fn enter_global<'tcx, F, R>(gcx: &'tcx GlobalCtxt<'tcx>, f: F) -> R
1829 F: FnOnce(TyCtxt<'tcx>) -> R,
1831 // Update `GCX_PTR` to indicate there's a `GlobalCtxt` available.
1832 GCX_PTR.with(|lock| {
1833 *lock.lock() = gcx as *const _ as usize;
1835 // Set `GCX_PTR` back to 0 when we exit.
1836 let _on_drop = OnDrop(move || {
1837 GCX_PTR.with(|lock| *lock.lock() = 0);
1843 let icx = ImplicitCtxt {
1850 enter_context(&icx, |_| {
1855 scoped_thread_local! {
1856 /// Stores a pointer to the `GlobalCtxt` if one is available.
1857 /// This is used to access the `GlobalCtxt` in the deadlock handler given to Rayon.
1858 pub static GCX_PTR: Lock<usize>
1861 /// Creates a `TyCtxt` and `ImplicitCtxt` based on the `GCX_PTR` thread local.
1862 /// This is used in the deadlock handler.
1863 pub unsafe fn with_global<F, R>(f: F) -> R
1865 F: for<'tcx> FnOnce(TyCtxt<'tcx>) -> R,
1867 let gcx = GCX_PTR.with(|lock| *lock.lock());
1869 let gcx = &*(gcx as *const GlobalCtxt<'_>);
1873 let icx = ImplicitCtxt {
1880 enter_context(&icx, |_| f(tcx))
1883 /// Allows access to the current `ImplicitCtxt` in a closure if one is available.
1885 pub fn with_context_opt<F, R>(f: F) -> R
1887 F: for<'a, 'tcx> FnOnce(Option<&ImplicitCtxt<'a, 'tcx>>) -> R,
1889 let context = get_tlv();
1893 // We could get a `ImplicitCtxt` pointer from another thread.
1894 // Ensure that `ImplicitCtxt` is `Sync`.
1895 sync::assert_sync::<ImplicitCtxt<'_, '_>>();
1897 unsafe { f(Some(&*(context as *const ImplicitCtxt<'_, '_>))) }
1901 /// Allows access to the current `ImplicitCtxt`.
1902 /// Panics if there is no `ImplicitCtxt` available.
1904 pub fn with_context<F, R>(f: F) -> R
1906 F: for<'a, 'tcx> FnOnce(&ImplicitCtxt<'a, 'tcx>) -> R,
1908 with_context_opt(|opt_context| f(opt_context.expect("no ImplicitCtxt stored in tls")))
1911 /// Allows access to the current `ImplicitCtxt` whose tcx field has the same global
1912 /// interner as the tcx argument passed in. This means the closure is given an `ImplicitCtxt`
1913 /// with the same `'tcx` lifetime as the `TyCtxt` passed in.
1914 /// This will panic if you pass it a `TyCtxt` which has a different global interner from
1915 /// the current `ImplicitCtxt`'s `tcx` field.
1917 pub fn with_related_context<'tcx, F, R>(tcx: TyCtxt<'tcx>, f: F) -> R
1919 F: FnOnce(&ImplicitCtxt<'_, 'tcx>) -> R,
1921 with_context(|context| {
1923 assert!(ptr_eq(context.tcx.gcx, tcx.gcx));
1924 let context: &ImplicitCtxt<'_, '_> = mem::transmute(context);
1930 /// Allows access to the `TyCtxt` in the current `ImplicitCtxt`.
1931 /// Panics if there is no `ImplicitCtxt` available.
1933 pub fn with<F, R>(f: F) -> R
1935 F: for<'tcx> FnOnce(TyCtxt<'tcx>) -> R,
1937 with_context(|context| f(context.tcx))
1940 /// Allows access to the `TyCtxt` in the current `ImplicitCtxt`.
1941 /// The closure is passed None if there is no `ImplicitCtxt` available.
1943 pub fn with_opt<F, R>(f: F) -> R
1945 F: for<'tcx> FnOnce(Option<TyCtxt<'tcx>>) -> R,
1947 with_context_opt(|opt_context| f(opt_context.map(|context| context.tcx)))
1951 macro_rules! sty_debug_print {
1952 ($ctxt: expr, $($variant: ident),*) => {{
1953 // Curious inner module to allow variant names to be used as
1955 #[allow(non_snake_case)]
1957 use crate::ty::{self, TyCtxt};
1958 use crate::ty::context::Interned;
1960 #[derive(Copy, Clone)]
1969 pub fn go(tcx: TyCtxt<'_>) {
1970 let mut total = DebugStat {
1977 $(let mut $variant = total;)*
1979 let shards = tcx.interners.type_.lock_shards();
1980 let types = shards.iter().flat_map(|shard| shard.keys());
1981 for &Interned(t) in types {
1982 let variant = match t.kind {
1983 ty::Bool | ty::Char | ty::Int(..) | ty::Uint(..) |
1984 ty::Float(..) | ty::Str | ty::Never => continue,
1985 ty::Error => /* unimportant */ continue,
1986 $(ty::$variant(..) => &mut $variant,)*
1988 let lt = t.flags.intersects(ty::TypeFlags::HAS_RE_INFER);
1989 let ty = t.flags.intersects(ty::TypeFlags::HAS_TY_INFER);
1990 let ct = t.flags.intersects(ty::TypeFlags::HAS_CT_INFER);
1994 if lt { total.lt_infer += 1; variant.lt_infer += 1 }
1995 if ty { total.ty_infer += 1; variant.ty_infer += 1 }
1996 if ct { total.ct_infer += 1; variant.ct_infer += 1 }
1997 if lt && ty && ct { total.all_infer += 1; variant.all_infer += 1 }
1999 println!("Ty interner total ty lt ct all");
2000 $(println!(" {:18}: {uses:6} {usespc:4.1}%, \
2001 {ty:4.1}% {lt:5.1}% {ct:4.1}% {all:4.1}%",
2002 stringify!($variant),
2003 uses = $variant.total,
2004 usespc = $variant.total as f64 * 100.0 / total.total as f64,
2005 ty = $variant.ty_infer as f64 * 100.0 / total.total as f64,
2006 lt = $variant.lt_infer as f64 * 100.0 / total.total as f64,
2007 ct = $variant.ct_infer as f64 * 100.0 / total.total as f64,
2008 all = $variant.all_infer as f64 * 100.0 / total.total as f64);
2010 println!(" total {uses:6} \
2011 {ty:4.1}% {lt:5.1}% {ct:4.1}% {all:4.1}%",
2013 ty = total.ty_infer as f64 * 100.0 / total.total as f64,
2014 lt = total.lt_infer as f64 * 100.0 / total.total as f64,
2015 ct = total.ct_infer as f64 * 100.0 / total.total as f64,
2016 all = total.all_infer as f64 * 100.0 / total.total as f64)
2024 impl<'tcx> TyCtxt<'tcx> {
2025 pub fn print_debug_stats(self) {
2028 Adt, Array, Slice, RawPtr, Ref, FnDef, FnPtr, Placeholder,
2029 Generator, GeneratorWitness, Dynamic, Closure, Tuple, Bound,
2030 Param, Infer, UnnormalizedProjection, Projection, Opaque, Foreign);
2032 println!("InternalSubsts interner: #{}", self.interners.substs.len());
2033 println!("Region interner: #{}", self.interners.region.len());
2034 println!("Stability interner: #{}", self.stability_interner.len());
2035 println!("Allocation interner: #{}", self.allocation_interner.len());
2036 println!("Layout interner: #{}", self.layout_interner.len());
2041 /// An entry in an interner.
2042 struct Interned<'tcx, T: ?Sized>(&'tcx T);
2044 impl<'tcx, T: 'tcx+?Sized> Clone for Interned<'tcx, T> {
2045 fn clone(&self) -> Self {
2049 impl<'tcx, T: 'tcx+?Sized> Copy for Interned<'tcx, T> {}
2051 // N.B., an `Interned<Ty>` compares and hashes as a `TyKind`.
2052 impl<'tcx> PartialEq for Interned<'tcx, TyS<'tcx>> {
2053 fn eq(&self, other: &Interned<'tcx, TyS<'tcx>>) -> bool {
2054 self.0.kind == other.0.kind
2058 impl<'tcx> Eq for Interned<'tcx, TyS<'tcx>> {}
2060 impl<'tcx> Hash for Interned<'tcx, TyS<'tcx>> {
2061 fn hash<H: Hasher>(&self, s: &mut H) {
2066 #[allow(rustc::usage_of_ty_tykind)]
2067 impl<'tcx> Borrow<TyKind<'tcx>> for Interned<'tcx, TyS<'tcx>> {
2068 fn borrow<'a>(&'a self) -> &'a TyKind<'tcx> {
2073 // N.B., an `Interned<List<T>>` compares and hashes as its elements.
2074 impl<'tcx, T: PartialEq> PartialEq for Interned<'tcx, List<T>> {
2075 fn eq(&self, other: &Interned<'tcx, List<T>>) -> bool {
2076 self.0[..] == other.0[..]
2080 impl<'tcx, T: Eq> Eq for Interned<'tcx, List<T>> {}
2082 impl<'tcx, T: Hash> Hash for Interned<'tcx, List<T>> {
2083 fn hash<H: Hasher>(&self, s: &mut H) {
2088 impl<'tcx> Borrow<[Ty<'tcx>]> for Interned<'tcx, List<Ty<'tcx>>> {
2089 fn borrow<'a>(&'a self) -> &'a [Ty<'tcx>] {
2094 impl<'tcx> Borrow<[CanonicalVarInfo]> for Interned<'tcx, List<CanonicalVarInfo>> {
2095 fn borrow(&self) -> &[CanonicalVarInfo] {
2100 impl<'tcx> Borrow<[GenericArg<'tcx>]> for Interned<'tcx, InternalSubsts<'tcx>> {
2101 fn borrow<'a>(&'a self) -> &'a [GenericArg<'tcx>] {
2106 impl<'tcx> Borrow<[ProjectionKind]>
2107 for Interned<'tcx, List<ProjectionKind>> {
2108 fn borrow(&self) -> &[ProjectionKind] {
2113 impl<'tcx> Borrow<RegionKind> for Interned<'tcx, RegionKind> {
2114 fn borrow(&self) -> &RegionKind {
2119 impl<'tcx> Borrow<GoalKind<'tcx>> for Interned<'tcx, GoalKind<'tcx>> {
2120 fn borrow<'a>(&'a self) -> &'a GoalKind<'tcx> {
2125 impl<'tcx> Borrow<[ExistentialPredicate<'tcx>]>
2126 for Interned<'tcx, List<ExistentialPredicate<'tcx>>>
2128 fn borrow<'a>(&'a self) -> &'a [ExistentialPredicate<'tcx>] {
2133 impl<'tcx> Borrow<[Predicate<'tcx>]> for Interned<'tcx, List<Predicate<'tcx>>> {
2134 fn borrow<'a>(&'a self) -> &'a [Predicate<'tcx>] {
2139 impl<'tcx> Borrow<Const<'tcx>> for Interned<'tcx, Const<'tcx>> {
2140 fn borrow<'a>(&'a self) -> &'a Const<'tcx> {
2145 impl<'tcx> Borrow<[Clause<'tcx>]> for Interned<'tcx, List<Clause<'tcx>>> {
2146 fn borrow<'a>(&'a self) -> &'a [Clause<'tcx>] {
2151 impl<'tcx> Borrow<[Goal<'tcx>]> for Interned<'tcx, List<Goal<'tcx>>> {
2152 fn borrow<'a>(&'a self) -> &'a [Goal<'tcx>] {
2157 macro_rules! intern_method {
2158 ($lt_tcx:tt, $name:ident: $method:ident($alloc:ty,
2160 $alloc_to_key:expr) -> $ty:ty) => {
2161 impl<$lt_tcx> TyCtxt<$lt_tcx> {
2162 pub fn $method(self, v: $alloc) -> &$lt_tcx $ty {
2163 let key = ($alloc_to_key)(&v);
2165 self.interners.$name.intern_ref(key, || {
2166 Interned($alloc_method(&self.interners.arena, v))
2174 macro_rules! direct_interners {
2175 ($lt_tcx:tt, $($name:ident: $method:ident($ty:ty)),+) => {
2176 $(impl<$lt_tcx> PartialEq for Interned<$lt_tcx, $ty> {
2177 fn eq(&self, other: &Self) -> bool {
2182 impl<$lt_tcx> Eq for Interned<$lt_tcx, $ty> {}
2184 impl<$lt_tcx> Hash for Interned<$lt_tcx, $ty> {
2185 fn hash<H: Hasher>(&self, s: &mut H) {
2193 |a: &$lt_tcx SyncDroplessArena, v| -> &$lt_tcx $ty { a.alloc(v) },
2198 pub fn keep_local<'tcx, T: ty::TypeFoldable<'tcx>>(x: &T) -> bool {
2199 x.has_type_flags(ty::TypeFlags::KEEP_IN_LOCAL_TCX)
2202 direct_interners!('tcx,
2203 region: mk_region(RegionKind),
2204 goal: mk_goal(GoalKind<'tcx>),
2205 const_: mk_const(Const<'tcx>)
2208 macro_rules! slice_interners {
2209 ($($field:ident: $method:ident($ty:ty)),+) => (
2210 $(intern_method!( 'tcx, $field: $method(
2212 |a, v| List::from_arena(a, v),
2213 Deref::deref) -> List<$ty>);)+
2218 existential_predicates: _intern_existential_predicates(ExistentialPredicate<'tcx>),
2219 predicates: _intern_predicates(Predicate<'tcx>),
2220 type_list: _intern_type_list(Ty<'tcx>),
2221 substs: _intern_substs(GenericArg<'tcx>),
2222 clauses: _intern_clauses(Clause<'tcx>),
2223 goal_list: _intern_goals(Goal<'tcx>),
2224 projs: _intern_projs(ProjectionKind)
2227 // This isn't a perfect fit: `CanonicalVarInfo` slices are always
2228 // allocated in the global arena, so this `intern_method!` macro is
2229 // overly general. However, we just return `false` for the code that checks
2230 // whether they belong in the thread-local arena, so no harm done, and
2231 // seems better than open-coding the rest.
2234 canonical_var_infos: _intern_canonical_var_infos(
2235 &[CanonicalVarInfo],
2236 |a, v| List::from_arena(a, v),
2238 ) -> List<CanonicalVarInfo>
2241 impl<'tcx> TyCtxt<'tcx> {
2242 /// Given a `fn` type, returns an equivalent `unsafe fn` type;
2243 /// that is, a `fn` type that is equivalent in every way for being
2245 pub fn safe_to_unsafe_fn_ty(self, sig: PolyFnSig<'tcx>) -> Ty<'tcx> {
2246 assert_eq!(sig.unsafety(), hir::Unsafety::Normal);
2247 self.mk_fn_ptr(sig.map_bound(|sig| ty::FnSig {
2248 unsafety: hir::Unsafety::Unsafe,
2253 /// Given a closure signature `sig`, returns an equivalent `fn`
2254 /// type with the same signature. Detuples and so forth -- so
2255 /// e.g., if we have a sig with `Fn<(u32, i32)>` then you would get
2256 /// a `fn(u32, i32)`.
2257 /// `unsafety` determines the unsafety of the `fn` type. If you pass
2258 /// `hir::Unsafety::Unsafe` in the previous example, then you would get
2259 /// an `unsafe fn (u32, i32)`.
2260 /// It cannot convert a closure that requires unsafe.
2261 pub fn coerce_closure_fn_ty(self, sig: PolyFnSig<'tcx>, unsafety: hir::Unsafety) -> Ty<'tcx> {
2262 let converted_sig = sig.map_bound(|s| {
2263 let params_iter = match s.inputs()[0].kind {
2264 ty::Tuple(params) => {
2265 params.into_iter().map(|k| k.expect_ty())
2278 self.mk_fn_ptr(converted_sig)
2281 #[allow(rustc::usage_of_ty_tykind)]
2283 pub fn mk_ty(&self, st: TyKind<'tcx>) -> Ty<'tcx> {
2284 self.interners.intern_ty(st)
2287 pub fn mk_mach_int(self, tm: ast::IntTy) -> Ty<'tcx> {
2289 ast::IntTy::Isize => self.types.isize,
2290 ast::IntTy::I8 => self.types.i8,
2291 ast::IntTy::I16 => self.types.i16,
2292 ast::IntTy::I32 => self.types.i32,
2293 ast::IntTy::I64 => self.types.i64,
2294 ast::IntTy::I128 => self.types.i128,
2298 pub fn mk_mach_uint(self, tm: ast::UintTy) -> Ty<'tcx> {
2300 ast::UintTy::Usize => self.types.usize,
2301 ast::UintTy::U8 => self.types.u8,
2302 ast::UintTy::U16 => self.types.u16,
2303 ast::UintTy::U32 => self.types.u32,
2304 ast::UintTy::U64 => self.types.u64,
2305 ast::UintTy::U128 => self.types.u128,
2309 pub fn mk_mach_float(self, tm: ast::FloatTy) -> Ty<'tcx> {
2311 ast::FloatTy::F32 => self.types.f32,
2312 ast::FloatTy::F64 => self.types.f64,
2317 pub fn mk_str(self) -> Ty<'tcx> {
2322 pub fn mk_static_str(self) -> Ty<'tcx> {
2323 self.mk_imm_ref(self.lifetimes.re_static, self.mk_str())
2327 pub fn mk_adt(self, def: &'tcx AdtDef, substs: SubstsRef<'tcx>) -> Ty<'tcx> {
2328 // Take a copy of substs so that we own the vectors inside.
2329 self.mk_ty(Adt(def, substs))
2333 pub fn mk_foreign(self, def_id: DefId) -> Ty<'tcx> {
2334 self.mk_ty(Foreign(def_id))
2337 fn mk_generic_adt(self, wrapper_def_id: DefId, ty_param: Ty<'tcx>) -> Ty<'tcx> {
2338 let adt_def = self.adt_def(wrapper_def_id);
2339 let substs = InternalSubsts::for_item(self, wrapper_def_id, |param, substs| {
2341 GenericParamDefKind::Lifetime |
2342 GenericParamDefKind::Const => {
2345 GenericParamDefKind::Type { has_default, .. } => {
2346 if param.index == 0 {
2349 assert!(has_default);
2350 self.type_of(param.def_id).subst(self, substs).into()
2355 self.mk_ty(Adt(adt_def, substs))
2359 pub fn mk_box(self, ty: Ty<'tcx>) -> Ty<'tcx> {
2360 let def_id = self.require_lang_item(lang_items::OwnedBoxLangItem, None);
2361 self.mk_generic_adt(def_id, ty)
2365 pub fn mk_lang_item(self, ty: Ty<'tcx>, item: lang_items::LangItem) -> Option<Ty<'tcx>> {
2366 let def_id = self.lang_items().require(item).ok()?;
2367 Some(self.mk_generic_adt(def_id, ty))
2371 pub fn mk_maybe_uninit(self, ty: Ty<'tcx>) -> Ty<'tcx> {
2372 let def_id = self.require_lang_item(lang_items::MaybeUninitLangItem, None);
2373 self.mk_generic_adt(def_id, ty)
2377 pub fn mk_ptr(self, tm: TypeAndMut<'tcx>) -> Ty<'tcx> {
2378 self.mk_ty(RawPtr(tm))
2382 pub fn mk_ref(self, r: Region<'tcx>, tm: TypeAndMut<'tcx>) -> Ty<'tcx> {
2383 self.mk_ty(Ref(r, tm.ty, tm.mutbl))
2387 pub fn mk_mut_ref(self, r: Region<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
2388 self.mk_ref(r, TypeAndMut {ty: ty, mutbl: hir::MutMutable})
2392 pub fn mk_imm_ref(self, r: Region<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
2393 self.mk_ref(r, TypeAndMut {ty: ty, mutbl: hir::MutImmutable})
2397 pub fn mk_mut_ptr(self, ty: Ty<'tcx>) -> Ty<'tcx> {
2398 self.mk_ptr(TypeAndMut {ty: ty, mutbl: hir::MutMutable})
2402 pub fn mk_imm_ptr(self, ty: Ty<'tcx>) -> Ty<'tcx> {
2403 self.mk_ptr(TypeAndMut {ty: ty, mutbl: hir::MutImmutable})
2407 pub fn mk_nil_ptr(self) -> Ty<'tcx> {
2408 self.mk_imm_ptr(self.mk_unit())
2412 pub fn mk_array(self, ty: Ty<'tcx>, n: u64) -> Ty<'tcx> {
2413 self.mk_ty(Array(ty, ty::Const::from_usize(self, n)))
2417 pub fn mk_slice(self, ty: Ty<'tcx>) -> Ty<'tcx> {
2418 self.mk_ty(Slice(ty))
2422 pub fn intern_tup(self, ts: &[Ty<'tcx>]) -> Ty<'tcx> {
2423 let kinds: Vec<_> = ts.into_iter().map(|&t| GenericArg::from(t)).collect();
2424 self.mk_ty(Tuple(self.intern_substs(&kinds)))
2427 pub fn mk_tup<I: InternAs<[Ty<'tcx>], Ty<'tcx>>>(self, iter: I) -> I::Output {
2428 iter.intern_with(|ts| {
2429 let kinds: Vec<_> = ts.into_iter().map(|&t| GenericArg::from(t)).collect();
2430 self.mk_ty(Tuple(self.intern_substs(&kinds)))
2435 pub fn mk_unit(self) -> Ty<'tcx> {
2440 pub fn mk_diverging_default(self) -> Ty<'tcx> {
2441 if self.features().never_type {
2444 self.intern_tup(&[])
2449 pub fn mk_bool(self) -> Ty<'tcx> {
2454 pub fn mk_fn_def(self, def_id: DefId,
2455 substs: SubstsRef<'tcx>) -> Ty<'tcx> {
2456 self.mk_ty(FnDef(def_id, substs))
2460 pub fn mk_fn_ptr(self, fty: PolyFnSig<'tcx>) -> Ty<'tcx> {
2461 self.mk_ty(FnPtr(fty))
2467 obj: ty::Binder<&'tcx List<ExistentialPredicate<'tcx>>>,
2468 reg: ty::Region<'tcx>
2470 self.mk_ty(Dynamic(obj, reg))
2474 pub fn mk_projection(self,
2476 substs: SubstsRef<'tcx>)
2478 self.mk_ty(Projection(ProjectionTy {
2485 pub fn mk_closure(self, closure_id: DefId, closure_substs: ClosureSubsts<'tcx>)
2487 self.mk_ty(Closure(closure_id, closure_substs))
2491 pub fn mk_generator(self,
2493 generator_substs: GeneratorSubsts<'tcx>,
2494 movability: hir::GeneratorMovability)
2496 self.mk_ty(Generator(id, generator_substs, movability))
2500 pub fn mk_generator_witness(self, types: ty::Binder<&'tcx List<Ty<'tcx>>>) -> Ty<'tcx> {
2501 self.mk_ty(GeneratorWitness(types))
2505 pub fn mk_ty_var(self, v: TyVid) -> Ty<'tcx> {
2506 self.mk_ty_infer(TyVar(v))
2510 pub fn mk_const_var(self, v: ConstVid<'tcx>, ty: Ty<'tcx>) -> &'tcx Const<'tcx> {
2511 self.mk_const(ty::Const {
2512 val: ConstValue::Infer(InferConst::Var(v)),
2518 pub fn mk_int_var(self, v: IntVid) -> Ty<'tcx> {
2519 self.mk_ty_infer(IntVar(v))
2523 pub fn mk_float_var(self, v: FloatVid) -> Ty<'tcx> {
2524 self.mk_ty_infer(FloatVar(v))
2528 pub fn mk_ty_infer(self, it: InferTy) -> Ty<'tcx> {
2529 self.mk_ty(Infer(it))
2533 pub fn mk_const_infer(
2535 ic: InferConst<'tcx>,
2537 ) -> &'tcx ty::Const<'tcx> {
2538 self.mk_const(ty::Const {
2539 val: ConstValue::Infer(ic),
2545 pub fn mk_ty_param(self, index: u32, name: InternedString) -> Ty<'tcx> {
2546 self.mk_ty(Param(ParamTy { index, name: name }))
2550 pub fn mk_const_param(
2553 name: InternedString,
2555 ) -> &'tcx Const<'tcx> {
2556 self.mk_const(ty::Const {
2557 val: ConstValue::Param(ParamConst { index, name }),
2563 pub fn mk_param_from_def(self, param: &ty::GenericParamDef) -> GenericArg<'tcx> {
2565 GenericParamDefKind::Lifetime => {
2566 self.mk_region(ty::ReEarlyBound(param.to_early_bound_region_data())).into()
2568 GenericParamDefKind::Type { .. } => self.mk_ty_param(param.index, param.name).into(),
2569 GenericParamDefKind::Const => {
2570 self.mk_const_param(param.index, param.name, self.type_of(param.def_id)).into()
2576 pub fn mk_opaque(self, def_id: DefId, substs: SubstsRef<'tcx>) -> Ty<'tcx> {
2577 self.mk_ty(Opaque(def_id, substs))
2580 pub fn intern_existential_predicates(self, eps: &[ExistentialPredicate<'tcx>])
2581 -> &'tcx List<ExistentialPredicate<'tcx>> {
2582 assert!(!eps.is_empty());
2583 assert!(eps.windows(2).all(|w| w[0].stable_cmp(self, &w[1]) != Ordering::Greater));
2584 self._intern_existential_predicates(eps)
2587 pub fn intern_predicates(self, preds: &[Predicate<'tcx>])
2588 -> &'tcx List<Predicate<'tcx>> {
2589 // FIXME consider asking the input slice to be sorted to avoid
2590 // re-interning permutations, in which case that would be asserted
2592 if preds.len() == 0 {
2593 // The macro-generated method below asserts we don't intern an empty slice.
2596 self._intern_predicates(preds)
2600 pub fn intern_type_list(self, ts: &[Ty<'tcx>]) -> &'tcx List<Ty<'tcx>> {
2604 self._intern_type_list(ts)
2608 pub fn intern_substs(self, ts: &[GenericArg<'tcx>]) -> &'tcx List<GenericArg<'tcx>> {
2612 self._intern_substs(ts)
2616 pub fn intern_projs(self, ps: &[ProjectionKind]) -> &'tcx List<ProjectionKind> {
2620 self._intern_projs(ps)
2624 pub fn intern_canonical_var_infos(self, ts: &[CanonicalVarInfo]) -> CanonicalVarInfos<'tcx> {
2628 self._intern_canonical_var_infos(ts)
2632 pub fn intern_clauses(self, ts: &[Clause<'tcx>]) -> Clauses<'tcx> {
2636 self._intern_clauses(ts)
2640 pub fn intern_goals(self, ts: &[Goal<'tcx>]) -> Goals<'tcx> {
2644 self._intern_goals(ts)
2648 pub fn mk_fn_sig<I>(self,
2652 unsafety: hir::Unsafety,
2654 -> <I::Item as InternIteratorElement<Ty<'tcx>, ty::FnSig<'tcx>>>::Output
2656 I: Iterator<Item: InternIteratorElement<Ty<'tcx>, ty::FnSig<'tcx>>>,
2658 inputs.chain(iter::once(output)).intern_with(|xs| ty::FnSig {
2659 inputs_and_output: self.intern_type_list(xs),
2660 c_variadic, unsafety, abi
2664 pub fn mk_existential_predicates<I: InternAs<[ExistentialPredicate<'tcx>],
2665 &'tcx List<ExistentialPredicate<'tcx>>>>(self, iter: I)
2667 iter.intern_with(|xs| self.intern_existential_predicates(xs))
2670 pub fn mk_predicates<I: InternAs<[Predicate<'tcx>],
2671 &'tcx List<Predicate<'tcx>>>>(self, iter: I)
2673 iter.intern_with(|xs| self.intern_predicates(xs))
2676 pub fn mk_type_list<I: InternAs<[Ty<'tcx>],
2677 &'tcx List<Ty<'tcx>>>>(self, iter: I) -> I::Output {
2678 iter.intern_with(|xs| self.intern_type_list(xs))
2681 pub fn mk_substs<I: InternAs<[GenericArg<'tcx>],
2682 &'tcx List<GenericArg<'tcx>>>>(self, iter: I) -> I::Output {
2683 iter.intern_with(|xs| self.intern_substs(xs))
2686 pub fn mk_substs_trait(self,
2688 rest: &[GenericArg<'tcx>])
2691 self.mk_substs(iter::once(self_ty.into()).chain(rest.iter().cloned()))
2694 pub fn mk_clauses<I: InternAs<[Clause<'tcx>], Clauses<'tcx>>>(self, iter: I) -> I::Output {
2695 iter.intern_with(|xs| self.intern_clauses(xs))
2698 pub fn mk_goals<I: InternAs<[Goal<'tcx>], Goals<'tcx>>>(self, iter: I) -> I::Output {
2699 iter.intern_with(|xs| self.intern_goals(xs))
2702 pub fn lint_hir<S: Into<MultiSpan>>(self,
2703 lint: &'static Lint,
2707 self.struct_span_lint_hir(lint, hir_id, span.into(), msg).emit()
2710 pub fn lint_hir_note<S: Into<MultiSpan>>(self,
2711 lint: &'static Lint,
2716 let mut err = self.struct_span_lint_hir(lint, hir_id, span.into(), msg);
2721 pub fn lint_node_note<S: Into<MultiSpan>>(self,
2722 lint: &'static Lint,
2727 let mut err = self.struct_span_lint_hir(lint, id, span.into(), msg);
2732 /// Walks upwards from `id` to find a node which might change lint levels with attributes.
2733 /// It stops at `bound` and just returns it if reached.
2734 pub fn maybe_lint_level_root_bounded(
2743 if lint::maybe_lint_level_root(self, id) {
2746 let next = self.hir().get_parent_node(id);
2748 bug!("lint traversal reached the root of the crate");
2754 pub fn lint_level_at_node(
2756 lint: &'static Lint,
2758 ) -> (lint::Level, lint::LintSource) {
2759 let sets = self.lint_levels(LOCAL_CRATE);
2761 if let Some(pair) = sets.level_and_source(lint, id, self.sess) {
2764 let next = self.hir().get_parent_node(id);
2766 bug!("lint traversal reached the root of the crate");
2772 pub fn struct_span_lint_hir<S: Into<MultiSpan>>(self,
2773 lint: &'static Lint,
2777 -> DiagnosticBuilder<'tcx>
2779 let (level, src) = self.lint_level_at_node(lint, hir_id);
2780 lint::struct_lint_level(self.sess, lint, level, src, Some(span.into()), msg)
2783 pub fn struct_lint_node(self, lint: &'static Lint, id: HirId, msg: &str)
2784 -> DiagnosticBuilder<'tcx>
2786 let (level, src) = self.lint_level_at_node(lint, id);
2787 lint::struct_lint_level(self.sess, lint, level, src, None, msg)
2790 pub fn in_scope_traits(self, id: HirId) -> Option<&'tcx StableVec<TraitCandidate>> {
2791 self.in_scope_traits_map(id.owner)
2792 .and_then(|map| map.get(&id.local_id))
2795 pub fn named_region(self, id: HirId) -> Option<resolve_lifetime::Region> {
2796 self.named_region_map(id.owner)
2797 .and_then(|map| map.get(&id.local_id).cloned())
2800 pub fn is_late_bound(self, id: HirId) -> bool {
2801 self.is_late_bound_map(id.owner)
2802 .map(|set| set.contains(&id.local_id))
2806 pub fn object_lifetime_defaults(self, id: HirId) -> Option<&'tcx [ObjectLifetimeDefault]> {
2807 self.object_lifetime_defaults_map(id.owner)
2808 .and_then(|map| map.get(&id.local_id).map(|v| &**v))
2812 pub trait InternAs<T: ?Sized, R> {
2814 fn intern_with<F>(self, f: F) -> Self::Output
2815 where F: FnOnce(&T) -> R;
2818 impl<I, T, R, E> InternAs<[T], R> for I
2819 where E: InternIteratorElement<T, R>,
2820 I: Iterator<Item=E> {
2821 type Output = E::Output;
2822 fn intern_with<F>(self, f: F) -> Self::Output
2823 where F: FnOnce(&[T]) -> R {
2824 E::intern_with(self, f)
2828 pub trait InternIteratorElement<T, R>: Sized {
2830 fn intern_with<I: Iterator<Item=Self>, F: FnOnce(&[T]) -> R>(iter: I, f: F) -> Self::Output;
2833 impl<T, R> InternIteratorElement<T, R> for T {
2835 fn intern_with<I: Iterator<Item=Self>, F: FnOnce(&[T]) -> R>(iter: I, f: F) -> Self::Output {
2836 f(&iter.collect::<SmallVec<[_; 8]>>())
2840 impl<'a, T, R> InternIteratorElement<T, R> for &'a T
2844 fn intern_with<I: Iterator<Item=Self>, F: FnOnce(&[T]) -> R>(iter: I, f: F) -> Self::Output {
2845 f(&iter.cloned().collect::<SmallVec<[_; 8]>>())
2849 impl<T, R, E> InternIteratorElement<T, R> for Result<T, E> {
2850 type Output = Result<R, E>;
2851 fn intern_with<I: Iterator<Item=Self>, F: FnOnce(&[T]) -> R>(iter: I, f: F) -> Self::Output {
2852 Ok(f(&iter.collect::<Result<SmallVec<[_; 8]>, _>>()?))
2856 // We are comparing types with different invariant lifetimes, so `ptr::eq`
2857 // won't work for us.
2858 fn ptr_eq<T, U>(t: *const T, u: *const U) -> bool {
2859 t as *const () == u as *const ()
2862 pub fn provide(providers: &mut ty::query::Providers<'_>) {
2863 providers.in_scope_traits_map = |tcx, id| tcx.gcx.trait_map.get(&id);
2864 providers.module_exports = |tcx, id| tcx.gcx.export_map.get(&id).map(|v| &v[..]);
2865 providers.crate_name = |tcx, id| {
2866 assert_eq!(id, LOCAL_CRATE);
2869 providers.get_lib_features = |tcx, id| {
2870 assert_eq!(id, LOCAL_CRATE);
2871 tcx.arena.alloc(middle::lib_features::collect(tcx))
2873 providers.get_lang_items = |tcx, id| {
2874 assert_eq!(id, LOCAL_CRATE);
2875 tcx.arena.alloc(middle::lang_items::collect(tcx))
2877 providers.diagnostic_items = |tcx, id| {
2878 assert_eq!(id, LOCAL_CRATE);
2879 middle::diagnostic_items::collect(tcx)
2881 providers.all_diagnostic_items = |tcx, id| {
2882 assert_eq!(id, LOCAL_CRATE);
2883 middle::diagnostic_items::collect_all(tcx)
2885 providers.maybe_unused_trait_import = |tcx, id| {
2886 tcx.maybe_unused_trait_imports.contains(&id)
2888 providers.maybe_unused_extern_crates = |tcx, cnum| {
2889 assert_eq!(cnum, LOCAL_CRATE);
2890 &tcx.maybe_unused_extern_crates[..]
2892 providers.names_imported_by_glob_use = |tcx, id| {
2893 assert_eq!(id.krate, LOCAL_CRATE);
2894 Lrc::new(tcx.glob_map.get(&id).cloned().unwrap_or_default())
2897 providers.stability_index = |tcx, cnum| {
2898 assert_eq!(cnum, LOCAL_CRATE);
2899 tcx.arena.alloc(stability::Index::new(tcx))
2901 providers.lookup_stability = |tcx, id| {
2902 assert_eq!(id.krate, LOCAL_CRATE);
2903 let id = tcx.hir().definitions().def_index_to_hir_id(id.index);
2904 tcx.stability().local_stability(id)
2906 providers.lookup_deprecation_entry = |tcx, id| {
2907 assert_eq!(id.krate, LOCAL_CRATE);
2908 let id = tcx.hir().definitions().def_index_to_hir_id(id.index);
2909 tcx.stability().local_deprecation_entry(id)
2911 providers.extern_mod_stmt_cnum = |tcx, id| {
2912 let id = tcx.hir().as_local_node_id(id).unwrap();
2913 tcx.cstore.extern_mod_stmt_cnum_untracked(id)
2915 providers.all_crate_nums = |tcx, cnum| {
2916 assert_eq!(cnum, LOCAL_CRATE);
2917 tcx.arena.alloc_slice(&tcx.cstore.crates_untracked())
2919 providers.postorder_cnums = |tcx, cnum| {
2920 assert_eq!(cnum, LOCAL_CRATE);
2921 tcx.arena.alloc_slice(&tcx.cstore.postorder_cnums_untracked())
2923 providers.output_filenames = |tcx, cnum| {
2924 assert_eq!(cnum, LOCAL_CRATE);
2925 tcx.output_filenames.clone()
2927 providers.features_query = |tcx, cnum| {
2928 assert_eq!(cnum, LOCAL_CRATE);
2929 tcx.arena.alloc(tcx.sess.features_untracked().clone())
2931 providers.is_panic_runtime = |tcx, cnum| {
2932 assert_eq!(cnum, LOCAL_CRATE);
2933 attr::contains_name(tcx.hir().krate_attrs(), sym::panic_runtime)
2935 providers.is_compiler_builtins = |tcx, cnum| {
2936 assert_eq!(cnum, LOCAL_CRATE);
2937 attr::contains_name(tcx.hir().krate_attrs(), sym::compiler_builtins)