]> git.lizzy.rs Git - rust.git/blob - src/librustc/ty/maps.rs
rip out everything but `MirPass`, move the logic into suites
[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::{DepGraph, DepNode, DepTrackingMap, DepTrackingMapConfig};
12 use hir::def_id::{CrateNum, DefId, LOCAL_CRATE};
13 use hir::def::Def;
14 use hir;
15 use middle::const_val;
16 use middle::privacy::AccessLevels;
17 use middle::region::RegionMaps;
18 use mir;
19 use mir::transform::{MirSuite, MirPassIndex};
20 use session::CompileResult;
21 use ty::{self, CrateInherentImpls, Ty, TyCtxt};
22 use ty::item_path;
23 use ty::steal::Steal;
24 use ty::subst::Substs;
25 use util::nodemap::{DefIdSet, NodeSet};
26
27 use rustc_data_structures::indexed_vec::IndexVec;
28 use std::cell::{RefCell, RefMut};
29 use std::option;
30 use std::fmt::Debug;
31 use std::hash::Hash;
32 use std::iter::{self, Once};
33 use std::mem;
34 use std::collections::BTreeMap;
35 use std::ops::Deref;
36 use std::rc::Rc;
37 use std::vec;
38 use syntax_pos::{Span, DUMMY_SP};
39 use syntax::symbol::Symbol;
40
41 pub trait Key: Clone + Hash + Eq + Debug {
42     fn map_crate(&self) -> CrateNum;
43     fn default_span(&self, tcx: TyCtxt) -> Span;
44 }
45
46 impl<'tcx> Key for ty::InstanceDef<'tcx> {
47     fn map_crate(&self) -> CrateNum {
48         LOCAL_CRATE
49     }
50
51     fn default_span(&self, tcx: TyCtxt) -> Span {
52         tcx.def_span(self.def_id())
53     }
54 }
55
56 impl<'tcx> Key for ty::Instance<'tcx> {
57     fn map_crate(&self) -> CrateNum {
58         LOCAL_CRATE
59     }
60
61     fn default_span(&self, tcx: TyCtxt) -> Span {
62         tcx.def_span(self.def_id())
63     }
64 }
65
66 impl Key for CrateNum {
67     fn map_crate(&self) -> CrateNum {
68         *self
69     }
70     fn default_span(&self, _: TyCtxt) -> Span {
71         DUMMY_SP
72     }
73 }
74
75 impl Key for DefId {
76     fn map_crate(&self) -> CrateNum {
77         self.krate
78     }
79     fn default_span(&self, tcx: TyCtxt) -> Span {
80         tcx.def_span(*self)
81     }
82 }
83
84 impl Key for (DefId, DefId) {
85     fn map_crate(&self) -> CrateNum {
86         self.0.krate
87     }
88     fn default_span(&self, tcx: TyCtxt) -> Span {
89         self.1.default_span(tcx)
90     }
91 }
92
93 impl Key for (CrateNum, DefId) {
94     fn map_crate(&self) -> CrateNum {
95         self.0
96     }
97     fn default_span(&self, tcx: TyCtxt) -> Span {
98         self.1.default_span(tcx)
99     }
100 }
101
102 impl<'tcx> Key for (DefId, &'tcx Substs<'tcx>) {
103     fn map_crate(&self) -> CrateNum {
104         self.0.krate
105     }
106     fn default_span(&self, tcx: TyCtxt) -> Span {
107         self.0.default_span(tcx)
108     }
109 }
110
111 impl Key for (MirSuite, DefId) {
112     fn map_crate(&self) -> CrateNum {
113         self.1.map_crate()
114     }
115     fn default_span(&self, tcx: TyCtxt) -> Span {
116         self.1.default_span(tcx)
117     }
118 }
119
120 impl Key for (MirSuite, MirPassIndex, DefId) {
121     fn map_crate(&self) -> CrateNum {
122         self.2.map_crate()
123     }
124     fn default_span(&self, tcx: TyCtxt) -> Span {
125         self.2.default_span(tcx)
126     }
127 }
128
129 trait Value<'tcx>: Sized {
130     fn from_cycle_error<'a>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Self;
131 }
132
133 impl<'tcx, T> Value<'tcx> for T {
134     default fn from_cycle_error<'a>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> T {
135         tcx.sess.abort_if_errors();
136         bug!("Value::from_cycle_error called without errors");
137     }
138 }
139
140 impl<'tcx, T: Default> Value<'tcx> for T {
141     default fn from_cycle_error<'a>(_: TyCtxt<'a, 'tcx, 'tcx>) -> T {
142         T::default()
143     }
144 }
145
146 impl<'tcx> Value<'tcx> for Ty<'tcx> {
147     fn from_cycle_error<'a>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Ty<'tcx> {
148         tcx.types.err
149     }
150 }
151
152 impl<'tcx> Value<'tcx> for ty::DtorckConstraint<'tcx> {
153     fn from_cycle_error<'a>(_: TyCtxt<'a, 'tcx, 'tcx>) -> Self {
154         Self::empty()
155     }
156 }
157
158 impl<'tcx> Value<'tcx> for ty::SymbolName {
159     fn from_cycle_error<'a>(_: TyCtxt<'a, 'tcx, 'tcx>) -> Self {
160         ty::SymbolName { name: Symbol::intern("<error>").as_str() }
161     }
162 }
163
164 trait IntoKeyValues<K: Key, V> {
165     type KeyValues: IntoIterator<Item=(K, V)>;
166
167     fn into_key_values(key: &K, value: Self) -> Self::KeyValues;
168 }
169
170 impl<K: Key, V> IntoKeyValues<K, V> for V {
171     type KeyValues = Once<(K, V)>;
172
173     fn into_key_values(key: &K, value: Self) -> Self::KeyValues {
174         iter::once((key.clone(), value))
175     }
176 }
177
178 /// Return type for a multi-query, which is a query which may (if it
179 /// chooses) return more than one (key, value) pair. Construct a
180 /// `Multi` using `Multi::from(...)`.
181 pub struct Multi<K: Key, V> {
182     single: Option<V>,
183     map: Vec<(K, V)>,
184 }
185
186 impl<K: Key, V> Multi<K, V> {
187     pub fn iter<'a>(&'a self, key: &'a K) -> impl Iterator<Item = (&'a K, &'a V)> + 'a {
188         self.single.iter()
189                    .map(move |v| (key, v))
190                    .chain(self.map.iter().map(move |&(ref k, ref v)| (k, v)))
191     }
192 }
193
194 /// Construct a `Multi` from a single value.
195 impl<K: Key, V> From<V> for Multi<K, V> {
196     fn from(value: V) -> Self {
197         Multi {
198             single: Some(value),
199             map: vec![],
200         }
201     }
202 }
203
204 /// Construct a `Multi` from a hashmap of (K, V) pairs.
205 impl<K: Key, V> From<Vec<(K, V)>> for Multi<K, V> {
206     fn from(value: Vec<(K, V)>) -> Self {
207         Multi {
208             single: None,
209             map: value
210         }
211     }
212 }
213
214 impl<K: Key, V> IntoKeyValues<K, V> for Multi<K, V> {
215     type KeyValues = iter::Chain<option::IntoIter<(K, V)>, vec::IntoIter<(K, V)>>;
216
217     fn into_key_values(key: &K, value: Self) -> Self::KeyValues {
218         value.single
219              .map(|v| (key.clone(), v))
220              .into_iter()
221              .chain(value.map)
222     }
223 }
224
225 pub struct CycleError<'a, 'tcx: 'a> {
226     span: Span,
227     cycle: RefMut<'a, [(Span, Query<'tcx>)]>,
228 }
229
230 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
231     pub fn report_cycle(self, CycleError { span, cycle }: CycleError) {
232         // Subtle: release the refcell lock before invoking `describe()`
233         // below by dropping `cycle`.
234         let stack = cycle.to_vec();
235         mem::drop(cycle);
236
237         assert!(!stack.is_empty());
238
239         // Disable naming impls with types in this path, since that
240         // sometimes cycles itself, leading to extra cycle errors.
241         // (And cycle errors around impls tend to occur during the
242         // collect/coherence phases anyhow.)
243         item_path::with_forced_impl_filename_line(|| {
244             let mut err =
245                 struct_span_err!(self.sess, span, E0391,
246                                  "unsupported cyclic reference between types/traits detected");
247             err.span_label(span, &format!("cyclic reference"));
248
249             err.span_note(stack[0].0, &format!("the cycle begins when {}...",
250                                                stack[0].1.describe(self)));
251
252             for &(span, ref query) in &stack[1..] {
253                 err.span_note(span, &format!("...which then requires {}...",
254                                              query.describe(self)));
255             }
256
257             err.note(&format!("...which then again requires {}, completing the cycle.",
258                               stack[0].1.describe(self)));
259
260             err.emit();
261         });
262     }
263
264     fn cycle_check<F, R>(self, span: Span, query: Query<'gcx>, compute: F)
265                          -> Result<R, CycleError<'a, 'gcx>>
266         where F: FnOnce() -> R
267     {
268         {
269             let mut stack = self.maps.query_stack.borrow_mut();
270             if let Some((i, _)) = stack.iter().enumerate().rev()
271                                        .find(|&(_, &(_, ref q))| *q == query) {
272                 return Err(CycleError {
273                     span: span,
274                     cycle: RefMut::map(stack, |stack| &mut stack[i..])
275                 });
276             }
277             stack.push((span, query));
278         }
279
280         let result = compute();
281
282         self.maps.query_stack.borrow_mut().pop();
283
284         Ok(result)
285     }
286 }
287
288 trait QueryDescription: DepTrackingMapConfig {
289     fn describe(tcx: TyCtxt, key: Self::Key) -> String;
290 }
291
292 impl<M: DepTrackingMapConfig<Key=DefId>> QueryDescription for M {
293     default fn describe(tcx: TyCtxt, def_id: DefId) -> String {
294         format!("processing `{}`", tcx.item_path_str(def_id))
295     }
296 }
297
298 impl<'tcx> QueryDescription for queries::super_predicates_of<'tcx> {
299     fn describe(tcx: TyCtxt, def_id: DefId) -> String {
300         format!("computing the supertraits of `{}`",
301                 tcx.item_path_str(def_id))
302     }
303 }
304
305 impl<'tcx> QueryDescription for queries::type_param_predicates<'tcx> {
306     fn describe(tcx: TyCtxt, (_, def_id): (DefId, DefId)) -> String {
307         let id = tcx.hir.as_local_node_id(def_id).unwrap();
308         format!("computing the bounds for type parameter `{}`",
309                 tcx.hir.ty_param_name(id))
310     }
311 }
312
313 impl<'tcx> QueryDescription for queries::coherent_trait<'tcx> {
314     fn describe(tcx: TyCtxt, (_, def_id): (CrateNum, DefId)) -> String {
315         format!("coherence checking all impls of trait `{}`",
316                 tcx.item_path_str(def_id))
317     }
318 }
319
320 impl<'tcx> QueryDescription for queries::crate_inherent_impls<'tcx> {
321     fn describe(_: TyCtxt, k: CrateNum) -> String {
322         format!("all inherent impls defined in crate `{:?}`", k)
323     }
324 }
325
326 impl<'tcx> QueryDescription for queries::crate_inherent_impls_overlap_check<'tcx> {
327     fn describe(_: TyCtxt, _: CrateNum) -> String {
328         format!("check for overlap between inherent impls defined in this crate")
329     }
330 }
331
332 impl<'tcx> QueryDescription for queries::mir_shims<'tcx> {
333     fn describe(tcx: TyCtxt, def: ty::InstanceDef<'tcx>) -> String {
334         format!("generating MIR shim for `{}`",
335                 tcx.item_path_str(def.def_id()))
336     }
337 }
338
339 impl<'tcx> QueryDescription for queries::privacy_access_levels<'tcx> {
340     fn describe(_: TyCtxt, _: CrateNum) -> String {
341         format!("privacy access levels")
342     }
343 }
344
345 impl<'tcx> QueryDescription for queries::typeck_item_bodies<'tcx> {
346     fn describe(_: TyCtxt, _: CrateNum) -> String {
347         format!("type-checking all item bodies")
348     }
349 }
350
351 impl<'tcx> QueryDescription for queries::reachable_set<'tcx> {
352     fn describe(_: TyCtxt, _: CrateNum) -> String {
353         format!("reachability")
354     }
355 }
356
357 impl<'tcx> QueryDescription for queries::const_eval<'tcx> {
358     fn describe(tcx: TyCtxt, (def_id, _): (DefId, &'tcx Substs<'tcx>)) -> String {
359         format!("const-evaluating `{}`", tcx.item_path_str(def_id))
360     }
361 }
362
363 impl<'tcx> QueryDescription for queries::mir_keys<'tcx> {
364     fn describe(_: TyCtxt, _: CrateNum) -> String {
365         format!("getting a list of all mir_keys")
366     }
367 }
368
369 impl<'tcx> QueryDescription for queries::symbol_name<'tcx> {
370     fn describe(_tcx: TyCtxt, instance: ty::Instance<'tcx>) -> String {
371         format!("computing the symbol for `{}`", instance)
372     }
373 }
374
375 impl<'tcx> QueryDescription for queries::describe_def<'tcx> {
376     fn describe(_: TyCtxt, _: DefId) -> String {
377         bug!("describe_def")
378     }
379 }
380
381 impl<'tcx> QueryDescription for queries::def_span<'tcx> {
382     fn describe(_: TyCtxt, _: DefId) -> String {
383         bug!("def_span")
384     }
385 }
386
387 impl<'tcx> QueryDescription for queries::item_body_nested_bodies<'tcx> {
388     fn describe(tcx: TyCtxt, def_id: DefId) -> String {
389         format!("nested item bodies of `{}`", tcx.item_path_str(def_id))
390     }
391 }
392
393 impl<'tcx> QueryDescription for queries::const_is_rvalue_promotable_to_static<'tcx> {
394     fn describe(tcx: TyCtxt, def_id: DefId) -> String {
395         format!("const checking if rvalue is promotable to static `{}`",
396             tcx.item_path_str(def_id))
397     }
398 }
399
400 impl<'tcx> QueryDescription for queries::is_item_mir_available<'tcx> {
401     fn describe(tcx: TyCtxt, def_id: DefId) -> String {
402         format!("checking if item is mir available: `{}`",
403             tcx.item_path_str(def_id))
404     }
405 }
406
407 impl<'tcx> QueryDescription for queries::mir_suite<'tcx> {
408     fn describe(_: TyCtxt, (suite, _): (MirSuite, DefId)) -> String {
409         format!("MIR suite #{}.*", suite.0)
410     }
411 }
412
413 impl<'tcx> QueryDescription for queries::mir_pass<'tcx> {
414     fn describe(_: TyCtxt, (suite, pass_num, _): (MirSuite, MirPassIndex, DefId)) -> String {
415         format!("MIR pass #{}.{}", suite.0, pass_num.0)
416     }
417 }
418
419 macro_rules! define_maps {
420     (<$tcx:tt>
421      $($(#[$attr:meta])*
422        [$($modifiers:tt)*] $name:ident: $node:ident($K:ty) -> $V:ty,)*) => {
423         define_map_struct! {
424             tcx: $tcx,
425             input: ($(([$($modifiers)*] [$($attr)*] [$name]))*)
426         }
427
428         impl<$tcx> Maps<$tcx> {
429             pub fn new(dep_graph: DepGraph,
430                        providers: IndexVec<CrateNum, Providers<$tcx>>)
431                        -> Self {
432                 Maps {
433                     providers,
434                     query_stack: RefCell::new(vec![]),
435                     $($name: RefCell::new(DepTrackingMap::new(dep_graph.clone()))),*
436                 }
437             }
438         }
439
440         #[allow(bad_style)]
441         #[derive(Copy, Clone, Debug, PartialEq, Eq)]
442         pub enum Query<$tcx> {
443             $($(#[$attr])* $name($K)),*
444         }
445
446         impl<$tcx> Query<$tcx> {
447             pub fn describe(&self, tcx: TyCtxt) -> String {
448                 match *self {
449                     $(Query::$name(key) => queries::$name::describe(tcx, key)),*
450                 }
451             }
452         }
453
454         pub mod queries {
455             use std::marker::PhantomData;
456
457             $(#[allow(bad_style)]
458             pub struct $name<$tcx> {
459                 data: PhantomData<&$tcx ()>
460             })*
461         }
462
463         $(impl<$tcx> DepTrackingMapConfig for queries::$name<$tcx> {
464             type Key = $K;
465             type Value = $V;
466
467             #[allow(unused)]
468             fn to_dep_node(key: &$K) -> DepNode<DefId> {
469                 use dep_graph::DepNode::*;
470
471                 $node(*key)
472             }
473         }
474         impl<'a, $tcx, 'lcx> queries::$name<$tcx> {
475             fn try_get_with<F, R>(tcx: TyCtxt<'a, $tcx, 'lcx>,
476                                   mut span: Span,
477                                   key: $K,
478                                   f: F)
479                                   -> Result<R, CycleError<'a, $tcx>>
480                 where F: FnOnce(&$V) -> R
481             {
482                 debug!("ty::queries::{}::try_get_with(key={:?}, span={:?})",
483                        stringify!($name),
484                        key,
485                        span);
486
487                 if let Some(result) = tcx.maps.$name.borrow().get(&key) {
488                     return Ok(f(result));
489                 }
490
491                 // FIXME(eddyb) Get more valid Span's on queries.
492                 // def_span guard is necesary to prevent a recursive loop,
493                 // default_span calls def_span query internally.
494                 if span == DUMMY_SP && stringify!($name) != "def_span" {
495                     span = key.default_span(tcx)
496                 }
497
498                 let _task = tcx.dep_graph.in_task(Self::to_dep_node(&key));
499
500                 let result = tcx.cycle_check(span, Query::$name(key), || {
501                     let provider = tcx.maps.providers[key.map_crate()].$name;
502                     provider(tcx.global_tcx(), key)
503                 })?;
504
505                 {
506                     let map = &mut *tcx.maps.$name.borrow_mut();
507                     for (k, v) in IntoKeyValues::<$K, $V>::into_key_values(&key, result) {
508                         map.insert(k, v);
509                     }
510                 }
511
512                 Ok(f(tcx.maps.$name.borrow().get(&key).expect("value just generated")))
513             }
514
515             pub fn try_get(tcx: TyCtxt<'a, $tcx, 'lcx>, span: Span, key: $K)
516                            -> Result<$V, CycleError<'a, $tcx>> {
517                 Self::try_get_with(tcx, span, key, Clone::clone)
518             }
519
520             pub fn force(tcx: TyCtxt<'a, $tcx, 'lcx>, span: Span, key: $K) {
521                 // FIXME(eddyb) Move away from using `DepTrackingMap`
522                 // so we don't have to explicitly ignore a false edge:
523                 // we can't observe a value dependency, only side-effects,
524                 // through `force`, and once everything has been updated,
525                 // perhaps only diagnostics, if those, will remain.
526                 let _ignore = tcx.dep_graph.in_ignore();
527                 match Self::try_get_with(tcx, span, key, |_| ()) {
528                     Ok(()) => {}
529                     Err(e) => tcx.report_cycle(e)
530                 }
531             }
532         })*
533
534         #[derive(Copy, Clone)]
535         pub struct TyCtxtAt<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
536             pub tcx: TyCtxt<'a, 'gcx, 'tcx>,
537             pub span: Span,
538         }
539
540         impl<'a, 'gcx, 'tcx> Deref for TyCtxtAt<'a, 'gcx, 'tcx> {
541             type Target = TyCtxt<'a, 'gcx, 'tcx>;
542             fn deref(&self) -> &Self::Target {
543                 &self.tcx
544             }
545         }
546
547         impl<'a, $tcx, 'lcx> TyCtxt<'a, $tcx, 'lcx> {
548             /// Return a transparent wrapper for `TyCtxt` which uses
549             /// `span` as the location of queries performed through it.
550             pub fn at(self, span: Span) -> TyCtxtAt<'a, $tcx, 'lcx> {
551                 TyCtxtAt {
552                     tcx: self,
553                     span
554                 }
555             }
556
557             $($(#[$attr])*
558             pub fn $name(self, key: $K) -> $V {
559                 self.at(DUMMY_SP).$name(key)
560             })*
561         }
562
563         impl<'a, $tcx, 'lcx> TyCtxtAt<'a, $tcx, 'lcx> {
564             $($(#[$attr])*
565             pub fn $name(self, key: $K) -> $V {
566                 queries::$name::try_get(self.tcx, self.span, key).unwrap_or_else(|e| {
567                     self.report_cycle(e);
568                     Value::from_cycle_error(self.global_tcx())
569                 })
570             })*
571         }
572
573         define_provider_struct! {
574             tcx: $tcx,
575             input: ($(([$($modifiers)*] [$name] [$K] [$V]))*),
576             output: ()
577         }
578
579         impl<$tcx> Copy for Providers<$tcx> {}
580         impl<$tcx> Clone for Providers<$tcx> {
581             fn clone(&self) -> Self { *self }
582         }
583     }
584 }
585
586 macro_rules! define_map_struct {
587     // Initial state
588     (tcx: $tcx:tt,
589      input: $input:tt) => {
590         define_map_struct! {
591             tcx: $tcx,
592             input: $input,
593             output: ()
594         }
595     };
596
597     // Final output
598     (tcx: $tcx:tt,
599      input: (),
600      output: ($($output:tt)*)) => {
601         pub struct Maps<$tcx> {
602             providers: IndexVec<CrateNum, Providers<$tcx>>,
603             query_stack: RefCell<Vec<(Span, Query<$tcx>)>>,
604             $($output)*
605         }
606     };
607
608     // Field recognized and ready to shift into the output
609     (tcx: $tcx:tt,
610      ready: ([$($pub:tt)*] [$($attr:tt)*] [$name:ident]),
611      input: $input:tt,
612      output: ($($output:tt)*)) => {
613         define_map_struct! {
614             tcx: $tcx,
615             input: $input,
616             output: ($($output)*
617                      $(#[$attr])* $($pub)* $name: RefCell<DepTrackingMap<queries::$name<$tcx>>>,)
618         }
619     };
620
621     // Detect things with the `pub` modifier
622     (tcx: $tcx:tt,
623      input: (([pub $($other_modifiers:tt)*] $attrs:tt $name:tt) $($input:tt)*),
624      output: $output:tt) => {
625         define_map_struct! {
626             tcx: $tcx,
627             ready: ([pub] $attrs $name),
628             input: ($($input)*),
629             output: $output
630         }
631     };
632
633     // No modifiers left? This is a private item.
634     (tcx: $tcx:tt,
635      input: (([] $attrs:tt $name:tt) $($input:tt)*),
636      output: $output:tt) => {
637         define_map_struct! {
638             tcx: $tcx,
639             ready: ([pub] $attrs $name),
640             input: ($($input)*),
641             output: $output
642         }
643     };
644
645     // Skip other modifiers
646     (tcx: $tcx:tt,
647      input: (([$other_modifier:tt $($modifiers:tt)*] $($fields:tt)*) $($input:tt)*),
648      output: $output:tt) => {
649         define_map_struct! {
650             tcx: $tcx,
651             input: (([$($modifiers)*] $($fields)*) $($input)*),
652             output: $output
653         }
654     };
655 }
656
657 macro_rules! define_provider_struct {
658     // Initial state:
659     (tcx: $tcx:tt, input: $input:tt) => {
660         define_provider_struct! {
661             tcx: $tcx,
662             input: $input,
663             output: ()
664         }
665     };
666
667     // Final state:
668     (tcx: $tcx:tt,
669      input: (),
670      output: ($(([$name:ident] [$K:ty] [$R:ty]))*)) => {
671         pub struct Providers<$tcx> {
672             $(pub $name: for<'a> fn(TyCtxt<'a, $tcx, $tcx>, $K) -> $R,)*
673         }
674
675         impl<$tcx> Default for Providers<$tcx> {
676             fn default() -> Self {
677                 $(fn $name<'a, $tcx>(_: TyCtxt<'a, $tcx, $tcx>, key: $K) -> $R {
678                     bug!("tcx.maps.{}({:?}) unsupported by its crate",
679                          stringify!($name), key);
680                 })*
681                 Providers { $($name),* }
682             }
683         }
684     };
685
686     // Something ready to shift:
687     (tcx: $tcx:tt,
688      ready: ($name:tt $K:tt $V:tt),
689      input: $input:tt,
690      output: ($($output:tt)*)) => {
691         define_provider_struct! {
692             tcx: $tcx,
693             input: $input,
694             output: ($($output)* ($name $K $V))
695         }
696     };
697
698     // The `multi` modifier indicates a **multiquery**, in which case
699     // the function returns a `Multi<K,V>` instead of just a value
700     // `V`.
701     (tcx: $tcx:tt,
702      input: (([multi $($other_modifiers:tt)*] $name:tt [$K:ty] [$V:ty]) $($input:tt)*),
703      output: $output:tt) => {
704         define_provider_struct! {
705             tcx: $tcx,
706             ready: ($name [$K] [Multi<$K,$V>]),
707             input: ($($input)*),
708             output: $output
709         }
710     };
711
712     // Regular queries produce a `V` only.
713     (tcx: $tcx:tt,
714      input: (([] $name:tt $K:tt $V:tt) $($input:tt)*),
715      output: $output:tt) => {
716         define_provider_struct! {
717             tcx: $tcx,
718             ready: ($name $K $V),
719             input: ($($input)*),
720             output: $output
721         }
722     };
723
724     // Skip modifiers other than `multi`.
725     (tcx: $tcx:tt,
726      input: (([$other_modifier:tt $($modifiers:tt)*] $($fields:tt)*) $($input:tt)*),
727      output: $output:tt) => {
728         define_provider_struct! {
729             tcx: $tcx,
730             input: (([$($modifiers)*] $($fields)*) $($input)*),
731             output: $output
732         }
733     };
734 }
735
736 // Each of these maps also corresponds to a method on a
737 // `Provider` trait for requesting a value of that type,
738 // and a method on `Maps` itself for doing that in a
739 // a way that memoizes and does dep-graph tracking,
740 // wrapping around the actual chain of providers that
741 // the driver creates (using several `rustc_*` crates).
742 define_maps! { <'tcx>
743     /// Records the type of every item.
744     [] type_of: ItemSignature(DefId) -> Ty<'tcx>,
745
746     /// Maps from the def-id of an item (trait/struct/enum/fn) to its
747     /// associated generics and predicates.
748     [] generics_of: ItemSignature(DefId) -> &'tcx ty::Generics,
749     [] predicates_of: ItemSignature(DefId) -> ty::GenericPredicates<'tcx>,
750
751     /// Maps from the def-id of a trait to the list of
752     /// super-predicates. This is a subset of the full list of
753     /// predicates. We store these in a separate map because we must
754     /// evaluate them even during type conversion, often before the
755     /// full predicates are available (note that supertraits have
756     /// additional acyclicity requirements).
757     [] super_predicates_of: ItemSignature(DefId) -> ty::GenericPredicates<'tcx>,
758
759     /// To avoid cycles within the predicates of a single item we compute
760     /// per-type-parameter predicates for resolving `T::AssocTy`.
761     [] type_param_predicates: TypeParamPredicates((DefId, DefId))
762         -> ty::GenericPredicates<'tcx>,
763
764     [] trait_def: ItemSignature(DefId) -> &'tcx ty::TraitDef,
765     [] adt_def: ItemSignature(DefId) -> &'tcx ty::AdtDef,
766     [] adt_destructor: AdtDestructor(DefId) -> Option<ty::Destructor>,
767     [] adt_sized_constraint: SizedConstraint(DefId) -> &'tcx [Ty<'tcx>],
768     [] adt_dtorck_constraint: DtorckConstraint(DefId) -> ty::DtorckConstraint<'tcx>,
769
770     /// True if this is a foreign item (i.e., linked via `extern { ... }`).
771     [] is_foreign_item: IsForeignItem(DefId) -> bool,
772
773     /// Maps from def-id of a type or region parameter to its
774     /// (inferred) variance.
775     [pub] variances_of: ItemSignature(DefId) -> Rc<Vec<ty::Variance>>,
776
777     /// Maps from an impl/trait def-id to a list of the def-ids of its items
778     [] associated_item_def_ids: AssociatedItemDefIds(DefId) -> Rc<Vec<DefId>>,
779
780     /// Maps from a trait item to the trait item "descriptor"
781     [] associated_item: AssociatedItems(DefId) -> ty::AssociatedItem,
782
783     [] impl_trait_ref: ItemSignature(DefId) -> Option<ty::TraitRef<'tcx>>,
784     [] impl_polarity: ItemSignature(DefId) -> hir::ImplPolarity,
785
786     /// Maps a DefId of a type to a list of its inherent impls.
787     /// Contains implementations of methods that are inherent to a type.
788     /// Methods in these implementations don't need to be exported.
789     [] inherent_impls: InherentImpls(DefId) -> Rc<Vec<DefId>>,
790
791     /// Set of all the def-ids in this crate that have MIR associated with
792     /// them. This includes all the body owners, but also things like struct
793     /// constructors.
794     [] mir_keys: mir_keys(CrateNum) -> Rc<DefIdSet>,
795
796     /// Maps DefId's that have an associated Mir to the result
797     /// of the MIR qualify_consts pass. The actual meaning of
798     /// the value isn't known except to the pass itself.
799     [] mir_const_qualif: Mir(DefId) -> u8,
800
801     /// Performs the initial MIR construction. You almost certainly do not
802     /// want to use this query, because its output is intended to be stolen
803     /// immediately by the MIR passes below. Consider `optimized_mir` instead.
804     ///
805     /// See the README for the `mir` module for details.
806     [] mir_build: Mir(DefId) -> &'tcx Steal<mir::Mir<'tcx>>,
807
808     /// Fetch the MIR for a given def-id after the given set of passes has ben
809     /// applied to it. This is mostly an "intermediate" query. Normally, you would
810     /// prefer to use `optimized_mir(def_id)`, which will fetch the MIR after all
811     /// optimizations and so forth.
812     ///
813     /// See the README for the `mir` module for details.
814     [] mir_suite: mir_suite((MirSuite, DefId)) -> &'tcx Steal<mir::Mir<'tcx>>,
815
816     /// Fetch the MIR for a given def-id after a given pass has been executed. This is
817     /// **only** intended to be used by the `mir_suite` provider -- if you are using it
818     /// manually, you're doing it wrong.
819     ///
820     /// See the README for the `mir` module for details.
821     [] mir_pass: mir_pass((MirSuite, MirPassIndex, DefId)) -> &'tcx Steal<mir::Mir<'tcx>>,
822
823     /// MIR after our optimization passes have run. This is MIR that is ready
824     /// for trans. This is also the only query that can fetch non-local MIR, at present.
825     [] optimized_mir: Mir(DefId) -> &'tcx mir::Mir<'tcx>,
826
827     /// Records the type of each closure. The def ID is the ID of the
828     /// expression defining the closure.
829     [] closure_kind: ItemSignature(DefId) -> ty::ClosureKind,
830
831     /// Records the type of each closure. The def ID is the ID of the
832     /// expression defining the closure.
833     [] closure_type: ItemSignature(DefId) -> ty::PolyFnSig<'tcx>,
834
835     /// Caches CoerceUnsized kinds for impls on custom types.
836     [] coerce_unsized_info: ItemSignature(DefId)
837         -> ty::adjustment::CoerceUnsizedInfo,
838
839     [] typeck_item_bodies: typeck_item_bodies_dep_node(CrateNum) -> CompileResult,
840
841     [] typeck_tables_of: TypeckTables(DefId) -> &'tcx ty::TypeckTables<'tcx>,
842
843     [] has_typeck_tables: TypeckTables(DefId) -> bool,
844
845     [] coherent_trait: coherent_trait_dep_node((CrateNum, DefId)) -> (),
846
847     [] borrowck: BorrowCheck(DefId) -> (),
848
849     /// Gets a complete map from all types to their inherent impls.
850     /// Not meant to be used directly outside of coherence.
851     /// (Defined only for LOCAL_CRATE)
852     [] crate_inherent_impls: crate_inherent_impls_dep_node(CrateNum) -> CrateInherentImpls,
853
854     /// Checks all types in the krate for overlap in their inherent impls. Reports errors.
855     /// Not meant to be used directly outside of coherence.
856     /// (Defined only for LOCAL_CRATE)
857     [] crate_inherent_impls_overlap_check: crate_inherent_impls_dep_node(CrateNum) -> (),
858
859     /// Results of evaluating const items or constants embedded in
860     /// other items (such as enum variant explicit discriminants).
861     [] const_eval: const_eval_dep_node((DefId, &'tcx Substs<'tcx>))
862         -> const_val::EvalResult<'tcx>,
863
864     /// Performs the privacy check and computes "access levels".
865     [] privacy_access_levels: PrivacyAccessLevels(CrateNum) -> Rc<AccessLevels>,
866
867     [] reachable_set: reachability_dep_node(CrateNum) -> Rc<NodeSet>,
868
869     /// Per-function `RegionMaps`. The `DefId` should be the owner-def-id for the fn body;
870     /// in the case of closures or "inline" expressions, this will be redirected to the enclosing
871     /// fn item.
872     [] region_maps: RegionMaps(DefId) -> Rc<RegionMaps<'tcx>>,
873
874     [] mir_shims: mir_shim_dep_node(ty::InstanceDef<'tcx>) -> &'tcx mir::Mir<'tcx>,
875
876     [] def_symbol_name: SymbolName(DefId) -> ty::SymbolName,
877     [] symbol_name: symbol_name_dep_node(ty::Instance<'tcx>) -> ty::SymbolName,
878
879     [] describe_def: DescribeDef(DefId) -> Option<Def>,
880     [] def_span: DefSpan(DefId) -> Span,
881
882     [] item_body_nested_bodies: metadata_dep_node(DefId) -> Rc<BTreeMap<hir::BodyId, hir::Body>>,
883     [] const_is_rvalue_promotable_to_static: metadata_dep_node(DefId) -> bool,
884     [] is_item_mir_available: metadata_dep_node(DefId) -> bool,
885 }
886
887 fn coherent_trait_dep_node((_, def_id): (CrateNum, DefId)) -> DepNode<DefId> {
888     DepNode::CoherenceCheckTrait(def_id)
889 }
890
891 fn crate_inherent_impls_dep_node(_: CrateNum) -> DepNode<DefId> {
892     DepNode::Coherence
893 }
894
895 fn reachability_dep_node(_: CrateNum) -> DepNode<DefId> {
896     DepNode::Reachability
897 }
898
899 fn metadata_dep_node(def_id: DefId) -> DepNode<DefId> {
900     DepNode::MetaData(def_id)
901 }
902
903 fn mir_shim_dep_node(instance: ty::InstanceDef) -> DepNode<DefId> {
904     instance.dep_node()
905 }
906
907 fn symbol_name_dep_node(instance: ty::Instance) -> DepNode<DefId> {
908     // symbol_name uses the substs only to traverse them to find the
909     // hash, and that does not create any new dep-nodes.
910     DepNode::SymbolName(instance.def.def_id())
911 }
912
913 fn typeck_item_bodies_dep_node(_: CrateNum) -> DepNode<DefId> {
914     DepNode::TypeckBodiesKrate
915 }
916
917 fn const_eval_dep_node((def_id, _): (DefId, &Substs)) -> DepNode<DefId> {
918     DepNode::ConstEval(def_id)
919 }
920
921 fn mir_keys(_: CrateNum) -> DepNode<DefId> {
922     DepNode::MirKeys
923 }
924
925 fn mir_suite((_suite, def_id): (MirSuite, DefId)) -> DepNode<DefId> {
926     DepNode::Mir(def_id)
927 }
928
929 fn mir_pass((_suite, _pass_num, def_id): (MirSuite, MirPassIndex, DefId)) -> DepNode<DefId> {
930     DepNode::Mir(def_id)
931 }