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