1 //! Type context book-keeping.
3 use crate::arena::Arena;
4 use crate::dep_graph::{DepGraph, DepKind, DepKindStruct};
5 use crate::hir::place::Place as HirPlace;
6 use crate::infer::canonical::{Canonical, CanonicalVarInfo, CanonicalVarInfos};
7 use crate::lint::{struct_lint_level, LintDiagnosticBuilder, LintLevelSource};
8 use crate::middle::resolve_lifetime::{self, LifetimeScopeForPath};
9 use crate::middle::stability;
10 use crate::mir::interpret::{self, Allocation, ConstValue, Scalar};
11 use crate::mir::{Body, Field, Local, Place, PlaceElem, ProjectionKind, Promoted};
12 use crate::thir::Thir;
14 use crate::ty::query::{self, TyCtxtAt};
15 use crate::ty::subst::{GenericArg, GenericArgKind, InternalSubsts, Subst, SubstsRef, UserSubsts};
16 use crate::ty::TyKind::*;
18 self, AdtDef, AdtKind, Binder, BindingMode, BoundVar, CanonicalPolyFnSig,
19 ClosureSizeProfileData, Const, ConstVid, DefIdTree, ExistentialPredicate, FloatTy, FloatVar,
20 FloatVid, GenericParamDefKind, InferConst, InferTy, IntTy, IntVar, IntVid, List, ParamConst,
21 ParamTy, PolyFnSig, Predicate, PredicateInner, PredicateKind, ProjectionTy, Region, RegionKind,
22 ReprOptions, TraitObjectVisitor, Ty, TyKind, TyS, TyVar, TyVid, TypeAndMut, UintTy,
25 use rustc_attr as attr;
26 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
27 use rustc_data_structures::memmap::Mmap;
28 use rustc_data_structures::profiling::SelfProfilerRef;
29 use rustc_data_structures::sharded::{IntoPointer, ShardedHashMap};
30 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
31 use rustc_data_structures::steal::Steal;
32 use rustc_data_structures::sync::{self, Lock, Lrc, WorkerLocal};
33 use rustc_data_structures::vec_map::VecMap;
34 use rustc_errors::ErrorReported;
36 use rustc_hir::def::{DefKind, Res};
37 use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, LocalDefId, LOCAL_CRATE};
38 use rustc_hir::intravisit::Visitor;
39 use rustc_hir::lang_items::LangItem;
41 Constness, ExprKind, HirId, ImplItemKind, ItemKind, ItemLocalId, ItemLocalMap, ItemLocalSet,
42 Node, TraitCandidate, TraitItemKind,
44 use rustc_index::vec::{Idx, IndexVec};
45 use rustc_macros::HashStable;
46 use rustc_middle::mir::FakeReadCause;
47 use rustc_query_system::ich::{NodeIdHashingMode, StableHashingContext};
48 use rustc_serialize::opaque::{FileEncodeResult, FileEncoder};
49 use rustc_session::config::{BorrowckMode, CrateType, OutputFilenames};
50 use rustc_session::lint::{Level, Lint};
51 use rustc_session::Limit;
52 use rustc_session::Session;
53 use rustc_span::def_id::{DefPathHash, StableCrateId};
54 use rustc_span::source_map::{MultiSpan, SourceMap};
55 use rustc_span::symbol::{kw, sym, Ident, Symbol};
56 use rustc_span::{Span, DUMMY_SP};
57 use rustc_target::abi::{Layout, TargetDataLayout, VariantIdx};
58 use rustc_target::spec::abi;
60 use smallvec::SmallVec;
62 use std::borrow::Borrow;
63 use std::cmp::Ordering;
64 use std::collections::hash_map::{self, Entry};
66 use std::hash::{Hash, Hasher};
69 use std::ops::{Bound, Deref};
72 pub trait OnDiskCache<'tcx>: rustc_data_structures::sync::Sync {
73 /// Creates a new `OnDiskCache` instance from the serialized data in `data`.
74 fn new(sess: &'tcx Session, data: Mmap, start_pos: usize) -> Self
78 fn new_empty(source_map: &'tcx SourceMap) -> Self
82 fn drop_serialized_data(&self, tcx: TyCtxt<'tcx>);
84 fn serialize(&self, tcx: TyCtxt<'tcx>, encoder: &mut FileEncoder) -> FileEncodeResult;
87 /// A type that is not publicly constructable. This prevents people from making [`TyKind::Error`]s
88 /// except through the error-reporting functions on a [`tcx`][TyCtxt].
89 #[derive(Copy, Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
90 #[derive(TyEncodable, TyDecodable, HashStable)]
91 pub struct DelaySpanBugEmitted(());
93 type InternedSet<'tcx, T> = ShardedHashMap<Interned<'tcx, T>, ()>;
95 pub struct CtxtInterners<'tcx> {
96 /// The arena that types, regions, etc. are allocated from.
97 arena: &'tcx WorkerLocal<Arena<'tcx>>,
99 // Specifically use a speedy hash algorithm for these hash sets, since
100 // they're accessed quite often.
101 type_: InternedSet<'tcx, TyS<'tcx>>,
102 type_list: InternedSet<'tcx, List<Ty<'tcx>>>,
103 substs: InternedSet<'tcx, InternalSubsts<'tcx>>,
104 canonical_var_infos: InternedSet<'tcx, List<CanonicalVarInfo<'tcx>>>,
105 region: InternedSet<'tcx, RegionKind>,
106 poly_existential_predicates:
107 InternedSet<'tcx, List<ty::Binder<'tcx, ExistentialPredicate<'tcx>>>>,
108 predicate: InternedSet<'tcx, PredicateInner<'tcx>>,
109 predicates: InternedSet<'tcx, List<Predicate<'tcx>>>,
110 projs: InternedSet<'tcx, List<ProjectionKind>>,
111 place_elems: InternedSet<'tcx, List<PlaceElem<'tcx>>>,
112 const_: InternedSet<'tcx, Const<'tcx>>,
113 const_allocation: InternedSet<'tcx, Allocation>,
114 bound_variable_kinds: InternedSet<'tcx, List<ty::BoundVariableKind>>,
115 layout: InternedSet<'tcx, Layout>,
116 adt_def: InternedSet<'tcx, AdtDef>,
118 /// `#[stable]` and `#[unstable]` attributes
119 stability: InternedSet<'tcx, attr::Stability>,
121 /// `#[rustc_const_stable]` and `#[rustc_const_unstable]` attributes
122 const_stability: InternedSet<'tcx, attr::ConstStability>,
125 impl<'tcx> CtxtInterners<'tcx> {
126 fn new(arena: &'tcx WorkerLocal<Arena<'tcx>>) -> CtxtInterners<'tcx> {
129 type_: Default::default(),
130 type_list: Default::default(),
131 substs: Default::default(),
132 region: Default::default(),
133 poly_existential_predicates: Default::default(),
134 canonical_var_infos: Default::default(),
135 predicate: Default::default(),
136 predicates: Default::default(),
137 projs: Default::default(),
138 place_elems: Default::default(),
139 const_: Default::default(),
140 const_allocation: Default::default(),
141 bound_variable_kinds: Default::default(),
142 layout: Default::default(),
143 adt_def: Default::default(),
144 stability: Default::default(),
145 const_stability: Default::default(),
150 #[allow(rustc::usage_of_ty_tykind)]
152 fn intern_ty(&self, kind: TyKind<'tcx>) -> Ty<'tcx> {
154 .intern(kind, |kind| {
155 let flags = super::flags::FlagComputation::for_kind(&kind);
157 let ty_struct = TyS {
160 outer_exclusive_binder: flags.outer_exclusive_binder,
163 Interned(self.arena.alloc(ty_struct))
171 kind: Binder<'tcx, PredicateKind<'tcx>>,
172 ) -> &'tcx PredicateInner<'tcx> {
174 .intern(kind, |kind| {
175 let flags = super::flags::FlagComputation::for_predicate(kind);
177 let predicate_struct = PredicateInner {
180 outer_exclusive_binder: flags.outer_exclusive_binder,
183 Interned(self.arena.alloc(predicate_struct))
189 pub struct CommonTypes<'tcx> {
209 pub self_param: Ty<'tcx>,
211 /// Dummy type used for the `Self` of a `TraitRef` created for converting
212 /// a trait object, and which gets removed in `ExistentialTraitRef`.
213 /// This type must not appear anywhere in other converted types.
214 pub trait_object_dummy_self: Ty<'tcx>,
217 pub struct CommonLifetimes<'tcx> {
218 /// `ReEmpty` in the root universe.
219 pub re_root_empty: Region<'tcx>,
222 pub re_static: Region<'tcx>,
224 /// Erased region, used outside of type inference.
225 pub re_erased: Region<'tcx>,
228 pub struct CommonConsts<'tcx> {
229 pub unit: &'tcx Const<'tcx>,
232 pub struct LocalTableInContext<'a, V> {
233 hir_owner: LocalDefId,
234 data: &'a ItemLocalMap<V>,
237 /// Validate that the given HirId (respectively its `local_id` part) can be
238 /// safely used as a key in the maps of a TypeckResults. For that to be
239 /// the case, the HirId must have the same `owner` as all the other IDs in
240 /// this table (signified by `hir_owner`). Otherwise the HirId
241 /// would be in a different frame of reference and using its `local_id`
242 /// would result in lookup errors, or worse, in silently wrong data being
245 fn validate_hir_id_for_typeck_results(hir_owner: LocalDefId, hir_id: hir::HirId) {
246 if hir_id.owner != hir_owner {
247 invalid_hir_id_for_typeck_results(hir_owner, hir_id);
253 fn invalid_hir_id_for_typeck_results(hir_owner: LocalDefId, hir_id: hir::HirId) {
254 ty::tls::with(|tcx| {
256 "node {} with HirId::owner {:?} cannot be placed in TypeckResults with hir_owner {:?}",
257 tcx.hir().node_to_string(hir_id),
264 impl<'a, V> LocalTableInContext<'a, V> {
265 pub fn contains_key(&self, id: hir::HirId) -> bool {
266 validate_hir_id_for_typeck_results(self.hir_owner, id);
267 self.data.contains_key(&id.local_id)
270 pub fn get(&self, id: hir::HirId) -> Option<&V> {
271 validate_hir_id_for_typeck_results(self.hir_owner, id);
272 self.data.get(&id.local_id)
275 pub fn iter(&self) -> hash_map::Iter<'_, hir::ItemLocalId, V> {
280 impl<'a, V> ::std::ops::Index<hir::HirId> for LocalTableInContext<'a, V> {
283 fn index(&self, key: hir::HirId) -> &V {
284 self.get(key).expect("LocalTableInContext: key not found")
288 pub struct LocalTableInContextMut<'a, V> {
289 hir_owner: LocalDefId,
290 data: &'a mut ItemLocalMap<V>,
293 impl<'a, V> LocalTableInContextMut<'a, V> {
294 pub fn get_mut(&mut self, id: hir::HirId) -> Option<&mut V> {
295 validate_hir_id_for_typeck_results(self.hir_owner, id);
296 self.data.get_mut(&id.local_id)
299 pub fn entry(&mut self, id: hir::HirId) -> Entry<'_, hir::ItemLocalId, V> {
300 validate_hir_id_for_typeck_results(self.hir_owner, id);
301 self.data.entry(id.local_id)
304 pub fn insert(&mut self, id: hir::HirId, val: V) -> Option<V> {
305 validate_hir_id_for_typeck_results(self.hir_owner, id);
306 self.data.insert(id.local_id, val)
309 pub fn remove(&mut self, id: hir::HirId) -> Option<V> {
310 validate_hir_id_for_typeck_results(self.hir_owner, id);
311 self.data.remove(&id.local_id)
315 /// Whenever a value may be live across a generator yield, the type of that value winds up in the
316 /// `GeneratorInteriorTypeCause` struct. This struct adds additional information about such
317 /// captured types that can be useful for diagnostics. In particular, it stores the span that
318 /// caused a given type to be recorded, along with the scope that enclosed the value (which can
319 /// be used to find the await that the value is live across).
323 /// ```ignore (pseudo-Rust)
331 /// Here, we would store the type `T`, the span of the value `x`, the "scope-span" for
332 /// the scope that contains `x`, the expr `T` evaluated from, and the span of `foo.await`.
333 #[derive(TyEncodable, TyDecodable, Clone, Debug, Eq, Hash, PartialEq, HashStable)]
334 #[derive(TypeFoldable)]
335 pub struct GeneratorInteriorTypeCause<'tcx> {
336 /// Type of the captured binding.
338 /// Span of the binding that was captured.
340 /// Span of the scope of the captured binding.
341 pub scope_span: Option<Span>,
342 /// Span of `.await` or `yield` expression.
343 pub yield_span: Span,
344 /// Expr which the type evaluated from.
345 pub expr: Option<hir::HirId>,
348 #[derive(TyEncodable, TyDecodable, Debug)]
349 pub struct TypeckResults<'tcx> {
350 /// The `HirId::owner` all `ItemLocalId`s in this table are relative to.
351 pub hir_owner: LocalDefId,
353 /// Resolved definitions for `<T>::X` associated paths and
354 /// method calls, including those of overloaded operators.
355 type_dependent_defs: ItemLocalMap<Result<(DefKind, DefId), ErrorReported>>,
357 /// Resolved field indices for field accesses in expressions (`S { field }`, `obj.field`)
358 /// or patterns (`S { field }`). The index is often useful by itself, but to learn more
359 /// about the field you also need definition of the variant to which the field
360 /// belongs, but it may not exist if it's a tuple field (`tuple.0`).
361 field_indices: ItemLocalMap<usize>,
363 /// Stores the types for various nodes in the AST. Note that this table
364 /// is not guaranteed to be populated outside inference. See
365 /// typeck::check::fn_ctxt for details.
366 node_types: ItemLocalMap<Ty<'tcx>>,
368 /// Stores the type parameters which were substituted to obtain the type
369 /// of this node. This only applies to nodes that refer to entities
370 /// parameterized by type parameters, such as generic fns, types, or
372 node_substs: ItemLocalMap<SubstsRef<'tcx>>,
374 /// This will either store the canonicalized types provided by the user
375 /// or the substitutions that the user explicitly gave (if any) attached
376 /// to `id`. These will not include any inferred values. The canonical form
377 /// is used to capture things like `_` or other unspecified values.
379 /// For example, if the user wrote `foo.collect::<Vec<_>>()`, then the
380 /// canonical substitutions would include only `for<X> { Vec<X> }`.
382 /// See also `AscribeUserType` statement in MIR.
383 user_provided_types: ItemLocalMap<CanonicalUserType<'tcx>>,
385 /// Stores the canonicalized types provided by the user. See also
386 /// `AscribeUserType` statement in MIR.
387 pub user_provided_sigs: DefIdMap<CanonicalPolyFnSig<'tcx>>,
389 adjustments: ItemLocalMap<Vec<ty::adjustment::Adjustment<'tcx>>>,
391 /// Stores the actual binding mode for all instances of hir::BindingAnnotation.
392 pat_binding_modes: ItemLocalMap<BindingMode>,
394 /// Stores the types which were implicitly dereferenced in pattern binding modes
395 /// for later usage in THIR lowering. For example,
398 /// match &&Some(5i32) {
403 /// leads to a `vec![&&Option<i32>, &Option<i32>]`. Empty vectors are not stored.
406 /// <https://github.com/rust-lang/rfcs/blob/master/text/2005-match-ergonomics.md#definitions>
407 pat_adjustments: ItemLocalMap<Vec<Ty<'tcx>>>,
409 /// Records the reasons that we picked the kind of each closure;
410 /// not all closures are present in the map.
411 closure_kind_origins: ItemLocalMap<(Span, HirPlace<'tcx>)>,
413 /// For each fn, records the "liberated" types of its arguments
414 /// and return type. Liberated means that all bound regions
415 /// (including late-bound regions) are replaced with free
416 /// equivalents. This table is not used in codegen (since regions
417 /// are erased there) and hence is not serialized to metadata.
419 /// This table also contains the "revealed" values for any `impl Trait`
420 /// that appear in the signature and whose values are being inferred
421 /// by this function.
426 /// fn foo(x: &u32) -> impl Debug { *x }
429 /// The function signature here would be:
432 /// for<'a> fn(&'a u32) -> Foo
435 /// where `Foo` is an opaque type created for this function.
438 /// The *liberated* form of this would be
441 /// fn(&'a u32) -> u32
444 /// Note that `'a` is not bound (it would be an `ReFree`) and
445 /// that the `Foo` opaque type is replaced by its hidden type.
446 liberated_fn_sigs: ItemLocalMap<ty::FnSig<'tcx>>,
448 /// For each FRU expression, record the normalized types of the fields
449 /// of the struct - this is needed because it is non-trivial to
450 /// normalize while preserving regions. This table is used only in
451 /// MIR construction and hence is not serialized to metadata.
452 fru_field_types: ItemLocalMap<Vec<Ty<'tcx>>>,
454 /// For every coercion cast we add the HIR node ID of the cast
455 /// expression to this set.
456 coercion_casts: ItemLocalSet,
458 /// Set of trait imports actually used in the method resolution.
459 /// This is used for warning unused imports. During type
460 /// checking, this `Lrc` should not be cloned: it must have a ref-count
461 /// of 1 so that we can insert things into the set mutably.
462 pub used_trait_imports: Lrc<FxHashSet<LocalDefId>>,
464 /// If any errors occurred while type-checking this body,
465 /// this field will be set to `Some(ErrorReported)`.
466 pub tainted_by_errors: Option<ErrorReported>,
468 /// All the opaque types that have hidden types set
469 /// by this function. For return-position-impl-trait we also store the
470 /// type here, so that mir-borrowck can figure out hidden types,
471 /// even if they are only set in dead code (which doesn't show up in MIR).
472 /// For type-alias-impl-trait, this map is only used to prevent query cycles,
473 /// so the hidden types are all `None`.
474 pub concrete_opaque_types: VecMap<DefId, Option<Ty<'tcx>>>,
476 /// Tracks the minimum captures required for a closure;
477 /// see `MinCaptureInformationMap` for more details.
478 pub closure_min_captures: ty::MinCaptureInformationMap<'tcx>,
480 /// Tracks the fake reads required for a closure and the reason for the fake read.
481 /// When performing pattern matching for closures, there are times we don't end up
482 /// reading places that are mentioned in a closure (because of _ patterns). However,
483 /// to ensure the places are initialized, we introduce fake reads.
484 /// Consider these two examples:
485 /// ``` (discriminant matching with only wildcard arm)
487 /// let c = || match x { _ => () };
489 /// In this example, we don't need to actually read/borrow `x` in `c`, and so we don't
490 /// want to capture it. However, we do still want an error here, because `x` should have
491 /// to be initialized at the point where c is created. Therefore, we add a "fake read"
493 /// ``` (destructured assignments)
495 /// let (t1, t2) = t;
498 /// In the second example, we capture the disjoint fields of `t` (`t.0` & `t.1`), but
499 /// we never capture `t`. This becomes an issue when we build MIR as we require
500 /// information on `t` in order to create place `t.0` and `t.1`. We can solve this
501 /// issue by fake reading `t`.
502 pub closure_fake_reads: FxHashMap<DefId, Vec<(HirPlace<'tcx>, FakeReadCause, hir::HirId)>>,
504 /// Stores the type, expression, span and optional scope span of all types
505 /// that are live across the yield of this generator (if a generator).
506 pub generator_interior_types: ty::Binder<'tcx, Vec<GeneratorInteriorTypeCause<'tcx>>>,
508 /// We sometimes treat byte string literals (which are of type `&[u8; N]`)
509 /// as `&[u8]`, depending on the pattern in which they are used.
510 /// This hashset records all instances where we behave
511 /// like this to allow `const_to_pat` to reliably handle this situation.
512 pub treat_byte_string_as_slice: ItemLocalSet,
514 /// Contains the data for evaluating the effect of feature `capture_disjoint_fields`
516 pub closure_size_eval: FxHashMap<DefId, ClosureSizeProfileData<'tcx>>,
519 impl<'tcx> TypeckResults<'tcx> {
520 pub fn new(hir_owner: LocalDefId) -> TypeckResults<'tcx> {
523 type_dependent_defs: Default::default(),
524 field_indices: Default::default(),
525 user_provided_types: Default::default(),
526 user_provided_sigs: Default::default(),
527 node_types: Default::default(),
528 node_substs: Default::default(),
529 adjustments: Default::default(),
530 pat_binding_modes: Default::default(),
531 pat_adjustments: Default::default(),
532 closure_kind_origins: Default::default(),
533 liberated_fn_sigs: Default::default(),
534 fru_field_types: Default::default(),
535 coercion_casts: Default::default(),
536 used_trait_imports: Lrc::new(Default::default()),
537 tainted_by_errors: None,
538 concrete_opaque_types: Default::default(),
539 closure_min_captures: Default::default(),
540 closure_fake_reads: Default::default(),
541 generator_interior_types: ty::Binder::dummy(Default::default()),
542 treat_byte_string_as_slice: Default::default(),
543 closure_size_eval: Default::default(),
547 /// Returns the final resolution of a `QPath` in an `Expr` or `Pat` node.
548 pub fn qpath_res(&self, qpath: &hir::QPath<'_>, id: hir::HirId) -> Res {
550 hir::QPath::Resolved(_, ref path) => path.res,
551 hir::QPath::TypeRelative(..) | hir::QPath::LangItem(..) => self
552 .type_dependent_def(id)
553 .map_or(Res::Err, |(kind, def_id)| Res::Def(kind, def_id)),
557 pub fn type_dependent_defs(
559 ) -> LocalTableInContext<'_, Result<(DefKind, DefId), ErrorReported>> {
560 LocalTableInContext { hir_owner: self.hir_owner, data: &self.type_dependent_defs }
563 pub fn type_dependent_def(&self, id: HirId) -> Option<(DefKind, DefId)> {
564 validate_hir_id_for_typeck_results(self.hir_owner, id);
565 self.type_dependent_defs.get(&id.local_id).cloned().and_then(|r| r.ok())
568 pub fn type_dependent_def_id(&self, id: HirId) -> Option<DefId> {
569 self.type_dependent_def(id).map(|(_, def_id)| def_id)
572 pub fn type_dependent_defs_mut(
574 ) -> LocalTableInContextMut<'_, Result<(DefKind, DefId), ErrorReported>> {
575 LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.type_dependent_defs }
578 pub fn field_indices(&self) -> LocalTableInContext<'_, usize> {
579 LocalTableInContext { hir_owner: self.hir_owner, data: &self.field_indices }
582 pub fn field_indices_mut(&mut self) -> LocalTableInContextMut<'_, usize> {
583 LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.field_indices }
586 pub fn user_provided_types(&self) -> LocalTableInContext<'_, CanonicalUserType<'tcx>> {
587 LocalTableInContext { hir_owner: self.hir_owner, data: &self.user_provided_types }
590 pub fn user_provided_types_mut(
592 ) -> LocalTableInContextMut<'_, CanonicalUserType<'tcx>> {
593 LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.user_provided_types }
596 pub fn node_types(&self) -> LocalTableInContext<'_, Ty<'tcx>> {
597 LocalTableInContext { hir_owner: self.hir_owner, data: &self.node_types }
600 pub fn node_types_mut(&mut self) -> LocalTableInContextMut<'_, Ty<'tcx>> {
601 LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.node_types }
604 pub fn node_type(&self, id: hir::HirId) -> Ty<'tcx> {
605 self.node_type_opt(id).unwrap_or_else(|| {
606 bug!("node_type: no type for node `{}`", tls::with(|tcx| tcx.hir().node_to_string(id)))
610 pub fn node_type_opt(&self, id: hir::HirId) -> Option<Ty<'tcx>> {
611 validate_hir_id_for_typeck_results(self.hir_owner, id);
612 self.node_types.get(&id.local_id).cloned()
615 pub fn node_substs_mut(&mut self) -> LocalTableInContextMut<'_, SubstsRef<'tcx>> {
616 LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.node_substs }
619 pub fn node_substs(&self, id: hir::HirId) -> SubstsRef<'tcx> {
620 validate_hir_id_for_typeck_results(self.hir_owner, id);
621 self.node_substs.get(&id.local_id).cloned().unwrap_or_else(|| InternalSubsts::empty())
624 pub fn node_substs_opt(&self, id: hir::HirId) -> Option<SubstsRef<'tcx>> {
625 validate_hir_id_for_typeck_results(self.hir_owner, id);
626 self.node_substs.get(&id.local_id).cloned()
629 // Returns the type of a pattern as a monotype. Like @expr_ty, this function
630 // doesn't provide type parameter substitutions.
631 pub fn pat_ty(&self, pat: &hir::Pat<'_>) -> Ty<'tcx> {
632 self.node_type(pat.hir_id)
635 // Returns the type of an expression as a monotype.
637 // NB (1): This is the PRE-ADJUSTMENT TYPE for the expression. That is, in
638 // some cases, we insert `Adjustment` annotations such as auto-deref or
639 // auto-ref. The type returned by this function does not consider such
640 // adjustments. See `expr_ty_adjusted()` instead.
642 // NB (2): This type doesn't provide type parameter substitutions; e.g., if you
643 // ask for the type of "id" in "id(3)", it will return "fn(&isize) -> isize"
644 // instead of "fn(ty) -> T with T = isize".
645 pub fn expr_ty(&self, expr: &hir::Expr<'_>) -> Ty<'tcx> {
646 self.node_type(expr.hir_id)
649 pub fn expr_ty_opt(&self, expr: &hir::Expr<'_>) -> Option<Ty<'tcx>> {
650 self.node_type_opt(expr.hir_id)
653 pub fn adjustments(&self) -> LocalTableInContext<'_, Vec<ty::adjustment::Adjustment<'tcx>>> {
654 LocalTableInContext { hir_owner: self.hir_owner, data: &self.adjustments }
657 pub fn adjustments_mut(
659 ) -> LocalTableInContextMut<'_, Vec<ty::adjustment::Adjustment<'tcx>>> {
660 LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.adjustments }
663 pub fn expr_adjustments(&self, expr: &hir::Expr<'_>) -> &[ty::adjustment::Adjustment<'tcx>] {
664 validate_hir_id_for_typeck_results(self.hir_owner, expr.hir_id);
665 self.adjustments.get(&expr.hir_id.local_id).map_or(&[], |a| &a[..])
668 /// Returns the type of `expr`, considering any `Adjustment`
669 /// entry recorded for that expression.
670 pub fn expr_ty_adjusted(&self, expr: &hir::Expr<'_>) -> Ty<'tcx> {
671 self.expr_adjustments(expr).last().map_or_else(|| self.expr_ty(expr), |adj| adj.target)
674 pub fn expr_ty_adjusted_opt(&self, expr: &hir::Expr<'_>) -> Option<Ty<'tcx>> {
675 self.expr_adjustments(expr).last().map(|adj| adj.target).or_else(|| self.expr_ty_opt(expr))
678 pub fn is_method_call(&self, expr: &hir::Expr<'_>) -> bool {
679 // Only paths and method calls/overloaded operators have
680 // entries in type_dependent_defs, ignore the former here.
681 if let hir::ExprKind::Path(_) = expr.kind {
685 matches!(self.type_dependent_defs().get(expr.hir_id), Some(Ok((DefKind::AssocFn, _))))
688 pub fn extract_binding_mode(&self, s: &Session, id: HirId, sp: Span) -> Option<BindingMode> {
689 self.pat_binding_modes().get(id).copied().or_else(|| {
690 s.delay_span_bug(sp, "missing binding mode");
695 pub fn pat_binding_modes(&self) -> LocalTableInContext<'_, BindingMode> {
696 LocalTableInContext { hir_owner: self.hir_owner, data: &self.pat_binding_modes }
699 pub fn pat_binding_modes_mut(&mut self) -> LocalTableInContextMut<'_, BindingMode> {
700 LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.pat_binding_modes }
703 pub fn pat_adjustments(&self) -> LocalTableInContext<'_, Vec<Ty<'tcx>>> {
704 LocalTableInContext { hir_owner: self.hir_owner, data: &self.pat_adjustments }
707 pub fn pat_adjustments_mut(&mut self) -> LocalTableInContextMut<'_, Vec<Ty<'tcx>>> {
708 LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.pat_adjustments }
711 /// For a given closure, returns the iterator of `ty::CapturedPlace`s that are captured
713 pub fn closure_min_captures_flattened(
715 closure_def_id: DefId,
716 ) -> impl Iterator<Item = &ty::CapturedPlace<'tcx>> {
717 self.closure_min_captures
718 .get(&closure_def_id)
719 .map(|closure_min_captures| closure_min_captures.values().flat_map(|v| v.iter()))
724 pub fn closure_kind_origins(&self) -> LocalTableInContext<'_, (Span, HirPlace<'tcx>)> {
725 LocalTableInContext { hir_owner: self.hir_owner, data: &self.closure_kind_origins }
728 pub fn closure_kind_origins_mut(
730 ) -> LocalTableInContextMut<'_, (Span, HirPlace<'tcx>)> {
731 LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.closure_kind_origins }
734 pub fn liberated_fn_sigs(&self) -> LocalTableInContext<'_, ty::FnSig<'tcx>> {
735 LocalTableInContext { hir_owner: self.hir_owner, data: &self.liberated_fn_sigs }
738 pub fn liberated_fn_sigs_mut(&mut self) -> LocalTableInContextMut<'_, ty::FnSig<'tcx>> {
739 LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.liberated_fn_sigs }
742 pub fn fru_field_types(&self) -> LocalTableInContext<'_, Vec<Ty<'tcx>>> {
743 LocalTableInContext { hir_owner: self.hir_owner, data: &self.fru_field_types }
746 pub fn fru_field_types_mut(&mut self) -> LocalTableInContextMut<'_, Vec<Ty<'tcx>>> {
747 LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.fru_field_types }
750 pub fn is_coercion_cast(&self, hir_id: hir::HirId) -> bool {
751 validate_hir_id_for_typeck_results(self.hir_owner, hir_id);
752 self.coercion_casts.contains(&hir_id.local_id)
755 pub fn set_coercion_cast(&mut self, id: ItemLocalId) {
756 self.coercion_casts.insert(id);
759 pub fn coercion_casts(&self) -> &ItemLocalSet {
764 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for TypeckResults<'tcx> {
765 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
766 let ty::TypeckResults {
768 ref type_dependent_defs,
770 ref user_provided_types,
771 ref user_provided_sigs,
775 ref pat_binding_modes,
777 ref closure_kind_origins,
778 ref liberated_fn_sigs,
781 ref used_trait_imports,
783 ref concrete_opaque_types,
784 ref closure_min_captures,
785 ref closure_fake_reads,
786 ref generator_interior_types,
787 ref treat_byte_string_as_slice,
788 ref closure_size_eval,
791 hcx.with_node_id_hashing_mode(NodeIdHashingMode::HashDefPath, |hcx| {
792 hcx.local_def_path_hash(hir_owner);
794 type_dependent_defs.hash_stable(hcx, hasher);
795 field_indices.hash_stable(hcx, hasher);
796 user_provided_types.hash_stable(hcx, hasher);
797 user_provided_sigs.hash_stable(hcx, hasher);
798 node_types.hash_stable(hcx, hasher);
799 node_substs.hash_stable(hcx, hasher);
800 adjustments.hash_stable(hcx, hasher);
801 pat_binding_modes.hash_stable(hcx, hasher);
802 pat_adjustments.hash_stable(hcx, hasher);
804 closure_kind_origins.hash_stable(hcx, hasher);
805 liberated_fn_sigs.hash_stable(hcx, hasher);
806 fru_field_types.hash_stable(hcx, hasher);
807 coercion_casts.hash_stable(hcx, hasher);
808 used_trait_imports.hash_stable(hcx, hasher);
809 tainted_by_errors.hash_stable(hcx, hasher);
810 concrete_opaque_types.hash_stable(hcx, hasher);
811 closure_min_captures.hash_stable(hcx, hasher);
812 closure_fake_reads.hash_stable(hcx, hasher);
813 generator_interior_types.hash_stable(hcx, hasher);
814 treat_byte_string_as_slice.hash_stable(hcx, hasher);
815 closure_size_eval.hash_stable(hcx, hasher);
820 rustc_index::newtype_index! {
821 pub struct UserTypeAnnotationIndex {
823 DEBUG_FORMAT = "UserType({})",
824 const START_INDEX = 0,
828 /// Mapping of type annotation indices to canonical user type annotations.
829 pub type CanonicalUserTypeAnnotations<'tcx> =
830 IndexVec<UserTypeAnnotationIndex, CanonicalUserTypeAnnotation<'tcx>>;
832 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
833 pub struct CanonicalUserTypeAnnotation<'tcx> {
834 pub user_ty: CanonicalUserType<'tcx>,
836 pub inferred_ty: Ty<'tcx>,
839 /// Canonicalized user type annotation.
840 pub type CanonicalUserType<'tcx> = Canonical<'tcx, UserType<'tcx>>;
842 impl<'tcx> CanonicalUserType<'tcx> {
843 /// Returns `true` if this represents a substitution of the form `[?0, ?1, ?2]`,
844 /// i.e., each thing is mapped to a canonical variable with the same index.
845 pub fn is_identity(&self) -> bool {
847 UserType::Ty(_) => false,
848 UserType::TypeOf(_, user_substs) => {
849 if user_substs.user_self_ty.is_some() {
853 iter::zip(user_substs.substs, BoundVar::new(0)..).all(|(kind, cvar)| {
854 match kind.unpack() {
855 GenericArgKind::Type(ty) => match ty.kind() {
856 ty::Bound(debruijn, b) => {
857 // We only allow a `ty::INNERMOST` index in substitutions.
858 assert_eq!(*debruijn, ty::INNERMOST);
864 GenericArgKind::Lifetime(r) => match r {
865 ty::ReLateBound(debruijn, br) => {
866 // We only allow a `ty::INNERMOST` index in substitutions.
867 assert_eq!(*debruijn, ty::INNERMOST);
873 GenericArgKind::Const(ct) => match ct.val {
874 ty::ConstKind::Bound(debruijn, b) => {
875 // We only allow a `ty::INNERMOST` index in substitutions.
876 assert_eq!(debruijn, ty::INNERMOST);
888 /// A user-given type annotation attached to a constant. These arise
889 /// from constants that are named via paths, like `Foo::<A>::new` and
891 #[derive(Copy, Clone, Debug, PartialEq, TyEncodable, TyDecodable)]
892 #[derive(HashStable, TypeFoldable, Lift)]
893 pub enum UserType<'tcx> {
896 /// The canonical type is the result of `type_of(def_id)` with the
897 /// given substitutions applied.
898 TypeOf(DefId, UserSubsts<'tcx>),
901 impl<'tcx> CommonTypes<'tcx> {
902 fn new(interners: &CtxtInterners<'tcx>) -> CommonTypes<'tcx> {
903 let mk = |ty| interners.intern_ty(ty);
906 unit: mk(Tuple(List::empty())),
910 isize: mk(Int(ty::IntTy::Isize)),
911 i8: mk(Int(ty::IntTy::I8)),
912 i16: mk(Int(ty::IntTy::I16)),
913 i32: mk(Int(ty::IntTy::I32)),
914 i64: mk(Int(ty::IntTy::I64)),
915 i128: mk(Int(ty::IntTy::I128)),
916 usize: mk(Uint(ty::UintTy::Usize)),
917 u8: mk(Uint(ty::UintTy::U8)),
918 u16: mk(Uint(ty::UintTy::U16)),
919 u32: mk(Uint(ty::UintTy::U32)),
920 u64: mk(Uint(ty::UintTy::U64)),
921 u128: mk(Uint(ty::UintTy::U128)),
922 f32: mk(Float(ty::FloatTy::F32)),
923 f64: mk(Float(ty::FloatTy::F64)),
925 self_param: mk(ty::Param(ty::ParamTy { index: 0, name: kw::SelfUpper })),
927 trait_object_dummy_self: mk(Infer(ty::FreshTy(0))),
932 impl<'tcx> CommonLifetimes<'tcx> {
933 fn new(interners: &CtxtInterners<'tcx>) -> CommonLifetimes<'tcx> {
934 let mk = |r| interners.region.intern(r, |r| Interned(interners.arena.alloc(r))).0;
937 re_root_empty: mk(RegionKind::ReEmpty(ty::UniverseIndex::ROOT)),
938 re_static: mk(RegionKind::ReStatic),
939 re_erased: mk(RegionKind::ReErased),
944 impl<'tcx> CommonConsts<'tcx> {
945 fn new(interners: &CtxtInterners<'tcx>, types: &CommonTypes<'tcx>) -> CommonConsts<'tcx> {
946 let mk_const = |c| interners.const_.intern(c, |c| Interned(interners.arena.alloc(c))).0;
949 unit: mk_const(ty::Const {
950 val: ty::ConstKind::Value(ConstValue::Scalar(Scalar::ZST)),
957 // This struct contains information regarding the `ReFree(FreeRegion)` corresponding to a lifetime
960 pub struct FreeRegionInfo {
961 // `LocalDefId` corresponding to FreeRegion
962 pub def_id: LocalDefId,
963 // the bound region corresponding to FreeRegion
964 pub boundregion: ty::BoundRegionKind,
965 // checks if bound region is in Impl Item
966 pub is_impl_item: bool,
969 /// The central data structure of the compiler. It stores references
970 /// to the various **arenas** and also houses the results of the
971 /// various **compiler queries** that have been performed. See the
972 /// [rustc dev guide] for more details.
974 /// [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/ty.html
975 #[derive(Copy, Clone)]
976 #[rustc_diagnostic_item = "TyCtxt"]
977 #[cfg_attr(not(bootstrap), rustc_pass_by_value)]
978 pub struct TyCtxt<'tcx> {
979 gcx: &'tcx GlobalCtxt<'tcx>,
982 impl<'tcx> Deref for TyCtxt<'tcx> {
983 type Target = &'tcx GlobalCtxt<'tcx>;
985 fn deref(&self) -> &Self::Target {
990 pub struct GlobalCtxt<'tcx> {
991 pub arena: &'tcx WorkerLocal<Arena<'tcx>>,
993 interners: CtxtInterners<'tcx>,
995 pub sess: &'tcx Session,
997 /// This only ever stores a `LintStore` but we don't want a dependency on that type here.
999 /// FIXME(Centril): consider `dyn LintStoreMarker` once
1000 /// we can upcast to `Any` for some additional type safety.
1001 pub lint_store: Lrc<dyn Any + sync::Sync + sync::Send>,
1003 pub dep_graph: DepGraph,
1005 pub prof: SelfProfilerRef,
1007 /// Common types, pre-interned for your convenience.
1008 pub types: CommonTypes<'tcx>,
1010 /// Common lifetimes, pre-interned for your convenience.
1011 pub lifetimes: CommonLifetimes<'tcx>,
1013 /// Common consts, pre-interned for your convenience.
1014 pub consts: CommonConsts<'tcx>,
1016 /// Output of the resolver.
1017 pub(crate) untracked_resolutions: ty::ResolverOutputs,
1019 pub(crate) untracked_crate: &'tcx hir::Crate<'tcx>,
1021 /// This provides access to the incremental compilation on-disk cache for query results.
1022 /// Do not access this directly. It is only meant to be used by
1023 /// `DepGraph::try_mark_green()` and the query infrastructure.
1024 /// This is `None` if we are not incremental compilation mode
1025 pub on_disk_cache: Option<&'tcx dyn OnDiskCache<'tcx>>,
1027 pub queries: &'tcx dyn query::QueryEngine<'tcx>,
1028 pub query_caches: query::QueryCaches<'tcx>,
1029 query_kinds: &'tcx [DepKindStruct],
1031 // Internal caches for metadata decoding. No need to track deps on this.
1032 pub ty_rcache: Lock<FxHashMap<ty::CReaderCacheKey, Ty<'tcx>>>,
1033 pub pred_rcache: Lock<FxHashMap<ty::CReaderCacheKey, Predicate<'tcx>>>,
1035 /// Caches the results of trait selection. This cache is used
1036 /// for things that do not have to do with the parameters in scope.
1037 pub selection_cache: traits::SelectionCache<'tcx>,
1039 /// Caches the results of trait evaluation. This cache is used
1040 /// for things that do not have to do with the parameters in scope.
1041 /// Merge this with `selection_cache`?
1042 pub evaluation_cache: traits::EvaluationCache<'tcx>,
1044 /// The definite name of the current crate after taking into account
1045 /// attributes, commandline parameters, etc.
1048 /// Data layout specification for the current target.
1049 pub data_layout: TargetDataLayout,
1051 /// Stores memory for globals (statics/consts).
1052 pub(crate) alloc_map: Lock<interpret::AllocMap<'tcx>>,
1054 output_filenames: Arc<OutputFilenames>,
1057 impl<'tcx> TyCtxt<'tcx> {
1058 pub fn typeck_opt_const_arg(
1060 def: ty::WithOptConstParam<LocalDefId>,
1061 ) -> &'tcx TypeckResults<'tcx> {
1062 if let Some(param_did) = def.const_param_did {
1063 self.typeck_const_arg((def.did, param_did))
1065 self.typeck(def.did)
1069 pub fn alloc_steal_thir(self, thir: Thir<'tcx>) -> &'tcx Steal<Thir<'tcx>> {
1070 self.arena.alloc(Steal::new(thir))
1073 pub fn alloc_steal_mir(self, mir: Body<'tcx>) -> &'tcx Steal<Body<'tcx>> {
1074 self.arena.alloc(Steal::new(mir))
1077 pub fn alloc_steal_promoted(
1079 promoted: IndexVec<Promoted, Body<'tcx>>,
1080 ) -> &'tcx Steal<IndexVec<Promoted, Body<'tcx>>> {
1081 self.arena.alloc(Steal::new(promoted))
1084 pub fn alloc_adt_def(
1088 variants: IndexVec<VariantIdx, ty::VariantDef>,
1090 ) -> &'tcx ty::AdtDef {
1091 self.intern_adt_def(ty::AdtDef::new(self, did, kind, variants, repr))
1094 /// Allocates a read-only byte or string literal for `mir::interpret`.
1095 pub fn allocate_bytes(self, bytes: &[u8]) -> interpret::AllocId {
1096 // Create an allocation that just contains these bytes.
1097 let alloc = interpret::Allocation::from_bytes_byte_aligned_immutable(bytes);
1098 let alloc = self.intern_const_alloc(alloc);
1099 self.create_memory_alloc(alloc)
1102 /// Returns a range of the start/end indices specified with the
1103 /// `rustc_layout_scalar_valid_range` attribute.
1104 // FIXME(eddyb) this is an awkward spot for this method, maybe move it?
1105 pub fn layout_scalar_valid_range(self, def_id: DefId) -> (Bound<u128>, Bound<u128>) {
1106 let attrs = self.get_attrs(def_id);
1108 let attr = match attrs.iter().find(|a| a.has_name(name)) {
1110 None => return Bound::Unbounded,
1112 debug!("layout_scalar_valid_range: attr={:?}", attr);
1115 ast::NestedMetaItem::Literal(ast::Lit {
1116 kind: ast::LitKind::Int(a, _), ..
1119 ) = attr.meta_item_list().as_deref()
1124 .delay_span_bug(attr.span, "invalid rustc_layout_scalar_valid_range attribute");
1129 get(sym::rustc_layout_scalar_valid_range_start),
1130 get(sym::rustc_layout_scalar_valid_range_end),
1134 pub fn lift<T: Lift<'tcx>>(self, value: T) -> Option<T::Lifted> {
1135 value.lift_to_tcx(self)
1138 /// Creates a type context and call the closure with a `TyCtxt` reference
1139 /// to the context. The closure enforces that the type context and any interned
1140 /// value (types, substs, etc.) can only be used while `ty::tls` has a valid
1141 /// reference to the context, to allow formatting values that need it.
1142 pub fn create_global_ctxt(
1144 lint_store: Lrc<dyn Any + sync::Send + sync::Sync>,
1145 arena: &'tcx WorkerLocal<Arena<'tcx>>,
1146 resolutions: ty::ResolverOutputs,
1147 krate: &'tcx hir::Crate<'tcx>,
1148 dep_graph: DepGraph,
1149 on_disk_cache: Option<&'tcx dyn OnDiskCache<'tcx>>,
1150 queries: &'tcx dyn query::QueryEngine<'tcx>,
1151 query_kinds: &'tcx [DepKindStruct],
1153 output_filenames: OutputFilenames,
1154 ) -> GlobalCtxt<'tcx> {
1155 let data_layout = TargetDataLayout::parse(&s.target).unwrap_or_else(|err| {
1158 let interners = CtxtInterners::new(arena);
1159 let common_types = CommonTypes::new(&interners);
1160 let common_lifetimes = CommonLifetimes::new(&interners);
1161 let common_consts = CommonConsts::new(&interners, &common_types);
1169 untracked_resolutions: resolutions,
1170 prof: s.prof.clone(),
1171 types: common_types,
1172 lifetimes: common_lifetimes,
1173 consts: common_consts,
1174 untracked_crate: krate,
1177 query_caches: query::QueryCaches::default(),
1179 ty_rcache: Default::default(),
1180 pred_rcache: Default::default(),
1181 selection_cache: Default::default(),
1182 evaluation_cache: Default::default(),
1183 crate_name: Symbol::intern(crate_name),
1185 alloc_map: Lock::new(interpret::AllocMap::new()),
1186 output_filenames: Arc::new(output_filenames),
1190 crate fn query_kind(self, k: DepKind) -> &'tcx DepKindStruct {
1191 &self.query_kinds[k as usize]
1194 /// Constructs a `TyKind::Error` type and registers a `delay_span_bug` to ensure it gets used.
1196 pub fn ty_error(self) -> Ty<'tcx> {
1197 self.ty_error_with_message(DUMMY_SP, "TyKind::Error constructed but no error reported")
1200 /// Constructs a `TyKind::Error` type and registers a `delay_span_bug` with the given `msg` to
1201 /// ensure it gets used.
1203 pub fn ty_error_with_message<S: Into<MultiSpan>>(self, span: S, msg: &str) -> Ty<'tcx> {
1204 self.sess.delay_span_bug(span, msg);
1205 self.mk_ty(Error(DelaySpanBugEmitted(())))
1208 /// Like [TyCtxt::ty_error] but for constants.
1210 pub fn const_error(self, ty: Ty<'tcx>) -> &'tcx Const<'tcx> {
1211 self.const_error_with_message(
1214 "ty::ConstKind::Error constructed but no error reported",
1218 /// Like [TyCtxt::ty_error_with_message] but for constants.
1220 pub fn const_error_with_message<S: Into<MultiSpan>>(
1225 ) -> &'tcx Const<'tcx> {
1226 self.sess.delay_span_bug(span, msg);
1227 self.mk_const(ty::Const { val: ty::ConstKind::Error(DelaySpanBugEmitted(())), ty })
1230 pub fn consider_optimizing<T: Fn() -> String>(self, msg: T) -> bool {
1231 let cname = self.crate_name(LOCAL_CRATE);
1232 self.sess.consider_optimizing(cname.as_str(), msg)
1235 /// Obtain all lang items of this crate and all dependencies (recursively)
1236 pub fn lang_items(self) -> &'tcx rustc_hir::lang_items::LanguageItems {
1237 self.get_lang_items(())
1240 /// Obtain the given diagnostic item's `DefId`. Use `is_diagnostic_item` if you just want to
1241 /// compare against another `DefId`, since `is_diagnostic_item` is cheaper.
1242 pub fn get_diagnostic_item(self, name: Symbol) -> Option<DefId> {
1243 self.all_diagnostic_items(()).name_to_id.get(&name).copied()
1246 /// Obtain the diagnostic item's name
1247 pub fn get_diagnostic_name(self, id: DefId) -> Option<Symbol> {
1248 self.diagnostic_items(id.krate).id_to_name.get(&id).copied()
1251 /// Check whether the diagnostic item with the given `name` has the given `DefId`.
1252 pub fn is_diagnostic_item(self, name: Symbol, did: DefId) -> bool {
1253 self.diagnostic_items(did.krate).name_to_id.get(&name) == Some(&did)
1256 pub fn stability(self) -> &'tcx stability::Index<'tcx> {
1257 self.stability_index(())
1260 pub fn features(self) -> &'tcx rustc_feature::Features {
1261 self.features_query(())
1264 pub fn def_key(self, id: DefId) -> rustc_hir::definitions::DefKey {
1265 // Accessing the DefKey is ok, since it is part of DefPathHash.
1266 if let Some(id) = id.as_local() {
1267 self.untracked_resolutions.definitions.def_key(id)
1269 self.untracked_resolutions.cstore.def_key(id)
1273 /// Converts a `DefId` into its fully expanded `DefPath` (every
1274 /// `DefId` is really just an interned `DefPath`).
1276 /// Note that if `id` is not local to this crate, the result will
1277 /// be a non-local `DefPath`.
1278 pub fn def_path(self, id: DefId) -> rustc_hir::definitions::DefPath {
1279 // Accessing the DefPath is ok, since it is part of DefPathHash.
1280 if let Some(id) = id.as_local() {
1281 self.untracked_resolutions.definitions.def_path(id)
1283 self.untracked_resolutions.cstore.def_path(id)
1288 pub fn def_path_hash(self, def_id: DefId) -> rustc_hir::definitions::DefPathHash {
1289 // Accessing the DefPathHash is ok, it is incr. comp. stable.
1290 if let Some(def_id) = def_id.as_local() {
1291 self.untracked_resolutions.definitions.def_path_hash(def_id)
1293 self.untracked_resolutions.cstore.def_path_hash(def_id)
1298 pub fn stable_crate_id(self, crate_num: CrateNum) -> StableCrateId {
1299 if crate_num == LOCAL_CRATE {
1300 self.sess.local_stable_crate_id()
1302 self.untracked_resolutions.cstore.stable_crate_id(crate_num)
1306 /// Maps a StableCrateId to the corresponding CrateNum. This method assumes
1307 /// that the crate in question has already been loaded by the CrateStore.
1309 pub fn stable_crate_id_to_crate_num(self, stable_crate_id: StableCrateId) -> CrateNum {
1310 if stable_crate_id == self.sess.local_stable_crate_id() {
1313 self.untracked_resolutions.cstore.stable_crate_id_to_crate_num(stable_crate_id)
1317 /// Converts a `DefPathHash` to its corresponding `DefId` in the current compilation
1318 /// session, if it still exists. This is used during incremental compilation to
1319 /// turn a deserialized `DefPathHash` into its current `DefId`.
1320 pub fn def_path_hash_to_def_id(self, hash: DefPathHash, err: &mut dyn FnMut() -> !) -> DefId {
1321 debug!("def_path_hash_to_def_id({:?})", hash);
1323 let stable_crate_id = hash.stable_crate_id();
1325 // If this is a DefPathHash from the local crate, we can look up the
1326 // DefId in the tcx's `Definitions`.
1327 if stable_crate_id == self.sess.local_stable_crate_id() {
1328 self.untracked_resolutions
1330 .local_def_path_hash_to_def_id(hash, err)
1333 // If this is a DefPathHash from an upstream crate, let the CrateStore map
1335 let cstore = &self.untracked_resolutions.cstore;
1336 let cnum = cstore.stable_crate_id_to_crate_num(stable_crate_id);
1337 cstore.def_path_hash_to_def_id(cnum, hash)
1341 pub fn def_path_debug_str(self, def_id: DefId) -> String {
1342 // We are explicitly not going through queries here in order to get
1343 // crate name and stable crate id since this code is called from debug!()
1344 // statements within the query system and we'd run into endless
1345 // recursion otherwise.
1346 let (crate_name, stable_crate_id) = if def_id.is_local() {
1347 (self.crate_name, self.sess.local_stable_crate_id())
1349 let cstore = &self.untracked_resolutions.cstore;
1350 (cstore.crate_name(def_id.krate), cstore.stable_crate_id(def_id.krate))
1356 // Don't print the whole stable crate id. That's just
1357 // annoying in debug output.
1358 &(format!("{:08x}", stable_crate_id.to_u64()))[..4],
1359 self.def_path(def_id).to_string_no_crate_verbose()
1363 /// Note that this is *untracked* and should only be used within the query
1364 /// system if the result is otherwise tracked through queries
1365 pub fn cstore_untracked(self) -> &'tcx ty::CrateStoreDyn {
1366 &*self.untracked_resolutions.cstore
1369 /// Note that this is *untracked* and should only be used within the query
1370 /// system if the result is otherwise tracked through queries
1371 pub fn definitions_untracked(self) -> &'tcx hir::definitions::Definitions {
1372 &self.untracked_resolutions.definitions
1376 pub fn create_stable_hashing_context(self) -> StableHashingContext<'tcx> {
1377 let resolutions = &self.gcx.untracked_resolutions;
1378 StableHashingContext::new(self.sess, &resolutions.definitions, &*resolutions.cstore)
1382 pub fn create_no_span_stable_hashing_context(self) -> StableHashingContext<'tcx> {
1383 let resolutions = &self.gcx.untracked_resolutions;
1384 StableHashingContext::ignore_spans(
1386 &resolutions.definitions,
1387 &*resolutions.cstore,
1391 pub fn serialize_query_result_cache(self, encoder: &mut FileEncoder) -> FileEncodeResult {
1392 self.on_disk_cache.as_ref().map_or(Ok(()), |c| c.serialize(self, encoder))
1395 /// If `true`, we should use the MIR-based borrowck, but also
1396 /// fall back on the AST borrowck if the MIR-based one errors.
1397 pub fn migrate_borrowck(self) -> bool {
1398 self.borrowck_mode().migrate()
1401 /// What mode(s) of borrowck should we run? AST? MIR? both?
1402 /// (Also considers the `#![feature(nll)]` setting.)
1403 pub fn borrowck_mode(self) -> BorrowckMode {
1404 // Here are the main constraints we need to deal with:
1406 // 1. An opts.borrowck_mode of `BorrowckMode::Migrate` is
1407 // synonymous with no `-Z borrowck=...` flag at all.
1409 // 2. We want to allow developers on the Nightly channel
1410 // to opt back into the "hard error" mode for NLL,
1411 // (which they can do via specifying `#![feature(nll)]`
1412 // explicitly in their crate).
1414 // So, this precedence list is how pnkfelix chose to work with
1415 // the above constraints:
1417 // * `#![feature(nll)]` *always* means use NLL with hard
1418 // errors. (To simplify the code here, it now even overrides
1419 // a user's attempt to specify `-Z borrowck=compare`, which
1420 // we arguably do not need anymore and should remove.)
1422 // * Otherwise, if no `-Z borrowck=...` then use migrate mode
1424 // * Otherwise, use the behavior requested via `-Z borrowck=...`
1426 if self.features().nll {
1427 return BorrowckMode::Mir;
1430 self.sess.opts.borrowck_mode
1433 /// If `true`, we should use lazy normalization for constants, otherwise
1434 /// we still evaluate them eagerly.
1436 pub fn lazy_normalization(self) -> bool {
1437 let features = self.features();
1438 // Note: We only use lazy normalization for generic const expressions.
1439 features.generic_const_exprs
1443 pub fn local_crate_exports_generics(self) -> bool {
1444 debug_assert!(self.sess.opts.share_generics());
1446 self.sess.crate_types().iter().any(|crate_type| {
1448 CrateType::Executable
1449 | CrateType::Staticlib
1450 | CrateType::ProcMacro
1451 | CrateType::Cdylib => false,
1453 // FIXME rust-lang/rust#64319, rust-lang/rust#64872:
1454 // We want to block export of generics from dylibs,
1455 // but we must fix rust-lang/rust#65890 before we can
1456 // do that robustly.
1457 CrateType::Dylib => true,
1459 CrateType::Rlib => true,
1464 // Returns the `DefId` and the `BoundRegionKind` corresponding to the given region.
1465 pub fn is_suitable_region(self, region: Region<'tcx>) -> Option<FreeRegionInfo> {
1466 let (suitable_region_binding_scope, bound_region) = match *region {
1467 ty::ReFree(ref free_region) => {
1468 (free_region.scope.expect_local(), free_region.bound_region)
1470 ty::ReEarlyBound(ref ebr) => (
1471 self.parent(ebr.def_id).unwrap().expect_local(),
1472 ty::BoundRegionKind::BrNamed(ebr.def_id, ebr.name),
1474 _ => return None, // not a free region
1477 let is_impl_item = match self.hir().find_by_def_id(suitable_region_binding_scope) {
1478 Some(Node::Item(..) | Node::TraitItem(..)) => false,
1479 Some(Node::ImplItem(..)) => {
1480 self.is_bound_region_in_impl_item(suitable_region_binding_scope)
1485 Some(FreeRegionInfo {
1486 def_id: suitable_region_binding_scope,
1487 boundregion: bound_region,
1492 /// Given a `DefId` for an `fn`, return all the `dyn` and `impl` traits in its return type.
1493 pub fn return_type_impl_or_dyn_traits(
1495 scope_def_id: LocalDefId,
1496 ) -> Vec<&'tcx hir::Ty<'tcx>> {
1497 let hir_id = self.hir().local_def_id_to_hir_id(scope_def_id);
1498 let hir_output = match self.hir().fn_decl_by_hir_id(hir_id) {
1499 Some(hir::FnDecl { output: hir::FnRetTy::Return(ty), .. }) => ty,
1503 let mut v = TraitObjectVisitor(vec![], self.hir());
1504 v.visit_ty(hir_output);
1508 pub fn return_type_impl_trait(self, scope_def_id: LocalDefId) -> Option<(Ty<'tcx>, Span)> {
1509 // `type_of()` will fail on these (#55796, #86483), so only allow `fn`s or closures.
1510 match self.hir().get_by_def_id(scope_def_id) {
1511 Node::Item(&hir::Item { kind: ItemKind::Fn(..), .. }) => {}
1512 Node::TraitItem(&hir::TraitItem { kind: TraitItemKind::Fn(..), .. }) => {}
1513 Node::ImplItem(&hir::ImplItem { kind: ImplItemKind::Fn(..), .. }) => {}
1514 Node::Expr(&hir::Expr { kind: ExprKind::Closure(..), .. }) => {}
1518 let ret_ty = self.type_of(scope_def_id);
1519 match ret_ty.kind() {
1520 ty::FnDef(_, _) => {
1521 let sig = ret_ty.fn_sig(self);
1522 let output = self.erase_late_bound_regions(sig.output());
1523 if output.is_impl_trait() {
1524 let hir_id = self.hir().local_def_id_to_hir_id(scope_def_id);
1525 let fn_decl = self.hir().fn_decl_by_hir_id(hir_id).unwrap();
1526 Some((output, fn_decl.output.span()))
1535 // Checks if the bound region is in Impl Item.
1536 pub fn is_bound_region_in_impl_item(self, suitable_region_binding_scope: LocalDefId) -> bool {
1538 self.associated_item(suitable_region_binding_scope.to_def_id()).container.id();
1539 if self.impl_trait_ref(container_id).is_some() {
1540 // For now, we do not try to target impls of traits. This is
1541 // because this message is going to suggest that the user
1542 // change the fn signature, but they may not be free to do so,
1543 // since the signature must match the trait.
1545 // FIXME(#42706) -- in some cases, we could do better here.
1551 /// Determines whether identifiers in the assembly have strict naming rules.
1552 /// Currently, only NVPTX* targets need it.
1553 pub fn has_strict_asm_symbol_naming(self) -> bool {
1554 self.sess.target.arch.contains("nvptx")
1557 /// Returns `&'static core::panic::Location<'static>`.
1558 pub fn caller_location_ty(self) -> Ty<'tcx> {
1560 self.lifetimes.re_static,
1561 self.type_of(self.require_lang_item(LangItem::PanicLocation, None))
1562 .subst(self, self.mk_substs([self.lifetimes.re_static.into()].iter())),
1566 /// Returns a displayable description and article for the given `def_id` (e.g. `("a", "struct")`).
1567 pub fn article_and_description(self, def_id: DefId) -> (&'static str, &'static str) {
1568 match self.def_kind(def_id) {
1569 DefKind::Generator => match self.generator_kind(def_id).unwrap() {
1570 rustc_hir::GeneratorKind::Async(..) => ("an", "async closure"),
1571 rustc_hir::GeneratorKind::Gen => ("a", "generator"),
1573 def_kind => (def_kind.article(), def_kind.descr(def_id)),
1577 pub fn type_length_limit(self) -> Limit {
1578 self.limits(()).type_length_limit
1581 pub fn recursion_limit(self) -> Limit {
1582 self.limits(()).recursion_limit
1585 pub fn move_size_limit(self) -> Limit {
1586 self.limits(()).move_size_limit
1589 pub fn const_eval_limit(self) -> Limit {
1590 self.limits(()).const_eval_limit
1593 pub fn all_traits(self) -> impl Iterator<Item = DefId> + 'tcx {
1594 iter::once(LOCAL_CRATE)
1595 .chain(self.crates(()).iter().copied())
1596 .flat_map(move |cnum| self.traits_in_crate(cnum).iter().copied())
1600 /// A trait implemented for all `X<'a>` types that can be safely and
1601 /// efficiently converted to `X<'tcx>` as long as they are part of the
1602 /// provided `TyCtxt<'tcx>`.
1603 /// This can be done, for example, for `Ty<'tcx>` or `SubstsRef<'tcx>`
1604 /// by looking them up in their respective interners.
1606 /// However, this is still not the best implementation as it does
1607 /// need to compare the components, even for interned values.
1608 /// It would be more efficient if `TypedArena` provided a way to
1609 /// determine whether the address is in the allocated range.
1611 /// `None` is returned if the value or one of the components is not part
1612 /// of the provided context.
1613 /// For `Ty`, `None` can be returned if either the type interner doesn't
1614 /// contain the `TyKind` key or if the address of the interned
1615 /// pointer differs. The latter case is possible if a primitive type,
1616 /// e.g., `()` or `u8`, was interned in a different context.
1617 pub trait Lift<'tcx>: fmt::Debug {
1618 type Lifted: fmt::Debug + 'tcx;
1619 fn lift_to_tcx(self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted>;
1622 macro_rules! nop_lift {
1623 ($set:ident; $ty:ty => $lifted:ty) => {
1624 impl<'a, 'tcx> Lift<'tcx> for $ty {
1625 type Lifted = $lifted;
1626 fn lift_to_tcx(self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
1627 if tcx.interners.$set.contains_pointer_to(&Interned(self)) {
1628 Some(unsafe { mem::transmute(self) })
1637 macro_rules! nop_list_lift {
1638 ($set:ident; $ty:ty => $lifted:ty) => {
1639 impl<'a, 'tcx> Lift<'tcx> for &'a List<$ty> {
1640 type Lifted = &'tcx List<$lifted>;
1641 fn lift_to_tcx(self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
1642 if self.is_empty() {
1643 return Some(List::empty());
1645 if tcx.interners.$set.contains_pointer_to(&Interned(self)) {
1646 Some(unsafe { mem::transmute(self) })
1655 nop_lift! {type_; Ty<'a> => Ty<'tcx>}
1656 nop_lift! {region; Region<'a> => Region<'tcx>}
1657 nop_lift! {const_; &'a Const<'a> => &'tcx Const<'tcx>}
1658 nop_lift! {const_allocation; &'a Allocation => &'tcx Allocation}
1659 nop_lift! {predicate; &'a PredicateInner<'a> => &'tcx PredicateInner<'tcx>}
1661 nop_list_lift! {type_list; Ty<'a> => Ty<'tcx>}
1662 nop_list_lift! {poly_existential_predicates; ty::Binder<'a, ExistentialPredicate<'a>> => ty::Binder<'tcx, ExistentialPredicate<'tcx>>}
1663 nop_list_lift! {predicates; Predicate<'a> => Predicate<'tcx>}
1664 nop_list_lift! {canonical_var_infos; CanonicalVarInfo<'a> => CanonicalVarInfo<'tcx>}
1665 nop_list_lift! {projs; ProjectionKind => ProjectionKind}
1666 nop_list_lift! {bound_variable_kinds; ty::BoundVariableKind => ty::BoundVariableKind}
1668 // This is the impl for `&'a InternalSubsts<'a>`.
1669 nop_list_lift! {substs; GenericArg<'a> => GenericArg<'tcx>}
1671 CloneLiftImpls! { for<'tcx> { Constness, traits::WellFormedLoc, } }
1674 use super::{ptr_eq, GlobalCtxt, TyCtxt};
1676 use crate::dep_graph::{DepKind, TaskDepsRef};
1677 use crate::ty::query;
1678 use rustc_data_structures::sync::{self, Lock};
1679 use rustc_data_structures::thin_vec::ThinVec;
1680 use rustc_errors::Diagnostic;
1683 #[cfg(not(parallel_compiler))]
1684 use std::cell::Cell;
1686 #[cfg(parallel_compiler)]
1687 use rustc_rayon_core as rayon_core;
1689 /// This is the implicit state of rustc. It contains the current
1690 /// `TyCtxt` and query. It is updated when creating a local interner or
1691 /// executing a new query. Whenever there's a `TyCtxt` value available
1692 /// you should also have access to an `ImplicitCtxt` through the functions
1695 pub struct ImplicitCtxt<'a, 'tcx> {
1696 /// The current `TyCtxt`.
1697 pub tcx: TyCtxt<'tcx>,
1699 /// The current query job, if any. This is updated by `JobOwner::start` in
1700 /// `ty::query::plumbing` when executing a query.
1701 pub query: Option<query::QueryJobId<DepKind>>,
1703 /// Where to store diagnostics for the current query job, if any.
1704 /// This is updated by `JobOwner::start` in `ty::query::plumbing` when executing a query.
1705 pub diagnostics: Option<&'a Lock<ThinVec<Diagnostic>>>,
1707 /// Used to prevent layout from recursing too deeply.
1708 pub layout_depth: usize,
1710 /// The current dep graph task. This is used to add dependencies to queries
1711 /// when executing them.
1712 pub task_deps: TaskDepsRef<'a>,
1715 impl<'a, 'tcx> ImplicitCtxt<'a, 'tcx> {
1716 pub fn new(gcx: &'tcx GlobalCtxt<'tcx>) -> Self {
1717 let tcx = TyCtxt { gcx };
1723 task_deps: TaskDepsRef::Ignore,
1728 /// Sets Rayon's thread-local variable, which is preserved for Rayon jobs
1729 /// to `value` during the call to `f`. It is restored to its previous value after.
1730 /// This is used to set the pointer to the new `ImplicitCtxt`.
1731 #[cfg(parallel_compiler)]
1733 fn set_tlv<F: FnOnce() -> R, R>(value: usize, f: F) -> R {
1734 rayon_core::tlv::with(value, f)
1737 /// Gets Rayon's thread-local variable, which is preserved for Rayon jobs.
1738 /// This is used to get the pointer to the current `ImplicitCtxt`.
1739 #[cfg(parallel_compiler)]
1741 pub fn get_tlv() -> usize {
1742 rayon_core::tlv::get()
1745 #[cfg(not(parallel_compiler))]
1747 /// A thread local variable that stores a pointer to the current `ImplicitCtxt`.
1748 static TLV: Cell<usize> = const { Cell::new(0) };
1751 /// Sets TLV to `value` during the call to `f`.
1752 /// It is restored to its previous value after.
1753 /// This is used to set the pointer to the new `ImplicitCtxt`.
1754 #[cfg(not(parallel_compiler))]
1756 fn set_tlv<F: FnOnce() -> R, R>(value: usize, f: F) -> R {
1757 let old = get_tlv();
1758 let _reset = rustc_data_structures::OnDrop(move || TLV.with(|tlv| tlv.set(old)));
1759 TLV.with(|tlv| tlv.set(value));
1763 /// Gets the pointer to the current `ImplicitCtxt`.
1764 #[cfg(not(parallel_compiler))]
1766 fn get_tlv() -> usize {
1767 TLV.with(|tlv| tlv.get())
1770 /// Sets `context` as the new current `ImplicitCtxt` for the duration of the function `f`.
1772 pub fn enter_context<'a, 'tcx, F, R>(context: &ImplicitCtxt<'a, 'tcx>, f: F) -> R
1774 F: FnOnce(&ImplicitCtxt<'a, 'tcx>) -> R,
1776 set_tlv(context as *const _ as usize, || f(&context))
1779 /// Allows access to the current `ImplicitCtxt` in a closure if one is available.
1781 pub fn with_context_opt<F, R>(f: F) -> R
1783 F: for<'a, 'tcx> FnOnce(Option<&ImplicitCtxt<'a, 'tcx>>) -> R,
1785 let context = get_tlv();
1789 // We could get an `ImplicitCtxt` pointer from another thread.
1790 // Ensure that `ImplicitCtxt` is `Sync`.
1791 sync::assert_sync::<ImplicitCtxt<'_, '_>>();
1793 unsafe { f(Some(&*(context as *const ImplicitCtxt<'_, '_>))) }
1797 /// Allows access to the current `ImplicitCtxt`.
1798 /// Panics if there is no `ImplicitCtxt` available.
1800 pub fn with_context<F, R>(f: F) -> R
1802 F: for<'a, 'tcx> FnOnce(&ImplicitCtxt<'a, 'tcx>) -> R,
1804 with_context_opt(|opt_context| f(opt_context.expect("no ImplicitCtxt stored in tls")))
1807 /// Allows access to the current `ImplicitCtxt` whose tcx field is the same as the tcx argument
1808 /// passed in. This means the closure is given an `ImplicitCtxt` with the same `'tcx` lifetime
1809 /// as the `TyCtxt` passed in.
1810 /// This will panic if you pass it a `TyCtxt` which is different from the current
1811 /// `ImplicitCtxt`'s `tcx` field.
1813 pub fn with_related_context<'tcx, F, R>(tcx: TyCtxt<'tcx>, f: F) -> R
1815 F: FnOnce(&ImplicitCtxt<'_, 'tcx>) -> R,
1817 with_context(|context| unsafe {
1818 assert!(ptr_eq(context.tcx.gcx, tcx.gcx));
1819 let context: &ImplicitCtxt<'_, '_> = mem::transmute(context);
1824 /// Allows access to the `TyCtxt` in the current `ImplicitCtxt`.
1825 /// Panics if there is no `ImplicitCtxt` available.
1827 pub fn with<F, R>(f: F) -> R
1829 F: for<'tcx> FnOnce(TyCtxt<'tcx>) -> R,
1831 with_context(|context| f(context.tcx))
1834 /// Allows access to the `TyCtxt` in the current `ImplicitCtxt`.
1835 /// The closure is passed None if there is no `ImplicitCtxt` available.
1837 pub fn with_opt<F, R>(f: F) -> R
1839 F: for<'tcx> FnOnce(Option<TyCtxt<'tcx>>) -> R,
1841 with_context_opt(|opt_context| f(opt_context.map(|context| context.tcx)))
1845 macro_rules! sty_debug_print {
1846 ($fmt: expr, $ctxt: expr, $($variant: ident),*) => {{
1847 // Curious inner module to allow variant names to be used as
1849 #[allow(non_snake_case)]
1851 use crate::ty::{self, TyCtxt};
1852 use crate::ty::context::Interned;
1854 #[derive(Copy, Clone)]
1863 pub fn go(fmt: &mut std::fmt::Formatter<'_>, tcx: TyCtxt<'_>) -> std::fmt::Result {
1864 let mut total = DebugStat {
1871 $(let mut $variant = total;)*
1873 let shards = tcx.interners.type_.lock_shards();
1874 let types = shards.iter().flat_map(|shard| shard.keys());
1875 for &Interned(t) in types {
1876 let variant = match t.kind() {
1877 ty::Bool | ty::Char | ty::Int(..) | ty::Uint(..) |
1878 ty::Float(..) | ty::Str | ty::Never => continue,
1879 ty::Error(_) => /* unimportant */ continue,
1880 $(ty::$variant(..) => &mut $variant,)*
1882 let lt = t.flags().intersects(ty::TypeFlags::HAS_RE_INFER);
1883 let ty = t.flags().intersects(ty::TypeFlags::HAS_TY_INFER);
1884 let ct = t.flags().intersects(ty::TypeFlags::HAS_CT_INFER);
1888 if lt { total.lt_infer += 1; variant.lt_infer += 1 }
1889 if ty { total.ty_infer += 1; variant.ty_infer += 1 }
1890 if ct { total.ct_infer += 1; variant.ct_infer += 1 }
1891 if lt && ty && ct { total.all_infer += 1; variant.all_infer += 1 }
1893 writeln!(fmt, "Ty interner total ty lt ct all")?;
1894 $(writeln!(fmt, " {:18}: {uses:6} {usespc:4.1}%, \
1895 {ty:4.1}% {lt:5.1}% {ct:4.1}% {all:4.1}%",
1896 stringify!($variant),
1897 uses = $variant.total,
1898 usespc = $variant.total as f64 * 100.0 / total.total as f64,
1899 ty = $variant.ty_infer as f64 * 100.0 / total.total as f64,
1900 lt = $variant.lt_infer as f64 * 100.0 / total.total as f64,
1901 ct = $variant.ct_infer as f64 * 100.0 / total.total as f64,
1902 all = $variant.all_infer as f64 * 100.0 / total.total as f64)?;
1904 writeln!(fmt, " total {uses:6} \
1905 {ty:4.1}% {lt:5.1}% {ct:4.1}% {all:4.1}%",
1907 ty = total.ty_infer as f64 * 100.0 / total.total as f64,
1908 lt = total.lt_infer as f64 * 100.0 / total.total as f64,
1909 ct = total.ct_infer as f64 * 100.0 / total.total as f64,
1910 all = total.all_infer as f64 * 100.0 / total.total as f64)
1914 inner::go($fmt, $ctxt)
1918 impl<'tcx> TyCtxt<'tcx> {
1919 pub fn debug_stats(self) -> impl std::fmt::Debug + 'tcx {
1920 struct DebugStats<'tcx>(TyCtxt<'tcx>);
1922 impl<'tcx> std::fmt::Debug for DebugStats<'tcx> {
1923 fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1948 writeln!(fmt, "InternalSubsts interner: #{}", self.0.interners.substs.len())?;
1949 writeln!(fmt, "Region interner: #{}", self.0.interners.region.len())?;
1950 writeln!(fmt, "Stability interner: #{}", self.0.interners.stability.len())?;
1953 "Const Stability interner: #{}",
1954 self.0.interners.const_stability.len()
1958 "Const Allocation interner: #{}",
1959 self.0.interners.const_allocation.len()
1961 writeln!(fmt, "Layout interner: #{}", self.0.interners.layout.len())?;
1971 // This type holds a `T` in the interner. The `T` is stored in the arena and
1972 // this type just holds a pointer to it, but it still effectively owns it. It
1973 // impls `Borrow` so that it can be looked up using the original
1974 // (non-arena-memory-owning) types.
1975 struct Interned<'tcx, T: ?Sized>(&'tcx T);
1977 impl<'tcx, T: 'tcx + ?Sized> Clone for Interned<'tcx, T> {
1978 fn clone(&self) -> Self {
1983 impl<'tcx, T: 'tcx + ?Sized> Copy for Interned<'tcx, T> {}
1985 impl<'tcx, T: 'tcx + ?Sized> IntoPointer for Interned<'tcx, T> {
1986 fn into_pointer(&self) -> *const () {
1987 self.0 as *const _ as *const ()
1991 #[allow(rustc::usage_of_ty_tykind)]
1992 impl<'tcx> Borrow<TyKind<'tcx>> for Interned<'tcx, TyS<'tcx>> {
1993 fn borrow<'a>(&'a self) -> &'a TyKind<'tcx> {
1998 impl<'tcx> PartialEq for Interned<'tcx, TyS<'tcx>> {
1999 fn eq(&self, other: &Interned<'tcx, TyS<'tcx>>) -> bool {
2000 // The `Borrow` trait requires that `x.borrow() == y.borrow()` equals
2002 self.0.kind() == other.0.kind()
2006 impl<'tcx> Eq for Interned<'tcx, TyS<'tcx>> {}
2008 impl<'tcx> Hash for Interned<'tcx, TyS<'tcx>> {
2009 fn hash<H: Hasher>(&self, s: &mut H) {
2010 // The `Borrow` trait requires that `x.borrow().hash(s) == x.hash(s)`.
2011 self.0.kind().hash(s)
2015 impl<'tcx> Borrow<Binder<'tcx, PredicateKind<'tcx>>> for Interned<'tcx, PredicateInner<'tcx>> {
2016 fn borrow<'a>(&'a self) -> &'a Binder<'tcx, PredicateKind<'tcx>> {
2021 impl<'tcx> PartialEq for Interned<'tcx, PredicateInner<'tcx>> {
2022 fn eq(&self, other: &Interned<'tcx, PredicateInner<'tcx>>) -> bool {
2023 // The `Borrow` trait requires that `x.borrow() == y.borrow()` equals
2025 self.0.kind == other.0.kind
2029 impl<'tcx> Eq for Interned<'tcx, PredicateInner<'tcx>> {}
2031 impl<'tcx> Hash for Interned<'tcx, PredicateInner<'tcx>> {
2032 fn hash<H: Hasher>(&self, s: &mut H) {
2033 // The `Borrow` trait requires that `x.borrow().hash(s) == x.hash(s)`.
2038 impl<'tcx, T> Borrow<[T]> for Interned<'tcx, List<T>> {
2039 fn borrow<'a>(&'a self) -> &'a [T] {
2044 impl<'tcx, T: PartialEq> PartialEq for Interned<'tcx, List<T>> {
2045 fn eq(&self, other: &Interned<'tcx, List<T>>) -> bool {
2046 // The `Borrow` trait requires that `x.borrow() == y.borrow()` equals
2048 self.0[..] == other.0[..]
2052 impl<'tcx, T: Eq> Eq for Interned<'tcx, List<T>> {}
2054 impl<'tcx, T: Hash> Hash for Interned<'tcx, List<T>> {
2055 fn hash<H: Hasher>(&self, s: &mut H) {
2056 // The `Borrow` trait requires that `x.borrow().hash(s) == x.hash(s)`.
2061 macro_rules! direct_interners {
2062 ($($name:ident: $method:ident($ty:ty),)+) => {
2063 $(impl<'tcx> Borrow<$ty> for Interned<'tcx, $ty> {
2064 fn borrow<'a>(&'a self) -> &'a $ty {
2069 impl<'tcx> PartialEq for Interned<'tcx, $ty> {
2070 fn eq(&self, other: &Self) -> bool {
2071 // The `Borrow` trait requires that `x.borrow() == y.borrow()`
2077 impl<'tcx> Eq for Interned<'tcx, $ty> {}
2079 impl<'tcx> Hash for Interned<'tcx, $ty> {
2080 fn hash<H: Hasher>(&self, s: &mut H) {
2081 // The `Borrow` trait requires that `x.borrow().hash(s) ==
2087 impl<'tcx> TyCtxt<'tcx> {
2088 pub fn $method(self, v: $ty) -> &'tcx $ty {
2089 self.interners.$name.intern(v, |v| {
2090 Interned(self.interners.arena.alloc(v))
2098 region: mk_region(RegionKind),
2099 const_: mk_const(Const<'tcx>),
2100 const_allocation: intern_const_alloc(Allocation),
2101 layout: intern_layout(Layout),
2102 adt_def: intern_adt_def(AdtDef),
2103 stability: intern_stability(attr::Stability),
2104 const_stability: intern_const_stability(attr::ConstStability),
2107 macro_rules! slice_interners {
2108 ($($field:ident: $method:ident($ty:ty)),+ $(,)?) => (
2109 impl<'tcx> TyCtxt<'tcx> {
2110 $(pub fn $method(self, v: &[$ty]) -> &'tcx List<$ty> {
2111 self.interners.$field.intern_ref(v, || {
2112 Interned(List::from_arena(&*self.arena, v))
2120 type_list: _intern_type_list(Ty<'tcx>),
2121 substs: _intern_substs(GenericArg<'tcx>),
2122 canonical_var_infos: _intern_canonical_var_infos(CanonicalVarInfo<'tcx>),
2123 poly_existential_predicates:
2124 _intern_poly_existential_predicates(ty::Binder<'tcx, ExistentialPredicate<'tcx>>),
2125 predicates: _intern_predicates(Predicate<'tcx>),
2126 projs: _intern_projs(ProjectionKind),
2127 place_elems: _intern_place_elems(PlaceElem<'tcx>),
2128 bound_variable_kinds: _intern_bound_variable_kinds(ty::BoundVariableKind),
2131 impl<'tcx> TyCtxt<'tcx> {
2132 /// Given a `fn` type, returns an equivalent `unsafe fn` type;
2133 /// that is, a `fn` type that is equivalent in every way for being
2135 pub fn safe_to_unsafe_fn_ty(self, sig: PolyFnSig<'tcx>) -> Ty<'tcx> {
2136 assert_eq!(sig.unsafety(), hir::Unsafety::Normal);
2137 self.mk_fn_ptr(sig.map_bound(|sig| ty::FnSig { unsafety: hir::Unsafety::Unsafe, ..sig }))
2140 /// Given the def_id of a Trait `trait_def_id` and the name of an associated item `assoc_name`
2141 /// returns true if the `trait_def_id` defines an associated item of name `assoc_name`.
2142 pub fn trait_may_define_assoc_type(self, trait_def_id: DefId, assoc_name: Ident) -> bool {
2143 self.super_traits_of(trait_def_id).any(|trait_did| {
2144 self.associated_items(trait_did)
2145 .find_by_name_and_kind(self, assoc_name, ty::AssocKind::Type, trait_did)
2150 /// Computes the def-ids of the transitive supertraits of `trait_def_id`. This (intentionally)
2151 /// does not compute the full elaborated super-predicates but just the set of def-ids. It is used
2152 /// to identify which traits may define a given associated type to help avoid cycle errors.
2153 /// Returns a `DefId` iterator.
2154 fn super_traits_of(self, trait_def_id: DefId) -> impl Iterator<Item = DefId> + 'tcx {
2155 let mut set = FxHashSet::default();
2156 let mut stack = vec![trait_def_id];
2158 set.insert(trait_def_id);
2160 iter::from_fn(move || -> Option<DefId> {
2161 let trait_did = stack.pop()?;
2162 let generic_predicates = self.super_predicates_of(trait_did);
2164 for (predicate, _) in generic_predicates.predicates {
2165 if let ty::PredicateKind::Trait(data) = predicate.kind().skip_binder() {
2166 if set.insert(data.def_id()) {
2167 stack.push(data.def_id());
2176 /// Given a closure signature, returns an equivalent fn signature. Detuples
2177 /// and so forth -- so e.g., if we have a sig with `Fn<(u32, i32)>` then
2178 /// you would get a `fn(u32, i32)`.
2179 /// `unsafety` determines the unsafety of the fn signature. If you pass
2180 /// `hir::Unsafety::Unsafe` in the previous example, then you would get
2181 /// an `unsafe fn (u32, i32)`.
2182 /// It cannot convert a closure that requires unsafe.
2183 pub fn signature_unclosure(
2185 sig: PolyFnSig<'tcx>,
2186 unsafety: hir::Unsafety,
2187 ) -> PolyFnSig<'tcx> {
2189 let params_iter = match s.inputs()[0].kind() {
2190 ty::Tuple(params) => params.into_iter().map(|k| k.expect_ty()),
2193 self.mk_fn_sig(params_iter, s.output(), s.c_variadic, unsafety, abi::Abi::Rust)
2197 /// Same a `self.mk_region(kind)`, but avoids accessing the interners if
2200 pub fn reuse_or_mk_region(self, r: Region<'tcx>, kind: RegionKind) -> Region<'tcx> {
2201 if *r == kind { r } else { self.mk_region(kind) }
2204 #[allow(rustc::usage_of_ty_tykind)]
2206 pub fn mk_ty(self, st: TyKind<'tcx>) -> Ty<'tcx> {
2207 self.interners.intern_ty(st)
2211 pub fn mk_predicate(self, binder: Binder<'tcx, PredicateKind<'tcx>>) -> Predicate<'tcx> {
2212 let inner = self.interners.intern_predicate(binder);
2217 pub fn reuse_or_mk_predicate(
2219 pred: Predicate<'tcx>,
2220 binder: Binder<'tcx, PredicateKind<'tcx>>,
2221 ) -> Predicate<'tcx> {
2222 if pred.kind() != binder { self.mk_predicate(binder) } else { pred }
2225 pub fn mk_mach_int(self, tm: IntTy) -> Ty<'tcx> {
2227 IntTy::Isize => self.types.isize,
2228 IntTy::I8 => self.types.i8,
2229 IntTy::I16 => self.types.i16,
2230 IntTy::I32 => self.types.i32,
2231 IntTy::I64 => self.types.i64,
2232 IntTy::I128 => self.types.i128,
2236 pub fn mk_mach_uint(self, tm: UintTy) -> Ty<'tcx> {
2238 UintTy::Usize => self.types.usize,
2239 UintTy::U8 => self.types.u8,
2240 UintTy::U16 => self.types.u16,
2241 UintTy::U32 => self.types.u32,
2242 UintTy::U64 => self.types.u64,
2243 UintTy::U128 => self.types.u128,
2247 pub fn mk_mach_float(self, tm: FloatTy) -> Ty<'tcx> {
2249 FloatTy::F32 => self.types.f32,
2250 FloatTy::F64 => self.types.f64,
2255 pub fn mk_static_str(self) -> Ty<'tcx> {
2256 self.mk_imm_ref(self.lifetimes.re_static, self.types.str_)
2260 pub fn mk_adt(self, def: &'tcx AdtDef, substs: SubstsRef<'tcx>) -> Ty<'tcx> {
2261 // Take a copy of substs so that we own the vectors inside.
2262 self.mk_ty(Adt(def, substs))
2266 pub fn mk_foreign(self, def_id: DefId) -> Ty<'tcx> {
2267 self.mk_ty(Foreign(def_id))
2270 fn mk_generic_adt(self, wrapper_def_id: DefId, ty_param: Ty<'tcx>) -> Ty<'tcx> {
2271 let adt_def = self.adt_def(wrapper_def_id);
2273 InternalSubsts::for_item(self, wrapper_def_id, |param, substs| match param.kind {
2274 GenericParamDefKind::Lifetime | GenericParamDefKind::Const { .. } => bug!(),
2275 GenericParamDefKind::Type { has_default, .. } => {
2276 if param.index == 0 {
2279 assert!(has_default);
2280 self.type_of(param.def_id).subst(self, substs).into()
2284 self.mk_ty(Adt(adt_def, substs))
2288 pub fn mk_box(self, ty: Ty<'tcx>) -> Ty<'tcx> {
2289 let def_id = self.require_lang_item(LangItem::OwnedBox, None);
2290 self.mk_generic_adt(def_id, ty)
2294 pub fn mk_lang_item(self, ty: Ty<'tcx>, item: LangItem) -> Option<Ty<'tcx>> {
2295 let def_id = self.lang_items().require(item).ok()?;
2296 Some(self.mk_generic_adt(def_id, ty))
2300 pub fn mk_diagnostic_item(self, ty: Ty<'tcx>, name: Symbol) -> Option<Ty<'tcx>> {
2301 let def_id = self.get_diagnostic_item(name)?;
2302 Some(self.mk_generic_adt(def_id, ty))
2306 pub fn mk_maybe_uninit(self, ty: Ty<'tcx>) -> Ty<'tcx> {
2307 let def_id = self.require_lang_item(LangItem::MaybeUninit, None);
2308 self.mk_generic_adt(def_id, ty)
2312 pub fn mk_ptr(self, tm: TypeAndMut<'tcx>) -> Ty<'tcx> {
2313 self.mk_ty(RawPtr(tm))
2317 pub fn mk_ref(self, r: Region<'tcx>, tm: TypeAndMut<'tcx>) -> Ty<'tcx> {
2318 self.mk_ty(Ref(r, tm.ty, tm.mutbl))
2322 pub fn mk_mut_ref(self, r: Region<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
2323 self.mk_ref(r, TypeAndMut { ty, mutbl: hir::Mutability::Mut })
2327 pub fn mk_imm_ref(self, r: Region<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
2328 self.mk_ref(r, TypeAndMut { ty, mutbl: hir::Mutability::Not })
2332 pub fn mk_mut_ptr(self, ty: Ty<'tcx>) -> Ty<'tcx> {
2333 self.mk_ptr(TypeAndMut { ty, mutbl: hir::Mutability::Mut })
2337 pub fn mk_imm_ptr(self, ty: Ty<'tcx>) -> Ty<'tcx> {
2338 self.mk_ptr(TypeAndMut { ty, mutbl: hir::Mutability::Not })
2342 pub fn mk_array(self, ty: Ty<'tcx>, n: u64) -> Ty<'tcx> {
2343 self.mk_ty(Array(ty, ty::Const::from_usize(self, n)))
2347 pub fn mk_slice(self, ty: Ty<'tcx>) -> Ty<'tcx> {
2348 self.mk_ty(Slice(ty))
2352 pub fn intern_tup(self, ts: &[Ty<'tcx>]) -> Ty<'tcx> {
2353 let kinds: Vec<_> = ts.iter().map(|&t| GenericArg::from(t)).collect();
2354 self.mk_ty(Tuple(self.intern_substs(&kinds)))
2357 pub fn mk_tup<I: InternAs<[Ty<'tcx>], Ty<'tcx>>>(self, iter: I) -> I::Output {
2358 iter.intern_with(|ts| {
2359 let kinds: Vec<_> = ts.iter().map(|&t| GenericArg::from(t)).collect();
2360 self.mk_ty(Tuple(self.intern_substs(&kinds)))
2365 pub fn mk_unit(self) -> Ty<'tcx> {
2370 pub fn mk_diverging_default(self) -> Ty<'tcx> {
2371 if self.features().never_type_fallback { self.types.never } else { self.types.unit }
2375 pub fn mk_fn_def(self, def_id: DefId, substs: SubstsRef<'tcx>) -> Ty<'tcx> {
2376 self.mk_ty(FnDef(def_id, substs))
2380 pub fn mk_fn_ptr(self, fty: PolyFnSig<'tcx>) -> Ty<'tcx> {
2381 self.mk_ty(FnPtr(fty))
2387 obj: &'tcx List<ty::Binder<'tcx, ExistentialPredicate<'tcx>>>,
2388 reg: ty::Region<'tcx>,
2390 self.mk_ty(Dynamic(obj, reg))
2394 pub fn mk_projection(self, item_def_id: DefId, substs: SubstsRef<'tcx>) -> Ty<'tcx> {
2395 self.mk_ty(Projection(ProjectionTy { item_def_id, substs }))
2399 pub fn mk_closure(self, closure_id: DefId, closure_substs: SubstsRef<'tcx>) -> Ty<'tcx> {
2400 self.mk_ty(Closure(closure_id, closure_substs))
2404 pub fn mk_generator(
2407 generator_substs: SubstsRef<'tcx>,
2408 movability: hir::Movability,
2410 self.mk_ty(Generator(id, generator_substs, movability))
2414 pub fn mk_generator_witness(self, types: ty::Binder<'tcx, &'tcx List<Ty<'tcx>>>) -> Ty<'tcx> {
2415 self.mk_ty(GeneratorWitness(types))
2419 pub fn mk_ty_var(self, v: TyVid) -> Ty<'tcx> {
2420 self.mk_ty_infer(TyVar(v))
2424 pub fn mk_const_var(self, v: ConstVid<'tcx>, ty: Ty<'tcx>) -> &'tcx Const<'tcx> {
2425 self.mk_const(ty::Const { val: ty::ConstKind::Infer(InferConst::Var(v)), ty })
2429 pub fn mk_int_var(self, v: IntVid) -> Ty<'tcx> {
2430 self.mk_ty_infer(IntVar(v))
2434 pub fn mk_float_var(self, v: FloatVid) -> Ty<'tcx> {
2435 self.mk_ty_infer(FloatVar(v))
2439 pub fn mk_ty_infer(self, it: InferTy) -> Ty<'tcx> {
2440 self.mk_ty(Infer(it))
2444 pub fn mk_const_infer(self, ic: InferConst<'tcx>, ty: Ty<'tcx>) -> &'tcx ty::Const<'tcx> {
2445 self.mk_const(ty::Const { val: ty::ConstKind::Infer(ic), ty })
2449 pub fn mk_ty_param(self, index: u32, name: Symbol) -> Ty<'tcx> {
2450 self.mk_ty(Param(ParamTy { index, name }))
2454 pub fn mk_const_param(self, index: u32, name: Symbol, ty: Ty<'tcx>) -> &'tcx Const<'tcx> {
2455 self.mk_const(ty::Const { val: ty::ConstKind::Param(ParamConst { index, name }), ty })
2458 pub fn mk_param_from_def(self, param: &ty::GenericParamDef) -> GenericArg<'tcx> {
2460 GenericParamDefKind::Lifetime => {
2461 self.mk_region(ty::ReEarlyBound(param.to_early_bound_region_data())).into()
2463 GenericParamDefKind::Type { .. } => self.mk_ty_param(param.index, param.name).into(),
2464 GenericParamDefKind::Const { .. } => {
2465 self.mk_const_param(param.index, param.name, self.type_of(param.def_id)).into()
2471 pub fn mk_opaque(self, def_id: DefId, substs: SubstsRef<'tcx>) -> Ty<'tcx> {
2472 self.mk_ty(Opaque(def_id, substs))
2475 pub fn mk_place_field(self, place: Place<'tcx>, f: Field, ty: Ty<'tcx>) -> Place<'tcx> {
2476 self.mk_place_elem(place, PlaceElem::Field(f, ty))
2479 pub fn mk_place_deref(self, place: Place<'tcx>) -> Place<'tcx> {
2480 self.mk_place_elem(place, PlaceElem::Deref)
2483 pub fn mk_place_downcast(
2486 adt_def: &'tcx AdtDef,
2487 variant_index: VariantIdx,
2491 PlaceElem::Downcast(Some(adt_def.variants[variant_index].name), variant_index),
2495 pub fn mk_place_downcast_unnamed(
2498 variant_index: VariantIdx,
2500 self.mk_place_elem(place, PlaceElem::Downcast(None, variant_index))
2503 pub fn mk_place_index(self, place: Place<'tcx>, index: Local) -> Place<'tcx> {
2504 self.mk_place_elem(place, PlaceElem::Index(index))
2507 /// This method copies `Place`'s projection, add an element and reintern it. Should not be used
2508 /// to build a full `Place` it's just a convenient way to grab a projection and modify it in
2510 pub fn mk_place_elem(self, place: Place<'tcx>, elem: PlaceElem<'tcx>) -> Place<'tcx> {
2511 let mut projection = place.projection.to_vec();
2512 projection.push(elem);
2514 Place { local: place.local, projection: self.intern_place_elems(&projection) }
2517 pub fn intern_poly_existential_predicates(
2519 eps: &[ty::Binder<'tcx, ExistentialPredicate<'tcx>>],
2520 ) -> &'tcx List<ty::Binder<'tcx, ExistentialPredicate<'tcx>>> {
2521 assert!(!eps.is_empty());
2524 .all(|[a, b]| a.skip_binder().stable_cmp(self, &b.skip_binder())
2525 != Ordering::Greater)
2527 self._intern_poly_existential_predicates(eps)
2530 pub fn intern_predicates(self, preds: &[Predicate<'tcx>]) -> &'tcx List<Predicate<'tcx>> {
2531 // FIXME consider asking the input slice to be sorted to avoid
2532 // re-interning permutations, in which case that would be asserted
2534 if preds.is_empty() {
2535 // The macro-generated method below asserts we don't intern an empty slice.
2538 self._intern_predicates(preds)
2542 pub fn intern_type_list(self, ts: &[Ty<'tcx>]) -> &'tcx List<Ty<'tcx>> {
2543 if ts.is_empty() { List::empty() } else { self._intern_type_list(ts) }
2546 pub fn intern_substs(self, ts: &[GenericArg<'tcx>]) -> &'tcx List<GenericArg<'tcx>> {
2547 if ts.is_empty() { List::empty() } else { self._intern_substs(ts) }
2550 pub fn intern_projs(self, ps: &[ProjectionKind]) -> &'tcx List<ProjectionKind> {
2551 if ps.is_empty() { List::empty() } else { self._intern_projs(ps) }
2554 pub fn intern_place_elems(self, ts: &[PlaceElem<'tcx>]) -> &'tcx List<PlaceElem<'tcx>> {
2555 if ts.is_empty() { List::empty() } else { self._intern_place_elems(ts) }
2558 pub fn intern_canonical_var_infos(
2560 ts: &[CanonicalVarInfo<'tcx>],
2561 ) -> CanonicalVarInfos<'tcx> {
2562 if ts.is_empty() { List::empty() } else { self._intern_canonical_var_infos(ts) }
2565 pub fn intern_bound_variable_kinds(
2567 ts: &[ty::BoundVariableKind],
2568 ) -> &'tcx List<ty::BoundVariableKind> {
2569 if ts.is_empty() { List::empty() } else { self._intern_bound_variable_kinds(ts) }
2572 pub fn mk_fn_sig<I>(
2577 unsafety: hir::Unsafety,
2579 ) -> <I::Item as InternIteratorElement<Ty<'tcx>, ty::FnSig<'tcx>>>::Output
2581 I: Iterator<Item: InternIteratorElement<Ty<'tcx>, ty::FnSig<'tcx>>>,
2583 inputs.chain(iter::once(output)).intern_with(|xs| ty::FnSig {
2584 inputs_and_output: self.intern_type_list(xs),
2591 pub fn mk_poly_existential_predicates<
2593 [ty::Binder<'tcx, ExistentialPredicate<'tcx>>],
2594 &'tcx List<ty::Binder<'tcx, ExistentialPredicate<'tcx>>>,
2600 iter.intern_with(|xs| self.intern_poly_existential_predicates(xs))
2603 pub fn mk_predicates<I: InternAs<[Predicate<'tcx>], &'tcx List<Predicate<'tcx>>>>(
2607 iter.intern_with(|xs| self.intern_predicates(xs))
2610 pub fn mk_type_list<I: InternAs<[Ty<'tcx>], &'tcx List<Ty<'tcx>>>>(self, iter: I) -> I::Output {
2611 iter.intern_with(|xs| self.intern_type_list(xs))
2614 pub fn mk_substs<I: InternAs<[GenericArg<'tcx>], &'tcx List<GenericArg<'tcx>>>>(
2618 iter.intern_with(|xs| self.intern_substs(xs))
2621 pub fn mk_place_elems<I: InternAs<[PlaceElem<'tcx>], &'tcx List<PlaceElem<'tcx>>>>(
2625 iter.intern_with(|xs| self.intern_place_elems(xs))
2628 pub fn mk_substs_trait(self, self_ty: Ty<'tcx>, rest: &[GenericArg<'tcx>]) -> SubstsRef<'tcx> {
2629 self.mk_substs(iter::once(self_ty.into()).chain(rest.iter().cloned()))
2632 pub fn mk_bound_variable_kinds<
2633 I: InternAs<[ty::BoundVariableKind], &'tcx List<ty::BoundVariableKind>>,
2638 iter.intern_with(|xs| self.intern_bound_variable_kinds(xs))
2641 /// Walks upwards from `id` to find a node which might change lint levels with attributes.
2642 /// It stops at `bound` and just returns it if reached.
2643 pub fn maybe_lint_level_root_bounded(self, mut id: HirId, bound: HirId) -> HirId {
2644 let hir = self.hir();
2650 if hir.attrs(id).iter().any(|attr| Level::from_symbol(attr.name_or_empty()).is_some()) {
2653 let next = hir.get_parent_node(id);
2655 bug!("lint traversal reached the root of the crate");
2661 pub fn lint_level_at_node(
2663 lint: &'static Lint,
2665 ) -> (Level, LintLevelSource) {
2666 let sets = self.lint_levels(());
2668 if let Some(pair) = sets.level_and_source(lint, id, self.sess) {
2671 let next = self.hir().get_parent_node(id);
2673 bug!("lint traversal reached the root of the crate");
2679 pub fn struct_span_lint_hir(
2681 lint: &'static Lint,
2683 span: impl Into<MultiSpan>,
2684 decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a>),
2686 let (level, src) = self.lint_level_at_node(lint, hir_id);
2687 struct_lint_level(self.sess, lint, level, src, Some(span.into()), decorate);
2690 pub fn struct_lint_node(
2692 lint: &'static Lint,
2694 decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a>),
2696 let (level, src) = self.lint_level_at_node(lint, id);
2697 struct_lint_level(self.sess, lint, level, src, None, decorate);
2700 pub fn in_scope_traits(self, id: HirId) -> Option<&'tcx [TraitCandidate]> {
2701 let map = self.in_scope_traits_map(id.owner)?;
2702 let candidates = map.get(&id.local_id)?;
2706 pub fn named_region(self, id: HirId) -> Option<resolve_lifetime::Region> {
2707 debug!(?id, "named_region");
2708 self.named_region_map(id.owner).and_then(|map| map.get(&id.local_id).cloned())
2711 pub fn is_late_bound(self, id: HirId) -> bool {
2712 self.is_late_bound_map(id.owner)
2713 .map_or(false, |(owner, set)| owner == id.owner && set.contains(&id.local_id))
2716 pub fn late_bound_vars(self, id: HirId) -> &'tcx List<ty::BoundVariableKind> {
2717 self.mk_bound_variable_kinds(
2718 self.late_bound_vars_map(id.owner)
2719 .and_then(|map| map.get(&id.local_id).cloned())
2720 .unwrap_or_else(|| {
2721 bug!("No bound vars found for {:?} ({:?})", self.hir().node_to_string(id), id)
2727 pub fn lifetime_scope(self, id: HirId) -> Option<&'tcx LifetimeScopeForPath> {
2728 self.lifetime_scope_map(id.owner).as_ref().and_then(|map| map.get(&id.local_id))
2731 /// Whether the `def_id` counts as const fn in the current crate, considering all active
2733 pub fn is_const_fn(self, def_id: DefId) -> bool {
2734 if self.is_const_fn_raw(def_id) {
2735 match self.lookup_const_stability(def_id) {
2736 Some(stability) if stability.level.is_unstable() => {
2737 // has a `rustc_const_unstable` attribute, check whether the user enabled the
2738 // corresponding feature gate.
2740 .declared_lib_features
2742 .any(|&(sym, _)| sym == stability.feature)
2744 // functions without const stability are either stable user written
2745 // const fn or the user is using feature gates and we thus don't
2746 // care what they do
2755 impl<'tcx> TyCtxtAt<'tcx> {
2756 /// Constructs a `TyKind::Error` type and registers a `delay_span_bug` to ensure it gets used.
2758 pub fn ty_error(self) -> Ty<'tcx> {
2759 self.tcx.ty_error_with_message(self.span, "TyKind::Error constructed but no error reported")
2762 /// Constructs a `TyKind::Error` type and registers a `delay_span_bug` with the given `msg to
2763 /// ensure it gets used.
2765 pub fn ty_error_with_message(self, msg: &str) -> Ty<'tcx> {
2766 self.tcx.ty_error_with_message(self.span, msg)
2770 pub trait InternAs<T: ?Sized, R> {
2772 fn intern_with<F>(self, f: F) -> Self::Output
2777 impl<I, T, R, E> InternAs<[T], R> for I
2779 E: InternIteratorElement<T, R>,
2780 I: Iterator<Item = E>,
2782 type Output = E::Output;
2783 fn intern_with<F>(self, f: F) -> Self::Output
2785 F: FnOnce(&[T]) -> R,
2787 E::intern_with(self, f)
2791 pub trait InternIteratorElement<T, R>: Sized {
2793 fn intern_with<I: Iterator<Item = Self>, F: FnOnce(&[T]) -> R>(iter: I, f: F) -> Self::Output;
2796 impl<T, R> InternIteratorElement<T, R> for T {
2798 fn intern_with<I: Iterator<Item = Self>, F: FnOnce(&[T]) -> R>(
2802 // This code is hot enough that it's worth specializing for the most
2803 // common length lists, to avoid the overhead of `SmallVec` creation.
2804 // Lengths 0, 1, and 2 typically account for ~95% of cases. If
2805 // `size_hint` is incorrect a panic will occur via an `unwrap` or an
2807 match iter.size_hint() {
2809 assert!(iter.next().is_none());
2813 let t0 = iter.next().unwrap();
2814 assert!(iter.next().is_none());
2818 let t0 = iter.next().unwrap();
2819 let t1 = iter.next().unwrap();
2820 assert!(iter.next().is_none());
2823 _ => f(&iter.collect::<SmallVec<[_; 8]>>()),
2828 impl<'a, T, R> InternIteratorElement<T, R> for &'a T
2833 fn intern_with<I: Iterator<Item = Self>, F: FnOnce(&[T]) -> R>(iter: I, f: F) -> Self::Output {
2834 // This code isn't hot.
2835 f(&iter.cloned().collect::<SmallVec<[_; 8]>>())
2839 impl<T, R, E> InternIteratorElement<T, R> for Result<T, E> {
2840 type Output = Result<R, E>;
2841 fn intern_with<I: Iterator<Item = Self>, F: FnOnce(&[T]) -> R>(
2845 // This code is hot enough that it's worth specializing for the most
2846 // common length lists, to avoid the overhead of `SmallVec` creation.
2847 // Lengths 0, 1, and 2 typically account for ~95% of cases. If
2848 // `size_hint` is incorrect a panic will occur via an `unwrap` or an
2849 // `assert`, unless a failure happens first, in which case the result
2850 // will be an error anyway.
2851 Ok(match iter.size_hint() {
2853 assert!(iter.next().is_none());
2857 let t0 = iter.next().unwrap()?;
2858 assert!(iter.next().is_none());
2862 let t0 = iter.next().unwrap()?;
2863 let t1 = iter.next().unwrap()?;
2864 assert!(iter.next().is_none());
2867 _ => f(&iter.collect::<Result<SmallVec<[_; 8]>, _>>()?),
2872 // We are comparing types with different invariant lifetimes, so `ptr::eq`
2873 // won't work for us.
2874 fn ptr_eq<T, U>(t: *const T, u: *const U) -> bool {
2875 t as *const () == u as *const ()
2878 pub fn provide(providers: &mut ty::query::Providers) {
2879 providers.resolutions = |tcx, ()| &tcx.untracked_resolutions;
2880 providers.module_reexports =
2881 |tcx, id| tcx.resolutions(()).reexport_map.get(&id).map(|v| &v[..]);
2882 providers.crate_name = |tcx, id| {
2883 assert_eq!(id, LOCAL_CRATE);
2886 providers.maybe_unused_trait_import =
2887 |tcx, id| tcx.resolutions(()).maybe_unused_trait_imports.contains(&id);
2888 providers.maybe_unused_extern_crates =
2889 |tcx, ()| &tcx.resolutions(()).maybe_unused_extern_crates[..];
2890 providers.names_imported_by_glob_use = |tcx, id| {
2891 tcx.arena.alloc(tcx.resolutions(()).glob_map.get(&id).cloned().unwrap_or_default())
2894 providers.lookup_stability = |tcx, id| tcx.stability().local_stability(id.expect_local());
2895 providers.lookup_const_stability =
2896 |tcx, id| tcx.stability().local_const_stability(id.expect_local());
2897 providers.lookup_deprecation_entry =
2898 |tcx, id| tcx.stability().local_deprecation_entry(id.expect_local());
2899 providers.extern_mod_stmt_cnum =
2900 |tcx, id| tcx.resolutions(()).extern_crate_map.get(&id).cloned();
2901 providers.output_filenames = |tcx, ()| &tcx.output_filenames;
2902 providers.features_query = |tcx, ()| tcx.sess.features_untracked();
2903 providers.is_panic_runtime = |tcx, cnum| {
2904 assert_eq!(cnum, LOCAL_CRATE);
2905 tcx.sess.contains_name(tcx.hir().krate_attrs(), sym::panic_runtime)
2907 providers.is_compiler_builtins = |tcx, cnum| {
2908 assert_eq!(cnum, LOCAL_CRATE);
2909 tcx.sess.contains_name(tcx.hir().krate_attrs(), sym::compiler_builtins)
2911 providers.has_panic_handler = |tcx, cnum| {
2912 assert_eq!(cnum, LOCAL_CRATE);
2913 // We want to check if the panic handler was defined in this crate
2914 tcx.lang_items().panic_impl().map_or(false, |did| did.is_local())