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