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