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::{Kind, 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, UnpackedKind};
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, StableHasherResult, 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};
69 use rustc_target::spec::abi;
70 use rustc_macros::HashStable;
73 use syntax::source_map::MultiSpan;
74 use syntax::feature_gate;
75 use syntax::symbol::{Symbol, InternedString, kw, sym};
78 pub struct AllArenas {
79 pub interner: SyncDroplessArena,
83 pub fn new() -> Self {
85 interner: SyncDroplessArena::default(),
90 type InternedSet<'tcx, T> = ShardedHashMap<Interned<'tcx, T>, ()>;
92 pub struct CtxtInterners<'tcx> {
93 /// The arena that types, regions, etc. are allocated from.
94 arena: &'tcx SyncDroplessArena,
96 /// Specifically use a speedy hash algorithm for these hash sets, since
97 /// they're accessed quite often.
98 type_: InternedSet<'tcx, TyS<'tcx>>,
99 type_list: InternedSet<'tcx, List<Ty<'tcx>>>,
100 substs: InternedSet<'tcx, InternalSubsts<'tcx>>,
101 canonical_var_infos: InternedSet<'tcx, List<CanonicalVarInfo>>,
102 region: InternedSet<'tcx, RegionKind>,
103 existential_predicates: InternedSet<'tcx, List<ExistentialPredicate<'tcx>>>,
104 predicates: InternedSet<'tcx, List<Predicate<'tcx>>>,
105 clauses: InternedSet<'tcx, List<Clause<'tcx>>>,
106 goal: InternedSet<'tcx, GoalKind<'tcx>>,
107 goal_list: InternedSet<'tcx, List<Goal<'tcx>>>,
108 projs: InternedSet<'tcx, List<ProjectionKind>>,
109 const_: InternedSet<'tcx, Const<'tcx>>,
112 impl<'tcx> CtxtInterners<'tcx> {
113 fn new(arena: &'tcx SyncDroplessArena) -> CtxtInterners<'tcx> {
116 type_: Default::default(),
117 type_list: Default::default(),
118 substs: Default::default(),
119 region: Default::default(),
120 existential_predicates: Default::default(),
121 canonical_var_infos: Default::default(),
122 predicates: Default::default(),
123 clauses: Default::default(),
124 goal: Default::default(),
125 goal_list: Default::default(),
126 projs: Default::default(),
127 const_: Default::default(),
132 #[allow(rustc::usage_of_ty_tykind)]
137 self.type_.intern(st, |st| {
138 let flags = super::flags::FlagComputation::for_sty(&st);
140 let ty_struct = TyS {
143 outer_exclusive_binder: flags.outer_exclusive_binder,
146 Interned(self.arena.alloc(ty_struct))
151 pub struct Common<'tcx> {
152 pub empty_predicates: ty::GenericPredicates<'tcx>,
155 pub struct CommonTypes<'tcx> {
174 pub self_param: Ty<'tcx>,
177 /// Dummy type used for the `Self` of a `TraitRef` created for converting
178 /// a trait object, and which gets removed in `ExistentialTraitRef`.
179 /// This type must not appear anywhere in other converted types.
180 pub trait_object_dummy_self: Ty<'tcx>,
183 pub struct CommonLifetimes<'tcx> {
184 pub re_empty: Region<'tcx>,
185 pub re_static: Region<'tcx>,
186 pub re_erased: Region<'tcx>,
189 pub struct CommonConsts<'tcx> {
190 pub err: &'tcx Const<'tcx>,
193 pub struct LocalTableInContext<'a, V> {
194 local_id_root: Option<DefId>,
195 data: &'a ItemLocalMap<V>
198 /// Validate that the given HirId (respectively its `local_id` part) can be
199 /// safely used as a key in the tables of a TypeckTable. For that to be
200 /// the case, the HirId must have the same `owner` as all the other IDs in
201 /// this table (signified by `local_id_root`). Otherwise the HirId
202 /// would be in a different frame of reference and using its `local_id`
203 /// would result in lookup errors, or worse, in silently wrong data being
205 fn validate_hir_id_for_typeck_tables(local_id_root: Option<DefId>,
208 if cfg!(debug_assertions) {
209 if let Some(local_id_root) = local_id_root {
210 if hir_id.owner != local_id_root.index {
211 ty::tls::with(|tcx| {
212 bug!("node {} with HirId::owner {:?} cannot be placed in \
213 TypeckTables with local_id_root {:?}",
214 tcx.hir().node_to_string(hir_id),
215 DefId::local(hir_id.owner),
220 // We use "Null Object" TypeckTables in some of the analysis passes.
221 // These are just expected to be empty and their `local_id_root` is
222 // `None`. Therefore we cannot verify whether a given `HirId` would
223 // be a valid key for the given table. Instead we make sure that
224 // nobody tries to write to such a Null Object table.
226 bug!("access to invalid TypeckTables")
232 impl<'a, V> LocalTableInContext<'a, V> {
233 pub fn contains_key(&self, id: hir::HirId) -> bool {
234 validate_hir_id_for_typeck_tables(self.local_id_root, id, false);
235 self.data.contains_key(&id.local_id)
238 pub fn get(&self, id: hir::HirId) -> Option<&V> {
239 validate_hir_id_for_typeck_tables(self.local_id_root, id, false);
240 self.data.get(&id.local_id)
243 pub fn iter(&self) -> hash_map::Iter<'_, hir::ItemLocalId, V> {
248 impl<'a, V> ::std::ops::Index<hir::HirId> for LocalTableInContext<'a, V> {
251 fn index(&self, key: hir::HirId) -> &V {
252 self.get(key).expect("LocalTableInContext: key not found")
256 pub struct LocalTableInContextMut<'a, V> {
257 local_id_root: Option<DefId>,
258 data: &'a mut ItemLocalMap<V>
261 impl<'a, V> LocalTableInContextMut<'a, V> {
262 pub fn get_mut(&mut self, id: hir::HirId) -> Option<&mut V> {
263 validate_hir_id_for_typeck_tables(self.local_id_root, id, true);
264 self.data.get_mut(&id.local_id)
267 pub fn entry(&mut self, id: hir::HirId) -> Entry<'_, hir::ItemLocalId, V> {
268 validate_hir_id_for_typeck_tables(self.local_id_root, id, true);
269 self.data.entry(id.local_id)
272 pub fn insert(&mut self, id: hir::HirId, val: V) -> Option<V> {
273 validate_hir_id_for_typeck_tables(self.local_id_root, id, true);
274 self.data.insert(id.local_id, val)
277 pub fn remove(&mut self, id: hir::HirId) -> Option<V> {
278 validate_hir_id_for_typeck_tables(self.local_id_root, id, true);
279 self.data.remove(&id.local_id)
283 /// All information necessary to validate and reveal an `impl Trait`.
284 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
285 pub struct ResolvedOpaqueTy<'tcx> {
286 /// The revealed type as seen by this function.
287 pub concrete_type: Ty<'tcx>,
288 /// Generic parameters on the opaque type as passed by this function.
289 /// For `type Foo<A, B> = impl Bar<A, B>; fn foo<T, U>() -> Foo<T, U> { .. }`
290 /// this is `[T, U]`, not `[A, B]`.
291 pub substs: SubstsRef<'tcx>,
294 #[derive(RustcEncodable, RustcDecodable, Debug)]
295 pub struct TypeckTables<'tcx> {
296 /// The HirId::owner all ItemLocalIds in this table are relative to.
297 pub local_id_root: Option<DefId>,
299 /// Resolved definitions for `<T>::X` associated paths and
300 /// method calls, including those of overloaded operators.
301 type_dependent_defs: ItemLocalMap<Result<(DefKind, DefId), ErrorReported>>,
303 /// Resolved field indices for field accesses in expressions (`S { field }`, `obj.field`)
304 /// or patterns (`S { field }`). The index is often useful by itself, but to learn more
305 /// about the field you also need definition of the variant to which the field
306 /// belongs, but it may not exist if it's a tuple field (`tuple.0`).
307 field_indices: ItemLocalMap<usize>,
309 /// Stores the types for various nodes in the AST. Note that this table
310 /// is not guaranteed to be populated until after typeck. See
311 /// typeck::check::fn_ctxt for details.
312 node_types: ItemLocalMap<Ty<'tcx>>,
314 /// Stores the type parameters which were substituted to obtain the type
315 /// of this node. This only applies to nodes that refer to entities
316 /// parameterized by type parameters, such as generic fns, types, or
318 node_substs: ItemLocalMap<SubstsRef<'tcx>>,
320 /// This will either store the canonicalized types provided by the user
321 /// or the substitutions that the user explicitly gave (if any) attached
322 /// to `id`. These will not include any inferred values. The canonical form
323 /// is used to capture things like `_` or other unspecified values.
325 /// For example, if the user wrote `foo.collect::<Vec<_>>()`, then the
326 /// canonical substitutions would include only `for<X> { Vec<X> }`.
328 /// See also `AscribeUserType` statement in MIR.
329 user_provided_types: ItemLocalMap<CanonicalUserType<'tcx>>,
331 /// Stores the canonicalized types provided by the user. See also
332 /// `AscribeUserType` statement in MIR.
333 pub user_provided_sigs: DefIdMap<CanonicalPolyFnSig<'tcx>>,
335 adjustments: ItemLocalMap<Vec<ty::adjustment::Adjustment<'tcx>>>,
337 /// Stores the actual binding mode for all instances of hir::BindingAnnotation.
338 pat_binding_modes: ItemLocalMap<BindingMode>,
340 /// Stores the types which were implicitly dereferenced in pattern binding modes
341 /// for later usage in HAIR lowering. For example,
344 /// match &&Some(5i32) {
349 /// leads to a `vec![&&Option<i32>, &Option<i32>]`. Empty vectors are not stored.
352 /// https://github.com/rust-lang/rfcs/blob/master/text/2005-match-ergonomics.md#definitions
353 pat_adjustments: ItemLocalMap<Vec<Ty<'tcx>>>,
356 pub upvar_capture_map: ty::UpvarCaptureMap<'tcx>,
358 /// Records the reasons that we picked the kind of each closure;
359 /// not all closures are present in the map.
360 closure_kind_origins: ItemLocalMap<(Span, ast::Name)>,
362 /// For each fn, records the "liberated" types of its arguments
363 /// and return type. Liberated means that all bound regions
364 /// (including late-bound regions) are replaced with free
365 /// equivalents. This table is not used in codegen (since regions
366 /// are erased there) and hence is not serialized to metadata.
367 liberated_fn_sigs: ItemLocalMap<ty::FnSig<'tcx>>,
369 /// For each FRU expression, record the normalized types of the fields
370 /// of the struct - this is needed because it is non-trivial to
371 /// normalize while preserving regions. This table is used only in
372 /// MIR construction and hence is not serialized to metadata.
373 fru_field_types: ItemLocalMap<Vec<Ty<'tcx>>>,
375 /// For every coercion cast we add the HIR node ID of the cast
376 /// expression to this set.
377 coercion_casts: ItemLocalSet,
379 /// Set of trait imports actually used in the method resolution.
380 /// This is used for warning unused imports. During type
381 /// checking, this `Lrc` should not be cloned: it must have a ref-count
382 /// of 1 so that we can insert things into the set mutably.
383 pub used_trait_imports: Lrc<DefIdSet>,
385 /// If any errors occurred while type-checking this body,
386 /// this field will be set to `true`.
387 pub tainted_by_errors: bool,
389 /// Stores the free-region relationships that were deduced from
390 /// its where-clauses and parameter types. These are then
391 /// read-again by borrowck.
392 pub free_region_map: FreeRegionMap<'tcx>,
394 /// All the opaque types that are restricted to concrete types
395 /// by this function.
396 pub concrete_opaque_types: FxHashMap<DefId, ResolvedOpaqueTy<'tcx>>,
398 /// Given the closure ID this map provides the list of UpvarIDs used by it.
399 /// The upvarID contains the HIR node ID and it also contains the full path
400 /// leading to the member of the struct or tuple that is used instead of the
402 pub upvar_list: ty::UpvarListMap,
405 impl<'tcx> TypeckTables<'tcx> {
406 pub fn empty(local_id_root: Option<DefId>) -> TypeckTables<'tcx> {
409 type_dependent_defs: Default::default(),
410 field_indices: Default::default(),
411 user_provided_types: Default::default(),
412 user_provided_sigs: Default::default(),
413 node_types: Default::default(),
414 node_substs: Default::default(),
415 adjustments: Default::default(),
416 pat_binding_modes: Default::default(),
417 pat_adjustments: Default::default(),
418 upvar_capture_map: Default::default(),
419 closure_kind_origins: Default::default(),
420 liberated_fn_sigs: Default::default(),
421 fru_field_types: Default::default(),
422 coercion_casts: Default::default(),
423 used_trait_imports: Lrc::new(Default::default()),
424 tainted_by_errors: false,
425 free_region_map: Default::default(),
426 concrete_opaque_types: Default::default(),
427 upvar_list: Default::default(),
431 /// Returns the final resolution of a `QPath` in an `Expr` or `Pat` node.
432 pub fn qpath_res(&self, qpath: &hir::QPath, id: hir::HirId) -> Res {
434 hir::QPath::Resolved(_, ref path) => path.res,
435 hir::QPath::TypeRelative(..) => self.type_dependent_def(id)
436 .map_or(Res::Err, |(kind, def_id)| Res::Def(kind, def_id)),
440 pub fn type_dependent_defs(
442 ) -> LocalTableInContext<'_, Result<(DefKind, DefId), ErrorReported>> {
443 LocalTableInContext {
444 local_id_root: self.local_id_root,
445 data: &self.type_dependent_defs
449 pub fn type_dependent_def(&self, id: HirId) -> Option<(DefKind, DefId)> {
450 validate_hir_id_for_typeck_tables(self.local_id_root, id, false);
451 self.type_dependent_defs.get(&id.local_id).cloned().and_then(|r| r.ok())
454 pub fn type_dependent_def_id(&self, id: HirId) -> Option<DefId> {
455 self.type_dependent_def(id).map(|(_, def_id)| def_id)
458 pub fn type_dependent_defs_mut(
460 ) -> LocalTableInContextMut<'_, Result<(DefKind, DefId), ErrorReported>> {
461 LocalTableInContextMut {
462 local_id_root: self.local_id_root,
463 data: &mut self.type_dependent_defs
467 pub fn field_indices(&self) -> LocalTableInContext<'_, usize> {
468 LocalTableInContext {
469 local_id_root: self.local_id_root,
470 data: &self.field_indices
474 pub fn field_indices_mut(&mut self) -> LocalTableInContextMut<'_, usize> {
475 LocalTableInContextMut {
476 local_id_root: self.local_id_root,
477 data: &mut self.field_indices
481 pub fn user_provided_types(
483 ) -> LocalTableInContext<'_, CanonicalUserType<'tcx>> {
484 LocalTableInContext {
485 local_id_root: self.local_id_root,
486 data: &self.user_provided_types
490 pub fn user_provided_types_mut(
492 ) -> LocalTableInContextMut<'_, CanonicalUserType<'tcx>> {
493 LocalTableInContextMut {
494 local_id_root: self.local_id_root,
495 data: &mut self.user_provided_types
499 pub fn node_types(&self) -> LocalTableInContext<'_, Ty<'tcx>> {
500 LocalTableInContext {
501 local_id_root: self.local_id_root,
502 data: &self.node_types
506 pub fn node_types_mut(&mut self) -> LocalTableInContextMut<'_, Ty<'tcx>> {
507 LocalTableInContextMut {
508 local_id_root: self.local_id_root,
509 data: &mut self.node_types
513 pub fn node_type(&self, id: hir::HirId) -> Ty<'tcx> {
514 self.node_type_opt(id).unwrap_or_else(||
515 bug!("node_type: no type for node `{}`",
516 tls::with(|tcx| tcx.hir().node_to_string(id)))
520 pub fn node_type_opt(&self, id: hir::HirId) -> Option<Ty<'tcx>> {
521 validate_hir_id_for_typeck_tables(self.local_id_root, id, false);
522 self.node_types.get(&id.local_id).cloned()
525 pub fn node_substs_mut(&mut self) -> LocalTableInContextMut<'_, SubstsRef<'tcx>> {
526 LocalTableInContextMut {
527 local_id_root: self.local_id_root,
528 data: &mut self.node_substs
532 pub fn node_substs(&self, id: hir::HirId) -> SubstsRef<'tcx> {
533 validate_hir_id_for_typeck_tables(self.local_id_root, id, false);
534 self.node_substs.get(&id.local_id).cloned().unwrap_or_else(|| InternalSubsts::empty())
537 pub fn node_substs_opt(&self, id: hir::HirId) -> Option<SubstsRef<'tcx>> {
538 validate_hir_id_for_typeck_tables(self.local_id_root, id, false);
539 self.node_substs.get(&id.local_id).cloned()
542 // Returns the type of a pattern as a monotype. Like @expr_ty, this function
543 // doesn't provide type parameter substitutions.
544 pub fn pat_ty(&self, pat: &hir::Pat) -> Ty<'tcx> {
545 self.node_type(pat.hir_id)
548 pub fn pat_ty_opt(&self, pat: &hir::Pat) -> Option<Ty<'tcx>> {
549 self.node_type_opt(pat.hir_id)
552 // Returns the type of an expression as a monotype.
554 // NB (1): This is the PRE-ADJUSTMENT TYPE for the expression. That is, in
555 // some cases, we insert `Adjustment` annotations such as auto-deref or
556 // auto-ref. The type returned by this function does not consider such
557 // adjustments. See `expr_ty_adjusted()` instead.
559 // NB (2): This type doesn't provide type parameter substitutions; e.g., if you
560 // ask for the type of "id" in "id(3)", it will return "fn(&isize) -> isize"
561 // instead of "fn(ty) -> T with T = isize".
562 pub fn expr_ty(&self, expr: &hir::Expr) -> Ty<'tcx> {
563 self.node_type(expr.hir_id)
566 pub fn expr_ty_opt(&self, expr: &hir::Expr) -> Option<Ty<'tcx>> {
567 self.node_type_opt(expr.hir_id)
570 pub fn adjustments(&self) -> LocalTableInContext<'_, Vec<ty::adjustment::Adjustment<'tcx>>> {
571 LocalTableInContext {
572 local_id_root: self.local_id_root,
573 data: &self.adjustments
577 pub fn adjustments_mut(&mut self)
578 -> LocalTableInContextMut<'_, Vec<ty::adjustment::Adjustment<'tcx>>> {
579 LocalTableInContextMut {
580 local_id_root: self.local_id_root,
581 data: &mut self.adjustments
585 pub fn expr_adjustments(&self, expr: &hir::Expr)
586 -> &[ty::adjustment::Adjustment<'tcx>] {
587 validate_hir_id_for_typeck_tables(self.local_id_root, expr.hir_id, false);
588 self.adjustments.get(&expr.hir_id.local_id).map_or(&[], |a| &a[..])
591 /// Returns the type of `expr`, considering any `Adjustment`
592 /// entry recorded for that expression.
593 pub fn expr_ty_adjusted(&self, expr: &hir::Expr) -> Ty<'tcx> {
594 self.expr_adjustments(expr)
596 .map_or_else(|| self.expr_ty(expr), |adj| adj.target)
599 pub fn expr_ty_adjusted_opt(&self, expr: &hir::Expr) -> Option<Ty<'tcx>> {
600 self.expr_adjustments(expr)
602 .map(|adj| adj.target)
603 .or_else(|| self.expr_ty_opt(expr))
606 pub fn is_method_call(&self, expr: &hir::Expr) -> bool {
607 // Only paths and method calls/overloaded operators have
608 // entries in type_dependent_defs, ignore the former here.
609 if let hir::ExprKind::Path(_) = expr.node {
613 match self.type_dependent_defs().get(expr.hir_id) {
614 Some(Ok((DefKind::Method, _))) => true,
619 pub fn pat_binding_modes(&self) -> LocalTableInContext<'_, BindingMode> {
620 LocalTableInContext {
621 local_id_root: self.local_id_root,
622 data: &self.pat_binding_modes
626 pub fn pat_binding_modes_mut(&mut self)
627 -> LocalTableInContextMut<'_, BindingMode> {
628 LocalTableInContextMut {
629 local_id_root: self.local_id_root,
630 data: &mut self.pat_binding_modes
634 pub fn pat_adjustments(&self) -> LocalTableInContext<'_, Vec<Ty<'tcx>>> {
635 LocalTableInContext {
636 local_id_root: self.local_id_root,
637 data: &self.pat_adjustments,
641 pub fn pat_adjustments_mut(&mut self)
642 -> LocalTableInContextMut<'_, Vec<Ty<'tcx>>> {
643 LocalTableInContextMut {
644 local_id_root: self.local_id_root,
645 data: &mut self.pat_adjustments,
649 pub fn upvar_capture(&self, upvar_id: ty::UpvarId) -> ty::UpvarCapture<'tcx> {
650 self.upvar_capture_map[&upvar_id]
653 pub fn closure_kind_origins(&self) -> LocalTableInContext<'_, (Span, ast::Name)> {
654 LocalTableInContext {
655 local_id_root: self.local_id_root,
656 data: &self.closure_kind_origins
660 pub fn closure_kind_origins_mut(&mut self) -> LocalTableInContextMut<'_, (Span, ast::Name)> {
661 LocalTableInContextMut {
662 local_id_root: self.local_id_root,
663 data: &mut self.closure_kind_origins
667 pub fn liberated_fn_sigs(&self) -> LocalTableInContext<'_, ty::FnSig<'tcx>> {
668 LocalTableInContext {
669 local_id_root: self.local_id_root,
670 data: &self.liberated_fn_sigs
674 pub fn liberated_fn_sigs_mut(&mut self) -> LocalTableInContextMut<'_, ty::FnSig<'tcx>> {
675 LocalTableInContextMut {
676 local_id_root: self.local_id_root,
677 data: &mut self.liberated_fn_sigs
681 pub fn fru_field_types(&self) -> LocalTableInContext<'_, Vec<Ty<'tcx>>> {
682 LocalTableInContext {
683 local_id_root: self.local_id_root,
684 data: &self.fru_field_types
688 pub fn fru_field_types_mut(&mut self) -> LocalTableInContextMut<'_, Vec<Ty<'tcx>>> {
689 LocalTableInContextMut {
690 local_id_root: self.local_id_root,
691 data: &mut self.fru_field_types
695 pub fn is_coercion_cast(&self, hir_id: hir::HirId) -> bool {
696 validate_hir_id_for_typeck_tables(self.local_id_root, hir_id, true);
697 self.coercion_casts.contains(&hir_id.local_id)
700 pub fn set_coercion_cast(&mut self, id: ItemLocalId) {
701 self.coercion_casts.insert(id);
704 pub fn coercion_casts(&self) -> &ItemLocalSet {
710 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for TypeckTables<'tcx> {
711 fn hash_stable<W: StableHasherResult>(&self,
712 hcx: &mut StableHashingContext<'a>,
713 hasher: &mut StableHasher<W>) {
714 let ty::TypeckTables {
716 ref type_dependent_defs,
718 ref user_provided_types,
719 ref user_provided_sigs,
723 ref pat_binding_modes,
725 ref upvar_capture_map,
726 ref closure_kind_origins,
727 ref liberated_fn_sigs,
732 ref used_trait_imports,
735 ref concrete_opaque_types,
740 hcx.with_node_id_hashing_mode(NodeIdHashingMode::HashDefPath, |hcx| {
741 type_dependent_defs.hash_stable(hcx, hasher);
742 field_indices.hash_stable(hcx, hasher);
743 user_provided_types.hash_stable(hcx, hasher);
744 user_provided_sigs.hash_stable(hcx, hasher);
745 node_types.hash_stable(hcx, hasher);
746 node_substs.hash_stable(hcx, hasher);
747 adjustments.hash_stable(hcx, hasher);
748 pat_binding_modes.hash_stable(hcx, hasher);
749 pat_adjustments.hash_stable(hcx, hasher);
750 hash_stable_hashmap(hcx, hasher, upvar_capture_map, |up_var_id, hcx| {
757 local_id_root.expect("trying to hash invalid TypeckTables");
759 let var_owner_def_id = DefId {
760 krate: local_id_root.krate,
761 index: var_path.hir_id.owner,
763 let closure_def_id = DefId {
764 krate: local_id_root.krate,
765 index: closure_expr_id.to_def_id().index,
767 (hcx.def_path_hash(var_owner_def_id),
768 var_path.hir_id.local_id,
769 hcx.def_path_hash(closure_def_id))
772 closure_kind_origins.hash_stable(hcx, hasher);
773 liberated_fn_sigs.hash_stable(hcx, hasher);
774 fru_field_types.hash_stable(hcx, hasher);
775 coercion_casts.hash_stable(hcx, hasher);
776 used_trait_imports.hash_stable(hcx, hasher);
777 tainted_by_errors.hash_stable(hcx, hasher);
778 free_region_map.hash_stable(hcx, hasher);
779 concrete_opaque_types.hash_stable(hcx, hasher);
780 upvar_list.hash_stable(hcx, hasher);
786 pub struct UserTypeAnnotationIndex {
788 DEBUG_FORMAT = "UserType({})",
789 const START_INDEX = 0,
793 /// Mapping of type annotation indices to canonical user type annotations.
794 pub type CanonicalUserTypeAnnotations<'tcx> =
795 IndexVec<UserTypeAnnotationIndex, CanonicalUserTypeAnnotation<'tcx>>;
797 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
798 pub struct CanonicalUserTypeAnnotation<'tcx> {
799 pub user_ty: CanonicalUserType<'tcx>,
801 pub inferred_ty: Ty<'tcx>,
804 BraceStructTypeFoldableImpl! {
805 impl<'tcx> TypeFoldable<'tcx> for CanonicalUserTypeAnnotation<'tcx> {
806 user_ty, span, inferred_ty
810 BraceStructLiftImpl! {
811 impl<'a, 'tcx> Lift<'tcx> for CanonicalUserTypeAnnotation<'a> {
812 type Lifted = CanonicalUserTypeAnnotation<'tcx>;
813 user_ty, span, inferred_ty
817 /// Canonicalized user type annotation.
818 pub type CanonicalUserType<'tcx> = Canonical<'tcx, UserType<'tcx>>;
820 impl CanonicalUserType<'tcx> {
821 /// Returns `true` if this represents a substitution of the form `[?0, ?1, ?2]`,
822 /// i.e., each thing is mapped to a canonical variable with the same index.
823 pub fn is_identity(&self) -> bool {
825 UserType::Ty(_) => false,
826 UserType::TypeOf(_, user_substs) => {
827 if user_substs.user_self_ty.is_some() {
831 user_substs.substs.iter().zip(BoundVar::new(0)..).all(|(kind, cvar)| {
832 match kind.unpack() {
833 UnpackedKind::Type(ty) => match ty.sty {
834 ty::Bound(debruijn, b) => {
835 // We only allow a `ty::INNERMOST` index in substitutions.
836 assert_eq!(debruijn, ty::INNERMOST);
842 UnpackedKind::Lifetime(r) => match r {
843 ty::ReLateBound(debruijn, br) => {
844 // We only allow a `ty::INNERMOST` index in substitutions.
845 assert_eq!(*debruijn, ty::INNERMOST);
846 cvar == br.assert_bound_var()
851 UnpackedKind::Const(ct) => match ct.val {
852 ConstValue::Infer(InferConst::Canonical(debruijn, b)) => {
853 // We only allow a `ty::INNERMOST` index in substitutions.
854 assert_eq!(debruijn, ty::INNERMOST);
866 /// A user-given type annotation attached to a constant. These arise
867 /// from constants that are named via paths, like `Foo::<A>::new` and
869 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
870 pub enum UserType<'tcx> {
873 /// The canonical type is the result of `type_of(def_id)` with the
874 /// given substitutions applied.
875 TypeOf(DefId, UserSubsts<'tcx>),
878 EnumTypeFoldableImpl! {
879 impl<'tcx> TypeFoldable<'tcx> for UserType<'tcx> {
881 (UserType::TypeOf)(def, substs),
886 impl<'a, 'tcx> Lift<'tcx> for UserType<'a> {
887 type Lifted = UserType<'tcx>;
889 (UserType::TypeOf)(def, substs),
893 impl<'tcx> CommonTypes<'tcx> {
894 fn new(interners: &CtxtInterners<'tcx>) -> CommonTypes<'tcx> {
895 let mk = |sty| interners.intern_ty(sty);
898 unit: mk(Tuple(List::empty())),
903 isize: mk(Int(ast::IntTy::Isize)),
904 i8: mk(Int(ast::IntTy::I8)),
905 i16: mk(Int(ast::IntTy::I16)),
906 i32: mk(Int(ast::IntTy::I32)),
907 i64: mk(Int(ast::IntTy::I64)),
908 i128: mk(Int(ast::IntTy::I128)),
909 usize: mk(Uint(ast::UintTy::Usize)),
910 u8: mk(Uint(ast::UintTy::U8)),
911 u16: mk(Uint(ast::UintTy::U16)),
912 u32: mk(Uint(ast::UintTy::U32)),
913 u64: mk(Uint(ast::UintTy::U64)),
914 u128: mk(Uint(ast::UintTy::U128)),
915 f32: mk(Float(ast::FloatTy::F32)),
916 f64: mk(Float(ast::FloatTy::F64)),
917 self_param: mk(ty::Param(ty::ParamTy {
919 name: kw::SelfUpper.as_interned_str(),
922 trait_object_dummy_self: mk(Infer(ty::FreshTy(0))),
927 impl<'tcx> CommonLifetimes<'tcx> {
928 fn new(interners: &CtxtInterners<'tcx>) -> CommonLifetimes<'tcx> {
930 interners.region.intern(r, |r| {
931 Interned(interners.arena.alloc(r))
936 re_empty: mk(RegionKind::ReEmpty),
937 re_static: mk(RegionKind::ReStatic),
938 re_erased: mk(RegionKind::ReErased),
943 impl<'tcx> CommonConsts<'tcx> {
944 fn new(interners: &CtxtInterners<'tcx>, types: &CommonTypes<'tcx>) -> CommonConsts<'tcx> {
946 interners.const_.intern(c, |c| {
947 Interned(interners.arena.alloc(c))
952 err: mk_const(ty::Const {
953 val: ConstValue::Scalar(Scalar::zst()),
960 // This struct contains information regarding the `ReFree(FreeRegion)` corresponding to a lifetime
963 pub struct FreeRegionInfo {
964 // def id corresponding to FreeRegion
966 // the bound region corresponding to FreeRegion
967 pub boundregion: ty::BoundRegion,
968 // checks if bound region is in Impl Item
969 pub is_impl_item: bool,
972 /// The central data structure of the compiler. It stores references
973 /// to the various **arenas** and also houses the results of the
974 /// various **compiler queries** that have been performed. See the
975 /// [rustc guide] for more details.
977 /// [rustc guide]: https://rust-lang.github.io/rustc-guide/ty.html
978 #[derive(Copy, Clone)]
979 #[cfg_attr(not(bootstrap), rustc_diagnostic_item = "TyCtxt")]
980 pub struct TyCtxt<'tcx> {
981 gcx: &'tcx GlobalCtxt<'tcx>,
984 impl<'tcx> Deref for TyCtxt<'tcx> {
985 type Target = &'tcx GlobalCtxt<'tcx>;
987 fn deref(&self) -> &Self::Target {
992 pub struct GlobalCtxt<'tcx> {
993 pub arena: WorkerLocal<Arena<'tcx>>,
995 interners: CtxtInterners<'tcx>,
997 cstore: &'tcx CrateStoreDyn,
999 pub sess: &'tcx Session,
1001 pub dep_graph: DepGraph,
1004 pub common: Common<'tcx>,
1006 /// Common types, pre-interned for your convenience.
1007 pub types: CommonTypes<'tcx>,
1009 /// Common lifetimes, pre-interned for your convenience.
1010 pub lifetimes: CommonLifetimes<'tcx>,
1012 /// Common consts, pre-interned for your convenience.
1013 pub consts: CommonConsts<'tcx>,
1015 /// Map indicating what traits are in scope for places where this
1016 /// is relevant; generated by resolve.
1017 trait_map: FxHashMap<DefIndex,
1018 FxHashMap<ItemLocalId,
1019 StableVec<TraitCandidate>>>,
1021 /// Export map produced by name resolution.
1022 export_map: FxHashMap<DefId, Vec<Export<hir::HirId>>>,
1024 hir_map: hir_map::Map<'tcx>,
1026 /// A map from `DefPathHash` -> `DefId`. Includes `DefId`s from the local crate
1027 /// as well as all upstream crates. Only populated in incremental mode.
1028 pub def_path_hash_to_def_id: Option<FxHashMap<DefPathHash, DefId>>,
1030 pub queries: query::Queries<'tcx>,
1032 maybe_unused_trait_imports: FxHashSet<DefId>,
1033 maybe_unused_extern_crates: Vec<(DefId, Span)>,
1034 /// A map of glob use to a set of names it actually imports. Currently only
1035 /// used in save-analysis.
1036 glob_map: FxHashMap<DefId, FxHashSet<ast::Name>>,
1037 /// Extern prelude entries. The value is `true` if the entry was introduced
1038 /// via `extern crate` item and not `--extern` option or compiler built-in.
1039 pub extern_prelude: FxHashMap<ast::Name, bool>,
1041 // Internal cache for metadata decoding. No need to track deps on this.
1042 pub rcache: Lock<FxHashMap<ty::CReaderCacheKey, Ty<'tcx>>>,
1044 /// Caches the results of trait selection. This cache is used
1045 /// for things that do not have to do with the parameters in scope.
1046 pub selection_cache: traits::SelectionCache<'tcx>,
1048 /// Caches the results of trait evaluation. This cache is used
1049 /// for things that do not have to do with the parameters in scope.
1050 /// Merge this with `selection_cache`?
1051 pub evaluation_cache: traits::EvaluationCache<'tcx>,
1053 /// The definite name of the current crate after taking into account
1054 /// attributes, commandline parameters, etc.
1055 pub crate_name: Symbol,
1057 /// Data layout specification for the current target.
1058 pub data_layout: TargetDataLayout,
1060 stability_interner: ShardedHashMap<&'tcx attr::Stability, ()>,
1062 /// Stores the value of constants (and deduplicates the actual memory)
1063 allocation_interner: ShardedHashMap<&'tcx Allocation, ()>,
1065 pub alloc_map: Lock<interpret::AllocMap<'tcx>>,
1067 layout_interner: ShardedHashMap<&'tcx LayoutDetails, ()>,
1069 /// A general purpose channel to throw data out the back towards LLVM worker
1072 /// This is intended to only get used during the codegen phase of the compiler
1073 /// when satisfying the query for a particular codegen unit. Internally in
1074 /// the query it'll send data along this channel to get processed later.
1075 pub tx_to_llvm_workers: Lock<mpsc::Sender<Box<dyn Any + Send>>>,
1077 output_filenames: Arc<OutputFilenames>,
1080 impl<'tcx> TyCtxt<'tcx> {
1081 /// Gets the global `TyCtxt`.
1083 pub fn global_tcx(self) -> TyCtxt<'tcx> {
1090 pub fn hir(self) -> &'tcx hir_map::Map<'tcx> {
1094 pub fn alloc_steal_mir(self, mir: Body<'tcx>) -> &'tcx Steal<Body<'tcx>> {
1095 self.arena.alloc(Steal::new(mir))
1098 pub fn alloc_steal_promoted(self, promoted: IndexVec<Promoted, Body<'tcx>>) ->
1099 &'tcx Steal<IndexVec<Promoted, Body<'tcx>>> {
1100 self.arena.alloc(Steal::new(promoted))
1103 pub fn intern_promoted(self, promoted: IndexVec<Promoted, Body<'tcx>>) ->
1104 &'tcx IndexVec<Promoted, Body<'tcx>> {
1105 self.arena.alloc(promoted)
1108 pub fn alloc_adt_def(
1112 variants: IndexVec<VariantIdx, ty::VariantDef>,
1114 ) -> &'tcx ty::AdtDef {
1115 let def = ty::AdtDef::new(self, did, kind, variants, repr);
1116 self.arena.alloc(def)
1119 pub fn intern_const_alloc(self, alloc: Allocation) -> &'tcx Allocation {
1120 self.allocation_interner.intern(alloc, |alloc| {
1121 self.arena.alloc(alloc)
1125 /// Allocates a read-only byte or string literal for `mir::interpret`.
1126 pub fn allocate_bytes(self, bytes: &[u8]) -> interpret::AllocId {
1127 // Create an allocation that just contains these bytes.
1128 let alloc = interpret::Allocation::from_byte_aligned_bytes(bytes);
1129 let alloc = self.intern_const_alloc(alloc);
1130 self.alloc_map.lock().create_memory_alloc(alloc)
1133 pub fn intern_stability(self, stab: attr::Stability) -> &'tcx attr::Stability {
1134 self.stability_interner.intern(stab, |stab| {
1135 self.arena.alloc(stab)
1139 pub fn intern_layout(self, layout: LayoutDetails) -> &'tcx LayoutDetails {
1140 self.layout_interner.intern(layout, |layout| {
1141 self.arena.alloc(layout)
1145 /// Returns a range of the start/end indices specified with the
1146 /// `rustc_layout_scalar_valid_range` attribute.
1147 pub fn layout_scalar_valid_range(self, def_id: DefId) -> (Bound<u128>, Bound<u128>) {
1148 let attrs = self.get_attrs(def_id);
1150 let attr = match attrs.iter().find(|a| a.check_name(name)) {
1152 None => return Bound::Unbounded,
1154 for meta in attr.meta_item_list().expect("rustc_layout_scalar_valid_range takes args") {
1155 match meta.literal().expect("attribute takes lit").node {
1156 ast::LitKind::Int(a, _) => return Bound::Included(a),
1157 _ => span_bug!(attr.span, "rustc_layout_scalar_valid_range expects int arg"),
1160 span_bug!(attr.span, "no arguments to `rustc_layout_scalar_valid_range` attribute");
1162 (get(sym::rustc_layout_scalar_valid_range_start),
1163 get(sym::rustc_layout_scalar_valid_range_end))
1166 pub fn lift<T: ?Sized + Lift<'tcx>>(self, value: &T) -> Option<T::Lifted> {
1167 value.lift_to_tcx(self)
1170 /// Like lift, but only tries in the global tcx.
1171 pub fn lift_to_global<T: ?Sized + Lift<'tcx>>(self, value: &T) -> Option<T::Lifted> {
1172 value.lift_to_tcx(self.global_tcx())
1175 /// Creates a type context and call the closure with a `TyCtxt` reference
1176 /// to the context. The closure enforces that the type context and any interned
1177 /// value (types, substs, etc.) can only be used while `ty::tls` has a valid
1178 /// reference to the context, to allow formatting values that need it.
1179 pub fn create_global_ctxt(
1181 cstore: &'tcx CrateStoreDyn,
1182 local_providers: ty::query::Providers<'tcx>,
1183 extern_providers: ty::query::Providers<'tcx>,
1184 arenas: &'tcx AllArenas,
1185 resolutions: ty::Resolutions,
1186 hir: hir_map::Map<'tcx>,
1187 on_disk_query_result_cache: query::OnDiskCache<'tcx>,
1189 tx: mpsc::Sender<Box<dyn Any + Send>>,
1190 output_filenames: &OutputFilenames,
1191 ) -> GlobalCtxt<'tcx> {
1192 let data_layout = TargetDataLayout::parse(&s.target.target).unwrap_or_else(|err| {
1195 let interners = CtxtInterners::new(&arenas.interner);
1196 let common = Common {
1197 empty_predicates: ty::GenericPredicates {
1202 let common_types = CommonTypes::new(&interners);
1203 let common_lifetimes = CommonLifetimes::new(&interners);
1204 let common_consts = CommonConsts::new(&interners, &common_types);
1205 let dep_graph = hir.dep_graph.clone();
1206 let max_cnum = cstore.crates_untracked().iter().map(|c| c.as_usize()).max().unwrap_or(0);
1207 let mut providers = IndexVec::from_elem_n(extern_providers, max_cnum + 1);
1208 providers[LOCAL_CRATE] = local_providers;
1210 let def_path_hash_to_def_id = if s.opts.build_dep_graph() {
1211 let upstream_def_path_tables: Vec<(CrateNum, Lrc<_>)> = cstore
1214 .map(|&cnum| (cnum, cstore.def_path_table(cnum)))
1217 let def_path_tables = || {
1218 upstream_def_path_tables
1220 .map(|&(cnum, ref rc)| (cnum, &**rc))
1221 .chain(iter::once((LOCAL_CRATE, hir.definitions().def_path_table())))
1224 // Precompute the capacity of the hashmap so we don't have to
1225 // re-allocate when populating it.
1226 let capacity = def_path_tables().map(|(_, t)| t.size()).sum::<usize>();
1228 let mut map: FxHashMap<_, _> = FxHashMap::with_capacity_and_hasher(
1230 ::std::default::Default::default()
1233 for (cnum, def_path_table) in def_path_tables() {
1234 def_path_table.add_def_path_hashes_to(cnum, &mut map);
1242 let mut trait_map: FxHashMap<_, FxHashMap<_, _>> = FxHashMap::default();
1243 for (k, v) in resolutions.trait_map {
1244 let hir_id = hir.node_to_hir_id(k);
1245 let map = trait_map.entry(hir_id.owner).or_default();
1246 map.insert(hir_id.local_id, StableVec::new(v));
1252 arena: WorkerLocal::new(|_| Arena::default()),
1256 types: common_types,
1257 lifetimes: common_lifetimes,
1258 consts: common_consts,
1260 export_map: resolutions.export_map.into_iter().map(|(k, v)| {
1261 let exports: Vec<_> = v.into_iter().map(|e| {
1262 e.map_id(|id| hir.node_to_hir_id(id))
1266 maybe_unused_trait_imports:
1267 resolutions.maybe_unused_trait_imports
1269 .map(|id| hir.local_def_id_from_node_id(id))
1271 maybe_unused_extern_crates:
1272 resolutions.maybe_unused_extern_crates
1274 .map(|(id, sp)| (hir.local_def_id_from_node_id(id), sp))
1276 glob_map: resolutions.glob_map.into_iter().map(|(id, names)| {
1277 (hir.local_def_id_from_node_id(id), names)
1279 extern_prelude: resolutions.extern_prelude,
1281 def_path_hash_to_def_id,
1282 queries: query::Queries::new(
1285 on_disk_query_result_cache,
1287 rcache: Default::default(),
1288 selection_cache: Default::default(),
1289 evaluation_cache: Default::default(),
1290 crate_name: Symbol::intern(crate_name),
1292 layout_interner: Default::default(),
1293 stability_interner: Default::default(),
1294 allocation_interner: Default::default(),
1295 alloc_map: Lock::new(interpret::AllocMap::new()),
1296 tx_to_llvm_workers: Lock::new(tx),
1297 output_filenames: Arc::new(output_filenames.clone()),
1301 pub fn consider_optimizing<T: Fn() -> String>(&self, msg: T) -> bool {
1302 let cname = self.crate_name(LOCAL_CRATE).as_str();
1303 self.sess.consider_optimizing(&cname, msg)
1306 pub fn lib_features(self) -> &'tcx middle::lib_features::LibFeatures {
1307 self.get_lib_features(LOCAL_CRATE)
1310 /// Obtain all lang items of this crate and all dependencies (recursively)
1311 pub fn lang_items(self) -> &'tcx middle::lang_items::LanguageItems {
1312 self.get_lang_items(LOCAL_CRATE)
1315 /// Obtain the given diagnostic item's `DefId`. Use `is_diagnostic_item` if you just want to
1316 /// compare against another `DefId`, since `is_diagnostic_item` is cheaper.
1317 pub fn get_diagnostic_item(self, name: Symbol) -> Option<DefId> {
1318 self.all_diagnostic_items(LOCAL_CRATE).get(&name).copied()
1321 /// Check whether the diagnostic item with the given `name` has the given `DefId`.
1322 pub fn is_diagnostic_item(self, name: Symbol, did: DefId) -> bool {
1323 self.diagnostic_items(did.krate).get(&name) == Some(&did)
1326 pub fn stability(self) -> &'tcx stability::Index<'tcx> {
1327 self.stability_index(LOCAL_CRATE)
1330 pub fn crates(self) -> &'tcx [CrateNum] {
1331 self.all_crate_nums(LOCAL_CRATE)
1334 pub fn features(self) -> &'tcx feature_gate::Features {
1335 self.features_query(LOCAL_CRATE)
1338 pub fn def_key(self, id: DefId) -> hir_map::DefKey {
1340 self.hir().def_key(id)
1342 self.cstore.def_key(id)
1346 /// Converts a `DefId` into its fully expanded `DefPath` (every
1347 /// `DefId` is really just an interned `DefPath`).
1349 /// Note that if `id` is not local to this crate, the result will
1350 /// be a non-local `DefPath`.
1351 pub fn def_path(self, id: DefId) -> hir_map::DefPath {
1353 self.hir().def_path(id)
1355 self.cstore.def_path(id)
1359 /// Returns whether or not the crate with CrateNum 'cnum'
1360 /// is marked as a private dependency
1361 pub fn is_private_dep(self, cnum: CrateNum) -> bool {
1362 if cnum == LOCAL_CRATE {
1365 self.cstore.crate_is_private_dep_untracked(cnum)
1370 pub fn def_path_hash(self, def_id: DefId) -> hir_map::DefPathHash {
1371 if def_id.is_local() {
1372 self.hir().definitions().def_path_hash(def_id.index)
1374 self.cstore.def_path_hash(def_id)
1378 pub fn def_path_debug_str(self, def_id: DefId) -> String {
1379 // We are explicitly not going through queries here in order to get
1380 // crate name and disambiguator since this code is called from debug!()
1381 // statements within the query system and we'd run into endless
1382 // recursion otherwise.
1383 let (crate_name, crate_disambiguator) = if def_id.is_local() {
1384 (self.crate_name.clone(),
1385 self.sess.local_crate_disambiguator())
1387 (self.cstore.crate_name_untracked(def_id.krate),
1388 self.cstore.crate_disambiguator_untracked(def_id.krate))
1393 // Don't print the whole crate disambiguator. That's just
1394 // annoying in debug output.
1395 &(crate_disambiguator.to_fingerprint().to_hex())[..4],
1396 self.def_path(def_id).to_string_no_crate())
1399 pub fn metadata_encoding_version(self) -> Vec<u8> {
1400 self.cstore.metadata_encoding_version().to_vec()
1403 pub fn encode_metadata(self)-> EncodedMetadata {
1404 self.cstore.encode_metadata(self)
1407 // Note that this is *untracked* and should only be used within the query
1408 // system if the result is otherwise tracked through queries
1409 pub fn crate_data_as_rc_any(self, cnum: CrateNum) -> Lrc<dyn Any> {
1410 self.cstore.crate_data_as_rc_any(cnum)
1414 pub fn create_stable_hashing_context(self) -> StableHashingContext<'tcx> {
1415 let krate = self.gcx.hir_map.forest.untracked_krate();
1417 StableHashingContext::new(self.sess,
1419 self.hir().definitions(),
1423 // This method makes sure that we have a DepNode and a Fingerprint for
1424 // every upstream crate. It needs to be called once right after the tcx is
1426 // With full-fledged red/green, the method will probably become unnecessary
1427 // as this will be done on-demand.
1428 pub fn allocate_metadata_dep_nodes(self) {
1429 // We cannot use the query versions of crates() and crate_hash(), since
1430 // those would need the DepNodes that we are allocating here.
1431 for cnum in self.cstore.crates_untracked() {
1432 let dep_node = DepNode::new(self, DepConstructor::CrateMetadata(cnum));
1433 let crate_hash = self.cstore.crate_hash_untracked(cnum);
1434 self.dep_graph.with_task(dep_node,
1437 |_, x| x, // No transformation needed
1438 dep_graph::hash_result,
1443 pub fn serialize_query_result_cache<E>(self,
1445 -> Result<(), E::Error>
1446 where E: ty::codec::TyEncoder
1448 self.queries.on_disk_cache.serialize(self.global_tcx(), encoder)
1451 /// If `true`, we should use the AST-based borrowck (we may *also* use
1452 /// the MIR-based borrowck).
1453 pub fn use_ast_borrowck(self) -> bool {
1454 self.borrowck_mode().use_ast()
1457 /// If `true`, we should use the MIR-based borrowck, but also
1458 /// fall back on the AST borrowck if the MIR-based one errors.
1459 pub fn migrate_borrowck(self) -> bool {
1460 self.borrowck_mode().migrate()
1463 /// If `true`, make MIR codegen for `match` emit a temp that holds a
1464 /// borrow of the input to the match expression.
1465 pub fn generate_borrow_of_any_match_input(&self) -> bool {
1466 self.emit_read_for_match()
1469 /// If `true`, make MIR codegen for `match` emit FakeRead
1470 /// statements (which simulate the maximal effect of executing the
1471 /// patterns in a match arm).
1472 pub fn emit_read_for_match(&self) -> bool {
1473 !self.sess.opts.debugging_opts.nll_dont_emit_read_for_match
1476 /// What mode(s) of borrowck should we run? AST? MIR? both?
1477 /// (Also considers the `#![feature(nll)]` setting.)
1478 pub fn borrowck_mode(&self) -> BorrowckMode {
1479 // Here are the main constraints we need to deal with:
1481 // 1. An opts.borrowck_mode of `BorrowckMode::Migrate` is
1482 // synonymous with no `-Z borrowck=...` flag at all.
1484 // 2. We want to allow developers on the Nightly channel
1485 // to opt back into the "hard error" mode for NLL,
1486 // (which they can do via specifying `#![feature(nll)]`
1487 // explicitly in their crate).
1489 // So, this precedence list is how pnkfelix chose to work with
1490 // the above constraints:
1492 // * `#![feature(nll)]` *always* means use NLL with hard
1493 // errors. (To simplify the code here, it now even overrides
1494 // a user's attempt to specify `-Z borrowck=compare`, which
1495 // we arguably do not need anymore and should remove.)
1497 // * Otherwise, if no `-Z borrowck=...` then use migrate mode
1499 // * Otherwise, use the behavior requested via `-Z borrowck=...`
1501 if self.features().nll { return BorrowckMode::Mir; }
1503 self.sess.opts.borrowck_mode
1507 pub fn local_crate_exports_generics(self) -> bool {
1508 debug_assert!(self.sess.opts.share_generics());
1510 self.sess.crate_types.borrow().iter().any(|crate_type| {
1512 CrateType::Executable |
1513 CrateType::Staticlib |
1514 CrateType::ProcMacro |
1515 CrateType::Cdylib => false,
1517 CrateType::Dylib => true,
1522 // Returns the `DefId` and the `BoundRegion` corresponding to the given region.
1523 pub fn is_suitable_region(&self, region: Region<'tcx>) -> Option<FreeRegionInfo> {
1524 let (suitable_region_binding_scope, bound_region) = match *region {
1525 ty::ReFree(ref free_region) => (free_region.scope, free_region.bound_region),
1526 ty::ReEarlyBound(ref ebr) => (
1527 self.parent(ebr.def_id).unwrap(),
1528 ty::BoundRegion::BrNamed(ebr.def_id, ebr.name),
1530 _ => return None, // not a free region
1533 let hir_id = self.hir()
1534 .as_local_hir_id(suitable_region_binding_scope)
1536 let is_impl_item = match self.hir().find(hir_id) {
1537 Some(Node::Item(..)) | Some(Node::TraitItem(..)) => false,
1538 Some(Node::ImplItem(..)) => {
1539 self.is_bound_region_in_impl_item(suitable_region_binding_scope)
1544 return Some(FreeRegionInfo {
1545 def_id: suitable_region_binding_scope,
1546 boundregion: bound_region,
1547 is_impl_item: is_impl_item,
1551 pub fn return_type_impl_trait(
1553 scope_def_id: DefId,
1554 ) -> Option<Ty<'tcx>> {
1555 // HACK: `type_of_def_id()` will fail on these (#55796), so return `None`.
1556 let hir_id = self.hir().as_local_hir_id(scope_def_id).unwrap();
1557 match self.hir().get(hir_id) {
1558 Node::Item(item) => {
1560 ItemKind::Fn(..) => { /* `type_of_def_id()` will work */ }
1566 _ => { /* `type_of_def_id()` will work or panic */ }
1569 let ret_ty = self.type_of(scope_def_id);
1571 ty::FnDef(_, _) => {
1572 let sig = ret_ty.fn_sig(*self);
1573 let output = self.erase_late_bound_regions(&sig.output());
1574 if output.is_impl_trait() {
1584 // Checks if the bound region is in Impl Item.
1585 pub fn is_bound_region_in_impl_item(
1587 suitable_region_binding_scope: DefId,
1589 let container_id = self.associated_item(suitable_region_binding_scope)
1592 if self.impl_trait_ref(container_id).is_some() {
1593 // For now, we do not try to target impls of traits. This is
1594 // because this message is going to suggest that the user
1595 // change the fn signature, but they may not be free to do so,
1596 // since the signature must match the trait.
1598 // FIXME(#42706) -- in some cases, we could do better here.
1604 /// Determines whether identifiers in the assembly have strict naming rules.
1605 /// Currently, only NVPTX* targets need it.
1606 pub fn has_strict_asm_symbol_naming(&self) -> bool {
1607 self.sess.target.target.arch.contains("nvptx")
1611 impl<'tcx> GlobalCtxt<'tcx> {
1612 /// Calls the closure with a local `TyCtxt` using the given arena.
1613 /// `interners` is a slot passed so we can create a CtxtInterners
1614 /// with the same lifetime as `arena`.
1615 pub fn enter_local<F, R>(&'tcx self, f: F) -> R
1617 F: FnOnce(TyCtxt<'tcx>) -> R,
1622 ty::tls::with_related_context(tcx.global_tcx(), |icx| {
1623 let new_icx = ty::tls::ImplicitCtxt {
1625 query: icx.query.clone(),
1626 diagnostics: icx.diagnostics,
1627 layout_depth: icx.layout_depth,
1628 task_deps: icx.task_deps,
1630 ty::tls::enter_context(&new_icx, |_| {
1637 /// A trait implemented for all `X<'a>` types that can be safely and
1638 /// efficiently converted to `X<'tcx>` as long as they are part of the
1639 /// provided `TyCtxt<'tcx>`.
1640 /// This can be done, for example, for `Ty<'tcx>` or `SubstsRef<'tcx>`
1641 /// by looking them up in their respective interners.
1643 /// However, this is still not the best implementation as it does
1644 /// need to compare the components, even for interned values.
1645 /// It would be more efficient if `TypedArena` provided a way to
1646 /// determine whether the address is in the allocated range.
1648 /// `None` is returned if the value or one of the components is not part
1649 /// of the provided context.
1650 /// For `Ty`, `None` can be returned if either the type interner doesn't
1651 /// contain the `TyKind` key or if the address of the interned
1652 /// pointer differs. The latter case is possible if a primitive type,
1653 /// e.g., `()` or `u8`, was interned in a different context.
1654 pub trait Lift<'tcx>: fmt::Debug {
1655 type Lifted: fmt::Debug + 'tcx;
1656 fn lift_to_tcx(&self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted>;
1659 macro_rules! nop_lift {
1660 ($ty:ty => $lifted:ty) => {
1661 impl<'a, 'tcx> Lift<'tcx> for $ty {
1662 type Lifted = $lifted;
1663 fn lift_to_tcx(&self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
1664 if tcx.interners.arena.in_arena(*self as *const _) {
1665 Some(unsafe { mem::transmute(*self) })
1674 macro_rules! nop_list_lift {
1675 ($ty:ty => $lifted:ty) => {
1676 impl<'a, 'tcx> Lift<'tcx> for &'a List<$ty> {
1677 type Lifted = &'tcx List<$lifted>;
1678 fn lift_to_tcx(&self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
1679 if self.is_empty() {
1680 return Some(List::empty());
1682 if tcx.interners.arena.in_arena(*self as *const _) {
1683 Some(unsafe { mem::transmute(*self) })
1692 nop_lift!{Ty<'a> => Ty<'tcx>}
1693 nop_lift!{Region<'a> => Region<'tcx>}
1694 nop_lift!{Goal<'a> => Goal<'tcx>}
1695 nop_lift!{&'a Const<'a> => &'tcx Const<'tcx>}
1697 nop_list_lift!{Goal<'a> => Goal<'tcx>}
1698 nop_list_lift!{Clause<'a> => Clause<'tcx>}
1699 nop_list_lift!{Ty<'a> => Ty<'tcx>}
1700 nop_list_lift!{ExistentialPredicate<'a> => ExistentialPredicate<'tcx>}
1701 nop_list_lift!{Predicate<'a> => Predicate<'tcx>}
1702 nop_list_lift!{CanonicalVarInfo => CanonicalVarInfo}
1703 nop_list_lift!{ProjectionKind => ProjectionKind}
1705 // This is the impl for `&'a InternalSubsts<'a>`.
1706 nop_list_lift!{Kind<'a> => Kind<'tcx>}
1709 use super::{GlobalCtxt, TyCtxt, ptr_eq};
1714 use crate::ty::query;
1715 use errors::{Diagnostic, TRACK_DIAGNOSTICS};
1716 use rustc_data_structures::OnDrop;
1717 use rustc_data_structures::sync::{self, Lrc, Lock};
1718 use rustc_data_structures::thin_vec::ThinVec;
1719 use crate::dep_graph::TaskDeps;
1721 #[cfg(not(parallel_compiler))]
1722 use std::cell::Cell;
1724 #[cfg(parallel_compiler)]
1725 use rustc_rayon_core as rayon_core;
1727 /// This is the implicit state of rustc. It contains the current
1728 /// `TyCtxt` and query. It is updated when creating a local interner or
1729 /// executing a new query. Whenever there's a `TyCtxt` value available
1730 /// you should also have access to an `ImplicitCtxt` through the functions
1733 pub struct ImplicitCtxt<'a, 'tcx> {
1734 /// The current `TyCtxt`. Initially created by `enter_global` and updated
1735 /// by `enter_local` with a new local interner.
1736 pub tcx: TyCtxt<'tcx>,
1738 /// The current query job, if any. This is updated by `JobOwner::start` in
1739 /// `ty::query::plumbing` when executing a query.
1740 pub query: Option<Lrc<query::QueryJob<'tcx>>>,
1742 /// Where to store diagnostics for the current query job, if any.
1743 /// This is updated by `JobOwner::start` in `ty::query::plumbing` when executing a query.
1744 pub diagnostics: Option<&'a Lock<ThinVec<Diagnostic>>>,
1746 /// Used to prevent layout from recursing too deeply.
1747 pub layout_depth: usize,
1749 /// The current dep graph task. This is used to add dependencies to queries
1750 /// when executing them.
1751 pub task_deps: Option<&'a Lock<TaskDeps>>,
1754 /// Sets Rayon's thread-local variable, which is preserved for Rayon jobs
1755 /// to `value` during the call to `f`. It is restored to its previous value after.
1756 /// This is used to set the pointer to the new `ImplicitCtxt`.
1757 #[cfg(parallel_compiler)]
1759 fn set_tlv<F: FnOnce() -> R, R>(value: usize, f: F) -> R {
1760 rayon_core::tlv::with(value, f)
1763 /// Gets Rayon's thread-local variable, which is preserved for Rayon jobs.
1764 /// This is used to get the pointer to the current `ImplicitCtxt`.
1765 #[cfg(parallel_compiler)]
1767 fn get_tlv() -> usize {
1768 rayon_core::tlv::get()
1771 #[cfg(not(parallel_compiler))]
1773 /// A thread local variable that stores a pointer to the current `ImplicitCtxt`.
1774 static TLV: Cell<usize> = Cell::new(0);
1777 /// Sets TLV to `value` during the call to `f`.
1778 /// It is restored to its previous value after.
1779 /// This is used to set the pointer to the new `ImplicitCtxt`.
1780 #[cfg(not(parallel_compiler))]
1782 fn set_tlv<F: FnOnce() -> R, R>(value: usize, f: F) -> R {
1783 let old = get_tlv();
1784 let _reset = OnDrop(move || TLV.with(|tlv| tlv.set(old)));
1785 TLV.with(|tlv| tlv.set(value));
1789 /// Gets the pointer to the current `ImplicitCtxt`.
1790 #[cfg(not(parallel_compiler))]
1791 fn get_tlv() -> usize {
1792 TLV.with(|tlv| tlv.get())
1795 /// This is a callback from libsyntax as it cannot access the implicit state
1796 /// in librustc otherwise.
1797 fn span_debug(span: syntax_pos::Span, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1799 if let Some(tcx) = tcx {
1800 write!(f, "{}", tcx.sess.source_map().span_to_string(span))
1802 syntax_pos::default_span_debug(span, f)
1807 /// This is a callback from libsyntax as it cannot access the implicit state
1808 /// in librustc otherwise. It is used to when diagnostic messages are
1809 /// emitted and stores them in the current query, if there is one.
1810 fn track_diagnostic(diagnostic: &Diagnostic) {
1811 with_context_opt(|icx| {
1812 if let Some(icx) = icx {
1813 if let Some(ref diagnostics) = icx.diagnostics {
1814 let mut diagnostics = diagnostics.lock();
1815 diagnostics.extend(Some(diagnostic.clone()));
1821 /// Sets up the callbacks from libsyntax on the current thread.
1822 pub fn with_thread_locals<F, R>(f: F) -> R
1823 where F: FnOnce() -> R
1825 syntax_pos::SPAN_DEBUG.with(|span_dbg| {
1826 let original_span_debug = span_dbg.get();
1827 span_dbg.set(span_debug);
1829 let _on_drop = OnDrop(move || {
1830 span_dbg.set(original_span_debug);
1833 TRACK_DIAGNOSTICS.with(|current| {
1834 let original = current.get();
1835 current.set(track_diagnostic);
1837 let _on_drop = OnDrop(move || {
1838 current.set(original);
1846 /// Sets `context` as the new current `ImplicitCtxt` for the duration of the function `f`.
1848 pub fn enter_context<'a, 'tcx, F, R>(context: &ImplicitCtxt<'a, 'tcx>, f: F) -> R
1850 F: FnOnce(&ImplicitCtxt<'a, 'tcx>) -> R,
1852 set_tlv(context as *const _ as usize, || {
1857 /// Enters `GlobalCtxt` by setting up libsyntax callbacks and
1858 /// creating a initial `TyCtxt` and `ImplicitCtxt`.
1859 /// This happens once per rustc session and `TyCtxt`s only exists
1860 /// inside the `f` function.
1861 pub fn enter_global<'tcx, F, R>(gcx: &'tcx GlobalCtxt<'tcx>, f: F) -> R
1863 F: FnOnce(TyCtxt<'tcx>) -> R,
1865 // Update `GCX_PTR` to indicate there's a `GlobalCtxt` available.
1866 GCX_PTR.with(|lock| {
1867 *lock.lock() = gcx as *const _ as usize;
1869 // Set `GCX_PTR` back to 0 when we exit.
1870 let _on_drop = OnDrop(move || {
1871 GCX_PTR.with(|lock| *lock.lock() = 0);
1877 let icx = ImplicitCtxt {
1884 enter_context(&icx, |_| {
1889 scoped_thread_local! {
1890 /// Stores a pointer to the `GlobalCtxt` if one is available.
1891 /// This is used to access the `GlobalCtxt` in the deadlock handler given to Rayon.
1892 pub static GCX_PTR: Lock<usize>
1895 /// Creates a `TyCtxt` and `ImplicitCtxt` based on the `GCX_PTR` thread local.
1896 /// This is used in the deadlock handler.
1897 pub unsafe fn with_global<F, R>(f: F) -> R
1899 F: for<'tcx> FnOnce(TyCtxt<'tcx>) -> R,
1901 let gcx = GCX_PTR.with(|lock| *lock.lock());
1903 let gcx = &*(gcx as *const GlobalCtxt<'_>);
1907 let icx = ImplicitCtxt {
1914 enter_context(&icx, |_| f(tcx))
1917 /// Allows access to the current `ImplicitCtxt` in a closure if one is available.
1919 pub fn with_context_opt<F, R>(f: F) -> R
1921 F: for<'a, 'tcx> FnOnce(Option<&ImplicitCtxt<'a, 'tcx>>) -> R,
1923 let context = get_tlv();
1927 // We could get a `ImplicitCtxt` pointer from another thread.
1928 // Ensure that `ImplicitCtxt` is `Sync`.
1929 sync::assert_sync::<ImplicitCtxt<'_, '_>>();
1931 unsafe { f(Some(&*(context as *const ImplicitCtxt<'_, '_>))) }
1935 /// Allows access to the current `ImplicitCtxt`.
1936 /// Panics if there is no `ImplicitCtxt` available.
1938 pub fn with_context<F, R>(f: F) -> R
1940 F: for<'a, 'tcx> FnOnce(&ImplicitCtxt<'a, 'tcx>) -> R,
1942 with_context_opt(|opt_context| f(opt_context.expect("no ImplicitCtxt stored in tls")))
1945 /// Allows access to the current `ImplicitCtxt` whose tcx field has the same global
1946 /// interner as the tcx argument passed in. This means the closure is given an `ImplicitCtxt`
1947 /// with the same `'tcx` lifetime as the `TyCtxt` passed in.
1948 /// This will panic if you pass it a `TyCtxt` which has a different global interner from
1949 /// the current `ImplicitCtxt`'s `tcx` field.
1951 pub fn with_related_context<'tcx, F, R>(tcx: TyCtxt<'tcx>, f: F) -> R
1953 F: FnOnce(&ImplicitCtxt<'_, 'tcx>) -> R,
1955 with_context(|context| {
1957 assert!(ptr_eq(context.tcx.gcx, tcx.gcx));
1958 let context: &ImplicitCtxt<'_, '_> = mem::transmute(context);
1964 /// Allows access to the `TyCtxt` in the current `ImplicitCtxt`.
1965 /// Panics if there is no `ImplicitCtxt` available.
1967 pub fn with<F, R>(f: F) -> R
1969 F: for<'tcx> FnOnce(TyCtxt<'tcx>) -> R,
1971 with_context(|context| f(context.tcx))
1974 /// Allows access to the `TyCtxt` in the current `ImplicitCtxt`.
1975 /// The closure is passed None if there is no `ImplicitCtxt` available.
1977 pub fn with_opt<F, R>(f: F) -> R
1979 F: for<'tcx> FnOnce(Option<TyCtxt<'tcx>>) -> R,
1981 with_context_opt(|opt_context| f(opt_context.map(|context| context.tcx)))
1985 macro_rules! sty_debug_print {
1986 ($ctxt: expr, $($variant: ident),*) => {{
1987 // Curious inner module to allow variant names to be used as
1989 #[allow(non_snake_case)]
1991 use crate::ty::{self, TyCtxt};
1992 use crate::ty::context::Interned;
1994 #[derive(Copy, Clone)]
2003 pub fn go(tcx: TyCtxt<'_>) {
2004 let mut total = DebugStat {
2011 $(let mut $variant = total;)*
2013 let shards = tcx.interners.type_.lock_shards();
2014 let types = shards.iter().flat_map(|shard| shard.keys());
2015 for &Interned(t) in types {
2016 let variant = match t.sty {
2017 ty::Bool | ty::Char | ty::Int(..) | ty::Uint(..) |
2018 ty::Float(..) | ty::Str | ty::Never => continue,
2019 ty::Error => /* unimportant */ continue,
2020 $(ty::$variant(..) => &mut $variant,)*
2022 let lt = t.flags.intersects(ty::TypeFlags::HAS_RE_INFER);
2023 let ty = t.flags.intersects(ty::TypeFlags::HAS_TY_INFER);
2024 let ct = t.flags.intersects(ty::TypeFlags::HAS_CT_INFER);
2028 if lt { total.lt_infer += 1; variant.lt_infer += 1 }
2029 if ty { total.ty_infer += 1; variant.ty_infer += 1 }
2030 if ct { total.ct_infer += 1; variant.ct_infer += 1 }
2031 if lt && ty && ct { total.all_infer += 1; variant.all_infer += 1 }
2033 println!("Ty interner total ty lt ct all");
2034 $(println!(" {:18}: {uses:6} {usespc:4.1}%, \
2035 {ty:4.1}% {lt:5.1}% {ct:4.1}% {all:4.1}%",
2036 stringify!($variant),
2037 uses = $variant.total,
2038 usespc = $variant.total as f64 * 100.0 / total.total as f64,
2039 ty = $variant.ty_infer as f64 * 100.0 / total.total as f64,
2040 lt = $variant.lt_infer as f64 * 100.0 / total.total as f64,
2041 ct = $variant.ct_infer as f64 * 100.0 / total.total as f64,
2042 all = $variant.all_infer as f64 * 100.0 / total.total as f64);
2044 println!(" total {uses:6} \
2045 {ty:4.1}% {lt:5.1}% {ct:4.1}% {all:4.1}%",
2047 ty = total.ty_infer as f64 * 100.0 / total.total as f64,
2048 lt = total.lt_infer as f64 * 100.0 / total.total as f64,
2049 ct = total.ct_infer as f64 * 100.0 / total.total as f64,
2050 all = total.all_infer as f64 * 100.0 / total.total as f64)
2058 impl<'tcx> TyCtxt<'tcx> {
2059 pub fn print_debug_stats(self) {
2062 Adt, Array, Slice, RawPtr, Ref, FnDef, FnPtr, Placeholder,
2063 Generator, GeneratorWitness, Dynamic, Closure, Tuple, Bound,
2064 Param, Infer, UnnormalizedProjection, Projection, Opaque, Foreign);
2066 println!("InternalSubsts interner: #{}", self.interners.substs.len());
2067 println!("Region interner: #{}", self.interners.region.len());
2068 println!("Stability interner: #{}", self.stability_interner.len());
2069 println!("Allocation interner: #{}", self.allocation_interner.len());
2070 println!("Layout interner: #{}", self.layout_interner.len());
2075 /// An entry in an interner.
2076 struct Interned<'tcx, T: ?Sized>(&'tcx T);
2078 impl<'tcx, T: 'tcx+?Sized> Clone for Interned<'tcx, T> {
2079 fn clone(&self) -> Self {
2083 impl<'tcx, T: 'tcx+?Sized> Copy for Interned<'tcx, T> {}
2085 // N.B., an `Interned<Ty>` compares and hashes as a sty.
2086 impl<'tcx> PartialEq for Interned<'tcx, TyS<'tcx>> {
2087 fn eq(&self, other: &Interned<'tcx, TyS<'tcx>>) -> bool {
2088 self.0.sty == other.0.sty
2092 impl<'tcx> Eq for Interned<'tcx, TyS<'tcx>> {}
2094 impl<'tcx> Hash for Interned<'tcx, TyS<'tcx>> {
2095 fn hash<H: Hasher>(&self, s: &mut H) {
2100 #[allow(rustc::usage_of_ty_tykind)]
2101 impl<'tcx> Borrow<TyKind<'tcx>> for Interned<'tcx, TyS<'tcx>> {
2102 fn borrow<'a>(&'a self) -> &'a TyKind<'tcx> {
2107 // N.B., an `Interned<List<T>>` compares and hashes as its elements.
2108 impl<'tcx, T: PartialEq> PartialEq for Interned<'tcx, List<T>> {
2109 fn eq(&self, other: &Interned<'tcx, List<T>>) -> bool {
2110 self.0[..] == other.0[..]
2114 impl<'tcx, T: Eq> Eq for Interned<'tcx, List<T>> {}
2116 impl<'tcx, T: Hash> Hash for Interned<'tcx, List<T>> {
2117 fn hash<H: Hasher>(&self, s: &mut H) {
2122 impl<'tcx> Borrow<[Ty<'tcx>]> for Interned<'tcx, List<Ty<'tcx>>> {
2123 fn borrow<'a>(&'a self) -> &'a [Ty<'tcx>] {
2128 impl<'tcx> Borrow<[CanonicalVarInfo]> for Interned<'tcx, List<CanonicalVarInfo>> {
2129 fn borrow(&self) -> &[CanonicalVarInfo] {
2134 impl<'tcx> Borrow<[Kind<'tcx>]> for Interned<'tcx, InternalSubsts<'tcx>> {
2135 fn borrow<'a>(&'a self) -> &'a [Kind<'tcx>] {
2140 impl<'tcx> Borrow<[ProjectionKind]>
2141 for Interned<'tcx, List<ProjectionKind>> {
2142 fn borrow(&self) -> &[ProjectionKind] {
2147 impl<'tcx> Borrow<RegionKind> for Interned<'tcx, RegionKind> {
2148 fn borrow(&self) -> &RegionKind {
2153 impl<'tcx> Borrow<GoalKind<'tcx>> for Interned<'tcx, GoalKind<'tcx>> {
2154 fn borrow<'a>(&'a self) -> &'a GoalKind<'tcx> {
2159 impl<'tcx> Borrow<[ExistentialPredicate<'tcx>]>
2160 for Interned<'tcx, List<ExistentialPredicate<'tcx>>>
2162 fn borrow<'a>(&'a self) -> &'a [ExistentialPredicate<'tcx>] {
2167 impl<'tcx> Borrow<[Predicate<'tcx>]> for Interned<'tcx, List<Predicate<'tcx>>> {
2168 fn borrow<'a>(&'a self) -> &'a [Predicate<'tcx>] {
2173 impl<'tcx> Borrow<Const<'tcx>> for Interned<'tcx, Const<'tcx>> {
2174 fn borrow<'a>(&'a self) -> &'a Const<'tcx> {
2179 impl<'tcx> Borrow<[Clause<'tcx>]> for Interned<'tcx, List<Clause<'tcx>>> {
2180 fn borrow<'a>(&'a self) -> &'a [Clause<'tcx>] {
2185 impl<'tcx> Borrow<[Goal<'tcx>]> for Interned<'tcx, List<Goal<'tcx>>> {
2186 fn borrow<'a>(&'a self) -> &'a [Goal<'tcx>] {
2191 macro_rules! intern_method {
2192 ($lt_tcx:tt, $name:ident: $method:ident($alloc:ty,
2194 $alloc_to_key:expr) -> $ty:ty) => {
2195 impl<$lt_tcx> TyCtxt<$lt_tcx> {
2196 pub fn $method(self, v: $alloc) -> &$lt_tcx $ty {
2197 let key = ($alloc_to_key)(&v);
2199 self.interners.$name.intern_ref(key, || {
2200 Interned($alloc_method(&self.interners.arena, v))
2208 macro_rules! direct_interners {
2209 ($lt_tcx:tt, $($name:ident: $method:ident($ty:ty)),+) => {
2210 $(impl<$lt_tcx> PartialEq for Interned<$lt_tcx, $ty> {
2211 fn eq(&self, other: &Self) -> bool {
2216 impl<$lt_tcx> Eq for Interned<$lt_tcx, $ty> {}
2218 impl<$lt_tcx> Hash for Interned<$lt_tcx, $ty> {
2219 fn hash<H: Hasher>(&self, s: &mut H) {
2227 |a: &$lt_tcx SyncDroplessArena, v| -> &$lt_tcx $ty { a.alloc(v) },
2232 pub fn keep_local<'tcx, T: ty::TypeFoldable<'tcx>>(x: &T) -> bool {
2233 x.has_type_flags(ty::TypeFlags::KEEP_IN_LOCAL_TCX)
2236 direct_interners!('tcx,
2237 region: mk_region(RegionKind),
2238 goal: mk_goal(GoalKind<'tcx>),
2239 const_: mk_const(Const<'tcx>)
2242 macro_rules! slice_interners {
2243 ($($field:ident: $method:ident($ty:ty)),+) => (
2244 $(intern_method!( 'tcx, $field: $method(
2246 |a, v| List::from_arena(a, v),
2247 Deref::deref) -> List<$ty>);)+
2252 existential_predicates: _intern_existential_predicates(ExistentialPredicate<'tcx>),
2253 predicates: _intern_predicates(Predicate<'tcx>),
2254 type_list: _intern_type_list(Ty<'tcx>),
2255 substs: _intern_substs(Kind<'tcx>),
2256 clauses: _intern_clauses(Clause<'tcx>),
2257 goal_list: _intern_goals(Goal<'tcx>),
2258 projs: _intern_projs(ProjectionKind)
2261 // This isn't a perfect fit: `CanonicalVarInfo` slices are always
2262 // allocated in the global arena, so this `intern_method!` macro is
2263 // overly general. However, we just return `false` for the code that checks
2264 // whether they belong in the thread-local arena, so no harm done, and
2265 // seems better than open-coding the rest.
2268 canonical_var_infos: _intern_canonical_var_infos(
2269 &[CanonicalVarInfo],
2270 |a, v| List::from_arena(a, v),
2272 ) -> List<CanonicalVarInfo>
2275 impl<'tcx> TyCtxt<'tcx> {
2276 /// Given a `fn` type, returns an equivalent `unsafe fn` type;
2277 /// that is, a `fn` type that is equivalent in every way for being
2279 pub fn safe_to_unsafe_fn_ty(self, sig: PolyFnSig<'tcx>) -> Ty<'tcx> {
2280 assert_eq!(sig.unsafety(), hir::Unsafety::Normal);
2281 self.mk_fn_ptr(sig.map_bound(|sig| ty::FnSig {
2282 unsafety: hir::Unsafety::Unsafe,
2287 /// Given a closure signature `sig`, returns an equivalent `fn`
2288 /// type with the same signature. Detuples and so forth -- so
2289 /// e.g., if we have a sig with `Fn<(u32, i32)>` then you would get
2290 /// a `fn(u32, i32)`.
2291 /// `unsafety` determines the unsafety of the `fn` type. If you pass
2292 /// `hir::Unsafety::Unsafe` in the previous example, then you would get
2293 /// an `unsafe fn (u32, i32)`.
2294 /// It cannot convert a closure that requires unsafe.
2295 pub fn coerce_closure_fn_ty(self, sig: PolyFnSig<'tcx>, unsafety: hir::Unsafety) -> Ty<'tcx> {
2296 let converted_sig = sig.map_bound(|s| {
2297 let params_iter = match s.inputs()[0].sty {
2298 ty::Tuple(params) => {
2299 params.into_iter().map(|k| k.expect_ty())
2312 self.mk_fn_ptr(converted_sig)
2315 #[allow(rustc::usage_of_ty_tykind)]
2317 pub fn mk_ty(&self, st: TyKind<'tcx>) -> Ty<'tcx> {
2318 self.interners.intern_ty(st)
2321 pub fn mk_mach_int(self, tm: ast::IntTy) -> Ty<'tcx> {
2323 ast::IntTy::Isize => self.types.isize,
2324 ast::IntTy::I8 => self.types.i8,
2325 ast::IntTy::I16 => self.types.i16,
2326 ast::IntTy::I32 => self.types.i32,
2327 ast::IntTy::I64 => self.types.i64,
2328 ast::IntTy::I128 => self.types.i128,
2332 pub fn mk_mach_uint(self, tm: ast::UintTy) -> Ty<'tcx> {
2334 ast::UintTy::Usize => self.types.usize,
2335 ast::UintTy::U8 => self.types.u8,
2336 ast::UintTy::U16 => self.types.u16,
2337 ast::UintTy::U32 => self.types.u32,
2338 ast::UintTy::U64 => self.types.u64,
2339 ast::UintTy::U128 => self.types.u128,
2343 pub fn mk_mach_float(self, tm: ast::FloatTy) -> Ty<'tcx> {
2345 ast::FloatTy::F32 => self.types.f32,
2346 ast::FloatTy::F64 => self.types.f64,
2351 pub fn mk_str(self) -> Ty<'tcx> {
2356 pub fn mk_static_str(self) -> Ty<'tcx> {
2357 self.mk_imm_ref(self.lifetimes.re_static, self.mk_str())
2361 pub fn mk_adt(self, def: &'tcx AdtDef, substs: SubstsRef<'tcx>) -> Ty<'tcx> {
2362 // Take a copy of substs so that we own the vectors inside.
2363 self.mk_ty(Adt(def, substs))
2367 pub fn mk_foreign(self, def_id: DefId) -> Ty<'tcx> {
2368 self.mk_ty(Foreign(def_id))
2371 fn mk_generic_adt(self, wrapper_def_id: DefId, ty_param: Ty<'tcx>) -> Ty<'tcx> {
2372 let adt_def = self.adt_def(wrapper_def_id);
2373 let substs = InternalSubsts::for_item(self, wrapper_def_id, |param, substs| {
2375 GenericParamDefKind::Lifetime |
2376 GenericParamDefKind::Const => {
2379 GenericParamDefKind::Type { has_default, .. } => {
2380 if param.index == 0 {
2383 assert!(has_default);
2384 self.type_of(param.def_id).subst(self, substs).into()
2389 self.mk_ty(Adt(adt_def, substs))
2393 pub fn mk_box(self, ty: Ty<'tcx>) -> Ty<'tcx> {
2394 let def_id = self.require_lang_item(lang_items::OwnedBoxLangItem, None);
2395 self.mk_generic_adt(def_id, ty)
2399 pub fn mk_lang_item(self, ty: Ty<'tcx>, item: lang_items::LangItem) -> Ty<'tcx> {
2400 let def_id = self.require_lang_item(item, None);
2401 self.mk_generic_adt(def_id, ty)
2405 pub fn mk_maybe_uninit(self, ty: Ty<'tcx>) -> Ty<'tcx> {
2406 let def_id = self.require_lang_item(lang_items::MaybeUninitLangItem, None);
2407 self.mk_generic_adt(def_id, ty)
2411 pub fn mk_ptr(self, tm: TypeAndMut<'tcx>) -> Ty<'tcx> {
2412 self.mk_ty(RawPtr(tm))
2416 pub fn mk_ref(self, r: Region<'tcx>, tm: TypeAndMut<'tcx>) -> Ty<'tcx> {
2417 self.mk_ty(Ref(r, tm.ty, tm.mutbl))
2421 pub fn mk_mut_ref(self, r: Region<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
2422 self.mk_ref(r, TypeAndMut {ty: ty, mutbl: hir::MutMutable})
2426 pub fn mk_imm_ref(self, r: Region<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
2427 self.mk_ref(r, TypeAndMut {ty: ty, mutbl: hir::MutImmutable})
2431 pub fn mk_mut_ptr(self, ty: Ty<'tcx>) -> Ty<'tcx> {
2432 self.mk_ptr(TypeAndMut {ty: ty, mutbl: hir::MutMutable})
2436 pub fn mk_imm_ptr(self, ty: Ty<'tcx>) -> Ty<'tcx> {
2437 self.mk_ptr(TypeAndMut {ty: ty, mutbl: hir::MutImmutable})
2441 pub fn mk_nil_ptr(self) -> Ty<'tcx> {
2442 self.mk_imm_ptr(self.mk_unit())
2446 pub fn mk_array(self, ty: Ty<'tcx>, n: u64) -> Ty<'tcx> {
2447 self.mk_ty(Array(ty, ty::Const::from_usize(self.global_tcx(), n)))
2451 pub fn mk_slice(self, ty: Ty<'tcx>) -> Ty<'tcx> {
2452 self.mk_ty(Slice(ty))
2456 pub fn intern_tup(self, ts: &[Ty<'tcx>]) -> Ty<'tcx> {
2457 let kinds: Vec<_> = ts.into_iter().map(|&t| Kind::from(t)).collect();
2458 self.mk_ty(Tuple(self.intern_substs(&kinds)))
2461 pub fn mk_tup<I: InternAs<[Ty<'tcx>], Ty<'tcx>>>(self, iter: I) -> I::Output {
2462 iter.intern_with(|ts| {
2463 let kinds: Vec<_> = ts.into_iter().map(|&t| Kind::from(t)).collect();
2464 self.mk_ty(Tuple(self.intern_substs(&kinds)))
2469 pub fn mk_unit(self) -> Ty<'tcx> {
2474 pub fn mk_diverging_default(self) -> Ty<'tcx> {
2475 if self.features().never_type {
2478 self.intern_tup(&[])
2483 pub fn mk_bool(self) -> Ty<'tcx> {
2488 pub fn mk_fn_def(self, def_id: DefId,
2489 substs: SubstsRef<'tcx>) -> Ty<'tcx> {
2490 self.mk_ty(FnDef(def_id, substs))
2494 pub fn mk_fn_ptr(self, fty: PolyFnSig<'tcx>) -> Ty<'tcx> {
2495 self.mk_ty(FnPtr(fty))
2501 obj: ty::Binder<&'tcx List<ExistentialPredicate<'tcx>>>,
2502 reg: ty::Region<'tcx>
2504 self.mk_ty(Dynamic(obj, reg))
2508 pub fn mk_projection(self,
2510 substs: SubstsRef<'tcx>)
2512 self.mk_ty(Projection(ProjectionTy {
2519 pub fn mk_closure(self, closure_id: DefId, closure_substs: ClosureSubsts<'tcx>)
2521 self.mk_ty(Closure(closure_id, closure_substs))
2525 pub fn mk_generator(self,
2527 generator_substs: GeneratorSubsts<'tcx>,
2528 movability: hir::GeneratorMovability)
2530 self.mk_ty(Generator(id, generator_substs, movability))
2534 pub fn mk_generator_witness(self, types: ty::Binder<&'tcx List<Ty<'tcx>>>) -> Ty<'tcx> {
2535 self.mk_ty(GeneratorWitness(types))
2539 pub fn mk_ty_var(self, v: TyVid) -> Ty<'tcx> {
2540 self.mk_ty_infer(TyVar(v))
2544 pub fn mk_const_var(self, v: ConstVid<'tcx>, ty: Ty<'tcx>) -> &'tcx Const<'tcx> {
2545 self.mk_const(ty::Const {
2546 val: ConstValue::Infer(InferConst::Var(v)),
2552 pub fn mk_int_var(self, v: IntVid) -> Ty<'tcx> {
2553 self.mk_ty_infer(IntVar(v))
2557 pub fn mk_float_var(self, v: FloatVid) -> Ty<'tcx> {
2558 self.mk_ty_infer(FloatVar(v))
2562 pub fn mk_ty_infer(self, it: InferTy) -> Ty<'tcx> {
2563 self.mk_ty(Infer(it))
2567 pub fn mk_const_infer(
2569 ic: InferConst<'tcx>,
2571 ) -> &'tcx ty::Const<'tcx> {
2572 self.mk_const(ty::Const {
2573 val: ConstValue::Infer(ic),
2579 pub fn mk_ty_param(self, index: u32, name: InternedString) -> Ty<'tcx> {
2580 self.mk_ty(Param(ParamTy { index, name: name }))
2584 pub fn mk_const_param(
2587 name: InternedString,
2589 ) -> &'tcx Const<'tcx> {
2590 self.mk_const(ty::Const {
2591 val: ConstValue::Param(ParamConst { index, name }),
2597 pub fn mk_param_from_def(self, param: &ty::GenericParamDef) -> Kind<'tcx> {
2599 GenericParamDefKind::Lifetime => {
2600 self.mk_region(ty::ReEarlyBound(param.to_early_bound_region_data())).into()
2602 GenericParamDefKind::Type { .. } => self.mk_ty_param(param.index, param.name).into(),
2603 GenericParamDefKind::Const => {
2604 self.mk_const_param(param.index, param.name, self.type_of(param.def_id)).into()
2610 pub fn mk_opaque(self, def_id: DefId, substs: SubstsRef<'tcx>) -> Ty<'tcx> {
2611 self.mk_ty(Opaque(def_id, substs))
2614 pub fn intern_existential_predicates(self, eps: &[ExistentialPredicate<'tcx>])
2615 -> &'tcx List<ExistentialPredicate<'tcx>> {
2616 assert!(!eps.is_empty());
2617 assert!(eps.windows(2).all(|w| w[0].stable_cmp(self, &w[1]) != Ordering::Greater));
2618 self._intern_existential_predicates(eps)
2621 pub fn intern_predicates(self, preds: &[Predicate<'tcx>])
2622 -> &'tcx List<Predicate<'tcx>> {
2623 // FIXME consider asking the input slice to be sorted to avoid
2624 // re-interning permutations, in which case that would be asserted
2626 if preds.len() == 0 {
2627 // The macro-generated method below asserts we don't intern an empty slice.
2630 self._intern_predicates(preds)
2634 pub fn intern_type_list(self, ts: &[Ty<'tcx>]) -> &'tcx List<Ty<'tcx>> {
2638 self._intern_type_list(ts)
2642 pub fn intern_substs(self, ts: &[Kind<'tcx>]) -> &'tcx List<Kind<'tcx>> {
2646 self._intern_substs(ts)
2650 pub fn intern_projs(self, ps: &[ProjectionKind]) -> &'tcx List<ProjectionKind> {
2654 self._intern_projs(ps)
2658 pub fn intern_canonical_var_infos(self, ts: &[CanonicalVarInfo]) -> CanonicalVarInfos<'tcx> {
2662 self.global_tcx()._intern_canonical_var_infos(ts)
2666 pub fn intern_clauses(self, ts: &[Clause<'tcx>]) -> Clauses<'tcx> {
2670 self._intern_clauses(ts)
2674 pub fn intern_goals(self, ts: &[Goal<'tcx>]) -> Goals<'tcx> {
2678 self._intern_goals(ts)
2682 pub fn mk_fn_sig<I>(self,
2686 unsafety: hir::Unsafety,
2688 -> <I::Item as InternIteratorElement<Ty<'tcx>, ty::FnSig<'tcx>>>::Output
2690 I: Iterator<Item: InternIteratorElement<Ty<'tcx>, ty::FnSig<'tcx>>>,
2692 inputs.chain(iter::once(output)).intern_with(|xs| ty::FnSig {
2693 inputs_and_output: self.intern_type_list(xs),
2694 c_variadic, unsafety, abi
2698 pub fn mk_existential_predicates<I: InternAs<[ExistentialPredicate<'tcx>],
2699 &'tcx List<ExistentialPredicate<'tcx>>>>(self, iter: I)
2701 iter.intern_with(|xs| self.intern_existential_predicates(xs))
2704 pub fn mk_predicates<I: InternAs<[Predicate<'tcx>],
2705 &'tcx List<Predicate<'tcx>>>>(self, iter: I)
2707 iter.intern_with(|xs| self.intern_predicates(xs))
2710 pub fn mk_type_list<I: InternAs<[Ty<'tcx>],
2711 &'tcx List<Ty<'tcx>>>>(self, iter: I) -> I::Output {
2712 iter.intern_with(|xs| self.intern_type_list(xs))
2715 pub fn mk_substs<I: InternAs<[Kind<'tcx>],
2716 &'tcx List<Kind<'tcx>>>>(self, iter: I) -> I::Output {
2717 iter.intern_with(|xs| self.intern_substs(xs))
2720 pub fn mk_substs_trait(self,
2722 rest: &[Kind<'tcx>])
2725 self.mk_substs(iter::once(self_ty.into()).chain(rest.iter().cloned()))
2728 pub fn mk_clauses<I: InternAs<[Clause<'tcx>], Clauses<'tcx>>>(self, iter: I) -> I::Output {
2729 iter.intern_with(|xs| self.intern_clauses(xs))
2732 pub fn mk_goals<I: InternAs<[Goal<'tcx>], Goals<'tcx>>>(self, iter: I) -> I::Output {
2733 iter.intern_with(|xs| self.intern_goals(xs))
2736 pub fn lint_hir<S: Into<MultiSpan>>(self,
2737 lint: &'static Lint,
2741 self.struct_span_lint_hir(lint, hir_id, span.into(), msg).emit()
2744 pub fn lint_hir_note<S: Into<MultiSpan>>(self,
2745 lint: &'static Lint,
2750 let mut err = self.struct_span_lint_hir(lint, hir_id, span.into(), msg);
2755 pub fn lint_node_note<S: Into<MultiSpan>>(self,
2756 lint: &'static Lint,
2761 let mut err = self.struct_span_lint_hir(lint, id, span.into(), msg);
2766 /// Walks upwards from `id` to find a node which might change lint levels with attributes.
2767 /// It stops at `bound` and just returns it if reached.
2768 pub fn maybe_lint_level_root_bounded(
2777 if lint::maybe_lint_level_root(self, id) {
2780 let next = self.hir().get_parent_node(id);
2782 bug!("lint traversal reached the root of the crate");
2788 pub fn lint_level_at_node(
2790 lint: &'static Lint,
2792 ) -> (lint::Level, lint::LintSource) {
2793 let sets = self.lint_levels(LOCAL_CRATE);
2795 if let Some(pair) = sets.level_and_source(lint, id, self.sess) {
2798 let next = self.hir().get_parent_node(id);
2800 bug!("lint traversal reached the root of the crate");
2806 pub fn struct_span_lint_hir<S: Into<MultiSpan>>(self,
2807 lint: &'static Lint,
2811 -> DiagnosticBuilder<'tcx>
2813 let (level, src) = self.lint_level_at_node(lint, hir_id);
2814 lint::struct_lint_level(self.sess, lint, level, src, Some(span.into()), msg)
2817 pub fn struct_lint_node(self, lint: &'static Lint, id: HirId, msg: &str)
2818 -> DiagnosticBuilder<'tcx>
2820 let (level, src) = self.lint_level_at_node(lint, id);
2821 lint::struct_lint_level(self.sess, lint, level, src, None, msg)
2824 pub fn in_scope_traits(self, id: HirId) -> Option<&'tcx StableVec<TraitCandidate>> {
2825 self.in_scope_traits_map(id.owner)
2826 .and_then(|map| map.get(&id.local_id))
2829 pub fn named_region(self, id: HirId) -> Option<resolve_lifetime::Region> {
2830 self.named_region_map(id.owner)
2831 .and_then(|map| map.get(&id.local_id).cloned())
2834 pub fn is_late_bound(self, id: HirId) -> bool {
2835 self.is_late_bound_map(id.owner)
2836 .map(|set| set.contains(&id.local_id))
2840 pub fn object_lifetime_defaults(self, id: HirId) -> Option<&'tcx [ObjectLifetimeDefault]> {
2841 self.object_lifetime_defaults_map(id.owner)
2842 .and_then(|map| map.get(&id.local_id).map(|v| &**v))
2846 pub trait InternAs<T: ?Sized, R> {
2848 fn intern_with<F>(self, f: F) -> Self::Output
2849 where F: FnOnce(&T) -> R;
2852 impl<I, T, R, E> InternAs<[T], R> for I
2853 where E: InternIteratorElement<T, R>,
2854 I: Iterator<Item=E> {
2855 type Output = E::Output;
2856 fn intern_with<F>(self, f: F) -> Self::Output
2857 where F: FnOnce(&[T]) -> R {
2858 E::intern_with(self, f)
2862 pub trait InternIteratorElement<T, R>: Sized {
2864 fn intern_with<I: Iterator<Item=Self>, F: FnOnce(&[T]) -> R>(iter: I, f: F) -> Self::Output;
2867 impl<T, R> InternIteratorElement<T, R> for T {
2869 fn intern_with<I: Iterator<Item=Self>, F: FnOnce(&[T]) -> R>(iter: I, f: F) -> Self::Output {
2870 f(&iter.collect::<SmallVec<[_; 8]>>())
2874 impl<'a, T, R> InternIteratorElement<T, R> for &'a T
2878 fn intern_with<I: Iterator<Item=Self>, F: FnOnce(&[T]) -> R>(iter: I, f: F) -> Self::Output {
2879 f(&iter.cloned().collect::<SmallVec<[_; 8]>>())
2883 impl<T, R, E> InternIteratorElement<T, R> for Result<T, E> {
2884 type Output = Result<R, E>;
2885 fn intern_with<I: Iterator<Item=Self>, F: FnOnce(&[T]) -> R>(iter: I, f: F) -> Self::Output {
2886 Ok(f(&iter.collect::<Result<SmallVec<[_; 8]>, _>>()?))
2890 // We are comparing types with different invariant lifetimes, so `ptr::eq`
2891 // won't work for us.
2892 fn ptr_eq<T, U>(t: *const T, u: *const U) -> bool {
2893 t as *const () == u as *const ()
2896 pub fn provide(providers: &mut ty::query::Providers<'_>) {
2897 providers.in_scope_traits_map = |tcx, id| tcx.gcx.trait_map.get(&id);
2898 providers.module_exports = |tcx, id| tcx.gcx.export_map.get(&id).map(|v| &v[..]);
2899 providers.crate_name = |tcx, id| {
2900 assert_eq!(id, LOCAL_CRATE);
2903 providers.get_lib_features = |tcx, id| {
2904 assert_eq!(id, LOCAL_CRATE);
2905 tcx.arena.alloc(middle::lib_features::collect(tcx))
2907 providers.get_lang_items = |tcx, id| {
2908 assert_eq!(id, LOCAL_CRATE);
2909 tcx.arena.alloc(middle::lang_items::collect(tcx))
2911 providers.diagnostic_items = |tcx, id| {
2912 assert_eq!(id, LOCAL_CRATE);
2913 middle::diagnostic_items::collect(tcx)
2915 providers.all_diagnostic_items = |tcx, id| {
2916 assert_eq!(id, LOCAL_CRATE);
2917 middle::diagnostic_items::collect_all(tcx)
2919 providers.maybe_unused_trait_import = |tcx, id| {
2920 tcx.maybe_unused_trait_imports.contains(&id)
2922 providers.maybe_unused_extern_crates = |tcx, cnum| {
2923 assert_eq!(cnum, LOCAL_CRATE);
2924 &tcx.maybe_unused_extern_crates[..]
2926 providers.names_imported_by_glob_use = |tcx, id| {
2927 assert_eq!(id.krate, LOCAL_CRATE);
2928 Lrc::new(tcx.glob_map.get(&id).cloned().unwrap_or_default())
2931 providers.stability_index = |tcx, cnum| {
2932 assert_eq!(cnum, LOCAL_CRATE);
2933 tcx.arena.alloc(stability::Index::new(tcx))
2935 providers.lookup_stability = |tcx, id| {
2936 assert_eq!(id.krate, LOCAL_CRATE);
2937 let id = tcx.hir().definitions().def_index_to_hir_id(id.index);
2938 tcx.stability().local_stability(id)
2940 providers.lookup_deprecation_entry = |tcx, id| {
2941 assert_eq!(id.krate, LOCAL_CRATE);
2942 let id = tcx.hir().definitions().def_index_to_hir_id(id.index);
2943 tcx.stability().local_deprecation_entry(id)
2945 providers.extern_mod_stmt_cnum = |tcx, id| {
2946 let id = tcx.hir().as_local_node_id(id).unwrap();
2947 tcx.cstore.extern_mod_stmt_cnum_untracked(id)
2949 providers.all_crate_nums = |tcx, cnum| {
2950 assert_eq!(cnum, LOCAL_CRATE);
2951 tcx.arena.alloc_slice(&tcx.cstore.crates_untracked())
2953 providers.postorder_cnums = |tcx, cnum| {
2954 assert_eq!(cnum, LOCAL_CRATE);
2955 tcx.arena.alloc_slice(&tcx.cstore.postorder_cnums_untracked())
2957 providers.output_filenames = |tcx, cnum| {
2958 assert_eq!(cnum, LOCAL_CRATE);
2959 tcx.output_filenames.clone()
2961 providers.features_query = |tcx, cnum| {
2962 assert_eq!(cnum, LOCAL_CRATE);
2963 tcx.arena.alloc(tcx.sess.features_untracked().clone())
2965 providers.is_panic_runtime = |tcx, cnum| {
2966 assert_eq!(cnum, LOCAL_CRATE);
2967 attr::contains_name(tcx.hir().krate_attrs(), sym::panic_runtime)
2969 providers.is_compiler_builtins = |tcx, cnum| {
2970 assert_eq!(cnum, LOCAL_CRATE);
2971 attr::contains_name(tcx.hir().krate_attrs(), sym::compiler_builtins)