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_index::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 /// Whenever a value may be live across a generator yield, the type of that value winds up in the
292 /// `GeneratorInteriorTypeCause` struct. This struct adds additional information about such
293 /// captured types that can be useful for diagnostics. In particular, it stores the span that
294 /// caused a given type to be recorded, along with the scope that enclosed the value (which can
295 /// be used to find the await that the value is live across).
299 /// ```ignore (pseudo-Rust)
307 /// Here, we would store the type `T`, the span of the value `x`, and the "scope-span" for
308 /// the scope that contains `x`.
309 #[derive(RustcEncodable, RustcDecodable, Clone, Debug, Eq, Hash, HashStable, PartialEq)]
310 pub struct GeneratorInteriorTypeCause<'tcx> {
311 /// Type of the captured binding.
313 /// Span of the binding that was captured.
315 /// Span of the scope of the captured binding.
316 pub scope_span: Option<Span>,
319 #[derive(RustcEncodable, RustcDecodable, Debug)]
320 pub struct TypeckTables<'tcx> {
321 /// The HirId::owner all ItemLocalIds in this table are relative to.
322 pub local_id_root: Option<DefId>,
324 /// Resolved definitions for `<T>::X` associated paths and
325 /// method calls, including those of overloaded operators.
326 type_dependent_defs: ItemLocalMap<Result<(DefKind, DefId), ErrorReported>>,
328 /// Resolved field indices for field accesses in expressions (`S { field }`, `obj.field`)
329 /// or patterns (`S { field }`). The index is often useful by itself, but to learn more
330 /// about the field you also need definition of the variant to which the field
331 /// belongs, but it may not exist if it's a tuple field (`tuple.0`).
332 field_indices: ItemLocalMap<usize>,
334 /// Stores the types for various nodes in the AST. Note that this table
335 /// is not guaranteed to be populated until after typeck. See
336 /// typeck::check::fn_ctxt for details.
337 node_types: ItemLocalMap<Ty<'tcx>>,
339 /// Stores the type parameters which were substituted to obtain the type
340 /// of this node. This only applies to nodes that refer to entities
341 /// parameterized by type parameters, such as generic fns, types, or
343 node_substs: ItemLocalMap<SubstsRef<'tcx>>,
345 /// This will either store the canonicalized types provided by the user
346 /// or the substitutions that the user explicitly gave (if any) attached
347 /// to `id`. These will not include any inferred values. The canonical form
348 /// is used to capture things like `_` or other unspecified values.
350 /// For example, if the user wrote `foo.collect::<Vec<_>>()`, then the
351 /// canonical substitutions would include only `for<X> { Vec<X> }`.
353 /// See also `AscribeUserType` statement in MIR.
354 user_provided_types: ItemLocalMap<CanonicalUserType<'tcx>>,
356 /// Stores the canonicalized types provided by the user. See also
357 /// `AscribeUserType` statement in MIR.
358 pub user_provided_sigs: DefIdMap<CanonicalPolyFnSig<'tcx>>,
360 adjustments: ItemLocalMap<Vec<ty::adjustment::Adjustment<'tcx>>>,
362 /// Stores the actual binding mode for all instances of hir::BindingAnnotation.
363 pat_binding_modes: ItemLocalMap<BindingMode>,
365 /// Stores the types which were implicitly dereferenced in pattern binding modes
366 /// for later usage in HAIR lowering. For example,
369 /// match &&Some(5i32) {
374 /// leads to a `vec![&&Option<i32>, &Option<i32>]`. Empty vectors are not stored.
377 /// https://github.com/rust-lang/rfcs/blob/master/text/2005-match-ergonomics.md#definitions
378 pat_adjustments: ItemLocalMap<Vec<Ty<'tcx>>>,
381 pub upvar_capture_map: ty::UpvarCaptureMap<'tcx>,
383 /// Records the reasons that we picked the kind of each closure;
384 /// not all closures are present in the map.
385 closure_kind_origins: ItemLocalMap<(Span, ast::Name)>,
387 /// For each fn, records the "liberated" types of its arguments
388 /// and return type. Liberated means that all bound regions
389 /// (including late-bound regions) are replaced with free
390 /// equivalents. This table is not used in codegen (since regions
391 /// are erased there) and hence is not serialized to metadata.
392 liberated_fn_sigs: ItemLocalMap<ty::FnSig<'tcx>>,
394 /// For each FRU expression, record the normalized types of the fields
395 /// of the struct - this is needed because it is non-trivial to
396 /// normalize while preserving regions. This table is used only in
397 /// MIR construction and hence is not serialized to metadata.
398 fru_field_types: ItemLocalMap<Vec<Ty<'tcx>>>,
400 /// For every coercion cast we add the HIR node ID of the cast
401 /// expression to this set.
402 coercion_casts: ItemLocalSet,
404 /// Set of trait imports actually used in the method resolution.
405 /// This is used for warning unused imports. During type
406 /// checking, this `Lrc` should not be cloned: it must have a ref-count
407 /// of 1 so that we can insert things into the set mutably.
408 pub used_trait_imports: Lrc<DefIdSet>,
410 /// If any errors occurred while type-checking this body,
411 /// this field will be set to `true`.
412 pub tainted_by_errors: bool,
414 /// Stores the free-region relationships that were deduced from
415 /// its where-clauses and parameter types. These are then
416 /// read-again by borrowck.
417 pub free_region_map: FreeRegionMap<'tcx>,
419 /// All the opaque types that are restricted to concrete types
420 /// by this function.
421 pub concrete_opaque_types: FxHashMap<DefId, ResolvedOpaqueTy<'tcx>>,
423 /// Given the closure ID this map provides the list of UpvarIDs used by it.
424 /// The upvarID contains the HIR node ID and it also contains the full path
425 /// leading to the member of the struct or tuple that is used instead of the
427 pub upvar_list: ty::UpvarListMap,
429 /// Stores the type, span and optional scope span of all types
430 /// that are live across the yield of this generator (if a generator).
431 pub generator_interior_types: Vec<GeneratorInteriorTypeCause<'tcx>>,
434 impl<'tcx> TypeckTables<'tcx> {
435 pub fn empty(local_id_root: Option<DefId>) -> TypeckTables<'tcx> {
438 type_dependent_defs: Default::default(),
439 field_indices: Default::default(),
440 user_provided_types: Default::default(),
441 user_provided_sigs: Default::default(),
442 node_types: Default::default(),
443 node_substs: Default::default(),
444 adjustments: Default::default(),
445 pat_binding_modes: Default::default(),
446 pat_adjustments: Default::default(),
447 upvar_capture_map: Default::default(),
448 closure_kind_origins: Default::default(),
449 liberated_fn_sigs: Default::default(),
450 fru_field_types: Default::default(),
451 coercion_casts: Default::default(),
452 used_trait_imports: Lrc::new(Default::default()),
453 tainted_by_errors: false,
454 free_region_map: Default::default(),
455 concrete_opaque_types: Default::default(),
456 upvar_list: Default::default(),
457 generator_interior_types: Default::default(),
461 /// Returns the final resolution of a `QPath` in an `Expr` or `Pat` node.
462 pub fn qpath_res(&self, qpath: &hir::QPath, id: hir::HirId) -> Res {
464 hir::QPath::Resolved(_, ref path) => path.res,
465 hir::QPath::TypeRelative(..) => self.type_dependent_def(id)
466 .map_or(Res::Err, |(kind, def_id)| Res::Def(kind, def_id)),
470 pub fn type_dependent_defs(
472 ) -> LocalTableInContext<'_, Result<(DefKind, DefId), ErrorReported>> {
473 LocalTableInContext {
474 local_id_root: self.local_id_root,
475 data: &self.type_dependent_defs
479 pub fn type_dependent_def(&self, id: HirId) -> Option<(DefKind, DefId)> {
480 validate_hir_id_for_typeck_tables(self.local_id_root, id, false);
481 self.type_dependent_defs.get(&id.local_id).cloned().and_then(|r| r.ok())
484 pub fn type_dependent_def_id(&self, id: HirId) -> Option<DefId> {
485 self.type_dependent_def(id).map(|(_, def_id)| def_id)
488 pub fn type_dependent_defs_mut(
490 ) -> LocalTableInContextMut<'_, Result<(DefKind, DefId), ErrorReported>> {
491 LocalTableInContextMut {
492 local_id_root: self.local_id_root,
493 data: &mut self.type_dependent_defs
497 pub fn field_indices(&self) -> LocalTableInContext<'_, usize> {
498 LocalTableInContext {
499 local_id_root: self.local_id_root,
500 data: &self.field_indices
504 pub fn field_indices_mut(&mut self) -> LocalTableInContextMut<'_, usize> {
505 LocalTableInContextMut {
506 local_id_root: self.local_id_root,
507 data: &mut self.field_indices
511 pub fn user_provided_types(
513 ) -> LocalTableInContext<'_, CanonicalUserType<'tcx>> {
514 LocalTableInContext {
515 local_id_root: self.local_id_root,
516 data: &self.user_provided_types
520 pub fn user_provided_types_mut(
522 ) -> LocalTableInContextMut<'_, CanonicalUserType<'tcx>> {
523 LocalTableInContextMut {
524 local_id_root: self.local_id_root,
525 data: &mut self.user_provided_types
529 pub fn node_types(&self) -> LocalTableInContext<'_, Ty<'tcx>> {
530 LocalTableInContext {
531 local_id_root: self.local_id_root,
532 data: &self.node_types
536 pub fn node_types_mut(&mut self) -> LocalTableInContextMut<'_, Ty<'tcx>> {
537 LocalTableInContextMut {
538 local_id_root: self.local_id_root,
539 data: &mut self.node_types
543 pub fn node_type(&self, id: hir::HirId) -> Ty<'tcx> {
544 self.node_type_opt(id).unwrap_or_else(||
545 bug!("node_type: no type for node `{}`",
546 tls::with(|tcx| tcx.hir().node_to_string(id)))
550 pub fn node_type_opt(&self, id: hir::HirId) -> Option<Ty<'tcx>> {
551 validate_hir_id_for_typeck_tables(self.local_id_root, id, false);
552 self.node_types.get(&id.local_id).cloned()
555 pub fn node_substs_mut(&mut self) -> LocalTableInContextMut<'_, SubstsRef<'tcx>> {
556 LocalTableInContextMut {
557 local_id_root: self.local_id_root,
558 data: &mut self.node_substs
562 pub fn node_substs(&self, id: hir::HirId) -> SubstsRef<'tcx> {
563 validate_hir_id_for_typeck_tables(self.local_id_root, id, false);
564 self.node_substs.get(&id.local_id).cloned().unwrap_or_else(|| InternalSubsts::empty())
567 pub fn node_substs_opt(&self, id: hir::HirId) -> Option<SubstsRef<'tcx>> {
568 validate_hir_id_for_typeck_tables(self.local_id_root, id, false);
569 self.node_substs.get(&id.local_id).cloned()
572 // Returns the type of a pattern as a monotype. Like @expr_ty, this function
573 // doesn't provide type parameter substitutions.
574 pub fn pat_ty(&self, pat: &hir::Pat) -> Ty<'tcx> {
575 self.node_type(pat.hir_id)
578 pub fn pat_ty_opt(&self, pat: &hir::Pat) -> Option<Ty<'tcx>> {
579 self.node_type_opt(pat.hir_id)
582 // Returns the type of an expression as a monotype.
584 // NB (1): This is the PRE-ADJUSTMENT TYPE for the expression. That is, in
585 // some cases, we insert `Adjustment` annotations such as auto-deref or
586 // auto-ref. The type returned by this function does not consider such
587 // adjustments. See `expr_ty_adjusted()` instead.
589 // NB (2): This type doesn't provide type parameter substitutions; e.g., if you
590 // ask for the type of "id" in "id(3)", it will return "fn(&isize) -> isize"
591 // instead of "fn(ty) -> T with T = isize".
592 pub fn expr_ty(&self, expr: &hir::Expr) -> Ty<'tcx> {
593 self.node_type(expr.hir_id)
596 pub fn expr_ty_opt(&self, expr: &hir::Expr) -> Option<Ty<'tcx>> {
597 self.node_type_opt(expr.hir_id)
600 pub fn adjustments(&self) -> LocalTableInContext<'_, Vec<ty::adjustment::Adjustment<'tcx>>> {
601 LocalTableInContext {
602 local_id_root: self.local_id_root,
603 data: &self.adjustments
607 pub fn adjustments_mut(&mut self)
608 -> LocalTableInContextMut<'_, Vec<ty::adjustment::Adjustment<'tcx>>> {
609 LocalTableInContextMut {
610 local_id_root: self.local_id_root,
611 data: &mut self.adjustments
615 pub fn expr_adjustments(&self, expr: &hir::Expr)
616 -> &[ty::adjustment::Adjustment<'tcx>] {
617 validate_hir_id_for_typeck_tables(self.local_id_root, expr.hir_id, false);
618 self.adjustments.get(&expr.hir_id.local_id).map_or(&[], |a| &a[..])
621 /// Returns the type of `expr`, considering any `Adjustment`
622 /// entry recorded for that expression.
623 pub fn expr_ty_adjusted(&self, expr: &hir::Expr) -> Ty<'tcx> {
624 self.expr_adjustments(expr)
626 .map_or_else(|| self.expr_ty(expr), |adj| adj.target)
629 pub fn expr_ty_adjusted_opt(&self, expr: &hir::Expr) -> Option<Ty<'tcx>> {
630 self.expr_adjustments(expr)
632 .map(|adj| adj.target)
633 .or_else(|| self.expr_ty_opt(expr))
636 pub fn is_method_call(&self, expr: &hir::Expr) -> bool {
637 // Only paths and method calls/overloaded operators have
638 // entries in type_dependent_defs, ignore the former here.
639 if let hir::ExprKind::Path(_) = expr.kind {
643 match self.type_dependent_defs().get(expr.hir_id) {
644 Some(Ok((DefKind::Method, _))) => true,
649 pub fn pat_binding_modes(&self) -> LocalTableInContext<'_, BindingMode> {
650 LocalTableInContext {
651 local_id_root: self.local_id_root,
652 data: &self.pat_binding_modes
656 pub fn pat_binding_modes_mut(&mut self)
657 -> LocalTableInContextMut<'_, BindingMode> {
658 LocalTableInContextMut {
659 local_id_root: self.local_id_root,
660 data: &mut self.pat_binding_modes
664 pub fn pat_adjustments(&self) -> LocalTableInContext<'_, Vec<Ty<'tcx>>> {
665 LocalTableInContext {
666 local_id_root: self.local_id_root,
667 data: &self.pat_adjustments,
671 pub fn pat_adjustments_mut(&mut self)
672 -> LocalTableInContextMut<'_, Vec<Ty<'tcx>>> {
673 LocalTableInContextMut {
674 local_id_root: self.local_id_root,
675 data: &mut self.pat_adjustments,
679 pub fn upvar_capture(&self, upvar_id: ty::UpvarId) -> ty::UpvarCapture<'tcx> {
680 self.upvar_capture_map[&upvar_id]
683 pub fn closure_kind_origins(&self) -> LocalTableInContext<'_, (Span, ast::Name)> {
684 LocalTableInContext {
685 local_id_root: self.local_id_root,
686 data: &self.closure_kind_origins
690 pub fn closure_kind_origins_mut(&mut self) -> LocalTableInContextMut<'_, (Span, ast::Name)> {
691 LocalTableInContextMut {
692 local_id_root: self.local_id_root,
693 data: &mut self.closure_kind_origins
697 pub fn liberated_fn_sigs(&self) -> LocalTableInContext<'_, ty::FnSig<'tcx>> {
698 LocalTableInContext {
699 local_id_root: self.local_id_root,
700 data: &self.liberated_fn_sigs
704 pub fn liberated_fn_sigs_mut(&mut self) -> LocalTableInContextMut<'_, ty::FnSig<'tcx>> {
705 LocalTableInContextMut {
706 local_id_root: self.local_id_root,
707 data: &mut self.liberated_fn_sigs
711 pub fn fru_field_types(&self) -> LocalTableInContext<'_, Vec<Ty<'tcx>>> {
712 LocalTableInContext {
713 local_id_root: self.local_id_root,
714 data: &self.fru_field_types
718 pub fn fru_field_types_mut(&mut self) -> LocalTableInContextMut<'_, Vec<Ty<'tcx>>> {
719 LocalTableInContextMut {
720 local_id_root: self.local_id_root,
721 data: &mut self.fru_field_types
725 pub fn is_coercion_cast(&self, hir_id: hir::HirId) -> bool {
726 validate_hir_id_for_typeck_tables(self.local_id_root, hir_id, true);
727 self.coercion_casts.contains(&hir_id.local_id)
730 pub fn set_coercion_cast(&mut self, id: ItemLocalId) {
731 self.coercion_casts.insert(id);
734 pub fn coercion_casts(&self) -> &ItemLocalSet {
740 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for TypeckTables<'tcx> {
741 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
742 let ty::TypeckTables {
744 ref type_dependent_defs,
746 ref user_provided_types,
747 ref user_provided_sigs,
751 ref pat_binding_modes,
753 ref upvar_capture_map,
754 ref closure_kind_origins,
755 ref liberated_fn_sigs,
760 ref used_trait_imports,
763 ref concrete_opaque_types,
765 ref generator_interior_types,
769 hcx.with_node_id_hashing_mode(NodeIdHashingMode::HashDefPath, |hcx| {
770 type_dependent_defs.hash_stable(hcx, hasher);
771 field_indices.hash_stable(hcx, hasher);
772 user_provided_types.hash_stable(hcx, hasher);
773 user_provided_sigs.hash_stable(hcx, hasher);
774 node_types.hash_stable(hcx, hasher);
775 node_substs.hash_stable(hcx, hasher);
776 adjustments.hash_stable(hcx, hasher);
777 pat_binding_modes.hash_stable(hcx, hasher);
778 pat_adjustments.hash_stable(hcx, hasher);
779 hash_stable_hashmap(hcx, hasher, upvar_capture_map, |up_var_id, hcx| {
786 local_id_root.expect("trying to hash invalid TypeckTables");
788 let var_owner_def_id = DefId {
789 krate: local_id_root.krate,
790 index: var_path.hir_id.owner,
792 let closure_def_id = DefId {
793 krate: local_id_root.krate,
794 index: closure_expr_id.to_def_id().index,
796 (hcx.def_path_hash(var_owner_def_id),
797 var_path.hir_id.local_id,
798 hcx.def_path_hash(closure_def_id))
801 closure_kind_origins.hash_stable(hcx, hasher);
802 liberated_fn_sigs.hash_stable(hcx, hasher);
803 fru_field_types.hash_stable(hcx, hasher);
804 coercion_casts.hash_stable(hcx, hasher);
805 used_trait_imports.hash_stable(hcx, hasher);
806 tainted_by_errors.hash_stable(hcx, hasher);
807 free_region_map.hash_stable(hcx, hasher);
808 concrete_opaque_types.hash_stable(hcx, hasher);
809 upvar_list.hash_stable(hcx, hasher);
810 generator_interior_types.hash_stable(hcx, hasher);
815 rustc_index::newtype_index! {
816 pub struct UserTypeAnnotationIndex {
818 DEBUG_FORMAT = "UserType({})",
819 const START_INDEX = 0,
823 /// Mapping of type annotation indices to canonical user type annotations.
824 pub type CanonicalUserTypeAnnotations<'tcx> =
825 IndexVec<UserTypeAnnotationIndex, CanonicalUserTypeAnnotation<'tcx>>;
827 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
828 pub struct CanonicalUserTypeAnnotation<'tcx> {
829 pub user_ty: CanonicalUserType<'tcx>,
831 pub inferred_ty: Ty<'tcx>,
834 BraceStructTypeFoldableImpl! {
835 impl<'tcx> TypeFoldable<'tcx> for CanonicalUserTypeAnnotation<'tcx> {
836 user_ty, span, inferred_ty
840 BraceStructLiftImpl! {
841 impl<'a, 'tcx> Lift<'tcx> for CanonicalUserTypeAnnotation<'a> {
842 type Lifted = CanonicalUserTypeAnnotation<'tcx>;
843 user_ty, span, inferred_ty
847 /// Canonicalized user type annotation.
848 pub type CanonicalUserType<'tcx> = Canonical<'tcx, UserType<'tcx>>;
850 impl CanonicalUserType<'tcx> {
851 /// Returns `true` if this represents a substitution of the form `[?0, ?1, ?2]`,
852 /// i.e., each thing is mapped to a canonical variable with the same index.
853 pub fn is_identity(&self) -> bool {
855 UserType::Ty(_) => false,
856 UserType::TypeOf(_, user_substs) => {
857 if user_substs.user_self_ty.is_some() {
861 user_substs.substs.iter().zip(BoundVar::new(0)..).all(|(kind, cvar)| {
862 match kind.unpack() {
863 GenericArgKind::Type(ty) => match ty.kind {
864 ty::Bound(debruijn, b) => {
865 // We only allow a `ty::INNERMOST` index in substitutions.
866 assert_eq!(debruijn, ty::INNERMOST);
872 GenericArgKind::Lifetime(r) => match r {
873 ty::ReLateBound(debruijn, br) => {
874 // We only allow a `ty::INNERMOST` index in substitutions.
875 assert_eq!(*debruijn, ty::INNERMOST);
876 cvar == br.assert_bound_var()
881 GenericArgKind::Const(ct) => match ct.val {
882 ConstValue::Infer(InferConst::Canonical(debruijn, b)) => {
883 // We only allow a `ty::INNERMOST` index in substitutions.
884 assert_eq!(debruijn, ty::INNERMOST);
896 /// A user-given type annotation attached to a constant. These arise
897 /// from constants that are named via paths, like `Foo::<A>::new` and
899 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
900 pub enum UserType<'tcx> {
903 /// The canonical type is the result of `type_of(def_id)` with the
904 /// given substitutions applied.
905 TypeOf(DefId, UserSubsts<'tcx>),
908 EnumTypeFoldableImpl! {
909 impl<'tcx> TypeFoldable<'tcx> for UserType<'tcx> {
911 (UserType::TypeOf)(def, substs),
916 impl<'a, 'tcx> Lift<'tcx> for UserType<'a> {
917 type Lifted = UserType<'tcx>;
919 (UserType::TypeOf)(def, substs),
923 impl<'tcx> CommonTypes<'tcx> {
924 fn new(interners: &CtxtInterners<'tcx>) -> CommonTypes<'tcx> {
925 let mk = |ty| interners.intern_ty(ty);
928 unit: mk(Tuple(List::empty())),
933 isize: mk(Int(ast::IntTy::Isize)),
934 i8: mk(Int(ast::IntTy::I8)),
935 i16: mk(Int(ast::IntTy::I16)),
936 i32: mk(Int(ast::IntTy::I32)),
937 i64: mk(Int(ast::IntTy::I64)),
938 i128: mk(Int(ast::IntTy::I128)),
939 usize: mk(Uint(ast::UintTy::Usize)),
940 u8: mk(Uint(ast::UintTy::U8)),
941 u16: mk(Uint(ast::UintTy::U16)),
942 u32: mk(Uint(ast::UintTy::U32)),
943 u64: mk(Uint(ast::UintTy::U64)),
944 u128: mk(Uint(ast::UintTy::U128)),
945 f32: mk(Float(ast::FloatTy::F32)),
946 f64: mk(Float(ast::FloatTy::F64)),
947 self_param: mk(ty::Param(ty::ParamTy {
949 name: kw::SelfUpper.as_interned_str(),
952 trait_object_dummy_self: mk(Infer(ty::FreshTy(0))),
957 impl<'tcx> CommonLifetimes<'tcx> {
958 fn new(interners: &CtxtInterners<'tcx>) -> CommonLifetimes<'tcx> {
960 interners.region.intern(r, |r| {
961 Interned(interners.arena.alloc(r))
966 re_empty: mk(RegionKind::ReEmpty),
967 re_static: mk(RegionKind::ReStatic),
968 re_erased: mk(RegionKind::ReErased),
973 impl<'tcx> CommonConsts<'tcx> {
974 fn new(interners: &CtxtInterners<'tcx>, types: &CommonTypes<'tcx>) -> CommonConsts<'tcx> {
976 interners.const_.intern(c, |c| {
977 Interned(interners.arena.alloc(c))
982 err: mk_const(ty::Const {
983 val: ConstValue::Scalar(Scalar::zst()),
990 // This struct contains information regarding the `ReFree(FreeRegion)` corresponding to a lifetime
993 pub struct FreeRegionInfo {
994 // def id corresponding to FreeRegion
996 // the bound region corresponding to FreeRegion
997 pub boundregion: ty::BoundRegion,
998 // checks if bound region is in Impl Item
999 pub is_impl_item: bool,
1002 /// The central data structure of the compiler. It stores references
1003 /// to the various **arenas** and also houses the results of the
1004 /// various **compiler queries** that have been performed. See the
1005 /// [rustc guide] for more details.
1007 /// [rustc guide]: https://rust-lang.github.io/rustc-guide/ty.html
1008 #[derive(Copy, Clone)]
1009 #[rustc_diagnostic_item = "TyCtxt"]
1010 pub struct TyCtxt<'tcx> {
1011 gcx: &'tcx GlobalCtxt<'tcx>,
1014 impl<'tcx> Deref for TyCtxt<'tcx> {
1015 type Target = &'tcx GlobalCtxt<'tcx>;
1017 fn deref(&self) -> &Self::Target {
1022 pub struct GlobalCtxt<'tcx> {
1023 pub arena: WorkerLocal<Arena<'tcx>>,
1025 interners: CtxtInterners<'tcx>,
1027 cstore: &'tcx CrateStoreDyn,
1029 pub sess: &'tcx Session,
1031 pub dep_graph: DepGraph,
1034 pub common: Common<'tcx>,
1036 /// Common types, pre-interned for your convenience.
1037 pub types: CommonTypes<'tcx>,
1039 /// Common lifetimes, pre-interned for your convenience.
1040 pub lifetimes: CommonLifetimes<'tcx>,
1042 /// Common consts, pre-interned for your convenience.
1043 pub consts: CommonConsts<'tcx>,
1045 /// Map indicating what traits are in scope for places where this
1046 /// is relevant; generated by resolve.
1047 trait_map: FxHashMap<DefIndex,
1048 FxHashMap<ItemLocalId,
1049 StableVec<TraitCandidate>>>,
1051 /// Export map produced by name resolution.
1052 export_map: FxHashMap<DefId, Vec<Export<hir::HirId>>>,
1054 hir_map: hir_map::Map<'tcx>,
1056 /// A map from `DefPathHash` -> `DefId`. Includes `DefId`s from the local crate
1057 /// as well as all upstream crates. Only populated in incremental mode.
1058 pub def_path_hash_to_def_id: Option<FxHashMap<DefPathHash, DefId>>,
1060 pub queries: query::Queries<'tcx>,
1062 maybe_unused_trait_imports: FxHashSet<DefId>,
1063 maybe_unused_extern_crates: Vec<(DefId, Span)>,
1064 /// A map of glob use to a set of names it actually imports. Currently only
1065 /// used in save-analysis.
1066 glob_map: FxHashMap<DefId, FxHashSet<ast::Name>>,
1067 /// Extern prelude entries. The value is `true` if the entry was introduced
1068 /// via `extern crate` item and not `--extern` option or compiler built-in.
1069 pub extern_prelude: FxHashMap<ast::Name, bool>,
1071 // Internal cache for metadata decoding. No need to track deps on this.
1072 pub rcache: Lock<FxHashMap<ty::CReaderCacheKey, Ty<'tcx>>>,
1074 /// Caches the results of trait selection. This cache is used
1075 /// for things that do not have to do with the parameters in scope.
1076 pub selection_cache: traits::SelectionCache<'tcx>,
1078 /// Caches the results of trait evaluation. This cache is used
1079 /// for things that do not have to do with the parameters in scope.
1080 /// Merge this with `selection_cache`?
1081 pub evaluation_cache: traits::EvaluationCache<'tcx>,
1083 /// The definite name of the current crate after taking into account
1084 /// attributes, commandline parameters, etc.
1085 pub crate_name: Symbol,
1087 /// Data layout specification for the current target.
1088 pub data_layout: TargetDataLayout,
1090 stability_interner: ShardedHashMap<&'tcx attr::Stability, ()>,
1092 /// Stores the value of constants (and deduplicates the actual memory)
1093 allocation_interner: ShardedHashMap<&'tcx Allocation, ()>,
1095 pub alloc_map: Lock<interpret::AllocMap<'tcx>>,
1097 layout_interner: ShardedHashMap<&'tcx LayoutDetails, ()>,
1099 output_filenames: Arc<OutputFilenames>,
1102 impl<'tcx> TyCtxt<'tcx> {
1104 pub fn hir(self) -> &'tcx hir_map::Map<'tcx> {
1108 pub fn alloc_steal_mir(self, mir: Body<'tcx>) -> &'tcx Steal<Body<'tcx>> {
1109 self.arena.alloc(Steal::new(mir))
1112 pub fn alloc_steal_promoted(self, promoted: IndexVec<Promoted, Body<'tcx>>) ->
1113 &'tcx Steal<IndexVec<Promoted, Body<'tcx>>> {
1114 self.arena.alloc(Steal::new(promoted))
1117 pub fn intern_promoted(self, promoted: IndexVec<Promoted, Body<'tcx>>) ->
1118 &'tcx IndexVec<Promoted, Body<'tcx>> {
1119 self.arena.alloc(promoted)
1122 pub fn alloc_adt_def(
1126 variants: IndexVec<VariantIdx, ty::VariantDef>,
1128 ) -> &'tcx ty::AdtDef {
1129 let def = ty::AdtDef::new(self, did, kind, variants, repr);
1130 self.arena.alloc(def)
1133 pub fn intern_const_alloc(self, alloc: Allocation) -> &'tcx Allocation {
1134 self.allocation_interner.intern(alloc, |alloc| {
1135 self.arena.alloc(alloc)
1139 /// Allocates a read-only byte or string literal for `mir::interpret`.
1140 pub fn allocate_bytes(self, bytes: &[u8]) -> interpret::AllocId {
1141 // Create an allocation that just contains these bytes.
1142 let alloc = interpret::Allocation::from_byte_aligned_bytes(bytes);
1143 let alloc = self.intern_const_alloc(alloc);
1144 self.alloc_map.lock().create_memory_alloc(alloc)
1147 pub fn intern_stability(self, stab: attr::Stability) -> &'tcx attr::Stability {
1148 self.stability_interner.intern(stab, |stab| {
1149 self.arena.alloc(stab)
1153 pub fn intern_layout(self, layout: LayoutDetails) -> &'tcx LayoutDetails {
1154 self.layout_interner.intern(layout, |layout| {
1155 self.arena.alloc(layout)
1159 /// Returns a range of the start/end indices specified with the
1160 /// `rustc_layout_scalar_valid_range` attribute.
1161 pub fn layout_scalar_valid_range(self, def_id: DefId) -> (Bound<u128>, Bound<u128>) {
1162 let attrs = self.get_attrs(def_id);
1164 let attr = match attrs.iter().find(|a| a.check_name(name)) {
1166 None => return Bound::Unbounded,
1168 for meta in attr.meta_item_list().expect("rustc_layout_scalar_valid_range takes args") {
1169 match meta.literal().expect("attribute takes lit").kind {
1170 ast::LitKind::Int(a, _) => return Bound::Included(a),
1171 _ => span_bug!(attr.span, "rustc_layout_scalar_valid_range expects int arg"),
1174 span_bug!(attr.span, "no arguments to `rustc_layout_scalar_valid_range` attribute");
1176 (get(sym::rustc_layout_scalar_valid_range_start),
1177 get(sym::rustc_layout_scalar_valid_range_end))
1180 pub fn lift<T: ?Sized + Lift<'tcx>>(self, value: &T) -> Option<T::Lifted> {
1181 value.lift_to_tcx(self)
1184 /// Creates a type context and call the closure with a `TyCtxt` reference
1185 /// to the context. The closure enforces that the type context and any interned
1186 /// value (types, substs, etc.) can only be used while `ty::tls` has a valid
1187 /// reference to the context, to allow formatting values that need it.
1188 pub fn create_global_ctxt(
1190 cstore: &'tcx CrateStoreDyn,
1191 local_providers: ty::query::Providers<'tcx>,
1192 extern_providers: ty::query::Providers<'tcx>,
1193 arenas: &'tcx AllArenas,
1194 resolutions: ty::Resolutions,
1195 hir: hir_map::Map<'tcx>,
1196 on_disk_query_result_cache: query::OnDiskCache<'tcx>,
1198 output_filenames: &OutputFilenames,
1199 ) -> GlobalCtxt<'tcx> {
1200 let data_layout = TargetDataLayout::parse(&s.target.target).unwrap_or_else(|err| {
1203 let interners = CtxtInterners::new(&arenas.interner);
1204 let common = Common {
1205 empty_predicates: ty::GenericPredicates {
1210 let common_types = CommonTypes::new(&interners);
1211 let common_lifetimes = CommonLifetimes::new(&interners);
1212 let common_consts = CommonConsts::new(&interners, &common_types);
1213 let dep_graph = hir.dep_graph.clone();
1214 let max_cnum = cstore.crates_untracked().iter().map(|c| c.as_usize()).max().unwrap_or(0);
1215 let mut providers = IndexVec::from_elem_n(extern_providers, max_cnum + 1);
1216 providers[LOCAL_CRATE] = local_providers;
1218 let def_path_hash_to_def_id = if s.opts.build_dep_graph() {
1219 let upstream_def_path_tables: Vec<(CrateNum, Lrc<_>)> = cstore
1222 .map(|&cnum| (cnum, cstore.def_path_table(cnum)))
1225 let def_path_tables = || {
1226 upstream_def_path_tables
1228 .map(|&(cnum, ref rc)| (cnum, &**rc))
1229 .chain(iter::once((LOCAL_CRATE, hir.definitions().def_path_table())))
1232 // Precompute the capacity of the hashmap so we don't have to
1233 // re-allocate when populating it.
1234 let capacity = def_path_tables().map(|(_, t)| t.size()).sum::<usize>();
1236 let mut map: FxHashMap<_, _> = FxHashMap::with_capacity_and_hasher(
1238 ::std::default::Default::default()
1241 for (cnum, def_path_table) in def_path_tables() {
1242 def_path_table.add_def_path_hashes_to(cnum, &mut map);
1250 let mut trait_map: FxHashMap<_, FxHashMap<_, _>> = FxHashMap::default();
1251 for (k, v) in resolutions.trait_map {
1252 let hir_id = hir.node_to_hir_id(k);
1253 let map = trait_map.entry(hir_id.owner).or_default();
1254 map.insert(hir_id.local_id, StableVec::new(v));
1260 arena: WorkerLocal::new(|_| Arena::default()),
1264 types: common_types,
1265 lifetimes: common_lifetimes,
1266 consts: common_consts,
1268 export_map: resolutions.export_map.into_iter().map(|(k, v)| {
1269 let exports: Vec<_> = v.into_iter().map(|e| {
1270 e.map_id(|id| hir.node_to_hir_id(id))
1274 maybe_unused_trait_imports:
1275 resolutions.maybe_unused_trait_imports
1277 .map(|id| hir.local_def_id_from_node_id(id))
1279 maybe_unused_extern_crates:
1280 resolutions.maybe_unused_extern_crates
1282 .map(|(id, sp)| (hir.local_def_id_from_node_id(id), sp))
1284 glob_map: resolutions.glob_map.into_iter().map(|(id, names)| {
1285 (hir.local_def_id_from_node_id(id), names)
1287 extern_prelude: resolutions.extern_prelude,
1289 def_path_hash_to_def_id,
1290 queries: query::Queries::new(
1293 on_disk_query_result_cache,
1295 rcache: Default::default(),
1296 selection_cache: Default::default(),
1297 evaluation_cache: Default::default(),
1298 crate_name: Symbol::intern(crate_name),
1300 layout_interner: Default::default(),
1301 stability_interner: Default::default(),
1302 allocation_interner: Default::default(),
1303 alloc_map: Lock::new(interpret::AllocMap::new()),
1304 output_filenames: Arc::new(output_filenames.clone()),
1308 pub fn consider_optimizing<T: Fn() -> String>(&self, msg: T) -> bool {
1309 let cname = self.crate_name(LOCAL_CRATE).as_str();
1310 self.sess.consider_optimizing(&cname, msg)
1313 pub fn lib_features(self) -> &'tcx middle::lib_features::LibFeatures {
1314 self.get_lib_features(LOCAL_CRATE)
1317 /// Obtain all lang items of this crate and all dependencies (recursively)
1318 pub fn lang_items(self) -> &'tcx middle::lang_items::LanguageItems {
1319 self.get_lang_items(LOCAL_CRATE)
1322 /// Obtain the given diagnostic item's `DefId`. Use `is_diagnostic_item` if you just want to
1323 /// compare against another `DefId`, since `is_diagnostic_item` is cheaper.
1324 pub fn get_diagnostic_item(self, name: Symbol) -> Option<DefId> {
1325 self.all_diagnostic_items(LOCAL_CRATE).get(&name).copied()
1328 /// Check whether the diagnostic item with the given `name` has the given `DefId`.
1329 pub fn is_diagnostic_item(self, name: Symbol, did: DefId) -> bool {
1330 self.diagnostic_items(did.krate).get(&name) == Some(&did)
1333 pub fn stability(self) -> &'tcx stability::Index<'tcx> {
1334 self.stability_index(LOCAL_CRATE)
1337 pub fn crates(self) -> &'tcx [CrateNum] {
1338 self.all_crate_nums(LOCAL_CRATE)
1341 pub fn features(self) -> &'tcx feature_gate::Features {
1342 self.features_query(LOCAL_CRATE)
1345 pub fn def_key(self, id: DefId) -> hir_map::DefKey {
1347 self.hir().def_key(id)
1349 self.cstore.def_key(id)
1353 /// Converts a `DefId` into its fully expanded `DefPath` (every
1354 /// `DefId` is really just an interned `DefPath`).
1356 /// Note that if `id` is not local to this crate, the result will
1357 /// be a non-local `DefPath`.
1358 pub fn def_path(self, id: DefId) -> hir_map::DefPath {
1360 self.hir().def_path(id)
1362 self.cstore.def_path(id)
1366 /// Returns whether or not the crate with CrateNum 'cnum'
1367 /// is marked as a private dependency
1368 pub fn is_private_dep(self, cnum: CrateNum) -> bool {
1369 if cnum == LOCAL_CRATE {
1372 self.cstore.crate_is_private_dep_untracked(cnum)
1377 pub fn def_path_hash(self, def_id: DefId) -> hir_map::DefPathHash {
1378 if def_id.is_local() {
1379 self.hir().definitions().def_path_hash(def_id.index)
1381 self.cstore.def_path_hash(def_id)
1385 pub fn def_path_debug_str(self, def_id: DefId) -> String {
1386 // We are explicitly not going through queries here in order to get
1387 // crate name and disambiguator since this code is called from debug!()
1388 // statements within the query system and we'd run into endless
1389 // recursion otherwise.
1390 let (crate_name, crate_disambiguator) = if def_id.is_local() {
1391 (self.crate_name.clone(),
1392 self.sess.local_crate_disambiguator())
1394 (self.cstore.crate_name_untracked(def_id.krate),
1395 self.cstore.crate_disambiguator_untracked(def_id.krate))
1400 // Don't print the whole crate disambiguator. That's just
1401 // annoying in debug output.
1402 &(crate_disambiguator.to_fingerprint().to_hex())[..4],
1403 self.def_path(def_id).to_string_no_crate())
1406 pub fn metadata_encoding_version(self) -> Vec<u8> {
1407 self.cstore.metadata_encoding_version().to_vec()
1410 pub fn encode_metadata(self)-> EncodedMetadata {
1411 self.cstore.encode_metadata(self)
1414 // Note that this is *untracked* and should only be used within the query
1415 // system if the result is otherwise tracked through queries
1416 pub fn crate_data_as_rc_any(self, cnum: CrateNum) -> Lrc<dyn Any> {
1417 self.cstore.crate_data_as_rc_any(cnum)
1421 pub fn create_stable_hashing_context(self) -> StableHashingContext<'tcx> {
1422 let krate = self.gcx.hir_map.forest.untracked_krate();
1424 StableHashingContext::new(self.sess,
1426 self.hir().definitions(),
1430 // This method makes sure that we have a DepNode and a Fingerprint for
1431 // every upstream crate. It needs to be called once right after the tcx is
1433 // With full-fledged red/green, the method will probably become unnecessary
1434 // as this will be done on-demand.
1435 pub fn allocate_metadata_dep_nodes(self) {
1436 // We cannot use the query versions of crates() and crate_hash(), since
1437 // those would need the DepNodes that we are allocating here.
1438 for cnum in self.cstore.crates_untracked() {
1439 let dep_node = DepNode::new(self, DepConstructor::CrateMetadata(cnum));
1440 let crate_hash = self.cstore.crate_hash_untracked(cnum);
1441 self.dep_graph.with_task(dep_node,
1444 |_, x| x, // No transformation needed
1445 dep_graph::hash_result,
1450 pub fn serialize_query_result_cache<E>(self,
1452 -> Result<(), E::Error>
1453 where E: ty::codec::TyEncoder
1455 self.queries.on_disk_cache.serialize(self, encoder)
1458 /// If `true`, we should use the MIR-based borrowck, but also
1459 /// fall back on the AST borrowck if the MIR-based one errors.
1460 pub fn migrate_borrowck(self) -> bool {
1461 self.borrowck_mode().migrate()
1464 /// If `true`, make MIR codegen for `match` emit a temp that holds a
1465 /// borrow of the input to the match expression.
1466 pub fn generate_borrow_of_any_match_input(&self) -> bool {
1467 self.emit_read_for_match()
1470 /// If `true`, make MIR codegen for `match` emit FakeRead
1471 /// statements (which simulate the maximal effect of executing the
1472 /// patterns in a match arm).
1473 pub fn emit_read_for_match(&self) -> bool {
1474 !self.sess.opts.debugging_opts.nll_dont_emit_read_for_match
1477 /// What mode(s) of borrowck should we run? AST? MIR? both?
1478 /// (Also considers the `#![feature(nll)]` setting.)
1479 pub fn borrowck_mode(&self) -> BorrowckMode {
1480 // Here are the main constraints we need to deal with:
1482 // 1. An opts.borrowck_mode of `BorrowckMode::Migrate` is
1483 // synonymous with no `-Z borrowck=...` flag at all.
1485 // 2. We want to allow developers on the Nightly channel
1486 // to opt back into the "hard error" mode for NLL,
1487 // (which they can do via specifying `#![feature(nll)]`
1488 // explicitly in their crate).
1490 // So, this precedence list is how pnkfelix chose to work with
1491 // the above constraints:
1493 // * `#![feature(nll)]` *always* means use NLL with hard
1494 // errors. (To simplify the code here, it now even overrides
1495 // a user's attempt to specify `-Z borrowck=compare`, which
1496 // we arguably do not need anymore and should remove.)
1498 // * Otherwise, if no `-Z borrowck=...` then use migrate mode
1500 // * Otherwise, use the behavior requested via `-Z borrowck=...`
1502 if self.features().nll { return BorrowckMode::Mir; }
1504 self.sess.opts.borrowck_mode
1508 pub fn local_crate_exports_generics(self) -> bool {
1509 debug_assert!(self.sess.opts.share_generics());
1511 self.sess.crate_types.borrow().iter().any(|crate_type| {
1513 CrateType::Executable |
1514 CrateType::Staticlib |
1515 CrateType::ProcMacro |
1517 CrateType::Cdylib => false,
1518 CrateType::Rlib => true,
1523 // Returns the `DefId` and the `BoundRegion` corresponding to the given region.
1524 pub fn is_suitable_region(&self, region: Region<'tcx>) -> Option<FreeRegionInfo> {
1525 let (suitable_region_binding_scope, bound_region) = match *region {
1526 ty::ReFree(ref free_region) => (free_region.scope, free_region.bound_region),
1527 ty::ReEarlyBound(ref ebr) => (
1528 self.parent(ebr.def_id).unwrap(),
1529 ty::BoundRegion::BrNamed(ebr.def_id, ebr.name),
1531 _ => return None, // not a free region
1534 let hir_id = self.hir()
1535 .as_local_hir_id(suitable_region_binding_scope)
1537 let is_impl_item = match self.hir().find(hir_id) {
1538 Some(Node::Item(..)) | Some(Node::TraitItem(..)) => false,
1539 Some(Node::ImplItem(..)) => {
1540 self.is_bound_region_in_impl_item(suitable_region_binding_scope)
1545 return Some(FreeRegionInfo {
1546 def_id: suitable_region_binding_scope,
1547 boundregion: bound_region,
1548 is_impl_item: is_impl_item,
1552 pub fn return_type_impl_trait(
1554 scope_def_id: DefId,
1555 ) -> Option<Ty<'tcx>> {
1556 // HACK: `type_of_def_id()` will fail on these (#55796), so return `None`.
1557 let hir_id = self.hir().as_local_hir_id(scope_def_id).unwrap();
1558 match self.hir().get(hir_id) {
1559 Node::Item(item) => {
1561 ItemKind::Fn(..) => { /* `type_of_def_id()` will work */ }
1567 _ => { /* `type_of_def_id()` will work or panic */ }
1570 let ret_ty = self.type_of(scope_def_id);
1572 ty::FnDef(_, _) => {
1573 let sig = ret_ty.fn_sig(*self);
1574 let output = self.erase_late_bound_regions(&sig.output());
1575 if output.is_impl_trait() {
1585 // Checks if the bound region is in Impl Item.
1586 pub fn is_bound_region_in_impl_item(
1588 suitable_region_binding_scope: DefId,
1590 let container_id = self.associated_item(suitable_region_binding_scope)
1593 if self.impl_trait_ref(container_id).is_some() {
1594 // For now, we do not try to target impls of traits. This is
1595 // because this message is going to suggest that the user
1596 // change the fn signature, but they may not be free to do so,
1597 // since the signature must match the trait.
1599 // FIXME(#42706) -- in some cases, we could do better here.
1605 /// Determines whether identifiers in the assembly have strict naming rules.
1606 /// Currently, only NVPTX* targets need it.
1607 pub fn has_strict_asm_symbol_naming(&self) -> bool {
1608 self.sess.target.target.arch.contains("nvptx")
1612 impl<'tcx> GlobalCtxt<'tcx> {
1613 /// Calls the closure with a local `TyCtxt` using the given arena.
1614 /// `interners` is a slot passed so we can create a CtxtInterners
1615 /// with the same lifetime as `arena`.
1616 pub fn enter_local<F, R>(&'tcx self, f: F) -> R
1618 F: FnOnce(TyCtxt<'tcx>) -> R,
1623 ty::tls::with_related_context(tcx, |icx| {
1624 let new_icx = ty::tls::ImplicitCtxt {
1626 query: icx.query.clone(),
1627 diagnostics: icx.diagnostics,
1628 layout_depth: icx.layout_depth,
1629 task_deps: icx.task_deps,
1631 ty::tls::enter_context(&new_icx, |_| {
1638 /// A trait implemented for all `X<'a>` types that can be safely and
1639 /// efficiently converted to `X<'tcx>` as long as they are part of the
1640 /// provided `TyCtxt<'tcx>`.
1641 /// This can be done, for example, for `Ty<'tcx>` or `SubstsRef<'tcx>`
1642 /// by looking them up in their respective interners.
1644 /// However, this is still not the best implementation as it does
1645 /// need to compare the components, even for interned values.
1646 /// It would be more efficient if `TypedArena` provided a way to
1647 /// determine whether the address is in the allocated range.
1649 /// `None` is returned if the value or one of the components is not part
1650 /// of the provided context.
1651 /// For `Ty`, `None` can be returned if either the type interner doesn't
1652 /// contain the `TyKind` key or if the address of the interned
1653 /// pointer differs. The latter case is possible if a primitive type,
1654 /// e.g., `()` or `u8`, was interned in a different context.
1655 pub trait Lift<'tcx>: fmt::Debug {
1656 type Lifted: fmt::Debug + 'tcx;
1657 fn lift_to_tcx(&self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted>;
1660 macro_rules! nop_lift {
1661 ($ty:ty => $lifted:ty) => {
1662 impl<'a, 'tcx> Lift<'tcx> for $ty {
1663 type Lifted = $lifted;
1664 fn lift_to_tcx(&self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
1665 if tcx.interners.arena.in_arena(*self as *const _) {
1666 Some(unsafe { mem::transmute(*self) })
1675 macro_rules! nop_list_lift {
1676 ($ty:ty => $lifted:ty) => {
1677 impl<'a, 'tcx> Lift<'tcx> for &'a List<$ty> {
1678 type Lifted = &'tcx List<$lifted>;
1679 fn lift_to_tcx(&self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
1680 if self.is_empty() {
1681 return Some(List::empty());
1683 if tcx.interners.arena.in_arena(*self as *const _) {
1684 Some(unsafe { mem::transmute(*self) })
1693 nop_lift!{Ty<'a> => Ty<'tcx>}
1694 nop_lift!{Region<'a> => Region<'tcx>}
1695 nop_lift!{Goal<'a> => Goal<'tcx>}
1696 nop_lift!{&'a Const<'a> => &'tcx Const<'tcx>}
1698 nop_list_lift!{Goal<'a> => Goal<'tcx>}
1699 nop_list_lift!{Clause<'a> => Clause<'tcx>}
1700 nop_list_lift!{Ty<'a> => Ty<'tcx>}
1701 nop_list_lift!{ExistentialPredicate<'a> => ExistentialPredicate<'tcx>}
1702 nop_list_lift!{Predicate<'a> => Predicate<'tcx>}
1703 nop_list_lift!{CanonicalVarInfo => CanonicalVarInfo}
1704 nop_list_lift!{ProjectionKind => ProjectionKind}
1706 // This is the impl for `&'a InternalSubsts<'a>`.
1707 nop_list_lift!{GenericArg<'a> => GenericArg<'tcx>}
1710 use super::{GlobalCtxt, TyCtxt, ptr_eq};
1715 use crate::ty::query;
1716 use errors::{Diagnostic, TRACK_DIAGNOSTICS};
1717 use rustc_data_structures::OnDrop;
1718 use rustc_data_structures::sync::{self, Lrc, Lock};
1719 use rustc_data_structures::thin_vec::ThinVec;
1720 use crate::dep_graph::TaskDeps;
1722 #[cfg(not(parallel_compiler))]
1723 use std::cell::Cell;
1725 #[cfg(parallel_compiler)]
1726 use rustc_rayon_core as rayon_core;
1728 /// This is the implicit state of rustc. It contains the current
1729 /// `TyCtxt` and query. It is updated when creating a local interner or
1730 /// executing a new query. Whenever there's a `TyCtxt` value available
1731 /// you should also have access to an `ImplicitCtxt` through the functions
1734 pub struct ImplicitCtxt<'a, 'tcx> {
1735 /// The current `TyCtxt`. Initially created by `enter_global` and updated
1736 /// by `enter_local` with a new local interner.
1737 pub tcx: TyCtxt<'tcx>,
1739 /// The current query job, if any. This is updated by `JobOwner::start` in
1740 /// `ty::query::plumbing` when executing a query.
1741 pub query: Option<Lrc<query::QueryJob<'tcx>>>,
1743 /// Where to store diagnostics for the current query job, if any.
1744 /// This is updated by `JobOwner::start` in `ty::query::plumbing` when executing a query.
1745 pub diagnostics: Option<&'a Lock<ThinVec<Diagnostic>>>,
1747 /// Used to prevent layout from recursing too deeply.
1748 pub layout_depth: usize,
1750 /// The current dep graph task. This is used to add dependencies to queries
1751 /// when executing them.
1752 pub task_deps: Option<&'a Lock<TaskDeps>>,
1755 /// Sets Rayon's thread-local variable, which is preserved for Rayon jobs
1756 /// to `value` during the call to `f`. It is restored to its previous value after.
1757 /// This is used to set the pointer to the new `ImplicitCtxt`.
1758 #[cfg(parallel_compiler)]
1760 fn set_tlv<F: FnOnce() -> R, R>(value: usize, f: F) -> R {
1761 rayon_core::tlv::with(value, f)
1764 /// Gets Rayon's thread-local variable, which is preserved for Rayon jobs.
1765 /// This is used to get the pointer to the current `ImplicitCtxt`.
1766 #[cfg(parallel_compiler)]
1768 fn get_tlv() -> usize {
1769 rayon_core::tlv::get()
1772 #[cfg(not(parallel_compiler))]
1774 /// A thread local variable that stores a pointer to the current `ImplicitCtxt`.
1775 static TLV: Cell<usize> = Cell::new(0);
1778 /// Sets TLV to `value` during the call to `f`.
1779 /// It is restored to its previous value after.
1780 /// This is used to set the pointer to the new `ImplicitCtxt`.
1781 #[cfg(not(parallel_compiler))]
1783 fn set_tlv<F: FnOnce() -> R, R>(value: usize, f: F) -> R {
1784 let old = get_tlv();
1785 let _reset = OnDrop(move || TLV.with(|tlv| tlv.set(old)));
1786 TLV.with(|tlv| tlv.set(value));
1790 /// Gets the pointer to the current `ImplicitCtxt`.
1791 #[cfg(not(parallel_compiler))]
1792 fn get_tlv() -> usize {
1793 TLV.with(|tlv| tlv.get())
1796 /// This is a callback from libsyntax as it cannot access the implicit state
1797 /// in librustc otherwise.
1798 fn span_debug(span: syntax_pos::Span, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1800 if let Some(tcx) = tcx {
1801 write!(f, "{}", tcx.sess.source_map().span_to_string(span))
1803 syntax_pos::default_span_debug(span, f)
1808 /// This is a callback from libsyntax as it cannot access the implicit state
1809 /// in librustc otherwise. It is used to when diagnostic messages are
1810 /// emitted and stores them in the current query, if there is one.
1811 fn track_diagnostic(diagnostic: &Diagnostic) {
1812 with_context_opt(|icx| {
1813 if let Some(icx) = icx {
1814 if let Some(ref diagnostics) = icx.diagnostics {
1815 let mut diagnostics = diagnostics.lock();
1816 diagnostics.extend(Some(diagnostic.clone()));
1822 /// Sets up the callbacks from libsyntax on the current thread.
1823 pub fn with_thread_locals<F, R>(f: F) -> R
1824 where F: FnOnce() -> R
1826 syntax_pos::SPAN_DEBUG.with(|span_dbg| {
1827 let original_span_debug = span_dbg.get();
1828 span_dbg.set(span_debug);
1830 let _on_drop = OnDrop(move || {
1831 span_dbg.set(original_span_debug);
1834 TRACK_DIAGNOSTICS.with(|current| {
1835 let original = current.get();
1836 current.set(track_diagnostic);
1838 let _on_drop = OnDrop(move || {
1839 current.set(original);
1847 /// Sets `context` as the new current `ImplicitCtxt` for the duration of the function `f`.
1849 pub fn enter_context<'a, 'tcx, F, R>(context: &ImplicitCtxt<'a, 'tcx>, f: F) -> R
1851 F: FnOnce(&ImplicitCtxt<'a, 'tcx>) -> R,
1853 set_tlv(context as *const _ as usize, || {
1858 /// Enters `GlobalCtxt` by setting up libsyntax callbacks and
1859 /// creating a initial `TyCtxt` and `ImplicitCtxt`.
1860 /// This happens once per rustc session and `TyCtxt`s only exists
1861 /// inside the `f` function.
1862 pub fn enter_global<'tcx, F, R>(gcx: &'tcx GlobalCtxt<'tcx>, f: F) -> R
1864 F: FnOnce(TyCtxt<'tcx>) -> R,
1866 // Update `GCX_PTR` to indicate there's a `GlobalCtxt` available.
1867 GCX_PTR.with(|lock| {
1868 *lock.lock() = gcx as *const _ as usize;
1870 // Set `GCX_PTR` back to 0 when we exit.
1871 let _on_drop = OnDrop(move || {
1872 GCX_PTR.with(|lock| *lock.lock() = 0);
1878 let icx = ImplicitCtxt {
1885 enter_context(&icx, |_| {
1890 scoped_thread_local! {
1891 /// Stores a pointer to the `GlobalCtxt` if one is available.
1892 /// This is used to access the `GlobalCtxt` in the deadlock handler given to Rayon.
1893 pub static GCX_PTR: Lock<usize>
1896 /// Creates a `TyCtxt` and `ImplicitCtxt` based on the `GCX_PTR` thread local.
1897 /// This is used in the deadlock handler.
1898 pub unsafe fn with_global<F, R>(f: F) -> R
1900 F: for<'tcx> FnOnce(TyCtxt<'tcx>) -> R,
1902 let gcx = GCX_PTR.with(|lock| *lock.lock());
1904 let gcx = &*(gcx as *const GlobalCtxt<'_>);
1908 let icx = ImplicitCtxt {
1915 enter_context(&icx, |_| f(tcx))
1918 /// Allows access to the current `ImplicitCtxt` in a closure if one is available.
1920 pub fn with_context_opt<F, R>(f: F) -> R
1922 F: for<'a, 'tcx> FnOnce(Option<&ImplicitCtxt<'a, 'tcx>>) -> R,
1924 let context = get_tlv();
1928 // We could get a `ImplicitCtxt` pointer from another thread.
1929 // Ensure that `ImplicitCtxt` is `Sync`.
1930 sync::assert_sync::<ImplicitCtxt<'_, '_>>();
1932 unsafe { f(Some(&*(context as *const ImplicitCtxt<'_, '_>))) }
1936 /// Allows access to the current `ImplicitCtxt`.
1937 /// Panics if there is no `ImplicitCtxt` available.
1939 pub fn with_context<F, R>(f: F) -> R
1941 F: for<'a, 'tcx> FnOnce(&ImplicitCtxt<'a, 'tcx>) -> R,
1943 with_context_opt(|opt_context| f(opt_context.expect("no ImplicitCtxt stored in tls")))
1946 /// Allows access to the current `ImplicitCtxt` whose tcx field has the same global
1947 /// interner as the tcx argument passed in. This means the closure is given an `ImplicitCtxt`
1948 /// with the same `'tcx` lifetime as the `TyCtxt` passed in.
1949 /// This will panic if you pass it a `TyCtxt` which has a different global interner from
1950 /// the current `ImplicitCtxt`'s `tcx` field.
1952 pub fn with_related_context<'tcx, F, R>(tcx: TyCtxt<'tcx>, f: F) -> R
1954 F: FnOnce(&ImplicitCtxt<'_, 'tcx>) -> R,
1956 with_context(|context| {
1958 assert!(ptr_eq(context.tcx.gcx, tcx.gcx));
1959 let context: &ImplicitCtxt<'_, '_> = mem::transmute(context);
1965 /// Allows access to the `TyCtxt` in the current `ImplicitCtxt`.
1966 /// Panics if there is no `ImplicitCtxt` available.
1968 pub fn with<F, R>(f: F) -> R
1970 F: for<'tcx> FnOnce(TyCtxt<'tcx>) -> R,
1972 with_context(|context| f(context.tcx))
1975 /// Allows access to the `TyCtxt` in the current `ImplicitCtxt`.
1976 /// The closure is passed None if there is no `ImplicitCtxt` available.
1978 pub fn with_opt<F, R>(f: F) -> R
1980 F: for<'tcx> FnOnce(Option<TyCtxt<'tcx>>) -> R,
1982 with_context_opt(|opt_context| f(opt_context.map(|context| context.tcx)))
1986 macro_rules! sty_debug_print {
1987 ($ctxt: expr, $($variant: ident),*) => {{
1988 // Curious inner module to allow variant names to be used as
1990 #[allow(non_snake_case)]
1992 use crate::ty::{self, TyCtxt};
1993 use crate::ty::context::Interned;
1995 #[derive(Copy, Clone)]
2004 pub fn go(tcx: TyCtxt<'_>) {
2005 let mut total = DebugStat {
2012 $(let mut $variant = total;)*
2014 let shards = tcx.interners.type_.lock_shards();
2015 let types = shards.iter().flat_map(|shard| shard.keys());
2016 for &Interned(t) in types {
2017 let variant = match t.kind {
2018 ty::Bool | ty::Char | ty::Int(..) | ty::Uint(..) |
2019 ty::Float(..) | ty::Str | ty::Never => continue,
2020 ty::Error => /* unimportant */ continue,
2021 $(ty::$variant(..) => &mut $variant,)*
2023 let lt = t.flags.intersects(ty::TypeFlags::HAS_RE_INFER);
2024 let ty = t.flags.intersects(ty::TypeFlags::HAS_TY_INFER);
2025 let ct = t.flags.intersects(ty::TypeFlags::HAS_CT_INFER);
2029 if lt { total.lt_infer += 1; variant.lt_infer += 1 }
2030 if ty { total.ty_infer += 1; variant.ty_infer += 1 }
2031 if ct { total.ct_infer += 1; variant.ct_infer += 1 }
2032 if lt && ty && ct { total.all_infer += 1; variant.all_infer += 1 }
2034 println!("Ty interner total ty lt ct all");
2035 $(println!(" {:18}: {uses:6} {usespc:4.1}%, \
2036 {ty:4.1}% {lt:5.1}% {ct:4.1}% {all:4.1}%",
2037 stringify!($variant),
2038 uses = $variant.total,
2039 usespc = $variant.total as f64 * 100.0 / total.total as f64,
2040 ty = $variant.ty_infer as f64 * 100.0 / total.total as f64,
2041 lt = $variant.lt_infer as f64 * 100.0 / total.total as f64,
2042 ct = $variant.ct_infer as f64 * 100.0 / total.total as f64,
2043 all = $variant.all_infer as f64 * 100.0 / total.total as f64);
2045 println!(" total {uses:6} \
2046 {ty:4.1}% {lt:5.1}% {ct:4.1}% {all:4.1}%",
2048 ty = total.ty_infer as f64 * 100.0 / total.total as f64,
2049 lt = total.lt_infer as f64 * 100.0 / total.total as f64,
2050 ct = total.ct_infer as f64 * 100.0 / total.total as f64,
2051 all = total.all_infer as f64 * 100.0 / total.total as f64)
2059 impl<'tcx> TyCtxt<'tcx> {
2060 pub fn print_debug_stats(self) {
2063 Adt, Array, Slice, RawPtr, Ref, FnDef, FnPtr, Placeholder,
2064 Generator, GeneratorWitness, Dynamic, Closure, Tuple, Bound,
2065 Param, Infer, UnnormalizedProjection, Projection, Opaque, Foreign);
2067 println!("InternalSubsts interner: #{}", self.interners.substs.len());
2068 println!("Region interner: #{}", self.interners.region.len());
2069 println!("Stability interner: #{}", self.stability_interner.len());
2070 println!("Allocation interner: #{}", self.allocation_interner.len());
2071 println!("Layout interner: #{}", self.layout_interner.len());
2076 /// An entry in an interner.
2077 struct Interned<'tcx, T: ?Sized>(&'tcx T);
2079 impl<'tcx, T: 'tcx+?Sized> Clone for Interned<'tcx, T> {
2080 fn clone(&self) -> Self {
2084 impl<'tcx, T: 'tcx+?Sized> Copy for Interned<'tcx, T> {}
2086 // N.B., an `Interned<Ty>` compares and hashes as a `TyKind`.
2087 impl<'tcx> PartialEq for Interned<'tcx, TyS<'tcx>> {
2088 fn eq(&self, other: &Interned<'tcx, TyS<'tcx>>) -> bool {
2089 self.0.kind == other.0.kind
2093 impl<'tcx> Eq for Interned<'tcx, TyS<'tcx>> {}
2095 impl<'tcx> Hash for Interned<'tcx, TyS<'tcx>> {
2096 fn hash<H: Hasher>(&self, s: &mut H) {
2101 #[allow(rustc::usage_of_ty_tykind)]
2102 impl<'tcx> Borrow<TyKind<'tcx>> for Interned<'tcx, TyS<'tcx>> {
2103 fn borrow<'a>(&'a self) -> &'a TyKind<'tcx> {
2108 // N.B., an `Interned<List<T>>` compares and hashes as its elements.
2109 impl<'tcx, T: PartialEq> PartialEq for Interned<'tcx, List<T>> {
2110 fn eq(&self, other: &Interned<'tcx, List<T>>) -> bool {
2111 self.0[..] == other.0[..]
2115 impl<'tcx, T: Eq> Eq for Interned<'tcx, List<T>> {}
2117 impl<'tcx, T: Hash> Hash for Interned<'tcx, List<T>> {
2118 fn hash<H: Hasher>(&self, s: &mut H) {
2123 impl<'tcx> Borrow<[Ty<'tcx>]> for Interned<'tcx, List<Ty<'tcx>>> {
2124 fn borrow<'a>(&'a self) -> &'a [Ty<'tcx>] {
2129 impl<'tcx> Borrow<[CanonicalVarInfo]> for Interned<'tcx, List<CanonicalVarInfo>> {
2130 fn borrow(&self) -> &[CanonicalVarInfo] {
2135 impl<'tcx> Borrow<[GenericArg<'tcx>]> for Interned<'tcx, InternalSubsts<'tcx>> {
2136 fn borrow<'a>(&'a self) -> &'a [GenericArg<'tcx>] {
2141 impl<'tcx> Borrow<[ProjectionKind]>
2142 for Interned<'tcx, List<ProjectionKind>> {
2143 fn borrow(&self) -> &[ProjectionKind] {
2148 impl<'tcx> Borrow<RegionKind> for Interned<'tcx, RegionKind> {
2149 fn borrow(&self) -> &RegionKind {
2154 impl<'tcx> Borrow<GoalKind<'tcx>> for Interned<'tcx, GoalKind<'tcx>> {
2155 fn borrow<'a>(&'a self) -> &'a GoalKind<'tcx> {
2160 impl<'tcx> Borrow<[ExistentialPredicate<'tcx>]>
2161 for Interned<'tcx, List<ExistentialPredicate<'tcx>>>
2163 fn borrow<'a>(&'a self) -> &'a [ExistentialPredicate<'tcx>] {
2168 impl<'tcx> Borrow<[Predicate<'tcx>]> for Interned<'tcx, List<Predicate<'tcx>>> {
2169 fn borrow<'a>(&'a self) -> &'a [Predicate<'tcx>] {
2174 impl<'tcx> Borrow<Const<'tcx>> for Interned<'tcx, Const<'tcx>> {
2175 fn borrow<'a>(&'a self) -> &'a Const<'tcx> {
2180 impl<'tcx> Borrow<[Clause<'tcx>]> for Interned<'tcx, List<Clause<'tcx>>> {
2181 fn borrow<'a>(&'a self) -> &'a [Clause<'tcx>] {
2186 impl<'tcx> Borrow<[Goal<'tcx>]> for Interned<'tcx, List<Goal<'tcx>>> {
2187 fn borrow<'a>(&'a self) -> &'a [Goal<'tcx>] {
2192 macro_rules! intern_method {
2193 ($lt_tcx:tt, $name:ident: $method:ident($alloc:ty,
2195 $alloc_to_key:expr) -> $ty:ty) => {
2196 impl<$lt_tcx> TyCtxt<$lt_tcx> {
2197 pub fn $method(self, v: $alloc) -> &$lt_tcx $ty {
2198 let key = ($alloc_to_key)(&v);
2200 self.interners.$name.intern_ref(key, || {
2201 Interned($alloc_method(&self.interners.arena, v))
2209 macro_rules! direct_interners {
2210 ($lt_tcx:tt, $($name:ident: $method:ident($ty:ty)),+) => {
2211 $(impl<$lt_tcx> PartialEq for Interned<$lt_tcx, $ty> {
2212 fn eq(&self, other: &Self) -> bool {
2217 impl<$lt_tcx> Eq for Interned<$lt_tcx, $ty> {}
2219 impl<$lt_tcx> Hash for Interned<$lt_tcx, $ty> {
2220 fn hash<H: Hasher>(&self, s: &mut H) {
2228 |a: &$lt_tcx SyncDroplessArena, v| -> &$lt_tcx $ty { a.alloc(v) },
2233 pub fn keep_local<'tcx, T: ty::TypeFoldable<'tcx>>(x: &T) -> bool {
2234 x.has_type_flags(ty::TypeFlags::KEEP_IN_LOCAL_TCX)
2237 direct_interners!('tcx,
2238 region: mk_region(RegionKind),
2239 goal: mk_goal(GoalKind<'tcx>),
2240 const_: mk_const(Const<'tcx>)
2243 macro_rules! slice_interners {
2244 ($($field:ident: $method:ident($ty:ty)),+) => (
2245 $(intern_method!( 'tcx, $field: $method(
2247 |a, v| List::from_arena(a, v),
2248 Deref::deref) -> List<$ty>);)+
2253 existential_predicates: _intern_existential_predicates(ExistentialPredicate<'tcx>),
2254 predicates: _intern_predicates(Predicate<'tcx>),
2255 type_list: _intern_type_list(Ty<'tcx>),
2256 substs: _intern_substs(GenericArg<'tcx>),
2257 clauses: _intern_clauses(Clause<'tcx>),
2258 goal_list: _intern_goals(Goal<'tcx>),
2259 projs: _intern_projs(ProjectionKind)
2262 // This isn't a perfect fit: `CanonicalVarInfo` slices are always
2263 // allocated in the global arena, so this `intern_method!` macro is
2264 // overly general. However, we just return `false` for the code that checks
2265 // whether they belong in the thread-local arena, so no harm done, and
2266 // seems better than open-coding the rest.
2269 canonical_var_infos: _intern_canonical_var_infos(
2270 &[CanonicalVarInfo],
2271 |a, v| List::from_arena(a, v),
2273 ) -> List<CanonicalVarInfo>
2276 impl<'tcx> TyCtxt<'tcx> {
2277 /// Given a `fn` type, returns an equivalent `unsafe fn` type;
2278 /// that is, a `fn` type that is equivalent in every way for being
2280 pub fn safe_to_unsafe_fn_ty(self, sig: PolyFnSig<'tcx>) -> Ty<'tcx> {
2281 assert_eq!(sig.unsafety(), hir::Unsafety::Normal);
2282 self.mk_fn_ptr(sig.map_bound(|sig| ty::FnSig {
2283 unsafety: hir::Unsafety::Unsafe,
2288 /// Given a closure signature `sig`, returns an equivalent `fn`
2289 /// type with the same signature. Detuples and so forth -- so
2290 /// e.g., if we have a sig with `Fn<(u32, i32)>` then you would get
2291 /// a `fn(u32, i32)`.
2292 /// `unsafety` determines the unsafety of the `fn` type. If you pass
2293 /// `hir::Unsafety::Unsafe` in the previous example, then you would get
2294 /// an `unsafe fn (u32, i32)`.
2295 /// It cannot convert a closure that requires unsafe.
2296 pub fn coerce_closure_fn_ty(self, sig: PolyFnSig<'tcx>, unsafety: hir::Unsafety) -> Ty<'tcx> {
2297 let converted_sig = sig.map_bound(|s| {
2298 let params_iter = match s.inputs()[0].kind {
2299 ty::Tuple(params) => {
2300 params.into_iter().map(|k| k.expect_ty())
2313 self.mk_fn_ptr(converted_sig)
2316 #[allow(rustc::usage_of_ty_tykind)]
2318 pub fn mk_ty(&self, st: TyKind<'tcx>) -> Ty<'tcx> {
2319 self.interners.intern_ty(st)
2322 pub fn mk_mach_int(self, tm: ast::IntTy) -> Ty<'tcx> {
2324 ast::IntTy::Isize => self.types.isize,
2325 ast::IntTy::I8 => self.types.i8,
2326 ast::IntTy::I16 => self.types.i16,
2327 ast::IntTy::I32 => self.types.i32,
2328 ast::IntTy::I64 => self.types.i64,
2329 ast::IntTy::I128 => self.types.i128,
2333 pub fn mk_mach_uint(self, tm: ast::UintTy) -> Ty<'tcx> {
2335 ast::UintTy::Usize => self.types.usize,
2336 ast::UintTy::U8 => self.types.u8,
2337 ast::UintTy::U16 => self.types.u16,
2338 ast::UintTy::U32 => self.types.u32,
2339 ast::UintTy::U64 => self.types.u64,
2340 ast::UintTy::U128 => self.types.u128,
2344 pub fn mk_mach_float(self, tm: ast::FloatTy) -> Ty<'tcx> {
2346 ast::FloatTy::F32 => self.types.f32,
2347 ast::FloatTy::F64 => self.types.f64,
2352 pub fn mk_str(self) -> Ty<'tcx> {
2357 pub fn mk_static_str(self) -> Ty<'tcx> {
2358 self.mk_imm_ref(self.lifetimes.re_static, self.mk_str())
2362 pub fn mk_adt(self, def: &'tcx AdtDef, substs: SubstsRef<'tcx>) -> Ty<'tcx> {
2363 // Take a copy of substs so that we own the vectors inside.
2364 self.mk_ty(Adt(def, substs))
2368 pub fn mk_foreign(self, def_id: DefId) -> Ty<'tcx> {
2369 self.mk_ty(Foreign(def_id))
2372 fn mk_generic_adt(self, wrapper_def_id: DefId, ty_param: Ty<'tcx>) -> Ty<'tcx> {
2373 let adt_def = self.adt_def(wrapper_def_id);
2374 let substs = InternalSubsts::for_item(self, wrapper_def_id, |param, substs| {
2376 GenericParamDefKind::Lifetime |
2377 GenericParamDefKind::Const => {
2380 GenericParamDefKind::Type { has_default, .. } => {
2381 if param.index == 0 {
2384 assert!(has_default);
2385 self.type_of(param.def_id).subst(self, substs).into()
2390 self.mk_ty(Adt(adt_def, substs))
2394 pub fn mk_box(self, ty: Ty<'tcx>) -> Ty<'tcx> {
2395 let def_id = self.require_lang_item(lang_items::OwnedBoxLangItem, None);
2396 self.mk_generic_adt(def_id, ty)
2400 pub fn mk_lang_item(self, ty: Ty<'tcx>, item: lang_items::LangItem) -> Option<Ty<'tcx>> {
2401 let def_id = self.lang_items().require(item).ok()?;
2402 Some(self.mk_generic_adt(def_id, ty))
2406 pub fn mk_maybe_uninit(self, ty: Ty<'tcx>) -> Ty<'tcx> {
2407 let def_id = self.require_lang_item(lang_items::MaybeUninitLangItem, None);
2408 self.mk_generic_adt(def_id, ty)
2412 pub fn mk_ptr(self, tm: TypeAndMut<'tcx>) -> Ty<'tcx> {
2413 self.mk_ty(RawPtr(tm))
2417 pub fn mk_ref(self, r: Region<'tcx>, tm: TypeAndMut<'tcx>) -> Ty<'tcx> {
2418 self.mk_ty(Ref(r, tm.ty, tm.mutbl))
2422 pub fn mk_mut_ref(self, r: Region<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
2423 self.mk_ref(r, TypeAndMut {ty: ty, mutbl: hir::MutMutable})
2427 pub fn mk_imm_ref(self, r: Region<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
2428 self.mk_ref(r, TypeAndMut {ty: ty, mutbl: hir::MutImmutable})
2432 pub fn mk_mut_ptr(self, ty: Ty<'tcx>) -> Ty<'tcx> {
2433 self.mk_ptr(TypeAndMut {ty: ty, mutbl: hir::MutMutable})
2437 pub fn mk_imm_ptr(self, ty: Ty<'tcx>) -> Ty<'tcx> {
2438 self.mk_ptr(TypeAndMut {ty: ty, mutbl: hir::MutImmutable})
2442 pub fn mk_nil_ptr(self) -> Ty<'tcx> {
2443 self.mk_imm_ptr(self.mk_unit())
2447 pub fn mk_array(self, ty: Ty<'tcx>, n: u64) -> Ty<'tcx> {
2448 self.mk_ty(Array(ty, ty::Const::from_usize(self, n)))
2452 pub fn mk_slice(self, ty: Ty<'tcx>) -> Ty<'tcx> {
2453 self.mk_ty(Slice(ty))
2457 pub fn intern_tup(self, ts: &[Ty<'tcx>]) -> Ty<'tcx> {
2458 let kinds: Vec<_> = ts.into_iter().map(|&t| GenericArg::from(t)).collect();
2459 self.mk_ty(Tuple(self.intern_substs(&kinds)))
2462 pub fn mk_tup<I: InternAs<[Ty<'tcx>], Ty<'tcx>>>(self, iter: I) -> I::Output {
2463 iter.intern_with(|ts| {
2464 let kinds: Vec<_> = ts.into_iter().map(|&t| GenericArg::from(t)).collect();
2465 self.mk_ty(Tuple(self.intern_substs(&kinds)))
2470 pub fn mk_unit(self) -> Ty<'tcx> {
2475 pub fn mk_diverging_default(self) -> Ty<'tcx> {
2476 if self.features().never_type {
2479 self.intern_tup(&[])
2484 pub fn mk_bool(self) -> Ty<'tcx> {
2489 pub fn mk_fn_def(self, def_id: DefId,
2490 substs: SubstsRef<'tcx>) -> Ty<'tcx> {
2491 self.mk_ty(FnDef(def_id, substs))
2495 pub fn mk_fn_ptr(self, fty: PolyFnSig<'tcx>) -> Ty<'tcx> {
2496 self.mk_ty(FnPtr(fty))
2502 obj: ty::Binder<&'tcx List<ExistentialPredicate<'tcx>>>,
2503 reg: ty::Region<'tcx>
2505 self.mk_ty(Dynamic(obj, reg))
2509 pub fn mk_projection(self,
2511 substs: SubstsRef<'tcx>)
2513 self.mk_ty(Projection(ProjectionTy {
2520 pub fn mk_closure(self, closure_id: DefId, closure_substs: ClosureSubsts<'tcx>)
2522 self.mk_ty(Closure(closure_id, closure_substs))
2526 pub fn mk_generator(self,
2528 generator_substs: GeneratorSubsts<'tcx>,
2529 movability: hir::GeneratorMovability)
2531 self.mk_ty(Generator(id, generator_substs, movability))
2535 pub fn mk_generator_witness(self, types: ty::Binder<&'tcx List<Ty<'tcx>>>) -> Ty<'tcx> {
2536 self.mk_ty(GeneratorWitness(types))
2540 pub fn mk_ty_var(self, v: TyVid) -> Ty<'tcx> {
2541 self.mk_ty_infer(TyVar(v))
2545 pub fn mk_const_var(self, v: ConstVid<'tcx>, ty: Ty<'tcx>) -> &'tcx Const<'tcx> {
2546 self.mk_const(ty::Const {
2547 val: ConstValue::Infer(InferConst::Var(v)),
2553 pub fn mk_int_var(self, v: IntVid) -> Ty<'tcx> {
2554 self.mk_ty_infer(IntVar(v))
2558 pub fn mk_float_var(self, v: FloatVid) -> Ty<'tcx> {
2559 self.mk_ty_infer(FloatVar(v))
2563 pub fn mk_ty_infer(self, it: InferTy) -> Ty<'tcx> {
2564 self.mk_ty(Infer(it))
2568 pub fn mk_const_infer(
2570 ic: InferConst<'tcx>,
2572 ) -> &'tcx ty::Const<'tcx> {
2573 self.mk_const(ty::Const {
2574 val: ConstValue::Infer(ic),
2580 pub fn mk_ty_param(self, index: u32, name: InternedString) -> Ty<'tcx> {
2581 self.mk_ty(Param(ParamTy { index, name: name }))
2585 pub fn mk_const_param(
2588 name: InternedString,
2590 ) -> &'tcx Const<'tcx> {
2591 self.mk_const(ty::Const {
2592 val: ConstValue::Param(ParamConst { index, name }),
2598 pub fn mk_param_from_def(self, param: &ty::GenericParamDef) -> GenericArg<'tcx> {
2600 GenericParamDefKind::Lifetime => {
2601 self.mk_region(ty::ReEarlyBound(param.to_early_bound_region_data())).into()
2603 GenericParamDefKind::Type { .. } => self.mk_ty_param(param.index, param.name).into(),
2604 GenericParamDefKind::Const => {
2605 self.mk_const_param(param.index, param.name, self.type_of(param.def_id)).into()
2611 pub fn mk_opaque(self, def_id: DefId, substs: SubstsRef<'tcx>) -> Ty<'tcx> {
2612 self.mk_ty(Opaque(def_id, substs))
2615 pub fn intern_existential_predicates(self, eps: &[ExistentialPredicate<'tcx>])
2616 -> &'tcx List<ExistentialPredicate<'tcx>> {
2617 assert!(!eps.is_empty());
2618 assert!(eps.windows(2).all(|w| w[0].stable_cmp(self, &w[1]) != Ordering::Greater));
2619 self._intern_existential_predicates(eps)
2622 pub fn intern_predicates(self, preds: &[Predicate<'tcx>])
2623 -> &'tcx List<Predicate<'tcx>> {
2624 // FIXME consider asking the input slice to be sorted to avoid
2625 // re-interning permutations, in which case that would be asserted
2627 if preds.len() == 0 {
2628 // The macro-generated method below asserts we don't intern an empty slice.
2631 self._intern_predicates(preds)
2635 pub fn intern_type_list(self, ts: &[Ty<'tcx>]) -> &'tcx List<Ty<'tcx>> {
2639 self._intern_type_list(ts)
2643 pub fn intern_substs(self, ts: &[GenericArg<'tcx>]) -> &'tcx List<GenericArg<'tcx>> {
2647 self._intern_substs(ts)
2651 pub fn intern_projs(self, ps: &[ProjectionKind]) -> &'tcx List<ProjectionKind> {
2655 self._intern_projs(ps)
2659 pub fn intern_canonical_var_infos(self, ts: &[CanonicalVarInfo]) -> CanonicalVarInfos<'tcx> {
2663 self._intern_canonical_var_infos(ts)
2667 pub fn intern_clauses(self, ts: &[Clause<'tcx>]) -> Clauses<'tcx> {
2671 self._intern_clauses(ts)
2675 pub fn intern_goals(self, ts: &[Goal<'tcx>]) -> Goals<'tcx> {
2679 self._intern_goals(ts)
2683 pub fn mk_fn_sig<I>(self,
2687 unsafety: hir::Unsafety,
2689 -> <I::Item as InternIteratorElement<Ty<'tcx>, ty::FnSig<'tcx>>>::Output
2691 I: Iterator<Item: InternIteratorElement<Ty<'tcx>, ty::FnSig<'tcx>>>,
2693 inputs.chain(iter::once(output)).intern_with(|xs| ty::FnSig {
2694 inputs_and_output: self.intern_type_list(xs),
2695 c_variadic, unsafety, abi
2699 pub fn mk_existential_predicates<I: InternAs<[ExistentialPredicate<'tcx>],
2700 &'tcx List<ExistentialPredicate<'tcx>>>>(self, iter: I)
2702 iter.intern_with(|xs| self.intern_existential_predicates(xs))
2705 pub fn mk_predicates<I: InternAs<[Predicate<'tcx>],
2706 &'tcx List<Predicate<'tcx>>>>(self, iter: I)
2708 iter.intern_with(|xs| self.intern_predicates(xs))
2711 pub fn mk_type_list<I: InternAs<[Ty<'tcx>],
2712 &'tcx List<Ty<'tcx>>>>(self, iter: I) -> I::Output {
2713 iter.intern_with(|xs| self.intern_type_list(xs))
2716 pub fn mk_substs<I: InternAs<[GenericArg<'tcx>],
2717 &'tcx List<GenericArg<'tcx>>>>(self, iter: I) -> I::Output {
2718 iter.intern_with(|xs| self.intern_substs(xs))
2721 pub fn mk_substs_trait(self,
2723 rest: &[GenericArg<'tcx>])
2726 self.mk_substs(iter::once(self_ty.into()).chain(rest.iter().cloned()))
2729 pub fn mk_clauses<I: InternAs<[Clause<'tcx>], Clauses<'tcx>>>(self, iter: I) -> I::Output {
2730 iter.intern_with(|xs| self.intern_clauses(xs))
2733 pub fn mk_goals<I: InternAs<[Goal<'tcx>], Goals<'tcx>>>(self, iter: I) -> I::Output {
2734 iter.intern_with(|xs| self.intern_goals(xs))
2737 pub fn lint_hir<S: Into<MultiSpan>>(self,
2738 lint: &'static Lint,
2742 self.struct_span_lint_hir(lint, hir_id, span.into(), msg).emit()
2745 pub fn lint_hir_note<S: Into<MultiSpan>>(self,
2746 lint: &'static Lint,
2751 let mut err = self.struct_span_lint_hir(lint, hir_id, span.into(), msg);
2756 pub fn lint_node_note<S: Into<MultiSpan>>(self,
2757 lint: &'static Lint,
2762 let mut err = self.struct_span_lint_hir(lint, id, span.into(), msg);
2767 /// Walks upwards from `id` to find a node which might change lint levels with attributes.
2768 /// It stops at `bound` and just returns it if reached.
2769 pub fn maybe_lint_level_root_bounded(
2778 if lint::maybe_lint_level_root(self, id) {
2781 let next = self.hir().get_parent_node(id);
2783 bug!("lint traversal reached the root of the crate");
2789 pub fn lint_level_at_node(
2791 lint: &'static Lint,
2793 ) -> (lint::Level, lint::LintSource) {
2794 let sets = self.lint_levels(LOCAL_CRATE);
2796 if let Some(pair) = sets.level_and_source(lint, id, self.sess) {
2799 let next = self.hir().get_parent_node(id);
2801 bug!("lint traversal reached the root of the crate");
2807 pub fn struct_span_lint_hir<S: Into<MultiSpan>>(self,
2808 lint: &'static Lint,
2812 -> DiagnosticBuilder<'tcx>
2814 let (level, src) = self.lint_level_at_node(lint, hir_id);
2815 lint::struct_lint_level(self.sess, lint, level, src, Some(span.into()), msg)
2818 pub fn struct_lint_node(self, lint: &'static Lint, id: HirId, msg: &str)
2819 -> DiagnosticBuilder<'tcx>
2821 let (level, src) = self.lint_level_at_node(lint, id);
2822 lint::struct_lint_level(self.sess, lint, level, src, None, msg)
2825 pub fn in_scope_traits(self, id: HirId) -> Option<&'tcx StableVec<TraitCandidate>> {
2826 self.in_scope_traits_map(id.owner)
2827 .and_then(|map| map.get(&id.local_id))
2830 pub fn named_region(self, id: HirId) -> Option<resolve_lifetime::Region> {
2831 self.named_region_map(id.owner)
2832 .and_then(|map| map.get(&id.local_id).cloned())
2835 pub fn is_late_bound(self, id: HirId) -> bool {
2836 self.is_late_bound_map(id.owner)
2837 .map(|set| set.contains(&id.local_id))
2841 pub fn object_lifetime_defaults(self, id: HirId) -> Option<&'tcx [ObjectLifetimeDefault]> {
2842 self.object_lifetime_defaults_map(id.owner)
2843 .and_then(|map| map.get(&id.local_id).map(|v| &**v))
2847 pub trait InternAs<T: ?Sized, R> {
2849 fn intern_with<F>(self, f: F) -> Self::Output
2850 where F: FnOnce(&T) -> R;
2853 impl<I, T, R, E> InternAs<[T], R> for I
2854 where E: InternIteratorElement<T, R>,
2855 I: Iterator<Item=E> {
2856 type Output = E::Output;
2857 fn intern_with<F>(self, f: F) -> Self::Output
2858 where F: FnOnce(&[T]) -> R {
2859 E::intern_with(self, f)
2863 pub trait InternIteratorElement<T, R>: Sized {
2865 fn intern_with<I: Iterator<Item=Self>, F: FnOnce(&[T]) -> R>(iter: I, f: F) -> Self::Output;
2868 impl<T, R> InternIteratorElement<T, R> for T {
2870 fn intern_with<I: Iterator<Item=Self>, F: FnOnce(&[T]) -> R>(iter: I, f: F) -> Self::Output {
2871 f(&iter.collect::<SmallVec<[_; 8]>>())
2875 impl<'a, T, R> InternIteratorElement<T, R> for &'a T
2879 fn intern_with<I: Iterator<Item=Self>, F: FnOnce(&[T]) -> R>(iter: I, f: F) -> Self::Output {
2880 f(&iter.cloned().collect::<SmallVec<[_; 8]>>())
2884 impl<T, R, E> InternIteratorElement<T, R> for Result<T, E> {
2885 type Output = Result<R, E>;
2886 fn intern_with<I: Iterator<Item=Self>, F: FnOnce(&[T]) -> R>(iter: I, f: F) -> Self::Output {
2887 Ok(f(&iter.collect::<Result<SmallVec<[_; 8]>, _>>()?))
2891 // We are comparing types with different invariant lifetimes, so `ptr::eq`
2892 // won't work for us.
2893 fn ptr_eq<T, U>(t: *const T, u: *const U) -> bool {
2894 t as *const () == u as *const ()
2897 pub fn provide(providers: &mut ty::query::Providers<'_>) {
2898 providers.in_scope_traits_map = |tcx, id| tcx.gcx.trait_map.get(&id);
2899 providers.module_exports = |tcx, id| tcx.gcx.export_map.get(&id).map(|v| &v[..]);
2900 providers.crate_name = |tcx, id| {
2901 assert_eq!(id, LOCAL_CRATE);
2904 providers.get_lib_features = |tcx, id| {
2905 assert_eq!(id, LOCAL_CRATE);
2906 tcx.arena.alloc(middle::lib_features::collect(tcx))
2908 providers.get_lang_items = |tcx, id| {
2909 assert_eq!(id, LOCAL_CRATE);
2910 tcx.arena.alloc(middle::lang_items::collect(tcx))
2912 providers.diagnostic_items = |tcx, id| {
2913 assert_eq!(id, LOCAL_CRATE);
2914 middle::diagnostic_items::collect(tcx)
2916 providers.all_diagnostic_items = |tcx, id| {
2917 assert_eq!(id, LOCAL_CRATE);
2918 middle::diagnostic_items::collect_all(tcx)
2920 providers.maybe_unused_trait_import = |tcx, id| {
2921 tcx.maybe_unused_trait_imports.contains(&id)
2923 providers.maybe_unused_extern_crates = |tcx, cnum| {
2924 assert_eq!(cnum, LOCAL_CRATE);
2925 &tcx.maybe_unused_extern_crates[..]
2927 providers.names_imported_by_glob_use = |tcx, id| {
2928 assert_eq!(id.krate, LOCAL_CRATE);
2929 Lrc::new(tcx.glob_map.get(&id).cloned().unwrap_or_default())
2932 providers.stability_index = |tcx, cnum| {
2933 assert_eq!(cnum, LOCAL_CRATE);
2934 tcx.arena.alloc(stability::Index::new(tcx))
2936 providers.lookup_stability = |tcx, id| {
2937 assert_eq!(id.krate, LOCAL_CRATE);
2938 let id = tcx.hir().definitions().def_index_to_hir_id(id.index);
2939 tcx.stability().local_stability(id)
2941 providers.lookup_deprecation_entry = |tcx, id| {
2942 assert_eq!(id.krate, LOCAL_CRATE);
2943 let id = tcx.hir().definitions().def_index_to_hir_id(id.index);
2944 tcx.stability().local_deprecation_entry(id)
2946 providers.extern_mod_stmt_cnum = |tcx, id| {
2947 let id = tcx.hir().as_local_node_id(id).unwrap();
2948 tcx.cstore.extern_mod_stmt_cnum_untracked(id)
2950 providers.all_crate_nums = |tcx, cnum| {
2951 assert_eq!(cnum, LOCAL_CRATE);
2952 tcx.arena.alloc_slice(&tcx.cstore.crates_untracked())
2954 providers.postorder_cnums = |tcx, cnum| {
2955 assert_eq!(cnum, LOCAL_CRATE);
2956 tcx.arena.alloc_slice(&tcx.cstore.postorder_cnums_untracked())
2958 providers.output_filenames = |tcx, cnum| {
2959 assert_eq!(cnum, LOCAL_CRATE);
2960 tcx.output_filenames.clone()
2962 providers.features_query = |tcx, cnum| {
2963 assert_eq!(cnum, LOCAL_CRATE);
2964 tcx.arena.alloc(tcx.sess.features_untracked().clone())
2966 providers.is_panic_runtime = |tcx, cnum| {
2967 assert_eq!(cnum, LOCAL_CRATE);
2968 attr::contains_name(tcx.hir().krate_attrs(), sym::panic_runtime)
2970 providers.is_compiler_builtins = |tcx, cnum| {
2971 assert_eq!(cnum, LOCAL_CRATE);
2972 attr::contains_name(tcx.hir().krate_attrs(), sym::compiler_builtins)