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