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