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