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