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