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, ObjectLifetimeDefault};
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_errors::ErrorReported;
35 use rustc_hir::def::{DefKind, Res};
36 use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, LocalDefId, LOCAL_CRATE};
37 use rustc_hir::intravisit::Visitor;
38 use rustc_hir::lang_items::LangItem;
40 Constness, ExprKind, HirId, ImplItemKind, ItemKind, ItemLocalId, ItemLocalMap, ItemLocalSet,
41 Node, TraitCandidate, TraitItemKind,
43 use rustc_index::vec::{Idx, IndexVec};
44 use rustc_macros::HashStable;
45 use rustc_middle::mir::FakeReadCause;
46 use rustc_query_system::ich::{NodeIdHashingMode, StableHashingContext};
47 use rustc_serialize::opaque::{FileEncodeResult, FileEncoder};
48 use rustc_session::config::{BorrowckMode, CrateType, OutputFilenames};
49 use rustc_session::lint::{Level, Lint};
50 use rustc_session::Limit;
51 use rustc_session::Session;
52 use rustc_span::def_id::{DefPathHash, StableCrateId};
53 use rustc_span::source_map::{MultiSpan, SourceMap};
54 use rustc_span::symbol::{kw, sym, Ident, Symbol};
55 use rustc_span::{Span, DUMMY_SP};
56 use rustc_target::abi::{Layout, TargetDataLayout, VariantIdx};
57 use rustc_target::spec::abi;
59 use smallvec::SmallVec;
61 use std::borrow::Borrow;
62 use std::cmp::Ordering;
63 use std::collections::hash_map::{self, Entry};
65 use std::hash::{Hash, Hasher};
68 use std::ops::{Bound, Deref};
71 pub trait OnDiskCache<'tcx>: rustc_data_structures::sync::Sync {
72 /// Creates a new `OnDiskCache` instance from the serialized data in `data`.
73 fn new(sess: &'tcx Session, data: Mmap, start_pos: usize) -> Self
77 fn new_empty(source_map: &'tcx SourceMap) -> Self
81 fn drop_serialized_data(&self, tcx: TyCtxt<'tcx>);
83 fn serialize(&self, tcx: TyCtxt<'tcx>, encoder: &mut FileEncoder) -> FileEncodeResult;
86 /// A type that is not publicly constructable. This prevents people from making [`TyKind::Error`]s
87 /// except through the error-reporting functions on a [`tcx`][TyCtxt].
88 #[derive(Copy, Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
89 #[derive(TyEncodable, TyDecodable, HashStable)]
90 pub struct DelaySpanBugEmitted(());
92 type InternedSet<'tcx, T> = ShardedHashMap<Interned<'tcx, T>, ()>;
94 pub struct CtxtInterners<'tcx> {
95 /// The arena that types, regions, etc. are allocated from.
96 arena: &'tcx WorkerLocal<Arena<'tcx>>,
98 // Specifically use a speedy hash algorithm for these hash sets, since
99 // they're accessed quite often.
100 type_: InternedSet<'tcx, TyS<'tcx>>,
101 type_list: InternedSet<'tcx, List<Ty<'tcx>>>,
102 substs: InternedSet<'tcx, InternalSubsts<'tcx>>,
103 canonical_var_infos: InternedSet<'tcx, List<CanonicalVarInfo<'tcx>>>,
104 region: InternedSet<'tcx, RegionKind>,
105 poly_existential_predicates:
106 InternedSet<'tcx, List<ty::Binder<'tcx, ExistentialPredicate<'tcx>>>>,
107 predicate: InternedSet<'tcx, PredicateInner<'tcx>>,
108 predicates: InternedSet<'tcx, List<Predicate<'tcx>>>,
109 projs: InternedSet<'tcx, List<ProjectionKind>>,
110 place_elems: InternedSet<'tcx, List<PlaceElem<'tcx>>>,
111 const_: InternedSet<'tcx, Const<'tcx>>,
112 const_allocation: InternedSet<'tcx, Allocation>,
113 bound_variable_kinds: InternedSet<'tcx, List<ty::BoundVariableKind>>,
114 layout: InternedSet<'tcx, Layout>,
115 adt_def: InternedSet<'tcx, AdtDef>,
117 /// `#[stable]` and `#[unstable]` attributes
118 stability: InternedSet<'tcx, attr::Stability>,
120 /// `#[rustc_const_stable]` and `#[rustc_const_unstable]` attributes
121 const_stability: InternedSet<'tcx, attr::ConstStability>,
124 impl<'tcx> CtxtInterners<'tcx> {
125 fn new(arena: &'tcx WorkerLocal<Arena<'tcx>>) -> CtxtInterners<'tcx> {
128 type_: Default::default(),
129 type_list: Default::default(),
130 substs: Default::default(),
131 region: Default::default(),
132 poly_existential_predicates: Default::default(),
133 canonical_var_infos: Default::default(),
134 predicate: Default::default(),
135 predicates: Default::default(),
136 projs: Default::default(),
137 place_elems: Default::default(),
138 const_: Default::default(),
139 const_allocation: Default::default(),
140 bound_variable_kinds: Default::default(),
141 layout: Default::default(),
142 adt_def: Default::default(),
143 stability: Default::default(),
144 const_stability: Default::default(),
149 #[allow(rustc::usage_of_ty_tykind)]
151 fn intern_ty(&self, kind: TyKind<'tcx>) -> Ty<'tcx> {
153 .intern(kind, |kind| {
154 let flags = super::flags::FlagComputation::for_kind(&kind);
156 let ty_struct = TyS {
159 outer_exclusive_binder: flags.outer_exclusive_binder,
162 Interned(self.arena.alloc(ty_struct))
170 kind: Binder<'tcx, PredicateKind<'tcx>>,
171 ) -> &'tcx PredicateInner<'tcx> {
173 .intern(kind, |kind| {
174 let flags = super::flags::FlagComputation::for_predicate(kind);
176 let predicate_struct = PredicateInner {
179 outer_exclusive_binder: flags.outer_exclusive_binder,
182 Interned(self.arena.alloc(predicate_struct))
188 pub struct CommonTypes<'tcx> {
208 pub self_param: Ty<'tcx>,
210 /// Dummy type used for the `Self` of a `TraitRef` created for converting
211 /// a trait object, and which gets removed in `ExistentialTraitRef`.
212 /// This type must not appear anywhere in other converted types.
213 pub trait_object_dummy_self: Ty<'tcx>,
216 pub struct CommonLifetimes<'tcx> {
217 /// `ReEmpty` in the root universe.
218 pub re_root_empty: Region<'tcx>,
221 pub re_static: Region<'tcx>,
223 /// Erased region, used after type-checking
224 pub re_erased: Region<'tcx>,
227 pub struct CommonConsts<'tcx> {
228 pub unit: &'tcx Const<'tcx>,
231 pub struct LocalTableInContext<'a, V> {
232 hir_owner: LocalDefId,
233 data: &'a ItemLocalMap<V>,
236 /// Validate that the given HirId (respectively its `local_id` part) can be
237 /// safely used as a key in the maps of a TypeckResults. For that to be
238 /// the case, the HirId must have the same `owner` as all the other IDs in
239 /// this table (signified by `hir_owner`). Otherwise the HirId
240 /// would be in a different frame of reference and using its `local_id`
241 /// would result in lookup errors, or worse, in silently wrong data being
244 fn validate_hir_id_for_typeck_results(hir_owner: LocalDefId, hir_id: hir::HirId) {
245 if hir_id.owner != hir_owner {
246 invalid_hir_id_for_typeck_results(hir_owner, hir_id);
252 fn invalid_hir_id_for_typeck_results(hir_owner: LocalDefId, hir_id: hir::HirId) {
253 ty::tls::with(|tcx| {
255 "node {} with HirId::owner {:?} cannot be placed in TypeckResults with hir_owner {:?}",
256 tcx.hir().node_to_string(hir_id),
263 impl<'a, V> LocalTableInContext<'a, V> {
264 pub fn contains_key(&self, id: hir::HirId) -> bool {
265 validate_hir_id_for_typeck_results(self.hir_owner, id);
266 self.data.contains_key(&id.local_id)
269 pub fn get(&self, id: hir::HirId) -> Option<&V> {
270 validate_hir_id_for_typeck_results(self.hir_owner, id);
271 self.data.get(&id.local_id)
274 pub fn iter(&self) -> hash_map::Iter<'_, hir::ItemLocalId, V> {
279 impl<'a, V> ::std::ops::Index<hir::HirId> for LocalTableInContext<'a, V> {
282 fn index(&self, key: hir::HirId) -> &V {
283 self.get(key).expect("LocalTableInContext: key not found")
287 pub struct LocalTableInContextMut<'a, V> {
288 hir_owner: LocalDefId,
289 data: &'a mut ItemLocalMap<V>,
292 impl<'a, V> LocalTableInContextMut<'a, V> {
293 pub fn get_mut(&mut self, id: hir::HirId) -> Option<&mut V> {
294 validate_hir_id_for_typeck_results(self.hir_owner, id);
295 self.data.get_mut(&id.local_id)
298 pub fn entry(&mut self, id: hir::HirId) -> Entry<'_, hir::ItemLocalId, V> {
299 validate_hir_id_for_typeck_results(self.hir_owner, id);
300 self.data.entry(id.local_id)
303 pub fn insert(&mut self, id: hir::HirId, val: V) -> Option<V> {
304 validate_hir_id_for_typeck_results(self.hir_owner, id);
305 self.data.insert(id.local_id, val)
308 pub fn remove(&mut self, id: hir::HirId) -> Option<V> {
309 validate_hir_id_for_typeck_results(self.hir_owner, id);
310 self.data.remove(&id.local_id)
314 /// Whenever a value may be live across a generator yield, the type of that value winds up in the
315 /// `GeneratorInteriorTypeCause` struct. This struct adds additional information about such
316 /// captured types that can be useful for diagnostics. In particular, it stores the span that
317 /// caused a given type to be recorded, along with the scope that enclosed the value (which can
318 /// be used to find the await that the value is live across).
322 /// ```ignore (pseudo-Rust)
330 /// Here, we would store the type `T`, the span of the value `x`, the "scope-span" for
331 /// the scope that contains `x`, the expr `T` evaluated from, and the span of `foo.await`.
332 #[derive(TyEncodable, TyDecodable, Clone, Debug, Eq, Hash, PartialEq, HashStable)]
333 #[derive(TypeFoldable)]
334 pub struct GeneratorInteriorTypeCause<'tcx> {
335 /// Type of the captured binding.
337 /// Span of the binding that was captured.
339 /// Span of the scope of the captured binding.
340 pub scope_span: Option<Span>,
341 /// Span of `.await` or `yield` expression.
342 pub yield_span: Span,
343 /// Expr which the type evaluated from.
344 pub expr: Option<hir::HirId>,
347 #[derive(TyEncodable, TyDecodable, Debug)]
348 pub struct TypeckResults<'tcx> {
349 /// The `HirId::owner` all `ItemLocalId`s in this table are relative to.
350 pub hir_owner: LocalDefId,
352 /// Resolved definitions for `<T>::X` associated paths and
353 /// method calls, including those of overloaded operators.
354 type_dependent_defs: ItemLocalMap<Result<(DefKind, DefId), ErrorReported>>,
356 /// Resolved field indices for field accesses in expressions (`S { field }`, `obj.field`)
357 /// or patterns (`S { field }`). The index is often useful by itself, but to learn more
358 /// about the field you also need definition of the variant to which the field
359 /// belongs, but it may not exist if it's a tuple field (`tuple.0`).
360 field_indices: ItemLocalMap<usize>,
362 /// Stores the types for various nodes in the AST. Note that this table
363 /// is not guaranteed to be populated until after typeck. See
364 /// typeck::check::fn_ctxt for details.
365 node_types: ItemLocalMap<Ty<'tcx>>,
367 /// Stores the type parameters which were substituted to obtain the type
368 /// of this node. This only applies to nodes that refer to entities
369 /// parameterized by type parameters, such as generic fns, types, or
371 node_substs: ItemLocalMap<SubstsRef<'tcx>>,
373 /// This will either store the canonicalized types provided by the user
374 /// or the substitutions that the user explicitly gave (if any) attached
375 /// to `id`. These will not include any inferred values. The canonical form
376 /// is used to capture things like `_` or other unspecified values.
378 /// For example, if the user wrote `foo.collect::<Vec<_>>()`, then the
379 /// canonical substitutions would include only `for<X> { Vec<X> }`.
381 /// See also `AscribeUserType` statement in MIR.
382 user_provided_types: ItemLocalMap<CanonicalUserType<'tcx>>,
384 /// Stores the canonicalized types provided by the user. See also
385 /// `AscribeUserType` statement in MIR.
386 pub user_provided_sigs: DefIdMap<CanonicalPolyFnSig<'tcx>>,
388 adjustments: ItemLocalMap<Vec<ty::adjustment::Adjustment<'tcx>>>,
390 /// Stores the actual binding mode for all instances of hir::BindingAnnotation.
391 pat_binding_modes: ItemLocalMap<BindingMode>,
393 /// Stores the types which were implicitly dereferenced in pattern binding modes
394 /// for later usage in THIR lowering. For example,
397 /// match &&Some(5i32) {
402 /// leads to a `vec![&&Option<i32>, &Option<i32>]`. Empty vectors are not stored.
405 /// <https://github.com/rust-lang/rfcs/blob/master/text/2005-match-ergonomics.md#definitions>
406 pat_adjustments: ItemLocalMap<Vec<Ty<'tcx>>>,
408 /// Records the reasons that we picked the kind of each closure;
409 /// not all closures are present in the map.
410 closure_kind_origins: ItemLocalMap<(Span, HirPlace<'tcx>)>,
412 /// For each fn, records the "liberated" types of its arguments
413 /// and return type. Liberated means that all bound regions
414 /// (including late-bound regions) are replaced with free
415 /// equivalents. This table is not used in codegen (since regions
416 /// are erased there) and hence is not serialized to metadata.
418 /// This table also contains the "revealed" values for any `impl Trait`
419 /// that appear in the signature and whose values are being inferred
420 /// by this function.
425 /// fn foo(x: &u32) -> impl Debug { *x }
428 /// The function signature here would be:
431 /// for<'a> fn(&'a u32) -> Foo
434 /// where `Foo` is an opaque type created for this function.
437 /// The *liberated* form of this would be
440 /// fn(&'a u32) -> u32
443 /// Note that `'a` is not bound (it would be an `ReFree`) and
444 /// that the `Foo` opaque type is replaced by its hidden type.
445 liberated_fn_sigs: ItemLocalMap<ty::FnSig<'tcx>>,
447 /// For each FRU expression, record the normalized types of the fields
448 /// of the struct - this is needed because it is non-trivial to
449 /// normalize while preserving regions. This table is used only in
450 /// MIR construction and hence is not serialized to metadata.
451 fru_field_types: ItemLocalMap<Vec<Ty<'tcx>>>,
453 /// For every coercion cast we add the HIR node ID of the cast
454 /// expression to this set.
455 coercion_casts: ItemLocalSet,
457 /// Set of trait imports actually used in the method resolution.
458 /// This is used for warning unused imports. During type
459 /// checking, this `Lrc` should not be cloned: it must have a ref-count
460 /// of 1 so that we can insert things into the set mutably.
461 pub used_trait_imports: Lrc<FxHashSet<LocalDefId>>,
463 /// If any errors occurred while type-checking this body,
464 /// this field will be set to `Some(ErrorReported)`.
465 pub tainted_by_errors: Option<ErrorReported>,
467 /// All the opaque types that are restricted to concrete types
468 /// by this function.
469 pub concrete_opaque_types: FxHashSet<DefId>,
471 /// Tracks the minimum captures required for a closure;
472 /// see `MinCaptureInformationMap` for more details.
473 pub closure_min_captures: ty::MinCaptureInformationMap<'tcx>,
475 /// Tracks the fake reads required for a closure and the reason for the fake read.
476 /// When performing pattern matching for closures, there are times we don't end up
477 /// reading places that are mentioned in a closure (because of _ patterns). However,
478 /// to ensure the places are initialized, we introduce fake reads.
479 /// Consider these two examples:
480 /// ``` (discriminant matching with only wildcard arm)
482 /// let c = || match x { _ => () };
484 /// In this example, we don't need to actually read/borrow `x` in `c`, and so we don't
485 /// want to capture it. However, we do still want an error here, because `x` should have
486 /// to be initialized at the point where c is created. Therefore, we add a "fake read"
488 /// ``` (destructured assignments)
490 /// let (t1, t2) = t;
493 /// In the second example, we capture the disjoint fields of `t` (`t.0` & `t.1`), but
494 /// we never capture `t`. This becomes an issue when we build MIR as we require
495 /// information on `t` in order to create place `t.0` and `t.1`. We can solve this
496 /// issue by fake reading `t`.
497 pub closure_fake_reads: FxHashMap<DefId, Vec<(HirPlace<'tcx>, FakeReadCause, hir::HirId)>>,
499 /// Stores the type, expression, span and optional scope span of all types
500 /// that are live across the yield of this generator (if a generator).
501 pub generator_interior_types: ty::Binder<'tcx, Vec<GeneratorInteriorTypeCause<'tcx>>>,
503 /// We sometimes treat byte string literals (which are of type `&[u8; N]`)
504 /// as `&[u8]`, depending on the pattern in which they are used.
505 /// This hashset records all instances where we behave
506 /// like this to allow `const_to_pat` to reliably handle this situation.
507 pub treat_byte_string_as_slice: ItemLocalSet,
509 /// Contains the data for evaluating the effect of feature `capture_disjoint_fields`
511 pub closure_size_eval: FxHashMap<DefId, ClosureSizeProfileData<'tcx>>,
514 impl<'tcx> TypeckResults<'tcx> {
515 pub fn new(hir_owner: LocalDefId) -> TypeckResults<'tcx> {
518 type_dependent_defs: Default::default(),
519 field_indices: Default::default(),
520 user_provided_types: Default::default(),
521 user_provided_sigs: Default::default(),
522 node_types: Default::default(),
523 node_substs: Default::default(),
524 adjustments: Default::default(),
525 pat_binding_modes: Default::default(),
526 pat_adjustments: Default::default(),
527 closure_kind_origins: Default::default(),
528 liberated_fn_sigs: Default::default(),
529 fru_field_types: Default::default(),
530 coercion_casts: Default::default(),
531 used_trait_imports: Lrc::new(Default::default()),
532 tainted_by_errors: None,
533 concrete_opaque_types: Default::default(),
534 closure_min_captures: Default::default(),
535 closure_fake_reads: Default::default(),
536 generator_interior_types: ty::Binder::dummy(Default::default()),
537 treat_byte_string_as_slice: Default::default(),
538 closure_size_eval: Default::default(),
542 /// Returns the final resolution of a `QPath` in an `Expr` or `Pat` node.
543 pub fn qpath_res(&self, qpath: &hir::QPath<'_>, id: hir::HirId) -> Res {
545 hir::QPath::Resolved(_, ref path) => path.res,
546 hir::QPath::TypeRelative(..) | hir::QPath::LangItem(..) => self
547 .type_dependent_def(id)
548 .map_or(Res::Err, |(kind, def_id)| Res::Def(kind, def_id)),
552 pub fn type_dependent_defs(
554 ) -> LocalTableInContext<'_, Result<(DefKind, DefId), ErrorReported>> {
555 LocalTableInContext { hir_owner: self.hir_owner, data: &self.type_dependent_defs }
558 pub fn type_dependent_def(&self, id: HirId) -> Option<(DefKind, DefId)> {
559 validate_hir_id_for_typeck_results(self.hir_owner, id);
560 self.type_dependent_defs.get(&id.local_id).cloned().and_then(|r| r.ok())
563 pub fn type_dependent_def_id(&self, id: HirId) -> Option<DefId> {
564 self.type_dependent_def(id).map(|(_, def_id)| def_id)
567 pub fn type_dependent_defs_mut(
569 ) -> LocalTableInContextMut<'_, Result<(DefKind, DefId), ErrorReported>> {
570 LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.type_dependent_defs }
573 pub fn field_indices(&self) -> LocalTableInContext<'_, usize> {
574 LocalTableInContext { hir_owner: self.hir_owner, data: &self.field_indices }
577 pub fn field_indices_mut(&mut self) -> LocalTableInContextMut<'_, usize> {
578 LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.field_indices }
581 pub fn user_provided_types(&self) -> LocalTableInContext<'_, CanonicalUserType<'tcx>> {
582 LocalTableInContext { hir_owner: self.hir_owner, data: &self.user_provided_types }
585 pub fn user_provided_types_mut(
587 ) -> LocalTableInContextMut<'_, CanonicalUserType<'tcx>> {
588 LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.user_provided_types }
591 pub fn node_types(&self) -> LocalTableInContext<'_, Ty<'tcx>> {
592 LocalTableInContext { hir_owner: self.hir_owner, data: &self.node_types }
595 pub fn node_types_mut(&mut self) -> LocalTableInContextMut<'_, Ty<'tcx>> {
596 LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.node_types }
599 pub fn node_type(&self, id: hir::HirId) -> Ty<'tcx> {
600 self.node_type_opt(id).unwrap_or_else(|| {
601 bug!("node_type: no type for node `{}`", tls::with(|tcx| tcx.hir().node_to_string(id)))
605 pub fn node_type_opt(&self, id: hir::HirId) -> Option<Ty<'tcx>> {
606 validate_hir_id_for_typeck_results(self.hir_owner, id);
607 self.node_types.get(&id.local_id).cloned()
610 pub fn node_substs_mut(&mut self) -> LocalTableInContextMut<'_, SubstsRef<'tcx>> {
611 LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.node_substs }
614 pub fn node_substs(&self, id: hir::HirId) -> SubstsRef<'tcx> {
615 validate_hir_id_for_typeck_results(self.hir_owner, id);
616 self.node_substs.get(&id.local_id).cloned().unwrap_or_else(|| InternalSubsts::empty())
619 pub fn node_substs_opt(&self, id: hir::HirId) -> Option<SubstsRef<'tcx>> {
620 validate_hir_id_for_typeck_results(self.hir_owner, id);
621 self.node_substs.get(&id.local_id).cloned()
624 // Returns the type of a pattern as a monotype. Like @expr_ty, this function
625 // doesn't provide type parameter substitutions.
626 pub fn pat_ty(&self, pat: &hir::Pat<'_>) -> Ty<'tcx> {
627 self.node_type(pat.hir_id)
630 // Returns the type of an expression as a monotype.
632 // NB (1): This is the PRE-ADJUSTMENT TYPE for the expression. That is, in
633 // some cases, we insert `Adjustment` annotations such as auto-deref or
634 // auto-ref. The type returned by this function does not consider such
635 // adjustments. See `expr_ty_adjusted()` instead.
637 // NB (2): This type doesn't provide type parameter substitutions; e.g., if you
638 // ask for the type of "id" in "id(3)", it will return "fn(&isize) -> isize"
639 // instead of "fn(ty) -> T with T = isize".
640 pub fn expr_ty(&self, expr: &hir::Expr<'_>) -> Ty<'tcx> {
641 self.node_type(expr.hir_id)
644 pub fn expr_ty_opt(&self, expr: &hir::Expr<'_>) -> Option<Ty<'tcx>> {
645 self.node_type_opt(expr.hir_id)
648 pub fn adjustments(&self) -> LocalTableInContext<'_, Vec<ty::adjustment::Adjustment<'tcx>>> {
649 LocalTableInContext { hir_owner: self.hir_owner, data: &self.adjustments }
652 pub fn adjustments_mut(
654 ) -> LocalTableInContextMut<'_, Vec<ty::adjustment::Adjustment<'tcx>>> {
655 LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.adjustments }
658 pub fn expr_adjustments(&self, expr: &hir::Expr<'_>) -> &[ty::adjustment::Adjustment<'tcx>] {
659 validate_hir_id_for_typeck_results(self.hir_owner, expr.hir_id);
660 self.adjustments.get(&expr.hir_id.local_id).map_or(&[], |a| &a[..])
663 /// Returns the type of `expr`, considering any `Adjustment`
664 /// entry recorded for that expression.
665 pub fn expr_ty_adjusted(&self, expr: &hir::Expr<'_>) -> Ty<'tcx> {
666 self.expr_adjustments(expr).last().map_or_else(|| self.expr_ty(expr), |adj| adj.target)
669 pub fn expr_ty_adjusted_opt(&self, expr: &hir::Expr<'_>) -> Option<Ty<'tcx>> {
670 self.expr_adjustments(expr).last().map(|adj| adj.target).or_else(|| self.expr_ty_opt(expr))
673 pub fn is_method_call(&self, expr: &hir::Expr<'_>) -> bool {
674 // Only paths and method calls/overloaded operators have
675 // entries in type_dependent_defs, ignore the former here.
676 if let hir::ExprKind::Path(_) = expr.kind {
680 matches!(self.type_dependent_defs().get(expr.hir_id), Some(Ok((DefKind::AssocFn, _))))
683 pub fn extract_binding_mode(&self, s: &Session, id: HirId, sp: Span) -> Option<BindingMode> {
684 self.pat_binding_modes().get(id).copied().or_else(|| {
685 s.delay_span_bug(sp, "missing binding mode");
690 pub fn pat_binding_modes(&self) -> LocalTableInContext<'_, BindingMode> {
691 LocalTableInContext { hir_owner: self.hir_owner, data: &self.pat_binding_modes }
694 pub fn pat_binding_modes_mut(&mut self) -> LocalTableInContextMut<'_, BindingMode> {
695 LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.pat_binding_modes }
698 pub fn pat_adjustments(&self) -> LocalTableInContext<'_, Vec<Ty<'tcx>>> {
699 LocalTableInContext { hir_owner: self.hir_owner, data: &self.pat_adjustments }
702 pub fn pat_adjustments_mut(&mut self) -> LocalTableInContextMut<'_, Vec<Ty<'tcx>>> {
703 LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.pat_adjustments }
706 /// For a given closure, returns the iterator of `ty::CapturedPlace`s that are captured
708 pub fn closure_min_captures_flattened(
710 closure_def_id: DefId,
711 ) -> impl Iterator<Item = &ty::CapturedPlace<'tcx>> {
712 self.closure_min_captures
713 .get(&closure_def_id)
714 .map(|closure_min_captures| closure_min_captures.values().flat_map(|v| v.iter()))
719 pub fn closure_kind_origins(&self) -> LocalTableInContext<'_, (Span, HirPlace<'tcx>)> {
720 LocalTableInContext { hir_owner: self.hir_owner, data: &self.closure_kind_origins }
723 pub fn closure_kind_origins_mut(
725 ) -> LocalTableInContextMut<'_, (Span, HirPlace<'tcx>)> {
726 LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.closure_kind_origins }
729 pub fn liberated_fn_sigs(&self) -> LocalTableInContext<'_, ty::FnSig<'tcx>> {
730 LocalTableInContext { hir_owner: self.hir_owner, data: &self.liberated_fn_sigs }
733 pub fn liberated_fn_sigs_mut(&mut self) -> LocalTableInContextMut<'_, ty::FnSig<'tcx>> {
734 LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.liberated_fn_sigs }
737 pub fn fru_field_types(&self) -> LocalTableInContext<'_, Vec<Ty<'tcx>>> {
738 LocalTableInContext { hir_owner: self.hir_owner, data: &self.fru_field_types }
741 pub fn fru_field_types_mut(&mut self) -> LocalTableInContextMut<'_, Vec<Ty<'tcx>>> {
742 LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.fru_field_types }
745 pub fn is_coercion_cast(&self, hir_id: hir::HirId) -> bool {
746 validate_hir_id_for_typeck_results(self.hir_owner, hir_id);
747 self.coercion_casts.contains(&hir_id.local_id)
750 pub fn set_coercion_cast(&mut self, id: ItemLocalId) {
751 self.coercion_casts.insert(id);
754 pub fn coercion_casts(&self) -> &ItemLocalSet {
759 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for TypeckResults<'tcx> {
760 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
761 let ty::TypeckResults {
763 ref type_dependent_defs,
765 ref user_provided_types,
766 ref user_provided_sigs,
770 ref pat_binding_modes,
772 ref closure_kind_origins,
773 ref liberated_fn_sigs,
776 ref used_trait_imports,
778 ref concrete_opaque_types,
779 ref closure_min_captures,
780 ref closure_fake_reads,
781 ref generator_interior_types,
782 ref treat_byte_string_as_slice,
783 ref closure_size_eval,
786 hcx.with_node_id_hashing_mode(NodeIdHashingMode::HashDefPath, |hcx| {
787 hcx.local_def_path_hash(hir_owner);
789 type_dependent_defs.hash_stable(hcx, hasher);
790 field_indices.hash_stable(hcx, hasher);
791 user_provided_types.hash_stable(hcx, hasher);
792 user_provided_sigs.hash_stable(hcx, hasher);
793 node_types.hash_stable(hcx, hasher);
794 node_substs.hash_stable(hcx, hasher);
795 adjustments.hash_stable(hcx, hasher);
796 pat_binding_modes.hash_stable(hcx, hasher);
797 pat_adjustments.hash_stable(hcx, hasher);
799 closure_kind_origins.hash_stable(hcx, hasher);
800 liberated_fn_sigs.hash_stable(hcx, hasher);
801 fru_field_types.hash_stable(hcx, hasher);
802 coercion_casts.hash_stable(hcx, hasher);
803 used_trait_imports.hash_stable(hcx, hasher);
804 tainted_by_errors.hash_stable(hcx, hasher);
805 concrete_opaque_types.hash_stable(hcx, hasher);
806 closure_min_captures.hash_stable(hcx, hasher);
807 closure_fake_reads.hash_stable(hcx, hasher);
808 generator_interior_types.hash_stable(hcx, hasher);
809 treat_byte_string_as_slice.hash_stable(hcx, hasher);
810 closure_size_eval.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(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
828 pub struct CanonicalUserTypeAnnotation<'tcx> {
829 pub user_ty: CanonicalUserType<'tcx>,
831 pub inferred_ty: Ty<'tcx>,
834 /// Canonicalized user type annotation.
835 pub type CanonicalUserType<'tcx> = Canonical<'tcx, UserType<'tcx>>;
837 impl<'tcx> CanonicalUserType<'tcx> {
838 /// Returns `true` if this represents a substitution of the form `[?0, ?1, ?2]`,
839 /// i.e., each thing is mapped to a canonical variable with the same index.
840 pub fn is_identity(&self) -> bool {
842 UserType::Ty(_) => false,
843 UserType::TypeOf(_, user_substs) => {
844 if user_substs.user_self_ty.is_some() {
848 iter::zip(user_substs.substs, BoundVar::new(0)..).all(|(kind, cvar)| {
849 match kind.unpack() {
850 GenericArgKind::Type(ty) => match ty.kind() {
851 ty::Bound(debruijn, b) => {
852 // We only allow a `ty::INNERMOST` index in substitutions.
853 assert_eq!(*debruijn, ty::INNERMOST);
859 GenericArgKind::Lifetime(r) => match r {
860 ty::ReLateBound(debruijn, br) => {
861 // We only allow a `ty::INNERMOST` index in substitutions.
862 assert_eq!(*debruijn, ty::INNERMOST);
868 GenericArgKind::Const(ct) => match ct.val {
869 ty::ConstKind::Bound(debruijn, b) => {
870 // We only allow a `ty::INNERMOST` index in substitutions.
871 assert_eq!(debruijn, ty::INNERMOST);
883 /// A user-given type annotation attached to a constant. These arise
884 /// from constants that are named via paths, like `Foo::<A>::new` and
886 #[derive(Copy, Clone, Debug, PartialEq, TyEncodable, TyDecodable)]
887 #[derive(HashStable, TypeFoldable, Lift)]
888 pub enum UserType<'tcx> {
891 /// The canonical type is the result of `type_of(def_id)` with the
892 /// given substitutions applied.
893 TypeOf(DefId, UserSubsts<'tcx>),
896 impl<'tcx> CommonTypes<'tcx> {
897 fn new(interners: &CtxtInterners<'tcx>) -> CommonTypes<'tcx> {
898 let mk = |ty| interners.intern_ty(ty);
901 unit: mk(Tuple(List::empty())),
905 isize: mk(Int(ty::IntTy::Isize)),
906 i8: mk(Int(ty::IntTy::I8)),
907 i16: mk(Int(ty::IntTy::I16)),
908 i32: mk(Int(ty::IntTy::I32)),
909 i64: mk(Int(ty::IntTy::I64)),
910 i128: mk(Int(ty::IntTy::I128)),
911 usize: mk(Uint(ty::UintTy::Usize)),
912 u8: mk(Uint(ty::UintTy::U8)),
913 u16: mk(Uint(ty::UintTy::U16)),
914 u32: mk(Uint(ty::UintTy::U32)),
915 u64: mk(Uint(ty::UintTy::U64)),
916 u128: mk(Uint(ty::UintTy::U128)),
917 f32: mk(Float(ty::FloatTy::F32)),
918 f64: mk(Float(ty::FloatTy::F64)),
920 self_param: mk(ty::Param(ty::ParamTy { index: 0, name: kw::SelfUpper })),
922 trait_object_dummy_self: mk(Infer(ty::FreshTy(0))),
927 impl<'tcx> CommonLifetimes<'tcx> {
928 fn new(interners: &CtxtInterners<'tcx>) -> CommonLifetimes<'tcx> {
929 let mk = |r| interners.region.intern(r, |r| Interned(interners.arena.alloc(r))).0;
932 re_root_empty: mk(RegionKind::ReEmpty(ty::UniverseIndex::ROOT)),
933 re_static: mk(RegionKind::ReStatic),
934 re_erased: mk(RegionKind::ReErased),
939 impl<'tcx> CommonConsts<'tcx> {
940 fn new(interners: &CtxtInterners<'tcx>, types: &CommonTypes<'tcx>) -> CommonConsts<'tcx> {
941 let mk_const = |c| interners.const_.intern(c, |c| Interned(interners.arena.alloc(c))).0;
944 unit: mk_const(ty::Const {
945 val: ty::ConstKind::Value(ConstValue::Scalar(Scalar::ZST)),
952 // This struct contains information regarding the `ReFree(FreeRegion)` corresponding to a lifetime
955 pub struct FreeRegionInfo {
956 // `LocalDefId` corresponding to FreeRegion
957 pub def_id: LocalDefId,
958 // the bound region corresponding to FreeRegion
959 pub boundregion: ty::BoundRegionKind,
960 // checks if bound region is in Impl Item
961 pub is_impl_item: bool,
964 /// The central data structure of the compiler. It stores references
965 /// to the various **arenas** and also houses the results of the
966 /// various **compiler queries** that have been performed. See the
967 /// [rustc dev guide] for more details.
969 /// [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/ty.html
970 #[derive(Copy, Clone)]
971 #[rustc_diagnostic_item = "TyCtxt"]
972 #[cfg_attr(not(bootstrap), rustc_pass_by_value)]
973 pub struct TyCtxt<'tcx> {
974 gcx: &'tcx GlobalCtxt<'tcx>,
977 impl<'tcx> Deref for TyCtxt<'tcx> {
978 type Target = &'tcx GlobalCtxt<'tcx>;
980 fn deref(&self) -> &Self::Target {
985 pub struct GlobalCtxt<'tcx> {
986 pub arena: &'tcx WorkerLocal<Arena<'tcx>>,
988 interners: CtxtInterners<'tcx>,
990 pub sess: &'tcx Session,
992 /// This only ever stores a `LintStore` but we don't want a dependency on that type here.
994 /// FIXME(Centril): consider `dyn LintStoreMarker` once
995 /// we can upcast to `Any` for some additional type safety.
996 pub lint_store: Lrc<dyn Any + sync::Sync + sync::Send>,
998 pub dep_graph: DepGraph,
1000 pub prof: SelfProfilerRef,
1002 /// Common types, pre-interned for your convenience.
1003 pub types: CommonTypes<'tcx>,
1005 /// Common lifetimes, pre-interned for your convenience.
1006 pub lifetimes: CommonLifetimes<'tcx>,
1008 /// Common consts, pre-interned for your convenience.
1009 pub consts: CommonConsts<'tcx>,
1011 /// Output of the resolver.
1012 pub(crate) untracked_resolutions: ty::ResolverOutputs,
1014 pub(crate) untracked_crate: &'tcx hir::Crate<'tcx>,
1016 /// This provides access to the incremental compilation on-disk cache for query results.
1017 /// Do not access this directly. It is only meant to be used by
1018 /// `DepGraph::try_mark_green()` and the query infrastructure.
1019 /// This is `None` if we are not incremental compilation mode
1020 pub on_disk_cache: Option<&'tcx dyn OnDiskCache<'tcx>>,
1022 pub queries: &'tcx dyn query::QueryEngine<'tcx>,
1023 pub query_caches: query::QueryCaches<'tcx>,
1024 query_kinds: &'tcx [DepKindStruct],
1026 // Internal caches for metadata decoding. No need to track deps on this.
1027 pub ty_rcache: Lock<FxHashMap<ty::CReaderCacheKey, Ty<'tcx>>>,
1028 pub pred_rcache: Lock<FxHashMap<ty::CReaderCacheKey, Predicate<'tcx>>>,
1030 /// Caches the results of trait selection. This cache is used
1031 /// for things that do not have to do with the parameters in scope.
1032 pub selection_cache: traits::SelectionCache<'tcx>,
1034 /// Caches the results of trait evaluation. This cache is used
1035 /// for things that do not have to do with the parameters in scope.
1036 /// Merge this with `selection_cache`?
1037 pub evaluation_cache: traits::EvaluationCache<'tcx>,
1039 /// The definite name of the current crate after taking into account
1040 /// attributes, commandline parameters, etc.
1043 /// Data layout specification for the current target.
1044 pub data_layout: TargetDataLayout,
1046 /// Stores memory for globals (statics/consts).
1047 pub(crate) alloc_map: Lock<interpret::AllocMap<'tcx>>,
1049 output_filenames: Arc<OutputFilenames>,
1052 impl<'tcx> TyCtxt<'tcx> {
1053 pub fn typeck_opt_const_arg(
1055 def: ty::WithOptConstParam<LocalDefId>,
1056 ) -> &'tcx TypeckResults<'tcx> {
1057 if let Some(param_did) = def.const_param_did {
1058 self.typeck_const_arg((def.did, param_did))
1060 self.typeck(def.did)
1064 pub fn alloc_steal_thir(self, thir: Thir<'tcx>) -> &'tcx Steal<Thir<'tcx>> {
1065 self.arena.alloc(Steal::new(thir))
1068 pub fn alloc_steal_mir(self, mir: Body<'tcx>) -> &'tcx Steal<Body<'tcx>> {
1069 self.arena.alloc(Steal::new(mir))
1072 pub fn alloc_steal_promoted(
1074 promoted: IndexVec<Promoted, Body<'tcx>>,
1075 ) -> &'tcx Steal<IndexVec<Promoted, Body<'tcx>>> {
1076 self.arena.alloc(Steal::new(promoted))
1079 pub fn alloc_adt_def(
1083 variants: IndexVec<VariantIdx, ty::VariantDef>,
1085 ) -> &'tcx ty::AdtDef {
1086 self.intern_adt_def(ty::AdtDef::new(self, did, kind, variants, repr))
1089 /// Allocates a read-only byte or string literal for `mir::interpret`.
1090 pub fn allocate_bytes(self, bytes: &[u8]) -> interpret::AllocId {
1091 // Create an allocation that just contains these bytes.
1092 let alloc = interpret::Allocation::from_bytes_byte_aligned_immutable(bytes);
1093 let alloc = self.intern_const_alloc(alloc);
1094 self.create_memory_alloc(alloc)
1097 /// Returns a range of the start/end indices specified with the
1098 /// `rustc_layout_scalar_valid_range` attribute.
1099 // FIXME(eddyb) this is an awkward spot for this method, maybe move it?
1100 pub fn layout_scalar_valid_range(self, def_id: DefId) -> (Bound<u128>, Bound<u128>) {
1101 let attrs = self.get_attrs(def_id);
1103 let attr = match attrs.iter().find(|a| a.has_name(name)) {
1105 None => return Bound::Unbounded,
1107 debug!("layout_scalar_valid_range: attr={:?}", attr);
1110 ast::NestedMetaItem::Literal(ast::Lit {
1111 kind: ast::LitKind::Int(a, _), ..
1114 ) = attr.meta_item_list().as_deref()
1119 .delay_span_bug(attr.span, "invalid rustc_layout_scalar_valid_range attribute");
1124 get(sym::rustc_layout_scalar_valid_range_start),
1125 get(sym::rustc_layout_scalar_valid_range_end),
1129 pub fn lift<T: Lift<'tcx>>(self, value: T) -> Option<T::Lifted> {
1130 value.lift_to_tcx(self)
1133 /// Creates a type context and call the closure with a `TyCtxt` reference
1134 /// to the context. The closure enforces that the type context and any interned
1135 /// value (types, substs, etc.) can only be used while `ty::tls` has a valid
1136 /// reference to the context, to allow formatting values that need it.
1137 pub fn create_global_ctxt(
1139 lint_store: Lrc<dyn Any + sync::Send + sync::Sync>,
1140 arena: &'tcx WorkerLocal<Arena<'tcx>>,
1141 resolutions: ty::ResolverOutputs,
1142 krate: &'tcx hir::Crate<'tcx>,
1143 dep_graph: DepGraph,
1144 on_disk_cache: Option<&'tcx dyn OnDiskCache<'tcx>>,
1145 queries: &'tcx dyn query::QueryEngine<'tcx>,
1146 query_kinds: &'tcx [DepKindStruct],
1148 output_filenames: OutputFilenames,
1149 ) -> GlobalCtxt<'tcx> {
1150 let data_layout = TargetDataLayout::parse(&s.target).unwrap_or_else(|err| {
1153 let interners = CtxtInterners::new(arena);
1154 let common_types = CommonTypes::new(&interners);
1155 let common_lifetimes = CommonLifetimes::new(&interners);
1156 let common_consts = CommonConsts::new(&interners, &common_types);
1164 untracked_resolutions: resolutions,
1165 prof: s.prof.clone(),
1166 types: common_types,
1167 lifetimes: common_lifetimes,
1168 consts: common_consts,
1169 untracked_crate: krate,
1172 query_caches: query::QueryCaches::default(),
1174 ty_rcache: Default::default(),
1175 pred_rcache: Default::default(),
1176 selection_cache: Default::default(),
1177 evaluation_cache: Default::default(),
1178 crate_name: Symbol::intern(crate_name),
1180 alloc_map: Lock::new(interpret::AllocMap::new()),
1181 output_filenames: Arc::new(output_filenames),
1185 crate fn query_kind(self, k: DepKind) -> &'tcx DepKindStruct {
1186 &self.query_kinds[k as usize]
1189 /// Constructs a `TyKind::Error` type and registers a `delay_span_bug` to ensure it gets used.
1191 pub fn ty_error(self) -> Ty<'tcx> {
1192 self.ty_error_with_message(DUMMY_SP, "TyKind::Error constructed but no error reported")
1195 /// Constructs a `TyKind::Error` type and registers a `delay_span_bug` with the given `msg` to
1196 /// ensure it gets used.
1198 pub fn ty_error_with_message<S: Into<MultiSpan>>(self, span: S, msg: &str) -> Ty<'tcx> {
1199 self.sess.delay_span_bug(span, msg);
1200 self.mk_ty(Error(DelaySpanBugEmitted(())))
1203 /// Like [TyCtxt::ty_error] but for constants.
1205 pub fn const_error(self, ty: Ty<'tcx>) -> &'tcx Const<'tcx> {
1206 self.const_error_with_message(
1209 "ty::ConstKind::Error constructed but no error reported",
1213 /// Like [TyCtxt::ty_error_with_message] but for constants.
1215 pub fn const_error_with_message<S: Into<MultiSpan>>(
1220 ) -> &'tcx Const<'tcx> {
1221 self.sess.delay_span_bug(span, msg);
1222 self.mk_const(ty::Const { val: ty::ConstKind::Error(DelaySpanBugEmitted(())), ty })
1225 pub fn consider_optimizing<T: Fn() -> String>(self, msg: T) -> bool {
1226 let cname = self.crate_name(LOCAL_CRATE);
1227 self.sess.consider_optimizing(cname.as_str(), msg)
1230 /// Obtain all lang items of this crate and all dependencies (recursively)
1231 pub fn lang_items(self) -> &'tcx rustc_hir::lang_items::LanguageItems {
1232 self.get_lang_items(())
1235 /// Obtain the given diagnostic item's `DefId`. Use `is_diagnostic_item` if you just want to
1236 /// compare against another `DefId`, since `is_diagnostic_item` is cheaper.
1237 pub fn get_diagnostic_item(self, name: Symbol) -> Option<DefId> {
1238 self.all_diagnostic_items(()).name_to_id.get(&name).copied()
1241 /// Obtain the diagnostic item's name
1242 pub fn get_diagnostic_name(self, id: DefId) -> Option<Symbol> {
1243 self.diagnostic_items(id.krate).id_to_name.get(&id).copied()
1246 /// Check whether the diagnostic item with the given `name` has the given `DefId`.
1247 pub fn is_diagnostic_item(self, name: Symbol, did: DefId) -> bool {
1248 self.diagnostic_items(did.krate).name_to_id.get(&name) == Some(&did)
1251 pub fn stability(self) -> &'tcx stability::Index<'tcx> {
1252 self.stability_index(())
1255 pub fn features(self) -> &'tcx rustc_feature::Features {
1256 self.features_query(())
1259 pub fn def_key(self, id: DefId) -> rustc_hir::definitions::DefKey {
1260 // Accessing the DefKey is ok, since it is part of DefPathHash.
1261 if let Some(id) = id.as_local() {
1262 self.untracked_resolutions.definitions.def_key(id)
1264 self.untracked_resolutions.cstore.def_key(id)
1268 /// Converts a `DefId` into its fully expanded `DefPath` (every
1269 /// `DefId` is really just an interned `DefPath`).
1271 /// Note that if `id` is not local to this crate, the result will
1272 /// be a non-local `DefPath`.
1273 pub fn def_path(self, id: DefId) -> rustc_hir::definitions::DefPath {
1274 // Accessing the DefPath is ok, since it is part of DefPathHash.
1275 if let Some(id) = id.as_local() {
1276 self.untracked_resolutions.definitions.def_path(id)
1278 self.untracked_resolutions.cstore.def_path(id)
1283 pub fn def_path_hash(self, def_id: DefId) -> rustc_hir::definitions::DefPathHash {
1284 // Accessing the DefPathHash is ok, it is incr. comp. stable.
1285 if let Some(def_id) = def_id.as_local() {
1286 self.untracked_resolutions.definitions.def_path_hash(def_id)
1288 self.untracked_resolutions.cstore.def_path_hash(def_id)
1293 pub fn stable_crate_id(self, crate_num: CrateNum) -> StableCrateId {
1294 if crate_num == LOCAL_CRATE {
1295 self.sess.local_stable_crate_id()
1297 self.untracked_resolutions.cstore.stable_crate_id(crate_num)
1301 /// Maps a StableCrateId to the corresponding CrateNum. This method assumes
1302 /// that the crate in question has already been loaded by the CrateStore.
1304 pub fn stable_crate_id_to_crate_num(self, stable_crate_id: StableCrateId) -> CrateNum {
1305 if stable_crate_id == self.sess.local_stable_crate_id() {
1308 self.untracked_resolutions.cstore.stable_crate_id_to_crate_num(stable_crate_id)
1312 /// Converts a `DefPathHash` to its corresponding `DefId` in the current compilation
1313 /// session, if it still exists. This is used during incremental compilation to
1314 /// turn a deserialized `DefPathHash` into its current `DefId`.
1315 pub fn def_path_hash_to_def_id(self, hash: DefPathHash, err: &mut dyn FnMut() -> !) -> DefId {
1316 debug!("def_path_hash_to_def_id({:?})", hash);
1318 let stable_crate_id = hash.stable_crate_id();
1320 // If this is a DefPathHash from the local crate, we can look up the
1321 // DefId in the tcx's `Definitions`.
1322 if stable_crate_id == self.sess.local_stable_crate_id() {
1323 self.untracked_resolutions
1325 .local_def_path_hash_to_def_id(hash, err)
1328 // If this is a DefPathHash from an upstream crate, let the CrateStore map
1330 let cstore = &self.untracked_resolutions.cstore;
1331 let cnum = cstore.stable_crate_id_to_crate_num(stable_crate_id);
1332 cstore.def_path_hash_to_def_id(cnum, hash)
1336 pub fn def_path_debug_str(self, def_id: DefId) -> String {
1337 // We are explicitly not going through queries here in order to get
1338 // crate name and stable crate id since this code is called from debug!()
1339 // statements within the query system and we'd run into endless
1340 // recursion otherwise.
1341 let (crate_name, stable_crate_id) = if def_id.is_local() {
1342 (self.crate_name, self.sess.local_stable_crate_id())
1344 let cstore = &self.untracked_resolutions.cstore;
1345 (cstore.crate_name(def_id.krate), cstore.stable_crate_id(def_id.krate))
1351 // Don't print the whole stable crate id. That's just
1352 // annoying in debug output.
1353 &(format!("{:08x}", stable_crate_id.to_u64()))[..4],
1354 self.def_path(def_id).to_string_no_crate_verbose()
1358 /// Note that this is *untracked* and should only be used within the query
1359 /// system if the result is otherwise tracked through queries
1360 pub fn cstore_untracked(self) -> &'tcx ty::CrateStoreDyn {
1361 &*self.untracked_resolutions.cstore
1364 /// Note that this is *untracked* and should only be used within the query
1365 /// system if the result is otherwise tracked through queries
1366 pub fn definitions_untracked(self) -> &'tcx hir::definitions::Definitions {
1367 &self.untracked_resolutions.definitions
1371 pub fn create_stable_hashing_context(self) -> StableHashingContext<'tcx> {
1372 let resolutions = &self.gcx.untracked_resolutions;
1373 StableHashingContext::new(self.sess, &resolutions.definitions, &*resolutions.cstore)
1377 pub fn create_no_span_stable_hashing_context(self) -> StableHashingContext<'tcx> {
1378 let resolutions = &self.gcx.untracked_resolutions;
1379 StableHashingContext::ignore_spans(
1381 &resolutions.definitions,
1382 &*resolutions.cstore,
1386 pub fn serialize_query_result_cache(self, encoder: &mut FileEncoder) -> FileEncodeResult {
1387 self.on_disk_cache.as_ref().map_or(Ok(()), |c| c.serialize(self, encoder))
1390 /// If `true`, we should use the MIR-based borrowck, but also
1391 /// fall back on the AST borrowck if the MIR-based one errors.
1392 pub fn migrate_borrowck(self) -> bool {
1393 self.borrowck_mode().migrate()
1396 /// What mode(s) of borrowck should we run? AST? MIR? both?
1397 /// (Also considers the `#![feature(nll)]` setting.)
1398 pub fn borrowck_mode(self) -> BorrowckMode {
1399 // Here are the main constraints we need to deal with:
1401 // 1. An opts.borrowck_mode of `BorrowckMode::Migrate` is
1402 // synonymous with no `-Z borrowck=...` flag at all.
1404 // 2. We want to allow developers on the Nightly channel
1405 // to opt back into the "hard error" mode for NLL,
1406 // (which they can do via specifying `#![feature(nll)]`
1407 // explicitly in their crate).
1409 // So, this precedence list is how pnkfelix chose to work with
1410 // the above constraints:
1412 // * `#![feature(nll)]` *always* means use NLL with hard
1413 // errors. (To simplify the code here, it now even overrides
1414 // a user's attempt to specify `-Z borrowck=compare`, which
1415 // we arguably do not need anymore and should remove.)
1417 // * Otherwise, if no `-Z borrowck=...` then use migrate mode
1419 // * Otherwise, use the behavior requested via `-Z borrowck=...`
1421 if self.features().nll {
1422 return BorrowckMode::Mir;
1425 self.sess.opts.borrowck_mode
1428 /// If `true`, we should use lazy normalization for constants, otherwise
1429 /// we still evaluate them eagerly.
1431 pub fn lazy_normalization(self) -> bool {
1432 let features = self.features();
1433 // Note: We only use lazy normalization for generic const expressions.
1434 features.generic_const_exprs
1438 pub fn local_crate_exports_generics(self) -> bool {
1439 debug_assert!(self.sess.opts.share_generics());
1441 self.sess.crate_types().iter().any(|crate_type| {
1443 CrateType::Executable
1444 | CrateType::Staticlib
1445 | CrateType::ProcMacro
1446 | CrateType::Cdylib => false,
1448 // FIXME rust-lang/rust#64319, rust-lang/rust#64872:
1449 // We want to block export of generics from dylibs,
1450 // but we must fix rust-lang/rust#65890 before we can
1451 // do that robustly.
1452 CrateType::Dylib => true,
1454 CrateType::Rlib => true,
1459 // Returns the `DefId` and the `BoundRegionKind` corresponding to the given region.
1460 pub fn is_suitable_region(self, region: Region<'tcx>) -> Option<FreeRegionInfo> {
1461 let (suitable_region_binding_scope, bound_region) = match *region {
1462 ty::ReFree(ref free_region) => {
1463 (free_region.scope.expect_local(), free_region.bound_region)
1465 ty::ReEarlyBound(ref ebr) => (
1466 self.parent(ebr.def_id).unwrap().expect_local(),
1467 ty::BoundRegionKind::BrNamed(ebr.def_id, ebr.name),
1469 _ => return None, // not a free region
1472 let is_impl_item = match self.hir().find_by_def_id(suitable_region_binding_scope) {
1473 Some(Node::Item(..) | Node::TraitItem(..)) => false,
1474 Some(Node::ImplItem(..)) => {
1475 self.is_bound_region_in_impl_item(suitable_region_binding_scope)
1480 Some(FreeRegionInfo {
1481 def_id: suitable_region_binding_scope,
1482 boundregion: bound_region,
1487 /// Given a `DefId` for an `fn`, return all the `dyn` and `impl` traits in its return type.
1488 pub fn return_type_impl_or_dyn_traits(
1490 scope_def_id: LocalDefId,
1491 ) -> Vec<&'tcx hir::Ty<'tcx>> {
1492 let hir_id = self.hir().local_def_id_to_hir_id(scope_def_id);
1493 let hir_output = match self.hir().fn_decl_by_hir_id(hir_id) {
1494 Some(hir::FnDecl { output: hir::FnRetTy::Return(ty), .. }) => ty,
1498 let mut v = TraitObjectVisitor(vec![], self.hir());
1499 v.visit_ty(hir_output);
1503 pub fn return_type_impl_trait(self, scope_def_id: LocalDefId) -> Option<(Ty<'tcx>, Span)> {
1504 // `type_of()` will fail on these (#55796, #86483), so only allow `fn`s or closures.
1505 match self.hir().get_by_def_id(scope_def_id) {
1506 Node::Item(&hir::Item { kind: ItemKind::Fn(..), .. }) => {}
1507 Node::TraitItem(&hir::TraitItem { kind: TraitItemKind::Fn(..), .. }) => {}
1508 Node::ImplItem(&hir::ImplItem { kind: ImplItemKind::Fn(..), .. }) => {}
1509 Node::Expr(&hir::Expr { kind: ExprKind::Closure(..), .. }) => {}
1513 let ret_ty = self.type_of(scope_def_id);
1514 match ret_ty.kind() {
1515 ty::FnDef(_, _) => {
1516 let sig = ret_ty.fn_sig(self);
1517 let output = self.erase_late_bound_regions(sig.output());
1518 if output.is_impl_trait() {
1519 let hir_id = self.hir().local_def_id_to_hir_id(scope_def_id);
1520 let fn_decl = self.hir().fn_decl_by_hir_id(hir_id).unwrap();
1521 Some((output, fn_decl.output.span()))
1530 // Checks if the bound region is in Impl Item.
1531 pub fn is_bound_region_in_impl_item(self, suitable_region_binding_scope: LocalDefId) -> bool {
1533 self.associated_item(suitable_region_binding_scope.to_def_id()).container.id();
1534 if self.impl_trait_ref(container_id).is_some() {
1535 // For now, we do not try to target impls of traits. This is
1536 // because this message is going to suggest that the user
1537 // change the fn signature, but they may not be free to do so,
1538 // since the signature must match the trait.
1540 // FIXME(#42706) -- in some cases, we could do better here.
1546 /// Determines whether identifiers in the assembly have strict naming rules.
1547 /// Currently, only NVPTX* targets need it.
1548 pub fn has_strict_asm_symbol_naming(self) -> bool {
1549 self.sess.target.arch.contains("nvptx")
1552 /// Returns `&'static core::panic::Location<'static>`.
1553 pub fn caller_location_ty(self) -> Ty<'tcx> {
1555 self.lifetimes.re_static,
1556 self.type_of(self.require_lang_item(LangItem::PanicLocation, None))
1557 .subst(self, self.mk_substs([self.lifetimes.re_static.into()].iter())),
1561 /// Returns a displayable description and article for the given `def_id` (e.g. `("a", "struct")`).
1562 pub fn article_and_description(self, def_id: DefId) -> (&'static str, &'static str) {
1563 match self.def_kind(def_id) {
1564 DefKind::Generator => match self.generator_kind(def_id).unwrap() {
1565 rustc_hir::GeneratorKind::Async(..) => ("an", "async closure"),
1566 rustc_hir::GeneratorKind::Gen => ("a", "generator"),
1568 def_kind => (def_kind.article(), def_kind.descr(def_id)),
1572 pub fn type_length_limit(self) -> Limit {
1573 self.limits(()).type_length_limit
1576 pub fn recursion_limit(self) -> Limit {
1577 self.limits(()).recursion_limit
1580 pub fn move_size_limit(self) -> Limit {
1581 self.limits(()).move_size_limit
1584 pub fn const_eval_limit(self) -> Limit {
1585 self.limits(()).const_eval_limit
1588 pub fn all_traits(self) -> impl Iterator<Item = DefId> + 'tcx {
1589 iter::once(LOCAL_CRATE)
1590 .chain(self.crates(()).iter().copied())
1591 .flat_map(move |cnum| self.traits_in_crate(cnum).iter().copied())
1595 /// A trait implemented for all `X<'a>` types that can be safely and
1596 /// efficiently converted to `X<'tcx>` as long as they are part of the
1597 /// provided `TyCtxt<'tcx>`.
1598 /// This can be done, for example, for `Ty<'tcx>` or `SubstsRef<'tcx>`
1599 /// by looking them up in their respective interners.
1601 /// However, this is still not the best implementation as it does
1602 /// need to compare the components, even for interned values.
1603 /// It would be more efficient if `TypedArena` provided a way to
1604 /// determine whether the address is in the allocated range.
1606 /// `None` is returned if the value or one of the components is not part
1607 /// of the provided context.
1608 /// For `Ty`, `None` can be returned if either the type interner doesn't
1609 /// contain the `TyKind` key or if the address of the interned
1610 /// pointer differs. The latter case is possible if a primitive type,
1611 /// e.g., `()` or `u8`, was interned in a different context.
1612 pub trait Lift<'tcx>: fmt::Debug {
1613 type Lifted: fmt::Debug + 'tcx;
1614 fn lift_to_tcx(self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted>;
1617 macro_rules! nop_lift {
1618 ($set:ident; $ty:ty => $lifted:ty) => {
1619 impl<'a, 'tcx> Lift<'tcx> for $ty {
1620 type Lifted = $lifted;
1621 fn lift_to_tcx(self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
1622 if tcx.interners.$set.contains_pointer_to(&Interned(self)) {
1623 Some(unsafe { mem::transmute(self) })
1632 macro_rules! nop_list_lift {
1633 ($set:ident; $ty:ty => $lifted:ty) => {
1634 impl<'a, 'tcx> Lift<'tcx> for &'a List<$ty> {
1635 type Lifted = &'tcx List<$lifted>;
1636 fn lift_to_tcx(self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
1637 if self.is_empty() {
1638 return Some(List::empty());
1640 if tcx.interners.$set.contains_pointer_to(&Interned(self)) {
1641 Some(unsafe { mem::transmute(self) })
1650 nop_lift! {type_; Ty<'a> => Ty<'tcx>}
1651 nop_lift! {region; Region<'a> => Region<'tcx>}
1652 nop_lift! {const_; &'a Const<'a> => &'tcx Const<'tcx>}
1653 nop_lift! {const_allocation; &'a Allocation => &'tcx Allocation}
1654 nop_lift! {predicate; &'a PredicateInner<'a> => &'tcx PredicateInner<'tcx>}
1656 nop_list_lift! {type_list; Ty<'a> => Ty<'tcx>}
1657 nop_list_lift! {poly_existential_predicates; ty::Binder<'a, ExistentialPredicate<'a>> => ty::Binder<'tcx, ExistentialPredicate<'tcx>>}
1658 nop_list_lift! {predicates; Predicate<'a> => Predicate<'tcx>}
1659 nop_list_lift! {canonical_var_infos; CanonicalVarInfo<'a> => CanonicalVarInfo<'tcx>}
1660 nop_list_lift! {projs; ProjectionKind => ProjectionKind}
1661 nop_list_lift! {bound_variable_kinds; ty::BoundVariableKind => ty::BoundVariableKind}
1663 // This is the impl for `&'a InternalSubsts<'a>`.
1664 nop_list_lift! {substs; GenericArg<'a> => GenericArg<'tcx>}
1666 CloneLiftImpls! { for<'tcx> { Constness, traits::WellFormedLoc, } }
1669 use super::{ptr_eq, GlobalCtxt, TyCtxt};
1671 use crate::dep_graph::{DepKind, TaskDepsRef};
1672 use crate::ty::query;
1673 use rustc_data_structures::sync::{self, Lock};
1674 use rustc_data_structures::thin_vec::ThinVec;
1675 use rustc_errors::Diagnostic;
1678 #[cfg(not(parallel_compiler))]
1679 use std::cell::Cell;
1681 #[cfg(parallel_compiler)]
1682 use rustc_rayon_core as rayon_core;
1684 /// This is the implicit state of rustc. It contains the current
1685 /// `TyCtxt` and query. It is updated when creating a local interner or
1686 /// executing a new query. Whenever there's a `TyCtxt` value available
1687 /// you should also have access to an `ImplicitCtxt` through the functions
1690 pub struct ImplicitCtxt<'a, 'tcx> {
1691 /// The current `TyCtxt`.
1692 pub tcx: TyCtxt<'tcx>,
1694 /// The current query job, if any. This is updated by `JobOwner::start` in
1695 /// `ty::query::plumbing` when executing a query.
1696 pub query: Option<query::QueryJobId<DepKind>>,
1698 /// Where to store diagnostics for the current query job, if any.
1699 /// This is updated by `JobOwner::start` in `ty::query::plumbing` when executing a query.
1700 pub diagnostics: Option<&'a Lock<ThinVec<Diagnostic>>>,
1702 /// Used to prevent layout from recursing too deeply.
1703 pub layout_depth: usize,
1705 /// The current dep graph task. This is used to add dependencies to queries
1706 /// when executing them.
1707 pub task_deps: TaskDepsRef<'a>,
1710 impl<'a, 'tcx> ImplicitCtxt<'a, 'tcx> {
1711 pub fn new(gcx: &'tcx GlobalCtxt<'tcx>) -> Self {
1712 let tcx = TyCtxt { gcx };
1718 task_deps: TaskDepsRef::Ignore,
1723 /// Sets Rayon's thread-local variable, which is preserved for Rayon jobs
1724 /// to `value` during the call to `f`. It is restored to its previous value after.
1725 /// This is used to set the pointer to the new `ImplicitCtxt`.
1726 #[cfg(parallel_compiler)]
1728 fn set_tlv<F: FnOnce() -> R, R>(value: usize, f: F) -> R {
1729 rayon_core::tlv::with(value, f)
1732 /// Gets Rayon's thread-local variable, which is preserved for Rayon jobs.
1733 /// This is used to get the pointer to the current `ImplicitCtxt`.
1734 #[cfg(parallel_compiler)]
1736 pub fn get_tlv() -> usize {
1737 rayon_core::tlv::get()
1740 #[cfg(not(parallel_compiler))]
1742 /// A thread local variable that stores a pointer to the current `ImplicitCtxt`.
1743 static TLV: Cell<usize> = const { Cell::new(0) };
1746 /// Sets TLV to `value` during the call to `f`.
1747 /// It is restored to its previous value after.
1748 /// This is used to set the pointer to the new `ImplicitCtxt`.
1749 #[cfg(not(parallel_compiler))]
1751 fn set_tlv<F: FnOnce() -> R, R>(value: usize, f: F) -> R {
1752 let old = get_tlv();
1753 let _reset = rustc_data_structures::OnDrop(move || TLV.with(|tlv| tlv.set(old)));
1754 TLV.with(|tlv| tlv.set(value));
1758 /// Gets the pointer to the current `ImplicitCtxt`.
1759 #[cfg(not(parallel_compiler))]
1761 fn get_tlv() -> usize {
1762 TLV.with(|tlv| tlv.get())
1765 /// Sets `context` as the new current `ImplicitCtxt` for the duration of the function `f`.
1767 pub fn enter_context<'a, 'tcx, F, R>(context: &ImplicitCtxt<'a, 'tcx>, f: F) -> R
1769 F: FnOnce(&ImplicitCtxt<'a, 'tcx>) -> R,
1771 set_tlv(context as *const _ as usize, || f(&context))
1774 /// Allows access to the current `ImplicitCtxt` in a closure if one is available.
1776 pub fn with_context_opt<F, R>(f: F) -> R
1778 F: for<'a, 'tcx> FnOnce(Option<&ImplicitCtxt<'a, 'tcx>>) -> R,
1780 let context = get_tlv();
1784 // We could get an `ImplicitCtxt` pointer from another thread.
1785 // Ensure that `ImplicitCtxt` is `Sync`.
1786 sync::assert_sync::<ImplicitCtxt<'_, '_>>();
1788 unsafe { f(Some(&*(context as *const ImplicitCtxt<'_, '_>))) }
1792 /// Allows access to the current `ImplicitCtxt`.
1793 /// Panics if there is no `ImplicitCtxt` available.
1795 pub fn with_context<F, R>(f: F) -> R
1797 F: for<'a, 'tcx> FnOnce(&ImplicitCtxt<'a, 'tcx>) -> R,
1799 with_context_opt(|opt_context| f(opt_context.expect("no ImplicitCtxt stored in tls")))
1802 /// Allows access to the current `ImplicitCtxt` whose tcx field is the same as the tcx argument
1803 /// passed in. This means the closure is given an `ImplicitCtxt` with the same `'tcx` lifetime
1804 /// as the `TyCtxt` passed in.
1805 /// This will panic if you pass it a `TyCtxt` which is different from the current
1806 /// `ImplicitCtxt`'s `tcx` field.
1808 pub fn with_related_context<'tcx, F, R>(tcx: TyCtxt<'tcx>, f: F) -> R
1810 F: FnOnce(&ImplicitCtxt<'_, 'tcx>) -> R,
1812 with_context(|context| unsafe {
1813 assert!(ptr_eq(context.tcx.gcx, tcx.gcx));
1814 let context: &ImplicitCtxt<'_, '_> = mem::transmute(context);
1819 /// Allows access to the `TyCtxt` in the current `ImplicitCtxt`.
1820 /// Panics if there is no `ImplicitCtxt` available.
1822 pub fn with<F, R>(f: F) -> R
1824 F: for<'tcx> FnOnce(TyCtxt<'tcx>) -> R,
1826 with_context(|context| f(context.tcx))
1829 /// Allows access to the `TyCtxt` in the current `ImplicitCtxt`.
1830 /// The closure is passed None if there is no `ImplicitCtxt` available.
1832 pub fn with_opt<F, R>(f: F) -> R
1834 F: for<'tcx> FnOnce(Option<TyCtxt<'tcx>>) -> R,
1836 with_context_opt(|opt_context| f(opt_context.map(|context| context.tcx)))
1840 macro_rules! sty_debug_print {
1841 ($fmt: expr, $ctxt: expr, $($variant: ident),*) => {{
1842 // Curious inner module to allow variant names to be used as
1844 #[allow(non_snake_case)]
1846 use crate::ty::{self, TyCtxt};
1847 use crate::ty::context::Interned;
1849 #[derive(Copy, Clone)]
1858 pub fn go(fmt: &mut std::fmt::Formatter<'_>, tcx: TyCtxt<'_>) -> std::fmt::Result {
1859 let mut total = DebugStat {
1866 $(let mut $variant = total;)*
1868 let shards = tcx.interners.type_.lock_shards();
1869 let types = shards.iter().flat_map(|shard| shard.keys());
1870 for &Interned(t) in types {
1871 let variant = match t.kind() {
1872 ty::Bool | ty::Char | ty::Int(..) | ty::Uint(..) |
1873 ty::Float(..) | ty::Str | ty::Never => continue,
1874 ty::Error(_) => /* unimportant */ continue,
1875 $(ty::$variant(..) => &mut $variant,)*
1877 let lt = t.flags().intersects(ty::TypeFlags::HAS_RE_INFER);
1878 let ty = t.flags().intersects(ty::TypeFlags::HAS_TY_INFER);
1879 let ct = t.flags().intersects(ty::TypeFlags::HAS_CT_INFER);
1883 if lt { total.lt_infer += 1; variant.lt_infer += 1 }
1884 if ty { total.ty_infer += 1; variant.ty_infer += 1 }
1885 if ct { total.ct_infer += 1; variant.ct_infer += 1 }
1886 if lt && ty && ct { total.all_infer += 1; variant.all_infer += 1 }
1888 writeln!(fmt, "Ty interner total ty lt ct all")?;
1889 $(writeln!(fmt, " {:18}: {uses:6} {usespc:4.1}%, \
1890 {ty:4.1}% {lt:5.1}% {ct:4.1}% {all:4.1}%",
1891 stringify!($variant),
1892 uses = $variant.total,
1893 usespc = $variant.total as f64 * 100.0 / total.total as f64,
1894 ty = $variant.ty_infer as f64 * 100.0 / total.total as f64,
1895 lt = $variant.lt_infer as f64 * 100.0 / total.total as f64,
1896 ct = $variant.ct_infer as f64 * 100.0 / total.total as f64,
1897 all = $variant.all_infer as f64 * 100.0 / total.total as f64)?;
1899 writeln!(fmt, " total {uses:6} \
1900 {ty:4.1}% {lt:5.1}% {ct:4.1}% {all:4.1}%",
1902 ty = total.ty_infer as f64 * 100.0 / total.total as f64,
1903 lt = total.lt_infer as f64 * 100.0 / total.total as f64,
1904 ct = total.ct_infer as f64 * 100.0 / total.total as f64,
1905 all = total.all_infer as f64 * 100.0 / total.total as f64)
1909 inner::go($fmt, $ctxt)
1913 impl<'tcx> TyCtxt<'tcx> {
1914 pub fn debug_stats(self) -> impl std::fmt::Debug + 'tcx {
1915 struct DebugStats<'tcx>(TyCtxt<'tcx>);
1917 impl<'tcx> std::fmt::Debug for DebugStats<'tcx> {
1918 fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1943 writeln!(fmt, "InternalSubsts interner: #{}", self.0.interners.substs.len())?;
1944 writeln!(fmt, "Region interner: #{}", self.0.interners.region.len())?;
1945 writeln!(fmt, "Stability interner: #{}", self.0.interners.stability.len())?;
1948 "Const Stability interner: #{}",
1949 self.0.interners.const_stability.len()
1953 "Const Allocation interner: #{}",
1954 self.0.interners.const_allocation.len()
1956 writeln!(fmt, "Layout interner: #{}", self.0.interners.layout.len())?;
1966 // This type holds a `T` in the interner. The `T` is stored in the arena and
1967 // this type just holds a pointer to it, but it still effectively owns it. It
1968 // impls `Borrow` so that it can be looked up using the original
1969 // (non-arena-memory-owning) types.
1970 struct Interned<'tcx, T: ?Sized>(&'tcx T);
1972 impl<'tcx, T: 'tcx + ?Sized> Clone for Interned<'tcx, T> {
1973 fn clone(&self) -> Self {
1978 impl<'tcx, T: 'tcx + ?Sized> Copy for Interned<'tcx, T> {}
1980 impl<'tcx, T: 'tcx + ?Sized> IntoPointer for Interned<'tcx, T> {
1981 fn into_pointer(&self) -> *const () {
1982 self.0 as *const _ as *const ()
1986 #[allow(rustc::usage_of_ty_tykind)]
1987 impl<'tcx> Borrow<TyKind<'tcx>> for Interned<'tcx, TyS<'tcx>> {
1988 fn borrow<'a>(&'a self) -> &'a TyKind<'tcx> {
1993 impl<'tcx> PartialEq for Interned<'tcx, TyS<'tcx>> {
1994 fn eq(&self, other: &Interned<'tcx, TyS<'tcx>>) -> bool {
1995 // The `Borrow` trait requires that `x.borrow() == y.borrow()` equals
1997 self.0.kind() == other.0.kind()
2001 impl<'tcx> Eq for Interned<'tcx, TyS<'tcx>> {}
2003 impl<'tcx> Hash for Interned<'tcx, TyS<'tcx>> {
2004 fn hash<H: Hasher>(&self, s: &mut H) {
2005 // The `Borrow` trait requires that `x.borrow().hash(s) == x.hash(s)`.
2006 self.0.kind().hash(s)
2010 impl<'tcx> Borrow<Binder<'tcx, PredicateKind<'tcx>>> for Interned<'tcx, PredicateInner<'tcx>> {
2011 fn borrow<'a>(&'a self) -> &'a Binder<'tcx, PredicateKind<'tcx>> {
2016 impl<'tcx> PartialEq for Interned<'tcx, PredicateInner<'tcx>> {
2017 fn eq(&self, other: &Interned<'tcx, PredicateInner<'tcx>>) -> bool {
2018 // The `Borrow` trait requires that `x.borrow() == y.borrow()` equals
2020 self.0.kind == other.0.kind
2024 impl<'tcx> Eq for Interned<'tcx, PredicateInner<'tcx>> {}
2026 impl<'tcx> Hash for Interned<'tcx, PredicateInner<'tcx>> {
2027 fn hash<H: Hasher>(&self, s: &mut H) {
2028 // The `Borrow` trait requires that `x.borrow().hash(s) == x.hash(s)`.
2033 impl<'tcx, T> Borrow<[T]> for Interned<'tcx, List<T>> {
2034 fn borrow<'a>(&'a self) -> &'a [T] {
2039 impl<'tcx, T: PartialEq> PartialEq for Interned<'tcx, List<T>> {
2040 fn eq(&self, other: &Interned<'tcx, List<T>>) -> bool {
2041 // The `Borrow` trait requires that `x.borrow() == y.borrow()` equals
2043 self.0[..] == other.0[..]
2047 impl<'tcx, T: Eq> Eq for Interned<'tcx, List<T>> {}
2049 impl<'tcx, T: Hash> Hash for Interned<'tcx, List<T>> {
2050 fn hash<H: Hasher>(&self, s: &mut H) {
2051 // The `Borrow` trait requires that `x.borrow().hash(s) == x.hash(s)`.
2056 macro_rules! direct_interners {
2057 ($($name:ident: $method:ident($ty:ty),)+) => {
2058 $(impl<'tcx> Borrow<$ty> for Interned<'tcx, $ty> {
2059 fn borrow<'a>(&'a self) -> &'a $ty {
2064 impl<'tcx> PartialEq for Interned<'tcx, $ty> {
2065 fn eq(&self, other: &Self) -> bool {
2066 // The `Borrow` trait requires that `x.borrow() == y.borrow()`
2072 impl<'tcx> Eq for Interned<'tcx, $ty> {}
2074 impl<'tcx> Hash for Interned<'tcx, $ty> {
2075 fn hash<H: Hasher>(&self, s: &mut H) {
2076 // The `Borrow` trait requires that `x.borrow().hash(s) ==
2082 impl<'tcx> TyCtxt<'tcx> {
2083 pub fn $method(self, v: $ty) -> &'tcx $ty {
2084 self.interners.$name.intern(v, |v| {
2085 Interned(self.interners.arena.alloc(v))
2093 region: mk_region(RegionKind),
2094 const_: mk_const(Const<'tcx>),
2095 const_allocation: intern_const_alloc(Allocation),
2096 layout: intern_layout(Layout),
2097 adt_def: intern_adt_def(AdtDef),
2098 stability: intern_stability(attr::Stability),
2099 const_stability: intern_const_stability(attr::ConstStability),
2102 macro_rules! slice_interners {
2103 ($($field:ident: $method:ident($ty:ty)),+ $(,)?) => (
2104 impl<'tcx> TyCtxt<'tcx> {
2105 $(pub fn $method(self, v: &[$ty]) -> &'tcx List<$ty> {
2106 self.interners.$field.intern_ref(v, || {
2107 Interned(List::from_arena(&*self.arena, v))
2115 type_list: _intern_type_list(Ty<'tcx>),
2116 substs: _intern_substs(GenericArg<'tcx>),
2117 canonical_var_infos: _intern_canonical_var_infos(CanonicalVarInfo<'tcx>),
2118 poly_existential_predicates:
2119 _intern_poly_existential_predicates(ty::Binder<'tcx, ExistentialPredicate<'tcx>>),
2120 predicates: _intern_predicates(Predicate<'tcx>),
2121 projs: _intern_projs(ProjectionKind),
2122 place_elems: _intern_place_elems(PlaceElem<'tcx>),
2123 bound_variable_kinds: _intern_bound_variable_kinds(ty::BoundVariableKind),
2126 impl<'tcx> TyCtxt<'tcx> {
2127 /// Given a `fn` type, returns an equivalent `unsafe fn` type;
2128 /// that is, a `fn` type that is equivalent in every way for being
2130 pub fn safe_to_unsafe_fn_ty(self, sig: PolyFnSig<'tcx>) -> Ty<'tcx> {
2131 assert_eq!(sig.unsafety(), hir::Unsafety::Normal);
2132 self.mk_fn_ptr(sig.map_bound(|sig| ty::FnSig { unsafety: hir::Unsafety::Unsafe, ..sig }))
2135 /// Given the def_id of a Trait `trait_def_id` and the name of an associated item `assoc_name`
2136 /// returns true if the `trait_def_id` defines an associated item of name `assoc_name`.
2137 pub fn trait_may_define_assoc_type(self, trait_def_id: DefId, assoc_name: Ident) -> bool {
2138 self.super_traits_of(trait_def_id).any(|trait_did| {
2139 self.associated_items(trait_did)
2140 .find_by_name_and_kind(self, assoc_name, ty::AssocKind::Type, trait_did)
2145 /// Computes the def-ids of the transitive supertraits of `trait_def_id`. This (intentionally)
2146 /// does not compute the full elaborated super-predicates but just the set of def-ids. It is used
2147 /// to identify which traits may define a given associated type to help avoid cycle errors.
2148 /// Returns a `DefId` iterator.
2149 fn super_traits_of(self, trait_def_id: DefId) -> impl Iterator<Item = DefId> + 'tcx {
2150 let mut set = FxHashSet::default();
2151 let mut stack = vec![trait_def_id];
2153 set.insert(trait_def_id);
2155 iter::from_fn(move || -> Option<DefId> {
2156 let trait_did = stack.pop()?;
2157 let generic_predicates = self.super_predicates_of(trait_did);
2159 for (predicate, _) in generic_predicates.predicates {
2160 if let ty::PredicateKind::Trait(data) = predicate.kind().skip_binder() {
2161 if set.insert(data.def_id()) {
2162 stack.push(data.def_id());
2171 /// Given a closure signature, returns an equivalent fn signature. Detuples
2172 /// and so forth -- so e.g., if we have a sig with `Fn<(u32, i32)>` then
2173 /// you would get a `fn(u32, i32)`.
2174 /// `unsafety` determines the unsafety of the fn signature. If you pass
2175 /// `hir::Unsafety::Unsafe` in the previous example, then you would get
2176 /// an `unsafe fn (u32, i32)`.
2177 /// It cannot convert a closure that requires unsafe.
2178 pub fn signature_unclosure(
2180 sig: PolyFnSig<'tcx>,
2181 unsafety: hir::Unsafety,
2182 ) -> PolyFnSig<'tcx> {
2184 let params_iter = match s.inputs()[0].kind() {
2185 ty::Tuple(params) => params.into_iter().map(|k| k.expect_ty()),
2188 self.mk_fn_sig(params_iter, s.output(), s.c_variadic, unsafety, abi::Abi::Rust)
2192 /// Same a `self.mk_region(kind)`, but avoids accessing the interners if
2195 pub fn reuse_or_mk_region(self, r: Region<'tcx>, kind: RegionKind) -> Region<'tcx> {
2196 if *r == kind { r } else { self.mk_region(kind) }
2199 #[allow(rustc::usage_of_ty_tykind)]
2201 pub fn mk_ty(self, st: TyKind<'tcx>) -> Ty<'tcx> {
2202 self.interners.intern_ty(st)
2206 pub fn mk_predicate(self, binder: Binder<'tcx, PredicateKind<'tcx>>) -> Predicate<'tcx> {
2207 let inner = self.interners.intern_predicate(binder);
2212 pub fn reuse_or_mk_predicate(
2214 pred: Predicate<'tcx>,
2215 binder: Binder<'tcx, PredicateKind<'tcx>>,
2216 ) -> Predicate<'tcx> {
2217 if pred.kind() != binder { self.mk_predicate(binder) } else { pred }
2220 pub fn mk_mach_int(self, tm: IntTy) -> Ty<'tcx> {
2222 IntTy::Isize => self.types.isize,
2223 IntTy::I8 => self.types.i8,
2224 IntTy::I16 => self.types.i16,
2225 IntTy::I32 => self.types.i32,
2226 IntTy::I64 => self.types.i64,
2227 IntTy::I128 => self.types.i128,
2231 pub fn mk_mach_uint(self, tm: UintTy) -> Ty<'tcx> {
2233 UintTy::Usize => self.types.usize,
2234 UintTy::U8 => self.types.u8,
2235 UintTy::U16 => self.types.u16,
2236 UintTy::U32 => self.types.u32,
2237 UintTy::U64 => self.types.u64,
2238 UintTy::U128 => self.types.u128,
2242 pub fn mk_mach_float(self, tm: FloatTy) -> Ty<'tcx> {
2244 FloatTy::F32 => self.types.f32,
2245 FloatTy::F64 => self.types.f64,
2250 pub fn mk_static_str(self) -> Ty<'tcx> {
2251 self.mk_imm_ref(self.lifetimes.re_static, self.types.str_)
2255 pub fn mk_adt(self, def: &'tcx AdtDef, substs: SubstsRef<'tcx>) -> Ty<'tcx> {
2256 // Take a copy of substs so that we own the vectors inside.
2257 self.mk_ty(Adt(def, substs))
2261 pub fn mk_foreign(self, def_id: DefId) -> Ty<'tcx> {
2262 self.mk_ty(Foreign(def_id))
2265 fn mk_generic_adt(self, wrapper_def_id: DefId, ty_param: Ty<'tcx>) -> Ty<'tcx> {
2266 let adt_def = self.adt_def(wrapper_def_id);
2268 InternalSubsts::for_item(self, wrapper_def_id, |param, substs| match param.kind {
2269 GenericParamDefKind::Lifetime | GenericParamDefKind::Const { .. } => bug!(),
2270 GenericParamDefKind::Type { has_default, .. } => {
2271 if param.index == 0 {
2274 assert!(has_default);
2275 self.type_of(param.def_id).subst(self, substs).into()
2279 self.mk_ty(Adt(adt_def, substs))
2283 pub fn mk_box(self, ty: Ty<'tcx>) -> Ty<'tcx> {
2284 let def_id = self.require_lang_item(LangItem::OwnedBox, None);
2285 self.mk_generic_adt(def_id, ty)
2289 pub fn mk_lang_item(self, ty: Ty<'tcx>, item: LangItem) -> Option<Ty<'tcx>> {
2290 let def_id = self.lang_items().require(item).ok()?;
2291 Some(self.mk_generic_adt(def_id, ty))
2295 pub fn mk_diagnostic_item(self, ty: Ty<'tcx>, name: Symbol) -> Option<Ty<'tcx>> {
2296 let def_id = self.get_diagnostic_item(name)?;
2297 Some(self.mk_generic_adt(def_id, ty))
2301 pub fn mk_maybe_uninit(self, ty: Ty<'tcx>) -> Ty<'tcx> {
2302 let def_id = self.require_lang_item(LangItem::MaybeUninit, None);
2303 self.mk_generic_adt(def_id, ty)
2307 pub fn mk_ptr(self, tm: TypeAndMut<'tcx>) -> Ty<'tcx> {
2308 self.mk_ty(RawPtr(tm))
2312 pub fn mk_ref(self, r: Region<'tcx>, tm: TypeAndMut<'tcx>) -> Ty<'tcx> {
2313 self.mk_ty(Ref(r, tm.ty, tm.mutbl))
2317 pub fn mk_mut_ref(self, r: Region<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
2318 self.mk_ref(r, TypeAndMut { ty, mutbl: hir::Mutability::Mut })
2322 pub fn mk_imm_ref(self, r: Region<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
2323 self.mk_ref(r, TypeAndMut { ty, mutbl: hir::Mutability::Not })
2327 pub fn mk_mut_ptr(self, ty: Ty<'tcx>) -> Ty<'tcx> {
2328 self.mk_ptr(TypeAndMut { ty, mutbl: hir::Mutability::Mut })
2332 pub fn mk_imm_ptr(self, ty: Ty<'tcx>) -> Ty<'tcx> {
2333 self.mk_ptr(TypeAndMut { ty, mutbl: hir::Mutability::Not })
2337 pub fn mk_array(self, ty: Ty<'tcx>, n: u64) -> Ty<'tcx> {
2338 self.mk_ty(Array(ty, ty::Const::from_usize(self, n)))
2342 pub fn mk_slice(self, ty: Ty<'tcx>) -> Ty<'tcx> {
2343 self.mk_ty(Slice(ty))
2347 pub fn intern_tup(self, ts: &[Ty<'tcx>]) -> Ty<'tcx> {
2348 let kinds: Vec<_> = ts.iter().map(|&t| GenericArg::from(t)).collect();
2349 self.mk_ty(Tuple(self.intern_substs(&kinds)))
2352 pub fn mk_tup<I: InternAs<[Ty<'tcx>], Ty<'tcx>>>(self, iter: I) -> I::Output {
2353 iter.intern_with(|ts| {
2354 let kinds: Vec<_> = ts.iter().map(|&t| GenericArg::from(t)).collect();
2355 self.mk_ty(Tuple(self.intern_substs(&kinds)))
2360 pub fn mk_unit(self) -> Ty<'tcx> {
2365 pub fn mk_diverging_default(self) -> Ty<'tcx> {
2366 if self.features().never_type_fallback { self.types.never } else { self.types.unit }
2370 pub fn mk_fn_def(self, def_id: DefId, substs: SubstsRef<'tcx>) -> Ty<'tcx> {
2371 self.mk_ty(FnDef(def_id, substs))
2375 pub fn mk_fn_ptr(self, fty: PolyFnSig<'tcx>) -> Ty<'tcx> {
2376 self.mk_ty(FnPtr(fty))
2382 obj: &'tcx List<ty::Binder<'tcx, ExistentialPredicate<'tcx>>>,
2383 reg: ty::Region<'tcx>,
2385 self.mk_ty(Dynamic(obj, reg))
2389 pub fn mk_projection(self, item_def_id: DefId, substs: SubstsRef<'tcx>) -> Ty<'tcx> {
2390 self.mk_ty(Projection(ProjectionTy { item_def_id, substs }))
2394 pub fn mk_closure(self, closure_id: DefId, closure_substs: SubstsRef<'tcx>) -> Ty<'tcx> {
2395 self.mk_ty(Closure(closure_id, closure_substs))
2399 pub fn mk_generator(
2402 generator_substs: SubstsRef<'tcx>,
2403 movability: hir::Movability,
2405 self.mk_ty(Generator(id, generator_substs, movability))
2409 pub fn mk_generator_witness(self, types: ty::Binder<'tcx, &'tcx List<Ty<'tcx>>>) -> Ty<'tcx> {
2410 self.mk_ty(GeneratorWitness(types))
2414 pub fn mk_ty_var(self, v: TyVid) -> Ty<'tcx> {
2415 self.mk_ty_infer(TyVar(v))
2419 pub fn mk_const_var(self, v: ConstVid<'tcx>, ty: Ty<'tcx>) -> &'tcx Const<'tcx> {
2420 self.mk_const(ty::Const { val: ty::ConstKind::Infer(InferConst::Var(v)), ty })
2424 pub fn mk_int_var(self, v: IntVid) -> Ty<'tcx> {
2425 self.mk_ty_infer(IntVar(v))
2429 pub fn mk_float_var(self, v: FloatVid) -> Ty<'tcx> {
2430 self.mk_ty_infer(FloatVar(v))
2434 pub fn mk_ty_infer(self, it: InferTy) -> Ty<'tcx> {
2435 self.mk_ty(Infer(it))
2439 pub fn mk_const_infer(self, ic: InferConst<'tcx>, ty: Ty<'tcx>) -> &'tcx ty::Const<'tcx> {
2440 self.mk_const(ty::Const { val: ty::ConstKind::Infer(ic), ty })
2444 pub fn mk_ty_param(self, index: u32, name: Symbol) -> Ty<'tcx> {
2445 self.mk_ty(Param(ParamTy { index, name }))
2449 pub fn mk_const_param(self, index: u32, name: Symbol, ty: Ty<'tcx>) -> &'tcx Const<'tcx> {
2450 self.mk_const(ty::Const { val: ty::ConstKind::Param(ParamConst { index, name }), ty })
2453 pub fn mk_param_from_def(self, param: &ty::GenericParamDef) -> GenericArg<'tcx> {
2455 GenericParamDefKind::Lifetime => {
2456 self.mk_region(ty::ReEarlyBound(param.to_early_bound_region_data())).into()
2458 GenericParamDefKind::Type { .. } => self.mk_ty_param(param.index, param.name).into(),
2459 GenericParamDefKind::Const { .. } => {
2460 self.mk_const_param(param.index, param.name, self.type_of(param.def_id)).into()
2466 pub fn mk_opaque(self, def_id: DefId, substs: SubstsRef<'tcx>) -> Ty<'tcx> {
2467 self.mk_ty(Opaque(def_id, substs))
2470 pub fn mk_place_field(self, place: Place<'tcx>, f: Field, ty: Ty<'tcx>) -> Place<'tcx> {
2471 self.mk_place_elem(place, PlaceElem::Field(f, ty))
2474 pub fn mk_place_deref(self, place: Place<'tcx>) -> Place<'tcx> {
2475 self.mk_place_elem(place, PlaceElem::Deref)
2478 pub fn mk_place_downcast(
2481 adt_def: &'tcx AdtDef,
2482 variant_index: VariantIdx,
2486 PlaceElem::Downcast(Some(adt_def.variants[variant_index].name), variant_index),
2490 pub fn mk_place_downcast_unnamed(
2493 variant_index: VariantIdx,
2495 self.mk_place_elem(place, PlaceElem::Downcast(None, variant_index))
2498 pub fn mk_place_index(self, place: Place<'tcx>, index: Local) -> Place<'tcx> {
2499 self.mk_place_elem(place, PlaceElem::Index(index))
2502 /// This method copies `Place`'s projection, add an element and reintern it. Should not be used
2503 /// to build a full `Place` it's just a convenient way to grab a projection and modify it in
2505 pub fn mk_place_elem(self, place: Place<'tcx>, elem: PlaceElem<'tcx>) -> Place<'tcx> {
2506 let mut projection = place.projection.to_vec();
2507 projection.push(elem);
2509 Place { local: place.local, projection: self.intern_place_elems(&projection) }
2512 pub fn intern_poly_existential_predicates(
2514 eps: &[ty::Binder<'tcx, ExistentialPredicate<'tcx>>],
2515 ) -> &'tcx List<ty::Binder<'tcx, ExistentialPredicate<'tcx>>> {
2516 assert!(!eps.is_empty());
2519 .all(|[a, b]| a.skip_binder().stable_cmp(self, &b.skip_binder())
2520 != Ordering::Greater)
2522 self._intern_poly_existential_predicates(eps)
2525 pub fn intern_predicates(self, preds: &[Predicate<'tcx>]) -> &'tcx List<Predicate<'tcx>> {
2526 // FIXME consider asking the input slice to be sorted to avoid
2527 // re-interning permutations, in which case that would be asserted
2529 if preds.is_empty() {
2530 // The macro-generated method below asserts we don't intern an empty slice.
2533 self._intern_predicates(preds)
2537 pub fn intern_type_list(self, ts: &[Ty<'tcx>]) -> &'tcx List<Ty<'tcx>> {
2538 if ts.is_empty() { List::empty() } else { self._intern_type_list(ts) }
2541 pub fn intern_substs(self, ts: &[GenericArg<'tcx>]) -> &'tcx List<GenericArg<'tcx>> {
2542 if ts.is_empty() { List::empty() } else { self._intern_substs(ts) }
2545 pub fn intern_projs(self, ps: &[ProjectionKind]) -> &'tcx List<ProjectionKind> {
2546 if ps.is_empty() { List::empty() } else { self._intern_projs(ps) }
2549 pub fn intern_place_elems(self, ts: &[PlaceElem<'tcx>]) -> &'tcx List<PlaceElem<'tcx>> {
2550 if ts.is_empty() { List::empty() } else { self._intern_place_elems(ts) }
2553 pub fn intern_canonical_var_infos(
2555 ts: &[CanonicalVarInfo<'tcx>],
2556 ) -> CanonicalVarInfos<'tcx> {
2557 if ts.is_empty() { List::empty() } else { self._intern_canonical_var_infos(ts) }
2560 pub fn intern_bound_variable_kinds(
2562 ts: &[ty::BoundVariableKind],
2563 ) -> &'tcx List<ty::BoundVariableKind> {
2564 if ts.is_empty() { List::empty() } else { self._intern_bound_variable_kinds(ts) }
2567 pub fn mk_fn_sig<I>(
2572 unsafety: hir::Unsafety,
2574 ) -> <I::Item as InternIteratorElement<Ty<'tcx>, ty::FnSig<'tcx>>>::Output
2576 I: Iterator<Item: InternIteratorElement<Ty<'tcx>, ty::FnSig<'tcx>>>,
2578 inputs.chain(iter::once(output)).intern_with(|xs| ty::FnSig {
2579 inputs_and_output: self.intern_type_list(xs),
2586 pub fn mk_poly_existential_predicates<
2588 [ty::Binder<'tcx, ExistentialPredicate<'tcx>>],
2589 &'tcx List<ty::Binder<'tcx, ExistentialPredicate<'tcx>>>,
2595 iter.intern_with(|xs| self.intern_poly_existential_predicates(xs))
2598 pub fn mk_predicates<I: InternAs<[Predicate<'tcx>], &'tcx List<Predicate<'tcx>>>>(
2602 iter.intern_with(|xs| self.intern_predicates(xs))
2605 pub fn mk_type_list<I: InternAs<[Ty<'tcx>], &'tcx List<Ty<'tcx>>>>(self, iter: I) -> I::Output {
2606 iter.intern_with(|xs| self.intern_type_list(xs))
2609 pub fn mk_substs<I: InternAs<[GenericArg<'tcx>], &'tcx List<GenericArg<'tcx>>>>(
2613 iter.intern_with(|xs| self.intern_substs(xs))
2616 pub fn mk_place_elems<I: InternAs<[PlaceElem<'tcx>], &'tcx List<PlaceElem<'tcx>>>>(
2620 iter.intern_with(|xs| self.intern_place_elems(xs))
2623 pub fn mk_substs_trait(self, self_ty: Ty<'tcx>, rest: &[GenericArg<'tcx>]) -> SubstsRef<'tcx> {
2624 self.mk_substs(iter::once(self_ty.into()).chain(rest.iter().cloned()))
2627 pub fn mk_bound_variable_kinds<
2628 I: InternAs<[ty::BoundVariableKind], &'tcx List<ty::BoundVariableKind>>,
2633 iter.intern_with(|xs| self.intern_bound_variable_kinds(xs))
2636 /// Walks upwards from `id` to find a node which might change lint levels with attributes.
2637 /// It stops at `bound` and just returns it if reached.
2638 pub fn maybe_lint_level_root_bounded(self, mut id: HirId, bound: HirId) -> HirId {
2639 let hir = self.hir();
2645 if hir.attrs(id).iter().any(|attr| Level::from_symbol(attr.name_or_empty()).is_some()) {
2648 let next = hir.get_parent_node(id);
2650 bug!("lint traversal reached the root of the crate");
2656 pub fn lint_level_at_node(
2658 lint: &'static Lint,
2660 ) -> (Level, LintLevelSource) {
2661 let sets = self.lint_levels(());
2663 if let Some(pair) = sets.level_and_source(lint, id, self.sess) {
2666 let next = self.hir().get_parent_node(id);
2668 bug!("lint traversal reached the root of the crate");
2674 pub fn struct_span_lint_hir(
2676 lint: &'static Lint,
2678 span: impl Into<MultiSpan>,
2679 decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a>),
2681 let (level, src) = self.lint_level_at_node(lint, hir_id);
2682 struct_lint_level(self.sess, lint, level, src, Some(span.into()), decorate);
2685 pub fn struct_lint_node(
2687 lint: &'static Lint,
2689 decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a>),
2691 let (level, src) = self.lint_level_at_node(lint, id);
2692 struct_lint_level(self.sess, lint, level, src, None, decorate);
2695 pub fn in_scope_traits(self, id: HirId) -> Option<&'tcx [TraitCandidate]> {
2696 let map = self.in_scope_traits_map(id.owner)?;
2697 let candidates = map.get(&id.local_id)?;
2701 pub fn named_region(self, id: HirId) -> Option<resolve_lifetime::Region> {
2702 debug!(?id, "named_region");
2703 self.named_region_map(id.owner).and_then(|map| map.get(&id.local_id).cloned())
2706 pub fn is_late_bound(self, id: HirId) -> bool {
2707 self.is_late_bound_map(id.owner)
2708 .map_or(false, |(owner, set)| owner == id.owner && set.contains(&id.local_id))
2711 pub fn object_lifetime_defaults(self, id: HirId) -> Option<Vec<ObjectLifetimeDefault>> {
2712 self.object_lifetime_defaults_map(id.owner)
2715 pub fn late_bound_vars(self, id: HirId) -> &'tcx List<ty::BoundVariableKind> {
2716 self.mk_bound_variable_kinds(
2717 self.late_bound_vars_map(id.owner)
2718 .and_then(|map| map.get(&id.local_id).cloned())
2719 .unwrap_or_else(|| {
2720 bug!("No bound vars found for {:?} ({:?})", self.hir().node_to_string(id), id)
2726 pub fn lifetime_scope(self, id: HirId) -> Option<LifetimeScopeForPath> {
2727 self.lifetime_scope_map(id.owner).and_then(|mut map| map.remove(&id.local_id))
2730 /// Whether the `def_id` counts as const fn in the current crate, considering all active
2732 pub fn is_const_fn(self, def_id: DefId) -> bool {
2733 if self.is_const_fn_raw(def_id) {
2734 match self.lookup_const_stability(def_id) {
2735 Some(stability) if stability.level.is_unstable() => {
2736 // has a `rustc_const_unstable` attribute, check whether the user enabled the
2737 // corresponding feature gate.
2739 .declared_lib_features
2741 .any(|&(sym, _)| sym == stability.feature)
2743 // functions without const stability are either stable user written
2744 // const fn or the user is using feature gates and we thus don't
2745 // care what they do
2754 impl<'tcx> TyCtxtAt<'tcx> {
2755 /// Constructs a `TyKind::Error` type and registers a `delay_span_bug` to ensure it gets used.
2757 pub fn ty_error(self) -> Ty<'tcx> {
2758 self.tcx.ty_error_with_message(self.span, "TyKind::Error constructed but no error reported")
2761 /// Constructs a `TyKind::Error` type and registers a `delay_span_bug` with the given `msg to
2762 /// ensure it gets used.
2764 pub fn ty_error_with_message(self, msg: &str) -> Ty<'tcx> {
2765 self.tcx.ty_error_with_message(self.span, msg)
2769 pub trait InternAs<T: ?Sized, R> {
2771 fn intern_with<F>(self, f: F) -> Self::Output
2776 impl<I, T, R, E> InternAs<[T], R> for I
2778 E: InternIteratorElement<T, R>,
2779 I: Iterator<Item = E>,
2781 type Output = E::Output;
2782 fn intern_with<F>(self, f: F) -> Self::Output
2784 F: FnOnce(&[T]) -> R,
2786 E::intern_with(self, f)
2790 pub trait InternIteratorElement<T, R>: Sized {
2792 fn intern_with<I: Iterator<Item = Self>, F: FnOnce(&[T]) -> R>(iter: I, f: F) -> Self::Output;
2795 impl<T, R> InternIteratorElement<T, R> for T {
2797 fn intern_with<I: Iterator<Item = Self>, F: FnOnce(&[T]) -> R>(iter: I, f: F) -> Self::Output {
2798 f(&iter.collect::<SmallVec<[_; 8]>>())
2802 impl<'a, T, R> InternIteratorElement<T, R> for &'a T
2807 fn intern_with<I: Iterator<Item = Self>, F: FnOnce(&[T]) -> R>(iter: I, f: F) -> Self::Output {
2808 f(&iter.cloned().collect::<SmallVec<[_; 8]>>())
2812 impl<T, R, E> InternIteratorElement<T, R> for Result<T, E> {
2813 type Output = Result<R, E>;
2814 fn intern_with<I: Iterator<Item = Self>, F: FnOnce(&[T]) -> R>(
2818 // This code is hot enough that it's worth specializing for the most
2819 // common length lists, to avoid the overhead of `SmallVec` creation.
2820 // The match arms are in order of frequency. The 1, 2, and 0 cases are
2821 // typically hit in ~95% of cases. We assume that if the upper and
2822 // lower bounds from `size_hint` agree they are correct.
2823 Ok(match iter.size_hint() {
2825 let t0 = iter.next().unwrap()?;
2826 assert!(iter.next().is_none());
2830 let t0 = iter.next().unwrap()?;
2831 let t1 = iter.next().unwrap()?;
2832 assert!(iter.next().is_none());
2836 assert!(iter.next().is_none());
2839 _ => f(&iter.collect::<Result<SmallVec<[_; 8]>, _>>()?),
2844 // We are comparing types with different invariant lifetimes, so `ptr::eq`
2845 // won't work for us.
2846 fn ptr_eq<T, U>(t: *const T, u: *const U) -> bool {
2847 t as *const () == u as *const ()
2850 pub fn provide(providers: &mut ty::query::Providers) {
2851 providers.in_scope_traits_map =
2852 |tcx, id| tcx.hir_crate(()).owners[id].as_ref().map(|owner_info| &owner_info.trait_map);
2853 providers.resolutions = |tcx, ()| &tcx.untracked_resolutions;
2854 providers.module_reexports =
2855 |tcx, id| tcx.resolutions(()).reexport_map.get(&id).map(|v| &v[..]);
2856 providers.crate_name = |tcx, id| {
2857 assert_eq!(id, LOCAL_CRATE);
2860 providers.maybe_unused_trait_import =
2861 |tcx, id| tcx.resolutions(()).maybe_unused_trait_imports.contains(&id);
2862 providers.maybe_unused_extern_crates =
2863 |tcx, ()| &tcx.resolutions(()).maybe_unused_extern_crates[..];
2864 providers.names_imported_by_glob_use = |tcx, id| {
2865 tcx.arena.alloc(tcx.resolutions(()).glob_map.get(&id).cloned().unwrap_or_default())
2868 providers.lookup_stability = |tcx, id| tcx.stability().local_stability(id.expect_local());
2869 providers.lookup_const_stability =
2870 |tcx, id| tcx.stability().local_const_stability(id.expect_local());
2871 providers.lookup_deprecation_entry =
2872 |tcx, id| tcx.stability().local_deprecation_entry(id.expect_local());
2873 providers.extern_mod_stmt_cnum =
2874 |tcx, id| tcx.resolutions(()).extern_crate_map.get(&id).cloned();
2875 providers.output_filenames = |tcx, ()| tcx.output_filenames.clone();
2876 providers.features_query = |tcx, ()| tcx.sess.features_untracked();
2877 providers.is_panic_runtime = |tcx, cnum| {
2878 assert_eq!(cnum, LOCAL_CRATE);
2879 tcx.sess.contains_name(tcx.hir().krate_attrs(), sym::panic_runtime)
2881 providers.is_compiler_builtins = |tcx, cnum| {
2882 assert_eq!(cnum, LOCAL_CRATE);
2883 tcx.sess.contains_name(tcx.hir().krate_attrs(), sym::compiler_builtins)
2885 providers.has_panic_handler = |tcx, cnum| {
2886 assert_eq!(cnum, LOCAL_CRATE);
2887 // We want to check if the panic handler was defined in this crate
2888 tcx.lang_items().panic_impl().map_or(false, |did| did.is_local())