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, DepKind};
21 use middle::privacy::AccessLevels;
23 use middle::region::RegionMaps;
24 use middle::resolve_lifetime::{Region, ObjectLifetimeDefault};
26 use mir::transform::{MirSuite, MirPassIndex};
27 use session::CompileResult;
28 use traits::specialization_graph;
29 use ty::{self, CrateInherentImpls, Ty, TyCtxt};
30 use ty::layout::{Layout, LayoutError};
33 use ty::subst::Substs;
34 use ty::fast_reject::SimplifiedType;
35 use util::nodemap::{DefIdSet, NodeSet};
36 use util::common::{profq_msg, ProfileQueriesMsg};
38 use rustc_data_structures::indexed_set::IdxSetBuf;
39 use rustc_back::PanicStrategy;
40 use rustc_data_structures::indexed_vec::IndexVec;
41 use rustc_data_structures::fx::FxHashMap;
42 use std::cell::{RefCell, RefMut, Cell};
45 use std::marker::PhantomData;
47 use std::collections::BTreeMap;
50 use syntax_pos::{Span, DUMMY_SP};
53 use syntax::symbol::Symbol;
55 pub trait Key: Clone + Hash + Eq + Debug {
56 fn map_crate(&self) -> CrateNum;
57 fn default_span(&self, tcx: TyCtxt) -> Span;
60 impl<'tcx> Key for ty::InstanceDef<'tcx> {
61 fn map_crate(&self) -> CrateNum {
65 fn default_span(&self, tcx: TyCtxt) -> Span {
66 tcx.def_span(self.def_id())
70 impl<'tcx> Key for ty::Instance<'tcx> {
71 fn map_crate(&self) -> CrateNum {
75 fn default_span(&self, tcx: TyCtxt) -> Span {
76 tcx.def_span(self.def_id())
80 impl Key for CrateNum {
81 fn map_crate(&self) -> CrateNum {
84 fn default_span(&self, _: TyCtxt) -> Span {
90 fn map_crate(&self) -> CrateNum {
93 fn default_span(&self, _tcx: TyCtxt) -> Span {
99 fn map_crate(&self) -> CrateNum {
102 fn default_span(&self, tcx: TyCtxt) -> Span {
107 impl Key for (DefId, DefId) {
108 fn map_crate(&self) -> CrateNum {
111 fn default_span(&self, tcx: TyCtxt) -> Span {
112 self.1.default_span(tcx)
116 impl Key for (CrateNum, DefId) {
117 fn map_crate(&self) -> CrateNum {
120 fn default_span(&self, tcx: TyCtxt) -> Span {
121 self.1.default_span(tcx)
125 impl Key for (DefId, SimplifiedType) {
126 fn map_crate(&self) -> CrateNum {
129 fn default_span(&self, tcx: TyCtxt) -> Span {
130 self.0.default_span(tcx)
134 impl<'tcx> Key for (DefId, &'tcx Substs<'tcx>) {
135 fn map_crate(&self) -> CrateNum {
138 fn default_span(&self, tcx: TyCtxt) -> Span {
139 self.0.default_span(tcx)
143 impl Key for (MirSuite, DefId) {
144 fn map_crate(&self) -> CrateNum {
147 fn default_span(&self, tcx: TyCtxt) -> Span {
148 self.1.default_span(tcx)
152 impl Key for (MirSuite, MirPassIndex, DefId) {
153 fn map_crate(&self) -> CrateNum {
156 fn default_span(&self, tcx: TyCtxt) -> Span {
157 self.2.default_span(tcx)
161 impl<'tcx, T: Clone + Hash + Eq + Debug> Key for ty::ParamEnvAnd<'tcx, T> {
162 fn map_crate(&self) -> CrateNum {
165 fn default_span(&self, _: TyCtxt) -> Span {
170 trait Value<'tcx>: Sized {
171 fn from_cycle_error<'a>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Self;
174 impl<'tcx, T> Value<'tcx> for T {
175 default fn from_cycle_error<'a>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> T {
176 tcx.sess.abort_if_errors();
177 bug!("Value::from_cycle_error called without errors");
181 impl<'tcx, T: Default> Value<'tcx> for T {
182 default fn from_cycle_error<'a>(_: TyCtxt<'a, 'tcx, 'tcx>) -> T {
187 impl<'tcx> Value<'tcx> for Ty<'tcx> {
188 fn from_cycle_error<'a>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Ty<'tcx> {
193 impl<'tcx> Value<'tcx> for ty::DtorckConstraint<'tcx> {
194 fn from_cycle_error<'a>(_: TyCtxt<'a, 'tcx, 'tcx>) -> Self {
199 impl<'tcx> Value<'tcx> for ty::SymbolName {
200 fn from_cycle_error<'a>(_: TyCtxt<'a, 'tcx, 'tcx>) -> Self {
201 ty::SymbolName { name: Symbol::intern("<error>").as_str() }
205 struct QueryMap<D: QueryDescription> {
206 phantom: PhantomData<D>,
207 map: FxHashMap<D::Key, QueryValue<D::Value>>,
210 struct QueryValue<T> {
213 diagnostics: Option<Box<QueryDiagnostics>>,
216 struct QueryDiagnostics {
217 diagnostics: Vec<Diagnostic>,
218 emitted_diagnostics: Cell<bool>,
221 impl<M: QueryDescription> QueryMap<M> {
222 fn new() -> QueryMap<M> {
224 phantom: PhantomData,
230 struct CycleError<'a, 'tcx: 'a> {
232 cycle: RefMut<'a, [(Span, Query<'tcx>)]>,
235 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
236 fn report_cycle(self, CycleError { span, cycle }: CycleError)
237 -> DiagnosticBuilder<'a>
239 // Subtle: release the refcell lock before invoking `describe()`
240 // below by dropping `cycle`.
241 let stack = cycle.to_vec();
244 assert!(!stack.is_empty());
246 // Disable naming impls with types in this path, since that
247 // sometimes cycles itself, leading to extra cycle errors.
248 // (And cycle errors around impls tend to occur during the
249 // collect/coherence phases anyhow.)
250 item_path::with_forced_impl_filename_line(|| {
252 struct_span_err!(self.sess, span, E0391,
253 "unsupported cyclic reference between types/traits detected");
254 err.span_label(span, "cyclic reference");
256 err.span_note(stack[0].0, &format!("the cycle begins when {}...",
257 stack[0].1.describe(self)));
259 for &(span, ref query) in &stack[1..] {
260 err.span_note(span, &format!("...which then requires {}...",
261 query.describe(self)));
264 err.note(&format!("...which then again requires {}, completing the cycle.",
265 stack[0].1.describe(self)));
271 fn cycle_check<F, R>(self, span: Span, query: Query<'gcx>, compute: F)
272 -> Result<R, CycleError<'a, 'gcx>>
273 where F: FnOnce() -> R
276 let mut stack = self.maps.query_stack.borrow_mut();
277 if let Some((i, _)) = stack.iter().enumerate().rev()
278 .find(|&(_, &(_, ref q))| *q == query) {
279 return Err(CycleError {
281 cycle: RefMut::map(stack, |stack| &mut stack[i..])
284 stack.push((span, query));
287 let result = compute();
289 self.maps.query_stack.borrow_mut().pop();
295 pub trait QueryConfig {
296 type Key: Eq + Hash + Clone;
300 trait QueryDescription: QueryConfig {
301 fn describe(tcx: TyCtxt, key: Self::Key) -> String;
304 impl<M: QueryConfig<Key=DefId>> QueryDescription for M {
305 default fn describe(tcx: TyCtxt, def_id: DefId) -> String {
306 format!("processing `{}`", tcx.item_path_str(def_id))
310 impl<'tcx> QueryDescription for queries::is_copy_raw<'tcx> {
311 fn describe(_tcx: TyCtxt, env: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> String {
312 format!("computing whether `{}` is `Copy`", env.value)
316 impl<'tcx> QueryDescription for queries::is_sized_raw<'tcx> {
317 fn describe(_tcx: TyCtxt, env: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> String {
318 format!("computing whether `{}` is `Sized`", env.value)
322 impl<'tcx> QueryDescription for queries::is_freeze_raw<'tcx> {
323 fn describe(_tcx: TyCtxt, env: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> String {
324 format!("computing whether `{}` is freeze", env.value)
328 impl<'tcx> QueryDescription for queries::needs_drop_raw<'tcx> {
329 fn describe(_tcx: TyCtxt, env: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> String {
330 format!("computing whether `{}` needs drop", env.value)
334 impl<'tcx> QueryDescription for queries::layout_raw<'tcx> {
335 fn describe(_tcx: TyCtxt, env: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> String {
336 format!("computing layout of `{}`", env.value)
340 impl<'tcx> QueryDescription for queries::super_predicates_of<'tcx> {
341 fn describe(tcx: TyCtxt, def_id: DefId) -> String {
342 format!("computing the supertraits of `{}`",
343 tcx.item_path_str(def_id))
347 impl<'tcx> QueryDescription for queries::type_param_predicates<'tcx> {
348 fn describe(tcx: TyCtxt, (_, def_id): (DefId, DefId)) -> String {
349 let id = tcx.hir.as_local_node_id(def_id).unwrap();
350 format!("computing the bounds for type parameter `{}`",
351 tcx.hir.ty_param_name(id))
355 impl<'tcx> QueryDescription for queries::coherent_trait<'tcx> {
356 fn describe(tcx: TyCtxt, (_, def_id): (CrateNum, DefId)) -> String {
357 format!("coherence checking all impls of trait `{}`",
358 tcx.item_path_str(def_id))
362 impl<'tcx> QueryDescription for queries::crate_inherent_impls<'tcx> {
363 fn describe(_: TyCtxt, k: CrateNum) -> String {
364 format!("all inherent impls defined in crate `{:?}`", k)
368 impl<'tcx> QueryDescription for queries::crate_inherent_impls_overlap_check<'tcx> {
369 fn describe(_: TyCtxt, _: CrateNum) -> String {
370 format!("check for overlap between inherent impls defined in this crate")
374 impl<'tcx> QueryDescription for queries::crate_variances<'tcx> {
375 fn describe(_tcx: TyCtxt, _: CrateNum) -> String {
376 format!("computing the variances for items in this crate")
380 impl<'tcx> QueryDescription for queries::mir_shims<'tcx> {
381 fn describe(tcx: TyCtxt, def: ty::InstanceDef<'tcx>) -> String {
382 format!("generating MIR shim for `{}`",
383 tcx.item_path_str(def.def_id()))
387 impl<'tcx> QueryDescription for queries::privacy_access_levels<'tcx> {
388 fn describe(_: TyCtxt, _: CrateNum) -> String {
389 format!("privacy access levels")
393 impl<'tcx> QueryDescription for queries::typeck_item_bodies<'tcx> {
394 fn describe(_: TyCtxt, _: CrateNum) -> String {
395 format!("type-checking all item bodies")
399 impl<'tcx> QueryDescription for queries::reachable_set<'tcx> {
400 fn describe(_: TyCtxt, _: CrateNum) -> String {
401 format!("reachability")
405 impl<'tcx> QueryDescription for queries::const_eval<'tcx> {
406 fn describe(tcx: TyCtxt, key: ty::ParamEnvAnd<'tcx, (DefId, &'tcx Substs<'tcx>)>) -> String {
407 format!("const-evaluating `{}`", tcx.item_path_str(key.value.0))
411 impl<'tcx> QueryDescription for queries::mir_keys<'tcx> {
412 fn describe(_: TyCtxt, _: CrateNum) -> String {
413 format!("getting a list of all mir_keys")
417 impl<'tcx> QueryDescription for queries::symbol_name<'tcx> {
418 fn describe(_tcx: TyCtxt, instance: ty::Instance<'tcx>) -> String {
419 format!("computing the symbol for `{}`", instance)
423 impl<'tcx> QueryDescription for queries::describe_def<'tcx> {
424 fn describe(_: TyCtxt, _: DefId) -> String {
429 impl<'tcx> QueryDescription for queries::def_span<'tcx> {
430 fn describe(_: TyCtxt, _: DefId) -> String {
436 impl<'tcx> QueryDescription for queries::stability<'tcx> {
437 fn describe(_: TyCtxt, _: DefId) -> String {
442 impl<'tcx> QueryDescription for queries::deprecation<'tcx> {
443 fn describe(_: TyCtxt, _: DefId) -> String {
448 impl<'tcx> QueryDescription for queries::item_attrs<'tcx> {
449 fn describe(_: TyCtxt, _: DefId) -> String {
454 impl<'tcx> QueryDescription for queries::is_exported_symbol<'tcx> {
455 fn describe(_: TyCtxt, _: DefId) -> String {
456 bug!("is_exported_symbol")
460 impl<'tcx> QueryDescription for queries::fn_arg_names<'tcx> {
461 fn describe(_: TyCtxt, _: DefId) -> String {
466 impl<'tcx> QueryDescription for queries::impl_parent<'tcx> {
467 fn describe(_: TyCtxt, _: DefId) -> String {
472 impl<'tcx> QueryDescription for queries::trait_of_item<'tcx> {
473 fn describe(_: TyCtxt, _: DefId) -> String {
474 bug!("trait_of_item")
478 impl<'tcx> QueryDescription for queries::item_body_nested_bodies<'tcx> {
479 fn describe(tcx: TyCtxt, def_id: DefId) -> String {
480 format!("nested item bodies of `{}`", tcx.item_path_str(def_id))
484 impl<'tcx> QueryDescription for queries::const_is_rvalue_promotable_to_static<'tcx> {
485 fn describe(tcx: TyCtxt, def_id: DefId) -> String {
486 format!("const checking if rvalue is promotable to static `{}`",
487 tcx.item_path_str(def_id))
491 impl<'tcx> QueryDescription for queries::is_mir_available<'tcx> {
492 fn describe(tcx: TyCtxt, def_id: DefId) -> String {
493 format!("checking if item is mir available: `{}`",
494 tcx.item_path_str(def_id))
498 impl<'tcx> QueryDescription for queries::trait_impls_of<'tcx> {
499 fn describe(tcx: TyCtxt, def_id: DefId) -> String {
500 format!("trait impls of `{}`", tcx.item_path_str(def_id))
504 impl<'tcx> QueryDescription for queries::is_object_safe<'tcx> {
505 fn describe(tcx: TyCtxt, def_id: DefId) -> String {
506 format!("determine object safety of trait `{}`", tcx.item_path_str(def_id))
510 impl<'tcx> QueryDescription for queries::is_const_fn<'tcx> {
511 fn describe(tcx: TyCtxt, def_id: DefId) -> String {
512 format!("checking if item is const fn: `{}`", tcx.item_path_str(def_id))
516 impl<'tcx> QueryDescription for queries::dylib_dependency_formats<'tcx> {
517 fn describe(_: TyCtxt, _: CrateNum) -> String {
518 "dylib dependency formats of crate".to_string()
522 impl<'tcx> QueryDescription for queries::is_panic_runtime<'tcx> {
523 fn describe(_: TyCtxt, _: CrateNum) -> 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, _: CrateNum) -> 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, _: CrateNum) -> 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 impl<'tcx> QueryDescription for queries::is_no_builtins<'tcx> {
571 fn describe(_tcx: TyCtxt, _: CrateNum) -> String {
572 format!("test whether a crate has #![no_builtins]")
576 impl<'tcx> QueryDescription for queries::panic_strategy<'tcx> {
577 fn describe(_tcx: TyCtxt, _: CrateNum) -> String {
578 format!("query a crate's configured panic strategy")
582 impl<'tcx> QueryDescription for queries::is_profiler_runtime<'tcx> {
583 fn describe(_tcx: TyCtxt, _: CrateNum) -> String {
584 format!("query a crate is #![profiler_runtime]")
588 impl<'tcx> QueryDescription for queries::is_sanitizer_runtime<'tcx> {
589 fn describe(_tcx: TyCtxt, _: CrateNum) -> String {
590 format!("query a crate is #![sanitizer_runtime]")
594 impl<'tcx> QueryDescription for queries::exported_symbols<'tcx> {
595 fn describe(_tcx: TyCtxt, _: CrateNum) -> String {
596 format!("looking up the exported symbols of a crate")
600 impl<'tcx> QueryDescription for queries::native_libraries<'tcx> {
601 fn describe(_tcx: TyCtxt, _: CrateNum) -> String {
602 format!("looking up the native libraries of a linked crate")
606 impl<'tcx> QueryDescription for queries::plugin_registrar_fn<'tcx> {
607 fn describe(_tcx: TyCtxt, _: CrateNum) -> String {
608 format!("looking up the plugin registrar for a crate")
612 impl<'tcx> QueryDescription for queries::derive_registrar_fn<'tcx> {
613 fn describe(_tcx: TyCtxt, _: CrateNum) -> String {
614 format!("looking up the derive registrar for a crate")
618 impl<'tcx> QueryDescription for queries::crate_disambiguator<'tcx> {
619 fn describe(_tcx: TyCtxt, _: CrateNum) -> String {
620 format!("looking up the disambiguator a crate")
624 impl<'tcx> QueryDescription for queries::crate_hash<'tcx> {
625 fn describe(_tcx: TyCtxt, _: CrateNum) -> String {
626 format!("looking up the hash a crate")
630 impl<'tcx> QueryDescription for queries::original_crate_name<'tcx> {
631 fn describe(_tcx: TyCtxt, _: CrateNum) -> String {
632 format!("looking up the original name a crate")
636 impl<'tcx> QueryDescription for queries::implementations_of_trait<'tcx> {
637 fn describe(_tcx: TyCtxt, _: (CrateNum, DefId)) -> String {
638 format!("looking up implementations of a trait in a crate")
642 impl<'tcx> QueryDescription for queries::all_trait_implementations<'tcx> {
643 fn describe(_tcx: TyCtxt, _: CrateNum) -> String {
644 format!("looking up all (?) trait implementations")
648 impl<'tcx> QueryDescription for queries::link_args<'tcx> {
649 fn describe(_tcx: TyCtxt, _: CrateNum) -> String {
650 format!("looking up link arguments for a crate")
654 impl<'tcx> QueryDescription for queries::named_region<'tcx> {
655 fn describe(_tcx: TyCtxt, _: HirId) -> String {
656 format!("fetching info about a named region")
660 impl<'tcx> QueryDescription for queries::is_late_bound<'tcx> {
661 fn describe(_tcx: TyCtxt, _: HirId) -> String {
662 format!("testing whether a lifetime is late bound")
666 impl<'tcx> QueryDescription for queries::object_lifetime_defaults<'tcx> {
667 fn describe(_tcx: TyCtxt, _: HirId) -> String {
668 format!("fetching a list of ObjectLifetimeDefault for a lifetime")
672 impl<'tcx> QueryDescription for queries::dep_kind<'tcx> {
673 fn describe(_tcx: TyCtxt, _: CrateNum) -> String {
674 format!("fetching what a dependency looks like")
678 impl<'tcx> QueryDescription for queries::crate_name<'tcx> {
679 fn describe(_tcx: TyCtxt, _: CrateNum) -> String {
680 format!("fetching what a crate is named")
684 impl<'tcx> QueryDescription for queries::extern_mod_stmt_cnum<'tcx> {
685 fn describe(_tcx: TyCtxt, _: HirId) -> String {
686 format!("looking up the CrateNum for an `extern mod` statement")
690 // If enabled, send a message to the profile-queries thread
691 macro_rules! profq_msg {
692 ($tcx:expr, $msg:expr) => {
693 if cfg!(debug_assertions) {
694 if $tcx.sess.profile_queries() {
701 // If enabled, format a key using its debug string, which can be
702 // expensive to compute (in terms of time).
703 macro_rules! profq_key {
704 ($tcx:expr, $key:expr) => {
705 if cfg!(debug_assertions) {
706 if $tcx.sess.profile_queries_and_keys() {
707 Some(format!("{:?}", $key))
713 macro_rules! define_maps {
716 [$($modifiers:tt)*] fn $name:ident: $node:ident($K:ty) -> $V:ty,)*) => {
719 input: ($(([$($modifiers)*] [$($attr)*] [$name]))*)
722 impl<$tcx> Maps<$tcx> {
723 pub fn new(providers: IndexVec<CrateNum, Providers<$tcx>>)
727 query_stack: RefCell::new(vec![]),
728 $($name: RefCell::new(QueryMap::new())),*
734 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
735 pub enum Query<$tcx> {
736 $($(#[$attr])* $name($K)),*
740 #[derive(Clone, Debug, PartialEq, Eq)]
742 $($name(Option<String>)),*
745 impl<$tcx> Query<$tcx> {
746 pub fn describe(&self, tcx: TyCtxt) -> String {
747 let (r, name) = match *self {
748 $(Query::$name(key) => {
749 (queries::$name::describe(tcx, key), stringify!($name))
752 if tcx.sess.verbose() {
753 format!("{} [{}]", r, name)
761 use std::marker::PhantomData;
763 $(#[allow(bad_style)]
764 pub struct $name<$tcx> {
765 data: PhantomData<&$tcx ()>
769 $(impl<$tcx> QueryConfig for queries::$name<$tcx> {
774 impl<'a, $tcx, 'lcx> queries::$name<$tcx> {
776 fn to_dep_node(tcx: TyCtxt<'a, $tcx, 'lcx>, key: &$K) -> DepNode {
777 use dep_graph::DepConstructor::*;
779 DepNode::new(tcx, $node(*key))
782 fn try_get_with<F, R>(tcx: TyCtxt<'a, $tcx, 'lcx>,
786 -> Result<R, CycleError<'a, $tcx>>
787 where F: FnOnce(&$V) -> R
789 debug!("ty::queries::{}::try_get_with(key={:?}, span={:?})",
795 ProfileQueriesMsg::QueryBegin(
797 QueryMsg::$name(profq_key!(tcx, key))
801 if let Some(value) = tcx.maps.$name.borrow().map.get(&key) {
802 if let Some(ref d) = value.diagnostics {
803 if !d.emitted_diagnostics.get() {
804 d.emitted_diagnostics.set(true);
805 let handle = tcx.sess.diagnostic();
806 for diagnostic in d.diagnostics.iter() {
807 DiagnosticBuilder::new_diagnostic(handle, diagnostic.clone())
812 profq_msg!(tcx, ProfileQueriesMsg::CacheHit);
813 tcx.dep_graph.read_index(value.index);
814 return Ok(f(&value.value));
816 // else, we are going to run the provider:
817 profq_msg!(tcx, ProfileQueriesMsg::ProviderBegin);
819 // FIXME(eddyb) Get more valid Span's on queries.
820 // def_span guard is necessary to prevent a recursive loop,
821 // default_span calls def_span query internally.
822 if span == DUMMY_SP && stringify!($name) != "def_span" {
823 span = key.default_span(tcx)
826 let res = tcx.cycle_check(span, Query::$name(key), || {
827 let dep_node = Self::to_dep_node(tcx, &key);
829 tcx.sess.diagnostic().track_diagnostics(|| {
830 if dep_node.kind.is_anon() {
831 tcx.dep_graph.with_anon_task(dep_node.kind, || {
832 let provider = tcx.maps.providers[key.map_crate()].$name;
833 provider(tcx.global_tcx(), key)
836 fn run_provider<'a, 'tcx, 'lcx>(tcx: TyCtxt<'a, 'tcx, 'lcx>,
839 let provider = tcx.maps.providers[key.map_crate()].$name;
840 provider(tcx.global_tcx(), key)
843 tcx.dep_graph.with_task(dep_node, tcx, key, run_provider)
847 profq_msg!(tcx, ProfileQueriesMsg::ProviderEnd);
848 let ((result, dep_node_index), diagnostics) = res;
850 tcx.dep_graph.read_index(dep_node_index);
852 let value = QueryValue {
854 index: dep_node_index,
855 diagnostics: if diagnostics.len() == 0 {
858 Some(Box::new(QueryDiagnostics {
860 emitted_diagnostics: Cell::new(true),
874 pub fn try_get(tcx: TyCtxt<'a, $tcx, 'lcx>, span: Span, key: $K)
875 -> Result<$V, DiagnosticBuilder<'a>> {
876 match Self::try_get_with(tcx, span, key, Clone::clone) {
878 Err(e) => Err(tcx.report_cycle(e)),
882 pub fn force(tcx: TyCtxt<'a, $tcx, 'lcx>, span: Span, key: $K) {
883 // Ignore dependencies, since we not reading the computed value
884 let _task = tcx.dep_graph.in_ignore();
886 match Self::try_get_with(tcx, span, key, |_| ()) {
888 Err(e) => tcx.report_cycle(e).emit(),
893 #[derive(Copy, Clone)]
894 pub struct TyCtxtAt<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
895 pub tcx: TyCtxt<'a, 'gcx, 'tcx>,
899 impl<'a, 'gcx, 'tcx> Deref for TyCtxtAt<'a, 'gcx, 'tcx> {
900 type Target = TyCtxt<'a, 'gcx, 'tcx>;
901 fn deref(&self) -> &Self::Target {
906 impl<'a, $tcx, 'lcx> TyCtxt<'a, $tcx, 'lcx> {
907 /// Return a transparent wrapper for `TyCtxt` which uses
908 /// `span` as the location of queries performed through it.
909 pub fn at(self, span: Span) -> TyCtxtAt<'a, $tcx, 'lcx> {
917 pub fn $name(self, key: $K) -> $V {
918 self.at(DUMMY_SP).$name(key)
922 impl<'a, $tcx, 'lcx> TyCtxtAt<'a, $tcx, 'lcx> {
924 pub fn $name(self, key: $K) -> $V {
925 queries::$name::try_get(self.tcx, self.span, key).unwrap_or_else(|mut e| {
927 Value::from_cycle_error(self.global_tcx())
932 define_provider_struct! {
934 input: ($(([$($modifiers)*] [$name] [$K] [$V]))*),
938 impl<$tcx> Copy for Providers<$tcx> {}
939 impl<$tcx> Clone for Providers<$tcx> {
940 fn clone(&self) -> Self { *self }
945 macro_rules! define_map_struct {
948 input: $input:tt) => {
959 output: ($($output:tt)*)) => {
960 pub struct Maps<$tcx> {
961 providers: IndexVec<CrateNum, Providers<$tcx>>,
962 query_stack: RefCell<Vec<(Span, Query<$tcx>)>>,
967 // Field recognized and ready to shift into the output
969 ready: ([$($pub:tt)*] [$($attr:tt)*] [$name:ident]),
971 output: ($($output:tt)*)) => {
976 $(#[$attr])* $($pub)* $name: RefCell<QueryMap<queries::$name<$tcx>>>,)
980 // No modifiers left? This is a private item.
982 input: (([] $attrs:tt $name:tt) $($input:tt)*),
983 output: $output:tt) => {
986 ready: ([] $attrs $name),
992 // Skip other modifiers
994 input: (([$other_modifier:tt $($modifiers:tt)*] $($fields:tt)*) $($input:tt)*),
995 output: $output:tt) => {
998 input: (([$($modifiers)*] $($fields)*) $($input)*),
1004 macro_rules! define_provider_struct {
1006 (tcx: $tcx:tt, input: $input:tt) => {
1007 define_provider_struct! {
1017 output: ($(([$name:ident] [$K:ty] [$R:ty]))*)) => {
1018 pub struct Providers<$tcx> {
1019 $(pub $name: for<'a> fn(TyCtxt<'a, $tcx, $tcx>, $K) -> $R,)*
1022 impl<$tcx> Default for Providers<$tcx> {
1023 fn default() -> Self {
1024 $(fn $name<'a, $tcx>(_: TyCtxt<'a, $tcx, $tcx>, key: $K) -> $R {
1025 bug!("tcx.maps.{}({:?}) unsupported by its crate",
1026 stringify!($name), key);
1028 Providers { $($name),* }
1033 // Something ready to shift:
1035 ready: ($name:tt $K:tt $V:tt),
1037 output: ($($output:tt)*)) => {
1038 define_provider_struct! {
1041 output: ($($output)* ($name $K $V))
1045 // Regular queries produce a `V` only.
1047 input: (([] $name:tt $K:tt $V:tt) $($input:tt)*),
1048 output: $output:tt) => {
1049 define_provider_struct! {
1051 ready: ($name $K $V),
1052 input: ($($input)*),
1059 input: (([$other_modifier:tt $($modifiers:tt)*] $($fields:tt)*) $($input:tt)*),
1060 output: $output:tt) => {
1061 define_provider_struct! {
1063 input: (([$($modifiers)*] $($fields)*) $($input)*),
1069 // Each of these maps also corresponds to a method on a
1070 // `Provider` trait for requesting a value of that type,
1071 // and a method on `Maps` itself for doing that in a
1072 // a way that memoizes and does dep-graph tracking,
1073 // wrapping around the actual chain of providers that
1074 // the driver creates (using several `rustc_*` crates).
1075 define_maps! { <'tcx>
1076 /// Records the type of every item.
1077 [] fn type_of: TypeOfItem(DefId) -> Ty<'tcx>,
1079 /// Maps from the def-id of an item (trait/struct/enum/fn) to its
1080 /// associated generics and predicates.
1081 [] fn generics_of: GenericsOfItem(DefId) -> &'tcx ty::Generics,
1082 [] fn predicates_of: PredicatesOfItem(DefId) -> ty::GenericPredicates<'tcx>,
1084 /// Maps from the def-id of a trait to the list of
1085 /// super-predicates. This is a subset of the full list of
1086 /// predicates. We store these in a separate map because we must
1087 /// evaluate them even during type conversion, often before the
1088 /// full predicates are available (note that supertraits have
1089 /// additional acyclicity requirements).
1090 [] fn super_predicates_of: SuperPredicatesOfItem(DefId) -> ty::GenericPredicates<'tcx>,
1092 /// To avoid cycles within the predicates of a single item we compute
1093 /// per-type-parameter predicates for resolving `T::AssocTy`.
1094 [] fn type_param_predicates: type_param_predicates((DefId, DefId))
1095 -> ty::GenericPredicates<'tcx>,
1097 [] fn trait_def: TraitDefOfItem(DefId) -> &'tcx ty::TraitDef,
1098 [] fn adt_def: AdtDefOfItem(DefId) -> &'tcx ty::AdtDef,
1099 [] fn adt_destructor: AdtDestructor(DefId) -> Option<ty::Destructor>,
1100 [] fn adt_sized_constraint: SizedConstraint(DefId) -> &'tcx [Ty<'tcx>],
1101 [] fn adt_dtorck_constraint: DtorckConstraint(DefId) -> ty::DtorckConstraint<'tcx>,
1103 /// True if this is a const fn
1104 [] fn is_const_fn: IsConstFn(DefId) -> bool,
1106 /// True if this is a foreign item (i.e., linked via `extern { ... }`).
1107 [] fn is_foreign_item: IsForeignItem(DefId) -> bool,
1109 /// True if this is a default impl (aka impl Foo for ..)
1110 [] fn is_default_impl: IsDefaultImpl(DefId) -> bool,
1112 /// Get a map with the variance of every item; use `item_variance`
1114 [] fn crate_variances: crate_variances(CrateNum) -> Rc<ty::CrateVariancesMap>,
1116 /// Maps from def-id of a type or region parameter to its
1117 /// (inferred) variance.
1118 [] fn variances_of: ItemVariances(DefId) -> Rc<Vec<ty::Variance>>,
1120 /// Maps from an impl/trait def-id to a list of the def-ids of its items
1121 [] fn associated_item_def_ids: AssociatedItemDefIds(DefId) -> Rc<Vec<DefId>>,
1123 /// Maps from a trait item to the trait item "descriptor"
1124 [] fn associated_item: AssociatedItems(DefId) -> ty::AssociatedItem,
1126 [] fn impl_trait_ref: ImplTraitRef(DefId) -> Option<ty::TraitRef<'tcx>>,
1127 [] fn impl_polarity: ImplPolarity(DefId) -> hir::ImplPolarity,
1129 /// Maps a DefId of a type to a list of its inherent impls.
1130 /// Contains implementations of methods that are inherent to a type.
1131 /// Methods in these implementations don't need to be exported.
1132 [] fn inherent_impls: InherentImpls(DefId) -> Rc<Vec<DefId>>,
1134 /// Set of all the def-ids in this crate that have MIR associated with
1135 /// them. This includes all the body owners, but also things like struct
1137 [] fn mir_keys: mir_keys(CrateNum) -> Rc<DefIdSet>,
1139 /// Maps DefId's that have an associated Mir to the result
1140 /// of the MIR qualify_consts pass. The actual meaning of
1141 /// the value isn't known except to the pass itself.
1142 [] fn mir_const_qualif: MirConstQualif(DefId) -> (u8, Rc<IdxSetBuf<mir::Local>>),
1144 /// Fetch the MIR for a given def-id up till the point where it is
1145 /// ready for const evaluation.
1147 /// See the README for the `mir` module for details.
1148 [] fn mir_const: MirConst(DefId) -> &'tcx Steal<mir::Mir<'tcx>>,
1150 [] fn mir_validated: MirValidated(DefId) -> &'tcx Steal<mir::Mir<'tcx>>,
1152 /// MIR after our optimization passes have run. This is MIR that is ready
1153 /// for trans. This is also the only query that can fetch non-local MIR, at present.
1154 [] fn optimized_mir: MirOptimized(DefId) -> &'tcx mir::Mir<'tcx>,
1156 /// Type of each closure. The def ID is the ID of the
1157 /// expression defining the closure.
1158 [] fn closure_kind: ClosureKind(DefId) -> ty::ClosureKind,
1160 /// The signature of functions and closures.
1161 [] fn fn_sig: FnSignature(DefId) -> ty::PolyFnSig<'tcx>,
1163 /// Records the signature of each generator. The def ID is the ID of the
1164 /// expression defining the closure.
1165 [] fn generator_sig: GenSignature(DefId) -> Option<ty::PolyGenSig<'tcx>>,
1167 /// Caches CoerceUnsized kinds for impls on custom types.
1168 [] fn coerce_unsized_info: CoerceUnsizedInfo(DefId)
1169 -> ty::adjustment::CoerceUnsizedInfo,
1171 [] fn typeck_item_bodies: typeck_item_bodies_dep_node(CrateNum) -> CompileResult,
1173 [] fn typeck_tables_of: TypeckTables(DefId) -> &'tcx ty::TypeckTables<'tcx>,
1175 [] fn has_typeck_tables: HasTypeckTables(DefId) -> bool,
1177 [] fn coherent_trait: coherent_trait_dep_node((CrateNum, DefId)) -> (),
1179 [] fn borrowck: BorrowCheck(DefId) -> (),
1180 // FIXME: shouldn't this return a `Result<(), BorrowckErrors>` instead?
1181 [] fn mir_borrowck: MirBorrowCheck(DefId) -> (),
1183 /// Gets a complete map from all types to their inherent impls.
1184 /// Not meant to be used directly outside of coherence.
1185 /// (Defined only for LOCAL_CRATE)
1186 [] fn crate_inherent_impls: crate_inherent_impls_dep_node(CrateNum) -> CrateInherentImpls,
1188 /// Checks all types in the krate for overlap in their inherent impls. Reports errors.
1189 /// Not meant to be used directly outside of coherence.
1190 /// (Defined only for LOCAL_CRATE)
1191 [] fn crate_inherent_impls_overlap_check: inherent_impls_overlap_check_dep_node(CrateNum) -> (),
1193 /// Results of evaluating const items or constants embedded in
1194 /// other items (such as enum variant explicit discriminants).
1195 [] fn const_eval: const_eval_dep_node(ty::ParamEnvAnd<'tcx, (DefId, &'tcx Substs<'tcx>)>)
1196 -> const_val::EvalResult<'tcx>,
1198 /// Performs the privacy check and computes "access levels".
1199 [] fn privacy_access_levels: PrivacyAccessLevels(CrateNum) -> Rc<AccessLevels>,
1201 [] fn reachable_set: reachability_dep_node(CrateNum) -> Rc<NodeSet>,
1203 /// Per-body `region::ScopeTree`. The `DefId` should be the owner-def-id for the body;
1204 /// in the case of closures, this will be redirected to the enclosing function.
1205 [] fn region_scope_tree: RegionScopeTree(DefId) -> Rc<region::ScopeTree>,
1207 [] fn mir_shims: mir_shim_dep_node(ty::InstanceDef<'tcx>) -> &'tcx mir::Mir<'tcx>,
1209 [] fn def_symbol_name: SymbolName(DefId) -> ty::SymbolName,
1210 [] fn symbol_name: symbol_name_dep_node(ty::Instance<'tcx>) -> ty::SymbolName,
1212 [] fn describe_def: DescribeDef(DefId) -> Option<Def>,
1213 [] fn def_span: DefSpan(DefId) -> Span,
1214 [] fn stability: Stability(DefId) -> Option<attr::Stability>,
1215 [] fn deprecation: Deprecation(DefId) -> Option<attr::Deprecation>,
1216 [] fn item_attrs: ItemAttrs(DefId) -> Rc<[ast::Attribute]>,
1217 [] fn fn_arg_names: FnArgNames(DefId) -> Vec<ast::Name>,
1218 [] fn impl_parent: ImplParent(DefId) -> Option<DefId>,
1219 [] fn trait_of_item: TraitOfItem(DefId) -> Option<DefId>,
1220 [] fn is_exported_symbol: IsExportedSymbol(DefId) -> bool,
1221 [] fn item_body_nested_bodies: ItemBodyNestedBodies(DefId)
1222 -> Rc<BTreeMap<hir::BodyId, hir::Body>>,
1223 [] fn const_is_rvalue_promotable_to_static: ConstIsRvaluePromotableToStatic(DefId) -> bool,
1224 [] fn is_mir_available: IsMirAvailable(DefId) -> bool,
1226 [] fn trait_impls_of: TraitImpls(DefId) -> Rc<ty::trait_def::TraitImpls>,
1227 [] fn specialization_graph_of: SpecializationGraph(DefId) -> Rc<specialization_graph::Graph>,
1228 [] fn is_object_safe: ObjectSafety(DefId) -> bool,
1230 // Get the ParameterEnvironment for a given item; this environment
1231 // will be in "user-facing" mode, meaning that it is suitabe for
1232 // type-checking etc, and it does not normalize specializable
1233 // associated types. This is almost always what you want,
1234 // unless you are doing MIR optimizations, in which case you
1235 // might want to use `reveal_all()` method to change modes.
1236 [] fn param_env: ParamEnv(DefId) -> ty::ParamEnv<'tcx>,
1238 // Trait selection queries. These are best used by invoking `ty.moves_by_default()`,
1239 // `ty.is_copy()`, etc, since that will prune the environment where possible.
1240 [] fn is_copy_raw: is_copy_dep_node(ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> bool,
1241 [] fn is_sized_raw: is_sized_dep_node(ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> bool,
1242 [] fn is_freeze_raw: is_freeze_dep_node(ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> bool,
1243 [] fn needs_drop_raw: needs_drop_dep_node(ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> bool,
1244 [] fn layout_raw: layout_dep_node(ty::ParamEnvAnd<'tcx, Ty<'tcx>>)
1245 -> Result<&'tcx Layout, LayoutError<'tcx>>,
1247 [] fn dylib_dependency_formats: DylibDepFormats(CrateNum)
1248 -> Rc<Vec<(CrateNum, LinkagePreference)>>,
1250 [] fn is_panic_runtime: IsPanicRuntime(CrateNum) -> bool,
1251 [] fn is_compiler_builtins: IsCompilerBuiltins(CrateNum) -> bool,
1252 [] fn has_global_allocator: HasGlobalAllocator(CrateNum) -> bool,
1253 [] fn is_sanitizer_runtime: IsSanitizerRuntime(CrateNum) -> bool,
1254 [] fn is_profiler_runtime: IsProfilerRuntime(CrateNum) -> bool,
1255 [] fn panic_strategy: GetPanicStrategy(CrateNum) -> PanicStrategy,
1256 [] fn is_no_builtins: IsNoBuiltins(CrateNum) -> bool,
1258 [] fn extern_crate: ExternCrate(DefId) -> Rc<Option<ExternCrate>>,
1260 [] fn specializes: specializes_node((DefId, DefId)) -> bool,
1261 [] fn in_scope_traits: InScopeTraits(HirId) -> Option<Rc<Vec<TraitCandidate>>>,
1262 [] fn module_exports: ModuleExports(HirId) -> Option<Rc<Vec<Export>>>,
1263 [] fn lint_levels: lint_levels_node(CrateNum) -> Rc<lint::LintLevelMap>,
1265 [] fn impl_defaultness: ImplDefaultness(DefId) -> hir::Defaultness,
1266 [] fn exported_symbols: ExportedSymbols(CrateNum) -> Rc<Vec<DefId>>,
1267 [] fn native_libraries: NativeLibraries(CrateNum) -> Rc<Vec<NativeLibrary>>,
1268 [] fn plugin_registrar_fn: PluginRegistrarFn(CrateNum) -> Option<DefId>,
1269 [] fn derive_registrar_fn: DeriveRegistrarFn(CrateNum) -> Option<DefId>,
1270 [] fn crate_disambiguator: CrateDisambiguator(CrateNum) -> Symbol,
1271 [] fn crate_hash: CrateHash(CrateNum) -> Svh,
1272 [] fn original_crate_name: OriginalCrateName(CrateNum) -> Symbol,
1274 [] fn implementations_of_trait: implementations_of_trait_node((CrateNum, DefId))
1276 [] fn all_trait_implementations: AllTraitImplementations(CrateNum)
1279 [] is_dllimport_foreign_item: IsDllimportForeignItem(DefId) -> bool,
1280 [] is_statically_included_foreign_item: IsStaticallyIncludedForeignItem(DefId) -> bool,
1281 [] native_library_kind: NativeLibraryKind(DefId)
1282 -> Option<NativeLibraryKind>,
1283 [] link_args: link_args_node(CrateNum) -> Rc<Vec<String>>,
1285 [] named_region: NamedRegion(HirId) -> Option<Region>,
1286 [] is_late_bound: IsLateBound(HirId) -> bool,
1287 [] object_lifetime_defaults: ObjectLifetimeDefaults(HirId)
1288 -> Option<Rc<Vec<ObjectLifetimeDefault>>>,
1290 [] visibility: Visibility(DefId) -> ty::Visibility,
1291 [] dep_kind: DepKind(CrateNum) -> DepKind,
1292 [] crate_name: CrateName(CrateNum) -> Symbol,
1293 [] item_children: ItemChildren(DefId) -> Rc<Vec<Export>>,
1294 [] extern_mod_stmt_cnum: ExternModStmtCnum(HirId) -> Option<CrateNum>,
1297 fn type_param_predicates<'tcx>((item_id, param_id): (DefId, DefId)) -> DepConstructor<'tcx> {
1298 DepConstructor::TypeParamPredicates {
1304 fn coherent_trait_dep_node<'tcx>((_, def_id): (CrateNum, DefId)) -> DepConstructor<'tcx> {
1305 DepConstructor::CoherenceCheckTrait(def_id)
1308 fn crate_inherent_impls_dep_node<'tcx>(_: CrateNum) -> DepConstructor<'tcx> {
1309 DepConstructor::Coherence
1312 fn inherent_impls_overlap_check_dep_node<'tcx>(_: CrateNum) -> DepConstructor<'tcx> {
1313 DepConstructor::CoherenceInherentImplOverlapCheck
1316 fn reachability_dep_node<'tcx>(_: CrateNum) -> DepConstructor<'tcx> {
1317 DepConstructor::Reachability
1320 fn mir_shim_dep_node<'tcx>(instance_def: ty::InstanceDef<'tcx>) -> DepConstructor<'tcx> {
1321 DepConstructor::MirShim {
1326 fn symbol_name_dep_node<'tcx>(instance: ty::Instance<'tcx>) -> DepConstructor<'tcx> {
1327 DepConstructor::InstanceSymbolName { instance }
1330 fn typeck_item_bodies_dep_node<'tcx>(_: CrateNum) -> DepConstructor<'tcx> {
1331 DepConstructor::TypeckBodiesKrate
1334 fn const_eval_dep_node<'tcx>(_: ty::ParamEnvAnd<'tcx, (DefId, &'tcx Substs<'tcx>)>)
1335 -> DepConstructor<'tcx> {
1336 DepConstructor::ConstEval
1339 fn mir_keys<'tcx>(_: CrateNum) -> DepConstructor<'tcx> {
1340 DepConstructor::MirKeys
1343 fn crate_variances<'tcx>(_: CrateNum) -> DepConstructor<'tcx> {
1344 DepConstructor::CrateVariances
1347 fn is_copy_dep_node<'tcx>(_: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> DepConstructor<'tcx> {
1348 DepConstructor::IsCopy
1351 fn is_sized_dep_node<'tcx>(_: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> DepConstructor<'tcx> {
1352 DepConstructor::IsSized
1355 fn is_freeze_dep_node<'tcx>(_: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> DepConstructor<'tcx> {
1356 DepConstructor::IsFreeze
1359 fn needs_drop_dep_node<'tcx>(_: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> DepConstructor<'tcx> {
1360 DepConstructor::NeedsDrop
1363 fn layout_dep_node<'tcx>(_: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> DepConstructor<'tcx> {
1364 DepConstructor::Layout
1367 fn lint_levels_node<'tcx>(_: CrateNum) -> DepConstructor<'tcx> {
1368 DepConstructor::LintLevels
1371 fn specializes_node<'tcx>((a, b): (DefId, DefId)) -> DepConstructor<'tcx> {
1372 DepConstructor::Specializes { impl1: a, impl2: b }
1375 fn implementations_of_trait_node<'tcx>((krate, trait_id): (CrateNum, DefId))
1376 -> DepConstructor<'tcx>
1378 DepConstructor::ImplementationsOfTrait { krate, trait_id }
1381 fn link_args_node<'tcx>(_: CrateNum) -> DepConstructor<'tcx> {
1382 DepConstructor::LinkArgs