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