]> git.lizzy.rs Git - rust.git/blob - src/librustc/ty/maps.rs
incr.comp.: Cache DepNodes with corresponding query results.
[rust.git] / src / librustc / ty / maps.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 use dep_graph::{DepConstructor, DepNode, DepNodeIndex};
12 use hir::def_id::{CrateNum, CRATE_DEF_INDEX, DefId, LOCAL_CRATE};
13 use hir::def::Def;
14 use hir;
15 use middle::const_val;
16 use middle::cstore::{ExternCrate, LinkagePreference};
17 use middle::privacy::AccessLevels;
18 use middle::region::RegionMaps;
19 use mir;
20 use mir::transform::{MirSuite, MirPassIndex};
21 use session::CompileResult;
22 use traits::specialization_graph;
23 use ty::{self, CrateInherentImpls, Ty, TyCtxt};
24 use ty::layout::{Layout, LayoutError};
25 use ty::item_path;
26 use ty::steal::Steal;
27 use ty::subst::Substs;
28 use ty::fast_reject::SimplifiedType;
29 use util::nodemap::{DefIdSet, NodeSet};
30
31 use rustc_data_structures::indexed_vec::IndexVec;
32 use rustc_data_structures::fx::FxHashMap;
33 use std::cell::{RefCell, RefMut};
34 use std::fmt::Debug;
35 use std::hash::Hash;
36 use std::marker::PhantomData;
37 use std::mem;
38 use std::collections::BTreeMap;
39 use std::ops::Deref;
40 use std::rc::Rc;
41 use syntax_pos::{Span, DUMMY_SP};
42 use syntax::attr;
43 use syntax::ast;
44 use syntax::symbol::Symbol;
45
46 pub trait Key: Clone + Hash + Eq + Debug {
47     fn map_crate(&self) -> CrateNum;
48     fn default_span(&self, tcx: TyCtxt) -> Span;
49 }
50
51 impl<'tcx> Key for ty::InstanceDef<'tcx> {
52     fn map_crate(&self) -> CrateNum {
53         LOCAL_CRATE
54     }
55
56     fn default_span(&self, tcx: TyCtxt) -> Span {
57         tcx.def_span(self.def_id())
58     }
59 }
60
61 impl<'tcx> Key for ty::Instance<'tcx> {
62     fn map_crate(&self) -> CrateNum {
63         LOCAL_CRATE
64     }
65
66     fn default_span(&self, tcx: TyCtxt) -> Span {
67         tcx.def_span(self.def_id())
68     }
69 }
70
71 impl Key for CrateNum {
72     fn map_crate(&self) -> CrateNum {
73         *self
74     }
75     fn default_span(&self, _: TyCtxt) -> Span {
76         DUMMY_SP
77     }
78 }
79
80 impl Key for DefId {
81     fn map_crate(&self) -> CrateNum {
82         self.krate
83     }
84     fn default_span(&self, tcx: TyCtxt) -> Span {
85         tcx.def_span(*self)
86     }
87 }
88
89 impl Key for (DefId, DefId) {
90     fn map_crate(&self) -> CrateNum {
91         self.0.krate
92     }
93     fn default_span(&self, tcx: TyCtxt) -> Span {
94         self.1.default_span(tcx)
95     }
96 }
97
98 impl Key for (CrateNum, DefId) {
99     fn map_crate(&self) -> CrateNum {
100         self.0
101     }
102     fn default_span(&self, tcx: TyCtxt) -> Span {
103         self.1.default_span(tcx)
104     }
105 }
106
107 impl Key for (DefId, SimplifiedType) {
108     fn map_crate(&self) -> CrateNum {
109         self.0.krate
110     }
111     fn default_span(&self, tcx: TyCtxt) -> Span {
112         self.0.default_span(tcx)
113     }
114 }
115
116 impl<'tcx> Key for (DefId, &'tcx Substs<'tcx>) {
117     fn map_crate(&self) -> CrateNum {
118         self.0.krate
119     }
120     fn default_span(&self, tcx: TyCtxt) -> Span {
121         self.0.default_span(tcx)
122     }
123 }
124
125 impl Key for (MirSuite, DefId) {
126     fn map_crate(&self) -> CrateNum {
127         self.1.map_crate()
128     }
129     fn default_span(&self, tcx: TyCtxt) -> Span {
130         self.1.default_span(tcx)
131     }
132 }
133
134 impl Key for (MirSuite, MirPassIndex, DefId) {
135     fn map_crate(&self) -> CrateNum {
136         self.2.map_crate()
137     }
138     fn default_span(&self, tcx: TyCtxt) -> Span {
139         self.2.default_span(tcx)
140     }
141 }
142
143 impl<'tcx, T: Clone + Hash + Eq + Debug> Key for ty::ParamEnvAnd<'tcx, T> {
144     fn map_crate(&self) -> CrateNum {
145         LOCAL_CRATE
146     }
147     fn default_span(&self, _: TyCtxt) -> Span {
148         DUMMY_SP
149     }
150 }
151
152 trait Value<'tcx>: Sized {
153     fn from_cycle_error<'a>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Self;
154 }
155
156 impl<'tcx, T> Value<'tcx> for T {
157     default fn from_cycle_error<'a>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> T {
158         tcx.sess.abort_if_errors();
159         bug!("Value::from_cycle_error called without errors");
160     }
161 }
162
163 impl<'tcx, T: Default> Value<'tcx> for T {
164     default fn from_cycle_error<'a>(_: TyCtxt<'a, 'tcx, 'tcx>) -> T {
165         T::default()
166     }
167 }
168
169 impl<'tcx> Value<'tcx> for Ty<'tcx> {
170     fn from_cycle_error<'a>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Ty<'tcx> {
171         tcx.types.err
172     }
173 }
174
175 impl<'tcx> Value<'tcx> for ty::DtorckConstraint<'tcx> {
176     fn from_cycle_error<'a>(_: TyCtxt<'a, 'tcx, 'tcx>) -> Self {
177         Self::empty()
178     }
179 }
180
181 impl<'tcx> Value<'tcx> for ty::SymbolName {
182     fn from_cycle_error<'a>(_: TyCtxt<'a, 'tcx, 'tcx>) -> Self {
183         ty::SymbolName { name: Symbol::intern("<error>").as_str() }
184     }
185 }
186
187 struct QueryMap<D: QueryDescription> {
188     phantom: PhantomData<D>,
189     map: FxHashMap<D::Key, (D::Value, DepNodeIndex)>,
190 }
191
192 impl<M: QueryDescription> QueryMap<M> {
193     fn new() -> QueryMap<M> {
194         QueryMap {
195             phantom: PhantomData,
196             map: FxHashMap(),
197         }
198     }
199 }
200
201 pub struct CycleError<'a, 'tcx: 'a> {
202     span: Span,
203     cycle: RefMut<'a, [(Span, Query<'tcx>)]>,
204 }
205
206 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
207     pub fn report_cycle(self, CycleError { span, cycle }: CycleError) {
208         // Subtle: release the refcell lock before invoking `describe()`
209         // below by dropping `cycle`.
210         let stack = cycle.to_vec();
211         mem::drop(cycle);
212
213         assert!(!stack.is_empty());
214
215         // Disable naming impls with types in this path, since that
216         // sometimes cycles itself, leading to extra cycle errors.
217         // (And cycle errors around impls tend to occur during the
218         // collect/coherence phases anyhow.)
219         item_path::with_forced_impl_filename_line(|| {
220             let mut err =
221                 struct_span_err!(self.sess, span, E0391,
222                                  "unsupported cyclic reference between types/traits detected");
223             err.span_label(span, "cyclic reference");
224
225             err.span_note(stack[0].0, &format!("the cycle begins when {}...",
226                                                stack[0].1.describe(self)));
227
228             for &(span, ref query) in &stack[1..] {
229                 err.span_note(span, &format!("...which then requires {}...",
230                                              query.describe(self)));
231             }
232
233             err.note(&format!("...which then again requires {}, completing the cycle.",
234                               stack[0].1.describe(self)));
235
236             err.emit();
237         });
238     }
239
240     fn cycle_check<F, R>(self, span: Span, query: Query<'gcx>, compute: F)
241                          -> Result<R, CycleError<'a, 'gcx>>
242         where F: FnOnce() -> R
243     {
244         {
245             let mut stack = self.maps.query_stack.borrow_mut();
246             if let Some((i, _)) = stack.iter().enumerate().rev()
247                                        .find(|&(_, &(_, ref q))| *q == query) {
248                 return Err(CycleError {
249                     span,
250                     cycle: RefMut::map(stack, |stack| &mut stack[i..])
251                 });
252             }
253             stack.push((span, query));
254         }
255
256         let result = compute();
257
258         self.maps.query_stack.borrow_mut().pop();
259
260         Ok(result)
261     }
262 }
263
264 pub trait QueryConfig {
265     type Key: Eq + Hash + Clone;
266     type Value;
267 }
268
269 trait QueryDescription: QueryConfig {
270     fn describe(tcx: TyCtxt, key: Self::Key) -> String;
271 }
272
273 impl<M: QueryConfig<Key=DefId>> QueryDescription for M {
274     default fn describe(tcx: TyCtxt, def_id: DefId) -> String {
275         format!("processing `{}`", tcx.item_path_str(def_id))
276     }
277 }
278
279 impl<'tcx> QueryDescription for queries::is_copy_raw<'tcx> {
280     fn describe(_tcx: TyCtxt, env: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> String {
281         format!("computing whether `{}` is `Copy`", env.value)
282     }
283 }
284
285 impl<'tcx> QueryDescription for queries::is_sized_raw<'tcx> {
286     fn describe(_tcx: TyCtxt, env: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> String {
287         format!("computing whether `{}` is `Sized`", env.value)
288     }
289 }
290
291 impl<'tcx> QueryDescription for queries::is_freeze_raw<'tcx> {
292     fn describe(_tcx: TyCtxt, env: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> String {
293         format!("computing whether `{}` is freeze", env.value)
294     }
295 }
296
297 impl<'tcx> QueryDescription for queries::needs_drop_raw<'tcx> {
298     fn describe(_tcx: TyCtxt, env: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> String {
299         format!("computing whether `{}` needs drop", env.value)
300     }
301 }
302
303 impl<'tcx> QueryDescription for queries::layout_raw<'tcx> {
304     fn describe(_tcx: TyCtxt, env: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> String {
305         format!("computing layout of `{}`", env.value)
306     }
307 }
308
309 impl<'tcx> QueryDescription for queries::super_predicates_of<'tcx> {
310     fn describe(tcx: TyCtxt, def_id: DefId) -> String {
311         format!("computing the supertraits of `{}`",
312                 tcx.item_path_str(def_id))
313     }
314 }
315
316 impl<'tcx> QueryDescription for queries::type_param_predicates<'tcx> {
317     fn describe(tcx: TyCtxt, (_, def_id): (DefId, DefId)) -> String {
318         let id = tcx.hir.as_local_node_id(def_id).unwrap();
319         format!("computing the bounds for type parameter `{}`",
320                 tcx.hir.ty_param_name(id))
321     }
322 }
323
324 impl<'tcx> QueryDescription for queries::coherent_trait<'tcx> {
325     fn describe(tcx: TyCtxt, (_, def_id): (CrateNum, DefId)) -> String {
326         format!("coherence checking all impls of trait `{}`",
327                 tcx.item_path_str(def_id))
328     }
329 }
330
331 impl<'tcx> QueryDescription for queries::crate_inherent_impls<'tcx> {
332     fn describe(_: TyCtxt, k: CrateNum) -> String {
333         format!("all inherent impls defined in crate `{:?}`", k)
334     }
335 }
336
337 impl<'tcx> QueryDescription for queries::crate_inherent_impls_overlap_check<'tcx> {
338     fn describe(_: TyCtxt, _: CrateNum) -> String {
339         format!("check for overlap between inherent impls defined in this crate")
340     }
341 }
342
343 impl<'tcx> QueryDescription for queries::crate_variances<'tcx> {
344     fn describe(_tcx: TyCtxt, _: CrateNum) -> String {
345         format!("computing the variances for items in this crate")
346     }
347 }
348
349 impl<'tcx> QueryDescription for queries::mir_shims<'tcx> {
350     fn describe(tcx: TyCtxt, def: ty::InstanceDef<'tcx>) -> String {
351         format!("generating MIR shim for `{}`",
352                 tcx.item_path_str(def.def_id()))
353     }
354 }
355
356 impl<'tcx> QueryDescription for queries::privacy_access_levels<'tcx> {
357     fn describe(_: TyCtxt, _: CrateNum) -> String {
358         format!("privacy access levels")
359     }
360 }
361
362 impl<'tcx> QueryDescription for queries::typeck_item_bodies<'tcx> {
363     fn describe(_: TyCtxt, _: CrateNum) -> String {
364         format!("type-checking all item bodies")
365     }
366 }
367
368 impl<'tcx> QueryDescription for queries::reachable_set<'tcx> {
369     fn describe(_: TyCtxt, _: CrateNum) -> String {
370         format!("reachability")
371     }
372 }
373
374 impl<'tcx> QueryDescription for queries::const_eval<'tcx> {
375     fn describe(tcx: TyCtxt, (def_id, _): (DefId, &'tcx Substs<'tcx>)) -> String {
376         format!("const-evaluating `{}`", tcx.item_path_str(def_id))
377     }
378 }
379
380 impl<'tcx> QueryDescription for queries::mir_keys<'tcx> {
381     fn describe(_: TyCtxt, _: CrateNum) -> String {
382         format!("getting a list of all mir_keys")
383     }
384 }
385
386 impl<'tcx> QueryDescription for queries::symbol_name<'tcx> {
387     fn describe(_tcx: TyCtxt, instance: ty::Instance<'tcx>) -> String {
388         format!("computing the symbol for `{}`", instance)
389     }
390 }
391
392 impl<'tcx> QueryDescription for queries::describe_def<'tcx> {
393     fn describe(_: TyCtxt, _: DefId) -> String {
394         bug!("describe_def")
395     }
396 }
397
398 impl<'tcx> QueryDescription for queries::def_span<'tcx> {
399     fn describe(_: TyCtxt, _: DefId) -> String {
400         bug!("def_span")
401     }
402 }
403
404
405 impl<'tcx> QueryDescription for queries::stability<'tcx> {
406     fn describe(_: TyCtxt, _: DefId) -> String {
407         bug!("stability")
408     }
409 }
410
411 impl<'tcx> QueryDescription for queries::deprecation<'tcx> {
412     fn describe(_: TyCtxt, _: DefId) -> String {
413         bug!("deprecation")
414     }
415 }
416
417 impl<'tcx> QueryDescription for queries::item_attrs<'tcx> {
418     fn describe(_: TyCtxt, _: DefId) -> String {
419         bug!("item_attrs")
420     }
421 }
422
423 impl<'tcx> QueryDescription for queries::is_exported_symbol<'tcx> {
424     fn describe(_: TyCtxt, _: DefId) -> String {
425         bug!("is_exported_symbol")
426     }
427 }
428
429 impl<'tcx> QueryDescription for queries::fn_arg_names<'tcx> {
430     fn describe(_: TyCtxt, _: DefId) -> String {
431         bug!("fn_arg_names")
432     }
433 }
434
435 impl<'tcx> QueryDescription for queries::impl_parent<'tcx> {
436     fn describe(_: TyCtxt, _: DefId) -> String {
437         bug!("impl_parent")
438     }
439 }
440
441 impl<'tcx> QueryDescription for queries::trait_of_item<'tcx> {
442     fn describe(_: TyCtxt, _: DefId) -> String {
443         bug!("trait_of_item")
444     }
445 }
446
447 impl<'tcx> QueryDescription for queries::item_body_nested_bodies<'tcx> {
448     fn describe(tcx: TyCtxt, def_id: DefId) -> String {
449         format!("nested item bodies of `{}`", tcx.item_path_str(def_id))
450     }
451 }
452
453 impl<'tcx> QueryDescription for queries::const_is_rvalue_promotable_to_static<'tcx> {
454     fn describe(tcx: TyCtxt, def_id: DefId) -> String {
455         format!("const checking if rvalue is promotable to static `{}`",
456             tcx.item_path_str(def_id))
457     }
458 }
459
460 impl<'tcx> QueryDescription for queries::is_mir_available<'tcx> {
461     fn describe(tcx: TyCtxt, def_id: DefId) -> String {
462         format!("checking if item is mir available: `{}`",
463             tcx.item_path_str(def_id))
464     }
465 }
466
467 impl<'tcx> QueryDescription for queries::trait_impls_of<'tcx> {
468     fn describe(tcx: TyCtxt, def_id: DefId) -> String {
469         format!("trait impls of `{}`", tcx.item_path_str(def_id))
470     }
471 }
472
473 impl<'tcx> QueryDescription for queries::relevant_trait_impls_for<'tcx> {
474     fn describe(tcx: TyCtxt, (def_id, ty): (DefId, SimplifiedType)) -> String {
475         format!("relevant impls for: `({}, {:?})`", tcx.item_path_str(def_id), ty)
476     }
477 }
478
479 impl<'tcx> QueryDescription for queries::is_object_safe<'tcx> {
480     fn describe(tcx: TyCtxt, def_id: DefId) -> String {
481         format!("determine object safety of trait `{}`", tcx.item_path_str(def_id))
482     }
483 }
484
485 impl<'tcx> QueryDescription for queries::is_const_fn<'tcx> {
486     fn describe(tcx: TyCtxt, def_id: DefId) -> String {
487         format!("checking if item is const fn: `{}`", tcx.item_path_str(def_id))
488     }
489 }
490
491 impl<'tcx> QueryDescription for queries::dylib_dependency_formats<'tcx> {
492     fn describe(_: TyCtxt, _: DefId) -> String {
493         "dylib dependency formats of crate".to_string()
494     }
495 }
496
497 impl<'tcx> QueryDescription for queries::is_allocator<'tcx> {
498     fn describe(_: TyCtxt, _: DefId) -> String {
499         "checking if the crate is_allocator".to_string()
500     }
501 }
502
503 impl<'tcx> QueryDescription for queries::is_panic_runtime<'tcx> {
504     fn describe(_: TyCtxt, _: DefId) -> String {
505         "checking if the crate is_panic_runtime".to_string()
506     }
507 }
508
509 impl<'tcx> QueryDescription for queries::extern_crate<'tcx> {
510     fn describe(_: TyCtxt, _: DefId) -> String {
511         "getting crate's ExternCrateData".to_string()
512     }
513 }
514
515 macro_rules! define_maps {
516     (<$tcx:tt>
517      $($(#[$attr:meta])*
518        [$($modifiers:tt)*] $name:ident: $node:ident($K:ty) -> $V:ty,)*) => {
519         define_map_struct! {
520             tcx: $tcx,
521             input: ($(([$($modifiers)*] [$($attr)*] [$name]))*)
522         }
523
524         impl<$tcx> Maps<$tcx> {
525             pub fn new(providers: IndexVec<CrateNum, Providers<$tcx>>)
526                        -> Self {
527                 Maps {
528                     providers,
529                     query_stack: RefCell::new(vec![]),
530                     $($name: RefCell::new(QueryMap::new())),*
531                 }
532             }
533         }
534
535         #[allow(bad_style)]
536         #[derive(Copy, Clone, Debug, PartialEq, Eq)]
537         pub enum Query<$tcx> {
538             $($(#[$attr])* $name($K)),*
539         }
540
541         impl<$tcx> Query<$tcx> {
542             pub fn describe(&self, tcx: TyCtxt) -> String {
543                 match *self {
544                     $(Query::$name(key) => queries::$name::describe(tcx, key)),*
545                 }
546             }
547         }
548
549         pub mod queries {
550             use std::marker::PhantomData;
551
552             $(#[allow(bad_style)]
553             pub struct $name<$tcx> {
554                 data: PhantomData<&$tcx ()>
555             })*
556         }
557
558         $(impl<$tcx> QueryConfig for queries::$name<$tcx> {
559             type Key = $K;
560             type Value = $V;
561         }
562
563         impl<'a, $tcx, 'lcx> queries::$name<$tcx> {
564             #[allow(unused)]
565             fn to_dep_node(tcx: TyCtxt<'a, $tcx, 'lcx>, key: &$K) -> DepNode {
566                 use dep_graph::DepConstructor::*;
567
568                 DepNode::new(tcx, $node(*key))
569             }
570
571             fn try_get_with<F, R>(tcx: TyCtxt<'a, $tcx, 'lcx>,
572                                   mut span: Span,
573                                   key: $K,
574                                   f: F)
575                                   -> Result<R, CycleError<'a, $tcx>>
576                 where F: FnOnce(&$V) -> R
577             {
578                 debug!("ty::queries::{}::try_get_with(key={:?}, span={:?})",
579                        stringify!($name),
580                        key,
581                        span);
582
583                 if let Some(&(ref result, dep_node_index)) = tcx.maps.$name.borrow().map.get(&key) {
584                     tcx.dep_graph.read_index(dep_node_index);
585                     return Ok(f(result));
586                 }
587
588                 // FIXME(eddyb) Get more valid Span's on queries.
589                 // def_span guard is necesary to prevent a recursive loop,
590                 // default_span calls def_span query internally.
591                 if span == DUMMY_SP && stringify!($name) != "def_span" {
592                     span = key.default_span(tcx)
593                 }
594
595                 let (result, dep_node_index) = tcx.cycle_check(span, Query::$name(key), || {
596                     let dep_node = Self::to_dep_node(tcx, &key);
597
598                     if dep_node.kind.is_anon() {
599                         tcx.dep_graph.with_anon_task(dep_node.kind, || {
600                             let provider = tcx.maps.providers[key.map_crate()].$name;
601                             provider(tcx.global_tcx(), key)
602                         })
603                     } else {
604                         fn run_provider<'a, 'tcx, 'lcx>(tcx: TyCtxt<'a, 'tcx, 'lcx>,
605                                                         key: $K)
606                                                         -> $V {
607                             let provider = tcx.maps.providers[key.map_crate()].$name;
608                             provider(tcx.global_tcx(), key)
609                         }
610
611                         tcx.dep_graph.with_task(dep_node, tcx, key, run_provider)
612                     }
613                 })?;
614
615                 tcx.dep_graph.read_index(dep_node_index);
616
617                 Ok(f(&tcx.maps
618                          .$name
619                          .borrow_mut()
620                          .map
621                          .entry(key)
622                          .or_insert((result, dep_node_index))
623                          .0))
624             }
625
626             pub fn try_get(tcx: TyCtxt<'a, $tcx, 'lcx>, span: Span, key: $K)
627                            -> Result<$V, CycleError<'a, $tcx>> {
628                 Self::try_get_with(tcx, span, key, Clone::clone)
629             }
630
631             pub fn force(tcx: TyCtxt<'a, $tcx, 'lcx>, span: Span, key: $K) {
632                 // Ignore dependencies, since we not reading the computed value
633                 let _task = tcx.dep_graph.in_ignore();
634
635                 match Self::try_get_with(tcx, span, key, |_| ()) {
636                     Ok(()) => {}
637                     Err(e) => tcx.report_cycle(e)
638                 }
639             }
640         })*
641
642         #[derive(Copy, Clone)]
643         pub struct TyCtxtAt<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
644             pub tcx: TyCtxt<'a, 'gcx, 'tcx>,
645             pub span: Span,
646         }
647
648         impl<'a, 'gcx, 'tcx> Deref for TyCtxtAt<'a, 'gcx, 'tcx> {
649             type Target = TyCtxt<'a, 'gcx, 'tcx>;
650             fn deref(&self) -> &Self::Target {
651                 &self.tcx
652             }
653         }
654
655         impl<'a, $tcx, 'lcx> TyCtxt<'a, $tcx, 'lcx> {
656             /// Return a transparent wrapper for `TyCtxt` which uses
657             /// `span` as the location of queries performed through it.
658             pub fn at(self, span: Span) -> TyCtxtAt<'a, $tcx, 'lcx> {
659                 TyCtxtAt {
660                     tcx: self,
661                     span
662                 }
663             }
664
665             $($(#[$attr])*
666             pub fn $name(self, key: $K) -> $V {
667                 self.at(DUMMY_SP).$name(key)
668             })*
669         }
670
671         impl<'a, $tcx, 'lcx> TyCtxtAt<'a, $tcx, 'lcx> {
672             $($(#[$attr])*
673             pub fn $name(self, key: $K) -> $V {
674                 queries::$name::try_get(self.tcx, self.span, key).unwrap_or_else(|e| {
675                     self.report_cycle(e);
676                     Value::from_cycle_error(self.global_tcx())
677                 })
678             })*
679         }
680
681         define_provider_struct! {
682             tcx: $tcx,
683             input: ($(([$($modifiers)*] [$name] [$K] [$V]))*),
684             output: ()
685         }
686
687         impl<$tcx> Copy for Providers<$tcx> {}
688         impl<$tcx> Clone for Providers<$tcx> {
689             fn clone(&self) -> Self { *self }
690         }
691     }
692 }
693
694 macro_rules! define_map_struct {
695     // Initial state
696     (tcx: $tcx:tt,
697      input: $input:tt) => {
698         define_map_struct! {
699             tcx: $tcx,
700             input: $input,
701             output: ()
702         }
703     };
704
705     // Final output
706     (tcx: $tcx:tt,
707      input: (),
708      output: ($($output:tt)*)) => {
709         pub struct Maps<$tcx> {
710             providers: IndexVec<CrateNum, Providers<$tcx>>,
711             query_stack: RefCell<Vec<(Span, Query<$tcx>)>>,
712             $($output)*
713         }
714     };
715
716     // Field recognized and ready to shift into the output
717     (tcx: $tcx:tt,
718      ready: ([$($pub:tt)*] [$($attr:tt)*] [$name:ident]),
719      input: $input:tt,
720      output: ($($output:tt)*)) => {
721         define_map_struct! {
722             tcx: $tcx,
723             input: $input,
724             output: ($($output)*
725                      $(#[$attr])* $($pub)* $name: RefCell<QueryMap<queries::$name<$tcx>>>,)
726         }
727     };
728
729     // No modifiers left? This is a private item.
730     (tcx: $tcx:tt,
731      input: (([] $attrs:tt $name:tt) $($input:tt)*),
732      output: $output:tt) => {
733         define_map_struct! {
734             tcx: $tcx,
735             ready: ([] $attrs $name),
736             input: ($($input)*),
737             output: $output
738         }
739     };
740
741     // Skip other modifiers
742     (tcx: $tcx:tt,
743      input: (([$other_modifier:tt $($modifiers:tt)*] $($fields:tt)*) $($input:tt)*),
744      output: $output:tt) => {
745         define_map_struct! {
746             tcx: $tcx,
747             input: (([$($modifiers)*] $($fields)*) $($input)*),
748             output: $output
749         }
750     };
751 }
752
753 macro_rules! define_provider_struct {
754     // Initial state:
755     (tcx: $tcx:tt, input: $input:tt) => {
756         define_provider_struct! {
757             tcx: $tcx,
758             input: $input,
759             output: ()
760         }
761     };
762
763     // Final state:
764     (tcx: $tcx:tt,
765      input: (),
766      output: ($(([$name:ident] [$K:ty] [$R:ty]))*)) => {
767         pub struct Providers<$tcx> {
768             $(pub $name: for<'a> fn(TyCtxt<'a, $tcx, $tcx>, $K) -> $R,)*
769         }
770
771         impl<$tcx> Default for Providers<$tcx> {
772             fn default() -> Self {
773                 $(fn $name<'a, $tcx>(_: TyCtxt<'a, $tcx, $tcx>, key: $K) -> $R {
774                     bug!("tcx.maps.{}({:?}) unsupported by its crate",
775                          stringify!($name), key);
776                 })*
777                 Providers { $($name),* }
778             }
779         }
780     };
781
782     // Something ready to shift:
783     (tcx: $tcx:tt,
784      ready: ($name:tt $K:tt $V:tt),
785      input: $input:tt,
786      output: ($($output:tt)*)) => {
787         define_provider_struct! {
788             tcx: $tcx,
789             input: $input,
790             output: ($($output)* ($name $K $V))
791         }
792     };
793
794     // Regular queries produce a `V` only.
795     (tcx: $tcx:tt,
796      input: (([] $name:tt $K:tt $V:tt) $($input:tt)*),
797      output: $output:tt) => {
798         define_provider_struct! {
799             tcx: $tcx,
800             ready: ($name $K $V),
801             input: ($($input)*),
802             output: $output
803         }
804     };
805
806     // Skip modifiers.
807     (tcx: $tcx:tt,
808      input: (([$other_modifier:tt $($modifiers:tt)*] $($fields:tt)*) $($input:tt)*),
809      output: $output:tt) => {
810         define_provider_struct! {
811             tcx: $tcx,
812             input: (([$($modifiers)*] $($fields)*) $($input)*),
813             output: $output
814         }
815     };
816 }
817
818 // Each of these maps also corresponds to a method on a
819 // `Provider` trait for requesting a value of that type,
820 // and a method on `Maps` itself for doing that in a
821 // a way that memoizes and does dep-graph tracking,
822 // wrapping around the actual chain of providers that
823 // the driver creates (using several `rustc_*` crates).
824 define_maps! { <'tcx>
825     /// Records the type of every item.
826     [] type_of: TypeOfItem(DefId) -> Ty<'tcx>,
827
828     /// Maps from the def-id of an item (trait/struct/enum/fn) to its
829     /// associated generics and predicates.
830     [] generics_of: GenericsOfItem(DefId) -> &'tcx ty::Generics,
831     [] predicates_of: PredicatesOfItem(DefId) -> ty::GenericPredicates<'tcx>,
832
833     /// Maps from the def-id of a trait to the list of
834     /// super-predicates. This is a subset of the full list of
835     /// predicates. We store these in a separate map because we must
836     /// evaluate them even during type conversion, often before the
837     /// full predicates are available (note that supertraits have
838     /// additional acyclicity requirements).
839     [] super_predicates_of: SuperPredicatesOfItem(DefId) -> ty::GenericPredicates<'tcx>,
840
841     /// To avoid cycles within the predicates of a single item we compute
842     /// per-type-parameter predicates for resolving `T::AssocTy`.
843     [] type_param_predicates: type_param_predicates((DefId, DefId))
844         -> ty::GenericPredicates<'tcx>,
845
846     [] trait_def: TraitDefOfItem(DefId) -> &'tcx ty::TraitDef,
847     [] adt_def: AdtDefOfItem(DefId) -> &'tcx ty::AdtDef,
848     [] adt_destructor: AdtDestructor(DefId) -> Option<ty::Destructor>,
849     [] adt_sized_constraint: SizedConstraint(DefId) -> &'tcx [Ty<'tcx>],
850     [] adt_dtorck_constraint: DtorckConstraint(DefId) -> ty::DtorckConstraint<'tcx>,
851
852     /// True if this is a const fn
853     [] is_const_fn: IsConstFn(DefId) -> bool,
854
855     /// True if this is a foreign item (i.e., linked via `extern { ... }`).
856     [] is_foreign_item: IsForeignItem(DefId) -> bool,
857
858     /// True if this is a default impl (aka impl Foo for ..)
859     [] is_default_impl: IsDefaultImpl(DefId) -> bool,
860
861     /// Get a map with the variance of every item; use `item_variance`
862     /// instead.
863     [] crate_variances: crate_variances(CrateNum) -> Rc<ty::CrateVariancesMap>,
864
865     /// Maps from def-id of a type or region parameter to its
866     /// (inferred) variance.
867     [] variances_of: ItemVariances(DefId) -> Rc<Vec<ty::Variance>>,
868
869     /// Maps from an impl/trait def-id to a list of the def-ids of its items
870     [] associated_item_def_ids: AssociatedItemDefIds(DefId) -> Rc<Vec<DefId>>,
871
872     /// Maps from a trait item to the trait item "descriptor"
873     [] associated_item: AssociatedItems(DefId) -> ty::AssociatedItem,
874
875     [] impl_trait_ref: ImplTraitRef(DefId) -> Option<ty::TraitRef<'tcx>>,
876     [] impl_polarity: ImplPolarity(DefId) -> hir::ImplPolarity,
877
878     /// Maps a DefId of a type to a list of its inherent impls.
879     /// Contains implementations of methods that are inherent to a type.
880     /// Methods in these implementations don't need to be exported.
881     [] inherent_impls: InherentImpls(DefId) -> Rc<Vec<DefId>>,
882
883     /// Set of all the def-ids in this crate that have MIR associated with
884     /// them. This includes all the body owners, but also things like struct
885     /// constructors.
886     [] mir_keys: mir_keys(CrateNum) -> Rc<DefIdSet>,
887
888     /// Maps DefId's that have an associated Mir to the result
889     /// of the MIR qualify_consts pass. The actual meaning of
890     /// the value isn't known except to the pass itself.
891     [] mir_const_qualif: MirConstQualif(DefId) -> u8,
892
893     /// Fetch the MIR for a given def-id up till the point where it is
894     /// ready for const evaluation.
895     ///
896     /// See the README for the `mir` module for details.
897     [] mir_const: MirConst(DefId) -> &'tcx Steal<mir::Mir<'tcx>>,
898
899     [] mir_validated: MirValidated(DefId) -> &'tcx Steal<mir::Mir<'tcx>>,
900
901     /// MIR after our optimization passes have run. This is MIR that is ready
902     /// for trans. This is also the only query that can fetch non-local MIR, at present.
903     [] optimized_mir: MirOptimized(DefId) -> &'tcx mir::Mir<'tcx>,
904
905     /// Type of each closure. The def ID is the ID of the
906     /// expression defining the closure.
907     [] closure_kind: ClosureKind(DefId) -> ty::ClosureKind,
908
909     /// The signature of functions and closures.
910     [] fn_sig: FnSignature(DefId) -> ty::PolyFnSig<'tcx>,
911
912     /// Caches CoerceUnsized kinds for impls on custom types.
913     [] coerce_unsized_info: CoerceUnsizedInfo(DefId)
914         -> ty::adjustment::CoerceUnsizedInfo,
915
916     [] typeck_item_bodies: typeck_item_bodies_dep_node(CrateNum) -> CompileResult,
917
918     [] typeck_tables_of: TypeckTables(DefId) -> &'tcx ty::TypeckTables<'tcx>,
919
920     [] has_typeck_tables: HasTypeckTables(DefId) -> bool,
921
922     [] coherent_trait: coherent_trait_dep_node((CrateNum, DefId)) -> (),
923
924     [] borrowck: BorrowCheck(DefId) -> (),
925
926     /// Gets a complete map from all types to their inherent impls.
927     /// Not meant to be used directly outside of coherence.
928     /// (Defined only for LOCAL_CRATE)
929     [] crate_inherent_impls: crate_inherent_impls_dep_node(CrateNum) -> CrateInherentImpls,
930
931     /// Checks all types in the krate for overlap in their inherent impls. Reports errors.
932     /// Not meant to be used directly outside of coherence.
933     /// (Defined only for LOCAL_CRATE)
934     [] crate_inherent_impls_overlap_check: crate_inherent_impls_dep_node(CrateNum) -> (),
935
936     /// Results of evaluating const items or constants embedded in
937     /// other items (such as enum variant explicit discriminants).
938     [] const_eval: const_eval_dep_node((DefId, &'tcx Substs<'tcx>))
939         -> const_val::EvalResult<'tcx>,
940
941     /// Performs the privacy check and computes "access levels".
942     [] privacy_access_levels: PrivacyAccessLevels(CrateNum) -> Rc<AccessLevels>,
943
944     [] reachable_set: reachability_dep_node(CrateNum) -> Rc<NodeSet>,
945
946     /// Per-function `RegionMaps`. The `DefId` should be the owner-def-id for the fn body;
947     /// in the case of closures or "inline" expressions, this will be redirected to the enclosing
948     /// fn item.
949     [] region_maps: RegionMaps(DefId) -> Rc<RegionMaps>,
950
951     [] mir_shims: mir_shim_dep_node(ty::InstanceDef<'tcx>) -> &'tcx mir::Mir<'tcx>,
952
953     [] def_symbol_name: SymbolName(DefId) -> ty::SymbolName,
954     [] symbol_name: symbol_name_dep_node(ty::Instance<'tcx>) -> ty::SymbolName,
955
956     [] describe_def: DescribeDef(DefId) -> Option<Def>,
957     [] def_span: DefSpan(DefId) -> Span,
958     [] stability: Stability(DefId) -> Option<attr::Stability>,
959     [] deprecation: Deprecation(DefId) -> Option<attr::Deprecation>,
960     [] item_attrs: ItemAttrs(DefId) -> Rc<[ast::Attribute]>,
961     [] fn_arg_names: FnArgNames(DefId) -> Vec<ast::Name>,
962     [] impl_parent: ImplParent(DefId) -> Option<DefId>,
963     [] trait_of_item: TraitOfItem(DefId) -> Option<DefId>,
964     [] is_exported_symbol: IsExportedSymbol(DefId) -> bool,
965     [] item_body_nested_bodies: ItemBodyNestedBodies(DefId) -> Rc<BTreeMap<hir::BodyId, hir::Body>>,
966     [] const_is_rvalue_promotable_to_static: ConstIsRvaluePromotableToStatic(DefId) -> bool,
967     [] is_mir_available: IsMirAvailable(DefId) -> bool,
968
969     [] trait_impls_of: TraitImpls(DefId) -> ty::trait_def::TraitImpls,
970     // Note that TraitDef::for_each_relevant_impl() will do type simplication for you.
971     [] relevant_trait_impls_for: relevant_trait_impls_for((DefId, SimplifiedType))
972         -> ty::trait_def::TraitImpls,
973     [] specialization_graph_of: SpecializationGraph(DefId) -> Rc<specialization_graph::Graph>,
974     [] is_object_safe: ObjectSafety(DefId) -> bool,
975
976     // Get the ParameterEnvironment for a given item; this environment
977     // will be in "user-facing" mode, meaning that it is suitabe for
978     // type-checking etc, and it does not normalize specializable
979     // associated types. This is almost always what you want,
980     // unless you are doing MIR optimizations, in which case you
981     // might want to use `reveal_all()` method to change modes.
982     [] param_env: ParamEnv(DefId) -> ty::ParamEnv<'tcx>,
983
984     // Trait selection queries. These are best used by invoking `ty.moves_by_default()`,
985     // `ty.is_copy()`, etc, since that will prune the environment where possible.
986     [] is_copy_raw: is_copy_dep_node(ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> bool,
987     [] is_sized_raw: is_sized_dep_node(ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> bool,
988     [] is_freeze_raw: is_freeze_dep_node(ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> bool,
989     [] needs_drop_raw: needs_drop_dep_node(ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> bool,
990     [] layout_raw: layout_dep_node(ty::ParamEnvAnd<'tcx, Ty<'tcx>>)
991                                   -> Result<&'tcx Layout, LayoutError<'tcx>>,
992
993     [] dylib_dependency_formats: DylibDepFormats(DefId)
994                                     -> Rc<Vec<(CrateNum, LinkagePreference)>>,
995
996     [] is_allocator: IsAllocator(DefId) -> bool,
997     [] is_panic_runtime: IsPanicRuntime(DefId) -> bool,
998
999     [] extern_crate: ExternCrate(DefId) -> Rc<Option<ExternCrate>>,
1000 }
1001
1002 fn type_param_predicates<'tcx>((item_id, param_id): (DefId, DefId)) -> DepConstructor<'tcx> {
1003     DepConstructor::TypeParamPredicates {
1004         item_id,
1005         param_id
1006     }
1007 }
1008
1009 fn coherent_trait_dep_node<'tcx>((_, def_id): (CrateNum, DefId)) -> DepConstructor<'tcx> {
1010     DepConstructor::CoherenceCheckTrait(def_id)
1011 }
1012
1013 fn crate_inherent_impls_dep_node<'tcx>(_: CrateNum) -> DepConstructor<'tcx> {
1014     DepConstructor::Coherence
1015 }
1016
1017 fn reachability_dep_node<'tcx>(_: CrateNum) -> DepConstructor<'tcx> {
1018     DepConstructor::Reachability
1019 }
1020
1021 fn mir_shim_dep_node<'tcx>(instance_def: ty::InstanceDef<'tcx>) -> DepConstructor<'tcx> {
1022     DepConstructor::MirShim {
1023         instance_def
1024     }
1025 }
1026
1027 fn symbol_name_dep_node<'tcx>(instance: ty::Instance<'tcx>) -> DepConstructor<'tcx> {
1028     DepConstructor::InstanceSymbolName { instance }
1029 }
1030
1031 fn typeck_item_bodies_dep_node<'tcx>(_: CrateNum) -> DepConstructor<'tcx> {
1032     DepConstructor::TypeckBodiesKrate
1033 }
1034
1035 fn const_eval_dep_node<'tcx>((def_id, substs): (DefId, &'tcx Substs<'tcx>))
1036                              -> DepConstructor<'tcx> {
1037     DepConstructor::ConstEval { def_id, substs }
1038 }
1039
1040 fn mir_keys<'tcx>(_: CrateNum) -> DepConstructor<'tcx> {
1041     DepConstructor::MirKeys
1042 }
1043
1044 fn crate_variances<'tcx>(_: CrateNum) -> DepConstructor<'tcx> {
1045     DepConstructor::CrateVariances
1046 }
1047
1048 fn relevant_trait_impls_for<'tcx>((def_id, t): (DefId, SimplifiedType)) -> DepConstructor<'tcx> {
1049     DepConstructor::RelevantTraitImpls(def_id, t)
1050 }
1051
1052 fn is_copy_dep_node<'tcx>(key: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> DepConstructor<'tcx> {
1053     let def_id = ty::item_path::characteristic_def_id_of_type(key.value)
1054         .unwrap_or(DefId::local(CRATE_DEF_INDEX));
1055     DepConstructor::IsCopy(def_id)
1056 }
1057
1058 fn is_sized_dep_node<'tcx>(key: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> DepConstructor<'tcx> {
1059     let def_id = ty::item_path::characteristic_def_id_of_type(key.value)
1060         .unwrap_or(DefId::local(CRATE_DEF_INDEX));
1061     DepConstructor::IsSized(def_id)
1062 }
1063
1064 fn is_freeze_dep_node<'tcx>(key: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> DepConstructor<'tcx> {
1065     let def_id = ty::item_path::characteristic_def_id_of_type(key.value)
1066         .unwrap_or(DefId::local(CRATE_DEF_INDEX));
1067     DepConstructor::IsFreeze(def_id)
1068 }
1069
1070 fn needs_drop_dep_node<'tcx>(key: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> DepConstructor<'tcx> {
1071     let def_id = ty::item_path::characteristic_def_id_of_type(key.value)
1072         .unwrap_or(DefId::local(CRATE_DEF_INDEX));
1073     DepConstructor::NeedsDrop(def_id)
1074 }
1075
1076 fn layout_dep_node<'tcx>(key: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> DepConstructor<'tcx> {
1077     let def_id = ty::item_path::characteristic_def_id_of_type(key.value)
1078         .unwrap_or(DefId::local(CRATE_DEF_INDEX));
1079     DepConstructor::Layout(def_id)
1080 }