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