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