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