1 //! Type context book-keeping.
3 use crate::arena::Arena;
4 use crate::dep_graph::DepGraph;
5 use crate::dep_graph::{self, DepConstructor};
6 use crate::hir::exports::Export;
7 use crate::ich::{NodeIdHashingMode, StableHashingContext};
8 use crate::infer::canonical::{Canonical, CanonicalVarInfo, CanonicalVarInfos};
9 use crate::lint::LintDiagnosticBuilder;
10 use crate::lint::{struct_lint_level, LintSource};
12 use crate::middle::cstore::CrateStoreDyn;
13 use crate::middle::cstore::EncodedMetadata;
14 use crate::middle::resolve_lifetime::{self, ObjectLifetimeDefault};
15 use crate::middle::stability;
16 use crate::mir::interpret::{Allocation, ConstValue, Scalar};
18 interpret, BodyAndCache, Field, Local, Place, PlaceElem, ProjectionKind, Promoted,
21 use crate::traits::{Clause, Clauses, Goal, GoalKind, Goals};
23 use crate::ty::steal::Steal;
24 use crate::ty::subst::{GenericArg, InternalSubsts, Subst, SubstsRef};
25 use crate::ty::subst::{GenericArgKind, UserSubsts};
26 use crate::ty::CanonicalPolyFnSig;
27 use crate::ty::GenericParamDefKind;
28 use crate::ty::RegionKind;
29 use crate::ty::ReprOptions;
30 use crate::ty::TyKind::*;
31 use crate::ty::{self, DefIdTree, Ty, TypeAndMut};
32 use crate::ty::{AdtDef, AdtKind, Const, Region};
33 use crate::ty::{BindingMode, BoundVar};
34 use crate::ty::{ConstVid, FloatVar, FloatVid, IntVar, IntVid, TyVar, TyVid};
35 use crate::ty::{ExistentialPredicate, InferTy, ParamTy, PolyFnSig, Predicate, ProjectionTy};
36 use crate::ty::{InferConst, ParamConst};
37 use crate::ty::{List, TyKind, TyS};
39 use rustc_ast::expand::allocator::AllocatorKind;
40 use rustc_ast::node_id::NodeMap;
41 use rustc_attr as attr;
42 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
43 use rustc_data_structures::profiling::SelfProfilerRef;
44 use rustc_data_structures::sharded::{IntoPointer, ShardedHashMap};
45 use rustc_data_structures::stable_hasher::{
46 hash_stable_hashmap, HashStable, StableHasher, StableVec,
48 use rustc_data_structures::sync::{self, Lock, Lrc, WorkerLocal};
49 use rustc_errors::ErrorReported;
51 use rustc_hir::def::{DefKind, Res};
52 use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, DefIdSet, LocalDefId, LOCAL_CRATE};
53 use rustc_hir::definitions::{DefPathData, DefPathHash, Definitions};
54 use rustc_hir::lang_items;
55 use rustc_hir::lang_items::PanicLocationLangItem;
56 use rustc_hir::{HirId, Node, TraitCandidate};
57 use rustc_hir::{ItemKind, ItemLocalId, ItemLocalMap, ItemLocalSet};
58 use rustc_index::vec::{Idx, IndexVec};
59 use rustc_macros::HashStable;
60 use rustc_session::config::CrateType;
61 use rustc_session::config::{BorrowckMode, OutputFilenames};
62 use rustc_session::lint::{Level, Lint};
63 use rustc_session::Session;
64 use rustc_span::source_map::MultiSpan;
65 use rustc_span::symbol::{kw, sym, Symbol};
67 use rustc_target::abi::{Layout, TargetDataLayout, VariantIdx};
68 use rustc_target::spec::abi;
70 use smallvec::SmallVec;
72 use std::borrow::Borrow;
73 use std::cmp::Ordering;
74 use std::collections::hash_map::{self, Entry};
76 use std::hash::{Hash, Hasher};
79 use std::ops::{Bound, Deref};
82 type InternedSet<'tcx, T> = ShardedHashMap<Interned<'tcx, T>, ()>;
84 pub struct CtxtInterners<'tcx> {
85 /// The arena that types, regions, etc. are allocated from.
86 arena: &'tcx WorkerLocal<Arena<'tcx>>,
88 /// Specifically use a speedy hash algorithm for these hash sets, since
89 /// they're accessed quite often.
90 type_: InternedSet<'tcx, TyS<'tcx>>,
91 type_list: InternedSet<'tcx, List<Ty<'tcx>>>,
92 substs: InternedSet<'tcx, InternalSubsts<'tcx>>,
93 canonical_var_infos: InternedSet<'tcx, List<CanonicalVarInfo>>,
94 region: InternedSet<'tcx, RegionKind>,
95 existential_predicates: InternedSet<'tcx, List<ExistentialPredicate<'tcx>>>,
96 predicates: InternedSet<'tcx, List<Predicate<'tcx>>>,
97 clauses: InternedSet<'tcx, List<Clause<'tcx>>>,
98 goal: InternedSet<'tcx, GoalKind<'tcx>>,
99 goal_list: InternedSet<'tcx, List<Goal<'tcx>>>,
100 projs: InternedSet<'tcx, List<ProjectionKind>>,
101 place_elems: InternedSet<'tcx, List<PlaceElem<'tcx>>>,
102 const_: InternedSet<'tcx, Const<'tcx>>,
105 impl<'tcx> CtxtInterners<'tcx> {
106 fn new(arena: &'tcx WorkerLocal<Arena<'tcx>>) -> CtxtInterners<'tcx> {
109 type_: Default::default(),
110 type_list: Default::default(),
111 substs: Default::default(),
112 region: Default::default(),
113 existential_predicates: Default::default(),
114 canonical_var_infos: Default::default(),
115 predicates: Default::default(),
116 clauses: Default::default(),
117 goal: Default::default(),
118 goal_list: Default::default(),
119 projs: Default::default(),
120 place_elems: Default::default(),
121 const_: Default::default(),
126 #[allow(rustc::usage_of_ty_tykind)]
128 fn intern_ty(&self, kind: TyKind<'tcx>) -> Ty<'tcx> {
130 .intern(kind, |kind| {
131 let flags = super::flags::FlagComputation::for_kind(&kind);
133 let ty_struct = TyS {
136 outer_exclusive_binder: flags.outer_exclusive_binder,
139 Interned(self.arena.alloc(ty_struct))
145 pub struct CommonTypes<'tcx> {
164 pub self_param: Ty<'tcx>,
167 /// Dummy type used for the `Self` of a `TraitRef` created for converting
168 /// a trait object, and which gets removed in `ExistentialTraitRef`.
169 /// This type must not appear anywhere in other converted types.
170 pub trait_object_dummy_self: Ty<'tcx>,
173 pub struct CommonLifetimes<'tcx> {
174 /// `ReEmpty` in the root universe.
175 pub re_root_empty: Region<'tcx>,
178 pub re_static: Region<'tcx>,
180 /// Erased region, used after type-checking
181 pub re_erased: Region<'tcx>,
184 pub struct CommonConsts<'tcx> {
185 pub err: &'tcx Const<'tcx>,
188 pub struct LocalTableInContext<'a, V> {
189 hir_owner: Option<LocalDefId>,
190 data: &'a ItemLocalMap<V>,
193 /// Validate that the given HirId (respectively its `local_id` part) can be
194 /// safely used as a key in the tables of a TypeckTable. For that to be
195 /// the case, the HirId must have the same `owner` as all the other IDs in
196 /// this table (signified by `hir_owner`). Otherwise the HirId
197 /// would be in a different frame of reference and using its `local_id`
198 /// would result in lookup errors, or worse, in silently wrong data being
200 fn validate_hir_id_for_typeck_tables(
201 hir_owner: Option<LocalDefId>,
205 if let Some(hir_owner) = hir_owner {
206 if hir_id.owner != hir_owner {
207 ty::tls::with(|tcx| {
209 "node {} with HirId::owner {:?} cannot be placed in \
210 TypeckTables with hir_owner {:?}",
211 tcx.hir().node_to_string(hir_id),
218 // We use "Null Object" TypeckTables in some of the analysis passes.
219 // These are just expected to be empty and their `hir_owner` is
220 // `None`. Therefore we cannot verify whether a given `HirId` would
221 // be a valid key for the given table. Instead we make sure that
222 // nobody tries to write to such a Null Object table.
224 bug!("access to invalid TypeckTables")
229 impl<'a, V> LocalTableInContext<'a, V> {
230 pub fn contains_key(&self, id: hir::HirId) -> bool {
231 validate_hir_id_for_typeck_tables(self.hir_owner, id, false);
232 self.data.contains_key(&id.local_id)
235 pub fn get(&self, id: hir::HirId) -> Option<&V> {
236 validate_hir_id_for_typeck_tables(self.hir_owner, id, false);
237 self.data.get(&id.local_id)
240 pub fn iter(&self) -> hash_map::Iter<'_, hir::ItemLocalId, V> {
245 impl<'a, V> ::std::ops::Index<hir::HirId> for LocalTableInContext<'a, V> {
248 fn index(&self, key: hir::HirId) -> &V {
249 self.get(key).expect("LocalTableInContext: key not found")
253 pub struct LocalTableInContextMut<'a, V> {
254 hir_owner: Option<LocalDefId>,
255 data: &'a mut ItemLocalMap<V>,
258 impl<'a, V> LocalTableInContextMut<'a, V> {
259 pub fn get_mut(&mut self, id: hir::HirId) -> Option<&mut V> {
260 validate_hir_id_for_typeck_tables(self.hir_owner, id, true);
261 self.data.get_mut(&id.local_id)
264 pub fn entry(&mut self, id: hir::HirId) -> Entry<'_, hir::ItemLocalId, V> {
265 validate_hir_id_for_typeck_tables(self.hir_owner, id, true);
266 self.data.entry(id.local_id)
269 pub fn insert(&mut self, id: hir::HirId, val: V) -> Option<V> {
270 validate_hir_id_for_typeck_tables(self.hir_owner, id, true);
271 self.data.insert(id.local_id, val)
274 pub fn remove(&mut self, id: hir::HirId) -> Option<V> {
275 validate_hir_id_for_typeck_tables(self.hir_owner, id, true);
276 self.data.remove(&id.local_id)
280 /// All information necessary to validate and reveal an `impl Trait`.
281 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
282 pub struct ResolvedOpaqueTy<'tcx> {
283 /// The revealed type as seen by this function.
284 pub concrete_type: Ty<'tcx>,
285 /// Generic parameters on the opaque type as passed by this function.
286 /// For `type Foo<A, B> = impl Bar<A, B>; fn foo<T, U>() -> Foo<T, U> { .. }`
287 /// this is `[T, U]`, not `[A, B]`.
288 pub substs: SubstsRef<'tcx>,
291 /// Whenever a value may be live across a generator yield, the type of that value winds up in the
292 /// `GeneratorInteriorTypeCause` struct. This struct adds additional information about such
293 /// captured types that can be useful for diagnostics. In particular, it stores the span that
294 /// caused a given type to be recorded, along with the scope that enclosed the value (which can
295 /// be used to find the await that the value is live across).
299 /// ```ignore (pseudo-Rust)
307 /// Here, we would store the type `T`, the span of the value `x`, and the "scope-span" for
308 /// the scope that contains `x`.
309 #[derive(RustcEncodable, RustcDecodable, Clone, Debug, Eq, Hash, PartialEq, HashStable)]
310 pub struct GeneratorInteriorTypeCause<'tcx> {
311 /// Type of the captured binding.
313 /// Span of the binding that was captured.
315 /// Span of the scope of the captured binding.
316 pub scope_span: Option<Span>,
317 /// Expr which the type evaluated from.
318 pub expr: Option<hir::HirId>,
321 #[derive(RustcEncodable, RustcDecodable, Debug)]
322 pub struct TypeckTables<'tcx> {
323 /// The `HirId::owner` all `ItemLocalId`s in this table are relative to.
324 pub hir_owner: Option<LocalDefId>,
326 /// Resolved definitions for `<T>::X` associated paths and
327 /// method calls, including those of overloaded operators.
328 type_dependent_defs: ItemLocalMap<Result<(DefKind, DefId), ErrorReported>>,
330 /// Resolved field indices for field accesses in expressions (`S { field }`, `obj.field`)
331 /// or patterns (`S { field }`). The index is often useful by itself, but to learn more
332 /// about the field you also need definition of the variant to which the field
333 /// belongs, but it may not exist if it's a tuple field (`tuple.0`).
334 field_indices: ItemLocalMap<usize>,
336 /// Stores the types for various nodes in the AST. Note that this table
337 /// is not guaranteed to be populated until after typeck. See
338 /// typeck::check::fn_ctxt for details.
339 node_types: ItemLocalMap<Ty<'tcx>>,
341 /// Stores the type parameters which were substituted to obtain the type
342 /// of this node. This only applies to nodes that refer to entities
343 /// parameterized by type parameters, such as generic fns, types, or
345 node_substs: ItemLocalMap<SubstsRef<'tcx>>,
347 /// This will either store the canonicalized types provided by the user
348 /// or the substitutions that the user explicitly gave (if any) attached
349 /// to `id`. These will not include any inferred values. The canonical form
350 /// is used to capture things like `_` or other unspecified values.
352 /// For example, if the user wrote `foo.collect::<Vec<_>>()`, then the
353 /// canonical substitutions would include only `for<X> { Vec<X> }`.
355 /// See also `AscribeUserType` statement in MIR.
356 user_provided_types: ItemLocalMap<CanonicalUserType<'tcx>>,
358 /// Stores the canonicalized types provided by the user. See also
359 /// `AscribeUserType` statement in MIR.
360 pub user_provided_sigs: DefIdMap<CanonicalPolyFnSig<'tcx>>,
362 adjustments: ItemLocalMap<Vec<ty::adjustment::Adjustment<'tcx>>>,
364 /// Stores the actual binding mode for all instances of hir::BindingAnnotation.
365 pat_binding_modes: ItemLocalMap<BindingMode>,
367 /// Stores the types which were implicitly dereferenced in pattern binding modes
368 /// for later usage in HAIR lowering. For example,
371 /// match &&Some(5i32) {
376 /// leads to a `vec![&&Option<i32>, &Option<i32>]`. Empty vectors are not stored.
379 /// https://github.com/rust-lang/rfcs/blob/master/text/2005-match-ergonomics.md#definitions
380 pat_adjustments: ItemLocalMap<Vec<Ty<'tcx>>>,
383 pub upvar_capture_map: ty::UpvarCaptureMap<'tcx>,
385 /// Records the reasons that we picked the kind of each closure;
386 /// not all closures are present in the map.
387 closure_kind_origins: ItemLocalMap<(Span, ast::Name)>,
389 /// For each fn, records the "liberated" types of its arguments
390 /// and return type. Liberated means that all bound regions
391 /// (including late-bound regions) are replaced with free
392 /// equivalents. This table is not used in codegen (since regions
393 /// are erased there) and hence is not serialized to metadata.
394 liberated_fn_sigs: ItemLocalMap<ty::FnSig<'tcx>>,
396 /// For each FRU expression, record the normalized types of the fields
397 /// of the struct - this is needed because it is non-trivial to
398 /// normalize while preserving regions. This table is used only in
399 /// MIR construction and hence is not serialized to metadata.
400 fru_field_types: ItemLocalMap<Vec<Ty<'tcx>>>,
402 /// For every coercion cast we add the HIR node ID of the cast
403 /// expression to this set.
404 coercion_casts: ItemLocalSet,
406 /// Set of trait imports actually used in the method resolution.
407 /// This is used for warning unused imports. During type
408 /// checking, this `Lrc` should not be cloned: it must have a ref-count
409 /// of 1 so that we can insert things into the set mutably.
410 pub used_trait_imports: Lrc<DefIdSet>,
412 /// If any errors occurred while type-checking this body,
413 /// this field will be set to `true`.
414 pub tainted_by_errors: bool,
416 /// All the opaque types that are restricted to concrete types
417 /// by this function.
418 pub concrete_opaque_types: FxHashMap<DefId, ResolvedOpaqueTy<'tcx>>,
420 /// Given the closure ID this map provides the list of UpvarIDs used by it.
421 /// The upvarID contains the HIR node ID and it also contains the full path
422 /// leading to the member of the struct or tuple that is used instead of the
424 pub upvar_list: ty::UpvarListMap,
426 /// Stores the type, expression, span and optional scope span of all types
427 /// that are live across the yield of this generator (if a generator).
428 pub generator_interior_types: Vec<GeneratorInteriorTypeCause<'tcx>>,
431 impl<'tcx> TypeckTables<'tcx> {
432 pub fn empty(hir_owner: Option<LocalDefId>) -> TypeckTables<'tcx> {
435 type_dependent_defs: Default::default(),
436 field_indices: Default::default(),
437 user_provided_types: Default::default(),
438 user_provided_sigs: Default::default(),
439 node_types: Default::default(),
440 node_substs: Default::default(),
441 adjustments: Default::default(),
442 pat_binding_modes: Default::default(),
443 pat_adjustments: Default::default(),
444 upvar_capture_map: Default::default(),
445 closure_kind_origins: Default::default(),
446 liberated_fn_sigs: Default::default(),
447 fru_field_types: Default::default(),
448 coercion_casts: Default::default(),
449 used_trait_imports: Lrc::new(Default::default()),
450 tainted_by_errors: false,
451 concrete_opaque_types: Default::default(),
452 upvar_list: Default::default(),
453 generator_interior_types: Default::default(),
457 /// Returns the final resolution of a `QPath` in an `Expr` or `Pat` node.
458 pub fn qpath_res(&self, qpath: &hir::QPath<'_>, id: hir::HirId) -> Res {
460 hir::QPath::Resolved(_, ref path) => path.res,
461 hir::QPath::TypeRelative(..) => self
462 .type_dependent_def(id)
463 .map_or(Res::Err, |(kind, def_id)| Res::Def(kind, def_id)),
467 pub fn type_dependent_defs(
469 ) -> LocalTableInContext<'_, Result<(DefKind, DefId), ErrorReported>> {
470 LocalTableInContext { hir_owner: self.hir_owner, data: &self.type_dependent_defs }
473 pub fn type_dependent_def(&self, id: HirId) -> Option<(DefKind, DefId)> {
474 validate_hir_id_for_typeck_tables(self.hir_owner, id, false);
475 self.type_dependent_defs.get(&id.local_id).cloned().and_then(|r| r.ok())
478 pub fn type_dependent_def_id(&self, id: HirId) -> Option<DefId> {
479 self.type_dependent_def(id).map(|(_, def_id)| def_id)
482 pub fn type_dependent_defs_mut(
484 ) -> LocalTableInContextMut<'_, Result<(DefKind, DefId), ErrorReported>> {
485 LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.type_dependent_defs }
488 pub fn field_indices(&self) -> LocalTableInContext<'_, usize> {
489 LocalTableInContext { hir_owner: self.hir_owner, data: &self.field_indices }
492 pub fn field_indices_mut(&mut self) -> LocalTableInContextMut<'_, usize> {
493 LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.field_indices }
496 pub fn user_provided_types(&self) -> LocalTableInContext<'_, CanonicalUserType<'tcx>> {
497 LocalTableInContext { hir_owner: self.hir_owner, data: &self.user_provided_types }
500 pub fn user_provided_types_mut(
502 ) -> LocalTableInContextMut<'_, CanonicalUserType<'tcx>> {
503 LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.user_provided_types }
506 pub fn node_types(&self) -> LocalTableInContext<'_, Ty<'tcx>> {
507 LocalTableInContext { hir_owner: self.hir_owner, data: &self.node_types }
510 pub fn node_types_mut(&mut self) -> LocalTableInContextMut<'_, Ty<'tcx>> {
511 LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.node_types }
514 pub fn node_type(&self, id: hir::HirId) -> Ty<'tcx> {
515 self.node_type_opt(id).unwrap_or_else(|| {
516 bug!("node_type: no type for node `{}`", tls::with(|tcx| tcx.hir().node_to_string(id)))
520 pub fn node_type_opt(&self, id: hir::HirId) -> Option<Ty<'tcx>> {
521 validate_hir_id_for_typeck_tables(self.hir_owner, id, false);
522 self.node_types.get(&id.local_id).cloned()
525 pub fn node_substs_mut(&mut self) -> LocalTableInContextMut<'_, SubstsRef<'tcx>> {
526 LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.node_substs }
529 pub fn node_substs(&self, id: hir::HirId) -> SubstsRef<'tcx> {
530 validate_hir_id_for_typeck_tables(self.hir_owner, id, false);
531 self.node_substs.get(&id.local_id).cloned().unwrap_or_else(|| InternalSubsts::empty())
534 pub fn node_substs_opt(&self, id: hir::HirId) -> Option<SubstsRef<'tcx>> {
535 validate_hir_id_for_typeck_tables(self.hir_owner, id, false);
536 self.node_substs.get(&id.local_id).cloned()
539 // Returns the type of a pattern as a monotype. Like @expr_ty, this function
540 // doesn't provide type parameter substitutions.
541 pub fn pat_ty(&self, pat: &hir::Pat<'_>) -> Ty<'tcx> {
542 self.node_type(pat.hir_id)
545 pub fn pat_ty_opt(&self, pat: &hir::Pat<'_>) -> Option<Ty<'tcx>> {
546 self.node_type_opt(pat.hir_id)
549 // Returns the type of an expression as a monotype.
551 // NB (1): This is the PRE-ADJUSTMENT TYPE for the expression. That is, in
552 // some cases, we insert `Adjustment` annotations such as auto-deref or
553 // auto-ref. The type returned by this function does not consider such
554 // adjustments. See `expr_ty_adjusted()` instead.
556 // NB (2): This type doesn't provide type parameter substitutions; e.g., if you
557 // ask for the type of "id" in "id(3)", it will return "fn(&isize) -> isize"
558 // instead of "fn(ty) -> T with T = isize".
559 pub fn expr_ty(&self, expr: &hir::Expr<'_>) -> Ty<'tcx> {
560 self.node_type(expr.hir_id)
563 pub fn expr_ty_opt(&self, expr: &hir::Expr<'_>) -> Option<Ty<'tcx>> {
564 self.node_type_opt(expr.hir_id)
567 pub fn adjustments(&self) -> LocalTableInContext<'_, Vec<ty::adjustment::Adjustment<'tcx>>> {
568 LocalTableInContext { hir_owner: self.hir_owner, data: &self.adjustments }
571 pub fn adjustments_mut(
573 ) -> LocalTableInContextMut<'_, Vec<ty::adjustment::Adjustment<'tcx>>> {
574 LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.adjustments }
577 pub fn expr_adjustments(&self, expr: &hir::Expr<'_>) -> &[ty::adjustment::Adjustment<'tcx>] {
578 validate_hir_id_for_typeck_tables(self.hir_owner, expr.hir_id, false);
579 self.adjustments.get(&expr.hir_id.local_id).map_or(&[], |a| &a[..])
582 /// Returns the type of `expr`, considering any `Adjustment`
583 /// entry recorded for that expression.
584 pub fn expr_ty_adjusted(&self, expr: &hir::Expr<'_>) -> Ty<'tcx> {
585 self.expr_adjustments(expr).last().map_or_else(|| self.expr_ty(expr), |adj| adj.target)
588 pub fn expr_ty_adjusted_opt(&self, expr: &hir::Expr<'_>) -> Option<Ty<'tcx>> {
589 self.expr_adjustments(expr).last().map(|adj| adj.target).or_else(|| self.expr_ty_opt(expr))
592 pub fn is_method_call(&self, expr: &hir::Expr<'_>) -> bool {
593 // Only paths and method calls/overloaded operators have
594 // entries in type_dependent_defs, ignore the former here.
595 if let hir::ExprKind::Path(_) = expr.kind {
599 match self.type_dependent_defs().get(expr.hir_id) {
600 Some(Ok((DefKind::AssocFn, _))) => true,
605 pub fn extract_binding_mode(&self, s: &Session, id: HirId, sp: Span) -> Option<BindingMode> {
606 self.pat_binding_modes().get(id).copied().or_else(|| {
607 s.delay_span_bug(sp, "missing binding mode");
612 pub fn pat_binding_modes(&self) -> LocalTableInContext<'_, BindingMode> {
613 LocalTableInContext { hir_owner: self.hir_owner, data: &self.pat_binding_modes }
616 pub fn pat_binding_modes_mut(&mut self) -> LocalTableInContextMut<'_, BindingMode> {
617 LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.pat_binding_modes }
620 pub fn pat_adjustments(&self) -> LocalTableInContext<'_, Vec<Ty<'tcx>>> {
621 LocalTableInContext { hir_owner: self.hir_owner, data: &self.pat_adjustments }
624 pub fn pat_adjustments_mut(&mut self) -> LocalTableInContextMut<'_, Vec<Ty<'tcx>>> {
625 LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.pat_adjustments }
628 pub fn upvar_capture(&self, upvar_id: ty::UpvarId) -> ty::UpvarCapture<'tcx> {
629 self.upvar_capture_map[&upvar_id]
632 pub fn closure_kind_origins(&self) -> LocalTableInContext<'_, (Span, ast::Name)> {
633 LocalTableInContext { hir_owner: self.hir_owner, data: &self.closure_kind_origins }
636 pub fn closure_kind_origins_mut(&mut self) -> LocalTableInContextMut<'_, (Span, ast::Name)> {
637 LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.closure_kind_origins }
640 pub fn liberated_fn_sigs(&self) -> LocalTableInContext<'_, ty::FnSig<'tcx>> {
641 LocalTableInContext { hir_owner: self.hir_owner, data: &self.liberated_fn_sigs }
644 pub fn liberated_fn_sigs_mut(&mut self) -> LocalTableInContextMut<'_, ty::FnSig<'tcx>> {
645 LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.liberated_fn_sigs }
648 pub fn fru_field_types(&self) -> LocalTableInContext<'_, Vec<Ty<'tcx>>> {
649 LocalTableInContext { hir_owner: self.hir_owner, data: &self.fru_field_types }
652 pub fn fru_field_types_mut(&mut self) -> LocalTableInContextMut<'_, Vec<Ty<'tcx>>> {
653 LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.fru_field_types }
656 pub fn is_coercion_cast(&self, hir_id: hir::HirId) -> bool {
657 validate_hir_id_for_typeck_tables(self.hir_owner, hir_id, true);
658 self.coercion_casts.contains(&hir_id.local_id)
661 pub fn set_coercion_cast(&mut self, id: ItemLocalId) {
662 self.coercion_casts.insert(id);
665 pub fn coercion_casts(&self) -> &ItemLocalSet {
670 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for TypeckTables<'tcx> {
671 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
672 let ty::TypeckTables {
674 ref type_dependent_defs,
676 ref user_provided_types,
677 ref user_provided_sigs,
681 ref pat_binding_modes,
683 ref upvar_capture_map,
684 ref closure_kind_origins,
685 ref liberated_fn_sigs,
690 ref used_trait_imports,
692 ref concrete_opaque_types,
694 ref generator_interior_types,
697 hcx.with_node_id_hashing_mode(NodeIdHashingMode::HashDefPath, |hcx| {
698 type_dependent_defs.hash_stable(hcx, hasher);
699 field_indices.hash_stable(hcx, hasher);
700 user_provided_types.hash_stable(hcx, hasher);
701 user_provided_sigs.hash_stable(hcx, hasher);
702 node_types.hash_stable(hcx, hasher);
703 node_substs.hash_stable(hcx, hasher);
704 adjustments.hash_stable(hcx, hasher);
705 pat_binding_modes.hash_stable(hcx, hasher);
706 pat_adjustments.hash_stable(hcx, hasher);
707 hash_stable_hashmap(hcx, hasher, upvar_capture_map, |up_var_id, hcx| {
708 let ty::UpvarId { var_path, closure_expr_id } = *up_var_id;
710 assert_eq!(Some(var_path.hir_id.owner), hir_owner);
713 hcx.local_def_path_hash(var_path.hir_id.owner),
714 var_path.hir_id.local_id,
715 hcx.local_def_path_hash(closure_expr_id),
719 closure_kind_origins.hash_stable(hcx, hasher);
720 liberated_fn_sigs.hash_stable(hcx, hasher);
721 fru_field_types.hash_stable(hcx, hasher);
722 coercion_casts.hash_stable(hcx, hasher);
723 used_trait_imports.hash_stable(hcx, hasher);
724 tainted_by_errors.hash_stable(hcx, hasher);
725 concrete_opaque_types.hash_stable(hcx, hasher);
726 upvar_list.hash_stable(hcx, hasher);
727 generator_interior_types.hash_stable(hcx, hasher);
732 rustc_index::newtype_index! {
733 pub struct UserTypeAnnotationIndex {
735 DEBUG_FORMAT = "UserType({})",
736 const START_INDEX = 0,
740 /// Mapping of type annotation indices to canonical user type annotations.
741 pub type CanonicalUserTypeAnnotations<'tcx> =
742 IndexVec<UserTypeAnnotationIndex, CanonicalUserTypeAnnotation<'tcx>>;
744 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable, TypeFoldable, Lift)]
745 pub struct CanonicalUserTypeAnnotation<'tcx> {
746 pub user_ty: CanonicalUserType<'tcx>,
748 pub inferred_ty: Ty<'tcx>,
751 /// Canonicalized user type annotation.
752 pub type CanonicalUserType<'tcx> = Canonical<'tcx, UserType<'tcx>>;
754 impl CanonicalUserType<'tcx> {
755 /// Returns `true` if this represents a substitution of the form `[?0, ?1, ?2]`,
756 /// i.e., each thing is mapped to a canonical variable with the same index.
757 pub fn is_identity(&self) -> bool {
759 UserType::Ty(_) => false,
760 UserType::TypeOf(_, user_substs) => {
761 if user_substs.user_self_ty.is_some() {
765 user_substs.substs.iter().zip(BoundVar::new(0)..).all(|(kind, cvar)| {
766 match kind.unpack() {
767 GenericArgKind::Type(ty) => match ty.kind {
768 ty::Bound(debruijn, b) => {
769 // We only allow a `ty::INNERMOST` index in substitutions.
770 assert_eq!(debruijn, ty::INNERMOST);
776 GenericArgKind::Lifetime(r) => match r {
777 ty::ReLateBound(debruijn, br) => {
778 // We only allow a `ty::INNERMOST` index in substitutions.
779 assert_eq!(*debruijn, ty::INNERMOST);
780 cvar == br.assert_bound_var()
785 GenericArgKind::Const(ct) => match ct.val {
786 ty::ConstKind::Bound(debruijn, b) => {
787 // We only allow a `ty::INNERMOST` index in substitutions.
788 assert_eq!(debruijn, ty::INNERMOST);
800 /// A user-given type annotation attached to a constant. These arise
801 /// from constants that are named via paths, like `Foo::<A>::new` and
803 #[derive(Copy, Clone, Debug, PartialEq, RustcEncodable, RustcDecodable)]
804 #[derive(HashStable, TypeFoldable, Lift)]
805 pub enum UserType<'tcx> {
808 /// The canonical type is the result of `type_of(def_id)` with the
809 /// given substitutions applied.
810 TypeOf(DefId, UserSubsts<'tcx>),
813 impl<'tcx> CommonTypes<'tcx> {
814 fn new(interners: &CtxtInterners<'tcx>) -> CommonTypes<'tcx> {
815 let mk = |ty| interners.intern_ty(ty);
818 unit: mk(Tuple(List::empty())),
823 isize: mk(Int(ast::IntTy::Isize)),
824 i8: mk(Int(ast::IntTy::I8)),
825 i16: mk(Int(ast::IntTy::I16)),
826 i32: mk(Int(ast::IntTy::I32)),
827 i64: mk(Int(ast::IntTy::I64)),
828 i128: mk(Int(ast::IntTy::I128)),
829 usize: mk(Uint(ast::UintTy::Usize)),
830 u8: mk(Uint(ast::UintTy::U8)),
831 u16: mk(Uint(ast::UintTy::U16)),
832 u32: mk(Uint(ast::UintTy::U32)),
833 u64: mk(Uint(ast::UintTy::U64)),
834 u128: mk(Uint(ast::UintTy::U128)),
835 f32: mk(Float(ast::FloatTy::F32)),
836 f64: mk(Float(ast::FloatTy::F64)),
837 self_param: mk(ty::Param(ty::ParamTy { index: 0, name: kw::SelfUpper })),
839 trait_object_dummy_self: mk(Infer(ty::FreshTy(0))),
844 impl<'tcx> CommonLifetimes<'tcx> {
845 fn new(interners: &CtxtInterners<'tcx>) -> CommonLifetimes<'tcx> {
846 let mk = |r| interners.region.intern(r, |r| Interned(interners.arena.alloc(r))).0;
849 re_root_empty: mk(RegionKind::ReEmpty(ty::UniverseIndex::ROOT)),
850 re_static: mk(RegionKind::ReStatic),
851 re_erased: mk(RegionKind::ReErased),
856 impl<'tcx> CommonConsts<'tcx> {
857 fn new(interners: &CtxtInterners<'tcx>, types: &CommonTypes<'tcx>) -> CommonConsts<'tcx> {
858 let mk_const = |c| interners.const_.intern(c, |c| Interned(interners.arena.alloc(c))).0;
861 err: mk_const(ty::Const {
862 val: ty::ConstKind::Value(ConstValue::Scalar(Scalar::zst())),
869 // This struct contains information regarding the `ReFree(FreeRegion)` corresponding to a lifetime
872 pub struct FreeRegionInfo {
873 // def id corresponding to FreeRegion
875 // the bound region corresponding to FreeRegion
876 pub boundregion: ty::BoundRegion,
877 // checks if bound region is in Impl Item
878 pub is_impl_item: bool,
881 /// The central data structure of the compiler. It stores references
882 /// to the various **arenas** and also houses the results of the
883 /// various **compiler queries** that have been performed. See the
884 /// [rustc dev guide] for more details.
886 /// [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/ty.html
887 #[derive(Copy, Clone)]
888 #[rustc_diagnostic_item = "TyCtxt"]
889 pub struct TyCtxt<'tcx> {
890 gcx: &'tcx GlobalCtxt<'tcx>,
893 impl<'tcx> Deref for TyCtxt<'tcx> {
894 type Target = &'tcx GlobalCtxt<'tcx>;
896 fn deref(&self) -> &Self::Target {
901 pub struct GlobalCtxt<'tcx> {
902 pub arena: &'tcx WorkerLocal<Arena<'tcx>>,
904 interners: CtxtInterners<'tcx>,
906 pub(crate) cstore: Box<CrateStoreDyn>,
908 pub sess: &'tcx Session,
910 /// This only ever stores a `LintStore` but we don't want a dependency on that type here.
912 /// FIXME(Centril): consider `dyn LintStoreMarker` once
913 /// we can upcast to `Any` for some additional type safety.
914 pub lint_store: Lrc<dyn Any + sync::Sync + sync::Send>,
916 pub dep_graph: DepGraph,
918 pub prof: SelfProfilerRef,
920 /// Common types, pre-interned for your convenience.
921 pub types: CommonTypes<'tcx>,
923 /// Common lifetimes, pre-interned for your convenience.
924 pub lifetimes: CommonLifetimes<'tcx>,
926 /// Common consts, pre-interned for your convenience.
927 pub consts: CommonConsts<'tcx>,
929 /// Resolutions of `extern crate` items produced by resolver.
930 extern_crate_map: NodeMap<CrateNum>,
932 /// Map indicating what traits are in scope for places where this
933 /// is relevant; generated by resolve.
934 trait_map: FxHashMap<LocalDefId, FxHashMap<ItemLocalId, StableVec<TraitCandidate>>>,
936 /// Export map produced by name resolution.
937 export_map: FxHashMap<DefId, Vec<Export<hir::HirId>>>,
939 pub(crate) untracked_crate: &'tcx hir::Crate<'tcx>,
940 pub(crate) definitions: &'tcx Definitions,
942 /// A map from `DefPathHash` -> `DefId`. Includes `DefId`s from the local crate
943 /// as well as all upstream crates. Only populated in incremental mode.
944 pub def_path_hash_to_def_id: Option<FxHashMap<DefPathHash, DefId>>,
946 pub queries: query::Queries<'tcx>,
948 maybe_unused_trait_imports: FxHashSet<DefId>,
949 maybe_unused_extern_crates: Vec<(DefId, Span)>,
950 /// A map of glob use to a set of names it actually imports. Currently only
951 /// used in save-analysis.
952 glob_map: FxHashMap<DefId, FxHashSet<ast::Name>>,
953 /// Extern prelude entries. The value is `true` if the entry was introduced
954 /// via `extern crate` item and not `--extern` option or compiler built-in.
955 pub extern_prelude: FxHashMap<ast::Name, bool>,
957 // Internal cache for metadata decoding. No need to track deps on this.
958 pub rcache: Lock<FxHashMap<ty::CReaderCacheKey, Ty<'tcx>>>,
960 /// Caches the results of trait selection. This cache is used
961 /// for things that do not have to do with the parameters in scope.
962 pub selection_cache: traits::SelectionCache<'tcx>,
964 /// Caches the results of trait evaluation. This cache is used
965 /// for things that do not have to do with the parameters in scope.
966 /// Merge this with `selection_cache`?
967 pub evaluation_cache: traits::EvaluationCache<'tcx>,
969 /// The definite name of the current crate after taking into account
970 /// attributes, commandline parameters, etc.
971 pub crate_name: Symbol,
973 /// Data layout specification for the current target.
974 pub data_layout: TargetDataLayout,
976 /// `#[stable]` and `#[unstable]` attributes
977 stability_interner: ShardedHashMap<&'tcx attr::Stability, ()>,
979 /// `#[rustc_const_stable]` and `#[rustc_const_unstable]` attributes
980 const_stability_interner: ShardedHashMap<&'tcx attr::ConstStability, ()>,
982 /// Stores the value of constants (and deduplicates the actual memory)
983 allocation_interner: ShardedHashMap<&'tcx Allocation, ()>,
985 /// Stores memory for globals (statics/consts).
986 pub alloc_map: Lock<interpret::AllocMap<'tcx>>,
988 layout_interner: ShardedHashMap<&'tcx Layout, ()>,
990 output_filenames: Arc<OutputFilenames>,
993 impl<'tcx> TyCtxt<'tcx> {
994 pub fn alloc_steal_mir(self, mir: BodyAndCache<'tcx>) -> &'tcx Steal<BodyAndCache<'tcx>> {
995 self.arena.alloc(Steal::new(mir))
998 pub fn alloc_steal_promoted(
1000 promoted: IndexVec<Promoted, BodyAndCache<'tcx>>,
1001 ) -> &'tcx Steal<IndexVec<Promoted, BodyAndCache<'tcx>>> {
1002 self.arena.alloc(Steal::new(promoted))
1005 pub fn intern_promoted(
1007 promoted: IndexVec<Promoted, BodyAndCache<'tcx>>,
1008 ) -> &'tcx IndexVec<Promoted, BodyAndCache<'tcx>> {
1009 self.arena.alloc(promoted)
1012 pub fn alloc_adt_def(
1016 variants: IndexVec<VariantIdx, ty::VariantDef>,
1018 ) -> &'tcx ty::AdtDef {
1019 let def = ty::AdtDef::new(self, did, kind, variants, repr);
1020 self.arena.alloc(def)
1023 pub fn intern_const_alloc(self, alloc: Allocation) -> &'tcx Allocation {
1024 self.allocation_interner.intern(alloc, |alloc| self.arena.alloc(alloc))
1027 /// Allocates a read-only byte or string literal for `mir::interpret`.
1028 pub fn allocate_bytes(self, bytes: &[u8]) -> interpret::AllocId {
1029 // Create an allocation that just contains these bytes.
1030 let alloc = interpret::Allocation::from_byte_aligned_bytes(bytes);
1031 let alloc = self.intern_const_alloc(alloc);
1032 self.alloc_map.lock().create_memory_alloc(alloc)
1035 pub fn intern_stability(self, stab: attr::Stability) -> &'tcx attr::Stability {
1036 self.stability_interner.intern(stab, |stab| self.arena.alloc(stab))
1039 pub fn intern_const_stability(self, stab: attr::ConstStability) -> &'tcx attr::ConstStability {
1040 self.const_stability_interner.intern(stab, |stab| self.arena.alloc(stab))
1043 pub fn intern_layout(self, layout: Layout) -> &'tcx Layout {
1044 self.layout_interner.intern(layout, |layout| self.arena.alloc(layout))
1047 /// Returns a range of the start/end indices specified with the
1048 /// `rustc_layout_scalar_valid_range` attribute.
1049 pub fn layout_scalar_valid_range(self, def_id: DefId) -> (Bound<u128>, Bound<u128>) {
1050 let attrs = self.get_attrs(def_id);
1052 let attr = match attrs.iter().find(|a| a.check_name(name)) {
1054 None => return Bound::Unbounded,
1056 for meta in attr.meta_item_list().expect("rustc_layout_scalar_valid_range takes args") {
1057 match meta.literal().expect("attribute takes lit").kind {
1058 ast::LitKind::Int(a, _) => return Bound::Included(a),
1059 _ => span_bug!(attr.span, "rustc_layout_scalar_valid_range expects int arg"),
1062 span_bug!(attr.span, "no arguments to `rustc_layout_scalar_valid_range` attribute");
1065 get(sym::rustc_layout_scalar_valid_range_start),
1066 get(sym::rustc_layout_scalar_valid_range_end),
1070 pub fn lift<T: ?Sized + Lift<'tcx>>(self, value: &T) -> Option<T::Lifted> {
1071 value.lift_to_tcx(self)
1074 /// Creates a type context and call the closure with a `TyCtxt` reference
1075 /// to the context. The closure enforces that the type context and any interned
1076 /// value (types, substs, etc.) can only be used while `ty::tls` has a valid
1077 /// reference to the context, to allow formatting values that need it.
1078 pub fn create_global_ctxt(
1080 lint_store: Lrc<dyn Any + sync::Send + sync::Sync>,
1081 local_providers: ty::query::Providers<'tcx>,
1082 extern_providers: ty::query::Providers<'tcx>,
1083 arena: &'tcx WorkerLocal<Arena<'tcx>>,
1084 resolutions: ty::ResolverOutputs,
1085 krate: &'tcx hir::Crate<'tcx>,
1086 definitions: &'tcx Definitions,
1087 dep_graph: DepGraph,
1088 on_disk_query_result_cache: query::OnDiskCache<'tcx>,
1090 output_filenames: &OutputFilenames,
1091 ) -> GlobalCtxt<'tcx> {
1092 let data_layout = TargetDataLayout::parse(&s.target.target).unwrap_or_else(|err| {
1095 let interners = CtxtInterners::new(arena);
1096 let common_types = CommonTypes::new(&interners);
1097 let common_lifetimes = CommonLifetimes::new(&interners);
1098 let common_consts = CommonConsts::new(&interners, &common_types);
1099 let cstore = resolutions.cstore;
1100 let crates = cstore.crates_untracked();
1101 let max_cnum = crates.iter().map(|c| c.as_usize()).max().unwrap_or(0);
1102 let mut providers = IndexVec::from_elem_n(extern_providers, max_cnum + 1);
1103 providers[LOCAL_CRATE] = local_providers;
1105 let def_path_hash_to_def_id = if s.opts.build_dep_graph() {
1106 let def_path_tables = crates
1108 .map(|&cnum| (cnum, cstore.def_path_table(cnum)))
1109 .chain(iter::once((LOCAL_CRATE, definitions.def_path_table())));
1111 // Precompute the capacity of the hashmap so we don't have to
1112 // re-allocate when populating it.
1113 let capacity = def_path_tables.clone().map(|(_, t)| t.size()).sum::<usize>();
1115 let mut map: FxHashMap<_, _> =
1116 FxHashMap::with_capacity_and_hasher(capacity, ::std::default::Default::default());
1118 for (cnum, def_path_table) in def_path_tables {
1119 def_path_table.add_def_path_hashes_to(cnum, &mut map);
1127 let mut trait_map: FxHashMap<_, FxHashMap<_, _>> = FxHashMap::default();
1128 for (k, v) in resolutions.trait_map {
1129 let hir_id = definitions.node_id_to_hir_id(k);
1130 let map = trait_map.entry(hir_id.owner).or_default();
1133 .map(|tc| tc.map_import_ids(|id| definitions.node_id_to_hir_id(id)))
1135 map.insert(hir_id.local_id, StableVec::new(v));
1145 prof: s.prof.clone(),
1146 types: common_types,
1147 lifetimes: common_lifetimes,
1148 consts: common_consts,
1149 extern_crate_map: resolutions.extern_crate_map,
1151 export_map: resolutions
1155 let exports: Vec<_> = v
1157 .map(|e| e.map_id(|id| definitions.node_id_to_hir_id(id)))
1162 maybe_unused_trait_imports: resolutions
1163 .maybe_unused_trait_imports
1165 .map(|id| definitions.local_def_id(id).to_def_id())
1167 maybe_unused_extern_crates: resolutions
1168 .maybe_unused_extern_crates
1170 .map(|(id, sp)| (definitions.local_def_id(id).to_def_id(), sp))
1172 glob_map: resolutions
1175 .map(|(id, names)| (definitions.local_def_id(id).to_def_id(), names))
1177 extern_prelude: resolutions.extern_prelude,
1178 untracked_crate: krate,
1180 def_path_hash_to_def_id,
1181 queries: query::Queries::new(providers, extern_providers, on_disk_query_result_cache),
1182 rcache: Default::default(),
1183 selection_cache: Default::default(),
1184 evaluation_cache: Default::default(),
1185 crate_name: Symbol::intern(crate_name),
1187 layout_interner: Default::default(),
1188 stability_interner: Default::default(),
1189 const_stability_interner: Default::default(),
1190 allocation_interner: Default::default(),
1191 alloc_map: Lock::new(interpret::AllocMap::new()),
1192 output_filenames: Arc::new(output_filenames.clone()),
1196 pub fn consider_optimizing<T: Fn() -> String>(&self, msg: T) -> bool {
1197 let cname = self.crate_name(LOCAL_CRATE).as_str();
1198 self.sess.consider_optimizing(&cname, msg)
1201 pub fn lib_features(self) -> &'tcx middle::lib_features::LibFeatures {
1202 self.get_lib_features(LOCAL_CRATE)
1205 /// Obtain all lang items of this crate and all dependencies (recursively)
1206 pub fn lang_items(self) -> &'tcx rustc_hir::lang_items::LanguageItems {
1207 self.get_lang_items(LOCAL_CRATE)
1210 /// Obtain the given diagnostic item's `DefId`. Use `is_diagnostic_item` if you just want to
1211 /// compare against another `DefId`, since `is_diagnostic_item` is cheaper.
1212 pub fn get_diagnostic_item(self, name: Symbol) -> Option<DefId> {
1213 self.all_diagnostic_items(LOCAL_CRATE).get(&name).copied()
1216 /// Check whether the diagnostic item with the given `name` has the given `DefId`.
1217 pub fn is_diagnostic_item(self, name: Symbol, did: DefId) -> bool {
1218 self.diagnostic_items(did.krate).get(&name) == Some(&did)
1221 pub fn stability(self) -> &'tcx stability::Index<'tcx> {
1222 self.stability_index(LOCAL_CRATE)
1225 pub fn crates(self) -> &'tcx [CrateNum] {
1226 self.all_crate_nums(LOCAL_CRATE)
1229 pub fn allocator_kind(self) -> Option<AllocatorKind> {
1230 self.cstore.allocator_kind()
1233 pub fn features(self) -> &'tcx rustc_feature::Features {
1234 self.features_query(LOCAL_CRATE)
1237 pub fn def_key(self, id: DefId) -> rustc_hir::definitions::DefKey {
1238 if let Some(id) = id.as_local() { self.hir().def_key(id) } else { self.cstore.def_key(id) }
1241 /// Converts a `DefId` into its fully expanded `DefPath` (every
1242 /// `DefId` is really just an interned `DefPath`).
1244 /// Note that if `id` is not local to this crate, the result will
1245 /// be a non-local `DefPath`.
1246 pub fn def_path(self, id: DefId) -> rustc_hir::definitions::DefPath {
1247 if let Some(id) = id.as_local() {
1248 self.hir().def_path(id)
1250 self.cstore.def_path(id)
1254 /// Returns whether or not the crate with CrateNum 'cnum'
1255 /// is marked as a private dependency
1256 pub fn is_private_dep(self, cnum: CrateNum) -> bool {
1257 if cnum == LOCAL_CRATE { false } else { self.cstore.crate_is_private_dep_untracked(cnum) }
1261 pub fn def_path_hash(self, def_id: DefId) -> rustc_hir::definitions::DefPathHash {
1262 if let Some(def_id) = def_id.as_local() {
1263 self.definitions.def_path_hash(def_id)
1265 self.cstore.def_path_hash(def_id)
1269 pub fn def_path_debug_str(self, def_id: DefId) -> String {
1270 // We are explicitly not going through queries here in order to get
1271 // crate name and disambiguator since this code is called from debug!()
1272 // statements within the query system and we'd run into endless
1273 // recursion otherwise.
1274 let (crate_name, crate_disambiguator) = if def_id.is_local() {
1275 (self.crate_name, self.sess.local_crate_disambiguator())
1278 self.cstore.crate_name_untracked(def_id.krate),
1279 self.cstore.crate_disambiguator_untracked(def_id.krate),
1286 // Don't print the whole crate disambiguator. That's just
1287 // annoying in debug output.
1288 &(crate_disambiguator.to_fingerprint().to_hex())[..4],
1289 self.def_path(def_id).to_string_no_crate()
1293 pub fn metadata_encoding_version(self) -> Vec<u8> {
1294 self.cstore.metadata_encoding_version().to_vec()
1297 pub fn encode_metadata(self) -> EncodedMetadata {
1298 let _prof_timer = self.prof.verbose_generic_activity("generate_crate_metadata");
1299 self.cstore.encode_metadata(self)
1302 // Note that this is *untracked* and should only be used within the query
1303 // system if the result is otherwise tracked through queries
1304 pub fn cstore_as_any(self) -> &'tcx dyn Any {
1305 self.cstore.as_any()
1309 pub fn create_stable_hashing_context(self) -> StableHashingContext<'tcx> {
1310 let krate = self.gcx.untracked_crate;
1312 StableHashingContext::new(self.sess, krate, self.definitions, &*self.cstore)
1315 // This method makes sure that we have a DepNode and a Fingerprint for
1316 // every upstream crate. It needs to be called once right after the tcx is
1318 // With full-fledged red/green, the method will probably become unnecessary
1319 // as this will be done on-demand.
1320 pub fn allocate_metadata_dep_nodes(self) {
1321 // We cannot use the query versions of crates() and crate_hash(), since
1322 // those would need the DepNodes that we are allocating here.
1323 for cnum in self.cstore.crates_untracked() {
1324 let dep_node = DepConstructor::CrateMetadata(self, cnum);
1325 let crate_hash = self.cstore.crate_hash_untracked(cnum);
1326 self.dep_graph.with_task(
1330 |_, x| x, // No transformation needed
1331 dep_graph::hash_result,
1336 pub fn serialize_query_result_cache<E>(self, encoder: &mut E) -> Result<(), E::Error>
1338 E: ty::codec::TyEncoder,
1340 self.queries.on_disk_cache.serialize(self, encoder)
1343 /// If `true`, we should use the MIR-based borrowck, but also
1344 /// fall back on the AST borrowck if the MIR-based one errors.
1345 pub fn migrate_borrowck(self) -> bool {
1346 self.borrowck_mode().migrate()
1349 /// What mode(s) of borrowck should we run? AST? MIR? both?
1350 /// (Also considers the `#![feature(nll)]` setting.)
1351 pub fn borrowck_mode(&self) -> BorrowckMode {
1352 // Here are the main constraints we need to deal with:
1354 // 1. An opts.borrowck_mode of `BorrowckMode::Migrate` is
1355 // synonymous with no `-Z borrowck=...` flag at all.
1357 // 2. We want to allow developers on the Nightly channel
1358 // to opt back into the "hard error" mode for NLL,
1359 // (which they can do via specifying `#![feature(nll)]`
1360 // explicitly in their crate).
1362 // So, this precedence list is how pnkfelix chose to work with
1363 // the above constraints:
1365 // * `#![feature(nll)]` *always* means use NLL with hard
1366 // errors. (To simplify the code here, it now even overrides
1367 // a user's attempt to specify `-Z borrowck=compare`, which
1368 // we arguably do not need anymore and should remove.)
1370 // * Otherwise, if no `-Z borrowck=...` then use migrate mode
1372 // * Otherwise, use the behavior requested via `-Z borrowck=...`
1374 if self.features().nll {
1375 return BorrowckMode::Mir;
1378 self.sess.opts.borrowck_mode
1382 pub fn local_crate_exports_generics(self) -> bool {
1383 debug_assert!(self.sess.opts.share_generics());
1385 self.sess.crate_types.borrow().iter().any(|crate_type| {
1387 CrateType::Executable
1388 | CrateType::Staticlib
1389 | CrateType::ProcMacro
1390 | CrateType::Cdylib => false,
1392 // FIXME rust-lang/rust#64319, rust-lang/rust#64872:
1393 // We want to block export of generics from dylibs,
1394 // but we must fix rust-lang/rust#65890 before we can
1395 // do that robustly.
1396 CrateType::Dylib => true,
1398 CrateType::Rlib => true,
1403 // Returns the `DefId` and the `BoundRegion` corresponding to the given region.
1404 pub fn is_suitable_region(&self, region: Region<'tcx>) -> Option<FreeRegionInfo> {
1405 let (suitable_region_binding_scope, bound_region) = match *region {
1406 ty::ReFree(ref free_region) => (free_region.scope, free_region.bound_region),
1407 ty::ReEarlyBound(ref ebr) => {
1408 (self.parent(ebr.def_id).unwrap(), ty::BoundRegion::BrNamed(ebr.def_id, ebr.name))
1410 _ => return None, // not a free region
1413 let hir_id = self.hir().as_local_hir_id(suitable_region_binding_scope).unwrap();
1414 let is_impl_item = match self.hir().find(hir_id) {
1415 Some(Node::Item(..)) | Some(Node::TraitItem(..)) => false,
1416 Some(Node::ImplItem(..)) => {
1417 self.is_bound_region_in_impl_item(suitable_region_binding_scope)
1422 Some(FreeRegionInfo {
1423 def_id: suitable_region_binding_scope,
1424 boundregion: bound_region,
1429 pub fn return_type_impl_trait(&self, scope_def_id: DefId) -> Option<(Ty<'tcx>, Span)> {
1430 // HACK: `type_of_def_id()` will fail on these (#55796), so return `None`.
1431 let hir_id = self.hir().as_local_hir_id(scope_def_id).unwrap();
1432 match self.hir().get(hir_id) {
1433 Node::Item(item) => {
1435 ItemKind::Fn(..) => { /* `type_of_def_id()` will work */ }
1441 _ => { /* `type_of_def_id()` will work or panic */ }
1444 let ret_ty = self.type_of(scope_def_id);
1446 ty::FnDef(_, _) => {
1447 let sig = ret_ty.fn_sig(*self);
1448 let output = self.erase_late_bound_regions(&sig.output());
1449 if output.is_impl_trait() {
1450 let fn_decl = self.hir().fn_decl_by_hir_id(hir_id).unwrap();
1451 Some((output, fn_decl.output.span()))
1460 // Checks if the bound region is in Impl Item.
1461 pub fn is_bound_region_in_impl_item(&self, suitable_region_binding_scope: DefId) -> bool {
1462 let container_id = self.associated_item(suitable_region_binding_scope).container.id();
1463 if self.impl_trait_ref(container_id).is_some() {
1464 // For now, we do not try to target impls of traits. This is
1465 // because this message is going to suggest that the user
1466 // change the fn signature, but they may not be free to do so,
1467 // since the signature must match the trait.
1469 // FIXME(#42706) -- in some cases, we could do better here.
1475 /// Determines whether identifiers in the assembly have strict naming rules.
1476 /// Currently, only NVPTX* targets need it.
1477 pub fn has_strict_asm_symbol_naming(&self) -> bool {
1478 self.sess.target.target.arch.contains("nvptx")
1481 /// Returns `&'static core::panic::Location<'static>`.
1482 pub fn caller_location_ty(&self) -> Ty<'tcx> {
1484 self.lifetimes.re_static,
1485 self.type_of(self.require_lang_item(PanicLocationLangItem, None))
1486 .subst(*self, self.mk_substs([self.lifetimes.re_static.into()].iter())),
1490 /// Returns a displayable description and article for the given `def_id` (e.g. `("a", "struct")`).
1491 pub fn article_and_description(&self, def_id: DefId) -> (&'static str, &'static str) {
1492 self.def_kind(def_id)
1493 .map(|def_kind| (def_kind.article(), def_kind.descr(def_id)))
1494 .unwrap_or_else(|| match self.def_key(def_id).disambiguated_data.data {
1495 DefPathData::ClosureExpr => match self.generator_kind(def_id) {
1496 None => ("a", "closure"),
1497 Some(rustc_hir::GeneratorKind::Async(..)) => ("an", "async closure"),
1498 Some(rustc_hir::GeneratorKind::Gen) => ("a", "generator"),
1500 DefPathData::LifetimeNs(..) => ("a", "lifetime"),
1501 DefPathData::Impl => ("an", "implementation"),
1502 DefPathData::TypeNs(..) | DefPathData::ValueNs(..) | DefPathData::MacroNs(..) => {
1505 _ => bug!("article_and_description called on def_id {:?}", def_id),
1510 impl<'tcx> GlobalCtxt<'tcx> {
1511 /// Calls the closure with a local `TyCtxt` using the given arena.
1512 /// `interners` is a slot passed so we can create a CtxtInterners
1513 /// with the same lifetime as `arena`.
1514 pub fn enter_local<F, R>(&'tcx self, f: F) -> R
1516 F: FnOnce(TyCtxt<'tcx>) -> R,
1518 let tcx = TyCtxt { gcx: self };
1519 ty::tls::with_related_context(tcx, |icx| {
1520 let new_icx = ty::tls::ImplicitCtxt {
1523 diagnostics: icx.diagnostics,
1524 layout_depth: icx.layout_depth,
1525 task_deps: icx.task_deps,
1527 ty::tls::enter_context(&new_icx, |_| f(tcx))
1532 /// A trait implemented for all `X<'a>` types that can be safely and
1533 /// efficiently converted to `X<'tcx>` as long as they are part of the
1534 /// provided `TyCtxt<'tcx>`.
1535 /// This can be done, for example, for `Ty<'tcx>` or `SubstsRef<'tcx>`
1536 /// by looking them up in their respective interners.
1538 /// However, this is still not the best implementation as it does
1539 /// need to compare the components, even for interned values.
1540 /// It would be more efficient if `TypedArena` provided a way to
1541 /// determine whether the address is in the allocated range.
1543 /// `None` is returned if the value or one of the components is not part
1544 /// of the provided context.
1545 /// For `Ty`, `None` can be returned if either the type interner doesn't
1546 /// contain the `TyKind` key or if the address of the interned
1547 /// pointer differs. The latter case is possible if a primitive type,
1548 /// e.g., `()` or `u8`, was interned in a different context.
1549 pub trait Lift<'tcx>: fmt::Debug {
1550 type Lifted: fmt::Debug + 'tcx;
1551 fn lift_to_tcx(&self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted>;
1554 macro_rules! nop_lift {
1555 ($set:ident; $ty:ty => $lifted:ty) => {
1556 impl<'a, 'tcx> Lift<'tcx> for $ty {
1557 type Lifted = $lifted;
1558 fn lift_to_tcx(&self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
1559 if tcx.interners.$set.contains_pointer_to(&Interned(*self)) {
1560 Some(unsafe { mem::transmute(*self) })
1569 macro_rules! nop_list_lift {
1570 ($set:ident; $ty:ty => $lifted:ty) => {
1571 impl<'a, 'tcx> Lift<'tcx> for &'a List<$ty> {
1572 type Lifted = &'tcx List<$lifted>;
1573 fn lift_to_tcx(&self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
1574 if self.is_empty() {
1575 return Some(List::empty());
1577 if tcx.interners.$set.contains_pointer_to(&Interned(*self)) {
1578 Some(unsafe { mem::transmute(*self) })
1587 nop_lift! {type_; Ty<'a> => Ty<'tcx>}
1588 nop_lift! {region; Region<'a> => Region<'tcx>}
1589 nop_lift! {goal; Goal<'a> => Goal<'tcx>}
1590 nop_lift! {const_; &'a Const<'a> => &'tcx Const<'tcx>}
1592 nop_list_lift! {goal_list; Goal<'a> => Goal<'tcx>}
1593 nop_list_lift! {clauses; Clause<'a> => Clause<'tcx>}
1594 nop_list_lift! {type_list; Ty<'a> => Ty<'tcx>}
1595 nop_list_lift! {existential_predicates; ExistentialPredicate<'a> => ExistentialPredicate<'tcx>}
1596 nop_list_lift! {predicates; Predicate<'a> => Predicate<'tcx>}
1597 nop_list_lift! {canonical_var_infos; CanonicalVarInfo => CanonicalVarInfo}
1598 nop_list_lift! {projs; ProjectionKind => ProjectionKind}
1600 // This is the impl for `&'a InternalSubsts<'a>`.
1601 nop_list_lift! {substs; GenericArg<'a> => GenericArg<'tcx>}
1604 use super::{ptr_eq, GlobalCtxt, TyCtxt};
1606 use crate::dep_graph::{DepKind, TaskDeps};
1607 use crate::ty::query;
1608 use rustc_data_structures::sync::{self, Lock};
1609 use rustc_data_structures::thin_vec::ThinVec;
1610 use rustc_data_structures::OnDrop;
1611 use rustc_errors::Diagnostic;
1614 #[cfg(not(parallel_compiler))]
1615 use std::cell::Cell;
1617 #[cfg(parallel_compiler)]
1618 use rustc_rayon_core as rayon_core;
1620 /// This is the implicit state of rustc. It contains the current
1621 /// `TyCtxt` and query. It is updated when creating a local interner or
1622 /// executing a new query. Whenever there's a `TyCtxt` value available
1623 /// you should also have access to an `ImplicitCtxt` through the functions
1626 pub struct ImplicitCtxt<'a, 'tcx> {
1627 /// The current `TyCtxt`. Initially created by `enter_global` and updated
1628 /// by `enter_local` with a new local interner.
1629 pub tcx: TyCtxt<'tcx>,
1631 /// The current query job, if any. This is updated by `JobOwner::start` in
1632 /// `ty::query::plumbing` when executing a query.
1633 pub query: Option<query::QueryJobId<DepKind>>,
1635 /// Where to store diagnostics for the current query job, if any.
1636 /// This is updated by `JobOwner::start` in `ty::query::plumbing` when executing a query.
1637 pub diagnostics: Option<&'a Lock<ThinVec<Diagnostic>>>,
1639 /// Used to prevent layout from recursing too deeply.
1640 pub layout_depth: usize,
1642 /// The current dep graph task. This is used to add dependencies to queries
1643 /// when executing them.
1644 pub task_deps: Option<&'a Lock<TaskDeps>>,
1647 /// Sets Rayon's thread-local variable, which is preserved for Rayon jobs
1648 /// to `value` during the call to `f`. It is restored to its previous value after.
1649 /// This is used to set the pointer to the new `ImplicitCtxt`.
1650 #[cfg(parallel_compiler)]
1652 fn set_tlv<F: FnOnce() -> R, R>(value: usize, f: F) -> R {
1653 rayon_core::tlv::with(value, f)
1656 /// Gets Rayon's thread-local variable, which is preserved for Rayon jobs.
1657 /// This is used to get the pointer to the current `ImplicitCtxt`.
1658 #[cfg(parallel_compiler)]
1660 fn get_tlv() -> usize {
1661 rayon_core::tlv::get()
1664 #[cfg(not(parallel_compiler))]
1666 /// A thread local variable that stores a pointer to the current `ImplicitCtxt`.
1667 static TLV: Cell<usize> = Cell::new(0);
1670 /// Sets TLV to `value` during the call to `f`.
1671 /// It is restored to its previous value after.
1672 /// This is used to set the pointer to the new `ImplicitCtxt`.
1673 #[cfg(not(parallel_compiler))]
1675 fn set_tlv<F: FnOnce() -> R, R>(value: usize, f: F) -> R {
1676 let old = get_tlv();
1677 let _reset = OnDrop(move || TLV.with(|tlv| tlv.set(old)));
1678 TLV.with(|tlv| tlv.set(value));
1682 /// Gets the pointer to the current `ImplicitCtxt`.
1683 #[cfg(not(parallel_compiler))]
1685 fn get_tlv() -> usize {
1686 TLV.with(|tlv| tlv.get())
1689 /// Sets `context` as the new current `ImplicitCtxt` for the duration of the function `f`.
1691 pub fn enter_context<'a, 'tcx, F, R>(context: &ImplicitCtxt<'a, 'tcx>, f: F) -> R
1693 F: FnOnce(&ImplicitCtxt<'a, 'tcx>) -> R,
1695 set_tlv(context as *const _ as usize, || f(&context))
1698 /// Enters `GlobalCtxt` by setting up librustc_ast callbacks and
1699 /// creating a initial `TyCtxt` and `ImplicitCtxt`.
1700 /// This happens once per rustc session and `TyCtxt`s only exists
1701 /// inside the `f` function.
1702 pub fn enter_global<'tcx, F, R>(gcx: &'tcx GlobalCtxt<'tcx>, f: F) -> R
1704 F: FnOnce(TyCtxt<'tcx>) -> R,
1706 // Update `GCX_PTR` to indicate there's a `GlobalCtxt` available.
1707 GCX_PTR.with(|lock| {
1708 *lock.lock() = gcx as *const _ as usize;
1710 // Set `GCX_PTR` back to 0 when we exit.
1711 let _on_drop = OnDrop(move || {
1712 GCX_PTR.with(|lock| *lock.lock() = 0);
1715 let tcx = TyCtxt { gcx };
1717 ImplicitCtxt { tcx, query: None, diagnostics: None, layout_depth: 0, task_deps: None };
1718 enter_context(&icx, |_| f(tcx))
1721 scoped_thread_local! {
1722 /// Stores a pointer to the `GlobalCtxt` if one is available.
1723 /// This is used to access the `GlobalCtxt` in the deadlock handler given to Rayon.
1724 pub static GCX_PTR: Lock<usize>
1727 /// Creates a `TyCtxt` and `ImplicitCtxt` based on the `GCX_PTR` thread local.
1728 /// This is used in the deadlock handler.
1729 pub unsafe fn with_global<F, R>(f: F) -> R
1731 F: for<'tcx> FnOnce(TyCtxt<'tcx>) -> R,
1733 let gcx = GCX_PTR.with(|lock| *lock.lock());
1735 let gcx = &*(gcx as *const GlobalCtxt<'_>);
1736 let tcx = TyCtxt { gcx };
1738 ImplicitCtxt { query: None, diagnostics: None, tcx, layout_depth: 0, task_deps: None };
1739 enter_context(&icx, |_| f(tcx))
1742 /// Allows access to the current `ImplicitCtxt` in a closure if one is available.
1744 pub fn with_context_opt<F, R>(f: F) -> R
1746 F: for<'a, 'tcx> FnOnce(Option<&ImplicitCtxt<'a, 'tcx>>) -> R,
1748 let context = get_tlv();
1752 // We could get a `ImplicitCtxt` pointer from another thread.
1753 // Ensure that `ImplicitCtxt` is `Sync`.
1754 sync::assert_sync::<ImplicitCtxt<'_, '_>>();
1756 unsafe { f(Some(&*(context as *const ImplicitCtxt<'_, '_>))) }
1760 /// Allows access to the current `ImplicitCtxt`.
1761 /// Panics if there is no `ImplicitCtxt` available.
1763 pub fn with_context<F, R>(f: F) -> R
1765 F: for<'a, 'tcx> FnOnce(&ImplicitCtxt<'a, 'tcx>) -> R,
1767 with_context_opt(|opt_context| f(opt_context.expect("no ImplicitCtxt stored in tls")))
1770 /// Allows access to the current `ImplicitCtxt` whose tcx field has the same global
1771 /// interner as the tcx argument passed in. This means the closure is given an `ImplicitCtxt`
1772 /// with the same `'tcx` lifetime as the `TyCtxt` passed in.
1773 /// This will panic if you pass it a `TyCtxt` which has a different global interner from
1774 /// the current `ImplicitCtxt`'s `tcx` field.
1776 pub fn with_related_context<'tcx, F, R>(tcx: TyCtxt<'tcx>, f: F) -> R
1778 F: FnOnce(&ImplicitCtxt<'_, 'tcx>) -> R,
1780 with_context(|context| unsafe {
1781 assert!(ptr_eq(context.tcx.gcx, tcx.gcx));
1782 let context: &ImplicitCtxt<'_, '_> = mem::transmute(context);
1787 /// Allows access to the `TyCtxt` in the current `ImplicitCtxt`.
1788 /// Panics if there is no `ImplicitCtxt` available.
1790 pub fn with<F, R>(f: F) -> R
1792 F: for<'tcx> FnOnce(TyCtxt<'tcx>) -> R,
1794 with_context(|context| f(context.tcx))
1797 /// Allows access to the `TyCtxt` in the current `ImplicitCtxt`.
1798 /// The closure is passed None if there is no `ImplicitCtxt` available.
1800 pub fn with_opt<F, R>(f: F) -> R
1802 F: for<'tcx> FnOnce(Option<TyCtxt<'tcx>>) -> R,
1804 with_context_opt(|opt_context| f(opt_context.map(|context| context.tcx)))
1808 macro_rules! sty_debug_print {
1809 ($ctxt: expr, $($variant: ident),*) => {{
1810 // Curious inner module to allow variant names to be used as
1812 #[allow(non_snake_case)]
1814 use crate::ty::{self, TyCtxt};
1815 use crate::ty::context::Interned;
1817 #[derive(Copy, Clone)]
1826 pub fn go(tcx: TyCtxt<'_>) {
1827 let mut total = DebugStat {
1834 $(let mut $variant = total;)*
1836 let shards = tcx.interners.type_.lock_shards();
1837 let types = shards.iter().flat_map(|shard| shard.keys());
1838 for &Interned(t) in types {
1839 let variant = match t.kind {
1840 ty::Bool | ty::Char | ty::Int(..) | ty::Uint(..) |
1841 ty::Float(..) | ty::Str | ty::Never => continue,
1842 ty::Error => /* unimportant */ continue,
1843 $(ty::$variant(..) => &mut $variant,)*
1845 let lt = t.flags.intersects(ty::TypeFlags::HAS_RE_INFER);
1846 let ty = t.flags.intersects(ty::TypeFlags::HAS_TY_INFER);
1847 let ct = t.flags.intersects(ty::TypeFlags::HAS_CT_INFER);
1851 if lt { total.lt_infer += 1; variant.lt_infer += 1 }
1852 if ty { total.ty_infer += 1; variant.ty_infer += 1 }
1853 if ct { total.ct_infer += 1; variant.ct_infer += 1 }
1854 if lt && ty && ct { total.all_infer += 1; variant.all_infer += 1 }
1856 println!("Ty interner total ty lt ct all");
1857 $(println!(" {:18}: {uses:6} {usespc:4.1}%, \
1858 {ty:4.1}% {lt:5.1}% {ct:4.1}% {all:4.1}%",
1859 stringify!($variant),
1860 uses = $variant.total,
1861 usespc = $variant.total as f64 * 100.0 / total.total as f64,
1862 ty = $variant.ty_infer as f64 * 100.0 / total.total as f64,
1863 lt = $variant.lt_infer as f64 * 100.0 / total.total as f64,
1864 ct = $variant.ct_infer as f64 * 100.0 / total.total as f64,
1865 all = $variant.all_infer as f64 * 100.0 / total.total as f64);
1867 println!(" total {uses:6} \
1868 {ty:4.1}% {lt:5.1}% {ct:4.1}% {all:4.1}%",
1870 ty = total.ty_infer as f64 * 100.0 / total.total as f64,
1871 lt = total.lt_infer as f64 * 100.0 / total.total as f64,
1872 ct = total.ct_infer as f64 * 100.0 / total.total as f64,
1873 all = total.all_infer as f64 * 100.0 / total.total as f64)
1881 impl<'tcx> TyCtxt<'tcx> {
1882 pub fn print_debug_stats(self) {
1901 UnnormalizedProjection,
1907 println!("InternalSubsts interner: #{}", self.interners.substs.len());
1908 println!("Region interner: #{}", self.interners.region.len());
1909 println!("Stability interner: #{}", self.stability_interner.len());
1910 println!("Const Stability interner: #{}", self.const_stability_interner.len());
1911 println!("Allocation interner: #{}", self.allocation_interner.len());
1912 println!("Layout interner: #{}", self.layout_interner.len());
1916 /// An entry in an interner.
1917 struct Interned<'tcx, T: ?Sized>(&'tcx T);
1919 impl<'tcx, T: 'tcx + ?Sized> Clone for Interned<'tcx, T> {
1920 fn clone(&self) -> Self {
1924 impl<'tcx, T: 'tcx + ?Sized> Copy for Interned<'tcx, T> {}
1926 impl<'tcx, T: 'tcx + ?Sized> IntoPointer for Interned<'tcx, T> {
1927 fn into_pointer(&self) -> *const () {
1928 self.0 as *const _ as *const ()
1931 // N.B., an `Interned<Ty>` compares and hashes as a `TyKind`.
1932 impl<'tcx> PartialEq for Interned<'tcx, TyS<'tcx>> {
1933 fn eq(&self, other: &Interned<'tcx, TyS<'tcx>>) -> bool {
1934 self.0.kind == other.0.kind
1938 impl<'tcx> Eq for Interned<'tcx, TyS<'tcx>> {}
1940 impl<'tcx> Hash for Interned<'tcx, TyS<'tcx>> {
1941 fn hash<H: Hasher>(&self, s: &mut H) {
1946 #[allow(rustc::usage_of_ty_tykind)]
1947 impl<'tcx> Borrow<TyKind<'tcx>> for Interned<'tcx, TyS<'tcx>> {
1948 fn borrow<'a>(&'a self) -> &'a TyKind<'tcx> {
1953 // N.B., an `Interned<List<T>>` compares and hashes as its elements.
1954 impl<'tcx, T: PartialEq> PartialEq for Interned<'tcx, List<T>> {
1955 fn eq(&self, other: &Interned<'tcx, List<T>>) -> bool {
1956 self.0[..] == other.0[..]
1960 impl<'tcx, T: Eq> Eq for Interned<'tcx, List<T>> {}
1962 impl<'tcx, T: Hash> Hash for Interned<'tcx, List<T>> {
1963 fn hash<H: Hasher>(&self, s: &mut H) {
1968 impl<'tcx> Borrow<[Ty<'tcx>]> for Interned<'tcx, List<Ty<'tcx>>> {
1969 fn borrow<'a>(&'a self) -> &'a [Ty<'tcx>] {
1974 impl<'tcx> Borrow<[CanonicalVarInfo]> for Interned<'tcx, List<CanonicalVarInfo>> {
1975 fn borrow(&self) -> &[CanonicalVarInfo] {
1980 impl<'tcx> Borrow<[GenericArg<'tcx>]> for Interned<'tcx, InternalSubsts<'tcx>> {
1981 fn borrow<'a>(&'a self) -> &'a [GenericArg<'tcx>] {
1986 impl<'tcx> Borrow<[ProjectionKind]> for Interned<'tcx, List<ProjectionKind>> {
1987 fn borrow(&self) -> &[ProjectionKind] {
1992 impl<'tcx> Borrow<[PlaceElem<'tcx>]> for Interned<'tcx, List<PlaceElem<'tcx>>> {
1993 fn borrow(&self) -> &[PlaceElem<'tcx>] {
1998 impl<'tcx> Borrow<RegionKind> for Interned<'tcx, RegionKind> {
1999 fn borrow(&self) -> &RegionKind {
2004 impl<'tcx> Borrow<GoalKind<'tcx>> for Interned<'tcx, GoalKind<'tcx>> {
2005 fn borrow<'a>(&'a self) -> &'a GoalKind<'tcx> {
2010 impl<'tcx> Borrow<[ExistentialPredicate<'tcx>]>
2011 for Interned<'tcx, List<ExistentialPredicate<'tcx>>>
2013 fn borrow<'a>(&'a self) -> &'a [ExistentialPredicate<'tcx>] {
2018 impl<'tcx> Borrow<[Predicate<'tcx>]> for Interned<'tcx, List<Predicate<'tcx>>> {
2019 fn borrow<'a>(&'a self) -> &'a [Predicate<'tcx>] {
2024 impl<'tcx> Borrow<Const<'tcx>> for Interned<'tcx, Const<'tcx>> {
2025 fn borrow<'a>(&'a self) -> &'a Const<'tcx> {
2030 impl<'tcx> Borrow<[Clause<'tcx>]> for Interned<'tcx, List<Clause<'tcx>>> {
2031 fn borrow<'a>(&'a self) -> &'a [Clause<'tcx>] {
2036 impl<'tcx> Borrow<[Goal<'tcx>]> for Interned<'tcx, List<Goal<'tcx>>> {
2037 fn borrow<'a>(&'a self) -> &'a [Goal<'tcx>] {
2042 macro_rules! direct_interners {
2043 ($($name:ident: $method:ident($ty:ty)),+) => {
2044 $(impl<'tcx> PartialEq for Interned<'tcx, $ty> {
2045 fn eq(&self, other: &Self) -> bool {
2050 impl<'tcx> Eq for Interned<'tcx, $ty> {}
2052 impl<'tcx> Hash for Interned<'tcx, $ty> {
2053 fn hash<H: Hasher>(&self, s: &mut H) {
2058 impl<'tcx> TyCtxt<'tcx> {
2059 pub fn $method(self, v: $ty) -> &'tcx $ty {
2060 self.interners.$name.intern_ref(&v, || {
2061 Interned(self.interners.arena.alloc(v))
2069 region: mk_region(RegionKind),
2070 goal: mk_goal(GoalKind<'tcx>),
2071 const_: mk_const(Const<'tcx>)
2074 macro_rules! slice_interners {
2075 ($($field:ident: $method:ident($ty:ty)),+) => (
2076 $(impl<'tcx> TyCtxt<'tcx> {
2077 pub fn $method(self, v: &[$ty]) -> &'tcx List<$ty> {
2078 self.interners.$field.intern_ref(v, || {
2079 Interned(List::from_arena(&*self.arena, v))
2087 type_list: _intern_type_list(Ty<'tcx>),
2088 substs: _intern_substs(GenericArg<'tcx>),
2089 canonical_var_infos: _intern_canonical_var_infos(CanonicalVarInfo),
2090 existential_predicates: _intern_existential_predicates(ExistentialPredicate<'tcx>),
2091 predicates: _intern_predicates(Predicate<'tcx>),
2092 clauses: _intern_clauses(Clause<'tcx>),
2093 goal_list: _intern_goals(Goal<'tcx>),
2094 projs: _intern_projs(ProjectionKind),
2095 place_elems: _intern_place_elems(PlaceElem<'tcx>)
2098 impl<'tcx> TyCtxt<'tcx> {
2099 /// Given a `fn` type, returns an equivalent `unsafe fn` type;
2100 /// that is, a `fn` type that is equivalent in every way for being
2102 pub fn safe_to_unsafe_fn_ty(self, sig: PolyFnSig<'tcx>) -> Ty<'tcx> {
2103 assert_eq!(sig.unsafety(), hir::Unsafety::Normal);
2104 self.mk_fn_ptr(sig.map_bound(|sig| ty::FnSig { unsafety: hir::Unsafety::Unsafe, ..sig }))
2107 /// Given a closure signature `sig`, returns an equivalent `fn`
2108 /// type with the same signature. Detuples and so forth -- so
2109 /// e.g., if we have a sig with `Fn<(u32, i32)>` then you would get
2110 /// a `fn(u32, i32)`.
2111 /// `unsafety` determines the unsafety of the `fn` type. If you pass
2112 /// `hir::Unsafety::Unsafe` in the previous example, then you would get
2113 /// an `unsafe fn (u32, i32)`.
2114 /// It cannot convert a closure that requires unsafe.
2115 pub fn coerce_closure_fn_ty(self, sig: PolyFnSig<'tcx>, unsafety: hir::Unsafety) -> Ty<'tcx> {
2116 let converted_sig = sig.map_bound(|s| {
2117 let params_iter = match s.inputs()[0].kind {
2118 ty::Tuple(params) => params.into_iter().map(|k| k.expect_ty()),
2121 self.mk_fn_sig(params_iter, s.output(), s.c_variadic, unsafety, abi::Abi::Rust)
2124 self.mk_fn_ptr(converted_sig)
2127 #[allow(rustc::usage_of_ty_tykind)]
2129 pub fn mk_ty(&self, st: TyKind<'tcx>) -> Ty<'tcx> {
2130 self.interners.intern_ty(st)
2133 pub fn mk_mach_int(self, tm: ast::IntTy) -> Ty<'tcx> {
2135 ast::IntTy::Isize => self.types.isize,
2136 ast::IntTy::I8 => self.types.i8,
2137 ast::IntTy::I16 => self.types.i16,
2138 ast::IntTy::I32 => self.types.i32,
2139 ast::IntTy::I64 => self.types.i64,
2140 ast::IntTy::I128 => self.types.i128,
2144 pub fn mk_mach_uint(self, tm: ast::UintTy) -> Ty<'tcx> {
2146 ast::UintTy::Usize => self.types.usize,
2147 ast::UintTy::U8 => self.types.u8,
2148 ast::UintTy::U16 => self.types.u16,
2149 ast::UintTy::U32 => self.types.u32,
2150 ast::UintTy::U64 => self.types.u64,
2151 ast::UintTy::U128 => self.types.u128,
2155 pub fn mk_mach_float(self, tm: ast::FloatTy) -> Ty<'tcx> {
2157 ast::FloatTy::F32 => self.types.f32,
2158 ast::FloatTy::F64 => self.types.f64,
2163 pub fn mk_str(self) -> Ty<'tcx> {
2168 pub fn mk_static_str(self) -> Ty<'tcx> {
2169 self.mk_imm_ref(self.lifetimes.re_static, self.mk_str())
2173 pub fn mk_adt(self, def: &'tcx AdtDef, substs: SubstsRef<'tcx>) -> Ty<'tcx> {
2174 // Take a copy of substs so that we own the vectors inside.
2175 self.mk_ty(Adt(def, substs))
2179 pub fn mk_foreign(self, def_id: DefId) -> Ty<'tcx> {
2180 self.mk_ty(Foreign(def_id))
2183 fn mk_generic_adt(self, wrapper_def_id: DefId, ty_param: Ty<'tcx>) -> Ty<'tcx> {
2184 let adt_def = self.adt_def(wrapper_def_id);
2186 InternalSubsts::for_item(self, wrapper_def_id, |param, substs| match param.kind {
2187 GenericParamDefKind::Lifetime | GenericParamDefKind::Const => bug!(),
2188 GenericParamDefKind::Type { has_default, .. } => {
2189 if param.index == 0 {
2192 assert!(has_default);
2193 self.type_of(param.def_id).subst(self, substs).into()
2197 self.mk_ty(Adt(adt_def, substs))
2201 pub fn mk_box(self, ty: Ty<'tcx>) -> Ty<'tcx> {
2202 let def_id = self.require_lang_item(lang_items::OwnedBoxLangItem, None);
2203 self.mk_generic_adt(def_id, ty)
2207 pub fn mk_lang_item(self, ty: Ty<'tcx>, item: lang_items::LangItem) -> Option<Ty<'tcx>> {
2208 let def_id = self.lang_items().require(item).ok()?;
2209 Some(self.mk_generic_adt(def_id, ty))
2213 pub fn mk_diagnostic_item(self, ty: Ty<'tcx>, name: Symbol) -> Option<Ty<'tcx>> {
2214 let def_id = self.get_diagnostic_item(name)?;
2215 Some(self.mk_generic_adt(def_id, ty))
2219 pub fn mk_maybe_uninit(self, ty: Ty<'tcx>) -> Ty<'tcx> {
2220 let def_id = self.require_lang_item(lang_items::MaybeUninitLangItem, None);
2221 self.mk_generic_adt(def_id, ty)
2225 pub fn mk_ptr(self, tm: TypeAndMut<'tcx>) -> Ty<'tcx> {
2226 self.mk_ty(RawPtr(tm))
2230 pub fn mk_ref(self, r: Region<'tcx>, tm: TypeAndMut<'tcx>) -> Ty<'tcx> {
2231 self.mk_ty(Ref(r, tm.ty, tm.mutbl))
2235 pub fn mk_mut_ref(self, r: Region<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
2236 self.mk_ref(r, TypeAndMut { ty, mutbl: hir::Mutability::Mut })
2240 pub fn mk_imm_ref(self, r: Region<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
2241 self.mk_ref(r, TypeAndMut { ty, mutbl: hir::Mutability::Not })
2245 pub fn mk_mut_ptr(self, ty: Ty<'tcx>) -> Ty<'tcx> {
2246 self.mk_ptr(TypeAndMut { ty, mutbl: hir::Mutability::Mut })
2250 pub fn mk_imm_ptr(self, ty: Ty<'tcx>) -> Ty<'tcx> {
2251 self.mk_ptr(TypeAndMut { ty, mutbl: hir::Mutability::Not })
2255 pub fn mk_nil_ptr(self) -> Ty<'tcx> {
2256 self.mk_imm_ptr(self.mk_unit())
2260 pub fn mk_array(self, ty: Ty<'tcx>, n: u64) -> Ty<'tcx> {
2261 self.mk_ty(Array(ty, ty::Const::from_usize(self, n)))
2265 pub fn mk_slice(self, ty: Ty<'tcx>) -> Ty<'tcx> {
2266 self.mk_ty(Slice(ty))
2270 pub fn intern_tup(self, ts: &[Ty<'tcx>]) -> Ty<'tcx> {
2271 let kinds: Vec<_> = ts.iter().map(|&t| GenericArg::from(t)).collect();
2272 self.mk_ty(Tuple(self.intern_substs(&kinds)))
2275 pub fn mk_tup<I: InternAs<[Ty<'tcx>], Ty<'tcx>>>(self, iter: I) -> I::Output {
2276 iter.intern_with(|ts| {
2277 let kinds: Vec<_> = ts.iter().map(|&t| GenericArg::from(t)).collect();
2278 self.mk_ty(Tuple(self.intern_substs(&kinds)))
2283 pub fn mk_unit(self) -> Ty<'tcx> {
2288 pub fn mk_diverging_default(self) -> Ty<'tcx> {
2289 if self.features().never_type_fallback { self.types.never } else { self.types.unit }
2293 pub fn mk_bool(self) -> Ty<'tcx> {
2298 pub fn mk_fn_def(self, def_id: DefId, substs: SubstsRef<'tcx>) -> Ty<'tcx> {
2299 self.mk_ty(FnDef(def_id, substs))
2303 pub fn mk_fn_ptr(self, fty: PolyFnSig<'tcx>) -> Ty<'tcx> {
2304 self.mk_ty(FnPtr(fty))
2310 obj: ty::Binder<&'tcx List<ExistentialPredicate<'tcx>>>,
2311 reg: ty::Region<'tcx>,
2313 self.mk_ty(Dynamic(obj, reg))
2317 pub fn mk_projection(self, item_def_id: DefId, substs: SubstsRef<'tcx>) -> Ty<'tcx> {
2318 self.mk_ty(Projection(ProjectionTy { item_def_id, substs }))
2322 pub fn mk_closure(self, closure_id: DefId, closure_substs: SubstsRef<'tcx>) -> Ty<'tcx> {
2323 self.mk_ty(Closure(closure_id, closure_substs))
2327 pub fn mk_generator(
2330 generator_substs: SubstsRef<'tcx>,
2331 movability: hir::Movability,
2333 self.mk_ty(Generator(id, generator_substs, movability))
2337 pub fn mk_generator_witness(self, types: ty::Binder<&'tcx List<Ty<'tcx>>>) -> Ty<'tcx> {
2338 self.mk_ty(GeneratorWitness(types))
2342 pub fn mk_ty_var(self, v: TyVid) -> Ty<'tcx> {
2343 self.mk_ty_infer(TyVar(v))
2347 pub fn mk_const_var(self, v: ConstVid<'tcx>, ty: Ty<'tcx>) -> &'tcx Const<'tcx> {
2348 self.mk_const(ty::Const { val: ty::ConstKind::Infer(InferConst::Var(v)), ty })
2352 pub fn mk_int_var(self, v: IntVid) -> Ty<'tcx> {
2353 self.mk_ty_infer(IntVar(v))
2357 pub fn mk_float_var(self, v: FloatVid) -> Ty<'tcx> {
2358 self.mk_ty_infer(FloatVar(v))
2362 pub fn mk_ty_infer(self, it: InferTy) -> Ty<'tcx> {
2363 self.mk_ty(Infer(it))
2367 pub fn mk_const_infer(self, ic: InferConst<'tcx>, ty: Ty<'tcx>) -> &'tcx ty::Const<'tcx> {
2368 self.mk_const(ty::Const { val: ty::ConstKind::Infer(ic), ty })
2372 pub fn mk_ty_param(self, index: u32, name: Symbol) -> Ty<'tcx> {
2373 self.mk_ty(Param(ParamTy { index, name }))
2377 pub fn mk_const_param(self, index: u32, name: Symbol, ty: Ty<'tcx>) -> &'tcx Const<'tcx> {
2378 self.mk_const(ty::Const { val: ty::ConstKind::Param(ParamConst { index, name }), ty })
2381 pub fn mk_param_from_def(self, param: &ty::GenericParamDef) -> GenericArg<'tcx> {
2383 GenericParamDefKind::Lifetime => {
2384 self.mk_region(ty::ReEarlyBound(param.to_early_bound_region_data())).into()
2386 GenericParamDefKind::Type { .. } => self.mk_ty_param(param.index, param.name).into(),
2387 GenericParamDefKind::Const => {
2388 self.mk_const_param(param.index, param.name, self.type_of(param.def_id)).into()
2394 pub fn mk_opaque(self, def_id: DefId, substs: SubstsRef<'tcx>) -> Ty<'tcx> {
2395 self.mk_ty(Opaque(def_id, substs))
2398 pub fn mk_place_field(self, place: Place<'tcx>, f: Field, ty: Ty<'tcx>) -> Place<'tcx> {
2399 self.mk_place_elem(place, PlaceElem::Field(f, ty))
2402 pub fn mk_place_deref(self, place: Place<'tcx>) -> Place<'tcx> {
2403 self.mk_place_elem(place, PlaceElem::Deref)
2406 pub fn mk_place_downcast(
2409 adt_def: &'tcx AdtDef,
2410 variant_index: VariantIdx,
2414 PlaceElem::Downcast(Some(adt_def.variants[variant_index].ident.name), variant_index),
2418 pub fn mk_place_downcast_unnamed(
2421 variant_index: VariantIdx,
2423 self.mk_place_elem(place, PlaceElem::Downcast(None, variant_index))
2426 pub fn mk_place_index(self, place: Place<'tcx>, index: Local) -> Place<'tcx> {
2427 self.mk_place_elem(place, PlaceElem::Index(index))
2430 /// This method copies `Place`'s projection, add an element and reintern it. Should not be used
2431 /// to build a full `Place` it's just a convenient way to grab a projection and modify it in
2433 pub fn mk_place_elem(self, place: Place<'tcx>, elem: PlaceElem<'tcx>) -> Place<'tcx> {
2434 let mut projection = place.projection.to_vec();
2435 projection.push(elem);
2437 Place { local: place.local, projection: self.intern_place_elems(&projection) }
2440 pub fn intern_existential_predicates(
2442 eps: &[ExistentialPredicate<'tcx>],
2443 ) -> &'tcx List<ExistentialPredicate<'tcx>> {
2444 assert!(!eps.is_empty());
2445 assert!(eps.windows(2).all(|w| w[0].stable_cmp(self, &w[1]) != Ordering::Greater));
2446 self._intern_existential_predicates(eps)
2449 pub fn intern_predicates(self, preds: &[Predicate<'tcx>]) -> &'tcx List<Predicate<'tcx>> {
2450 // FIXME consider asking the input slice to be sorted to avoid
2451 // re-interning permutations, in which case that would be asserted
2453 if preds.is_empty() {
2454 // The macro-generated method below asserts we don't intern an empty slice.
2457 self._intern_predicates(preds)
2461 pub fn intern_type_list(self, ts: &[Ty<'tcx>]) -> &'tcx List<Ty<'tcx>> {
2462 if ts.is_empty() { List::empty() } else { self._intern_type_list(ts) }
2465 pub fn intern_substs(self, ts: &[GenericArg<'tcx>]) -> &'tcx List<GenericArg<'tcx>> {
2466 if ts.is_empty() { List::empty() } else { self._intern_substs(ts) }
2469 pub fn intern_projs(self, ps: &[ProjectionKind]) -> &'tcx List<ProjectionKind> {
2470 if ps.is_empty() { List::empty() } else { self._intern_projs(ps) }
2473 pub fn intern_place_elems(self, ts: &[PlaceElem<'tcx>]) -> &'tcx List<PlaceElem<'tcx>> {
2474 if ts.is_empty() { List::empty() } else { self._intern_place_elems(ts) }
2477 pub fn intern_canonical_var_infos(self, ts: &[CanonicalVarInfo]) -> CanonicalVarInfos<'tcx> {
2478 if ts.is_empty() { List::empty() } else { self._intern_canonical_var_infos(ts) }
2481 pub fn intern_clauses(self, ts: &[Clause<'tcx>]) -> Clauses<'tcx> {
2482 if ts.is_empty() { List::empty() } else { self._intern_clauses(ts) }
2485 pub fn intern_goals(self, ts: &[Goal<'tcx>]) -> Goals<'tcx> {
2486 if ts.is_empty() { List::empty() } else { self._intern_goals(ts) }
2489 pub fn mk_fn_sig<I>(
2494 unsafety: hir::Unsafety,
2496 ) -> <I::Item as InternIteratorElement<Ty<'tcx>, ty::FnSig<'tcx>>>::Output
2498 I: Iterator<Item: InternIteratorElement<Ty<'tcx>, ty::FnSig<'tcx>>>,
2500 inputs.chain(iter::once(output)).intern_with(|xs| ty::FnSig {
2501 inputs_and_output: self.intern_type_list(xs),
2508 pub fn mk_existential_predicates<
2509 I: InternAs<[ExistentialPredicate<'tcx>], &'tcx List<ExistentialPredicate<'tcx>>>,
2514 iter.intern_with(|xs| self.intern_existential_predicates(xs))
2517 pub fn mk_predicates<I: InternAs<[Predicate<'tcx>], &'tcx List<Predicate<'tcx>>>>(
2521 iter.intern_with(|xs| self.intern_predicates(xs))
2524 pub fn mk_type_list<I: InternAs<[Ty<'tcx>], &'tcx List<Ty<'tcx>>>>(self, iter: I) -> I::Output {
2525 iter.intern_with(|xs| self.intern_type_list(xs))
2528 pub fn mk_substs<I: InternAs<[GenericArg<'tcx>], &'tcx List<GenericArg<'tcx>>>>(
2532 iter.intern_with(|xs| self.intern_substs(xs))
2535 pub fn mk_place_elems<I: InternAs<[PlaceElem<'tcx>], &'tcx List<PlaceElem<'tcx>>>>(
2539 iter.intern_with(|xs| self.intern_place_elems(xs))
2542 pub fn mk_substs_trait(self, self_ty: Ty<'tcx>, rest: &[GenericArg<'tcx>]) -> SubstsRef<'tcx> {
2543 self.mk_substs(iter::once(self_ty.into()).chain(rest.iter().cloned()))
2546 pub fn mk_clauses<I: InternAs<[Clause<'tcx>], Clauses<'tcx>>>(self, iter: I) -> I::Output {
2547 iter.intern_with(|xs| self.intern_clauses(xs))
2550 pub fn mk_goals<I: InternAs<[Goal<'tcx>], Goals<'tcx>>>(self, iter: I) -> I::Output {
2551 iter.intern_with(|xs| self.intern_goals(xs))
2554 /// Walks upwards from `id` to find a node which might change lint levels with attributes.
2555 /// It stops at `bound` and just returns it if reached.
2556 pub fn maybe_lint_level_root_bounded(self, mut id: HirId, bound: HirId) -> HirId {
2557 let hir = self.hir();
2563 if hir.attrs(id).iter().any(|attr| Level::from_symbol(attr.name_or_empty()).is_some()) {
2566 let next = hir.get_parent_node(id);
2568 bug!("lint traversal reached the root of the crate");
2574 pub fn lint_level_at_node(
2576 lint: &'static Lint,
2578 ) -> (Level, LintSource) {
2579 let sets = self.lint_levels(LOCAL_CRATE);
2581 if let Some(pair) = sets.level_and_source(lint, id, self.sess) {
2584 let next = self.hir().get_parent_node(id);
2586 bug!("lint traversal reached the root of the crate");
2592 pub fn struct_span_lint_hir(
2594 lint: &'static Lint,
2596 span: impl Into<MultiSpan>,
2597 decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a>),
2599 let (level, src) = self.lint_level_at_node(lint, hir_id);
2600 struct_lint_level(self.sess, lint, level, src, Some(span.into()), decorate);
2603 pub fn struct_lint_node(
2605 lint: &'static Lint,
2607 decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a>),
2609 let (level, src) = self.lint_level_at_node(lint, id);
2610 struct_lint_level(self.sess, lint, level, src, None, decorate);
2613 pub fn in_scope_traits(self, id: HirId) -> Option<&'tcx StableVec<TraitCandidate>> {
2614 self.in_scope_traits_map(id.owner).and_then(|map| map.get(&id.local_id))
2617 pub fn named_region(self, id: HirId) -> Option<resolve_lifetime::Region> {
2618 self.named_region_map(id.owner).and_then(|map| map.get(&id.local_id).cloned())
2621 pub fn is_late_bound(self, id: HirId) -> bool {
2622 self.is_late_bound_map(id.owner).map(|set| set.contains(&id.local_id)).unwrap_or(false)
2625 pub fn object_lifetime_defaults(self, id: HirId) -> Option<&'tcx [ObjectLifetimeDefault]> {
2626 self.object_lifetime_defaults_map(id.owner)
2627 .and_then(|map| map.get(&id.local_id).map(|v| &**v))
2631 pub trait InternAs<T: ?Sized, R> {
2633 fn intern_with<F>(self, f: F) -> Self::Output
2638 impl<I, T, R, E> InternAs<[T], R> for I
2640 E: InternIteratorElement<T, R>,
2641 I: Iterator<Item = E>,
2643 type Output = E::Output;
2644 fn intern_with<F>(self, f: F) -> Self::Output
2646 F: FnOnce(&[T]) -> R,
2648 E::intern_with(self, f)
2652 pub trait InternIteratorElement<T, R>: Sized {
2654 fn intern_with<I: Iterator<Item = Self>, F: FnOnce(&[T]) -> R>(iter: I, f: F) -> Self::Output;
2657 impl<T, R> InternIteratorElement<T, R> for T {
2659 fn intern_with<I: Iterator<Item = Self>, F: FnOnce(&[T]) -> R>(iter: I, f: F) -> Self::Output {
2660 f(&iter.collect::<SmallVec<[_; 8]>>())
2664 impl<'a, T, R> InternIteratorElement<T, R> for &'a T
2669 fn intern_with<I: Iterator<Item = Self>, F: FnOnce(&[T]) -> R>(iter: I, f: F) -> Self::Output {
2670 f(&iter.cloned().collect::<SmallVec<[_; 8]>>())
2674 impl<T, R, E> InternIteratorElement<T, R> for Result<T, E> {
2675 type Output = Result<R, E>;
2676 fn intern_with<I: Iterator<Item = Self>, F: FnOnce(&[T]) -> R>(
2680 // This code is hot enough that it's worth specializing for the most
2681 // common length lists, to avoid the overhead of `SmallVec` creation.
2682 // The match arms are in order of frequency. The 1, 2, and 0 cases are
2683 // typically hit in ~95% of cases. We assume that if the upper and
2684 // lower bounds from `size_hint` agree they are correct.
2685 Ok(match iter.size_hint() {
2687 let t0 = iter.next().unwrap()?;
2688 assert!(iter.next().is_none());
2692 let t0 = iter.next().unwrap()?;
2693 let t1 = iter.next().unwrap()?;
2694 assert!(iter.next().is_none());
2698 assert!(iter.next().is_none());
2701 _ => f(&iter.collect::<Result<SmallVec<[_; 8]>, _>>()?),
2706 // We are comparing types with different invariant lifetimes, so `ptr::eq`
2707 // won't work for us.
2708 fn ptr_eq<T, U>(t: *const T, u: *const U) -> bool {
2709 t as *const () == u as *const ()
2712 pub fn provide(providers: &mut ty::query::Providers<'_>) {
2713 providers.in_scope_traits_map = |tcx, id| tcx.gcx.trait_map.get(&id);
2714 providers.module_exports = |tcx, id| tcx.gcx.export_map.get(&id).map(|v| &v[..]);
2715 providers.crate_name = |tcx, id| {
2716 assert_eq!(id, LOCAL_CRATE);
2719 providers.maybe_unused_trait_import = |tcx, id| tcx.maybe_unused_trait_imports.contains(&id);
2720 providers.maybe_unused_extern_crates = |tcx, cnum| {
2721 assert_eq!(cnum, LOCAL_CRATE);
2722 &tcx.maybe_unused_extern_crates[..]
2724 providers.names_imported_by_glob_use = |tcx, id| {
2725 assert_eq!(id.krate, LOCAL_CRATE);
2726 Lrc::new(tcx.glob_map.get(&id).cloned().unwrap_or_default())
2729 providers.lookup_stability = |tcx, id| {
2730 let id = tcx.hir().local_def_id_to_hir_id(id.expect_local());
2731 tcx.stability().local_stability(id)
2733 providers.lookup_const_stability = |tcx, id| {
2734 let id = tcx.hir().local_def_id_to_hir_id(id.expect_local());
2735 tcx.stability().local_const_stability(id)
2737 providers.lookup_deprecation_entry = |tcx, id| {
2738 let id = tcx.hir().local_def_id_to_hir_id(id.expect_local());
2739 tcx.stability().local_deprecation_entry(id)
2741 providers.extern_mod_stmt_cnum = |tcx, id| {
2742 let id = tcx.hir().as_local_node_id(id).unwrap();
2743 tcx.extern_crate_map.get(&id).cloned()
2745 providers.all_crate_nums = |tcx, cnum| {
2746 assert_eq!(cnum, LOCAL_CRATE);
2747 tcx.arena.alloc_slice(&tcx.cstore.crates_untracked())
2749 providers.output_filenames = |tcx, cnum| {
2750 assert_eq!(cnum, LOCAL_CRATE);
2751 tcx.output_filenames.clone()
2753 providers.features_query = |tcx, cnum| {
2754 assert_eq!(cnum, LOCAL_CRATE);
2755 tcx.arena.alloc(tcx.sess.features_untracked().clone())
2757 providers.is_panic_runtime = |tcx, cnum| {
2758 assert_eq!(cnum, LOCAL_CRATE);
2759 attr::contains_name(tcx.hir().krate_attrs(), sym::panic_runtime)
2761 providers.is_compiler_builtins = |tcx, cnum| {
2762 assert_eq!(cnum, LOCAL_CRATE);
2763 attr::contains_name(tcx.hir().krate_attrs(), sym::compiler_builtins)
2765 providers.has_panic_handler = |tcx, cnum| {
2766 assert_eq!(cnum, LOCAL_CRATE);
2767 // We want to check if the panic handler was defined in this crate
2768 tcx.lang_items().panic_impl().map_or(false, |did| did.is_local())