]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_middle/src/ty/context.rs
fix most compiler/ doctests
[rust.git] / compiler / rustc_middle / src / ty / context.rs
1 //! Type context book-keeping.
2
3 use crate::arena::Arena;
4 use crate::dep_graph::{DepGraph, DepKind, DepKindStruct};
5 use crate::hir::place::Place as HirPlace;
6 use crate::infer::canonical::{Canonical, CanonicalVarInfo, CanonicalVarInfos};
7 use crate::lint::{struct_lint_level, LintDiagnosticBuilder, LintLevelSource};
8 use crate::middle::resolve_lifetime::{self, LifetimeScopeForPath};
9 use crate::middle::stability;
10 use crate::mir::interpret::{self, Allocation, ConstAllocation, ConstValue, Scalar};
11 use crate::mir::{
12     Body, BorrowCheckResult, Field, Local, Place, PlaceElem, ProjectionKind, Promoted,
13 };
14 use crate::thir::Thir;
15 use crate::traits;
16 use crate::ty::query::{self, TyCtxtAt};
17 use crate::ty::subst::{GenericArg, GenericArgKind, InternalSubsts, Subst, SubstsRef, UserSubsts};
18 use crate::ty::TyKind::*;
19 use crate::ty::{
20     self, AdtDef, AdtDefData, AdtKind, Binder, BindingMode, BoundVar, CanonicalPolyFnSig,
21     ClosureSizeProfileData, Const, ConstS, ConstVid, DefIdTree, ExistentialPredicate, FloatTy,
22     FloatVar, FloatVid, GenericParamDefKind, InferConst, InferTy, IntTy, IntVar, IntVid, List,
23     ParamConst, ParamTy, PolyFnSig, Predicate, PredicateKind, PredicateS, ProjectionTy, Region,
24     RegionKind, ReprOptions, TraitObjectVisitor, Ty, TyKind, TyS, TyVar, TyVid, TypeAndMut, UintTy,
25 };
26 use rustc_ast as ast;
27 use rustc_data_structures::fingerprint::Fingerprint;
28 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
29 use rustc_data_structures::intern::{Interned, WithStableHash};
30 use rustc_data_structures::memmap::Mmap;
31 use rustc_data_structures::profiling::SelfProfilerRef;
32 use rustc_data_structures::sharded::{IntoPointer, ShardedHashMap};
33 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
34 use rustc_data_structures::steal::Steal;
35 use rustc_data_structures::sync::{self, Lock, Lrc, WorkerLocal};
36 use rustc_data_structures::vec_map::VecMap;
37 use rustc_errors::{ErrorGuaranteed, MultiSpan};
38 use rustc_hir as hir;
39 use rustc_hir::def::{DefKind, Res};
40 use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, LocalDefId, LOCAL_CRATE};
41 use rustc_hir::intravisit::Visitor;
42 use rustc_hir::lang_items::LangItem;
43 use rustc_hir::{
44     Constness, ExprKind, HirId, ImplItemKind, ItemKind, ItemLocalId, ItemLocalMap, ItemLocalSet,
45     Node, TraitCandidate, TraitItemKind,
46 };
47 use rustc_index::vec::{Idx, IndexVec};
48 use rustc_macros::HashStable;
49 use rustc_middle::mir::FakeReadCause;
50 use rustc_query_system::ich::StableHashingContext;
51 use rustc_serialize::opaque::{FileEncodeResult, FileEncoder};
52 use rustc_session::config::{BorrowckMode, CrateType, OutputFilenames};
53 use rustc_session::lint::{Level, Lint};
54 use rustc_session::Limit;
55 use rustc_session::Session;
56 use rustc_span::def_id::{DefPathHash, StableCrateId};
57 use rustc_span::source_map::SourceMap;
58 use rustc_span::symbol::{kw, sym, Ident, Symbol};
59 use rustc_span::{Span, DUMMY_SP};
60 use rustc_target::abi::{Layout, LayoutS, TargetDataLayout, VariantIdx};
61 use rustc_target::spec::abi;
62
63 use rustc_type_ir::TypeFlags;
64 use smallvec::SmallVec;
65 use std::any::Any;
66 use std::borrow::Borrow;
67 use std::cmp::Ordering;
68 use std::collections::hash_map::{self, Entry};
69 use std::fmt;
70 use std::hash::{Hash, Hasher};
71 use std::iter;
72 use std::mem;
73 use std::ops::{Bound, Deref};
74 use std::sync::Arc;
75
76 pub trait OnDiskCache<'tcx>: rustc_data_structures::sync::Sync {
77     /// Creates a new `OnDiskCache` instance from the serialized data in `data`.
78     fn new(sess: &'tcx Session, data: Mmap, start_pos: usize) -> Self
79     where
80         Self: Sized;
81
82     fn new_empty(source_map: &'tcx SourceMap) -> Self
83     where
84         Self: Sized;
85
86     fn drop_serialized_data(&self, tcx: TyCtxt<'tcx>);
87
88     fn serialize(&self, tcx: TyCtxt<'tcx>, encoder: &mut FileEncoder) -> FileEncodeResult;
89 }
90
91 /// A type that is not publicly constructable. This prevents people from making [`TyKind::Error`]s
92 /// except through the error-reporting functions on a [`tcx`][TyCtxt].
93 #[derive(Copy, Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
94 #[derive(TyEncodable, TyDecodable, HashStable)]
95 pub struct DelaySpanBugEmitted {
96     pub reported: ErrorGuaranteed,
97     _priv: (),
98 }
99
100 type InternedSet<'tcx, T> = ShardedHashMap<InternedInSet<'tcx, T>, ()>;
101
102 pub struct CtxtInterners<'tcx> {
103     /// The arena that types, regions, etc. are allocated from.
104     arena: &'tcx WorkerLocal<Arena<'tcx>>,
105
106     // Specifically use a speedy hash algorithm for these hash sets, since
107     // they're accessed quite often.
108     type_: InternedSet<'tcx, WithStableHash<TyS<'tcx>>>,
109     substs: InternedSet<'tcx, InternalSubsts<'tcx>>,
110     canonical_var_infos: InternedSet<'tcx, List<CanonicalVarInfo<'tcx>>>,
111     region: InternedSet<'tcx, RegionKind>,
112     poly_existential_predicates:
113         InternedSet<'tcx, List<ty::Binder<'tcx, ExistentialPredicate<'tcx>>>>,
114     predicate: InternedSet<'tcx, PredicateS<'tcx>>,
115     predicates: InternedSet<'tcx, List<Predicate<'tcx>>>,
116     projs: InternedSet<'tcx, List<ProjectionKind>>,
117     place_elems: InternedSet<'tcx, List<PlaceElem<'tcx>>>,
118     const_: InternedSet<'tcx, ConstS<'tcx>>,
119     const_allocation: InternedSet<'tcx, Allocation>,
120     bound_variable_kinds: InternedSet<'tcx, List<ty::BoundVariableKind>>,
121     layout: InternedSet<'tcx, LayoutS<'tcx>>,
122     adt_def: InternedSet<'tcx, AdtDefData>,
123 }
124
125 impl<'tcx> CtxtInterners<'tcx> {
126     fn new(arena: &'tcx WorkerLocal<Arena<'tcx>>) -> CtxtInterners<'tcx> {
127         CtxtInterners {
128             arena,
129             type_: 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         }
144     }
145
146     /// Interns a type.
147     #[allow(rustc::usage_of_ty_tykind)]
148     #[inline(never)]
149     fn intern_ty(
150         &self,
151         kind: TyKind<'tcx>,
152         sess: &Session,
153         resolutions: &ty::ResolverOutputs,
154     ) -> Ty<'tcx> {
155         Ty(Interned::new_unchecked(
156             self.type_
157                 .intern(kind, |kind| {
158                     let flags = super::flags::FlagComputation::for_kind(&kind);
159
160                     // It's impossible to hash inference regions (and will ICE), so we don't need to try to cache them.
161                     // Without incremental, we rarely stable-hash types, so let's not do it proactively.
162                     let stable_hash = if flags.flags.intersects(TypeFlags::HAS_RE_INFER)
163                         || sess.opts.incremental.is_none()
164                     {
165                         Fingerprint::ZERO
166                     } else {
167                         let mut hasher = StableHasher::new();
168                         let mut hcx = StableHashingContext::ignore_spans(
169                             sess,
170                             &resolutions.definitions,
171                             &*resolutions.cstore,
172                         );
173                         kind.hash_stable(&mut hcx, &mut hasher);
174                         hasher.finish()
175                     };
176
177                     let ty_struct = TyS {
178                         kind,
179                         flags: flags.flags,
180                         outer_exclusive_binder: flags.outer_exclusive_binder,
181                     };
182
183                     InternedInSet(
184                         self.arena.alloc(WithStableHash { internee: ty_struct, stable_hash }),
185                     )
186                 })
187                 .0,
188         ))
189     }
190
191     #[inline(never)]
192     fn intern_predicate(&self, kind: Binder<'tcx, PredicateKind<'tcx>>) -> Predicate<'tcx> {
193         Predicate(Interned::new_unchecked(
194             self.predicate
195                 .intern(kind, |kind| {
196                     let flags = super::flags::FlagComputation::for_predicate(kind);
197
198                     let predicate_struct = PredicateS {
199                         kind,
200                         flags: flags.flags,
201                         outer_exclusive_binder: flags.outer_exclusive_binder,
202                     };
203
204                     InternedInSet(self.arena.alloc(predicate_struct))
205                 })
206                 .0,
207         ))
208     }
209 }
210
211 pub struct CommonTypes<'tcx> {
212     pub unit: Ty<'tcx>,
213     pub bool: Ty<'tcx>,
214     pub char: Ty<'tcx>,
215     pub isize: Ty<'tcx>,
216     pub i8: Ty<'tcx>,
217     pub i16: Ty<'tcx>,
218     pub i32: Ty<'tcx>,
219     pub i64: Ty<'tcx>,
220     pub i128: Ty<'tcx>,
221     pub usize: Ty<'tcx>,
222     pub u8: Ty<'tcx>,
223     pub u16: Ty<'tcx>,
224     pub u32: Ty<'tcx>,
225     pub u64: Ty<'tcx>,
226     pub u128: Ty<'tcx>,
227     pub f32: Ty<'tcx>,
228     pub f64: Ty<'tcx>,
229     pub str_: Ty<'tcx>,
230     pub never: Ty<'tcx>,
231     pub self_param: Ty<'tcx>,
232
233     /// Dummy type used for the `Self` of a `TraitRef` created for converting
234     /// a trait object, and which gets removed in `ExistentialTraitRef`.
235     /// This type must not appear anywhere in other converted types.
236     pub trait_object_dummy_self: Ty<'tcx>,
237 }
238
239 pub struct CommonLifetimes<'tcx> {
240     /// `ReEmpty` in the root universe.
241     pub re_root_empty: Region<'tcx>,
242
243     /// `ReStatic`
244     pub re_static: Region<'tcx>,
245
246     /// Erased region, used outside of type inference.
247     pub re_erased: Region<'tcx>,
248 }
249
250 pub struct CommonConsts<'tcx> {
251     pub unit: Const<'tcx>,
252 }
253
254 pub struct LocalTableInContext<'a, V> {
255     hir_owner: LocalDefId,
256     data: &'a ItemLocalMap<V>,
257 }
258
259 /// Validate that the given HirId (respectively its `local_id` part) can be
260 /// safely used as a key in the maps of a TypeckResults. For that to be
261 /// the case, the HirId must have the same `owner` as all the other IDs in
262 /// this table (signified by `hir_owner`). Otherwise the HirId
263 /// would be in a different frame of reference and using its `local_id`
264 /// would result in lookup errors, or worse, in silently wrong data being
265 /// stored/returned.
266 #[inline]
267 fn validate_hir_id_for_typeck_results(hir_owner: LocalDefId, hir_id: hir::HirId) {
268     if hir_id.owner != hir_owner {
269         invalid_hir_id_for_typeck_results(hir_owner, hir_id);
270     }
271 }
272
273 #[cold]
274 #[inline(never)]
275 fn invalid_hir_id_for_typeck_results(hir_owner: LocalDefId, hir_id: hir::HirId) {
276     ty::tls::with(|tcx| {
277         bug!(
278             "node {} with HirId::owner {:?} cannot be placed in TypeckResults with hir_owner {:?}",
279             tcx.hir().node_to_string(hir_id),
280             hir_id.owner,
281             hir_owner
282         )
283     });
284 }
285
286 impl<'a, V> LocalTableInContext<'a, V> {
287     pub fn contains_key(&self, id: hir::HirId) -> bool {
288         validate_hir_id_for_typeck_results(self.hir_owner, id);
289         self.data.contains_key(&id.local_id)
290     }
291
292     pub fn get(&self, id: hir::HirId) -> Option<&V> {
293         validate_hir_id_for_typeck_results(self.hir_owner, id);
294         self.data.get(&id.local_id)
295     }
296
297     pub fn iter(&self) -> hash_map::Iter<'_, hir::ItemLocalId, V> {
298         self.data.iter()
299     }
300 }
301
302 impl<'a, V> ::std::ops::Index<hir::HirId> for LocalTableInContext<'a, V> {
303     type Output = V;
304
305     fn index(&self, key: hir::HirId) -> &V {
306         self.get(key).expect("LocalTableInContext: key not found")
307     }
308 }
309
310 pub struct LocalTableInContextMut<'a, V> {
311     hir_owner: LocalDefId,
312     data: &'a mut ItemLocalMap<V>,
313 }
314
315 impl<'a, V> LocalTableInContextMut<'a, V> {
316     pub fn get_mut(&mut self, id: hir::HirId) -> Option<&mut V> {
317         validate_hir_id_for_typeck_results(self.hir_owner, id);
318         self.data.get_mut(&id.local_id)
319     }
320
321     pub fn entry(&mut self, id: hir::HirId) -> Entry<'_, hir::ItemLocalId, V> {
322         validate_hir_id_for_typeck_results(self.hir_owner, id);
323         self.data.entry(id.local_id)
324     }
325
326     pub fn insert(&mut self, id: hir::HirId, val: V) -> Option<V> {
327         validate_hir_id_for_typeck_results(self.hir_owner, id);
328         self.data.insert(id.local_id, val)
329     }
330
331     pub fn remove(&mut self, id: hir::HirId) -> Option<V> {
332         validate_hir_id_for_typeck_results(self.hir_owner, id);
333         self.data.remove(&id.local_id)
334     }
335 }
336
337 /// Whenever a value may be live across a generator yield, the type of that value winds up in the
338 /// `GeneratorInteriorTypeCause` struct. This struct adds additional information about such
339 /// captured types that can be useful for diagnostics. In particular, it stores the span that
340 /// caused a given type to be recorded, along with the scope that enclosed the value (which can
341 /// be used to find the await that the value is live across).
342 ///
343 /// For example:
344 ///
345 /// ```ignore (pseudo-Rust)
346 /// async move {
347 ///     let x: T = expr;
348 ///     foo.await
349 ///     ...
350 /// }
351 /// ```
352 ///
353 /// Here, we would store the type `T`, the span of the value `x`, the "scope-span" for
354 /// the scope that contains `x`, the expr `T` evaluated from, and the span of `foo.await`.
355 #[derive(TyEncodable, TyDecodable, Clone, Debug, Eq, Hash, PartialEq, HashStable)]
356 #[derive(TypeFoldable)]
357 pub struct GeneratorInteriorTypeCause<'tcx> {
358     /// Type of the captured binding.
359     pub ty: Ty<'tcx>,
360     /// Span of the binding that was captured.
361     pub span: Span,
362     /// Span of the scope of the captured binding.
363     pub scope_span: Option<Span>,
364     /// Span of `.await` or `yield` expression.
365     pub yield_span: Span,
366     /// Expr which the type evaluated from.
367     pub expr: Option<hir::HirId>,
368 }
369
370 // This type holds diagnostic information on generators and async functions across crate boundaries
371 // and is used to provide better error messages
372 #[derive(TyEncodable, TyDecodable, Clone, Debug, HashStable)]
373 pub struct GeneratorDiagnosticData<'tcx> {
374     pub generator_interior_types: ty::Binder<'tcx, Vec<GeneratorInteriorTypeCause<'tcx>>>,
375     pub hir_owner: DefId,
376     pub nodes_types: ItemLocalMap<Ty<'tcx>>,
377     pub adjustments: ItemLocalMap<Vec<ty::adjustment::Adjustment<'tcx>>>,
378 }
379
380 #[derive(TyEncodable, TyDecodable, Debug, HashStable)]
381 pub struct TypeckResults<'tcx> {
382     /// The `HirId::owner` all `ItemLocalId`s in this table are relative to.
383     pub hir_owner: LocalDefId,
384
385     /// Resolved definitions for `<T>::X` associated paths and
386     /// method calls, including those of overloaded operators.
387     type_dependent_defs: ItemLocalMap<Result<(DefKind, DefId), ErrorGuaranteed>>,
388
389     /// Resolved field indices for field accesses in expressions (`S { field }`, `obj.field`)
390     /// or patterns (`S { field }`). The index is often useful by itself, but to learn more
391     /// about the field you also need definition of the variant to which the field
392     /// belongs, but it may not exist if it's a tuple field (`tuple.0`).
393     field_indices: ItemLocalMap<usize>,
394
395     /// Stores the types for various nodes in the AST. Note that this table
396     /// is not guaranteed to be populated outside inference. See
397     /// typeck::check::fn_ctxt for details.
398     node_types: ItemLocalMap<Ty<'tcx>>,
399
400     /// Stores the type parameters which were substituted to obtain the type
401     /// of this node. This only applies to nodes that refer to entities
402     /// parameterized by type parameters, such as generic fns, types, or
403     /// other items.
404     node_substs: ItemLocalMap<SubstsRef<'tcx>>,
405
406     /// This will either store the canonicalized types provided by the user
407     /// or the substitutions that the user explicitly gave (if any) attached
408     /// to `id`. These will not include any inferred values. The canonical form
409     /// is used to capture things like `_` or other unspecified values.
410     ///
411     /// For example, if the user wrote `foo.collect::<Vec<_>>()`, then the
412     /// canonical substitutions would include only `for<X> { Vec<X> }`.
413     ///
414     /// See also `AscribeUserType` statement in MIR.
415     user_provided_types: ItemLocalMap<CanonicalUserType<'tcx>>,
416
417     /// Stores the canonicalized types provided by the user. See also
418     /// `AscribeUserType` statement in MIR.
419     pub user_provided_sigs: DefIdMap<CanonicalPolyFnSig<'tcx>>,
420
421     adjustments: ItemLocalMap<Vec<ty::adjustment::Adjustment<'tcx>>>,
422
423     /// Stores the actual binding mode for all instances of hir::BindingAnnotation.
424     pat_binding_modes: ItemLocalMap<BindingMode>,
425
426     /// Stores the types which were implicitly dereferenced in pattern binding modes
427     /// for later usage in THIR lowering. For example,
428     ///
429     /// ```
430     /// match &&Some(5i32) {
431     ///     Some(n) => {},
432     ///     _ => {},
433     /// }
434     /// ```
435     /// leads to a `vec![&&Option<i32>, &Option<i32>]`. Empty vectors are not stored.
436     ///
437     /// See:
438     /// <https://github.com/rust-lang/rfcs/blob/master/text/2005-match-ergonomics.md#definitions>
439     pat_adjustments: ItemLocalMap<Vec<Ty<'tcx>>>,
440
441     /// Records the reasons that we picked the kind of each closure;
442     /// not all closures are present in the map.
443     closure_kind_origins: ItemLocalMap<(Span, HirPlace<'tcx>)>,
444
445     /// For each fn, records the "liberated" types of its arguments
446     /// and return type. Liberated means that all bound regions
447     /// (including late-bound regions) are replaced with free
448     /// equivalents. This table is not used in codegen (since regions
449     /// are erased there) and hence is not serialized to metadata.
450     ///
451     /// This table also contains the "revealed" values for any `impl Trait`
452     /// that appear in the signature and whose values are being inferred
453     /// by this function.
454     ///
455     /// # Example
456     ///
457     /// ```rust
458     /// # use std::fmt::Debug;
459     /// fn foo(x: &u32) -> impl Debug { *x }
460     /// ```
461     ///
462     /// The function signature here would be:
463     ///
464     /// ```ignore (illustrative)
465     /// for<'a> fn(&'a u32) -> Foo
466     /// ```
467     ///
468     /// where `Foo` is an opaque type created for this function.
469     ///
470     ///
471     /// The *liberated* form of this would be
472     ///
473     /// ```ignore (illustrative)
474     /// fn(&'a u32) -> u32
475     /// ```
476     ///
477     /// Note that `'a` is not bound (it would be an `ReFree`) and
478     /// that the `Foo` opaque type is replaced by its hidden type.
479     liberated_fn_sigs: ItemLocalMap<ty::FnSig<'tcx>>,
480
481     /// For each FRU expression, record the normalized types of the fields
482     /// of the struct - this is needed because it is non-trivial to
483     /// normalize while preserving regions. This table is used only in
484     /// MIR construction and hence is not serialized to metadata.
485     fru_field_types: ItemLocalMap<Vec<Ty<'tcx>>>,
486
487     /// For every coercion cast we add the HIR node ID of the cast
488     /// expression to this set.
489     coercion_casts: ItemLocalSet,
490
491     /// Set of trait imports actually used in the method resolution.
492     /// This is used for warning unused imports. During type
493     /// checking, this `Lrc` should not be cloned: it must have a ref-count
494     /// of 1 so that we can insert things into the set mutably.
495     pub used_trait_imports: Lrc<FxHashSet<LocalDefId>>,
496
497     /// If any errors occurred while type-checking this body,
498     /// this field will be set to `Some(ErrorGuaranteed)`.
499     pub tainted_by_errors: Option<ErrorGuaranteed>,
500
501     /// All the opaque types that have hidden types set
502     /// by this function. For return-position-impl-trait we also store the
503     /// type here, so that mir-borrowck can figure out hidden types,
504     /// even if they are only set in dead code (which doesn't show up in MIR).
505     /// For type-alias-impl-trait, this map is only used to prevent query cycles,
506     /// so the hidden types are all `None`.
507     pub concrete_opaque_types: VecMap<DefId, Option<Ty<'tcx>>>,
508
509     /// Tracks the minimum captures required for a closure;
510     /// see `MinCaptureInformationMap` for more details.
511     pub closure_min_captures: ty::MinCaptureInformationMap<'tcx>,
512
513     /// Tracks the fake reads required for a closure and the reason for the fake read.
514     /// When performing pattern matching for closures, there are times we don't end up
515     /// reading places that are mentioned in a closure (because of _ patterns). However,
516     /// to ensure the places are initialized, we introduce fake reads.
517     /// Consider these two examples:
518     /// ``` (discriminant matching with only wildcard arm)
519     /// let x: u8;
520     /// let c = || match x { _ => () };
521     /// ```
522     /// In this example, we don't need to actually read/borrow `x` in `c`, and so we don't
523     /// want to capture it. However, we do still want an error here, because `x` should have
524     /// to be initialized at the point where c is created. Therefore, we add a "fake read"
525     /// instead.
526     /// ``` (destructured assignments)
527     /// let c = || {
528     ///     let (t1, t2) = t;
529     /// }
530     /// ```
531     /// In the second example, we capture the disjoint fields of `t` (`t.0` & `t.1`), but
532     /// we never capture `t`. This becomes an issue when we build MIR as we require
533     /// information on `t` in order to create place `t.0` and `t.1`. We can solve this
534     /// issue by fake reading `t`.
535     pub closure_fake_reads: FxHashMap<DefId, Vec<(HirPlace<'tcx>, FakeReadCause, hir::HirId)>>,
536
537     /// Stores the type, expression, span and optional scope span of all types
538     /// that are live across the yield of this generator (if a generator).
539     pub generator_interior_types: ty::Binder<'tcx, Vec<GeneratorInteriorTypeCause<'tcx>>>,
540
541     /// We sometimes treat byte string literals (which are of type `&[u8; N]`)
542     /// as `&[u8]`, depending on the pattern  in which they are used.
543     /// This hashset records all instances where we behave
544     /// like this to allow `const_to_pat` to reliably handle this situation.
545     pub treat_byte_string_as_slice: ItemLocalSet,
546
547     /// Contains the data for evaluating the effect of feature `capture_disjoint_fields`
548     /// on closure size.
549     pub closure_size_eval: FxHashMap<DefId, ClosureSizeProfileData<'tcx>>,
550 }
551
552 impl<'tcx> TypeckResults<'tcx> {
553     pub fn new(hir_owner: LocalDefId) -> TypeckResults<'tcx> {
554         TypeckResults {
555             hir_owner,
556             type_dependent_defs: Default::default(),
557             field_indices: Default::default(),
558             user_provided_types: Default::default(),
559             user_provided_sigs: Default::default(),
560             node_types: Default::default(),
561             node_substs: Default::default(),
562             adjustments: Default::default(),
563             pat_binding_modes: Default::default(),
564             pat_adjustments: Default::default(),
565             closure_kind_origins: Default::default(),
566             liberated_fn_sigs: Default::default(),
567             fru_field_types: Default::default(),
568             coercion_casts: Default::default(),
569             used_trait_imports: Lrc::new(Default::default()),
570             tainted_by_errors: None,
571             concrete_opaque_types: Default::default(),
572             closure_min_captures: Default::default(),
573             closure_fake_reads: Default::default(),
574             generator_interior_types: ty::Binder::dummy(Default::default()),
575             treat_byte_string_as_slice: Default::default(),
576             closure_size_eval: Default::default(),
577         }
578     }
579
580     /// Returns the final resolution of a `QPath` in an `Expr` or `Pat` node.
581     pub fn qpath_res(&self, qpath: &hir::QPath<'_>, id: hir::HirId) -> Res {
582         match *qpath {
583             hir::QPath::Resolved(_, ref path) => path.res,
584             hir::QPath::TypeRelative(..) | hir::QPath::LangItem(..) => self
585                 .type_dependent_def(id)
586                 .map_or(Res::Err, |(kind, def_id)| Res::Def(kind, def_id)),
587         }
588     }
589
590     pub fn type_dependent_defs(
591         &self,
592     ) -> LocalTableInContext<'_, Result<(DefKind, DefId), ErrorGuaranteed>> {
593         LocalTableInContext { hir_owner: self.hir_owner, data: &self.type_dependent_defs }
594     }
595
596     pub fn type_dependent_def(&self, id: HirId) -> Option<(DefKind, DefId)> {
597         validate_hir_id_for_typeck_results(self.hir_owner, id);
598         self.type_dependent_defs.get(&id.local_id).cloned().and_then(|r| r.ok())
599     }
600
601     pub fn type_dependent_def_id(&self, id: HirId) -> Option<DefId> {
602         self.type_dependent_def(id).map(|(_, def_id)| def_id)
603     }
604
605     pub fn type_dependent_defs_mut(
606         &mut self,
607     ) -> LocalTableInContextMut<'_, Result<(DefKind, DefId), ErrorGuaranteed>> {
608         LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.type_dependent_defs }
609     }
610
611     pub fn field_indices(&self) -> LocalTableInContext<'_, usize> {
612         LocalTableInContext { hir_owner: self.hir_owner, data: &self.field_indices }
613     }
614
615     pub fn field_indices_mut(&mut self) -> LocalTableInContextMut<'_, usize> {
616         LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.field_indices }
617     }
618
619     pub fn user_provided_types(&self) -> LocalTableInContext<'_, CanonicalUserType<'tcx>> {
620         LocalTableInContext { hir_owner: self.hir_owner, data: &self.user_provided_types }
621     }
622
623     pub fn user_provided_types_mut(
624         &mut self,
625     ) -> LocalTableInContextMut<'_, CanonicalUserType<'tcx>> {
626         LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.user_provided_types }
627     }
628
629     pub fn node_types(&self) -> LocalTableInContext<'_, Ty<'tcx>> {
630         LocalTableInContext { hir_owner: self.hir_owner, data: &self.node_types }
631     }
632
633     pub fn node_types_mut(&mut self) -> LocalTableInContextMut<'_, Ty<'tcx>> {
634         LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.node_types }
635     }
636
637     pub fn get_generator_diagnostic_data(&self) -> GeneratorDiagnosticData<'tcx> {
638         let generator_interior_type = self.generator_interior_types.map_bound_ref(|vec| {
639             vec.iter()
640                 .map(|item| {
641                     GeneratorInteriorTypeCause {
642                         ty: item.ty,
643                         span: item.span,
644                         scope_span: item.scope_span,
645                         yield_span: item.yield_span,
646                         expr: None, //FIXME: Passing expression over crate boundaries is impossible at the moment
647                     }
648                 })
649                 .collect::<Vec<_>>()
650         });
651         GeneratorDiagnosticData {
652             generator_interior_types: generator_interior_type,
653             hir_owner: self.hir_owner.to_def_id(),
654             nodes_types: self.node_types.clone(),
655             adjustments: self.adjustments.clone(),
656         }
657     }
658
659     pub fn node_type(&self, id: hir::HirId) -> Ty<'tcx> {
660         self.node_type_opt(id).unwrap_or_else(|| {
661             bug!("node_type: no type for node `{}`", tls::with(|tcx| tcx.hir().node_to_string(id)))
662         })
663     }
664
665     pub fn node_type_opt(&self, id: hir::HirId) -> Option<Ty<'tcx>> {
666         validate_hir_id_for_typeck_results(self.hir_owner, id);
667         self.node_types.get(&id.local_id).cloned()
668     }
669
670     pub fn node_substs_mut(&mut self) -> LocalTableInContextMut<'_, SubstsRef<'tcx>> {
671         LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.node_substs }
672     }
673
674     pub fn node_substs(&self, id: hir::HirId) -> SubstsRef<'tcx> {
675         validate_hir_id_for_typeck_results(self.hir_owner, id);
676         self.node_substs.get(&id.local_id).cloned().unwrap_or_else(|| InternalSubsts::empty())
677     }
678
679     pub fn node_substs_opt(&self, id: hir::HirId) -> Option<SubstsRef<'tcx>> {
680         validate_hir_id_for_typeck_results(self.hir_owner, id);
681         self.node_substs.get(&id.local_id).cloned()
682     }
683
684     // Returns the type of a pattern as a monotype. Like @expr_ty, this function
685     // doesn't provide type parameter substitutions.
686     pub fn pat_ty(&self, pat: &hir::Pat<'_>) -> Ty<'tcx> {
687         self.node_type(pat.hir_id)
688     }
689
690     // Returns the type of an expression as a monotype.
691     //
692     // NB (1): This is the PRE-ADJUSTMENT TYPE for the expression.  That is, in
693     // some cases, we insert `Adjustment` annotations such as auto-deref or
694     // auto-ref.  The type returned by this function does not consider such
695     // adjustments.  See `expr_ty_adjusted()` instead.
696     //
697     // NB (2): This type doesn't provide type parameter substitutions; e.g., if you
698     // ask for the type of "id" in "id(3)", it will return "fn(&isize) -> isize"
699     // instead of "fn(ty) -> T with T = isize".
700     pub fn expr_ty(&self, expr: &hir::Expr<'_>) -> Ty<'tcx> {
701         self.node_type(expr.hir_id)
702     }
703
704     pub fn expr_ty_opt(&self, expr: &hir::Expr<'_>) -> Option<Ty<'tcx>> {
705         self.node_type_opt(expr.hir_id)
706     }
707
708     pub fn adjustments(&self) -> LocalTableInContext<'_, Vec<ty::adjustment::Adjustment<'tcx>>> {
709         LocalTableInContext { hir_owner: self.hir_owner, data: &self.adjustments }
710     }
711
712     pub fn adjustments_mut(
713         &mut self,
714     ) -> LocalTableInContextMut<'_, Vec<ty::adjustment::Adjustment<'tcx>>> {
715         LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.adjustments }
716     }
717
718     pub fn expr_adjustments(&self, expr: &hir::Expr<'_>) -> &[ty::adjustment::Adjustment<'tcx>] {
719         validate_hir_id_for_typeck_results(self.hir_owner, expr.hir_id);
720         self.adjustments.get(&expr.hir_id.local_id).map_or(&[], |a| &a[..])
721     }
722
723     /// Returns the type of `expr`, considering any `Adjustment`
724     /// entry recorded for that expression.
725     pub fn expr_ty_adjusted(&self, expr: &hir::Expr<'_>) -> Ty<'tcx> {
726         self.expr_adjustments(expr).last().map_or_else(|| self.expr_ty(expr), |adj| adj.target)
727     }
728
729     pub fn expr_ty_adjusted_opt(&self, expr: &hir::Expr<'_>) -> Option<Ty<'tcx>> {
730         self.expr_adjustments(expr).last().map(|adj| adj.target).or_else(|| self.expr_ty_opt(expr))
731     }
732
733     pub fn is_method_call(&self, expr: &hir::Expr<'_>) -> bool {
734         // Only paths and method calls/overloaded operators have
735         // entries in type_dependent_defs, ignore the former here.
736         if let hir::ExprKind::Path(_) = expr.kind {
737             return false;
738         }
739
740         matches!(self.type_dependent_defs().get(expr.hir_id), Some(Ok((DefKind::AssocFn, _))))
741     }
742
743     pub fn extract_binding_mode(&self, s: &Session, id: HirId, sp: Span) -> Option<BindingMode> {
744         self.pat_binding_modes().get(id).copied().or_else(|| {
745             s.delay_span_bug(sp, "missing binding mode");
746             None
747         })
748     }
749
750     pub fn pat_binding_modes(&self) -> LocalTableInContext<'_, BindingMode> {
751         LocalTableInContext { hir_owner: self.hir_owner, data: &self.pat_binding_modes }
752     }
753
754     pub fn pat_binding_modes_mut(&mut self) -> LocalTableInContextMut<'_, BindingMode> {
755         LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.pat_binding_modes }
756     }
757
758     pub fn pat_adjustments(&self) -> LocalTableInContext<'_, Vec<Ty<'tcx>>> {
759         LocalTableInContext { hir_owner: self.hir_owner, data: &self.pat_adjustments }
760     }
761
762     pub fn pat_adjustments_mut(&mut self) -> LocalTableInContextMut<'_, Vec<Ty<'tcx>>> {
763         LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.pat_adjustments }
764     }
765
766     /// For a given closure, returns the iterator of `ty::CapturedPlace`s that are captured
767     /// by the closure.
768     pub fn closure_min_captures_flattened(
769         &self,
770         closure_def_id: DefId,
771     ) -> impl Iterator<Item = &ty::CapturedPlace<'tcx>> {
772         self.closure_min_captures
773             .get(&closure_def_id)
774             .map(|closure_min_captures| closure_min_captures.values().flat_map(|v| v.iter()))
775             .into_iter()
776             .flatten()
777     }
778
779     pub fn closure_kind_origins(&self) -> LocalTableInContext<'_, (Span, HirPlace<'tcx>)> {
780         LocalTableInContext { hir_owner: self.hir_owner, data: &self.closure_kind_origins }
781     }
782
783     pub fn closure_kind_origins_mut(
784         &mut self,
785     ) -> LocalTableInContextMut<'_, (Span, HirPlace<'tcx>)> {
786         LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.closure_kind_origins }
787     }
788
789     pub fn liberated_fn_sigs(&self) -> LocalTableInContext<'_, ty::FnSig<'tcx>> {
790         LocalTableInContext { hir_owner: self.hir_owner, data: &self.liberated_fn_sigs }
791     }
792
793     pub fn liberated_fn_sigs_mut(&mut self) -> LocalTableInContextMut<'_, ty::FnSig<'tcx>> {
794         LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.liberated_fn_sigs }
795     }
796
797     pub fn fru_field_types(&self) -> LocalTableInContext<'_, Vec<Ty<'tcx>>> {
798         LocalTableInContext { hir_owner: self.hir_owner, data: &self.fru_field_types }
799     }
800
801     pub fn fru_field_types_mut(&mut self) -> LocalTableInContextMut<'_, Vec<Ty<'tcx>>> {
802         LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.fru_field_types }
803     }
804
805     pub fn is_coercion_cast(&self, hir_id: hir::HirId) -> bool {
806         validate_hir_id_for_typeck_results(self.hir_owner, hir_id);
807         self.coercion_casts.contains(&hir_id.local_id)
808     }
809
810     pub fn set_coercion_cast(&mut self, id: ItemLocalId) {
811         self.coercion_casts.insert(id);
812     }
813
814     pub fn coercion_casts(&self) -> &ItemLocalSet {
815         &self.coercion_casts
816     }
817 }
818
819 rustc_index::newtype_index! {
820     pub struct UserTypeAnnotationIndex {
821         derive [HashStable]
822         DEBUG_FORMAT = "UserType({})",
823         const START_INDEX = 0,
824     }
825 }
826
827 /// Mapping of type annotation indices to canonical user type annotations.
828 pub type CanonicalUserTypeAnnotations<'tcx> =
829     IndexVec<UserTypeAnnotationIndex, CanonicalUserTypeAnnotation<'tcx>>;
830
831 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
832 pub struct CanonicalUserTypeAnnotation<'tcx> {
833     pub user_ty: CanonicalUserType<'tcx>,
834     pub span: Span,
835     pub inferred_ty: Ty<'tcx>,
836 }
837
838 /// Canonicalized user type annotation.
839 pub type CanonicalUserType<'tcx> = Canonical<'tcx, UserType<'tcx>>;
840
841 impl<'tcx> CanonicalUserType<'tcx> {
842     /// Returns `true` if this represents a substitution of the form `[?0, ?1, ?2]`,
843     /// i.e., each thing is mapped to a canonical variable with the same index.
844     pub fn is_identity(&self) -> bool {
845         match self.value {
846             UserType::Ty(_) => false,
847             UserType::TypeOf(_, user_substs) => {
848                 if user_substs.user_self_ty.is_some() {
849                     return false;
850                 }
851
852                 iter::zip(user_substs.substs, BoundVar::new(0)..).all(|(kind, cvar)| {
853                     match kind.unpack() {
854                         GenericArgKind::Type(ty) => match ty.kind() {
855                             ty::Bound(debruijn, b) => {
856                                 // We only allow a `ty::INNERMOST` index in substitutions.
857                                 assert_eq!(*debruijn, ty::INNERMOST);
858                                 cvar == b.var
859                             }
860                             _ => false,
861                         },
862
863                         GenericArgKind::Lifetime(r) => match *r {
864                             ty::ReLateBound(debruijn, br) => {
865                                 // We only allow a `ty::INNERMOST` index in substitutions.
866                                 assert_eq!(debruijn, ty::INNERMOST);
867                                 cvar == br.var
868                             }
869                             _ => false,
870                         },
871
872                         GenericArgKind::Const(ct) => match ct.val() {
873                             ty::ConstKind::Bound(debruijn, b) => {
874                                 // We only allow a `ty::INNERMOST` index in substitutions.
875                                 assert_eq!(debruijn, ty::INNERMOST);
876                                 cvar == b
877                             }
878                             _ => false,
879                         },
880                     }
881                 })
882             }
883         }
884     }
885 }
886
887 /// A user-given type annotation attached to a constant. These arise
888 /// from constants that are named via paths, like `Foo::<A>::new` and
889 /// so forth.
890 #[derive(Copy, Clone, Debug, PartialEq, TyEncodable, TyDecodable)]
891 #[derive(HashStable, TypeFoldable, Lift)]
892 pub enum UserType<'tcx> {
893     Ty(Ty<'tcx>),
894
895     /// The canonical type is the result of `type_of(def_id)` with the
896     /// given substitutions applied.
897     TypeOf(DefId, UserSubsts<'tcx>),
898 }
899
900 impl<'tcx> CommonTypes<'tcx> {
901     fn new(
902         interners: &CtxtInterners<'tcx>,
903         sess: &Session,
904         resolutions: &ty::ResolverOutputs,
905     ) -> CommonTypes<'tcx> {
906         let mk = |ty| interners.intern_ty(ty, sess, resolutions);
907
908         CommonTypes {
909             unit: mk(Tuple(List::empty())),
910             bool: mk(Bool),
911             char: mk(Char),
912             never: mk(Never),
913             isize: mk(Int(ty::IntTy::Isize)),
914             i8: mk(Int(ty::IntTy::I8)),
915             i16: mk(Int(ty::IntTy::I16)),
916             i32: mk(Int(ty::IntTy::I32)),
917             i64: mk(Int(ty::IntTy::I64)),
918             i128: mk(Int(ty::IntTy::I128)),
919             usize: mk(Uint(ty::UintTy::Usize)),
920             u8: mk(Uint(ty::UintTy::U8)),
921             u16: mk(Uint(ty::UintTy::U16)),
922             u32: mk(Uint(ty::UintTy::U32)),
923             u64: mk(Uint(ty::UintTy::U64)),
924             u128: mk(Uint(ty::UintTy::U128)),
925             f32: mk(Float(ty::FloatTy::F32)),
926             f64: mk(Float(ty::FloatTy::F64)),
927             str_: mk(Str),
928             self_param: mk(ty::Param(ty::ParamTy { index: 0, name: kw::SelfUpper })),
929
930             trait_object_dummy_self: mk(Infer(ty::FreshTy(0))),
931         }
932     }
933 }
934
935 impl<'tcx> CommonLifetimes<'tcx> {
936     fn new(interners: &CtxtInterners<'tcx>) -> CommonLifetimes<'tcx> {
937         let mk = |r| {
938             Region(Interned::new_unchecked(
939                 interners.region.intern(r, |r| InternedInSet(interners.arena.alloc(r))).0,
940             ))
941         };
942
943         CommonLifetimes {
944             re_root_empty: mk(ty::ReEmpty(ty::UniverseIndex::ROOT)),
945             re_static: mk(ty::ReStatic),
946             re_erased: mk(ty::ReErased),
947         }
948     }
949 }
950
951 impl<'tcx> CommonConsts<'tcx> {
952     fn new(interners: &CtxtInterners<'tcx>, types: &CommonTypes<'tcx>) -> CommonConsts<'tcx> {
953         let mk_const = |c| {
954             Const(Interned::new_unchecked(
955                 interners.const_.intern(c, |c| InternedInSet(interners.arena.alloc(c))).0,
956             ))
957         };
958
959         CommonConsts {
960             unit: mk_const(ty::ConstS {
961                 val: ty::ConstKind::Value(ConstValue::Scalar(Scalar::ZST)),
962                 ty: types.unit,
963             }),
964         }
965     }
966 }
967
968 // This struct contains information regarding the `ReFree(FreeRegion)` corresponding to a lifetime
969 // conflict.
970 #[derive(Debug)]
971 pub struct FreeRegionInfo {
972     // `LocalDefId` corresponding to FreeRegion
973     pub def_id: LocalDefId,
974     // the bound region corresponding to FreeRegion
975     pub boundregion: ty::BoundRegionKind,
976     // checks if bound region is in Impl Item
977     pub is_impl_item: bool,
978 }
979
980 /// The central data structure of the compiler. It stores references
981 /// to the various **arenas** and also houses the results of the
982 /// various **compiler queries** that have been performed. See the
983 /// [rustc dev guide] for more details.
984 ///
985 /// [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/ty.html
986 #[derive(Copy, Clone)]
987 #[rustc_diagnostic_item = "TyCtxt"]
988 #[rustc_pass_by_value]
989 pub struct TyCtxt<'tcx> {
990     gcx: &'tcx GlobalCtxt<'tcx>,
991 }
992
993 impl<'tcx> Deref for TyCtxt<'tcx> {
994     type Target = &'tcx GlobalCtxt<'tcx>;
995     #[inline(always)]
996     fn deref(&self) -> &Self::Target {
997         &self.gcx
998     }
999 }
1000
1001 pub struct GlobalCtxt<'tcx> {
1002     pub arena: &'tcx WorkerLocal<Arena<'tcx>>,
1003
1004     interners: CtxtInterners<'tcx>,
1005
1006     pub sess: &'tcx Session,
1007
1008     /// This only ever stores a `LintStore` but we don't want a dependency on that type here.
1009     ///
1010     /// FIXME(Centril): consider `dyn LintStoreMarker` once
1011     /// we can upcast to `Any` for some additional type safety.
1012     pub lint_store: Lrc<dyn Any + sync::Sync + sync::Send>,
1013
1014     pub dep_graph: DepGraph,
1015
1016     pub prof: SelfProfilerRef,
1017
1018     /// Common types, pre-interned for your convenience.
1019     pub types: CommonTypes<'tcx>,
1020
1021     /// Common lifetimes, pre-interned for your convenience.
1022     pub lifetimes: CommonLifetimes<'tcx>,
1023
1024     /// Common consts, pre-interned for your convenience.
1025     pub consts: CommonConsts<'tcx>,
1026
1027     /// Output of the resolver.
1028     pub(crate) untracked_resolutions: ty::ResolverOutputs,
1029
1030     pub(crate) untracked_crate: &'tcx hir::Crate<'tcx>,
1031
1032     /// This provides access to the incremental compilation on-disk cache for query results.
1033     /// Do not access this directly. It is only meant to be used by
1034     /// `DepGraph::try_mark_green()` and the query infrastructure.
1035     /// This is `None` if we are not incremental compilation mode
1036     pub on_disk_cache: Option<&'tcx dyn OnDiskCache<'tcx>>,
1037
1038     pub queries: &'tcx dyn query::QueryEngine<'tcx>,
1039     pub query_caches: query::QueryCaches<'tcx>,
1040     query_kinds: &'tcx [DepKindStruct],
1041
1042     // Internal caches for metadata decoding. No need to track deps on this.
1043     pub ty_rcache: Lock<FxHashMap<ty::CReaderCacheKey, Ty<'tcx>>>,
1044     pub pred_rcache: Lock<FxHashMap<ty::CReaderCacheKey, Predicate<'tcx>>>,
1045
1046     /// Caches the results of trait selection. This cache is used
1047     /// for things that do not have to do with the parameters in scope.
1048     pub selection_cache: traits::SelectionCache<'tcx>,
1049
1050     /// Caches the results of trait evaluation. This cache is used
1051     /// for things that do not have to do with the parameters in scope.
1052     /// Merge this with `selection_cache`?
1053     pub evaluation_cache: traits::EvaluationCache<'tcx>,
1054
1055     /// The definite name of the current crate after taking into account
1056     /// attributes, commandline parameters, etc.
1057     crate_name: Symbol,
1058
1059     /// Data layout specification for the current target.
1060     pub data_layout: TargetDataLayout,
1061
1062     /// Stores memory for globals (statics/consts).
1063     pub(crate) alloc_map: Lock<interpret::AllocMap<'tcx>>,
1064
1065     output_filenames: Arc<OutputFilenames>,
1066 }
1067
1068 impl<'tcx> TyCtxt<'tcx> {
1069     pub fn typeck_opt_const_arg(
1070         self,
1071         def: ty::WithOptConstParam<LocalDefId>,
1072     ) -> &'tcx TypeckResults<'tcx> {
1073         if let Some(param_did) = def.const_param_did {
1074             self.typeck_const_arg((def.did, param_did))
1075         } else {
1076             self.typeck(def.did)
1077         }
1078     }
1079
1080     pub fn mir_borrowck_opt_const_arg(
1081         self,
1082         def: ty::WithOptConstParam<LocalDefId>,
1083     ) -> &'tcx BorrowCheckResult<'tcx> {
1084         if let Some(param_did) = def.const_param_did {
1085             self.mir_borrowck_const_arg((def.did, param_did))
1086         } else {
1087             self.mir_borrowck(def.did)
1088         }
1089     }
1090
1091     pub fn alloc_steal_thir(self, thir: Thir<'tcx>) -> &'tcx Steal<Thir<'tcx>> {
1092         self.arena.alloc(Steal::new(thir))
1093     }
1094
1095     pub fn alloc_steal_mir(self, mir: Body<'tcx>) -> &'tcx Steal<Body<'tcx>> {
1096         self.arena.alloc(Steal::new(mir))
1097     }
1098
1099     pub fn alloc_steal_promoted(
1100         self,
1101         promoted: IndexVec<Promoted, Body<'tcx>>,
1102     ) -> &'tcx Steal<IndexVec<Promoted, Body<'tcx>>> {
1103         self.arena.alloc(Steal::new(promoted))
1104     }
1105
1106     pub fn alloc_adt_def(
1107         self,
1108         did: DefId,
1109         kind: AdtKind,
1110         variants: IndexVec<VariantIdx, ty::VariantDef>,
1111         repr: ReprOptions,
1112     ) -> ty::AdtDef<'tcx> {
1113         self.intern_adt_def(ty::AdtDefData::new(self, did, kind, variants, repr))
1114     }
1115
1116     /// Allocates a read-only byte or string literal for `mir::interpret`.
1117     pub fn allocate_bytes(self, bytes: &[u8]) -> interpret::AllocId {
1118         // Create an allocation that just contains these bytes.
1119         let alloc = interpret::Allocation::from_bytes_byte_aligned_immutable(bytes);
1120         let alloc = self.intern_const_alloc(alloc);
1121         self.create_memory_alloc(alloc)
1122     }
1123
1124     /// Returns a range of the start/end indices specified with the
1125     /// `rustc_layout_scalar_valid_range` attribute.
1126     // FIXME(eddyb) this is an awkward spot for this method, maybe move it?
1127     pub fn layout_scalar_valid_range(self, def_id: DefId) -> (Bound<u128>, Bound<u128>) {
1128         let attrs = self.get_attrs(def_id);
1129         let get = |name| {
1130             let Some(attr) = attrs.iter().find(|a| a.has_name(name)) else {
1131                 return Bound::Unbounded;
1132             };
1133             debug!("layout_scalar_valid_range: attr={:?}", attr);
1134             if let Some(
1135                 &[
1136                     ast::NestedMetaItem::Literal(ast::Lit {
1137                         kind: ast::LitKind::Int(a, _), ..
1138                     }),
1139                 ],
1140             ) = attr.meta_item_list().as_deref()
1141             {
1142                 Bound::Included(a)
1143             } else {
1144                 self.sess
1145                     .delay_span_bug(attr.span, "invalid rustc_layout_scalar_valid_range attribute");
1146                 Bound::Unbounded
1147             }
1148         };
1149         (
1150             get(sym::rustc_layout_scalar_valid_range_start),
1151             get(sym::rustc_layout_scalar_valid_range_end),
1152         )
1153     }
1154
1155     pub fn lift<T: Lift<'tcx>>(self, value: T) -> Option<T::Lifted> {
1156         value.lift_to_tcx(self)
1157     }
1158
1159     /// Creates a type context and call the closure with a `TyCtxt` reference
1160     /// to the context. The closure enforces that the type context and any interned
1161     /// value (types, substs, etc.) can only be used while `ty::tls` has a valid
1162     /// reference to the context, to allow formatting values that need it.
1163     pub fn create_global_ctxt(
1164         s: &'tcx Session,
1165         lint_store: Lrc<dyn Any + sync::Send + sync::Sync>,
1166         arena: &'tcx WorkerLocal<Arena<'tcx>>,
1167         resolutions: ty::ResolverOutputs,
1168         krate: &'tcx hir::Crate<'tcx>,
1169         dep_graph: DepGraph,
1170         on_disk_cache: Option<&'tcx dyn OnDiskCache<'tcx>>,
1171         queries: &'tcx dyn query::QueryEngine<'tcx>,
1172         query_kinds: &'tcx [DepKindStruct],
1173         crate_name: &str,
1174         output_filenames: OutputFilenames,
1175     ) -> GlobalCtxt<'tcx> {
1176         let data_layout = TargetDataLayout::parse(&s.target).unwrap_or_else(|err| {
1177             s.fatal(&err);
1178         });
1179         let interners = CtxtInterners::new(arena);
1180         let common_types = CommonTypes::new(&interners, s, &resolutions);
1181         let common_lifetimes = CommonLifetimes::new(&interners);
1182         let common_consts = CommonConsts::new(&interners, &common_types);
1183
1184         GlobalCtxt {
1185             sess: s,
1186             lint_store,
1187             arena,
1188             interners,
1189             dep_graph,
1190             untracked_resolutions: resolutions,
1191             prof: s.prof.clone(),
1192             types: common_types,
1193             lifetimes: common_lifetimes,
1194             consts: common_consts,
1195             untracked_crate: krate,
1196             on_disk_cache,
1197             queries,
1198             query_caches: query::QueryCaches::default(),
1199             query_kinds,
1200             ty_rcache: Default::default(),
1201             pred_rcache: Default::default(),
1202             selection_cache: Default::default(),
1203             evaluation_cache: Default::default(),
1204             crate_name: Symbol::intern(crate_name),
1205             data_layout,
1206             alloc_map: Lock::new(interpret::AllocMap::new()),
1207             output_filenames: Arc::new(output_filenames),
1208         }
1209     }
1210
1211     crate fn query_kind(self, k: DepKind) -> &'tcx DepKindStruct {
1212         &self.query_kinds[k as usize]
1213     }
1214
1215     /// Constructs a `TyKind::Error` type and registers a `delay_span_bug` to ensure it gets used.
1216     #[track_caller]
1217     pub fn ty_error(self) -> Ty<'tcx> {
1218         self.ty_error_with_message(DUMMY_SP, "TyKind::Error constructed but no error reported")
1219     }
1220
1221     /// Constructs a `TyKind::Error` type and registers a `delay_span_bug` with the given `msg` to
1222     /// ensure it gets used.
1223     #[track_caller]
1224     pub fn ty_error_with_message<S: Into<MultiSpan>>(self, span: S, msg: &str) -> Ty<'tcx> {
1225         let reported = self.sess.delay_span_bug(span, msg);
1226         self.mk_ty(Error(DelaySpanBugEmitted { reported, _priv: () }))
1227     }
1228
1229     /// Like [TyCtxt::ty_error] but for constants.
1230     #[track_caller]
1231     pub fn const_error(self, ty: Ty<'tcx>) -> Const<'tcx> {
1232         self.const_error_with_message(
1233             ty,
1234             DUMMY_SP,
1235             "ty::ConstKind::Error constructed but no error reported",
1236         )
1237     }
1238
1239     /// Like [TyCtxt::ty_error_with_message] but for constants.
1240     #[track_caller]
1241     pub fn const_error_with_message<S: Into<MultiSpan>>(
1242         self,
1243         ty: Ty<'tcx>,
1244         span: S,
1245         msg: &str,
1246     ) -> Const<'tcx> {
1247         let reported = self.sess.delay_span_bug(span, msg);
1248         self.mk_const(ty::ConstS {
1249             val: ty::ConstKind::Error(DelaySpanBugEmitted { reported, _priv: () }),
1250             ty,
1251         })
1252     }
1253
1254     pub fn consider_optimizing<T: Fn() -> String>(self, msg: T) -> bool {
1255         let cname = self.crate_name(LOCAL_CRATE);
1256         self.sess.consider_optimizing(cname.as_str(), msg)
1257     }
1258
1259     /// Obtain all lang items of this crate and all dependencies (recursively)
1260     pub fn lang_items(self) -> &'tcx rustc_hir::lang_items::LanguageItems {
1261         self.get_lang_items(())
1262     }
1263
1264     /// Obtain the given diagnostic item's `DefId`. Use `is_diagnostic_item` if you just want to
1265     /// compare against another `DefId`, since `is_diagnostic_item` is cheaper.
1266     pub fn get_diagnostic_item(self, name: Symbol) -> Option<DefId> {
1267         self.all_diagnostic_items(()).name_to_id.get(&name).copied()
1268     }
1269
1270     /// Obtain the diagnostic item's name
1271     pub fn get_diagnostic_name(self, id: DefId) -> Option<Symbol> {
1272         self.diagnostic_items(id.krate).id_to_name.get(&id).copied()
1273     }
1274
1275     /// Check whether the diagnostic item with the given `name` has the given `DefId`.
1276     pub fn is_diagnostic_item(self, name: Symbol, did: DefId) -> bool {
1277         self.diagnostic_items(did.krate).name_to_id.get(&name) == Some(&did)
1278     }
1279
1280     pub fn stability(self) -> &'tcx stability::Index {
1281         self.stability_index(())
1282     }
1283
1284     pub fn features(self) -> &'tcx rustc_feature::Features {
1285         self.features_query(())
1286     }
1287
1288     pub fn def_key(self, id: DefId) -> rustc_hir::definitions::DefKey {
1289         // Accessing the DefKey is ok, since it is part of DefPathHash.
1290         if let Some(id) = id.as_local() {
1291             self.untracked_resolutions.definitions.def_key(id)
1292         } else {
1293             self.untracked_resolutions.cstore.def_key(id)
1294         }
1295     }
1296
1297     /// Converts a `DefId` into its fully expanded `DefPath` (every
1298     /// `DefId` is really just an interned `DefPath`).
1299     ///
1300     /// Note that if `id` is not local to this crate, the result will
1301     ///  be a non-local `DefPath`.
1302     pub fn def_path(self, id: DefId) -> rustc_hir::definitions::DefPath {
1303         // Accessing the DefPath is ok, since it is part of DefPathHash.
1304         if let Some(id) = id.as_local() {
1305             self.untracked_resolutions.definitions.def_path(id)
1306         } else {
1307             self.untracked_resolutions.cstore.def_path(id)
1308         }
1309     }
1310
1311     #[inline]
1312     pub fn def_path_hash(self, def_id: DefId) -> rustc_hir::definitions::DefPathHash {
1313         // Accessing the DefPathHash is ok, it is incr. comp. stable.
1314         if let Some(def_id) = def_id.as_local() {
1315             self.untracked_resolutions.definitions.def_path_hash(def_id)
1316         } else {
1317             self.untracked_resolutions.cstore.def_path_hash(def_id)
1318         }
1319     }
1320
1321     #[inline]
1322     pub fn stable_crate_id(self, crate_num: CrateNum) -> StableCrateId {
1323         if crate_num == LOCAL_CRATE {
1324             self.sess.local_stable_crate_id()
1325         } else {
1326             self.untracked_resolutions.cstore.stable_crate_id(crate_num)
1327         }
1328     }
1329
1330     /// Maps a StableCrateId to the corresponding CrateNum. This method assumes
1331     /// that the crate in question has already been loaded by the CrateStore.
1332     #[inline]
1333     pub fn stable_crate_id_to_crate_num(self, stable_crate_id: StableCrateId) -> CrateNum {
1334         if stable_crate_id == self.sess.local_stable_crate_id() {
1335             LOCAL_CRATE
1336         } else {
1337             self.untracked_resolutions.cstore.stable_crate_id_to_crate_num(stable_crate_id)
1338         }
1339     }
1340
1341     /// Converts a `DefPathHash` to its corresponding `DefId` in the current compilation
1342     /// session, if it still exists. This is used during incremental compilation to
1343     /// turn a deserialized `DefPathHash` into its current `DefId`.
1344     pub fn def_path_hash_to_def_id(self, hash: DefPathHash, err: &mut dyn FnMut() -> !) -> DefId {
1345         debug!("def_path_hash_to_def_id({:?})", hash);
1346
1347         let stable_crate_id = hash.stable_crate_id();
1348
1349         // If this is a DefPathHash from the local crate, we can look up the
1350         // DefId in the tcx's `Definitions`.
1351         if stable_crate_id == self.sess.local_stable_crate_id() {
1352             self.untracked_resolutions
1353                 .definitions
1354                 .local_def_path_hash_to_def_id(hash, err)
1355                 .to_def_id()
1356         } else {
1357             // If this is a DefPathHash from an upstream crate, let the CrateStore map
1358             // it to a DefId.
1359             let cstore = &self.untracked_resolutions.cstore;
1360             let cnum = cstore.stable_crate_id_to_crate_num(stable_crate_id);
1361             cstore.def_path_hash_to_def_id(cnum, hash)
1362         }
1363     }
1364
1365     pub fn def_path_debug_str(self, def_id: DefId) -> String {
1366         // We are explicitly not going through queries here in order to get
1367         // crate name and stable crate id since this code is called from debug!()
1368         // statements within the query system and we'd run into endless
1369         // recursion otherwise.
1370         let (crate_name, stable_crate_id) = if def_id.is_local() {
1371             (self.crate_name, self.sess.local_stable_crate_id())
1372         } else {
1373             let cstore = &self.untracked_resolutions.cstore;
1374             (cstore.crate_name(def_id.krate), cstore.stable_crate_id(def_id.krate))
1375         };
1376
1377         format!(
1378             "{}[{}]{}",
1379             crate_name,
1380             // Don't print the whole stable crate id. That's just
1381             // annoying in debug output.
1382             &(format!("{:08x}", stable_crate_id.to_u64()))[..4],
1383             self.def_path(def_id).to_string_no_crate_verbose()
1384         )
1385     }
1386
1387     /// Note that this is *untracked* and should only be used within the query
1388     /// system if the result is otherwise tracked through queries
1389     pub fn cstore_untracked(self) -> &'tcx ty::CrateStoreDyn {
1390         &*self.untracked_resolutions.cstore
1391     }
1392
1393     /// Note that this is *untracked* and should only be used within the query
1394     /// system if the result is otherwise tracked through queries
1395     pub fn definitions_untracked(self) -> &'tcx hir::definitions::Definitions {
1396         &self.untracked_resolutions.definitions
1397     }
1398
1399     #[inline(always)]
1400     pub fn create_stable_hashing_context(self) -> StableHashingContext<'tcx> {
1401         let resolutions = &self.gcx.untracked_resolutions;
1402         StableHashingContext::new(self.sess, &resolutions.definitions, &*resolutions.cstore)
1403     }
1404
1405     #[inline(always)]
1406     pub fn create_no_span_stable_hashing_context(self) -> StableHashingContext<'tcx> {
1407         let resolutions = &self.gcx.untracked_resolutions;
1408         StableHashingContext::ignore_spans(
1409             self.sess,
1410             &resolutions.definitions,
1411             &*resolutions.cstore,
1412         )
1413     }
1414
1415     pub fn serialize_query_result_cache(self, encoder: &mut FileEncoder) -> FileEncodeResult {
1416         self.on_disk_cache.as_ref().map_or(Ok(()), |c| c.serialize(self, encoder))
1417     }
1418
1419     /// If `true`, we should use the MIR-based borrowck, but also
1420     /// fall back on the AST borrowck if the MIR-based one errors.
1421     pub fn migrate_borrowck(self) -> bool {
1422         self.borrowck_mode().migrate()
1423     }
1424
1425     /// What mode(s) of borrowck should we run? AST? MIR? both?
1426     /// (Also considers the `#![feature(nll)]` setting.)
1427     pub fn borrowck_mode(self) -> BorrowckMode {
1428         // Here are the main constraints we need to deal with:
1429         //
1430         // 1. An opts.borrowck_mode of `BorrowckMode::Migrate` is
1431         //    synonymous with no `-Z borrowck=...` flag at all.
1432         //
1433         // 2. We want to allow developers on the Nightly channel
1434         //    to opt back into the "hard error" mode for NLL,
1435         //    (which they can do via specifying `#![feature(nll)]`
1436         //    explicitly in their crate).
1437         //
1438         // So, this precedence list is how pnkfelix chose to work with
1439         // the above constraints:
1440         //
1441         // * `#![feature(nll)]` *always* means use NLL with hard
1442         //   errors. (To simplify the code here, it now even overrides
1443         //   a user's attempt to specify `-Z borrowck=compare`, which
1444         //   we arguably do not need anymore and should remove.)
1445         //
1446         // * Otherwise, if no `-Z borrowck=...` then use migrate mode
1447         //
1448         // * Otherwise, use the behavior requested via `-Z borrowck=...`
1449
1450         if self.features().nll {
1451             return BorrowckMode::Mir;
1452         }
1453
1454         self.sess.opts.borrowck_mode
1455     }
1456
1457     /// If `true`, we should use lazy normalization for constants, otherwise
1458     /// we still evaluate them eagerly.
1459     #[inline]
1460     pub fn lazy_normalization(self) -> bool {
1461         let features = self.features();
1462         // Note: We only use lazy normalization for generic const expressions.
1463         features.generic_const_exprs
1464     }
1465
1466     #[inline]
1467     pub fn local_crate_exports_generics(self) -> bool {
1468         debug_assert!(self.sess.opts.share_generics());
1469
1470         self.sess.crate_types().iter().any(|crate_type| {
1471             match crate_type {
1472                 CrateType::Executable
1473                 | CrateType::Staticlib
1474                 | CrateType::ProcMacro
1475                 | CrateType::Cdylib => false,
1476
1477                 // FIXME rust-lang/rust#64319, rust-lang/rust#64872:
1478                 // We want to block export of generics from dylibs,
1479                 // but we must fix rust-lang/rust#65890 before we can
1480                 // do that robustly.
1481                 CrateType::Dylib => true,
1482
1483                 CrateType::Rlib => true,
1484             }
1485         })
1486     }
1487
1488     // Returns the `DefId` and the `BoundRegionKind` corresponding to the given region.
1489     pub fn is_suitable_region(self, region: Region<'tcx>) -> Option<FreeRegionInfo> {
1490         let (suitable_region_binding_scope, bound_region) = match *region {
1491             ty::ReFree(ref free_region) => {
1492                 (free_region.scope.expect_local(), free_region.bound_region)
1493             }
1494             ty::ReEarlyBound(ref ebr) => (
1495                 self.parent(ebr.def_id).unwrap().expect_local(),
1496                 ty::BoundRegionKind::BrNamed(ebr.def_id, ebr.name),
1497             ),
1498             _ => return None, // not a free region
1499         };
1500
1501         let is_impl_item = match self.hir().find_by_def_id(suitable_region_binding_scope) {
1502             Some(Node::Item(..) | Node::TraitItem(..)) => false,
1503             Some(Node::ImplItem(..)) => {
1504                 self.is_bound_region_in_impl_item(suitable_region_binding_scope)
1505             }
1506             _ => return None,
1507         };
1508
1509         Some(FreeRegionInfo {
1510             def_id: suitable_region_binding_scope,
1511             boundregion: bound_region,
1512             is_impl_item,
1513         })
1514     }
1515
1516     /// Given a `DefId` for an `fn`, return all the `dyn` and `impl` traits in its return type.
1517     pub fn return_type_impl_or_dyn_traits(
1518         self,
1519         scope_def_id: LocalDefId,
1520     ) -> Vec<&'tcx hir::Ty<'tcx>> {
1521         let hir_id = self.hir().local_def_id_to_hir_id(scope_def_id);
1522         let Some(hir::FnDecl { output: hir::FnRetTy::Return(hir_output), .. }) = self.hir().fn_decl_by_hir_id(hir_id) else {
1523             return vec![];
1524         };
1525
1526         let mut v = TraitObjectVisitor(vec![], self.hir());
1527         v.visit_ty(hir_output);
1528         v.0
1529     }
1530
1531     pub fn return_type_impl_trait(self, scope_def_id: LocalDefId) -> Option<(Ty<'tcx>, Span)> {
1532         // `type_of()` will fail on these (#55796, #86483), so only allow `fn`s or closures.
1533         match self.hir().get_by_def_id(scope_def_id) {
1534             Node::Item(&hir::Item { kind: ItemKind::Fn(..), .. }) => {}
1535             Node::TraitItem(&hir::TraitItem { kind: TraitItemKind::Fn(..), .. }) => {}
1536             Node::ImplItem(&hir::ImplItem { kind: ImplItemKind::Fn(..), .. }) => {}
1537             Node::Expr(&hir::Expr { kind: ExprKind::Closure(..), .. }) => {}
1538             _ => return None,
1539         }
1540
1541         let ret_ty = self.type_of(scope_def_id);
1542         match ret_ty.kind() {
1543             ty::FnDef(_, _) => {
1544                 let sig = ret_ty.fn_sig(self);
1545                 let output = self.erase_late_bound_regions(sig.output());
1546                 if output.is_impl_trait() {
1547                     let hir_id = self.hir().local_def_id_to_hir_id(scope_def_id);
1548                     let fn_decl = self.hir().fn_decl_by_hir_id(hir_id).unwrap();
1549                     Some((output, fn_decl.output.span()))
1550                 } else {
1551                     None
1552                 }
1553             }
1554             _ => None,
1555         }
1556     }
1557
1558     // Checks if the bound region is in Impl Item.
1559     pub fn is_bound_region_in_impl_item(self, suitable_region_binding_scope: LocalDefId) -> bool {
1560         let container_id =
1561             self.associated_item(suitable_region_binding_scope.to_def_id()).container.id();
1562         if self.impl_trait_ref(container_id).is_some() {
1563             // For now, we do not try to target impls of traits. This is
1564             // because this message is going to suggest that the user
1565             // change the fn signature, but they may not be free to do so,
1566             // since the signature must match the trait.
1567             //
1568             // FIXME(#42706) -- in some cases, we could do better here.
1569             return true;
1570         }
1571         false
1572     }
1573
1574     /// Determines whether identifiers in the assembly have strict naming rules.
1575     /// Currently, only NVPTX* targets need it.
1576     pub fn has_strict_asm_symbol_naming(self) -> bool {
1577         self.sess.target.arch.contains("nvptx")
1578     }
1579
1580     /// Returns `&'static core::panic::Location<'static>`.
1581     pub fn caller_location_ty(self) -> Ty<'tcx> {
1582         self.mk_imm_ref(
1583             self.lifetimes.re_static,
1584             self.type_of(self.require_lang_item(LangItem::PanicLocation, None))
1585                 .subst(self, self.mk_substs([self.lifetimes.re_static.into()].iter())),
1586         )
1587     }
1588
1589     /// Returns a displayable description and article for the given `def_id` (e.g. `("a", "struct")`).
1590     pub fn article_and_description(self, def_id: DefId) -> (&'static str, &'static str) {
1591         match self.def_kind(def_id) {
1592             DefKind::Generator => match self.generator_kind(def_id).unwrap() {
1593                 rustc_hir::GeneratorKind::Async(..) => ("an", "async closure"),
1594                 rustc_hir::GeneratorKind::Gen => ("a", "generator"),
1595             },
1596             def_kind => (def_kind.article(), def_kind.descr(def_id)),
1597         }
1598     }
1599
1600     pub fn type_length_limit(self) -> Limit {
1601         self.limits(()).type_length_limit
1602     }
1603
1604     pub fn recursion_limit(self) -> Limit {
1605         self.limits(()).recursion_limit
1606     }
1607
1608     pub fn move_size_limit(self) -> Limit {
1609         self.limits(()).move_size_limit
1610     }
1611
1612     pub fn const_eval_limit(self) -> Limit {
1613         self.limits(()).const_eval_limit
1614     }
1615
1616     pub fn all_traits(self) -> impl Iterator<Item = DefId> + 'tcx {
1617         iter::once(LOCAL_CRATE)
1618             .chain(self.crates(()).iter().copied())
1619             .flat_map(move |cnum| self.traits_in_crate(cnum).iter().copied())
1620     }
1621 }
1622
1623 /// A trait implemented for all `X<'a>` types that can be safely and
1624 /// efficiently converted to `X<'tcx>` as long as they are part of the
1625 /// provided `TyCtxt<'tcx>`.
1626 /// This can be done, for example, for `Ty<'tcx>` or `SubstsRef<'tcx>`
1627 /// by looking them up in their respective interners.
1628 ///
1629 /// However, this is still not the best implementation as it does
1630 /// need to compare the components, even for interned values.
1631 /// It would be more efficient if `TypedArena` provided a way to
1632 /// determine whether the address is in the allocated range.
1633 ///
1634 /// `None` is returned if the value or one of the components is not part
1635 /// of the provided context.
1636 /// For `Ty`, `None` can be returned if either the type interner doesn't
1637 /// contain the `TyKind` key or if the address of the interned
1638 /// pointer differs. The latter case is possible if a primitive type,
1639 /// e.g., `()` or `u8`, was interned in a different context.
1640 pub trait Lift<'tcx>: fmt::Debug {
1641     type Lifted: fmt::Debug + 'tcx;
1642     fn lift_to_tcx(self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted>;
1643 }
1644
1645 macro_rules! nop_lift {
1646     ($set:ident; $ty:ty => $lifted:ty) => {
1647         impl<'a, 'tcx> Lift<'tcx> for $ty {
1648             type Lifted = $lifted;
1649             fn lift_to_tcx(self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
1650                 if tcx.interners.$set.contains_pointer_to(&InternedInSet(self.0.0)) {
1651                     // SAFETY: `self` is interned and therefore valid
1652                     // for the entire lifetime of the `TyCtxt`.
1653                     Some(unsafe { mem::transmute(self) })
1654                 } else {
1655                     None
1656                 }
1657             }
1658         }
1659     };
1660 }
1661
1662 // Can't use the macros as we have reuse the `substs` here.
1663 //
1664 // See `intern_type_list` for more info.
1665 impl<'a, 'tcx> Lift<'tcx> for &'a List<Ty<'a>> {
1666     type Lifted = &'tcx List<Ty<'tcx>>;
1667     fn lift_to_tcx(self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
1668         if self.is_empty() {
1669             return Some(List::empty());
1670         }
1671         if tcx.interners.substs.contains_pointer_to(&InternedInSet(self.as_substs())) {
1672             // SAFETY: `self` is interned and therefore valid
1673             // for the entire lifetime of the `TyCtxt`.
1674             Some(unsafe { mem::transmute::<&'a List<Ty<'a>>, &'tcx List<Ty<'tcx>>>(self) })
1675         } else {
1676             None
1677         }
1678     }
1679 }
1680
1681 macro_rules! nop_list_lift {
1682     ($set:ident; $ty:ty => $lifted:ty) => {
1683         impl<'a, 'tcx> Lift<'tcx> for &'a List<$ty> {
1684             type Lifted = &'tcx List<$lifted>;
1685             fn lift_to_tcx(self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
1686                 if self.is_empty() {
1687                     return Some(List::empty());
1688                 }
1689                 if tcx.interners.$set.contains_pointer_to(&InternedInSet(self)) {
1690                     Some(unsafe { mem::transmute(self) })
1691                 } else {
1692                     None
1693                 }
1694             }
1695         }
1696     };
1697 }
1698
1699 nop_lift! {type_; Ty<'a> => Ty<'tcx>}
1700 nop_lift! {region; Region<'a> => Region<'tcx>}
1701 nop_lift! {const_; Const<'a> => Const<'tcx>}
1702 nop_lift! {const_allocation; ConstAllocation<'a> => ConstAllocation<'tcx>}
1703 nop_lift! {predicate; Predicate<'a> => Predicate<'tcx>}
1704
1705 nop_list_lift! {poly_existential_predicates; ty::Binder<'a, ExistentialPredicate<'a>> => ty::Binder<'tcx, ExistentialPredicate<'tcx>>}
1706 nop_list_lift! {predicates; Predicate<'a> => Predicate<'tcx>}
1707 nop_list_lift! {canonical_var_infos; CanonicalVarInfo<'a> => CanonicalVarInfo<'tcx>}
1708 nop_list_lift! {projs; ProjectionKind => ProjectionKind}
1709 nop_list_lift! {bound_variable_kinds; ty::BoundVariableKind => ty::BoundVariableKind}
1710
1711 // This is the impl for `&'a InternalSubsts<'a>`.
1712 nop_list_lift! {substs; GenericArg<'a> => GenericArg<'tcx>}
1713
1714 CloneLiftImpls! { for<'tcx> { Constness, traits::WellFormedLoc, } }
1715
1716 pub mod tls {
1717     use super::{ptr_eq, GlobalCtxt, TyCtxt};
1718
1719     use crate::dep_graph::TaskDepsRef;
1720     use crate::ty::query;
1721     use rustc_data_structures::sync::{self, Lock};
1722     use rustc_data_structures::thin_vec::ThinVec;
1723     use rustc_errors::Diagnostic;
1724     use std::mem;
1725
1726     #[cfg(not(parallel_compiler))]
1727     use std::cell::Cell;
1728
1729     #[cfg(parallel_compiler)]
1730     use rustc_rayon_core as rayon_core;
1731
1732     /// This is the implicit state of rustc. It contains the current
1733     /// `TyCtxt` and query. It is updated when creating a local interner or
1734     /// executing a new query. Whenever there's a `TyCtxt` value available
1735     /// you should also have access to an `ImplicitCtxt` through the functions
1736     /// in this module.
1737     #[derive(Clone)]
1738     pub struct ImplicitCtxt<'a, 'tcx> {
1739         /// The current `TyCtxt`.
1740         pub tcx: TyCtxt<'tcx>,
1741
1742         /// The current query job, if any. This is updated by `JobOwner::start` in
1743         /// `ty::query::plumbing` when executing a query.
1744         pub query: Option<query::QueryJobId>,
1745
1746         /// Where to store diagnostics for the current query job, if any.
1747         /// This is updated by `JobOwner::start` in `ty::query::plumbing` when executing a query.
1748         pub diagnostics: Option<&'a Lock<ThinVec<Diagnostic>>>,
1749
1750         /// Used to prevent layout from recursing too deeply.
1751         pub layout_depth: usize,
1752
1753         /// The current dep graph task. This is used to add dependencies to queries
1754         /// when executing them.
1755         pub task_deps: TaskDepsRef<'a>,
1756     }
1757
1758     impl<'a, 'tcx> ImplicitCtxt<'a, 'tcx> {
1759         pub fn new(gcx: &'tcx GlobalCtxt<'tcx>) -> Self {
1760             let tcx = TyCtxt { gcx };
1761             ImplicitCtxt {
1762                 tcx,
1763                 query: None,
1764                 diagnostics: None,
1765                 layout_depth: 0,
1766                 task_deps: TaskDepsRef::Ignore,
1767             }
1768         }
1769     }
1770
1771     /// Sets Rayon's thread-local variable, which is preserved for Rayon jobs
1772     /// to `value` during the call to `f`. It is restored to its previous value after.
1773     /// This is used to set the pointer to the new `ImplicitCtxt`.
1774     #[cfg(parallel_compiler)]
1775     #[inline]
1776     fn set_tlv<F: FnOnce() -> R, R>(value: usize, f: F) -> R {
1777         rayon_core::tlv::with(value, f)
1778     }
1779
1780     /// Gets Rayon's thread-local variable, which is preserved for Rayon jobs.
1781     /// This is used to get the pointer to the current `ImplicitCtxt`.
1782     #[cfg(parallel_compiler)]
1783     #[inline]
1784     pub fn get_tlv() -> usize {
1785         rayon_core::tlv::get()
1786     }
1787
1788     #[cfg(not(parallel_compiler))]
1789     thread_local! {
1790         /// A thread local variable that stores a pointer to the current `ImplicitCtxt`.
1791         static TLV: Cell<usize> = const { Cell::new(0) };
1792     }
1793
1794     /// Sets TLV to `value` during the call to `f`.
1795     /// It is restored to its previous value after.
1796     /// This is used to set the pointer to the new `ImplicitCtxt`.
1797     #[cfg(not(parallel_compiler))]
1798     #[inline]
1799     fn set_tlv<F: FnOnce() -> R, R>(value: usize, f: F) -> R {
1800         let old = get_tlv();
1801         let _reset = rustc_data_structures::OnDrop(move || TLV.with(|tlv| tlv.set(old)));
1802         TLV.with(|tlv| tlv.set(value));
1803         f()
1804     }
1805
1806     /// Gets the pointer to the current `ImplicitCtxt`.
1807     #[cfg(not(parallel_compiler))]
1808     #[inline]
1809     fn get_tlv() -> usize {
1810         TLV.with(|tlv| tlv.get())
1811     }
1812
1813     /// Sets `context` as the new current `ImplicitCtxt` for the duration of the function `f`.
1814     #[inline]
1815     pub fn enter_context<'a, 'tcx, F, R>(context: &ImplicitCtxt<'a, 'tcx>, f: F) -> R
1816     where
1817         F: FnOnce(&ImplicitCtxt<'a, 'tcx>) -> R,
1818     {
1819         set_tlv(context as *const _ as usize, || f(&context))
1820     }
1821
1822     /// Allows access to the current `ImplicitCtxt` in a closure if one is available.
1823     #[inline]
1824     pub fn with_context_opt<F, R>(f: F) -> R
1825     where
1826         F: for<'a, 'tcx> FnOnce(Option<&ImplicitCtxt<'a, 'tcx>>) -> R,
1827     {
1828         let context = get_tlv();
1829         if context == 0 {
1830             f(None)
1831         } else {
1832             // We could get an `ImplicitCtxt` pointer from another thread.
1833             // Ensure that `ImplicitCtxt` is `Sync`.
1834             sync::assert_sync::<ImplicitCtxt<'_, '_>>();
1835
1836             unsafe { f(Some(&*(context as *const ImplicitCtxt<'_, '_>))) }
1837         }
1838     }
1839
1840     /// Allows access to the current `ImplicitCtxt`.
1841     /// Panics if there is no `ImplicitCtxt` available.
1842     #[inline]
1843     pub fn with_context<F, R>(f: F) -> R
1844     where
1845         F: for<'a, 'tcx> FnOnce(&ImplicitCtxt<'a, 'tcx>) -> R,
1846     {
1847         with_context_opt(|opt_context| f(opt_context.expect("no ImplicitCtxt stored in tls")))
1848     }
1849
1850     /// Allows access to the current `ImplicitCtxt` whose tcx field is the same as the tcx argument
1851     /// passed in. This means the closure is given an `ImplicitCtxt` with the same `'tcx` lifetime
1852     /// as the `TyCtxt` passed in.
1853     /// This will panic if you pass it a `TyCtxt` which is different from the current
1854     /// `ImplicitCtxt`'s `tcx` field.
1855     #[inline]
1856     pub fn with_related_context<'tcx, F, R>(tcx: TyCtxt<'tcx>, f: F) -> R
1857     where
1858         F: FnOnce(&ImplicitCtxt<'_, 'tcx>) -> R,
1859     {
1860         with_context(|context| unsafe {
1861             assert!(ptr_eq(context.tcx.gcx, tcx.gcx));
1862             let context: &ImplicitCtxt<'_, '_> = mem::transmute(context);
1863             f(context)
1864         })
1865     }
1866
1867     /// Allows access to the `TyCtxt` in the current `ImplicitCtxt`.
1868     /// Panics if there is no `ImplicitCtxt` available.
1869     #[inline]
1870     pub fn with<F, R>(f: F) -> R
1871     where
1872         F: for<'tcx> FnOnce(TyCtxt<'tcx>) -> R,
1873     {
1874         with_context(|context| f(context.tcx))
1875     }
1876
1877     /// Allows access to the `TyCtxt` in the current `ImplicitCtxt`.
1878     /// The closure is passed None if there is no `ImplicitCtxt` available.
1879     #[inline]
1880     pub fn with_opt<F, R>(f: F) -> R
1881     where
1882         F: for<'tcx> FnOnce(Option<TyCtxt<'tcx>>) -> R,
1883     {
1884         with_context_opt(|opt_context| f(opt_context.map(|context| context.tcx)))
1885     }
1886 }
1887
1888 macro_rules! sty_debug_print {
1889     ($fmt: expr, $ctxt: expr, $($variant: ident),*) => {{
1890         // Curious inner module to allow variant names to be used as
1891         // variable names.
1892         #[allow(non_snake_case)]
1893         mod inner {
1894             use crate::ty::{self, TyCtxt};
1895             use crate::ty::context::InternedInSet;
1896
1897             #[derive(Copy, Clone)]
1898             struct DebugStat {
1899                 total: usize,
1900                 lt_infer: usize,
1901                 ty_infer: usize,
1902                 ct_infer: usize,
1903                 all_infer: usize,
1904             }
1905
1906             pub fn go(fmt: &mut std::fmt::Formatter<'_>, tcx: TyCtxt<'_>) -> std::fmt::Result {
1907                 let mut total = DebugStat {
1908                     total: 0,
1909                     lt_infer: 0,
1910                     ty_infer: 0,
1911                     ct_infer: 0,
1912                     all_infer: 0,
1913                 };
1914                 $(let mut $variant = total;)*
1915
1916                 let shards = tcx.interners.type_.lock_shards();
1917                 let types = shards.iter().flat_map(|shard| shard.keys());
1918                 for &InternedInSet(t) in types {
1919                     let variant = match t.kind {
1920                         ty::Bool | ty::Char | ty::Int(..) | ty::Uint(..) |
1921                             ty::Float(..) | ty::Str | ty::Never => continue,
1922                         ty::Error(_) => /* unimportant */ continue,
1923                         $(ty::$variant(..) => &mut $variant,)*
1924                     };
1925                     let lt = t.flags.intersects(ty::TypeFlags::HAS_RE_INFER);
1926                     let ty = t.flags.intersects(ty::TypeFlags::HAS_TY_INFER);
1927                     let ct = t.flags.intersects(ty::TypeFlags::HAS_CT_INFER);
1928
1929                     variant.total += 1;
1930                     total.total += 1;
1931                     if lt { total.lt_infer += 1; variant.lt_infer += 1 }
1932                     if ty { total.ty_infer += 1; variant.ty_infer += 1 }
1933                     if ct { total.ct_infer += 1; variant.ct_infer += 1 }
1934                     if lt && ty && ct { total.all_infer += 1; variant.all_infer += 1 }
1935                 }
1936                 writeln!(fmt, "Ty interner             total           ty lt ct all")?;
1937                 $(writeln!(fmt, "    {:18}: {uses:6} {usespc:4.1}%, \
1938                             {ty:4.1}% {lt:5.1}% {ct:4.1}% {all:4.1}%",
1939                     stringify!($variant),
1940                     uses = $variant.total,
1941                     usespc = $variant.total as f64 * 100.0 / total.total as f64,
1942                     ty = $variant.ty_infer as f64 * 100.0  / total.total as f64,
1943                     lt = $variant.lt_infer as f64 * 100.0  / total.total as f64,
1944                     ct = $variant.ct_infer as f64 * 100.0  / total.total as f64,
1945                     all = $variant.all_infer as f64 * 100.0  / total.total as f64)?;
1946                 )*
1947                 writeln!(fmt, "                  total {uses:6}        \
1948                           {ty:4.1}% {lt:5.1}% {ct:4.1}% {all:4.1}%",
1949                     uses = total.total,
1950                     ty = total.ty_infer as f64 * 100.0  / total.total as f64,
1951                     lt = total.lt_infer as f64 * 100.0  / total.total as f64,
1952                     ct = total.ct_infer as f64 * 100.0  / total.total as f64,
1953                     all = total.all_infer as f64 * 100.0  / total.total as f64)
1954             }
1955         }
1956
1957         inner::go($fmt, $ctxt)
1958     }}
1959 }
1960
1961 impl<'tcx> TyCtxt<'tcx> {
1962     pub fn debug_stats(self) -> impl std::fmt::Debug + 'tcx {
1963         struct DebugStats<'tcx>(TyCtxt<'tcx>);
1964
1965         impl<'tcx> std::fmt::Debug for DebugStats<'tcx> {
1966             fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1967                 sty_debug_print!(
1968                     fmt,
1969                     self.0,
1970                     Adt,
1971                     Array,
1972                     Slice,
1973                     RawPtr,
1974                     Ref,
1975                     FnDef,
1976                     FnPtr,
1977                     Placeholder,
1978                     Generator,
1979                     GeneratorWitness,
1980                     Dynamic,
1981                     Closure,
1982                     Tuple,
1983                     Bound,
1984                     Param,
1985                     Infer,
1986                     Projection,
1987                     Opaque,
1988                     Foreign
1989                 )?;
1990
1991                 writeln!(fmt, "InternalSubsts interner: #{}", self.0.interners.substs.len())?;
1992                 writeln!(fmt, "Region interner: #{}", self.0.interners.region.len())?;
1993                 writeln!(
1994                     fmt,
1995                     "Const Allocation interner: #{}",
1996                     self.0.interners.const_allocation.len()
1997                 )?;
1998                 writeln!(fmt, "Layout interner: #{}", self.0.interners.layout.len())?;
1999
2000                 Ok(())
2001             }
2002         }
2003
2004         DebugStats(self)
2005     }
2006 }
2007
2008 // This type holds a `T` in the interner. The `T` is stored in the arena and
2009 // this type just holds a pointer to it, but it still effectively owns it. It
2010 // impls `Borrow` so that it can be looked up using the original
2011 // (non-arena-memory-owning) types.
2012 struct InternedInSet<'tcx, T: ?Sized>(&'tcx T);
2013
2014 impl<'tcx, T: 'tcx + ?Sized> Clone for InternedInSet<'tcx, T> {
2015     fn clone(&self) -> Self {
2016         InternedInSet(self.0)
2017     }
2018 }
2019
2020 impl<'tcx, T: 'tcx + ?Sized> Copy for InternedInSet<'tcx, T> {}
2021
2022 impl<'tcx, T: 'tcx + ?Sized> IntoPointer for InternedInSet<'tcx, T> {
2023     fn into_pointer(&self) -> *const () {
2024         self.0 as *const _ as *const ()
2025     }
2026 }
2027
2028 #[allow(rustc::usage_of_ty_tykind)]
2029 impl<'tcx> Borrow<TyKind<'tcx>> for InternedInSet<'tcx, WithStableHash<TyS<'tcx>>> {
2030     fn borrow<'a>(&'a self) -> &'a TyKind<'tcx> {
2031         &self.0.kind
2032     }
2033 }
2034
2035 impl<'tcx> PartialEq for InternedInSet<'tcx, WithStableHash<TyS<'tcx>>> {
2036     fn eq(&self, other: &InternedInSet<'tcx, WithStableHash<TyS<'tcx>>>) -> bool {
2037         // The `Borrow` trait requires that `x.borrow() == y.borrow()` equals
2038         // `x == y`.
2039         self.0.kind == other.0.kind
2040     }
2041 }
2042
2043 impl<'tcx> Eq for InternedInSet<'tcx, WithStableHash<TyS<'tcx>>> {}
2044
2045 impl<'tcx> Hash for InternedInSet<'tcx, WithStableHash<TyS<'tcx>>> {
2046     fn hash<H: Hasher>(&self, s: &mut H) {
2047         // The `Borrow` trait requires that `x.borrow().hash(s) == x.hash(s)`.
2048         self.0.kind.hash(s)
2049     }
2050 }
2051
2052 impl<'tcx> Borrow<Binder<'tcx, PredicateKind<'tcx>>> for InternedInSet<'tcx, PredicateS<'tcx>> {
2053     fn borrow<'a>(&'a self) -> &'a Binder<'tcx, PredicateKind<'tcx>> {
2054         &self.0.kind
2055     }
2056 }
2057
2058 impl<'tcx> PartialEq for InternedInSet<'tcx, PredicateS<'tcx>> {
2059     fn eq(&self, other: &InternedInSet<'tcx, PredicateS<'tcx>>) -> bool {
2060         // The `Borrow` trait requires that `x.borrow() == y.borrow()` equals
2061         // `x == y`.
2062         self.0.kind == other.0.kind
2063     }
2064 }
2065
2066 impl<'tcx> Eq for InternedInSet<'tcx, PredicateS<'tcx>> {}
2067
2068 impl<'tcx> Hash for InternedInSet<'tcx, PredicateS<'tcx>> {
2069     fn hash<H: Hasher>(&self, s: &mut H) {
2070         // The `Borrow` trait requires that `x.borrow().hash(s) == x.hash(s)`.
2071         self.0.kind.hash(s)
2072     }
2073 }
2074
2075 impl<'tcx, T> Borrow<[T]> for InternedInSet<'tcx, List<T>> {
2076     fn borrow<'a>(&'a self) -> &'a [T] {
2077         &self.0[..]
2078     }
2079 }
2080
2081 impl<'tcx, T: PartialEq> PartialEq for InternedInSet<'tcx, List<T>> {
2082     fn eq(&self, other: &InternedInSet<'tcx, List<T>>) -> bool {
2083         // The `Borrow` trait requires that `x.borrow() == y.borrow()` equals
2084         // `x == y`.
2085         self.0[..] == other.0[..]
2086     }
2087 }
2088
2089 impl<'tcx, T: Eq> Eq for InternedInSet<'tcx, List<T>> {}
2090
2091 impl<'tcx, T: Hash> Hash for InternedInSet<'tcx, List<T>> {
2092     fn hash<H: Hasher>(&self, s: &mut H) {
2093         // The `Borrow` trait requires that `x.borrow().hash(s) == x.hash(s)`.
2094         self.0[..].hash(s)
2095     }
2096 }
2097
2098 macro_rules! direct_interners {
2099     ($($name:ident: $method:ident($ty:ty): $ret_ctor:ident -> $ret_ty:ty,)+) => {
2100         $(impl<'tcx> Borrow<$ty> for InternedInSet<'tcx, $ty> {
2101             fn borrow<'a>(&'a self) -> &'a $ty {
2102                 &self.0
2103             }
2104         }
2105
2106         impl<'tcx> PartialEq for InternedInSet<'tcx, $ty> {
2107             fn eq(&self, other: &Self) -> bool {
2108                 // The `Borrow` trait requires that `x.borrow() == y.borrow()`
2109                 // equals `x == y`.
2110                 self.0 == other.0
2111             }
2112         }
2113
2114         impl<'tcx> Eq for InternedInSet<'tcx, $ty> {}
2115
2116         impl<'tcx> Hash for InternedInSet<'tcx, $ty> {
2117             fn hash<H: Hasher>(&self, s: &mut H) {
2118                 // The `Borrow` trait requires that `x.borrow().hash(s) ==
2119                 // x.hash(s)`.
2120                 self.0.hash(s)
2121             }
2122         }
2123
2124         impl<'tcx> TyCtxt<'tcx> {
2125             pub fn $method(self, v: $ty) -> $ret_ty {
2126                 $ret_ctor(Interned::new_unchecked(self.interners.$name.intern(v, |v| {
2127                     InternedInSet(self.interners.arena.alloc(v))
2128                 }).0))
2129             }
2130         })+
2131     }
2132 }
2133
2134 direct_interners! {
2135     region: mk_region(RegionKind): Region -> Region<'tcx>,
2136     const_: mk_const(ConstS<'tcx>): Const -> Const<'tcx>,
2137     const_allocation: intern_const_alloc(Allocation): ConstAllocation -> ConstAllocation<'tcx>,
2138     layout: intern_layout(LayoutS<'tcx>): Layout -> Layout<'tcx>,
2139     adt_def: intern_adt_def(AdtDefData): AdtDef -> AdtDef<'tcx>,
2140 }
2141
2142 macro_rules! slice_interners {
2143     ($($field:ident: $method:ident($ty:ty)),+ $(,)?) => (
2144         impl<'tcx> TyCtxt<'tcx> {
2145             $(pub fn $method(self, v: &[$ty]) -> &'tcx List<$ty> {
2146                 self.interners.$field.intern_ref(v, || {
2147                     InternedInSet(List::from_arena(&*self.arena, v))
2148                 }).0
2149             })+
2150         }
2151     );
2152 }
2153
2154 slice_interners!(
2155     substs: _intern_substs(GenericArg<'tcx>),
2156     canonical_var_infos: _intern_canonical_var_infos(CanonicalVarInfo<'tcx>),
2157     poly_existential_predicates:
2158         _intern_poly_existential_predicates(ty::Binder<'tcx, ExistentialPredicate<'tcx>>),
2159     predicates: _intern_predicates(Predicate<'tcx>),
2160     projs: _intern_projs(ProjectionKind),
2161     place_elems: _intern_place_elems(PlaceElem<'tcx>),
2162     bound_variable_kinds: _intern_bound_variable_kinds(ty::BoundVariableKind),
2163 );
2164
2165 impl<'tcx> TyCtxt<'tcx> {
2166     /// Given a `fn` type, returns an equivalent `unsafe fn` type;
2167     /// that is, a `fn` type that is equivalent in every way for being
2168     /// unsafe.
2169     pub fn safe_to_unsafe_fn_ty(self, sig: PolyFnSig<'tcx>) -> Ty<'tcx> {
2170         assert_eq!(sig.unsafety(), hir::Unsafety::Normal);
2171         self.mk_fn_ptr(sig.map_bound(|sig| ty::FnSig { unsafety: hir::Unsafety::Unsafe, ..sig }))
2172     }
2173
2174     /// Given the def_id of a Trait `trait_def_id` and the name of an associated item `assoc_name`
2175     /// returns true if the `trait_def_id` defines an associated item of name `assoc_name`.
2176     pub fn trait_may_define_assoc_type(self, trait_def_id: DefId, assoc_name: Ident) -> bool {
2177         self.super_traits_of(trait_def_id).any(|trait_did| {
2178             self.associated_items(trait_did)
2179                 .find_by_name_and_kind(self, assoc_name, ty::AssocKind::Type, trait_did)
2180                 .is_some()
2181         })
2182     }
2183
2184     /// Computes the def-ids of the transitive supertraits of `trait_def_id`. This (intentionally)
2185     /// does not compute the full elaborated super-predicates but just the set of def-ids. It is used
2186     /// to identify which traits may define a given associated type to help avoid cycle errors.
2187     /// Returns a `DefId` iterator.
2188     fn super_traits_of(self, trait_def_id: DefId) -> impl Iterator<Item = DefId> + 'tcx {
2189         let mut set = FxHashSet::default();
2190         let mut stack = vec![trait_def_id];
2191
2192         set.insert(trait_def_id);
2193
2194         iter::from_fn(move || -> Option<DefId> {
2195             let trait_did = stack.pop()?;
2196             let generic_predicates = self.super_predicates_of(trait_did);
2197
2198             for (predicate, _) in generic_predicates.predicates {
2199                 if let ty::PredicateKind::Trait(data) = predicate.kind().skip_binder() {
2200                     if set.insert(data.def_id()) {
2201                         stack.push(data.def_id());
2202                     }
2203                 }
2204             }
2205
2206             Some(trait_did)
2207         })
2208     }
2209
2210     /// Given a closure signature, returns an equivalent fn signature. Detuples
2211     /// and so forth -- so e.g., if we have a sig with `Fn<(u32, i32)>` then
2212     /// you would get a `fn(u32, i32)`.
2213     /// `unsafety` determines the unsafety of the fn signature. If you pass
2214     /// `hir::Unsafety::Unsafe` in the previous example, then you would get
2215     /// an `unsafe fn (u32, i32)`.
2216     /// It cannot convert a closure that requires unsafe.
2217     pub fn signature_unclosure(
2218         self,
2219         sig: PolyFnSig<'tcx>,
2220         unsafety: hir::Unsafety,
2221     ) -> PolyFnSig<'tcx> {
2222         sig.map_bound(|s| {
2223             let params_iter = match s.inputs()[0].kind() {
2224                 ty::Tuple(params) => params.into_iter(),
2225                 _ => bug!(),
2226             };
2227             self.mk_fn_sig(params_iter, s.output(), s.c_variadic, unsafety, abi::Abi::Rust)
2228         })
2229     }
2230
2231     /// Same a `self.mk_region(kind)`, but avoids accessing the interners if
2232     /// `*r == kind`.
2233     #[inline]
2234     pub fn reuse_or_mk_region(self, r: Region<'tcx>, kind: RegionKind) -> Region<'tcx> {
2235         if *r == kind { r } else { self.mk_region(kind) }
2236     }
2237
2238     #[allow(rustc::usage_of_ty_tykind)]
2239     #[inline]
2240     pub fn mk_ty(self, st: TyKind<'tcx>) -> Ty<'tcx> {
2241         self.interners.intern_ty(st, self.sess, &self.gcx.untracked_resolutions)
2242     }
2243
2244     #[inline]
2245     pub fn mk_predicate(self, binder: Binder<'tcx, PredicateKind<'tcx>>) -> Predicate<'tcx> {
2246         self.interners.intern_predicate(binder)
2247     }
2248
2249     #[inline]
2250     pub fn reuse_or_mk_predicate(
2251         self,
2252         pred: Predicate<'tcx>,
2253         binder: Binder<'tcx, PredicateKind<'tcx>>,
2254     ) -> Predicate<'tcx> {
2255         if pred.kind() != binder { self.mk_predicate(binder) } else { pred }
2256     }
2257
2258     pub fn mk_mach_int(self, tm: IntTy) -> Ty<'tcx> {
2259         match tm {
2260             IntTy::Isize => self.types.isize,
2261             IntTy::I8 => self.types.i8,
2262             IntTy::I16 => self.types.i16,
2263             IntTy::I32 => self.types.i32,
2264             IntTy::I64 => self.types.i64,
2265             IntTy::I128 => self.types.i128,
2266         }
2267     }
2268
2269     pub fn mk_mach_uint(self, tm: UintTy) -> Ty<'tcx> {
2270         match tm {
2271             UintTy::Usize => self.types.usize,
2272             UintTy::U8 => self.types.u8,
2273             UintTy::U16 => self.types.u16,
2274             UintTy::U32 => self.types.u32,
2275             UintTy::U64 => self.types.u64,
2276             UintTy::U128 => self.types.u128,
2277         }
2278     }
2279
2280     pub fn mk_mach_float(self, tm: FloatTy) -> Ty<'tcx> {
2281         match tm {
2282             FloatTy::F32 => self.types.f32,
2283             FloatTy::F64 => self.types.f64,
2284         }
2285     }
2286
2287     #[inline]
2288     pub fn mk_static_str(self) -> Ty<'tcx> {
2289         self.mk_imm_ref(self.lifetimes.re_static, self.types.str_)
2290     }
2291
2292     #[inline]
2293     pub fn mk_adt(self, def: AdtDef<'tcx>, substs: SubstsRef<'tcx>) -> Ty<'tcx> {
2294         // Take a copy of substs so that we own the vectors inside.
2295         self.mk_ty(Adt(def, substs))
2296     }
2297
2298     #[inline]
2299     pub fn mk_foreign(self, def_id: DefId) -> Ty<'tcx> {
2300         self.mk_ty(Foreign(def_id))
2301     }
2302
2303     fn mk_generic_adt(self, wrapper_def_id: DefId, ty_param: Ty<'tcx>) -> Ty<'tcx> {
2304         let adt_def = self.adt_def(wrapper_def_id);
2305         let substs =
2306             InternalSubsts::for_item(self, wrapper_def_id, |param, substs| match param.kind {
2307                 GenericParamDefKind::Lifetime | GenericParamDefKind::Const { .. } => bug!(),
2308                 GenericParamDefKind::Type { has_default, .. } => {
2309                     if param.index == 0 {
2310                         ty_param.into()
2311                     } else {
2312                         assert!(has_default);
2313                         self.type_of(param.def_id).subst(self, substs).into()
2314                     }
2315                 }
2316             });
2317         self.mk_ty(Adt(adt_def, substs))
2318     }
2319
2320     #[inline]
2321     pub fn mk_box(self, ty: Ty<'tcx>) -> Ty<'tcx> {
2322         let def_id = self.require_lang_item(LangItem::OwnedBox, None);
2323         self.mk_generic_adt(def_id, ty)
2324     }
2325
2326     #[inline]
2327     pub fn mk_lang_item(self, ty: Ty<'tcx>, item: LangItem) -> Option<Ty<'tcx>> {
2328         let def_id = self.lang_items().require(item).ok()?;
2329         Some(self.mk_generic_adt(def_id, ty))
2330     }
2331
2332     #[inline]
2333     pub fn mk_diagnostic_item(self, ty: Ty<'tcx>, name: Symbol) -> Option<Ty<'tcx>> {
2334         let def_id = self.get_diagnostic_item(name)?;
2335         Some(self.mk_generic_adt(def_id, ty))
2336     }
2337
2338     #[inline]
2339     pub fn mk_maybe_uninit(self, ty: Ty<'tcx>) -> Ty<'tcx> {
2340         let def_id = self.require_lang_item(LangItem::MaybeUninit, None);
2341         self.mk_generic_adt(def_id, ty)
2342     }
2343
2344     #[inline]
2345     pub fn mk_ptr(self, tm: TypeAndMut<'tcx>) -> Ty<'tcx> {
2346         self.mk_ty(RawPtr(tm))
2347     }
2348
2349     #[inline]
2350     pub fn mk_ref(self, r: Region<'tcx>, tm: TypeAndMut<'tcx>) -> Ty<'tcx> {
2351         self.mk_ty(Ref(r, tm.ty, tm.mutbl))
2352     }
2353
2354     #[inline]
2355     pub fn mk_mut_ref(self, r: Region<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
2356         self.mk_ref(r, TypeAndMut { ty, mutbl: hir::Mutability::Mut })
2357     }
2358
2359     #[inline]
2360     pub fn mk_imm_ref(self, r: Region<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
2361         self.mk_ref(r, TypeAndMut { ty, mutbl: hir::Mutability::Not })
2362     }
2363
2364     #[inline]
2365     pub fn mk_mut_ptr(self, ty: Ty<'tcx>) -> Ty<'tcx> {
2366         self.mk_ptr(TypeAndMut { ty, mutbl: hir::Mutability::Mut })
2367     }
2368
2369     #[inline]
2370     pub fn mk_imm_ptr(self, ty: Ty<'tcx>) -> Ty<'tcx> {
2371         self.mk_ptr(TypeAndMut { ty, mutbl: hir::Mutability::Not })
2372     }
2373
2374     #[inline]
2375     pub fn mk_array(self, ty: Ty<'tcx>, n: u64) -> Ty<'tcx> {
2376         self.mk_ty(Array(ty, ty::Const::from_usize(self, n)))
2377     }
2378
2379     #[inline]
2380     pub fn mk_slice(self, ty: Ty<'tcx>) -> Ty<'tcx> {
2381         self.mk_ty(Slice(ty))
2382     }
2383
2384     #[inline]
2385     pub fn intern_tup(self, ts: &[Ty<'tcx>]) -> Ty<'tcx> {
2386         self.mk_ty(Tuple(self.intern_type_list(&ts)))
2387     }
2388
2389     pub fn mk_tup<I: InternAs<[Ty<'tcx>], Ty<'tcx>>>(self, iter: I) -> I::Output {
2390         iter.intern_with(|ts| self.mk_ty(Tuple(self.intern_type_list(&ts))))
2391     }
2392
2393     #[inline]
2394     pub fn mk_unit(self) -> Ty<'tcx> {
2395         self.types.unit
2396     }
2397
2398     #[inline]
2399     pub fn mk_diverging_default(self) -> Ty<'tcx> {
2400         if self.features().never_type_fallback { self.types.never } else { self.types.unit }
2401     }
2402
2403     #[inline]
2404     pub fn mk_fn_def(self, def_id: DefId, substs: SubstsRef<'tcx>) -> Ty<'tcx> {
2405         self.mk_ty(FnDef(def_id, substs))
2406     }
2407
2408     #[inline]
2409     pub fn mk_fn_ptr(self, fty: PolyFnSig<'tcx>) -> Ty<'tcx> {
2410         self.mk_ty(FnPtr(fty))
2411     }
2412
2413     #[inline]
2414     pub fn mk_dynamic(
2415         self,
2416         obj: &'tcx List<ty::Binder<'tcx, ExistentialPredicate<'tcx>>>,
2417         reg: ty::Region<'tcx>,
2418     ) -> Ty<'tcx> {
2419         self.mk_ty(Dynamic(obj, reg))
2420     }
2421
2422     #[inline]
2423     pub fn mk_projection(self, item_def_id: DefId, substs: SubstsRef<'tcx>) -> Ty<'tcx> {
2424         self.mk_ty(Projection(ProjectionTy { item_def_id, substs }))
2425     }
2426
2427     #[inline]
2428     pub fn mk_closure(self, closure_id: DefId, closure_substs: SubstsRef<'tcx>) -> Ty<'tcx> {
2429         self.mk_ty(Closure(closure_id, closure_substs))
2430     }
2431
2432     #[inline]
2433     pub fn mk_generator(
2434         self,
2435         id: DefId,
2436         generator_substs: SubstsRef<'tcx>,
2437         movability: hir::Movability,
2438     ) -> Ty<'tcx> {
2439         self.mk_ty(Generator(id, generator_substs, movability))
2440     }
2441
2442     #[inline]
2443     pub fn mk_generator_witness(self, types: ty::Binder<'tcx, &'tcx List<Ty<'tcx>>>) -> Ty<'tcx> {
2444         self.mk_ty(GeneratorWitness(types))
2445     }
2446
2447     #[inline]
2448     pub fn mk_ty_var(self, v: TyVid) -> Ty<'tcx> {
2449         self.mk_ty_infer(TyVar(v))
2450     }
2451
2452     #[inline]
2453     pub fn mk_const_var(self, v: ConstVid<'tcx>, ty: Ty<'tcx>) -> Const<'tcx> {
2454         self.mk_const(ty::ConstS { val: ty::ConstKind::Infer(InferConst::Var(v)), ty })
2455     }
2456
2457     #[inline]
2458     pub fn mk_int_var(self, v: IntVid) -> Ty<'tcx> {
2459         self.mk_ty_infer(IntVar(v))
2460     }
2461
2462     #[inline]
2463     pub fn mk_float_var(self, v: FloatVid) -> Ty<'tcx> {
2464         self.mk_ty_infer(FloatVar(v))
2465     }
2466
2467     #[inline]
2468     pub fn mk_ty_infer(self, it: InferTy) -> Ty<'tcx> {
2469         self.mk_ty(Infer(it))
2470     }
2471
2472     #[inline]
2473     pub fn mk_const_infer(self, ic: InferConst<'tcx>, ty: Ty<'tcx>) -> ty::Const<'tcx> {
2474         self.mk_const(ty::ConstS { val: ty::ConstKind::Infer(ic), ty })
2475     }
2476
2477     #[inline]
2478     pub fn mk_ty_param(self, index: u32, name: Symbol) -> Ty<'tcx> {
2479         self.mk_ty(Param(ParamTy { index, name }))
2480     }
2481
2482     #[inline]
2483     pub fn mk_const_param(self, index: u32, name: Symbol, ty: Ty<'tcx>) -> Const<'tcx> {
2484         self.mk_const(ty::ConstS { val: ty::ConstKind::Param(ParamConst { index, name }), ty })
2485     }
2486
2487     pub fn mk_param_from_def(self, param: &ty::GenericParamDef) -> GenericArg<'tcx> {
2488         match param.kind {
2489             GenericParamDefKind::Lifetime => {
2490                 self.mk_region(ty::ReEarlyBound(param.to_early_bound_region_data())).into()
2491             }
2492             GenericParamDefKind::Type { .. } => self.mk_ty_param(param.index, param.name).into(),
2493             GenericParamDefKind::Const { .. } => {
2494                 self.mk_const_param(param.index, param.name, self.type_of(param.def_id)).into()
2495             }
2496         }
2497     }
2498
2499     #[inline]
2500     pub fn mk_opaque(self, def_id: DefId, substs: SubstsRef<'tcx>) -> Ty<'tcx> {
2501         self.mk_ty(Opaque(def_id, substs))
2502     }
2503
2504     pub fn mk_place_field(self, place: Place<'tcx>, f: Field, ty: Ty<'tcx>) -> Place<'tcx> {
2505         self.mk_place_elem(place, PlaceElem::Field(f, ty))
2506     }
2507
2508     pub fn mk_place_deref(self, place: Place<'tcx>) -> Place<'tcx> {
2509         self.mk_place_elem(place, PlaceElem::Deref)
2510     }
2511
2512     pub fn mk_place_downcast(
2513         self,
2514         place: Place<'tcx>,
2515         adt_def: AdtDef<'tcx>,
2516         variant_index: VariantIdx,
2517     ) -> Place<'tcx> {
2518         self.mk_place_elem(
2519             place,
2520             PlaceElem::Downcast(Some(adt_def.variant(variant_index).name), variant_index),
2521         )
2522     }
2523
2524     pub fn mk_place_downcast_unnamed(
2525         self,
2526         place: Place<'tcx>,
2527         variant_index: VariantIdx,
2528     ) -> Place<'tcx> {
2529         self.mk_place_elem(place, PlaceElem::Downcast(None, variant_index))
2530     }
2531
2532     pub fn mk_place_index(self, place: Place<'tcx>, index: Local) -> Place<'tcx> {
2533         self.mk_place_elem(place, PlaceElem::Index(index))
2534     }
2535
2536     /// This method copies `Place`'s projection, add an element and reintern it. Should not be used
2537     /// to build a full `Place` it's just a convenient way to grab a projection and modify it in
2538     /// flight.
2539     pub fn mk_place_elem(self, place: Place<'tcx>, elem: PlaceElem<'tcx>) -> Place<'tcx> {
2540         let mut projection = place.projection.to_vec();
2541         projection.push(elem);
2542
2543         Place { local: place.local, projection: self.intern_place_elems(&projection) }
2544     }
2545
2546     pub fn intern_poly_existential_predicates(
2547         self,
2548         eps: &[ty::Binder<'tcx, ExistentialPredicate<'tcx>>],
2549     ) -> &'tcx List<ty::Binder<'tcx, ExistentialPredicate<'tcx>>> {
2550         assert!(!eps.is_empty());
2551         assert!(
2552             eps.array_windows()
2553                 .all(|[a, b]| a.skip_binder().stable_cmp(self, &b.skip_binder())
2554                     != Ordering::Greater)
2555         );
2556         self._intern_poly_existential_predicates(eps)
2557     }
2558
2559     pub fn intern_predicates(self, preds: &[Predicate<'tcx>]) -> &'tcx List<Predicate<'tcx>> {
2560         // FIXME consider asking the input slice to be sorted to avoid
2561         // re-interning permutations, in which case that would be asserted
2562         // here.
2563         if preds.is_empty() {
2564             // The macro-generated method below asserts we don't intern an empty slice.
2565             List::empty()
2566         } else {
2567             self._intern_predicates(preds)
2568         }
2569     }
2570
2571     pub fn intern_type_list(self, ts: &[Ty<'tcx>]) -> &'tcx List<Ty<'tcx>> {
2572         if ts.is_empty() {
2573             List::empty()
2574         } else {
2575             // Actually intern type lists as lists of `GenericArg`s.
2576             //
2577             // Transmuting from `Ty<'tcx>` to `GenericArg<'tcx>` is sound
2578             // as explained in ty_slice_as_generic_arg`. With this,
2579             // we guarantee that even when transmuting between `List<Ty<'tcx>>`
2580             // and `List<GenericArg<'tcx>>`, the uniqueness requirement for
2581             // lists is upheld.
2582             let substs = self._intern_substs(ty::subst::ty_slice_as_generic_args(ts));
2583             substs.try_as_type_list().unwrap()
2584         }
2585     }
2586
2587     pub fn intern_substs(self, ts: &[GenericArg<'tcx>]) -> &'tcx List<GenericArg<'tcx>> {
2588         if ts.is_empty() { List::empty() } else { self._intern_substs(ts) }
2589     }
2590
2591     pub fn intern_projs(self, ps: &[ProjectionKind]) -> &'tcx List<ProjectionKind> {
2592         if ps.is_empty() { List::empty() } else { self._intern_projs(ps) }
2593     }
2594
2595     pub fn intern_place_elems(self, ts: &[PlaceElem<'tcx>]) -> &'tcx List<PlaceElem<'tcx>> {
2596         if ts.is_empty() { List::empty() } else { self._intern_place_elems(ts) }
2597     }
2598
2599     pub fn intern_canonical_var_infos(
2600         self,
2601         ts: &[CanonicalVarInfo<'tcx>],
2602     ) -> CanonicalVarInfos<'tcx> {
2603         if ts.is_empty() { List::empty() } else { self._intern_canonical_var_infos(ts) }
2604     }
2605
2606     pub fn intern_bound_variable_kinds(
2607         self,
2608         ts: &[ty::BoundVariableKind],
2609     ) -> &'tcx List<ty::BoundVariableKind> {
2610         if ts.is_empty() { List::empty() } else { self._intern_bound_variable_kinds(ts) }
2611     }
2612
2613     pub fn mk_fn_sig<I>(
2614         self,
2615         inputs: I,
2616         output: I::Item,
2617         c_variadic: bool,
2618         unsafety: hir::Unsafety,
2619         abi: abi::Abi,
2620     ) -> <I::Item as InternIteratorElement<Ty<'tcx>, ty::FnSig<'tcx>>>::Output
2621     where
2622         I: Iterator<Item: InternIteratorElement<Ty<'tcx>, ty::FnSig<'tcx>>>,
2623     {
2624         inputs.chain(iter::once(output)).intern_with(|xs| ty::FnSig {
2625             inputs_and_output: self.intern_type_list(xs),
2626             c_variadic,
2627             unsafety,
2628             abi,
2629         })
2630     }
2631
2632     pub fn mk_poly_existential_predicates<
2633         I: InternAs<
2634             [ty::Binder<'tcx, ExistentialPredicate<'tcx>>],
2635             &'tcx List<ty::Binder<'tcx, ExistentialPredicate<'tcx>>>,
2636         >,
2637     >(
2638         self,
2639         iter: I,
2640     ) -> I::Output {
2641         iter.intern_with(|xs| self.intern_poly_existential_predicates(xs))
2642     }
2643
2644     pub fn mk_predicates<I: InternAs<[Predicate<'tcx>], &'tcx List<Predicate<'tcx>>>>(
2645         self,
2646         iter: I,
2647     ) -> I::Output {
2648         iter.intern_with(|xs| self.intern_predicates(xs))
2649     }
2650
2651     pub fn mk_type_list<I: InternAs<[Ty<'tcx>], &'tcx List<Ty<'tcx>>>>(self, iter: I) -> I::Output {
2652         iter.intern_with(|xs| self.intern_type_list(xs))
2653     }
2654
2655     pub fn mk_substs<I: InternAs<[GenericArg<'tcx>], &'tcx List<GenericArg<'tcx>>>>(
2656         self,
2657         iter: I,
2658     ) -> I::Output {
2659         iter.intern_with(|xs| self.intern_substs(xs))
2660     }
2661
2662     pub fn mk_place_elems<I: InternAs<[PlaceElem<'tcx>], &'tcx List<PlaceElem<'tcx>>>>(
2663         self,
2664         iter: I,
2665     ) -> I::Output {
2666         iter.intern_with(|xs| self.intern_place_elems(xs))
2667     }
2668
2669     pub fn mk_substs_trait(self, self_ty: Ty<'tcx>, rest: &[GenericArg<'tcx>]) -> SubstsRef<'tcx> {
2670         self.mk_substs(iter::once(self_ty.into()).chain(rest.iter().cloned()))
2671     }
2672
2673     pub fn mk_bound_variable_kinds<
2674         I: InternAs<[ty::BoundVariableKind], &'tcx List<ty::BoundVariableKind>>,
2675     >(
2676         self,
2677         iter: I,
2678     ) -> I::Output {
2679         iter.intern_with(|xs| self.intern_bound_variable_kinds(xs))
2680     }
2681
2682     /// Walks upwards from `id` to find a node which might change lint levels with attributes.
2683     /// It stops at `bound` and just returns it if reached.
2684     pub fn maybe_lint_level_root_bounded(self, mut id: HirId, bound: HirId) -> HirId {
2685         let hir = self.hir();
2686         loop {
2687             if id == bound {
2688                 return bound;
2689             }
2690
2691             if hir.attrs(id).iter().any(|attr| Level::from_attr(attr).is_some()) {
2692                 return id;
2693             }
2694             let next = hir.get_parent_node(id);
2695             if next == id {
2696                 bug!("lint traversal reached the root of the crate");
2697             }
2698             id = next;
2699         }
2700     }
2701
2702     pub fn lint_level_at_node(
2703         self,
2704         lint: &'static Lint,
2705         mut id: hir::HirId,
2706     ) -> (Level, LintLevelSource) {
2707         let sets = self.lint_levels(());
2708         loop {
2709             if let Some(pair) = sets.level_and_source(lint, id, self.sess) {
2710                 return pair;
2711             }
2712             let next = self.hir().get_parent_node(id);
2713             if next == id {
2714                 bug!("lint traversal reached the root of the crate");
2715             }
2716             id = next;
2717         }
2718     }
2719
2720     pub fn struct_span_lint_hir(
2721         self,
2722         lint: &'static Lint,
2723         hir_id: HirId,
2724         span: impl Into<MultiSpan>,
2725         decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a, ()>),
2726     ) {
2727         let (level, src) = self.lint_level_at_node(lint, hir_id);
2728         struct_lint_level(self.sess, lint, level, src, Some(span.into()), decorate);
2729     }
2730
2731     pub fn struct_lint_node(
2732         self,
2733         lint: &'static Lint,
2734         id: HirId,
2735         decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a, ()>),
2736     ) {
2737         let (level, src) = self.lint_level_at_node(lint, id);
2738         struct_lint_level(self.sess, lint, level, src, None, decorate);
2739     }
2740
2741     pub fn in_scope_traits(self, id: HirId) -> Option<&'tcx [TraitCandidate]> {
2742         let map = self.in_scope_traits_map(id.owner)?;
2743         let candidates = map.get(&id.local_id)?;
2744         Some(&*candidates)
2745     }
2746
2747     pub fn named_region(self, id: HirId) -> Option<resolve_lifetime::Region> {
2748         debug!(?id, "named_region");
2749         self.named_region_map(id.owner).and_then(|map| map.get(&id.local_id).cloned())
2750     }
2751
2752     pub fn late_bound_vars(self, id: HirId) -> &'tcx List<ty::BoundVariableKind> {
2753         self.mk_bound_variable_kinds(
2754             self.late_bound_vars_map(id.owner)
2755                 .and_then(|map| map.get(&id.local_id).cloned())
2756                 .unwrap_or_else(|| {
2757                     bug!("No bound vars found for {:?} ({:?})", self.hir().node_to_string(id), id)
2758                 })
2759                 .iter(),
2760         )
2761     }
2762
2763     pub fn lifetime_scope(self, id: HirId) -> Option<&'tcx LifetimeScopeForPath> {
2764         self.lifetime_scope_map(id.owner).as_ref().and_then(|map| map.get(&id.local_id))
2765     }
2766
2767     /// Whether the `def_id` counts as const fn in the current crate, considering all active
2768     /// feature gates
2769     pub fn is_const_fn(self, def_id: DefId) -> bool {
2770         if self.is_const_fn_raw(def_id) {
2771             match self.lookup_const_stability(def_id) {
2772                 Some(stability) if stability.level.is_unstable() => {
2773                     // has a `rustc_const_unstable` attribute, check whether the user enabled the
2774                     // corresponding feature gate.
2775                     self.features()
2776                         .declared_lib_features
2777                         .iter()
2778                         .any(|&(sym, _)| sym == stability.feature)
2779                 }
2780                 // functions without const stability are either stable user written
2781                 // const fn or the user is using feature gates and we thus don't
2782                 // care what they do
2783                 _ => true,
2784             }
2785         } else {
2786             false
2787         }
2788     }
2789 }
2790
2791 impl<'tcx> TyCtxtAt<'tcx> {
2792     /// Constructs a `TyKind::Error` type and registers a `delay_span_bug` to ensure it gets used.
2793     #[track_caller]
2794     pub fn ty_error(self) -> Ty<'tcx> {
2795         self.tcx.ty_error_with_message(self.span, "TyKind::Error constructed but no error reported")
2796     }
2797
2798     /// Constructs a `TyKind::Error` type and registers a `delay_span_bug` with the given `msg to
2799     /// ensure it gets used.
2800     #[track_caller]
2801     pub fn ty_error_with_message(self, msg: &str) -> Ty<'tcx> {
2802         self.tcx.ty_error_with_message(self.span, msg)
2803     }
2804 }
2805
2806 pub trait InternAs<T: ?Sized, R> {
2807     type Output;
2808     fn intern_with<F>(self, f: F) -> Self::Output
2809     where
2810         F: FnOnce(&T) -> R;
2811 }
2812
2813 impl<I, T, R, E> InternAs<[T], R> for I
2814 where
2815     E: InternIteratorElement<T, R>,
2816     I: Iterator<Item = E>,
2817 {
2818     type Output = E::Output;
2819     fn intern_with<F>(self, f: F) -> Self::Output
2820     where
2821         F: FnOnce(&[T]) -> R,
2822     {
2823         E::intern_with(self, f)
2824     }
2825 }
2826
2827 pub trait InternIteratorElement<T, R>: Sized {
2828     type Output;
2829     fn intern_with<I: Iterator<Item = Self>, F: FnOnce(&[T]) -> R>(iter: I, f: F) -> Self::Output;
2830 }
2831
2832 impl<T, R> InternIteratorElement<T, R> for T {
2833     type Output = R;
2834     fn intern_with<I: Iterator<Item = Self>, F: FnOnce(&[T]) -> R>(
2835         mut iter: I,
2836         f: F,
2837     ) -> Self::Output {
2838         // This code is hot enough that it's worth specializing for the most
2839         // common length lists, to avoid the overhead of `SmallVec` creation.
2840         // Lengths 0, 1, and 2 typically account for ~95% of cases. If
2841         // `size_hint` is incorrect a panic will occur via an `unwrap` or an
2842         // `assert`.
2843         match iter.size_hint() {
2844             (0, Some(0)) => {
2845                 assert!(iter.next().is_none());
2846                 f(&[])
2847             }
2848             (1, Some(1)) => {
2849                 let t0 = iter.next().unwrap();
2850                 assert!(iter.next().is_none());
2851                 f(&[t0])
2852             }
2853             (2, Some(2)) => {
2854                 let t0 = iter.next().unwrap();
2855                 let t1 = iter.next().unwrap();
2856                 assert!(iter.next().is_none());
2857                 f(&[t0, t1])
2858             }
2859             _ => f(&iter.collect::<SmallVec<[_; 8]>>()),
2860         }
2861     }
2862 }
2863
2864 impl<'a, T, R> InternIteratorElement<T, R> for &'a T
2865 where
2866     T: Clone + 'a,
2867 {
2868     type Output = R;
2869     fn intern_with<I: Iterator<Item = Self>, F: FnOnce(&[T]) -> R>(iter: I, f: F) -> Self::Output {
2870         // This code isn't hot.
2871         f(&iter.cloned().collect::<SmallVec<[_; 8]>>())
2872     }
2873 }
2874
2875 impl<T, R, E> InternIteratorElement<T, R> for Result<T, E> {
2876     type Output = Result<R, E>;
2877     fn intern_with<I: Iterator<Item = Self>, F: FnOnce(&[T]) -> R>(
2878         mut iter: I,
2879         f: F,
2880     ) -> Self::Output {
2881         // This code is hot enough that it's worth specializing for the most
2882         // common length lists, to avoid the overhead of `SmallVec` creation.
2883         // Lengths 0, 1, and 2 typically account for ~95% of cases. If
2884         // `size_hint` is incorrect a panic will occur via an `unwrap` or an
2885         // `assert`, unless a failure happens first, in which case the result
2886         // will be an error anyway.
2887         Ok(match iter.size_hint() {
2888             (0, Some(0)) => {
2889                 assert!(iter.next().is_none());
2890                 f(&[])
2891             }
2892             (1, Some(1)) => {
2893                 let t0 = iter.next().unwrap()?;
2894                 assert!(iter.next().is_none());
2895                 f(&[t0])
2896             }
2897             (2, Some(2)) => {
2898                 let t0 = iter.next().unwrap()?;
2899                 let t1 = iter.next().unwrap()?;
2900                 assert!(iter.next().is_none());
2901                 f(&[t0, t1])
2902             }
2903             _ => f(&iter.collect::<Result<SmallVec<[_; 8]>, _>>()?),
2904         })
2905     }
2906 }
2907
2908 // We are comparing types with different invariant lifetimes, so `ptr::eq`
2909 // won't work for us.
2910 fn ptr_eq<T, U>(t: *const T, u: *const U) -> bool {
2911     t as *const () == u as *const ()
2912 }
2913
2914 pub fn provide(providers: &mut ty::query::Providers) {
2915     providers.resolutions = |tcx, ()| &tcx.untracked_resolutions;
2916     providers.module_reexports =
2917         |tcx, id| tcx.resolutions(()).reexport_map.get(&id).map(|v| &v[..]);
2918     providers.crate_name = |tcx, id| {
2919         assert_eq!(id, LOCAL_CRATE);
2920         tcx.crate_name
2921     };
2922     providers.maybe_unused_trait_import =
2923         |tcx, id| tcx.resolutions(()).maybe_unused_trait_imports.contains(&id);
2924     providers.maybe_unused_extern_crates =
2925         |tcx, ()| &tcx.resolutions(()).maybe_unused_extern_crates[..];
2926     providers.names_imported_by_glob_use = |tcx, id| {
2927         tcx.arena.alloc(tcx.resolutions(()).glob_map.get(&id).cloned().unwrap_or_default())
2928     };
2929
2930     providers.extern_mod_stmt_cnum =
2931         |tcx, id| tcx.resolutions(()).extern_crate_map.get(&id).cloned();
2932     providers.output_filenames = |tcx, ()| &tcx.output_filenames;
2933     providers.features_query = |tcx, ()| tcx.sess.features_untracked();
2934     providers.is_panic_runtime = |tcx, cnum| {
2935         assert_eq!(cnum, LOCAL_CRATE);
2936         tcx.sess.contains_name(tcx.hir().krate_attrs(), sym::panic_runtime)
2937     };
2938     providers.is_compiler_builtins = |tcx, cnum| {
2939         assert_eq!(cnum, LOCAL_CRATE);
2940         tcx.sess.contains_name(tcx.hir().krate_attrs(), sym::compiler_builtins)
2941     };
2942     providers.has_panic_handler = |tcx, cnum| {
2943         assert_eq!(cnum, LOCAL_CRATE);
2944         // We want to check if the panic handler was defined in this crate
2945         tcx.lang_items().panic_impl().map_or(false, |did| did.is_local())
2946     };
2947 }