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