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;
20 use middle::region::RegionMaps;
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_vec::IndexVec;
35 use rustc_data_structures::fx::FxHashMap;
36 use std::cell::{RefCell, RefMut, Cell};
39 use std::marker::PhantomData;
41 use std::collections::BTreeMap;
44 use syntax_pos::{Span, DUMMY_SP};
47 use syntax::symbol::Symbol;
49 pub trait Key: Clone + Hash + Eq + Debug {
50 fn map_crate(&self) -> CrateNum;
51 fn default_span(&self, tcx: TyCtxt) -> Span;
54 impl<'tcx> Key for ty::InstanceDef<'tcx> {
55 fn map_crate(&self) -> CrateNum {
59 fn default_span(&self, tcx: TyCtxt) -> Span {
60 tcx.def_span(self.def_id())
64 impl<'tcx> Key for ty::Instance<'tcx> {
65 fn map_crate(&self) -> CrateNum {
69 fn default_span(&self, tcx: TyCtxt) -> Span {
70 tcx.def_span(self.def_id())
74 impl Key for CrateNum {
75 fn map_crate(&self) -> CrateNum {
78 fn default_span(&self, _: TyCtxt) -> Span {
84 fn map_crate(&self) -> CrateNum {
87 fn default_span(&self, _tcx: TyCtxt) -> Span {
93 fn map_crate(&self) -> CrateNum {
96 fn default_span(&self, tcx: TyCtxt) -> Span {
101 impl Key for (DefId, DefId) {
102 fn map_crate(&self) -> CrateNum {
105 fn default_span(&self, tcx: TyCtxt) -> Span {
106 self.1.default_span(tcx)
110 impl Key for (CrateNum, DefId) {
111 fn map_crate(&self) -> CrateNum {
114 fn default_span(&self, tcx: TyCtxt) -> Span {
115 self.1.default_span(tcx)
119 impl Key for (DefId, SimplifiedType) {
120 fn map_crate(&self) -> CrateNum {
123 fn default_span(&self, tcx: TyCtxt) -> Span {
124 self.0.default_span(tcx)
128 impl<'tcx> Key for (DefId, &'tcx Substs<'tcx>) {
129 fn map_crate(&self) -> CrateNum {
132 fn default_span(&self, tcx: TyCtxt) -> Span {
133 self.0.default_span(tcx)
137 impl Key for (MirSuite, DefId) {
138 fn map_crate(&self) -> CrateNum {
141 fn default_span(&self, tcx: TyCtxt) -> Span {
142 self.1.default_span(tcx)
146 impl Key for (MirSuite, MirPassIndex, DefId) {
147 fn map_crate(&self) -> CrateNum {
150 fn default_span(&self, tcx: TyCtxt) -> Span {
151 self.2.default_span(tcx)
155 impl<'tcx, T: Clone + Hash + Eq + Debug> Key for ty::ParamEnvAnd<'tcx, T> {
156 fn map_crate(&self) -> CrateNum {
159 fn default_span(&self, _: TyCtxt) -> Span {
164 trait Value<'tcx>: Sized {
165 fn from_cycle_error<'a>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Self;
168 impl<'tcx, T> Value<'tcx> for T {
169 default fn from_cycle_error<'a>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> T {
170 tcx.sess.abort_if_errors();
171 bug!("Value::from_cycle_error called without errors");
175 impl<'tcx, T: Default> Value<'tcx> for T {
176 default fn from_cycle_error<'a>(_: TyCtxt<'a, 'tcx, 'tcx>) -> T {
181 impl<'tcx> Value<'tcx> for Ty<'tcx> {
182 fn from_cycle_error<'a>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Ty<'tcx> {
187 impl<'tcx> Value<'tcx> for ty::DtorckConstraint<'tcx> {
188 fn from_cycle_error<'a>(_: TyCtxt<'a, 'tcx, 'tcx>) -> Self {
193 impl<'tcx> Value<'tcx> for ty::SymbolName {
194 fn from_cycle_error<'a>(_: TyCtxt<'a, 'tcx, 'tcx>) -> Self {
195 ty::SymbolName { name: Symbol::intern("<error>").as_str() }
199 struct QueryMap<D: QueryDescription> {
200 phantom: PhantomData<D>,
201 map: FxHashMap<D::Key, QueryValue<D::Value>>,
204 struct QueryValue<T> {
207 diagnostics: Option<Box<QueryDiagnostics>>,
210 struct QueryDiagnostics {
211 diagnostics: Vec<Diagnostic>,
212 emitted_diagnostics: Cell<bool>,
215 impl<M: QueryDescription> QueryMap<M> {
216 fn new() -> QueryMap<M> {
218 phantom: PhantomData,
224 struct CycleError<'a, 'tcx: 'a> {
226 cycle: RefMut<'a, [(Span, Query<'tcx>)]>,
229 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
230 fn report_cycle(self, CycleError { span, cycle }: CycleError)
231 -> DiagnosticBuilder<'a>
233 // Subtle: release the refcell lock before invoking `describe()`
234 // below by dropping `cycle`.
235 let stack = cycle.to_vec();
238 assert!(!stack.is_empty());
240 // Disable naming impls with types in this path, since that
241 // sometimes cycles itself, leading to extra cycle errors.
242 // (And cycle errors around impls tend to occur during the
243 // collect/coherence phases anyhow.)
244 item_path::with_forced_impl_filename_line(|| {
246 struct_span_err!(self.sess, span, E0391,
247 "unsupported cyclic reference between types/traits detected");
248 err.span_label(span, "cyclic reference");
250 err.span_note(stack[0].0, &format!("the cycle begins when {}...",
251 stack[0].1.describe(self)));
253 for &(span, ref query) in &stack[1..] {
254 err.span_note(span, &format!("...which then requires {}...",
255 query.describe(self)));
258 err.note(&format!("...which then again requires {}, completing the cycle.",
259 stack[0].1.describe(self)));
265 fn cycle_check<F, R>(self, span: Span, query: Query<'gcx>, compute: F)
266 -> Result<R, CycleError<'a, 'gcx>>
267 where F: FnOnce() -> R
270 let mut stack = self.maps.query_stack.borrow_mut();
271 if let Some((i, _)) = stack.iter().enumerate().rev()
272 .find(|&(_, &(_, ref q))| *q == query) {
273 return Err(CycleError {
275 cycle: RefMut::map(stack, |stack| &mut stack[i..])
278 stack.push((span, query));
281 let result = compute();
283 self.maps.query_stack.borrow_mut().pop();
289 pub trait QueryConfig {
290 type Key: Eq + Hash + Clone;
294 trait QueryDescription: QueryConfig {
295 fn describe(tcx: TyCtxt, key: Self::Key) -> String;
298 impl<M: QueryConfig<Key=DefId>> QueryDescription for M {
299 default fn describe(tcx: TyCtxt, def_id: DefId) -> String {
300 format!("processing `{}`", tcx.item_path_str(def_id))
304 impl<'tcx> QueryDescription for queries::is_copy_raw<'tcx> {
305 fn describe(_tcx: TyCtxt, env: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> String {
306 format!("computing whether `{}` is `Copy`", env.value)
310 impl<'tcx> QueryDescription for queries::is_sized_raw<'tcx> {
311 fn describe(_tcx: TyCtxt, env: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> String {
312 format!("computing whether `{}` is `Sized`", env.value)
316 impl<'tcx> QueryDescription for queries::is_freeze_raw<'tcx> {
317 fn describe(_tcx: TyCtxt, env: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> String {
318 format!("computing whether `{}` is freeze", env.value)
322 impl<'tcx> QueryDescription for queries::needs_drop_raw<'tcx> {
323 fn describe(_tcx: TyCtxt, env: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> String {
324 format!("computing whether `{}` needs drop", env.value)
328 impl<'tcx> QueryDescription for queries::layout_raw<'tcx> {
329 fn describe(_tcx: TyCtxt, env: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> String {
330 format!("computing layout of `{}`", env.value)
334 impl<'tcx> QueryDescription for queries::super_predicates_of<'tcx> {
335 fn describe(tcx: TyCtxt, def_id: DefId) -> String {
336 format!("computing the supertraits of `{}`",
337 tcx.item_path_str(def_id))
341 impl<'tcx> QueryDescription for queries::type_param_predicates<'tcx> {
342 fn describe(tcx: TyCtxt, (_, def_id): (DefId, DefId)) -> String {
343 let id = tcx.hir.as_local_node_id(def_id).unwrap();
344 format!("computing the bounds for type parameter `{}`",
345 tcx.hir.ty_param_name(id))
349 impl<'tcx> QueryDescription for queries::coherent_trait<'tcx> {
350 fn describe(tcx: TyCtxt, (_, def_id): (CrateNum, DefId)) -> String {
351 format!("coherence checking all impls of trait `{}`",
352 tcx.item_path_str(def_id))
356 impl<'tcx> QueryDescription for queries::crate_inherent_impls<'tcx> {
357 fn describe(_: TyCtxt, k: CrateNum) -> String {
358 format!("all inherent impls defined in crate `{:?}`", k)
362 impl<'tcx> QueryDescription for queries::crate_inherent_impls_overlap_check<'tcx> {
363 fn describe(_: TyCtxt, _: CrateNum) -> String {
364 format!("check for overlap between inherent impls defined in this crate")
368 impl<'tcx> QueryDescription for queries::crate_variances<'tcx> {
369 fn describe(_tcx: TyCtxt, _: CrateNum) -> String {
370 format!("computing the variances for items in this crate")
374 impl<'tcx> QueryDescription for queries::mir_shims<'tcx> {
375 fn describe(tcx: TyCtxt, def: ty::InstanceDef<'tcx>) -> String {
376 format!("generating MIR shim for `{}`",
377 tcx.item_path_str(def.def_id()))
381 impl<'tcx> QueryDescription for queries::privacy_access_levels<'tcx> {
382 fn describe(_: TyCtxt, _: CrateNum) -> String {
383 format!("privacy access levels")
387 impl<'tcx> QueryDescription for queries::typeck_item_bodies<'tcx> {
388 fn describe(_: TyCtxt, _: CrateNum) -> String {
389 format!("type-checking all item bodies")
393 impl<'tcx> QueryDescription for queries::reachable_set<'tcx> {
394 fn describe(_: TyCtxt, _: CrateNum) -> String {
395 format!("reachability")
399 impl<'tcx> QueryDescription for queries::const_eval<'tcx> {
400 fn describe(tcx: TyCtxt, key: ty::ParamEnvAnd<'tcx, (DefId, &'tcx Substs<'tcx>)>) -> String {
401 format!("const-evaluating `{}`", tcx.item_path_str(key.value.0))
405 impl<'tcx> QueryDescription for queries::mir_keys<'tcx> {
406 fn describe(_: TyCtxt, _: CrateNum) -> String {
407 format!("getting a list of all mir_keys")
411 impl<'tcx> QueryDescription for queries::symbol_name<'tcx> {
412 fn describe(_tcx: TyCtxt, instance: ty::Instance<'tcx>) -> String {
413 format!("computing the symbol for `{}`", instance)
417 impl<'tcx> QueryDescription for queries::describe_def<'tcx> {
418 fn describe(_: TyCtxt, _: DefId) -> String {
423 impl<'tcx> QueryDescription for queries::def_span<'tcx> {
424 fn describe(_: TyCtxt, _: DefId) -> String {
430 impl<'tcx> QueryDescription for queries::stability<'tcx> {
431 fn describe(_: TyCtxt, _: DefId) -> String {
436 impl<'tcx> QueryDescription for queries::deprecation<'tcx> {
437 fn describe(_: TyCtxt, _: DefId) -> String {
442 impl<'tcx> QueryDescription for queries::item_attrs<'tcx> {
443 fn describe(_: TyCtxt, _: DefId) -> String {
448 impl<'tcx> QueryDescription for queries::is_exported_symbol<'tcx> {
449 fn describe(_: TyCtxt, _: DefId) -> String {
450 bug!("is_exported_symbol")
454 impl<'tcx> QueryDescription for queries::fn_arg_names<'tcx> {
455 fn describe(_: TyCtxt, _: DefId) -> String {
460 impl<'tcx> QueryDescription for queries::impl_parent<'tcx> {
461 fn describe(_: TyCtxt, _: DefId) -> String {
466 impl<'tcx> QueryDescription for queries::trait_of_item<'tcx> {
467 fn describe(_: TyCtxt, _: DefId) -> String {
468 bug!("trait_of_item")
472 impl<'tcx> QueryDescription for queries::item_body_nested_bodies<'tcx> {
473 fn describe(tcx: TyCtxt, def_id: DefId) -> String {
474 format!("nested item bodies of `{}`", tcx.item_path_str(def_id))
478 impl<'tcx> QueryDescription for queries::const_is_rvalue_promotable_to_static<'tcx> {
479 fn describe(tcx: TyCtxt, def_id: DefId) -> String {
480 format!("const checking if rvalue is promotable to static `{}`",
481 tcx.item_path_str(def_id))
485 impl<'tcx> QueryDescription for queries::is_mir_available<'tcx> {
486 fn describe(tcx: TyCtxt, def_id: DefId) -> String {
487 format!("checking if item is mir available: `{}`",
488 tcx.item_path_str(def_id))
492 impl<'tcx> QueryDescription for queries::trait_impls_of<'tcx> {
493 fn describe(tcx: TyCtxt, def_id: DefId) -> String {
494 format!("trait impls of `{}`", tcx.item_path_str(def_id))
498 impl<'tcx> QueryDescription for queries::is_object_safe<'tcx> {
499 fn describe(tcx: TyCtxt, def_id: DefId) -> String {
500 format!("determine object safety of trait `{}`", tcx.item_path_str(def_id))
504 impl<'tcx> QueryDescription for queries::is_const_fn<'tcx> {
505 fn describe(tcx: TyCtxt, def_id: DefId) -> String {
506 format!("checking if item is const fn: `{}`", tcx.item_path_str(def_id))
510 impl<'tcx> QueryDescription for queries::dylib_dependency_formats<'tcx> {
511 fn describe(_: TyCtxt, _: DefId) -> String {
512 "dylib dependency formats of crate".to_string()
516 impl<'tcx> QueryDescription for queries::is_allocator<'tcx> {
517 fn describe(_: TyCtxt, _: DefId) -> String {
518 "checking if the crate is_allocator".to_string()
522 impl<'tcx> QueryDescription for queries::is_panic_runtime<'tcx> {
523 fn describe(_: TyCtxt, _: DefId) -> String {
524 "checking if the crate is_panic_runtime".to_string()
528 impl<'tcx> QueryDescription for queries::is_compiler_builtins<'tcx> {
529 fn describe(_: TyCtxt, _: DefId) -> String {
530 "checking if the crate is_compiler_builtins".to_string()
534 impl<'tcx> QueryDescription for queries::has_global_allocator<'tcx> {
535 fn describe(_: TyCtxt, _: DefId) -> String {
536 "checking if the crate has_global_allocator".to_string()
540 impl<'tcx> QueryDescription for queries::extern_crate<'tcx> {
541 fn describe(_: TyCtxt, _: DefId) -> String {
542 "getting crate's ExternCrateData".to_string()
546 impl<'tcx> QueryDescription for queries::lint_levels<'tcx> {
547 fn describe(_tcx: TyCtxt, _: CrateNum) -> String {
548 format!("computing the lint levels for items in this crate")
552 impl<'tcx> QueryDescription for queries::specializes<'tcx> {
553 fn describe(_tcx: TyCtxt, _: (DefId, DefId)) -> String {
554 format!("computing whether impls specialize one another")
558 impl<'tcx> QueryDescription for queries::in_scope_traits<'tcx> {
559 fn describe(_tcx: TyCtxt, _: HirId) -> String {
560 format!("fetching the traits in scope at a particular ast node")
564 impl<'tcx> QueryDescription for queries::module_exports<'tcx> {
565 fn describe(_tcx: TyCtxt, _: HirId) -> String {
566 format!("fetching the exported items for a module")
570 // If enabled, send a message to the profile-queries thread
571 macro_rules! profq_msg {
572 ($tcx:expr, $msg:expr) => {
573 if cfg!(debug_assertions) {
574 if $tcx.sess.profile_queries() {
581 // If enabled, format a key using its debug string, which can be
582 // expensive to compute (in terms of time).
583 macro_rules! profq_key {
584 ($tcx:expr, $key:expr) => {
585 if cfg!(debug_assertions) {
586 if $tcx.sess.profile_queries_and_keys() {
587 Some(format!("{:?}", $key))
593 macro_rules! define_maps {
596 [$($modifiers:tt)*] $name:ident: $node:ident($K:ty) -> $V:ty,)*) => {
599 input: ($(([$($modifiers)*] [$($attr)*] [$name]))*)
602 impl<$tcx> Maps<$tcx> {
603 pub fn new(providers: IndexVec<CrateNum, Providers<$tcx>>)
607 query_stack: RefCell::new(vec![]),
608 $($name: RefCell::new(QueryMap::new())),*
614 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
615 pub enum Query<$tcx> {
616 $($(#[$attr])* $name($K)),*
620 #[derive(Clone, Debug, PartialEq, Eq)]
622 $($name(Option<String>)),*
625 impl<$tcx> Query<$tcx> {
626 pub fn describe(&self, tcx: TyCtxt) -> String {
627 let (r, name) = match *self {
628 $(Query::$name(key) => {
629 (queries::$name::describe(tcx, key), stringify!($name))
632 if tcx.sess.verbose() {
633 format!("{} [{}]", r, name)
641 use std::marker::PhantomData;
643 $(#[allow(bad_style)]
644 pub struct $name<$tcx> {
645 data: PhantomData<&$tcx ()>
649 $(impl<$tcx> QueryConfig for queries::$name<$tcx> {
654 impl<'a, $tcx, 'lcx> queries::$name<$tcx> {
656 fn to_dep_node(tcx: TyCtxt<'a, $tcx, 'lcx>, key: &$K) -> DepNode {
657 use dep_graph::DepConstructor::*;
659 DepNode::new(tcx, $node(*key))
662 fn try_get_with<F, R>(tcx: TyCtxt<'a, $tcx, 'lcx>,
666 -> Result<R, CycleError<'a, $tcx>>
667 where F: FnOnce(&$V) -> R
669 debug!("ty::queries::{}::try_get_with(key={:?}, span={:?})",
675 ProfileQueriesMsg::QueryBegin(
677 QueryMsg::$name(profq_key!(tcx, key))
681 if let Some(value) = tcx.maps.$name.borrow().map.get(&key) {
682 if let Some(ref d) = value.diagnostics {
683 if !d.emitted_diagnostics.get() {
684 d.emitted_diagnostics.set(true);
685 let handle = tcx.sess.diagnostic();
686 for diagnostic in d.diagnostics.iter() {
687 DiagnosticBuilder::new_diagnostic(handle, diagnostic.clone())
692 profq_msg!(tcx, ProfileQueriesMsg::CacheHit);
693 tcx.dep_graph.read_index(value.index);
694 return Ok(f(&value.value));
696 // else, we are going to run the provider:
697 profq_msg!(tcx, ProfileQueriesMsg::ProviderBegin);
699 // FIXME(eddyb) Get more valid Span's on queries.
700 // def_span guard is necessary to prevent a recursive loop,
701 // default_span calls def_span query internally.
702 if span == DUMMY_SP && stringify!($name) != "def_span" {
703 span = key.default_span(tcx)
706 let res = tcx.cycle_check(span, Query::$name(key), || {
707 let dep_node = Self::to_dep_node(tcx, &key);
709 tcx.sess.diagnostic().track_diagnostics(|| {
710 if dep_node.kind.is_anon() {
711 tcx.dep_graph.with_anon_task(dep_node.kind, || {
712 let provider = tcx.maps.providers[key.map_crate()].$name;
713 provider(tcx.global_tcx(), key)
716 fn run_provider<'a, 'tcx, 'lcx>(tcx: TyCtxt<'a, 'tcx, 'lcx>,
719 let provider = tcx.maps.providers[key.map_crate()].$name;
720 provider(tcx.global_tcx(), key)
723 tcx.dep_graph.with_task(dep_node, tcx, key, run_provider)
727 profq_msg!(tcx, ProfileQueriesMsg::ProviderEnd);
728 let ((result, dep_node_index), diagnostics) = res;
730 tcx.dep_graph.read_index(dep_node_index);
732 let value = QueryValue {
734 index: dep_node_index,
735 diagnostics: if diagnostics.len() == 0 {
738 Some(Box::new(QueryDiagnostics {
740 emitted_diagnostics: Cell::new(true),
754 pub fn try_get(tcx: TyCtxt<'a, $tcx, 'lcx>, span: Span, key: $K)
755 -> Result<$V, DiagnosticBuilder<'a>> {
756 match Self::try_get_with(tcx, span, key, Clone::clone) {
758 Err(e) => Err(tcx.report_cycle(e)),
762 pub fn force(tcx: TyCtxt<'a, $tcx, 'lcx>, span: Span, key: $K) {
763 // Ignore dependencies, since we not reading the computed value
764 let _task = tcx.dep_graph.in_ignore();
766 match Self::try_get_with(tcx, span, key, |_| ()) {
768 Err(e) => tcx.report_cycle(e).emit(),
773 #[derive(Copy, Clone)]
774 pub struct TyCtxtAt<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
775 pub tcx: TyCtxt<'a, 'gcx, 'tcx>,
779 impl<'a, 'gcx, 'tcx> Deref for TyCtxtAt<'a, 'gcx, 'tcx> {
780 type Target = TyCtxt<'a, 'gcx, 'tcx>;
781 fn deref(&self) -> &Self::Target {
786 impl<'a, $tcx, 'lcx> TyCtxt<'a, $tcx, 'lcx> {
787 /// Return a transparent wrapper for `TyCtxt` which uses
788 /// `span` as the location of queries performed through it.
789 pub fn at(self, span: Span) -> TyCtxtAt<'a, $tcx, 'lcx> {
797 pub fn $name(self, key: $K) -> $V {
798 self.at(DUMMY_SP).$name(key)
802 impl<'a, $tcx, 'lcx> TyCtxtAt<'a, $tcx, 'lcx> {
804 pub fn $name(self, key: $K) -> $V {
805 queries::$name::try_get(self.tcx, self.span, key).unwrap_or_else(|mut e| {
807 Value::from_cycle_error(self.global_tcx())
812 define_provider_struct! {
814 input: ($(([$($modifiers)*] [$name] [$K] [$V]))*),
818 impl<$tcx> Copy for Providers<$tcx> {}
819 impl<$tcx> Clone for Providers<$tcx> {
820 fn clone(&self) -> Self { *self }
825 macro_rules! define_map_struct {
828 input: $input:tt) => {
839 output: ($($output:tt)*)) => {
840 pub struct Maps<$tcx> {
841 providers: IndexVec<CrateNum, Providers<$tcx>>,
842 query_stack: RefCell<Vec<(Span, Query<$tcx>)>>,
847 // Field recognized and ready to shift into the output
849 ready: ([$($pub:tt)*] [$($attr:tt)*] [$name:ident]),
851 output: ($($output:tt)*)) => {
856 $(#[$attr])* $($pub)* $name: RefCell<QueryMap<queries::$name<$tcx>>>,)
860 // No modifiers left? This is a private item.
862 input: (([] $attrs:tt $name:tt) $($input:tt)*),
863 output: $output:tt) => {
866 ready: ([] $attrs $name),
872 // Skip other modifiers
874 input: (([$other_modifier:tt $($modifiers:tt)*] $($fields:tt)*) $($input:tt)*),
875 output: $output:tt) => {
878 input: (([$($modifiers)*] $($fields)*) $($input)*),
884 macro_rules! define_provider_struct {
886 (tcx: $tcx:tt, input: $input:tt) => {
887 define_provider_struct! {
897 output: ($(([$name:ident] [$K:ty] [$R:ty]))*)) => {
898 pub struct Providers<$tcx> {
899 $(pub $name: for<'a> fn(TyCtxt<'a, $tcx, $tcx>, $K) -> $R,)*
902 impl<$tcx> Default for Providers<$tcx> {
903 fn default() -> Self {
904 $(fn $name<'a, $tcx>(_: TyCtxt<'a, $tcx, $tcx>, key: $K) -> $R {
905 bug!("tcx.maps.{}({:?}) unsupported by its crate",
906 stringify!($name), key);
908 Providers { $($name),* }
913 // Something ready to shift:
915 ready: ($name:tt $K:tt $V:tt),
917 output: ($($output:tt)*)) => {
918 define_provider_struct! {
921 output: ($($output)* ($name $K $V))
925 // Regular queries produce a `V` only.
927 input: (([] $name:tt $K:tt $V:tt) $($input:tt)*),
928 output: $output:tt) => {
929 define_provider_struct! {
931 ready: ($name $K $V),
939 input: (([$other_modifier:tt $($modifiers:tt)*] $($fields:tt)*) $($input:tt)*),
940 output: $output:tt) => {
941 define_provider_struct! {
943 input: (([$($modifiers)*] $($fields)*) $($input)*),
949 // Each of these maps also corresponds to a method on a
950 // `Provider` trait for requesting a value of that type,
951 // and a method on `Maps` itself for doing that in a
952 // a way that memoizes and does dep-graph tracking,
953 // wrapping around the actual chain of providers that
954 // the driver creates (using several `rustc_*` crates).
955 define_maps! { <'tcx>
956 /// Records the type of every item.
957 [] type_of: TypeOfItem(DefId) -> Ty<'tcx>,
959 /// Maps from the def-id of an item (trait/struct/enum/fn) to its
960 /// associated generics and predicates.
961 [] generics_of: GenericsOfItem(DefId) -> &'tcx ty::Generics,
962 [] predicates_of: PredicatesOfItem(DefId) -> ty::GenericPredicates<'tcx>,
964 /// Maps from the def-id of a trait to the list of
965 /// super-predicates. This is a subset of the full list of
966 /// predicates. We store these in a separate map because we must
967 /// evaluate them even during type conversion, often before the
968 /// full predicates are available (note that supertraits have
969 /// additional acyclicity requirements).
970 [] super_predicates_of: SuperPredicatesOfItem(DefId) -> ty::GenericPredicates<'tcx>,
972 /// To avoid cycles within the predicates of a single item we compute
973 /// per-type-parameter predicates for resolving `T::AssocTy`.
974 [] type_param_predicates: type_param_predicates((DefId, DefId))
975 -> ty::GenericPredicates<'tcx>,
977 [] trait_def: TraitDefOfItem(DefId) -> &'tcx ty::TraitDef,
978 [] adt_def: AdtDefOfItem(DefId) -> &'tcx ty::AdtDef,
979 [] adt_destructor: AdtDestructor(DefId) -> Option<ty::Destructor>,
980 [] adt_sized_constraint: SizedConstraint(DefId) -> &'tcx [Ty<'tcx>],
981 [] adt_dtorck_constraint: DtorckConstraint(DefId) -> ty::DtorckConstraint<'tcx>,
983 /// True if this is a const fn
984 [] is_const_fn: IsConstFn(DefId) -> bool,
986 /// True if this is a foreign item (i.e., linked via `extern { ... }`).
987 [] is_foreign_item: IsForeignItem(DefId) -> bool,
989 /// True if this is a default impl (aka impl Foo for ..)
990 [] is_default_impl: IsDefaultImpl(DefId) -> bool,
992 /// Get a map with the variance of every item; use `item_variance`
994 [] crate_variances: crate_variances(CrateNum) -> Rc<ty::CrateVariancesMap>,
996 /// Maps from def-id of a type or region parameter to its
997 /// (inferred) variance.
998 [] variances_of: ItemVariances(DefId) -> Rc<Vec<ty::Variance>>,
1000 /// Maps from an impl/trait def-id to a list of the def-ids of its items
1001 [] associated_item_def_ids: AssociatedItemDefIds(DefId) -> Rc<Vec<DefId>>,
1003 /// Maps from a trait item to the trait item "descriptor"
1004 [] associated_item: AssociatedItems(DefId) -> ty::AssociatedItem,
1006 [] impl_trait_ref: ImplTraitRef(DefId) -> Option<ty::TraitRef<'tcx>>,
1007 [] impl_polarity: ImplPolarity(DefId) -> hir::ImplPolarity,
1009 /// Maps a DefId of a type to a list of its inherent impls.
1010 /// Contains implementations of methods that are inherent to a type.
1011 /// Methods in these implementations don't need to be exported.
1012 [] inherent_impls: InherentImpls(DefId) -> Rc<Vec<DefId>>,
1014 /// Set of all the def-ids in this crate that have MIR associated with
1015 /// them. This includes all the body owners, but also things like struct
1017 [] mir_keys: mir_keys(CrateNum) -> Rc<DefIdSet>,
1019 /// Maps DefId's that have an associated Mir to the result
1020 /// of the MIR qualify_consts pass. The actual meaning of
1021 /// the value isn't known except to the pass itself.
1022 [] mir_const_qualif: MirConstQualif(DefId) -> u8,
1024 /// Fetch the MIR for a given def-id up till the point where it is
1025 /// ready for const evaluation.
1027 /// See the README for the `mir` module for details.
1028 [] mir_const: MirConst(DefId) -> &'tcx Steal<mir::Mir<'tcx>>,
1030 [] mir_validated: MirValidated(DefId) -> &'tcx Steal<mir::Mir<'tcx>>,
1032 /// MIR after our optimization passes have run. This is MIR that is ready
1033 /// for trans. This is also the only query that can fetch non-local MIR, at present.
1034 [] optimized_mir: MirOptimized(DefId) -> &'tcx mir::Mir<'tcx>,
1036 /// Type of each closure. The def ID is the ID of the
1037 /// expression defining the closure.
1038 [] closure_kind: ClosureKind(DefId) -> ty::ClosureKind,
1040 /// The signature of functions and closures.
1041 [] fn_sig: FnSignature(DefId) -> ty::PolyFnSig<'tcx>,
1043 /// Records the signature of each generator. The def ID is the ID of the
1044 /// expression defining the closure.
1045 [] generator_sig: GenSignature(DefId) -> Option<ty::PolyGenSig<'tcx>>,
1047 /// Caches CoerceUnsized kinds for impls on custom types.
1048 [] coerce_unsized_info: CoerceUnsizedInfo(DefId)
1049 -> ty::adjustment::CoerceUnsizedInfo,
1051 [] typeck_item_bodies: typeck_item_bodies_dep_node(CrateNum) -> CompileResult,
1053 [] typeck_tables_of: TypeckTables(DefId) -> &'tcx ty::TypeckTables<'tcx>,
1055 [] has_typeck_tables: HasTypeckTables(DefId) -> bool,
1057 [] coherent_trait: coherent_trait_dep_node((CrateNum, DefId)) -> (),
1059 [] borrowck: BorrowCheck(DefId) -> (),
1060 // FIXME: shouldn't this return a `Result<(), BorrowckErrors>` instead?
1061 [] mir_borrowck: MirBorrowCheck(DefId) -> (),
1063 /// Gets a complete map from all types to their inherent impls.
1064 /// Not meant to be used directly outside of coherence.
1065 /// (Defined only for LOCAL_CRATE)
1066 [] crate_inherent_impls: crate_inherent_impls_dep_node(CrateNum) -> CrateInherentImpls,
1068 /// Checks all types in the krate for overlap in their inherent impls. Reports errors.
1069 /// Not meant to be used directly outside of coherence.
1070 /// (Defined only for LOCAL_CRATE)
1071 [] crate_inherent_impls_overlap_check: inherent_impls_overlap_check_dep_node(CrateNum) -> (),
1073 /// Results of evaluating const items or constants embedded in
1074 /// other items (such as enum variant explicit discriminants).
1075 [] const_eval: const_eval_dep_node(ty::ParamEnvAnd<'tcx, (DefId, &'tcx Substs<'tcx>)>)
1076 -> const_val::EvalResult<'tcx>,
1078 /// Performs the privacy check and computes "access levels".
1079 [] privacy_access_levels: PrivacyAccessLevels(CrateNum) -> Rc<AccessLevels>,
1081 [] reachable_set: reachability_dep_node(CrateNum) -> Rc<NodeSet>,
1083 /// Per-function `RegionMaps`. The `DefId` should be the owner-def-id for the fn body;
1084 /// in the case of closures or "inline" expressions, this will be redirected to the enclosing
1086 [] region_maps: RegionMaps(DefId) -> Rc<RegionMaps>,
1088 [] mir_shims: mir_shim_dep_node(ty::InstanceDef<'tcx>) -> &'tcx mir::Mir<'tcx>,
1090 [] def_symbol_name: SymbolName(DefId) -> ty::SymbolName,
1091 [] symbol_name: symbol_name_dep_node(ty::Instance<'tcx>) -> ty::SymbolName,
1093 [] describe_def: DescribeDef(DefId) -> Option<Def>,
1094 [] def_span: DefSpan(DefId) -> Span,
1095 [] stability: Stability(DefId) -> Option<attr::Stability>,
1096 [] deprecation: Deprecation(DefId) -> Option<attr::Deprecation>,
1097 [] item_attrs: ItemAttrs(DefId) -> Rc<[ast::Attribute]>,
1098 [] fn_arg_names: FnArgNames(DefId) -> Vec<ast::Name>,
1099 [] impl_parent: ImplParent(DefId) -> Option<DefId>,
1100 [] trait_of_item: TraitOfItem(DefId) -> Option<DefId>,
1101 [] is_exported_symbol: IsExportedSymbol(DefId) -> bool,
1102 [] item_body_nested_bodies: ItemBodyNestedBodies(DefId) -> Rc<BTreeMap<hir::BodyId, hir::Body>>,
1103 [] const_is_rvalue_promotable_to_static: ConstIsRvaluePromotableToStatic(DefId) -> bool,
1104 [] is_mir_available: IsMirAvailable(DefId) -> bool,
1106 [] trait_impls_of: TraitImpls(DefId) -> Rc<ty::trait_def::TraitImpls>,
1107 [] specialization_graph_of: SpecializationGraph(DefId) -> Rc<specialization_graph::Graph>,
1108 [] is_object_safe: ObjectSafety(DefId) -> bool,
1110 // Get the ParameterEnvironment for a given item; this environment
1111 // will be in "user-facing" mode, meaning that it is suitabe for
1112 // type-checking etc, and it does not normalize specializable
1113 // associated types. This is almost always what you want,
1114 // unless you are doing MIR optimizations, in which case you
1115 // might want to use `reveal_all()` method to change modes.
1116 [] param_env: ParamEnv(DefId) -> ty::ParamEnv<'tcx>,
1118 // Trait selection queries. These are best used by invoking `ty.moves_by_default()`,
1119 // `ty.is_copy()`, etc, since that will prune the environment where possible.
1120 [] is_copy_raw: is_copy_dep_node(ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> bool,
1121 [] is_sized_raw: is_sized_dep_node(ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> bool,
1122 [] is_freeze_raw: is_freeze_dep_node(ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> bool,
1123 [] needs_drop_raw: needs_drop_dep_node(ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> bool,
1124 [] layout_raw: layout_dep_node(ty::ParamEnvAnd<'tcx, Ty<'tcx>>)
1125 -> Result<&'tcx Layout, LayoutError<'tcx>>,
1127 [] dylib_dependency_formats: DylibDepFormats(DefId)
1128 -> Rc<Vec<(CrateNum, LinkagePreference)>>,
1130 [] is_allocator: IsAllocator(DefId) -> bool,
1131 [] is_panic_runtime: IsPanicRuntime(DefId) -> bool,
1132 [] is_compiler_builtins: IsCompilerBuiltins(DefId) -> bool,
1133 [] has_global_allocator: HasGlobalAllocator(DefId) -> bool,
1135 [] extern_crate: ExternCrate(DefId) -> Rc<Option<ExternCrate>>,
1137 [] lint_levels: lint_levels(CrateNum) -> Rc<lint::LintLevelMap>,
1139 [] specializes: specializes_node((DefId, DefId)) -> bool,
1140 [] in_scope_traits: InScopeTraits(HirId) -> Option<Rc<Vec<TraitCandidate>>>,
1141 [] module_exports: ModuleExports(HirId) -> Option<Rc<Vec<Export>>>,
1144 fn type_param_predicates<'tcx>((item_id, param_id): (DefId, DefId)) -> DepConstructor<'tcx> {
1145 DepConstructor::TypeParamPredicates {
1151 fn coherent_trait_dep_node<'tcx>((_, def_id): (CrateNum, DefId)) -> DepConstructor<'tcx> {
1152 DepConstructor::CoherenceCheckTrait(def_id)
1155 fn crate_inherent_impls_dep_node<'tcx>(_: CrateNum) -> DepConstructor<'tcx> {
1156 DepConstructor::Coherence
1159 fn inherent_impls_overlap_check_dep_node<'tcx>(_: CrateNum) -> DepConstructor<'tcx> {
1160 DepConstructor::CoherenceInherentImplOverlapCheck
1163 fn reachability_dep_node<'tcx>(_: CrateNum) -> DepConstructor<'tcx> {
1164 DepConstructor::Reachability
1167 fn mir_shim_dep_node<'tcx>(instance_def: ty::InstanceDef<'tcx>) -> DepConstructor<'tcx> {
1168 DepConstructor::MirShim {
1173 fn symbol_name_dep_node<'tcx>(instance: ty::Instance<'tcx>) -> DepConstructor<'tcx> {
1174 DepConstructor::InstanceSymbolName { instance }
1177 fn typeck_item_bodies_dep_node<'tcx>(_: CrateNum) -> DepConstructor<'tcx> {
1178 DepConstructor::TypeckBodiesKrate
1181 fn const_eval_dep_node<'tcx>(_: ty::ParamEnvAnd<'tcx, (DefId, &'tcx Substs<'tcx>)>)
1182 -> DepConstructor<'tcx> {
1183 DepConstructor::ConstEval
1186 fn mir_keys<'tcx>(_: CrateNum) -> DepConstructor<'tcx> {
1187 DepConstructor::MirKeys
1190 fn crate_variances<'tcx>(_: CrateNum) -> DepConstructor<'tcx> {
1191 DepConstructor::CrateVariances
1194 fn is_copy_dep_node<'tcx>(_: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> DepConstructor<'tcx> {
1195 DepConstructor::IsCopy
1198 fn is_sized_dep_node<'tcx>(_: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> DepConstructor<'tcx> {
1199 DepConstructor::IsSized
1202 fn is_freeze_dep_node<'tcx>(_: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> DepConstructor<'tcx> {
1203 DepConstructor::IsFreeze
1206 fn needs_drop_dep_node<'tcx>(_: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> DepConstructor<'tcx> {
1207 DepConstructor::NeedsDrop
1210 fn layout_dep_node<'tcx>(_: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> DepConstructor<'tcx> {
1211 DepConstructor::Layout
1214 fn lint_levels<'tcx>(_: CrateNum) -> DepConstructor<'tcx> {
1215 DepConstructor::LintLevels
1218 fn specializes_node<'tcx>((a, b): (DefId, DefId)) -> DepConstructor<'tcx> {
1219 DepConstructor::Specializes { impl1: a, impl2: b }