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.
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.
11 use dep_graph::{DepConstructor, DepNode, DepNodeIndex};
12 use errors::{Diagnostic, DiagnosticBuilder};
13 use hir::def_id::{CrateNum, DefId, LOCAL_CRATE};
14 use hir::def::{Def, Export};
15 use hir::{self, TraitCandidate, HirId};
17 use middle::const_val;
18 use middle::cstore::{ExternCrate, LinkagePreference};
19 use middle::privacy::AccessLevels;
22 use mir::transform::{MirSuite, MirPassIndex};
23 use session::CompileResult;
24 use traits::specialization_graph;
25 use ty::{self, CrateInherentImpls, Ty, TyCtxt};
26 use ty::layout::{Layout, LayoutError};
29 use ty::subst::Substs;
30 use ty::fast_reject::SimplifiedType;
31 use util::nodemap::{DefIdSet, NodeSet};
32 use util::common::{profq_msg, ProfileQueriesMsg};
34 use rustc_data_structures::indexed_set::IdxSetBuf;
35 use rustc_data_structures::indexed_vec::IndexVec;
36 use rustc_data_structures::fx::FxHashMap;
37 use std::cell::{RefCell, RefMut, Cell};
40 use std::marker::PhantomData;
42 use std::collections::BTreeMap;
45 use syntax_pos::{Span, DUMMY_SP};
48 use syntax::symbol::Symbol;
50 pub trait Key: Clone + Hash + Eq + Debug {
51 fn map_crate(&self) -> CrateNum;
52 fn default_span(&self, tcx: TyCtxt) -> Span;
55 impl<'tcx> Key for ty::InstanceDef<'tcx> {
56 fn map_crate(&self) -> CrateNum {
60 fn default_span(&self, tcx: TyCtxt) -> Span {
61 tcx.def_span(self.def_id())
65 impl<'tcx> Key for ty::Instance<'tcx> {
66 fn map_crate(&self) -> CrateNum {
70 fn default_span(&self, tcx: TyCtxt) -> Span {
71 tcx.def_span(self.def_id())
75 impl Key for CrateNum {
76 fn map_crate(&self) -> CrateNum {
79 fn default_span(&self, _: TyCtxt) -> Span {
85 fn map_crate(&self) -> CrateNum {
88 fn default_span(&self, _tcx: TyCtxt) -> Span {
94 fn map_crate(&self) -> CrateNum {
97 fn default_span(&self, tcx: TyCtxt) -> Span {
102 impl Key for (DefId, DefId) {
103 fn map_crate(&self) -> CrateNum {
106 fn default_span(&self, tcx: TyCtxt) -> Span {
107 self.1.default_span(tcx)
111 impl Key for (CrateNum, DefId) {
112 fn map_crate(&self) -> CrateNum {
115 fn default_span(&self, tcx: TyCtxt) -> Span {
116 self.1.default_span(tcx)
120 impl Key for (DefId, SimplifiedType) {
121 fn map_crate(&self) -> CrateNum {
124 fn default_span(&self, tcx: TyCtxt) -> Span {
125 self.0.default_span(tcx)
129 impl<'tcx> Key for (DefId, &'tcx Substs<'tcx>) {
130 fn map_crate(&self) -> CrateNum {
133 fn default_span(&self, tcx: TyCtxt) -> Span {
134 self.0.default_span(tcx)
138 impl Key for (MirSuite, DefId) {
139 fn map_crate(&self) -> CrateNum {
142 fn default_span(&self, tcx: TyCtxt) -> Span {
143 self.1.default_span(tcx)
147 impl Key for (MirSuite, MirPassIndex, DefId) {
148 fn map_crate(&self) -> CrateNum {
151 fn default_span(&self, tcx: TyCtxt) -> Span {
152 self.2.default_span(tcx)
156 impl<'tcx, T: Clone + Hash + Eq + Debug> Key for ty::ParamEnvAnd<'tcx, T> {
157 fn map_crate(&self) -> CrateNum {
160 fn default_span(&self, _: TyCtxt) -> Span {
165 trait Value<'tcx>: Sized {
166 fn from_cycle_error<'a>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Self;
169 impl<'tcx, T> Value<'tcx> for T {
170 default fn from_cycle_error<'a>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> T {
171 tcx.sess.abort_if_errors();
172 bug!("Value::from_cycle_error called without errors");
176 impl<'tcx, T: Default> Value<'tcx> for T {
177 default fn from_cycle_error<'a>(_: TyCtxt<'a, 'tcx, 'tcx>) -> T {
182 impl<'tcx> Value<'tcx> for Ty<'tcx> {
183 fn from_cycle_error<'a>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Ty<'tcx> {
188 impl<'tcx> Value<'tcx> for ty::DtorckConstraint<'tcx> {
189 fn from_cycle_error<'a>(_: TyCtxt<'a, 'tcx, 'tcx>) -> Self {
194 impl<'tcx> Value<'tcx> for ty::SymbolName {
195 fn from_cycle_error<'a>(_: TyCtxt<'a, 'tcx, 'tcx>) -> Self {
196 ty::SymbolName { name: Symbol::intern("<error>").as_str() }
200 struct QueryMap<D: QueryDescription> {
201 phantom: PhantomData<D>,
202 map: FxHashMap<D::Key, QueryValue<D::Value>>,
205 struct QueryValue<T> {
208 diagnostics: Option<Box<QueryDiagnostics>>,
211 struct QueryDiagnostics {
212 diagnostics: Vec<Diagnostic>,
213 emitted_diagnostics: Cell<bool>,
216 impl<M: QueryDescription> QueryMap<M> {
217 fn new() -> QueryMap<M> {
219 phantom: PhantomData,
225 struct CycleError<'a, 'tcx: 'a> {
227 cycle: RefMut<'a, [(Span, Query<'tcx>)]>,
230 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
231 fn report_cycle(self, CycleError { span, cycle }: CycleError)
232 -> DiagnosticBuilder<'a>
234 // Subtle: release the refcell lock before invoking `describe()`
235 // below by dropping `cycle`.
236 let stack = cycle.to_vec();
239 assert!(!stack.is_empty());
241 // Disable naming impls with types in this path, since that
242 // sometimes cycles itself, leading to extra cycle errors.
243 // (And cycle errors around impls tend to occur during the
244 // collect/coherence phases anyhow.)
245 item_path::with_forced_impl_filename_line(|| {
247 struct_span_err!(self.sess, span, E0391,
248 "unsupported cyclic reference between types/traits detected");
249 err.span_label(span, "cyclic reference");
251 err.span_note(stack[0].0, &format!("the cycle begins when {}...",
252 stack[0].1.describe(self)));
254 for &(span, ref query) in &stack[1..] {
255 err.span_note(span, &format!("...which then requires {}...",
256 query.describe(self)));
259 err.note(&format!("...which then again requires {}, completing the cycle.",
260 stack[0].1.describe(self)));
266 fn cycle_check<F, R>(self, span: Span, query: Query<'gcx>, compute: F)
267 -> Result<R, CycleError<'a, 'gcx>>
268 where F: FnOnce() -> R
271 let mut stack = self.maps.query_stack.borrow_mut();
272 if let Some((i, _)) = stack.iter().enumerate().rev()
273 .find(|&(_, &(_, ref q))| *q == query) {
274 return Err(CycleError {
276 cycle: RefMut::map(stack, |stack| &mut stack[i..])
279 stack.push((span, query));
282 let result = compute();
284 self.maps.query_stack.borrow_mut().pop();
290 pub trait QueryConfig {
291 type Key: Eq + Hash + Clone;
295 trait QueryDescription: QueryConfig {
296 fn describe(tcx: TyCtxt, key: Self::Key) -> String;
299 impl<M: QueryConfig<Key=DefId>> QueryDescription for M {
300 default fn describe(tcx: TyCtxt, def_id: DefId) -> String {
301 format!("processing `{}`", tcx.item_path_str(def_id))
305 impl<'tcx> QueryDescription for queries::is_copy_raw<'tcx> {
306 fn describe(_tcx: TyCtxt, env: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> String {
307 format!("computing whether `{}` is `Copy`", env.value)
311 impl<'tcx> QueryDescription for queries::is_sized_raw<'tcx> {
312 fn describe(_tcx: TyCtxt, env: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> String {
313 format!("computing whether `{}` is `Sized`", env.value)
317 impl<'tcx> QueryDescription for queries::is_freeze_raw<'tcx> {
318 fn describe(_tcx: TyCtxt, env: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> String {
319 format!("computing whether `{}` is freeze", env.value)
323 impl<'tcx> QueryDescription for queries::needs_drop_raw<'tcx> {
324 fn describe(_tcx: TyCtxt, env: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> String {
325 format!("computing whether `{}` needs drop", env.value)
329 impl<'tcx> QueryDescription for queries::layout_raw<'tcx> {
330 fn describe(_tcx: TyCtxt, env: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> String {
331 format!("computing layout of `{}`", env.value)
335 impl<'tcx> QueryDescription for queries::super_predicates_of<'tcx> {
336 fn describe(tcx: TyCtxt, def_id: DefId) -> String {
337 format!("computing the supertraits of `{}`",
338 tcx.item_path_str(def_id))
342 impl<'tcx> QueryDescription for queries::type_param_predicates<'tcx> {
343 fn describe(tcx: TyCtxt, (_, def_id): (DefId, DefId)) -> String {
344 let id = tcx.hir.as_local_node_id(def_id).unwrap();
345 format!("computing the bounds for type parameter `{}`",
346 tcx.hir.ty_param_name(id))
350 impl<'tcx> QueryDescription for queries::coherent_trait<'tcx> {
351 fn describe(tcx: TyCtxt, (_, def_id): (CrateNum, DefId)) -> String {
352 format!("coherence checking all impls of trait `{}`",
353 tcx.item_path_str(def_id))
357 impl<'tcx> QueryDescription for queries::crate_inherent_impls<'tcx> {
358 fn describe(_: TyCtxt, k: CrateNum) -> String {
359 format!("all inherent impls defined in crate `{:?}`", k)
363 impl<'tcx> QueryDescription for queries::crate_inherent_impls_overlap_check<'tcx> {
364 fn describe(_: TyCtxt, _: CrateNum) -> String {
365 format!("check for overlap between inherent impls defined in this crate")
369 impl<'tcx> QueryDescription for queries::crate_variances<'tcx> {
370 fn describe(_tcx: TyCtxt, _: CrateNum) -> String {
371 format!("computing the variances for items in this crate")
375 impl<'tcx> QueryDescription for queries::mir_shims<'tcx> {
376 fn describe(tcx: TyCtxt, def: ty::InstanceDef<'tcx>) -> String {
377 format!("generating MIR shim for `{}`",
378 tcx.item_path_str(def.def_id()))
382 impl<'tcx> QueryDescription for queries::privacy_access_levels<'tcx> {
383 fn describe(_: TyCtxt, _: CrateNum) -> String {
384 format!("privacy access levels")
388 impl<'tcx> QueryDescription for queries::typeck_item_bodies<'tcx> {
389 fn describe(_: TyCtxt, _: CrateNum) -> String {
390 format!("type-checking all item bodies")
394 impl<'tcx> QueryDescription for queries::reachable_set<'tcx> {
395 fn describe(_: TyCtxt, _: CrateNum) -> String {
396 format!("reachability")
400 impl<'tcx> QueryDescription for queries::const_eval<'tcx> {
401 fn describe(tcx: TyCtxt, key: ty::ParamEnvAnd<'tcx, (DefId, &'tcx Substs<'tcx>)>) -> String {
402 format!("const-evaluating `{}`", tcx.item_path_str(key.value.0))
406 impl<'tcx> QueryDescription for queries::mir_keys<'tcx> {
407 fn describe(_: TyCtxt, _: CrateNum) -> String {
408 format!("getting a list of all mir_keys")
412 impl<'tcx> QueryDescription for queries::symbol_name<'tcx> {
413 fn describe(_tcx: TyCtxt, instance: ty::Instance<'tcx>) -> String {
414 format!("computing the symbol for `{}`", instance)
418 impl<'tcx> QueryDescription for queries::describe_def<'tcx> {
419 fn describe(_: TyCtxt, _: DefId) -> String {
424 impl<'tcx> QueryDescription for queries::def_span<'tcx> {
425 fn describe(_: TyCtxt, _: DefId) -> String {
431 impl<'tcx> QueryDescription for queries::stability<'tcx> {
432 fn describe(_: TyCtxt, _: DefId) -> String {
437 impl<'tcx> QueryDescription for queries::deprecation<'tcx> {
438 fn describe(_: TyCtxt, _: DefId) -> String {
443 impl<'tcx> QueryDescription for queries::item_attrs<'tcx> {
444 fn describe(_: TyCtxt, _: DefId) -> String {
449 impl<'tcx> QueryDescription for queries::is_exported_symbol<'tcx> {
450 fn describe(_: TyCtxt, _: DefId) -> String {
451 bug!("is_exported_symbol")
455 impl<'tcx> QueryDescription for queries::fn_arg_names<'tcx> {
456 fn describe(_: TyCtxt, _: DefId) -> String {
461 impl<'tcx> QueryDescription for queries::impl_parent<'tcx> {
462 fn describe(_: TyCtxt, _: DefId) -> String {
467 impl<'tcx> QueryDescription for queries::trait_of_item<'tcx> {
468 fn describe(_: TyCtxt, _: DefId) -> String {
469 bug!("trait_of_item")
473 impl<'tcx> QueryDescription for queries::item_body_nested_bodies<'tcx> {
474 fn describe(tcx: TyCtxt, def_id: DefId) -> String {
475 format!("nested item bodies of `{}`", tcx.item_path_str(def_id))
479 impl<'tcx> QueryDescription for queries::const_is_rvalue_promotable_to_static<'tcx> {
480 fn describe(tcx: TyCtxt, def_id: DefId) -> String {
481 format!("const checking if rvalue is promotable to static `{}`",
482 tcx.item_path_str(def_id))
486 impl<'tcx> QueryDescription for queries::is_mir_available<'tcx> {
487 fn describe(tcx: TyCtxt, def_id: DefId) -> String {
488 format!("checking if item is mir available: `{}`",
489 tcx.item_path_str(def_id))
493 impl<'tcx> QueryDescription for queries::trait_impls_of<'tcx> {
494 fn describe(tcx: TyCtxt, def_id: DefId) -> String {
495 format!("trait impls of `{}`", tcx.item_path_str(def_id))
499 impl<'tcx> QueryDescription for queries::is_object_safe<'tcx> {
500 fn describe(tcx: TyCtxt, def_id: DefId) -> String {
501 format!("determine object safety of trait `{}`", tcx.item_path_str(def_id))
505 impl<'tcx> QueryDescription for queries::is_const_fn<'tcx> {
506 fn describe(tcx: TyCtxt, def_id: DefId) -> String {
507 format!("checking if item is const fn: `{}`", tcx.item_path_str(def_id))
511 impl<'tcx> QueryDescription for queries::dylib_dependency_formats<'tcx> {
512 fn describe(_: TyCtxt, _: DefId) -> String {
513 "dylib dependency formats of crate".to_string()
517 impl<'tcx> QueryDescription for queries::is_allocator<'tcx> {
518 fn describe(_: TyCtxt, _: DefId) -> String {
519 "checking if the crate is_allocator".to_string()
523 impl<'tcx> QueryDescription for queries::is_panic_runtime<'tcx> {
524 fn describe(_: TyCtxt, _: DefId) -> String {
525 "checking if the crate is_panic_runtime".to_string()
529 impl<'tcx> QueryDescription for queries::is_compiler_builtins<'tcx> {
530 fn describe(_: TyCtxt, _: DefId) -> String {
531 "checking if the crate is_compiler_builtins".to_string()
535 impl<'tcx> QueryDescription for queries::has_global_allocator<'tcx> {
536 fn describe(_: TyCtxt, _: DefId) -> String {
537 "checking if the crate has_global_allocator".to_string()
541 impl<'tcx> QueryDescription for queries::extern_crate<'tcx> {
542 fn describe(_: TyCtxt, _: DefId) -> String {
543 "getting crate's ExternCrateData".to_string()
547 impl<'tcx> QueryDescription for queries::lint_levels<'tcx> {
548 fn describe(_tcx: TyCtxt, _: CrateNum) -> String {
549 format!("computing the lint levels for items in this crate")
553 impl<'tcx> QueryDescription for queries::specializes<'tcx> {
554 fn describe(_tcx: TyCtxt, _: (DefId, DefId)) -> String {
555 format!("computing whether impls specialize one another")
559 impl<'tcx> QueryDescription for queries::in_scope_traits<'tcx> {
560 fn describe(_tcx: TyCtxt, _: HirId) -> String {
561 format!("fetching the traits in scope at a particular ast node")
565 impl<'tcx> QueryDescription for queries::module_exports<'tcx> {
566 fn describe(_tcx: TyCtxt, _: HirId) -> String {
567 format!("fetching the exported items for a module")
571 // If enabled, send a message to the profile-queries thread
572 macro_rules! profq_msg {
573 ($tcx:expr, $msg:expr) => {
574 if cfg!(debug_assertions) {
575 if $tcx.sess.profile_queries() {
582 // If enabled, format a key using its debug string, which can be
583 // expensive to compute (in terms of time).
584 macro_rules! profq_key {
585 ($tcx:expr, $key:expr) => {
586 if cfg!(debug_assertions) {
587 if $tcx.sess.profile_queries_and_keys() {
588 Some(format!("{:?}", $key))
594 macro_rules! define_maps {
597 [$($modifiers:tt)*] fn $name:ident: $node:ident($K:ty) -> $V:ty,)*) => {
600 input: ($(([$($modifiers)*] [$($attr)*] [$name]))*)
603 impl<$tcx> Maps<$tcx> {
604 pub fn new(providers: IndexVec<CrateNum, Providers<$tcx>>)
608 query_stack: RefCell::new(vec![]),
609 $($name: RefCell::new(QueryMap::new())),*
615 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
616 pub enum Query<$tcx> {
617 $($(#[$attr])* $name($K)),*
621 #[derive(Clone, Debug, PartialEq, Eq)]
623 $($name(Option<String>)),*
626 impl<$tcx> Query<$tcx> {
627 pub fn describe(&self, tcx: TyCtxt) -> String {
628 let (r, name) = match *self {
629 $(Query::$name(key) => {
630 (queries::$name::describe(tcx, key), stringify!($name))
633 if tcx.sess.verbose() {
634 format!("{} [{}]", r, name)
642 use std::marker::PhantomData;
644 $(#[allow(bad_style)]
645 pub struct $name<$tcx> {
646 data: PhantomData<&$tcx ()>
650 $(impl<$tcx> QueryConfig for queries::$name<$tcx> {
655 impl<'a, $tcx, 'lcx> queries::$name<$tcx> {
657 fn to_dep_node(tcx: TyCtxt<'a, $tcx, 'lcx>, key: &$K) -> DepNode {
658 use dep_graph::DepConstructor::*;
660 DepNode::new(tcx, $node(*key))
663 fn try_get_with<F, R>(tcx: TyCtxt<'a, $tcx, 'lcx>,
667 -> Result<R, CycleError<'a, $tcx>>
668 where F: FnOnce(&$V) -> R
670 debug!("ty::queries::{}::try_get_with(key={:?}, span={:?})",
676 ProfileQueriesMsg::QueryBegin(
678 QueryMsg::$name(profq_key!(tcx, key))
682 if let Some(value) = tcx.maps.$name.borrow().map.get(&key) {
683 if let Some(ref d) = value.diagnostics {
684 if !d.emitted_diagnostics.get() {
685 d.emitted_diagnostics.set(true);
686 let handle = tcx.sess.diagnostic();
687 for diagnostic in d.diagnostics.iter() {
688 DiagnosticBuilder::new_diagnostic(handle, diagnostic.clone())
693 profq_msg!(tcx, ProfileQueriesMsg::CacheHit);
694 tcx.dep_graph.read_index(value.index);
695 return Ok(f(&value.value));
697 // else, we are going to run the provider:
698 profq_msg!(tcx, ProfileQueriesMsg::ProviderBegin);
700 // FIXME(eddyb) Get more valid Span's on queries.
701 // def_span guard is necessary to prevent a recursive loop,
702 // default_span calls def_span query internally.
703 if span == DUMMY_SP && stringify!($name) != "def_span" {
704 span = key.default_span(tcx)
707 let res = tcx.cycle_check(span, Query::$name(key), || {
708 let dep_node = Self::to_dep_node(tcx, &key);
710 tcx.sess.diagnostic().track_diagnostics(|| {
711 if dep_node.kind.is_anon() {
712 tcx.dep_graph.with_anon_task(dep_node.kind, || {
713 let provider = tcx.maps.providers[key.map_crate()].$name;
714 provider(tcx.global_tcx(), key)
717 fn run_provider<'a, 'tcx, 'lcx>(tcx: TyCtxt<'a, 'tcx, 'lcx>,
720 let provider = tcx.maps.providers[key.map_crate()].$name;
721 provider(tcx.global_tcx(), key)
724 tcx.dep_graph.with_task(dep_node, tcx, key, run_provider)
728 profq_msg!(tcx, ProfileQueriesMsg::ProviderEnd);
729 let ((result, dep_node_index), diagnostics) = res;
731 tcx.dep_graph.read_index(dep_node_index);
733 let value = QueryValue {
735 index: dep_node_index,
736 diagnostics: if diagnostics.len() == 0 {
739 Some(Box::new(QueryDiagnostics {
741 emitted_diagnostics: Cell::new(true),
755 pub fn try_get(tcx: TyCtxt<'a, $tcx, 'lcx>, span: Span, key: $K)
756 -> Result<$V, DiagnosticBuilder<'a>> {
757 match Self::try_get_with(tcx, span, key, Clone::clone) {
759 Err(e) => Err(tcx.report_cycle(e)),
763 pub fn force(tcx: TyCtxt<'a, $tcx, 'lcx>, span: Span, key: $K) {
764 // Ignore dependencies, since we not reading the computed value
765 let _task = tcx.dep_graph.in_ignore();
767 match Self::try_get_with(tcx, span, key, |_| ()) {
769 Err(e) => tcx.report_cycle(e).emit(),
774 #[derive(Copy, Clone)]
775 pub struct TyCtxtAt<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
776 pub tcx: TyCtxt<'a, 'gcx, 'tcx>,
780 impl<'a, 'gcx, 'tcx> Deref for TyCtxtAt<'a, 'gcx, 'tcx> {
781 type Target = TyCtxt<'a, 'gcx, 'tcx>;
782 fn deref(&self) -> &Self::Target {
787 impl<'a, $tcx, 'lcx> TyCtxt<'a, $tcx, 'lcx> {
788 /// Return a transparent wrapper for `TyCtxt` which uses
789 /// `span` as the location of queries performed through it.
790 pub fn at(self, span: Span) -> TyCtxtAt<'a, $tcx, 'lcx> {
798 pub fn $name(self, key: $K) -> $V {
799 self.at(DUMMY_SP).$name(key)
803 impl<'a, $tcx, 'lcx> TyCtxtAt<'a, $tcx, 'lcx> {
805 pub fn $name(self, key: $K) -> $V {
806 queries::$name::try_get(self.tcx, self.span, key).unwrap_or_else(|mut e| {
808 Value::from_cycle_error(self.global_tcx())
813 define_provider_struct! {
815 input: ($(([$($modifiers)*] [$name] [$K] [$V]))*),
819 impl<$tcx> Copy for Providers<$tcx> {}
820 impl<$tcx> Clone for Providers<$tcx> {
821 fn clone(&self) -> Self { *self }
826 macro_rules! define_map_struct {
829 input: $input:tt) => {
840 output: ($($output:tt)*)) => {
841 pub struct Maps<$tcx> {
842 providers: IndexVec<CrateNum, Providers<$tcx>>,
843 query_stack: RefCell<Vec<(Span, Query<$tcx>)>>,
848 // Field recognized and ready to shift into the output
850 ready: ([$($pub:tt)*] [$($attr:tt)*] [$name:ident]),
852 output: ($($output:tt)*)) => {
857 $(#[$attr])* $($pub)* $name: RefCell<QueryMap<queries::$name<$tcx>>>,)
861 // No modifiers left? This is a private item.
863 input: (([] $attrs:tt $name:tt) $($input:tt)*),
864 output: $output:tt) => {
867 ready: ([] $attrs $name),
873 // Skip other modifiers
875 input: (([$other_modifier:tt $($modifiers:tt)*] $($fields:tt)*) $($input:tt)*),
876 output: $output:tt) => {
879 input: (([$($modifiers)*] $($fields)*) $($input)*),
885 macro_rules! define_provider_struct {
887 (tcx: $tcx:tt, input: $input:tt) => {
888 define_provider_struct! {
898 output: ($(([$name:ident] [$K:ty] [$R:ty]))*)) => {
899 pub struct Providers<$tcx> {
900 $(pub $name: for<'a> fn(TyCtxt<'a, $tcx, $tcx>, $K) -> $R,)*
903 impl<$tcx> Default for Providers<$tcx> {
904 fn default() -> Self {
905 $(fn $name<'a, $tcx>(_: TyCtxt<'a, $tcx, $tcx>, key: $K) -> $R {
906 bug!("tcx.maps.{}({:?}) unsupported by its crate",
907 stringify!($name), key);
909 Providers { $($name),* }
914 // Something ready to shift:
916 ready: ($name:tt $K:tt $V:tt),
918 output: ($($output:tt)*)) => {
919 define_provider_struct! {
922 output: ($($output)* ($name $K $V))
926 // Regular queries produce a `V` only.
928 input: (([] $name:tt $K:tt $V:tt) $($input:tt)*),
929 output: $output:tt) => {
930 define_provider_struct! {
932 ready: ($name $K $V),
940 input: (([$other_modifier:tt $($modifiers:tt)*] $($fields:tt)*) $($input:tt)*),
941 output: $output:tt) => {
942 define_provider_struct! {
944 input: (([$($modifiers)*] $($fields)*) $($input)*),
950 // Each of these maps also corresponds to a method on a
951 // `Provider` trait for requesting a value of that type,
952 // and a method on `Maps` itself for doing that in a
953 // a way that memoizes and does dep-graph tracking,
954 // wrapping around the actual chain of providers that
955 // the driver creates (using several `rustc_*` crates).
956 define_maps! { <'tcx>
957 /// Records the type of every item.
958 [] fn type_of: TypeOfItem(DefId) -> Ty<'tcx>,
960 /// Maps from the def-id of an item (trait/struct/enum/fn) to its
961 /// associated generics and predicates.
962 [] fn generics_of: GenericsOfItem(DefId) -> &'tcx ty::Generics,
963 [] fn predicates_of: PredicatesOfItem(DefId) -> ty::GenericPredicates<'tcx>,
965 /// Maps from the def-id of a trait to the list of
966 /// super-predicates. This is a subset of the full list of
967 /// predicates. We store these in a separate map because we must
968 /// evaluate them even during type conversion, often before the
969 /// full predicates are available (note that supertraits have
970 /// additional acyclicity requirements).
971 [] fn super_predicates_of: SuperPredicatesOfItem(DefId) -> ty::GenericPredicates<'tcx>,
973 /// To avoid cycles within the predicates of a single item we compute
974 /// per-type-parameter predicates for resolving `T::AssocTy`.
975 [] fn type_param_predicates: type_param_predicates((DefId, DefId))
976 -> ty::GenericPredicates<'tcx>,
978 [] fn trait_def: TraitDefOfItem(DefId) -> &'tcx ty::TraitDef,
979 [] fn adt_def: AdtDefOfItem(DefId) -> &'tcx ty::AdtDef,
980 [] fn adt_destructor: AdtDestructor(DefId) -> Option<ty::Destructor>,
981 [] fn adt_sized_constraint: SizedConstraint(DefId) -> &'tcx [Ty<'tcx>],
982 [] fn adt_dtorck_constraint: DtorckConstraint(DefId) -> ty::DtorckConstraint<'tcx>,
984 /// True if this is a const fn
985 [] fn is_const_fn: IsConstFn(DefId) -> bool,
987 /// True if this is a foreign item (i.e., linked via `extern { ... }`).
988 [] fn is_foreign_item: IsForeignItem(DefId) -> bool,
990 /// True if this is a default impl (aka impl Foo for ..)
991 [] fn is_default_impl: IsDefaultImpl(DefId) -> bool,
993 /// Get a map with the variance of every item; use `item_variance`
995 [] fn crate_variances: crate_variances(CrateNum) -> Rc<ty::CrateVariancesMap>,
997 /// Maps from def-id of a type or region parameter to its
998 /// (inferred) variance.
999 [] fn variances_of: ItemVariances(DefId) -> Rc<Vec<ty::Variance>>,
1001 /// Maps from an impl/trait def-id to a list of the def-ids of its items
1002 [] fn associated_item_def_ids: AssociatedItemDefIds(DefId) -> Rc<Vec<DefId>>,
1004 /// Maps from a trait item to the trait item "descriptor"
1005 [] fn associated_item: AssociatedItems(DefId) -> ty::AssociatedItem,
1007 [] fn impl_trait_ref: ImplTraitRef(DefId) -> Option<ty::TraitRef<'tcx>>,
1008 [] fn impl_polarity: ImplPolarity(DefId) -> hir::ImplPolarity,
1010 /// Maps a DefId of a type to a list of its inherent impls.
1011 /// Contains implementations of methods that are inherent to a type.
1012 /// Methods in these implementations don't need to be exported.
1013 [] fn inherent_impls: InherentImpls(DefId) -> Rc<Vec<DefId>>,
1015 /// Set of all the def-ids in this crate that have MIR associated with
1016 /// them. This includes all the body owners, but also things like struct
1018 [] fn mir_keys: mir_keys(CrateNum) -> Rc<DefIdSet>,
1020 /// Maps DefId's that have an associated Mir to the result
1021 /// of the MIR qualify_consts pass. The actual meaning of
1022 /// the value isn't known except to the pass itself.
1023 [] fn mir_const_qualif: MirConstQualif(DefId) -> (u8, Rc<IdxSetBuf<mir::Local>>),
1025 /// Fetch the MIR for a given def-id up till the point where it is
1026 /// ready for const evaluation.
1028 /// See the README for the `mir` module for details.
1029 [] fn mir_const: MirConst(DefId) -> &'tcx Steal<mir::Mir<'tcx>>,
1031 [] fn mir_validated: MirValidated(DefId) -> &'tcx Steal<mir::Mir<'tcx>>,
1033 /// MIR after our optimization passes have run. This is MIR that is ready
1034 /// for trans. This is also the only query that can fetch non-local MIR, at present.
1035 [] fn optimized_mir: MirOptimized(DefId) -> &'tcx mir::Mir<'tcx>,
1037 /// Type of each closure. The def ID is the ID of the
1038 /// expression defining the closure.
1039 [] fn closure_kind: ClosureKind(DefId) -> ty::ClosureKind,
1041 /// The signature of functions and closures.
1042 [] fn fn_sig: FnSignature(DefId) -> ty::PolyFnSig<'tcx>,
1044 /// Records the signature of each generator. The def ID is the ID of the
1045 /// expression defining the closure.
1046 [] fn generator_sig: GenSignature(DefId) -> Option<ty::PolyGenSig<'tcx>>,
1048 /// Caches CoerceUnsized kinds for impls on custom types.
1049 [] fn coerce_unsized_info: CoerceUnsizedInfo(DefId)
1050 -> ty::adjustment::CoerceUnsizedInfo,
1052 [] fn typeck_item_bodies: typeck_item_bodies_dep_node(CrateNum) -> CompileResult,
1054 [] fn typeck_tables_of: TypeckTables(DefId) -> &'tcx ty::TypeckTables<'tcx>,
1056 [] fn has_typeck_tables: HasTypeckTables(DefId) -> bool,
1058 [] fn coherent_trait: coherent_trait_dep_node((CrateNum, DefId)) -> (),
1060 [] fn borrowck: BorrowCheck(DefId) -> (),
1061 // FIXME: shouldn't this return a `Result<(), BorrowckErrors>` instead?
1062 [] fn mir_borrowck: MirBorrowCheck(DefId) -> (),
1064 /// Gets a complete map from all types to their inherent impls.
1065 /// Not meant to be used directly outside of coherence.
1066 /// (Defined only for LOCAL_CRATE)
1067 [] fn crate_inherent_impls: crate_inherent_impls_dep_node(CrateNum) -> CrateInherentImpls,
1069 /// Checks all types in the krate for overlap in their inherent impls. Reports errors.
1070 /// Not meant to be used directly outside of coherence.
1071 /// (Defined only for LOCAL_CRATE)
1072 [] fn crate_inherent_impls_overlap_check: inherent_impls_overlap_check_dep_node(CrateNum) -> (),
1074 /// Results of evaluating const items or constants embedded in
1075 /// other items (such as enum variant explicit discriminants).
1076 [] fn const_eval: const_eval_dep_node(ty::ParamEnvAnd<'tcx, (DefId, &'tcx Substs<'tcx>)>)
1077 -> const_val::EvalResult<'tcx>,
1079 /// Performs the privacy check and computes "access levels".
1080 [] fn privacy_access_levels: PrivacyAccessLevels(CrateNum) -> Rc<AccessLevels>,
1082 [] fn reachable_set: reachability_dep_node(CrateNum) -> Rc<NodeSet>,
1084 /// Per-body `region::ScopeTree`. The `DefId` should be the owner-def-id for the body;
1085 /// in the case of closures, this will be redirected to the enclosing function.
1086 [] fn region_scope_tree: RegionScopeTree(DefId) -> Rc<region::ScopeTree>,
1088 [] fn mir_shims: mir_shim_dep_node(ty::InstanceDef<'tcx>) -> &'tcx mir::Mir<'tcx>,
1090 [] fn def_symbol_name: SymbolName(DefId) -> ty::SymbolName,
1091 [] fn symbol_name: symbol_name_dep_node(ty::Instance<'tcx>) -> ty::SymbolName,
1093 [] fn describe_def: DescribeDef(DefId) -> Option<Def>,
1094 [] fn def_span: DefSpan(DefId) -> Span,
1095 [] fn stability: Stability(DefId) -> Option<attr::Stability>,
1096 [] fn deprecation: Deprecation(DefId) -> Option<attr::Deprecation>,
1097 [] fn item_attrs: ItemAttrs(DefId) -> Rc<[ast::Attribute]>,
1098 [] fn fn_arg_names: FnArgNames(DefId) -> Vec<ast::Name>,
1099 [] fn impl_parent: ImplParent(DefId) -> Option<DefId>,
1100 [] fn trait_of_item: TraitOfItem(DefId) -> Option<DefId>,
1101 [] fn is_exported_symbol: IsExportedSymbol(DefId) -> bool,
1102 [] fn item_body_nested_bodies: ItemBodyNestedBodies(DefId)
1103 -> Rc<BTreeMap<hir::BodyId, hir::Body>>,
1104 [] fn const_is_rvalue_promotable_to_static: ConstIsRvaluePromotableToStatic(DefId) -> bool,
1105 [] fn is_mir_available: IsMirAvailable(DefId) -> bool,
1107 [] fn trait_impls_of: TraitImpls(DefId) -> Rc<ty::trait_def::TraitImpls>,
1108 [] fn specialization_graph_of: SpecializationGraph(DefId) -> Rc<specialization_graph::Graph>,
1109 [] fn is_object_safe: ObjectSafety(DefId) -> bool,
1111 // Get the ParameterEnvironment for a given item; this environment
1112 // will be in "user-facing" mode, meaning that it is suitabe for
1113 // type-checking etc, and it does not normalize specializable
1114 // associated types. This is almost always what you want,
1115 // unless you are doing MIR optimizations, in which case you
1116 // might want to use `reveal_all()` method to change modes.
1117 [] fn param_env: ParamEnv(DefId) -> ty::ParamEnv<'tcx>,
1119 // Trait selection queries. These are best used by invoking `ty.moves_by_default()`,
1120 // `ty.is_copy()`, etc, since that will prune the environment where possible.
1121 [] fn is_copy_raw: is_copy_dep_node(ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> bool,
1122 [] fn is_sized_raw: is_sized_dep_node(ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> bool,
1123 [] fn is_freeze_raw: is_freeze_dep_node(ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> bool,
1124 [] fn needs_drop_raw: needs_drop_dep_node(ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> bool,
1125 [] fn layout_raw: layout_dep_node(ty::ParamEnvAnd<'tcx, Ty<'tcx>>)
1126 -> Result<&'tcx Layout, LayoutError<'tcx>>,
1128 [] fn dylib_dependency_formats: DylibDepFormats(DefId)
1129 -> Rc<Vec<(CrateNum, LinkagePreference)>>,
1131 [] fn is_allocator: IsAllocator(DefId) -> bool,
1132 [] fn is_panic_runtime: IsPanicRuntime(DefId) -> bool,
1133 [] fn is_compiler_builtins: IsCompilerBuiltins(DefId) -> bool,
1134 [] fn has_global_allocator: HasGlobalAllocator(DefId) -> bool,
1136 [] fn extern_crate: ExternCrate(DefId) -> Rc<Option<ExternCrate>>,
1138 [] fn lint_levels: lint_levels(CrateNum) -> Rc<lint::LintLevelMap>,
1140 [] fn specializes: specializes_node((DefId, DefId)) -> bool,
1141 [] fn in_scope_traits: InScopeTraits(HirId) -> Option<Rc<Vec<TraitCandidate>>>,
1142 [] fn module_exports: ModuleExports(HirId) -> Option<Rc<Vec<Export>>>,
1145 fn type_param_predicates<'tcx>((item_id, param_id): (DefId, DefId)) -> DepConstructor<'tcx> {
1146 DepConstructor::TypeParamPredicates {
1152 fn coherent_trait_dep_node<'tcx>((_, def_id): (CrateNum, DefId)) -> DepConstructor<'tcx> {
1153 DepConstructor::CoherenceCheckTrait(def_id)
1156 fn crate_inherent_impls_dep_node<'tcx>(_: CrateNum) -> DepConstructor<'tcx> {
1157 DepConstructor::Coherence
1160 fn inherent_impls_overlap_check_dep_node<'tcx>(_: CrateNum) -> DepConstructor<'tcx> {
1161 DepConstructor::CoherenceInherentImplOverlapCheck
1164 fn reachability_dep_node<'tcx>(_: CrateNum) -> DepConstructor<'tcx> {
1165 DepConstructor::Reachability
1168 fn mir_shim_dep_node<'tcx>(instance_def: ty::InstanceDef<'tcx>) -> DepConstructor<'tcx> {
1169 DepConstructor::MirShim {
1174 fn symbol_name_dep_node<'tcx>(instance: ty::Instance<'tcx>) -> DepConstructor<'tcx> {
1175 DepConstructor::InstanceSymbolName { instance }
1178 fn typeck_item_bodies_dep_node<'tcx>(_: CrateNum) -> DepConstructor<'tcx> {
1179 DepConstructor::TypeckBodiesKrate
1182 fn const_eval_dep_node<'tcx>(_: ty::ParamEnvAnd<'tcx, (DefId, &'tcx Substs<'tcx>)>)
1183 -> DepConstructor<'tcx> {
1184 DepConstructor::ConstEval
1187 fn mir_keys<'tcx>(_: CrateNum) -> DepConstructor<'tcx> {
1188 DepConstructor::MirKeys
1191 fn crate_variances<'tcx>(_: CrateNum) -> DepConstructor<'tcx> {
1192 DepConstructor::CrateVariances
1195 fn is_copy_dep_node<'tcx>(_: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> DepConstructor<'tcx> {
1196 DepConstructor::IsCopy
1199 fn is_sized_dep_node<'tcx>(_: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> DepConstructor<'tcx> {
1200 DepConstructor::IsSized
1203 fn is_freeze_dep_node<'tcx>(_: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> DepConstructor<'tcx> {
1204 DepConstructor::IsFreeze
1207 fn needs_drop_dep_node<'tcx>(_: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> DepConstructor<'tcx> {
1208 DepConstructor::NeedsDrop
1211 fn layout_dep_node<'tcx>(_: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> DepConstructor<'tcx> {
1212 DepConstructor::Layout
1215 fn lint_levels<'tcx>(_: CrateNum) -> DepConstructor<'tcx> {
1216 DepConstructor::LintLevels
1219 fn specializes_node<'tcx>((a, b): (DefId, DefId)) -> DepConstructor<'tcx> {
1220 DepConstructor::Specializes { impl1: a, impl2: b }