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