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