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