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};
18 use middle::const_val;
19 use middle::cstore::{ExternCrate, LinkagePreference, NativeLibrary};
20 use middle::cstore::NativeLibraryKind;
21 use middle::privacy::AccessLevels;
24 use mir::transform::{MirSuite, MirPassIndex};
25 use session::CompileResult;
26 use traits::specialization_graph;
27 use ty::{self, CrateInherentImpls, Ty, TyCtxt};
28 use ty::layout::{Layout, LayoutError};
31 use ty::subst::Substs;
32 use ty::fast_reject::SimplifiedType;
33 use util::nodemap::{DefIdSet, NodeSet};
34 use util::common::{profq_msg, ProfileQueriesMsg};
36 use rustc_data_structures::indexed_set::IdxSetBuf;
37 use rustc_back::PanicStrategy;
38 use rustc_data_structures::indexed_vec::IndexVec;
39 use rustc_data_structures::fx::FxHashMap;
40 use std::cell::{RefCell, RefMut, Cell};
43 use std::marker::PhantomData;
45 use std::collections::BTreeMap;
48 use syntax_pos::{Span, DUMMY_SP};
51 use syntax::symbol::Symbol;
53 pub trait Key: Clone + Hash + Eq + Debug {
54 fn map_crate(&self) -> CrateNum;
55 fn default_span(&self, tcx: TyCtxt) -> Span;
58 impl<'tcx> Key for ty::InstanceDef<'tcx> {
59 fn map_crate(&self) -> CrateNum {
63 fn default_span(&self, tcx: TyCtxt) -> Span {
64 tcx.def_span(self.def_id())
68 impl<'tcx> Key for ty::Instance<'tcx> {
69 fn map_crate(&self) -> CrateNum {
73 fn default_span(&self, tcx: TyCtxt) -> Span {
74 tcx.def_span(self.def_id())
78 impl Key for CrateNum {
79 fn map_crate(&self) -> CrateNum {
82 fn default_span(&self, _: TyCtxt) -> Span {
88 fn map_crate(&self) -> CrateNum {
91 fn default_span(&self, _tcx: TyCtxt) -> Span {
97 fn map_crate(&self) -> CrateNum {
100 fn default_span(&self, tcx: TyCtxt) -> Span {
105 impl Key for (DefId, DefId) {
106 fn map_crate(&self) -> CrateNum {
109 fn default_span(&self, tcx: TyCtxt) -> Span {
110 self.1.default_span(tcx)
114 impl Key for (CrateNum, DefId) {
115 fn map_crate(&self) -> CrateNum {
118 fn default_span(&self, tcx: TyCtxt) -> Span {
119 self.1.default_span(tcx)
123 impl Key for (DefId, SimplifiedType) {
124 fn map_crate(&self) -> CrateNum {
127 fn default_span(&self, tcx: TyCtxt) -> Span {
128 self.0.default_span(tcx)
132 impl<'tcx> Key for (DefId, &'tcx Substs<'tcx>) {
133 fn map_crate(&self) -> CrateNum {
136 fn default_span(&self, tcx: TyCtxt) -> Span {
137 self.0.default_span(tcx)
141 impl Key for (MirSuite, DefId) {
142 fn map_crate(&self) -> CrateNum {
145 fn default_span(&self, tcx: TyCtxt) -> Span {
146 self.1.default_span(tcx)
150 impl Key for (MirSuite, MirPassIndex, DefId) {
151 fn map_crate(&self) -> CrateNum {
154 fn default_span(&self, tcx: TyCtxt) -> Span {
155 self.2.default_span(tcx)
159 impl<'tcx, T: Clone + Hash + Eq + Debug> Key for ty::ParamEnvAnd<'tcx, T> {
160 fn map_crate(&self) -> CrateNum {
163 fn default_span(&self, _: TyCtxt) -> Span {
168 trait Value<'tcx>: Sized {
169 fn from_cycle_error<'a>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Self;
172 impl<'tcx, T> Value<'tcx> for T {
173 default fn from_cycle_error<'a>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> T {
174 tcx.sess.abort_if_errors();
175 bug!("Value::from_cycle_error called without errors");
179 impl<'tcx, T: Default> Value<'tcx> for T {
180 default fn from_cycle_error<'a>(_: TyCtxt<'a, 'tcx, 'tcx>) -> T {
185 impl<'tcx> Value<'tcx> for Ty<'tcx> {
186 fn from_cycle_error<'a>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Ty<'tcx> {
191 impl<'tcx> Value<'tcx> for ty::DtorckConstraint<'tcx> {
192 fn from_cycle_error<'a>(_: TyCtxt<'a, 'tcx, 'tcx>) -> Self {
197 impl<'tcx> Value<'tcx> for ty::SymbolName {
198 fn from_cycle_error<'a>(_: TyCtxt<'a, 'tcx, 'tcx>) -> Self {
199 ty::SymbolName { name: Symbol::intern("<error>").as_str() }
203 struct QueryMap<D: QueryDescription> {
204 phantom: PhantomData<D>,
205 map: FxHashMap<D::Key, QueryValue<D::Value>>,
208 struct QueryValue<T> {
211 diagnostics: Option<Box<QueryDiagnostics>>,
214 struct QueryDiagnostics {
215 diagnostics: Vec<Diagnostic>,
216 emitted_diagnostics: Cell<bool>,
219 impl<M: QueryDescription> QueryMap<M> {
220 fn new() -> QueryMap<M> {
222 phantom: PhantomData,
228 struct CycleError<'a, 'tcx: 'a> {
230 cycle: RefMut<'a, [(Span, Query<'tcx>)]>,
233 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
234 fn report_cycle(self, CycleError { span, cycle }: CycleError)
235 -> DiagnosticBuilder<'a>
237 // Subtle: release the refcell lock before invoking `describe()`
238 // below by dropping `cycle`.
239 let stack = cycle.to_vec();
242 assert!(!stack.is_empty());
244 // Disable naming impls with types in this path, since that
245 // sometimes cycles itself, leading to extra cycle errors.
246 // (And cycle errors around impls tend to occur during the
247 // collect/coherence phases anyhow.)
248 item_path::with_forced_impl_filename_line(|| {
250 struct_span_err!(self.sess, span, E0391,
251 "unsupported cyclic reference between types/traits detected");
252 err.span_label(span, "cyclic reference");
254 err.span_note(stack[0].0, &format!("the cycle begins when {}...",
255 stack[0].1.describe(self)));
257 for &(span, ref query) in &stack[1..] {
258 err.span_note(span, &format!("...which then requires {}...",
259 query.describe(self)));
262 err.note(&format!("...which then again requires {}, completing the cycle.",
263 stack[0].1.describe(self)));
269 fn cycle_check<F, R>(self, span: Span, query: Query<'gcx>, compute: F)
270 -> Result<R, CycleError<'a, 'gcx>>
271 where F: FnOnce() -> R
274 let mut stack = self.maps.query_stack.borrow_mut();
275 if let Some((i, _)) = stack.iter().enumerate().rev()
276 .find(|&(_, &(_, ref q))| *q == query) {
277 return Err(CycleError {
279 cycle: RefMut::map(stack, |stack| &mut stack[i..])
282 stack.push((span, query));
285 let result = compute();
287 self.maps.query_stack.borrow_mut().pop();
293 pub trait QueryConfig {
294 type Key: Eq + Hash + Clone;
298 trait QueryDescription: QueryConfig {
299 fn describe(tcx: TyCtxt, key: Self::Key) -> String;
302 impl<M: QueryConfig<Key=DefId>> QueryDescription for M {
303 default fn describe(tcx: TyCtxt, def_id: DefId) -> String {
304 format!("processing `{}`", tcx.item_path_str(def_id))
308 impl<'tcx> QueryDescription for queries::is_copy_raw<'tcx> {
309 fn describe(_tcx: TyCtxt, env: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> String {
310 format!("computing whether `{}` is `Copy`", env.value)
314 impl<'tcx> QueryDescription for queries::is_sized_raw<'tcx> {
315 fn describe(_tcx: TyCtxt, env: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> String {
316 format!("computing whether `{}` is `Sized`", env.value)
320 impl<'tcx> QueryDescription for queries::is_freeze_raw<'tcx> {
321 fn describe(_tcx: TyCtxt, env: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> String {
322 format!("computing whether `{}` is freeze", env.value)
326 impl<'tcx> QueryDescription for queries::needs_drop_raw<'tcx> {
327 fn describe(_tcx: TyCtxt, env: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> String {
328 format!("computing whether `{}` needs drop", env.value)
332 impl<'tcx> QueryDescription for queries::layout_raw<'tcx> {
333 fn describe(_tcx: TyCtxt, env: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> String {
334 format!("computing layout of `{}`", env.value)
338 impl<'tcx> QueryDescription for queries::super_predicates_of<'tcx> {
339 fn describe(tcx: TyCtxt, def_id: DefId) -> String {
340 format!("computing the supertraits of `{}`",
341 tcx.item_path_str(def_id))
345 impl<'tcx> QueryDescription for queries::type_param_predicates<'tcx> {
346 fn describe(tcx: TyCtxt, (_, def_id): (DefId, DefId)) -> String {
347 let id = tcx.hir.as_local_node_id(def_id).unwrap();
348 format!("computing the bounds for type parameter `{}`",
349 tcx.hir.ty_param_name(id))
353 impl<'tcx> QueryDescription for queries::coherent_trait<'tcx> {
354 fn describe(tcx: TyCtxt, (_, def_id): (CrateNum, DefId)) -> String {
355 format!("coherence checking all impls of trait `{}`",
356 tcx.item_path_str(def_id))
360 impl<'tcx> QueryDescription for queries::crate_inherent_impls<'tcx> {
361 fn describe(_: TyCtxt, k: CrateNum) -> String {
362 format!("all inherent impls defined in crate `{:?}`", k)
366 impl<'tcx> QueryDescription for queries::crate_inherent_impls_overlap_check<'tcx> {
367 fn describe(_: TyCtxt, _: CrateNum) -> String {
368 format!("check for overlap between inherent impls defined in this crate")
372 impl<'tcx> QueryDescription for queries::crate_variances<'tcx> {
373 fn describe(_tcx: TyCtxt, _: CrateNum) -> String {
374 format!("computing the variances for items in this crate")
378 impl<'tcx> QueryDescription for queries::mir_shims<'tcx> {
379 fn describe(tcx: TyCtxt, def: ty::InstanceDef<'tcx>) -> String {
380 format!("generating MIR shim for `{}`",
381 tcx.item_path_str(def.def_id()))
385 impl<'tcx> QueryDescription for queries::privacy_access_levels<'tcx> {
386 fn describe(_: TyCtxt, _: CrateNum) -> String {
387 format!("privacy access levels")
391 impl<'tcx> QueryDescription for queries::typeck_item_bodies<'tcx> {
392 fn describe(_: TyCtxt, _: CrateNum) -> String {
393 format!("type-checking all item bodies")
397 impl<'tcx> QueryDescription for queries::reachable_set<'tcx> {
398 fn describe(_: TyCtxt, _: CrateNum) -> String {
399 format!("reachability")
403 impl<'tcx> QueryDescription for queries::const_eval<'tcx> {
404 fn describe(tcx: TyCtxt, key: ty::ParamEnvAnd<'tcx, (DefId, &'tcx Substs<'tcx>)>) -> String {
405 format!("const-evaluating `{}`", tcx.item_path_str(key.value.0))
409 impl<'tcx> QueryDescription for queries::mir_keys<'tcx> {
410 fn describe(_: TyCtxt, _: CrateNum) -> String {
411 format!("getting a list of all mir_keys")
415 impl<'tcx> QueryDescription for queries::symbol_name<'tcx> {
416 fn describe(_tcx: TyCtxt, instance: ty::Instance<'tcx>) -> String {
417 format!("computing the symbol for `{}`", instance)
421 impl<'tcx> QueryDescription for queries::describe_def<'tcx> {
422 fn describe(_: TyCtxt, _: DefId) -> String {
427 impl<'tcx> QueryDescription for queries::def_span<'tcx> {
428 fn describe(_: TyCtxt, _: DefId) -> String {
434 impl<'tcx> QueryDescription for queries::stability<'tcx> {
435 fn describe(_: TyCtxt, _: DefId) -> String {
440 impl<'tcx> QueryDescription for queries::deprecation<'tcx> {
441 fn describe(_: TyCtxt, _: DefId) -> String {
446 impl<'tcx> QueryDescription for queries::item_attrs<'tcx> {
447 fn describe(_: TyCtxt, _: DefId) -> String {
452 impl<'tcx> QueryDescription for queries::is_exported_symbol<'tcx> {
453 fn describe(_: TyCtxt, _: DefId) -> String {
454 bug!("is_exported_symbol")
458 impl<'tcx> QueryDescription for queries::fn_arg_names<'tcx> {
459 fn describe(_: TyCtxt, _: DefId) -> String {
464 impl<'tcx> QueryDescription for queries::impl_parent<'tcx> {
465 fn describe(_: TyCtxt, _: DefId) -> String {
470 impl<'tcx> QueryDescription for queries::trait_of_item<'tcx> {
471 fn describe(_: TyCtxt, _: DefId) -> String {
472 bug!("trait_of_item")
476 impl<'tcx> QueryDescription for queries::item_body_nested_bodies<'tcx> {
477 fn describe(tcx: TyCtxt, def_id: DefId) -> String {
478 format!("nested item bodies of `{}`", tcx.item_path_str(def_id))
482 impl<'tcx> QueryDescription for queries::const_is_rvalue_promotable_to_static<'tcx> {
483 fn describe(tcx: TyCtxt, def_id: DefId) -> String {
484 format!("const checking if rvalue is promotable to static `{}`",
485 tcx.item_path_str(def_id))
489 impl<'tcx> QueryDescription for queries::is_mir_available<'tcx> {
490 fn describe(tcx: TyCtxt, def_id: DefId) -> String {
491 format!("checking if item is mir available: `{}`",
492 tcx.item_path_str(def_id))
496 impl<'tcx> QueryDescription for queries::trait_impls_of<'tcx> {
497 fn describe(tcx: TyCtxt, def_id: DefId) -> String {
498 format!("trait impls of `{}`", tcx.item_path_str(def_id))
502 impl<'tcx> QueryDescription for queries::is_object_safe<'tcx> {
503 fn describe(tcx: TyCtxt, def_id: DefId) -> String {
504 format!("determine object safety of trait `{}`", tcx.item_path_str(def_id))
508 impl<'tcx> QueryDescription for queries::is_const_fn<'tcx> {
509 fn describe(tcx: TyCtxt, def_id: DefId) -> String {
510 format!("checking if item is const fn: `{}`", tcx.item_path_str(def_id))
514 impl<'tcx> QueryDescription for queries::dylib_dependency_formats<'tcx> {
515 fn describe(_: TyCtxt, _: CrateNum) -> String {
516 "dylib dependency formats of crate".to_string()
520 impl<'tcx> QueryDescription for queries::is_panic_runtime<'tcx> {
521 fn describe(_: TyCtxt, _: CrateNum) -> String {
522 "checking if the crate is_panic_runtime".to_string()
526 impl<'tcx> QueryDescription for queries::is_compiler_builtins<'tcx> {
527 fn describe(_: TyCtxt, _: CrateNum) -> String {
528 "checking if the crate is_compiler_builtins".to_string()
532 impl<'tcx> QueryDescription for queries::has_global_allocator<'tcx> {
533 fn describe(_: TyCtxt, _: CrateNum) -> String {
534 "checking if the crate has_global_allocator".to_string()
538 impl<'tcx> QueryDescription for queries::extern_crate<'tcx> {
539 fn describe(_: TyCtxt, _: DefId) -> String {
540 "getting crate's ExternCrateData".to_string()
544 impl<'tcx> QueryDescription for queries::lint_levels<'tcx> {
545 fn describe(_tcx: TyCtxt, _: CrateNum) -> String {
546 format!("computing the lint levels for items in this crate")
550 impl<'tcx> QueryDescription for queries::specializes<'tcx> {
551 fn describe(_tcx: TyCtxt, _: (DefId, DefId)) -> String {
552 format!("computing whether impls specialize one another")
556 impl<'tcx> QueryDescription for queries::in_scope_traits<'tcx> {
557 fn describe(_tcx: TyCtxt, _: HirId) -> String {
558 format!("fetching the traits in scope at a particular ast node")
562 impl<'tcx> QueryDescription for queries::module_exports<'tcx> {
563 fn describe(_tcx: TyCtxt, _: HirId) -> String {
564 format!("fetching the exported items for a module")
568 impl<'tcx> QueryDescription for queries::is_no_builtins<'tcx> {
569 fn describe(_tcx: TyCtxt, _: CrateNum) -> String {
570 format!("test whether a crate has #![no_builtins]")
574 impl<'tcx> QueryDescription for queries::panic_strategy<'tcx> {
575 fn describe(_tcx: TyCtxt, _: CrateNum) -> String {
576 format!("query a crate's configured panic strategy")
580 impl<'tcx> QueryDescription for queries::is_profiler_runtime<'tcx> {
581 fn describe(_tcx: TyCtxt, _: CrateNum) -> String {
582 format!("query a crate is #![profiler_runtime]")
586 impl<'tcx> QueryDescription for queries::is_sanitizer_runtime<'tcx> {
587 fn describe(_tcx: TyCtxt, _: CrateNum) -> String {
588 format!("query a crate is #![sanitizer_runtime]")
592 impl<'tcx> QueryDescription for queries::exported_symbols<'tcx> {
593 fn describe(_tcx: TyCtxt, _: CrateNum) -> String {
594 format!("looking up the exported symbols of a crate")
598 impl<'tcx> QueryDescription for queries::native_libraries<'tcx> {
599 fn describe(_tcx: TyCtxt, _: CrateNum) -> String {
600 format!("looking up the native libraries of a linked crate")
604 impl<'tcx> QueryDescription for queries::plugin_registrar_fn<'tcx> {
605 fn describe(_tcx: TyCtxt, _: CrateNum) -> String {
606 format!("looking up the plugin registrar for a crate")
610 impl<'tcx> QueryDescription for queries::derive_registrar_fn<'tcx> {
611 fn describe(_tcx: TyCtxt, _: CrateNum) -> String {
612 format!("looking up the derive registrar for a crate")
616 impl<'tcx> QueryDescription for queries::crate_disambiguator<'tcx> {
617 fn describe(_tcx: TyCtxt, _: CrateNum) -> String {
618 format!("looking up the disambiguator a crate")
622 impl<'tcx> QueryDescription for queries::crate_hash<'tcx> {
623 fn describe(_tcx: TyCtxt, _: CrateNum) -> String {
624 format!("looking up the hash a crate")
628 impl<'tcx> QueryDescription for queries::original_crate_name<'tcx> {
629 fn describe(_tcx: TyCtxt, _: CrateNum) -> String {
630 format!("looking up the original name a crate")
634 impl<'tcx> QueryDescription for queries::implementations_of_trait<'tcx> {
635 fn describe(_tcx: TyCtxt, _: (CrateNum, DefId)) -> String {
636 format!("looking up implementations of a trait in a crate")
640 impl<'tcx> QueryDescription for queries::all_trait_implementations<'tcx> {
641 fn describe(_tcx: TyCtxt, _: CrateNum) -> String {
642 format!("looking up all (?) trait implementations")
646 impl<'tcx> QueryDescription for queries::link_args<'tcx> {
647 fn describe(_tcx: TyCtxt, _: CrateNum) -> String {
648 format!("looking up link arguments for a crate")
652 // If enabled, send a message to the profile-queries thread
653 macro_rules! profq_msg {
654 ($tcx:expr, $msg:expr) => {
655 if cfg!(debug_assertions) {
656 if $tcx.sess.profile_queries() {
663 // If enabled, format a key using its debug string, which can be
664 // expensive to compute (in terms of time).
665 macro_rules! profq_key {
666 ($tcx:expr, $key:expr) => {
667 if cfg!(debug_assertions) {
668 if $tcx.sess.profile_queries_and_keys() {
669 Some(format!("{:?}", $key))
675 macro_rules! define_maps {
678 [$($modifiers:tt)*] fn $name:ident: $node:ident($K:ty) -> $V:ty,)*) => {
681 input: ($(([$($modifiers)*] [$($attr)*] [$name]))*)
684 impl<$tcx> Maps<$tcx> {
685 pub fn new(providers: IndexVec<CrateNum, Providers<$tcx>>)
689 query_stack: RefCell::new(vec![]),
690 $($name: RefCell::new(QueryMap::new())),*
696 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
697 pub enum Query<$tcx> {
698 $($(#[$attr])* $name($K)),*
702 #[derive(Clone, Debug, PartialEq, Eq)]
704 $($name(Option<String>)),*
707 impl<$tcx> Query<$tcx> {
708 pub fn describe(&self, tcx: TyCtxt) -> String {
709 let (r, name) = match *self {
710 $(Query::$name(key) => {
711 (queries::$name::describe(tcx, key), stringify!($name))
714 if tcx.sess.verbose() {
715 format!("{} [{}]", r, name)
723 use std::marker::PhantomData;
725 $(#[allow(bad_style)]
726 pub struct $name<$tcx> {
727 data: PhantomData<&$tcx ()>
731 $(impl<$tcx> QueryConfig for queries::$name<$tcx> {
736 impl<'a, $tcx, 'lcx> queries::$name<$tcx> {
738 fn to_dep_node(tcx: TyCtxt<'a, $tcx, 'lcx>, key: &$K) -> DepNode {
739 use dep_graph::DepConstructor::*;
741 DepNode::new(tcx, $node(*key))
744 fn try_get_with<F, R>(tcx: TyCtxt<'a, $tcx, 'lcx>,
748 -> Result<R, CycleError<'a, $tcx>>
749 where F: FnOnce(&$V) -> R
751 debug!("ty::queries::{}::try_get_with(key={:?}, span={:?})",
757 ProfileQueriesMsg::QueryBegin(
759 QueryMsg::$name(profq_key!(tcx, key))
763 if let Some(value) = tcx.maps.$name.borrow().map.get(&key) {
764 if let Some(ref d) = value.diagnostics {
765 if !d.emitted_diagnostics.get() {
766 d.emitted_diagnostics.set(true);
767 let handle = tcx.sess.diagnostic();
768 for diagnostic in d.diagnostics.iter() {
769 DiagnosticBuilder::new_diagnostic(handle, diagnostic.clone())
774 profq_msg!(tcx, ProfileQueriesMsg::CacheHit);
775 tcx.dep_graph.read_index(value.index);
776 return Ok(f(&value.value));
778 // else, we are going to run the provider:
779 profq_msg!(tcx, ProfileQueriesMsg::ProviderBegin);
781 // FIXME(eddyb) Get more valid Span's on queries.
782 // def_span guard is necessary to prevent a recursive loop,
783 // default_span calls def_span query internally.
784 if span == DUMMY_SP && stringify!($name) != "def_span" {
785 span = key.default_span(tcx)
788 let res = tcx.cycle_check(span, Query::$name(key), || {
789 let dep_node = Self::to_dep_node(tcx, &key);
791 tcx.sess.diagnostic().track_diagnostics(|| {
792 if dep_node.kind.is_anon() {
793 tcx.dep_graph.with_anon_task(dep_node.kind, || {
794 let provider = tcx.maps.providers[key.map_crate()].$name;
795 provider(tcx.global_tcx(), key)
798 fn run_provider<'a, 'tcx, 'lcx>(tcx: TyCtxt<'a, 'tcx, 'lcx>,
801 let provider = tcx.maps.providers[key.map_crate()].$name;
802 provider(tcx.global_tcx(), key)
805 tcx.dep_graph.with_task(dep_node, tcx, key, run_provider)
809 profq_msg!(tcx, ProfileQueriesMsg::ProviderEnd);
810 let ((result, dep_node_index), diagnostics) = res;
812 tcx.dep_graph.read_index(dep_node_index);
814 let value = QueryValue {
816 index: dep_node_index,
817 diagnostics: if diagnostics.len() == 0 {
820 Some(Box::new(QueryDiagnostics {
822 emitted_diagnostics: Cell::new(true),
836 pub fn try_get(tcx: TyCtxt<'a, $tcx, 'lcx>, span: Span, key: $K)
837 -> Result<$V, DiagnosticBuilder<'a>> {
838 match Self::try_get_with(tcx, span, key, Clone::clone) {
840 Err(e) => Err(tcx.report_cycle(e)),
844 pub fn force(tcx: TyCtxt<'a, $tcx, 'lcx>, span: Span, key: $K) {
845 // Ignore dependencies, since we not reading the computed value
846 let _task = tcx.dep_graph.in_ignore();
848 match Self::try_get_with(tcx, span, key, |_| ()) {
850 Err(e) => tcx.report_cycle(e).emit(),
855 #[derive(Copy, Clone)]
856 pub struct TyCtxtAt<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
857 pub tcx: TyCtxt<'a, 'gcx, 'tcx>,
861 impl<'a, 'gcx, 'tcx> Deref for TyCtxtAt<'a, 'gcx, 'tcx> {
862 type Target = TyCtxt<'a, 'gcx, 'tcx>;
863 fn deref(&self) -> &Self::Target {
868 impl<'a, $tcx, 'lcx> TyCtxt<'a, $tcx, 'lcx> {
869 /// Return a transparent wrapper for `TyCtxt` which uses
870 /// `span` as the location of queries performed through it.
871 pub fn at(self, span: Span) -> TyCtxtAt<'a, $tcx, 'lcx> {
879 pub fn $name(self, key: $K) -> $V {
880 self.at(DUMMY_SP).$name(key)
884 impl<'a, $tcx, 'lcx> TyCtxtAt<'a, $tcx, 'lcx> {
886 pub fn $name(self, key: $K) -> $V {
887 queries::$name::try_get(self.tcx, self.span, key).unwrap_or_else(|mut e| {
889 Value::from_cycle_error(self.global_tcx())
894 define_provider_struct! {
896 input: ($(([$($modifiers)*] [$name] [$K] [$V]))*),
900 impl<$tcx> Copy for Providers<$tcx> {}
901 impl<$tcx> Clone for Providers<$tcx> {
902 fn clone(&self) -> Self { *self }
907 macro_rules! define_map_struct {
910 input: $input:tt) => {
921 output: ($($output:tt)*)) => {
922 pub struct Maps<$tcx> {
923 providers: IndexVec<CrateNum, Providers<$tcx>>,
924 query_stack: RefCell<Vec<(Span, Query<$tcx>)>>,
929 // Field recognized and ready to shift into the output
931 ready: ([$($pub:tt)*] [$($attr:tt)*] [$name:ident]),
933 output: ($($output:tt)*)) => {
938 $(#[$attr])* $($pub)* $name: RefCell<QueryMap<queries::$name<$tcx>>>,)
942 // No modifiers left? This is a private item.
944 input: (([] $attrs:tt $name:tt) $($input:tt)*),
945 output: $output:tt) => {
948 ready: ([] $attrs $name),
954 // Skip other modifiers
956 input: (([$other_modifier:tt $($modifiers:tt)*] $($fields:tt)*) $($input:tt)*),
957 output: $output:tt) => {
960 input: (([$($modifiers)*] $($fields)*) $($input)*),
966 macro_rules! define_provider_struct {
968 (tcx: $tcx:tt, input: $input:tt) => {
969 define_provider_struct! {
979 output: ($(([$name:ident] [$K:ty] [$R:ty]))*)) => {
980 pub struct Providers<$tcx> {
981 $(pub $name: for<'a> fn(TyCtxt<'a, $tcx, $tcx>, $K) -> $R,)*
984 impl<$tcx> Default for Providers<$tcx> {
985 fn default() -> Self {
986 $(fn $name<'a, $tcx>(_: TyCtxt<'a, $tcx, $tcx>, key: $K) -> $R {
987 bug!("tcx.maps.{}({:?}) unsupported by its crate",
988 stringify!($name), key);
990 Providers { $($name),* }
995 // Something ready to shift:
997 ready: ($name:tt $K:tt $V:tt),
999 output: ($($output:tt)*)) => {
1000 define_provider_struct! {
1003 output: ($($output)* ($name $K $V))
1007 // Regular queries produce a `V` only.
1009 input: (([] $name:tt $K:tt $V:tt) $($input:tt)*),
1010 output: $output:tt) => {
1011 define_provider_struct! {
1013 ready: ($name $K $V),
1014 input: ($($input)*),
1021 input: (([$other_modifier:tt $($modifiers:tt)*] $($fields:tt)*) $($input:tt)*),
1022 output: $output:tt) => {
1023 define_provider_struct! {
1025 input: (([$($modifiers)*] $($fields)*) $($input)*),
1031 // Each of these maps also corresponds to a method on a
1032 // `Provider` trait for requesting a value of that type,
1033 // and a method on `Maps` itself for doing that in a
1034 // a way that memoizes and does dep-graph tracking,
1035 // wrapping around the actual chain of providers that
1036 // the driver creates (using several `rustc_*` crates).
1037 define_maps! { <'tcx>
1038 /// Records the type of every item.
1039 [] fn type_of: TypeOfItem(DefId) -> Ty<'tcx>,
1041 /// Maps from the def-id of an item (trait/struct/enum/fn) to its
1042 /// associated generics and predicates.
1043 [] fn generics_of: GenericsOfItem(DefId) -> &'tcx ty::Generics,
1044 [] fn predicates_of: PredicatesOfItem(DefId) -> ty::GenericPredicates<'tcx>,
1046 /// Maps from the def-id of a trait to the list of
1047 /// super-predicates. This is a subset of the full list of
1048 /// predicates. We store these in a separate map because we must
1049 /// evaluate them even during type conversion, often before the
1050 /// full predicates are available (note that supertraits have
1051 /// additional acyclicity requirements).
1052 [] fn super_predicates_of: SuperPredicatesOfItem(DefId) -> ty::GenericPredicates<'tcx>,
1054 /// To avoid cycles within the predicates of a single item we compute
1055 /// per-type-parameter predicates for resolving `T::AssocTy`.
1056 [] fn type_param_predicates: type_param_predicates((DefId, DefId))
1057 -> ty::GenericPredicates<'tcx>,
1059 [] fn trait_def: TraitDefOfItem(DefId) -> &'tcx ty::TraitDef,
1060 [] fn adt_def: AdtDefOfItem(DefId) -> &'tcx ty::AdtDef,
1061 [] fn adt_destructor: AdtDestructor(DefId) -> Option<ty::Destructor>,
1062 [] fn adt_sized_constraint: SizedConstraint(DefId) -> &'tcx [Ty<'tcx>],
1063 [] fn adt_dtorck_constraint: DtorckConstraint(DefId) -> ty::DtorckConstraint<'tcx>,
1065 /// True if this is a const fn
1066 [] fn is_const_fn: IsConstFn(DefId) -> bool,
1068 /// True if this is a foreign item (i.e., linked via `extern { ... }`).
1069 [] fn is_foreign_item: IsForeignItem(DefId) -> bool,
1071 /// True if this is a default impl (aka impl Foo for ..)
1072 [] fn is_default_impl: IsDefaultImpl(DefId) -> bool,
1074 /// Get a map with the variance of every item; use `item_variance`
1076 [] fn crate_variances: crate_variances(CrateNum) -> Rc<ty::CrateVariancesMap>,
1078 /// Maps from def-id of a type or region parameter to its
1079 /// (inferred) variance.
1080 [] fn variances_of: ItemVariances(DefId) -> Rc<Vec<ty::Variance>>,
1082 /// Maps from an impl/trait def-id to a list of the def-ids of its items
1083 [] fn associated_item_def_ids: AssociatedItemDefIds(DefId) -> Rc<Vec<DefId>>,
1085 /// Maps from a trait item to the trait item "descriptor"
1086 [] fn associated_item: AssociatedItems(DefId) -> ty::AssociatedItem,
1088 [] fn impl_trait_ref: ImplTraitRef(DefId) -> Option<ty::TraitRef<'tcx>>,
1089 [] fn impl_polarity: ImplPolarity(DefId) -> hir::ImplPolarity,
1091 /// Maps a DefId of a type to a list of its inherent impls.
1092 /// Contains implementations of methods that are inherent to a type.
1093 /// Methods in these implementations don't need to be exported.
1094 [] fn inherent_impls: InherentImpls(DefId) -> Rc<Vec<DefId>>,
1096 /// Set of all the def-ids in this crate that have MIR associated with
1097 /// them. This includes all the body owners, but also things like struct
1099 [] fn mir_keys: mir_keys(CrateNum) -> Rc<DefIdSet>,
1101 /// Maps DefId's that have an associated Mir to the result
1102 /// of the MIR qualify_consts pass. The actual meaning of
1103 /// the value isn't known except to the pass itself.
1104 [] fn mir_const_qualif: MirConstQualif(DefId) -> (u8, Rc<IdxSetBuf<mir::Local>>),
1106 /// Fetch the MIR for a given def-id up till the point where it is
1107 /// ready for const evaluation.
1109 /// See the README for the `mir` module for details.
1110 [] fn mir_const: MirConst(DefId) -> &'tcx Steal<mir::Mir<'tcx>>,
1112 [] fn mir_validated: MirValidated(DefId) -> &'tcx Steal<mir::Mir<'tcx>>,
1114 /// MIR after our optimization passes have run. This is MIR that is ready
1115 /// for trans. This is also the only query that can fetch non-local MIR, at present.
1116 [] fn optimized_mir: MirOptimized(DefId) -> &'tcx mir::Mir<'tcx>,
1118 /// Type of each closure. The def ID is the ID of the
1119 /// expression defining the closure.
1120 [] fn closure_kind: ClosureKind(DefId) -> ty::ClosureKind,
1122 /// The signature of functions and closures.
1123 [] fn fn_sig: FnSignature(DefId) -> ty::PolyFnSig<'tcx>,
1125 /// Records the signature of each generator. The def ID is the ID of the
1126 /// expression defining the closure.
1127 [] fn generator_sig: GenSignature(DefId) -> Option<ty::PolyGenSig<'tcx>>,
1129 /// Caches CoerceUnsized kinds for impls on custom types.
1130 [] fn coerce_unsized_info: CoerceUnsizedInfo(DefId)
1131 -> ty::adjustment::CoerceUnsizedInfo,
1133 [] fn typeck_item_bodies: typeck_item_bodies_dep_node(CrateNum) -> CompileResult,
1135 [] fn typeck_tables_of: TypeckTables(DefId) -> &'tcx ty::TypeckTables<'tcx>,
1137 [] fn has_typeck_tables: HasTypeckTables(DefId) -> bool,
1139 [] fn coherent_trait: coherent_trait_dep_node((CrateNum, DefId)) -> (),
1141 [] fn borrowck: BorrowCheck(DefId) -> (),
1142 // FIXME: shouldn't this return a `Result<(), BorrowckErrors>` instead?
1143 [] fn mir_borrowck: MirBorrowCheck(DefId) -> (),
1145 /// Gets a complete map from all types to their inherent impls.
1146 /// Not meant to be used directly outside of coherence.
1147 /// (Defined only for LOCAL_CRATE)
1148 [] fn crate_inherent_impls: crate_inherent_impls_dep_node(CrateNum) -> CrateInherentImpls,
1150 /// Checks all types in the krate for overlap in their inherent impls. Reports errors.
1151 /// Not meant to be used directly outside of coherence.
1152 /// (Defined only for LOCAL_CRATE)
1153 [] fn crate_inherent_impls_overlap_check: inherent_impls_overlap_check_dep_node(CrateNum) -> (),
1155 /// Results of evaluating const items or constants embedded in
1156 /// other items (such as enum variant explicit discriminants).
1157 [] fn const_eval: const_eval_dep_node(ty::ParamEnvAnd<'tcx, (DefId, &'tcx Substs<'tcx>)>)
1158 -> const_val::EvalResult<'tcx>,
1160 /// Performs the privacy check and computes "access levels".
1161 [] fn privacy_access_levels: PrivacyAccessLevels(CrateNum) -> Rc<AccessLevels>,
1163 [] fn reachable_set: reachability_dep_node(CrateNum) -> Rc<NodeSet>,
1165 /// Per-body `region::ScopeTree`. The `DefId` should be the owner-def-id for the body;
1166 /// in the case of closures, this will be redirected to the enclosing function.
1167 [] fn region_scope_tree: RegionScopeTree(DefId) -> Rc<region::ScopeTree>,
1169 [] fn mir_shims: mir_shim_dep_node(ty::InstanceDef<'tcx>) -> &'tcx mir::Mir<'tcx>,
1171 [] fn def_symbol_name: SymbolName(DefId) -> ty::SymbolName,
1172 [] fn symbol_name: symbol_name_dep_node(ty::Instance<'tcx>) -> ty::SymbolName,
1174 [] fn describe_def: DescribeDef(DefId) -> Option<Def>,
1175 [] fn def_span: DefSpan(DefId) -> Span,
1176 [] fn stability: Stability(DefId) -> Option<attr::Stability>,
1177 [] fn deprecation: Deprecation(DefId) -> Option<attr::Deprecation>,
1178 [] fn item_attrs: ItemAttrs(DefId) -> Rc<[ast::Attribute]>,
1179 [] fn fn_arg_names: FnArgNames(DefId) -> Vec<ast::Name>,
1180 [] fn impl_parent: ImplParent(DefId) -> Option<DefId>,
1181 [] fn trait_of_item: TraitOfItem(DefId) -> Option<DefId>,
1182 [] fn is_exported_symbol: IsExportedSymbol(DefId) -> bool,
1183 [] fn item_body_nested_bodies: ItemBodyNestedBodies(DefId)
1184 -> Rc<BTreeMap<hir::BodyId, hir::Body>>,
1185 [] fn const_is_rvalue_promotable_to_static: ConstIsRvaluePromotableToStatic(DefId) -> bool,
1186 [] fn is_mir_available: IsMirAvailable(DefId) -> bool,
1188 [] fn trait_impls_of: TraitImpls(DefId) -> Rc<ty::trait_def::TraitImpls>,
1189 [] fn specialization_graph_of: SpecializationGraph(DefId) -> Rc<specialization_graph::Graph>,
1190 [] fn is_object_safe: ObjectSafety(DefId) -> bool,
1192 // Get the ParameterEnvironment for a given item; this environment
1193 // will be in "user-facing" mode, meaning that it is suitabe for
1194 // type-checking etc, and it does not normalize specializable
1195 // associated types. This is almost always what you want,
1196 // unless you are doing MIR optimizations, in which case you
1197 // might want to use `reveal_all()` method to change modes.
1198 [] fn param_env: ParamEnv(DefId) -> ty::ParamEnv<'tcx>,
1200 // Trait selection queries. These are best used by invoking `ty.moves_by_default()`,
1201 // `ty.is_copy()`, etc, since that will prune the environment where possible.
1202 [] fn is_copy_raw: is_copy_dep_node(ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> bool,
1203 [] fn is_sized_raw: is_sized_dep_node(ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> bool,
1204 [] fn is_freeze_raw: is_freeze_dep_node(ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> bool,
1205 [] fn needs_drop_raw: needs_drop_dep_node(ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> bool,
1206 [] fn layout_raw: layout_dep_node(ty::ParamEnvAnd<'tcx, Ty<'tcx>>)
1207 -> Result<&'tcx Layout, LayoutError<'tcx>>,
1209 [] fn dylib_dependency_formats: DylibDepFormats(CrateNum)
1210 -> Rc<Vec<(CrateNum, LinkagePreference)>>,
1212 [] fn is_panic_runtime: IsPanicRuntime(CrateNum) -> bool,
1213 [] fn is_compiler_builtins: IsCompilerBuiltins(CrateNum) -> bool,
1214 [] fn has_global_allocator: HasGlobalAllocator(CrateNum) -> bool,
1215 [] fn is_sanitizer_runtime: IsSanitizerRuntime(CrateNum) -> bool,
1216 [] fn is_profiler_runtime: IsProfilerRuntime(CrateNum) -> bool,
1217 [] fn panic_strategy: GetPanicStrategy(CrateNum) -> PanicStrategy,
1218 [] fn is_no_builtins: IsNoBuiltins(CrateNum) -> bool,
1220 [] fn extern_crate: ExternCrate(DefId) -> Rc<Option<ExternCrate>>,
1222 [] fn specializes: specializes_node((DefId, DefId)) -> bool,
1223 [] fn in_scope_traits: InScopeTraits(HirId) -> Option<Rc<Vec<TraitCandidate>>>,
1224 [] fn module_exports: ModuleExports(HirId) -> Option<Rc<Vec<Export>>>,
1225 [] fn lint_levels: lint_levels_node(CrateNum) -> Rc<lint::LintLevelMap>,
1227 [] fn impl_defaultness: ImplDefaultness(DefId) -> hir::Defaultness,
1228 [] fn exported_symbols: ExportedSymbols(CrateNum) -> Rc<Vec<DefId>>,
1229 [] fn native_libraries: NativeLibraries(CrateNum) -> Rc<Vec<NativeLibrary>>,
1230 [] fn plugin_registrar_fn: PluginRegistrarFn(CrateNum) -> Option<DefId>,
1231 [] fn derive_registrar_fn: DeriveRegistrarFn(CrateNum) -> Option<DefId>,
1232 [] fn crate_disambiguator: CrateDisambiguator(CrateNum) -> Symbol,
1233 [] fn crate_hash: CrateHash(CrateNum) -> Svh,
1234 [] fn original_crate_name: OriginalCrateName(CrateNum) -> Symbol,
1236 [] fn implementations_of_trait: implementations_of_trait_node((CrateNum, DefId))
1238 [] fn all_trait_implementations: AllTraitImplementations(CrateNum)
1241 [] is_dllimport_foreign_item: IsDllimportForeignItem(DefId) -> bool,
1242 [] is_statically_included_foreign_item: IsStaticallyIncludedForeignItem(DefId) -> bool,
1243 [] native_library_kind: NativeLibraryKind(DefId)
1244 -> Option<NativeLibraryKind>,
1245 [] link_args: link_args_node(CrateNum) -> Rc<Vec<String>>,
1248 fn type_param_predicates<'tcx>((item_id, param_id): (DefId, DefId)) -> DepConstructor<'tcx> {
1249 DepConstructor::TypeParamPredicates {
1255 fn coherent_trait_dep_node<'tcx>((_, def_id): (CrateNum, DefId)) -> DepConstructor<'tcx> {
1256 DepConstructor::CoherenceCheckTrait(def_id)
1259 fn crate_inherent_impls_dep_node<'tcx>(_: CrateNum) -> DepConstructor<'tcx> {
1260 DepConstructor::Coherence
1263 fn inherent_impls_overlap_check_dep_node<'tcx>(_: CrateNum) -> DepConstructor<'tcx> {
1264 DepConstructor::CoherenceInherentImplOverlapCheck
1267 fn reachability_dep_node<'tcx>(_: CrateNum) -> DepConstructor<'tcx> {
1268 DepConstructor::Reachability
1271 fn mir_shim_dep_node<'tcx>(instance_def: ty::InstanceDef<'tcx>) -> DepConstructor<'tcx> {
1272 DepConstructor::MirShim {
1277 fn symbol_name_dep_node<'tcx>(instance: ty::Instance<'tcx>) -> DepConstructor<'tcx> {
1278 DepConstructor::InstanceSymbolName { instance }
1281 fn typeck_item_bodies_dep_node<'tcx>(_: CrateNum) -> DepConstructor<'tcx> {
1282 DepConstructor::TypeckBodiesKrate
1285 fn const_eval_dep_node<'tcx>(_: ty::ParamEnvAnd<'tcx, (DefId, &'tcx Substs<'tcx>)>)
1286 -> DepConstructor<'tcx> {
1287 DepConstructor::ConstEval
1290 fn mir_keys<'tcx>(_: CrateNum) -> DepConstructor<'tcx> {
1291 DepConstructor::MirKeys
1294 fn crate_variances<'tcx>(_: CrateNum) -> DepConstructor<'tcx> {
1295 DepConstructor::CrateVariances
1298 fn is_copy_dep_node<'tcx>(_: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> DepConstructor<'tcx> {
1299 DepConstructor::IsCopy
1302 fn is_sized_dep_node<'tcx>(_: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> DepConstructor<'tcx> {
1303 DepConstructor::IsSized
1306 fn is_freeze_dep_node<'tcx>(_: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> DepConstructor<'tcx> {
1307 DepConstructor::IsFreeze
1310 fn needs_drop_dep_node<'tcx>(_: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> DepConstructor<'tcx> {
1311 DepConstructor::NeedsDrop
1314 fn layout_dep_node<'tcx>(_: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> DepConstructor<'tcx> {
1315 DepConstructor::Layout
1318 fn lint_levels_node<'tcx>(_: CrateNum) -> DepConstructor<'tcx> {
1319 DepConstructor::LintLevels
1322 fn specializes_node<'tcx>((a, b): (DefId, DefId)) -> DepConstructor<'tcx> {
1323 DepConstructor::Specializes { impl1: a, impl2: b }
1326 fn implementations_of_trait_node<'tcx>((krate, trait_id): (CrateNum, DefId))
1327 -> DepConstructor<'tcx>
1329 DepConstructor::ImplementationsOfTrait { krate, trait_id }
1332 fn link_args_node<'tcx>(_: CrateNum) -> DepConstructor<'tcx> {
1333 DepConstructor::LinkArgs