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::privacy::AccessLevels;
23 use mir::transform::{MirSuite, MirPassIndex};
24 use session::CompileResult;
25 use traits::specialization_graph;
26 use ty::{self, CrateInherentImpls, Ty, TyCtxt};
27 use ty::layout::{Layout, LayoutError};
30 use ty::subst::Substs;
31 use ty::fast_reject::SimplifiedType;
32 use util::nodemap::{DefIdSet, NodeSet};
33 use util::common::{profq_msg, ProfileQueriesMsg};
35 use rustc_data_structures::indexed_set::IdxSetBuf;
36 use rustc_back::PanicStrategy;
37 use rustc_data_structures::indexed_vec::IndexVec;
38 use rustc_data_structures::fx::FxHashMap;
39 use std::cell::{RefCell, RefMut, Cell};
42 use std::marker::PhantomData;
44 use std::collections::BTreeMap;
47 use syntax_pos::{Span, DUMMY_SP};
50 use syntax::symbol::Symbol;
52 pub trait Key: Clone + Hash + Eq + Debug {
53 fn map_crate(&self) -> CrateNum;
54 fn default_span(&self, tcx: TyCtxt) -> Span;
57 impl<'tcx> Key for ty::InstanceDef<'tcx> {
58 fn map_crate(&self) -> CrateNum {
62 fn default_span(&self, tcx: TyCtxt) -> Span {
63 tcx.def_span(self.def_id())
67 impl<'tcx> Key for ty::Instance<'tcx> {
68 fn map_crate(&self) -> CrateNum {
72 fn default_span(&self, tcx: TyCtxt) -> Span {
73 tcx.def_span(self.def_id())
77 impl Key for CrateNum {
78 fn map_crate(&self) -> CrateNum {
81 fn default_span(&self, _: TyCtxt) -> Span {
87 fn map_crate(&self) -> CrateNum {
90 fn default_span(&self, _tcx: TyCtxt) -> Span {
96 fn map_crate(&self) -> CrateNum {
99 fn default_span(&self, tcx: TyCtxt) -> Span {
104 impl Key for (DefId, DefId) {
105 fn map_crate(&self) -> CrateNum {
108 fn default_span(&self, tcx: TyCtxt) -> Span {
109 self.1.default_span(tcx)
113 impl Key for (CrateNum, DefId) {
114 fn map_crate(&self) -> CrateNum {
117 fn default_span(&self, tcx: TyCtxt) -> Span {
118 self.1.default_span(tcx)
122 impl Key for (DefId, SimplifiedType) {
123 fn map_crate(&self) -> CrateNum {
126 fn default_span(&self, tcx: TyCtxt) -> Span {
127 self.0.default_span(tcx)
131 impl<'tcx> Key for (DefId, &'tcx Substs<'tcx>) {
132 fn map_crate(&self) -> CrateNum {
135 fn default_span(&self, tcx: TyCtxt) -> Span {
136 self.0.default_span(tcx)
140 impl Key for (MirSuite, DefId) {
141 fn map_crate(&self) -> CrateNum {
144 fn default_span(&self, tcx: TyCtxt) -> Span {
145 self.1.default_span(tcx)
149 impl Key for (MirSuite, MirPassIndex, DefId) {
150 fn map_crate(&self) -> CrateNum {
153 fn default_span(&self, tcx: TyCtxt) -> Span {
154 self.2.default_span(tcx)
158 impl<'tcx, T: Clone + Hash + Eq + Debug> Key for ty::ParamEnvAnd<'tcx, T> {
159 fn map_crate(&self) -> CrateNum {
162 fn default_span(&self, _: TyCtxt) -> Span {
167 trait Value<'tcx>: Sized {
168 fn from_cycle_error<'a>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Self;
171 impl<'tcx, T> Value<'tcx> for T {
172 default fn from_cycle_error<'a>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> T {
173 tcx.sess.abort_if_errors();
174 bug!("Value::from_cycle_error called without errors");
178 impl<'tcx, T: Default> Value<'tcx> for T {
179 default fn from_cycle_error<'a>(_: TyCtxt<'a, 'tcx, 'tcx>) -> T {
184 impl<'tcx> Value<'tcx> for Ty<'tcx> {
185 fn from_cycle_error<'a>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Ty<'tcx> {
190 impl<'tcx> Value<'tcx> for ty::DtorckConstraint<'tcx> {
191 fn from_cycle_error<'a>(_: TyCtxt<'a, 'tcx, 'tcx>) -> Self {
196 impl<'tcx> Value<'tcx> for ty::SymbolName {
197 fn from_cycle_error<'a>(_: TyCtxt<'a, 'tcx, 'tcx>) -> Self {
198 ty::SymbolName { name: Symbol::intern("<error>").as_str() }
202 struct QueryMap<D: QueryDescription> {
203 phantom: PhantomData<D>,
204 map: FxHashMap<D::Key, QueryValue<D::Value>>,
207 struct QueryValue<T> {
210 diagnostics: Option<Box<QueryDiagnostics>>,
213 struct QueryDiagnostics {
214 diagnostics: Vec<Diagnostic>,
215 emitted_diagnostics: Cell<bool>,
218 impl<M: QueryDescription> QueryMap<M> {
219 fn new() -> QueryMap<M> {
221 phantom: PhantomData,
227 struct CycleError<'a, 'tcx: 'a> {
229 cycle: RefMut<'a, [(Span, Query<'tcx>)]>,
232 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
233 fn report_cycle(self, CycleError { span, cycle }: CycleError)
234 -> DiagnosticBuilder<'a>
236 // Subtle: release the refcell lock before invoking `describe()`
237 // below by dropping `cycle`.
238 let stack = cycle.to_vec();
241 assert!(!stack.is_empty());
243 // Disable naming impls with types in this path, since that
244 // sometimes cycles itself, leading to extra cycle errors.
245 // (And cycle errors around impls tend to occur during the
246 // collect/coherence phases anyhow.)
247 item_path::with_forced_impl_filename_line(|| {
249 struct_span_err!(self.sess, span, E0391,
250 "unsupported cyclic reference between types/traits detected");
251 err.span_label(span, "cyclic reference");
253 err.span_note(stack[0].0, &format!("the cycle begins when {}...",
254 stack[0].1.describe(self)));
256 for &(span, ref query) in &stack[1..] {
257 err.span_note(span, &format!("...which then requires {}...",
258 query.describe(self)));
261 err.note(&format!("...which then again requires {}, completing the cycle.",
262 stack[0].1.describe(self)));
268 fn cycle_check<F, R>(self, span: Span, query: Query<'gcx>, compute: F)
269 -> Result<R, CycleError<'a, 'gcx>>
270 where F: FnOnce() -> R
273 let mut stack = self.maps.query_stack.borrow_mut();
274 if let Some((i, _)) = stack.iter().enumerate().rev()
275 .find(|&(_, &(_, ref q))| *q == query) {
276 return Err(CycleError {
278 cycle: RefMut::map(stack, |stack| &mut stack[i..])
281 stack.push((span, query));
284 let result = compute();
286 self.maps.query_stack.borrow_mut().pop();
292 pub trait QueryConfig {
293 type Key: Eq + Hash + Clone;
297 trait QueryDescription: QueryConfig {
298 fn describe(tcx: TyCtxt, key: Self::Key) -> String;
301 impl<M: QueryConfig<Key=DefId>> QueryDescription for M {
302 default fn describe(tcx: TyCtxt, def_id: DefId) -> String {
303 format!("processing `{}`", tcx.item_path_str(def_id))
307 impl<'tcx> QueryDescription for queries::is_copy_raw<'tcx> {
308 fn describe(_tcx: TyCtxt, env: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> String {
309 format!("computing whether `{}` is `Copy`", env.value)
313 impl<'tcx> QueryDescription for queries::is_sized_raw<'tcx> {
314 fn describe(_tcx: TyCtxt, env: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> String {
315 format!("computing whether `{}` is `Sized`", env.value)
319 impl<'tcx> QueryDescription for queries::is_freeze_raw<'tcx> {
320 fn describe(_tcx: TyCtxt, env: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> String {
321 format!("computing whether `{}` is freeze", env.value)
325 impl<'tcx> QueryDescription for queries::needs_drop_raw<'tcx> {
326 fn describe(_tcx: TyCtxt, env: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> String {
327 format!("computing whether `{}` needs drop", env.value)
331 impl<'tcx> QueryDescription for queries::layout_raw<'tcx> {
332 fn describe(_tcx: TyCtxt, env: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> String {
333 format!("computing layout of `{}`", env.value)
337 impl<'tcx> QueryDescription for queries::super_predicates_of<'tcx> {
338 fn describe(tcx: TyCtxt, def_id: DefId) -> String {
339 format!("computing the supertraits of `{}`",
340 tcx.item_path_str(def_id))
344 impl<'tcx> QueryDescription for queries::type_param_predicates<'tcx> {
345 fn describe(tcx: TyCtxt, (_, def_id): (DefId, DefId)) -> String {
346 let id = tcx.hir.as_local_node_id(def_id).unwrap();
347 format!("computing the bounds for type parameter `{}`",
348 tcx.hir.ty_param_name(id))
352 impl<'tcx> QueryDescription for queries::coherent_trait<'tcx> {
353 fn describe(tcx: TyCtxt, (_, def_id): (CrateNum, DefId)) -> String {
354 format!("coherence checking all impls of trait `{}`",
355 tcx.item_path_str(def_id))
359 impl<'tcx> QueryDescription for queries::crate_inherent_impls<'tcx> {
360 fn describe(_: TyCtxt, k: CrateNum) -> String {
361 format!("all inherent impls defined in crate `{:?}`", k)
365 impl<'tcx> QueryDescription for queries::crate_inherent_impls_overlap_check<'tcx> {
366 fn describe(_: TyCtxt, _: CrateNum) -> String {
367 format!("check for overlap between inherent impls defined in this crate")
371 impl<'tcx> QueryDescription for queries::crate_variances<'tcx> {
372 fn describe(_tcx: TyCtxt, _: CrateNum) -> String {
373 format!("computing the variances for items in this crate")
377 impl<'tcx> QueryDescription for queries::mir_shims<'tcx> {
378 fn describe(tcx: TyCtxt, def: ty::InstanceDef<'tcx>) -> String {
379 format!("generating MIR shim for `{}`",
380 tcx.item_path_str(def.def_id()))
384 impl<'tcx> QueryDescription for queries::privacy_access_levels<'tcx> {
385 fn describe(_: TyCtxt, _: CrateNum) -> String {
386 format!("privacy access levels")
390 impl<'tcx> QueryDescription for queries::typeck_item_bodies<'tcx> {
391 fn describe(_: TyCtxt, _: CrateNum) -> String {
392 format!("type-checking all item bodies")
396 impl<'tcx> QueryDescription for queries::reachable_set<'tcx> {
397 fn describe(_: TyCtxt, _: CrateNum) -> String {
398 format!("reachability")
402 impl<'tcx> QueryDescription for queries::const_eval<'tcx> {
403 fn describe(tcx: TyCtxt, key: ty::ParamEnvAnd<'tcx, (DefId, &'tcx Substs<'tcx>)>) -> String {
404 format!("const-evaluating `{}`", tcx.item_path_str(key.value.0))
408 impl<'tcx> QueryDescription for queries::mir_keys<'tcx> {
409 fn describe(_: TyCtxt, _: CrateNum) -> String {
410 format!("getting a list of all mir_keys")
414 impl<'tcx> QueryDescription for queries::symbol_name<'tcx> {
415 fn describe(_tcx: TyCtxt, instance: ty::Instance<'tcx>) -> String {
416 format!("computing the symbol for `{}`", instance)
420 impl<'tcx> QueryDescription for queries::describe_def<'tcx> {
421 fn describe(_: TyCtxt, _: DefId) -> String {
426 impl<'tcx> QueryDescription for queries::def_span<'tcx> {
427 fn describe(_: TyCtxt, _: DefId) -> String {
433 impl<'tcx> QueryDescription for queries::stability<'tcx> {
434 fn describe(_: TyCtxt, _: DefId) -> String {
439 impl<'tcx> QueryDescription for queries::deprecation<'tcx> {
440 fn describe(_: TyCtxt, _: DefId) -> String {
445 impl<'tcx> QueryDescription for queries::item_attrs<'tcx> {
446 fn describe(_: TyCtxt, _: DefId) -> String {
451 impl<'tcx> QueryDescription for queries::is_exported_symbol<'tcx> {
452 fn describe(_: TyCtxt, _: DefId) -> String {
453 bug!("is_exported_symbol")
457 impl<'tcx> QueryDescription for queries::fn_arg_names<'tcx> {
458 fn describe(_: TyCtxt, _: DefId) -> String {
463 impl<'tcx> QueryDescription for queries::impl_parent<'tcx> {
464 fn describe(_: TyCtxt, _: DefId) -> String {
469 impl<'tcx> QueryDescription for queries::trait_of_item<'tcx> {
470 fn describe(_: TyCtxt, _: DefId) -> String {
471 bug!("trait_of_item")
475 impl<'tcx> QueryDescription for queries::item_body_nested_bodies<'tcx> {
476 fn describe(tcx: TyCtxt, def_id: DefId) -> String {
477 format!("nested item bodies of `{}`", tcx.item_path_str(def_id))
481 impl<'tcx> QueryDescription for queries::const_is_rvalue_promotable_to_static<'tcx> {
482 fn describe(tcx: TyCtxt, def_id: DefId) -> String {
483 format!("const checking if rvalue is promotable to static `{}`",
484 tcx.item_path_str(def_id))
488 impl<'tcx> QueryDescription for queries::is_mir_available<'tcx> {
489 fn describe(tcx: TyCtxt, def_id: DefId) -> String {
490 format!("checking if item is mir available: `{}`",
491 tcx.item_path_str(def_id))
495 impl<'tcx> QueryDescription for queries::trait_impls_of<'tcx> {
496 fn describe(tcx: TyCtxt, def_id: DefId) -> String {
497 format!("trait impls of `{}`", tcx.item_path_str(def_id))
501 impl<'tcx> QueryDescription for queries::is_object_safe<'tcx> {
502 fn describe(tcx: TyCtxt, def_id: DefId) -> String {
503 format!("determine object safety of trait `{}`", tcx.item_path_str(def_id))
507 impl<'tcx> QueryDescription for queries::is_const_fn<'tcx> {
508 fn describe(tcx: TyCtxt, def_id: DefId) -> String {
509 format!("checking if item is const fn: `{}`", tcx.item_path_str(def_id))
513 impl<'tcx> QueryDescription for queries::dylib_dependency_formats<'tcx> {
514 fn describe(_: TyCtxt, _: CrateNum) -> String {
515 "dylib dependency formats of crate".to_string()
519 impl<'tcx> QueryDescription for queries::is_panic_runtime<'tcx> {
520 fn describe(_: TyCtxt, _: CrateNum) -> String {
521 "checking if the crate is_panic_runtime".to_string()
525 impl<'tcx> QueryDescription for queries::is_compiler_builtins<'tcx> {
526 fn describe(_: TyCtxt, _: CrateNum) -> String {
527 "checking if the crate is_compiler_builtins".to_string()
531 impl<'tcx> QueryDescription for queries::has_global_allocator<'tcx> {
532 fn describe(_: TyCtxt, _: CrateNum) -> String {
533 "checking if the crate has_global_allocator".to_string()
537 impl<'tcx> QueryDescription for queries::extern_crate<'tcx> {
538 fn describe(_: TyCtxt, _: DefId) -> String {
539 "getting crate's ExternCrateData".to_string()
543 impl<'tcx> QueryDescription for queries::lint_levels<'tcx> {
544 fn describe(_tcx: TyCtxt, _: CrateNum) -> String {
545 format!("computing the lint levels for items in this crate")
549 impl<'tcx> QueryDescription for queries::specializes<'tcx> {
550 fn describe(_tcx: TyCtxt, _: (DefId, DefId)) -> String {
551 format!("computing whether impls specialize one another")
555 impl<'tcx> QueryDescription for queries::in_scope_traits<'tcx> {
556 fn describe(_tcx: TyCtxt, _: HirId) -> String {
557 format!("fetching the traits in scope at a particular ast node")
561 impl<'tcx> QueryDescription for queries::module_exports<'tcx> {
562 fn describe(_tcx: TyCtxt, _: HirId) -> String {
563 format!("fetching the exported items for a module")
567 impl<'tcx> QueryDescription for queries::is_no_builtins<'tcx> {
568 fn describe(_tcx: TyCtxt, _: CrateNum) -> String {
569 format!("test whether a crate has #![no_builtins]")
573 impl<'tcx> QueryDescription for queries::panic_strategy<'tcx> {
574 fn describe(_tcx: TyCtxt, _: CrateNum) -> String {
575 format!("query a crate's configured panic strategy")
579 impl<'tcx> QueryDescription for queries::is_profiler_runtime<'tcx> {
580 fn describe(_tcx: TyCtxt, _: CrateNum) -> String {
581 format!("query a crate is #![profiler_runtime]")
585 impl<'tcx> QueryDescription for queries::is_sanitizer_runtime<'tcx> {
586 fn describe(_tcx: TyCtxt, _: CrateNum) -> String {
587 format!("query a crate is #![sanitizer_runtime]")
591 impl<'tcx> QueryDescription for queries::exported_symbols<'tcx> {
592 fn describe(_tcx: TyCtxt, _: CrateNum) -> String {
593 format!("looking up the exported symbols of a crate")
597 impl<'tcx> QueryDescription for queries::native_libraries<'tcx> {
598 fn describe(_tcx: TyCtxt, _: CrateNum) -> String {
599 format!("looking up the native libraries of a linked crate")
603 impl<'tcx> QueryDescription for queries::plugin_registrar_fn<'tcx> {
604 fn describe(_tcx: TyCtxt, _: CrateNum) -> String {
605 format!("looking up the plugin registrar for a crate")
609 impl<'tcx> QueryDescription for queries::derive_registrar_fn<'tcx> {
610 fn describe(_tcx: TyCtxt, _: CrateNum) -> String {
611 format!("looking up the derive registrar for a crate")
615 impl<'tcx> QueryDescription for queries::crate_disambiguator<'tcx> {
616 fn describe(_tcx: TyCtxt, _: CrateNum) -> String {
617 format!("looking up the disambiguator a crate")
621 impl<'tcx> QueryDescription for queries::crate_hash<'tcx> {
622 fn describe(_tcx: TyCtxt, _: CrateNum) -> String {
623 format!("looking up the hash a crate")
627 // If enabled, send a message to the profile-queries thread
628 macro_rules! profq_msg {
629 ($tcx:expr, $msg:expr) => {
630 if cfg!(debug_assertions) {
631 if $tcx.sess.profile_queries() {
638 // If enabled, format a key using its debug string, which can be
639 // expensive to compute (in terms of time).
640 macro_rules! profq_key {
641 ($tcx:expr, $key:expr) => {
642 if cfg!(debug_assertions) {
643 if $tcx.sess.profile_queries_and_keys() {
644 Some(format!("{:?}", $key))
650 macro_rules! define_maps {
653 [$($modifiers:tt)*] fn $name:ident: $node:ident($K:ty) -> $V:ty,)*) => {
656 input: ($(([$($modifiers)*] [$($attr)*] [$name]))*)
659 impl<$tcx> Maps<$tcx> {
660 pub fn new(providers: IndexVec<CrateNum, Providers<$tcx>>)
664 query_stack: RefCell::new(vec![]),
665 $($name: RefCell::new(QueryMap::new())),*
671 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
672 pub enum Query<$tcx> {
673 $($(#[$attr])* $name($K)),*
677 #[derive(Clone, Debug, PartialEq, Eq)]
679 $($name(Option<String>)),*
682 impl<$tcx> Query<$tcx> {
683 pub fn describe(&self, tcx: TyCtxt) -> String {
684 let (r, name) = match *self {
685 $(Query::$name(key) => {
686 (queries::$name::describe(tcx, key), stringify!($name))
689 if tcx.sess.verbose() {
690 format!("{} [{}]", r, name)
698 use std::marker::PhantomData;
700 $(#[allow(bad_style)]
701 pub struct $name<$tcx> {
702 data: PhantomData<&$tcx ()>
706 $(impl<$tcx> QueryConfig for queries::$name<$tcx> {
711 impl<'a, $tcx, 'lcx> queries::$name<$tcx> {
713 fn to_dep_node(tcx: TyCtxt<'a, $tcx, 'lcx>, key: &$K) -> DepNode {
714 use dep_graph::DepConstructor::*;
716 DepNode::new(tcx, $node(*key))
719 fn try_get_with<F, R>(tcx: TyCtxt<'a, $tcx, 'lcx>,
723 -> Result<R, CycleError<'a, $tcx>>
724 where F: FnOnce(&$V) -> R
726 debug!("ty::queries::{}::try_get_with(key={:?}, span={:?})",
732 ProfileQueriesMsg::QueryBegin(
734 QueryMsg::$name(profq_key!(tcx, key))
738 if let Some(value) = tcx.maps.$name.borrow().map.get(&key) {
739 if let Some(ref d) = value.diagnostics {
740 if !d.emitted_diagnostics.get() {
741 d.emitted_diagnostics.set(true);
742 let handle = tcx.sess.diagnostic();
743 for diagnostic in d.diagnostics.iter() {
744 DiagnosticBuilder::new_diagnostic(handle, diagnostic.clone())
749 profq_msg!(tcx, ProfileQueriesMsg::CacheHit);
750 tcx.dep_graph.read_index(value.index);
751 return Ok(f(&value.value));
753 // else, we are going to run the provider:
754 profq_msg!(tcx, ProfileQueriesMsg::ProviderBegin);
756 // FIXME(eddyb) Get more valid Span's on queries.
757 // def_span guard is necessary to prevent a recursive loop,
758 // default_span calls def_span query internally.
759 if span == DUMMY_SP && stringify!($name) != "def_span" {
760 span = key.default_span(tcx)
763 let res = tcx.cycle_check(span, Query::$name(key), || {
764 let dep_node = Self::to_dep_node(tcx, &key);
766 tcx.sess.diagnostic().track_diagnostics(|| {
767 if dep_node.kind.is_anon() {
768 tcx.dep_graph.with_anon_task(dep_node.kind, || {
769 let provider = tcx.maps.providers[key.map_crate()].$name;
770 provider(tcx.global_tcx(), key)
773 fn run_provider<'a, 'tcx, 'lcx>(tcx: TyCtxt<'a, 'tcx, 'lcx>,
776 let provider = tcx.maps.providers[key.map_crate()].$name;
777 provider(tcx.global_tcx(), key)
780 tcx.dep_graph.with_task(dep_node, tcx, key, run_provider)
784 profq_msg!(tcx, ProfileQueriesMsg::ProviderEnd);
785 let ((result, dep_node_index), diagnostics) = res;
787 tcx.dep_graph.read_index(dep_node_index);
789 let value = QueryValue {
791 index: dep_node_index,
792 diagnostics: if diagnostics.len() == 0 {
795 Some(Box::new(QueryDiagnostics {
797 emitted_diagnostics: Cell::new(true),
811 pub fn try_get(tcx: TyCtxt<'a, $tcx, 'lcx>, span: Span, key: $K)
812 -> Result<$V, DiagnosticBuilder<'a>> {
813 match Self::try_get_with(tcx, span, key, Clone::clone) {
815 Err(e) => Err(tcx.report_cycle(e)),
819 pub fn force(tcx: TyCtxt<'a, $tcx, 'lcx>, span: Span, key: $K) {
820 // Ignore dependencies, since we not reading the computed value
821 let _task = tcx.dep_graph.in_ignore();
823 match Self::try_get_with(tcx, span, key, |_| ()) {
825 Err(e) => tcx.report_cycle(e).emit(),
830 #[derive(Copy, Clone)]
831 pub struct TyCtxtAt<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
832 pub tcx: TyCtxt<'a, 'gcx, 'tcx>,
836 impl<'a, 'gcx, 'tcx> Deref for TyCtxtAt<'a, 'gcx, 'tcx> {
837 type Target = TyCtxt<'a, 'gcx, 'tcx>;
838 fn deref(&self) -> &Self::Target {
843 impl<'a, $tcx, 'lcx> TyCtxt<'a, $tcx, 'lcx> {
844 /// Return a transparent wrapper for `TyCtxt` which uses
845 /// `span` as the location of queries performed through it.
846 pub fn at(self, span: Span) -> TyCtxtAt<'a, $tcx, 'lcx> {
854 pub fn $name(self, key: $K) -> $V {
855 self.at(DUMMY_SP).$name(key)
859 impl<'a, $tcx, 'lcx> TyCtxtAt<'a, $tcx, 'lcx> {
861 pub fn $name(self, key: $K) -> $V {
862 queries::$name::try_get(self.tcx, self.span, key).unwrap_or_else(|mut e| {
864 Value::from_cycle_error(self.global_tcx())
869 define_provider_struct! {
871 input: ($(([$($modifiers)*] [$name] [$K] [$V]))*),
875 impl<$tcx> Copy for Providers<$tcx> {}
876 impl<$tcx> Clone for Providers<$tcx> {
877 fn clone(&self) -> Self { *self }
882 macro_rules! define_map_struct {
885 input: $input:tt) => {
896 output: ($($output:tt)*)) => {
897 pub struct Maps<$tcx> {
898 providers: IndexVec<CrateNum, Providers<$tcx>>,
899 query_stack: RefCell<Vec<(Span, Query<$tcx>)>>,
904 // Field recognized and ready to shift into the output
906 ready: ([$($pub:tt)*] [$($attr:tt)*] [$name:ident]),
908 output: ($($output:tt)*)) => {
913 $(#[$attr])* $($pub)* $name: RefCell<QueryMap<queries::$name<$tcx>>>,)
917 // No modifiers left? This is a private item.
919 input: (([] $attrs:tt $name:tt) $($input:tt)*),
920 output: $output:tt) => {
923 ready: ([] $attrs $name),
929 // Skip other modifiers
931 input: (([$other_modifier:tt $($modifiers:tt)*] $($fields:tt)*) $($input:tt)*),
932 output: $output:tt) => {
935 input: (([$($modifiers)*] $($fields)*) $($input)*),
941 macro_rules! define_provider_struct {
943 (tcx: $tcx:tt, input: $input:tt) => {
944 define_provider_struct! {
954 output: ($(([$name:ident] [$K:ty] [$R:ty]))*)) => {
955 pub struct Providers<$tcx> {
956 $(pub $name: for<'a> fn(TyCtxt<'a, $tcx, $tcx>, $K) -> $R,)*
959 impl<$tcx> Default for Providers<$tcx> {
960 fn default() -> Self {
961 $(fn $name<'a, $tcx>(_: TyCtxt<'a, $tcx, $tcx>, key: $K) -> $R {
962 bug!("tcx.maps.{}({:?}) unsupported by its crate",
963 stringify!($name), key);
965 Providers { $($name),* }
970 // Something ready to shift:
972 ready: ($name:tt $K:tt $V:tt),
974 output: ($($output:tt)*)) => {
975 define_provider_struct! {
978 output: ($($output)* ($name $K $V))
982 // Regular queries produce a `V` only.
984 input: (([] $name:tt $K:tt $V:tt) $($input:tt)*),
985 output: $output:tt) => {
986 define_provider_struct! {
988 ready: ($name $K $V),
996 input: (([$other_modifier:tt $($modifiers:tt)*] $($fields:tt)*) $($input:tt)*),
997 output: $output:tt) => {
998 define_provider_struct! {
1000 input: (([$($modifiers)*] $($fields)*) $($input)*),
1006 // Each of these maps also corresponds to a method on a
1007 // `Provider` trait for requesting a value of that type,
1008 // and a method on `Maps` itself for doing that in a
1009 // a way that memoizes and does dep-graph tracking,
1010 // wrapping around the actual chain of providers that
1011 // the driver creates (using several `rustc_*` crates).
1012 define_maps! { <'tcx>
1013 /// Records the type of every item.
1014 [] fn type_of: TypeOfItem(DefId) -> Ty<'tcx>,
1016 /// Maps from the def-id of an item (trait/struct/enum/fn) to its
1017 /// associated generics and predicates.
1018 [] fn generics_of: GenericsOfItem(DefId) -> &'tcx ty::Generics,
1019 [] fn predicates_of: PredicatesOfItem(DefId) -> ty::GenericPredicates<'tcx>,
1021 /// Maps from the def-id of a trait to the list of
1022 /// super-predicates. This is a subset of the full list of
1023 /// predicates. We store these in a separate map because we must
1024 /// evaluate them even during type conversion, often before the
1025 /// full predicates are available (note that supertraits have
1026 /// additional acyclicity requirements).
1027 [] fn super_predicates_of: SuperPredicatesOfItem(DefId) -> ty::GenericPredicates<'tcx>,
1029 /// To avoid cycles within the predicates of a single item we compute
1030 /// per-type-parameter predicates for resolving `T::AssocTy`.
1031 [] fn type_param_predicates: type_param_predicates((DefId, DefId))
1032 -> ty::GenericPredicates<'tcx>,
1034 [] fn trait_def: TraitDefOfItem(DefId) -> &'tcx ty::TraitDef,
1035 [] fn adt_def: AdtDefOfItem(DefId) -> &'tcx ty::AdtDef,
1036 [] fn adt_destructor: AdtDestructor(DefId) -> Option<ty::Destructor>,
1037 [] fn adt_sized_constraint: SizedConstraint(DefId) -> &'tcx [Ty<'tcx>],
1038 [] fn adt_dtorck_constraint: DtorckConstraint(DefId) -> ty::DtorckConstraint<'tcx>,
1040 /// True if this is a const fn
1041 [] fn is_const_fn: IsConstFn(DefId) -> bool,
1043 /// True if this is a foreign item (i.e., linked via `extern { ... }`).
1044 [] fn is_foreign_item: IsForeignItem(DefId) -> bool,
1046 /// True if this is a default impl (aka impl Foo for ..)
1047 [] fn is_default_impl: IsDefaultImpl(DefId) -> bool,
1049 /// Get a map with the variance of every item; use `item_variance`
1051 [] fn crate_variances: crate_variances(CrateNum) -> Rc<ty::CrateVariancesMap>,
1053 /// Maps from def-id of a type or region parameter to its
1054 /// (inferred) variance.
1055 [] fn variances_of: ItemVariances(DefId) -> Rc<Vec<ty::Variance>>,
1057 /// Maps from an impl/trait def-id to a list of the def-ids of its items
1058 [] fn associated_item_def_ids: AssociatedItemDefIds(DefId) -> Rc<Vec<DefId>>,
1060 /// Maps from a trait item to the trait item "descriptor"
1061 [] fn associated_item: AssociatedItems(DefId) -> ty::AssociatedItem,
1063 [] fn impl_trait_ref: ImplTraitRef(DefId) -> Option<ty::TraitRef<'tcx>>,
1064 [] fn impl_polarity: ImplPolarity(DefId) -> hir::ImplPolarity,
1066 /// Maps a DefId of a type to a list of its inherent impls.
1067 /// Contains implementations of methods that are inherent to a type.
1068 /// Methods in these implementations don't need to be exported.
1069 [] fn inherent_impls: InherentImpls(DefId) -> Rc<Vec<DefId>>,
1071 /// Set of all the def-ids in this crate that have MIR associated with
1072 /// them. This includes all the body owners, but also things like struct
1074 [] fn mir_keys: mir_keys(CrateNum) -> Rc<DefIdSet>,
1076 /// Maps DefId's that have an associated Mir to the result
1077 /// of the MIR qualify_consts pass. The actual meaning of
1078 /// the value isn't known except to the pass itself.
1079 [] fn mir_const_qualif: MirConstQualif(DefId) -> (u8, Rc<IdxSetBuf<mir::Local>>),
1081 /// Fetch the MIR for a given def-id up till the point where it is
1082 /// ready for const evaluation.
1084 /// See the README for the `mir` module for details.
1085 [] fn mir_const: MirConst(DefId) -> &'tcx Steal<mir::Mir<'tcx>>,
1087 [] fn mir_validated: MirValidated(DefId) -> &'tcx Steal<mir::Mir<'tcx>>,
1089 /// MIR after our optimization passes have run. This is MIR that is ready
1090 /// for trans. This is also the only query that can fetch non-local MIR, at present.
1091 [] fn optimized_mir: MirOptimized(DefId) -> &'tcx mir::Mir<'tcx>,
1093 /// Type of each closure. The def ID is the ID of the
1094 /// expression defining the closure.
1095 [] fn closure_kind: ClosureKind(DefId) -> ty::ClosureKind,
1097 /// The signature of functions and closures.
1098 [] fn fn_sig: FnSignature(DefId) -> ty::PolyFnSig<'tcx>,
1100 /// Records the signature of each generator. The def ID is the ID of the
1101 /// expression defining the closure.
1102 [] fn generator_sig: GenSignature(DefId) -> Option<ty::PolyGenSig<'tcx>>,
1104 /// Caches CoerceUnsized kinds for impls on custom types.
1105 [] fn coerce_unsized_info: CoerceUnsizedInfo(DefId)
1106 -> ty::adjustment::CoerceUnsizedInfo,
1108 [] fn typeck_item_bodies: typeck_item_bodies_dep_node(CrateNum) -> CompileResult,
1110 [] fn typeck_tables_of: TypeckTables(DefId) -> &'tcx ty::TypeckTables<'tcx>,
1112 [] fn has_typeck_tables: HasTypeckTables(DefId) -> bool,
1114 [] fn coherent_trait: coherent_trait_dep_node((CrateNum, DefId)) -> (),
1116 [] fn borrowck: BorrowCheck(DefId) -> (),
1117 // FIXME: shouldn't this return a `Result<(), BorrowckErrors>` instead?
1118 [] fn mir_borrowck: MirBorrowCheck(DefId) -> (),
1120 /// Gets a complete map from all types to their inherent impls.
1121 /// Not meant to be used directly outside of coherence.
1122 /// (Defined only for LOCAL_CRATE)
1123 [] fn crate_inherent_impls: crate_inherent_impls_dep_node(CrateNum) -> CrateInherentImpls,
1125 /// Checks all types in the krate for overlap in their inherent impls. Reports errors.
1126 /// Not meant to be used directly outside of coherence.
1127 /// (Defined only for LOCAL_CRATE)
1128 [] fn crate_inherent_impls_overlap_check: inherent_impls_overlap_check_dep_node(CrateNum) -> (),
1130 /// Results of evaluating const items or constants embedded in
1131 /// other items (such as enum variant explicit discriminants).
1132 [] fn const_eval: const_eval_dep_node(ty::ParamEnvAnd<'tcx, (DefId, &'tcx Substs<'tcx>)>)
1133 -> const_val::EvalResult<'tcx>,
1135 /// Performs the privacy check and computes "access levels".
1136 [] fn privacy_access_levels: PrivacyAccessLevels(CrateNum) -> Rc<AccessLevels>,
1138 [] fn reachable_set: reachability_dep_node(CrateNum) -> Rc<NodeSet>,
1140 /// Per-body `region::ScopeTree`. The `DefId` should be the owner-def-id for the body;
1141 /// in the case of closures, this will be redirected to the enclosing function.
1142 [] fn region_scope_tree: RegionScopeTree(DefId) -> Rc<region::ScopeTree>,
1144 [] fn mir_shims: mir_shim_dep_node(ty::InstanceDef<'tcx>) -> &'tcx mir::Mir<'tcx>,
1146 [] fn def_symbol_name: SymbolName(DefId) -> ty::SymbolName,
1147 [] fn symbol_name: symbol_name_dep_node(ty::Instance<'tcx>) -> ty::SymbolName,
1149 [] fn describe_def: DescribeDef(DefId) -> Option<Def>,
1150 [] fn def_span: DefSpan(DefId) -> Span,
1151 [] fn stability: Stability(DefId) -> Option<attr::Stability>,
1152 [] fn deprecation: Deprecation(DefId) -> Option<attr::Deprecation>,
1153 [] fn item_attrs: ItemAttrs(DefId) -> Rc<[ast::Attribute]>,
1154 [] fn fn_arg_names: FnArgNames(DefId) -> Vec<ast::Name>,
1155 [] fn impl_parent: ImplParent(DefId) -> Option<DefId>,
1156 [] fn trait_of_item: TraitOfItem(DefId) -> Option<DefId>,
1157 [] fn is_exported_symbol: IsExportedSymbol(DefId) -> bool,
1158 [] fn item_body_nested_bodies: ItemBodyNestedBodies(DefId)
1159 -> Rc<BTreeMap<hir::BodyId, hir::Body>>,
1160 [] fn const_is_rvalue_promotable_to_static: ConstIsRvaluePromotableToStatic(DefId) -> bool,
1161 [] fn is_mir_available: IsMirAvailable(DefId) -> bool,
1163 [] fn trait_impls_of: TraitImpls(DefId) -> Rc<ty::trait_def::TraitImpls>,
1164 [] fn specialization_graph_of: SpecializationGraph(DefId) -> Rc<specialization_graph::Graph>,
1165 [] fn is_object_safe: ObjectSafety(DefId) -> bool,
1167 // Get the ParameterEnvironment for a given item; this environment
1168 // will be in "user-facing" mode, meaning that it is suitabe for
1169 // type-checking etc, and it does not normalize specializable
1170 // associated types. This is almost always what you want,
1171 // unless you are doing MIR optimizations, in which case you
1172 // might want to use `reveal_all()` method to change modes.
1173 [] fn param_env: ParamEnv(DefId) -> ty::ParamEnv<'tcx>,
1175 // Trait selection queries. These are best used by invoking `ty.moves_by_default()`,
1176 // `ty.is_copy()`, etc, since that will prune the environment where possible.
1177 [] fn is_copy_raw: is_copy_dep_node(ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> bool,
1178 [] fn is_sized_raw: is_sized_dep_node(ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> bool,
1179 [] fn is_freeze_raw: is_freeze_dep_node(ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> bool,
1180 [] fn needs_drop_raw: needs_drop_dep_node(ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> bool,
1181 [] fn layout_raw: layout_dep_node(ty::ParamEnvAnd<'tcx, Ty<'tcx>>)
1182 -> Result<&'tcx Layout, LayoutError<'tcx>>,
1184 [] fn dylib_dependency_formats: DylibDepFormats(CrateNum)
1185 -> Rc<Vec<(CrateNum, LinkagePreference)>>,
1187 [] fn is_panic_runtime: IsPanicRuntime(CrateNum) -> bool,
1188 [] fn is_compiler_builtins: IsCompilerBuiltins(CrateNum) -> bool,
1189 [] fn has_global_allocator: HasGlobalAllocator(CrateNum) -> bool,
1190 [] fn is_sanitizer_runtime: IsSanitizerRuntime(CrateNum) -> bool,
1191 [] fn is_profiler_runtime: IsProfilerRuntime(CrateNum) -> bool,
1192 [] fn panic_strategy: GetPanicStrategy(CrateNum) -> PanicStrategy,
1193 [] fn is_no_builtins: IsNoBuiltins(CrateNum) -> bool,
1195 [] fn extern_crate: ExternCrate(DefId) -> Rc<Option<ExternCrate>>,
1197 [] fn specializes: specializes_node((DefId, DefId)) -> bool,
1198 [] fn in_scope_traits: InScopeTraits(HirId) -> Option<Rc<Vec<TraitCandidate>>>,
1199 [] fn module_exports: ModuleExports(HirId) -> Option<Rc<Vec<Export>>>,
1200 [] fn lint_levels: lint_levels_node(CrateNum) -> Rc<lint::LintLevelMap>,
1202 [] fn impl_defaultness: ImplDefaultness(DefId) -> hir::Defaultness,
1203 [] fn exported_symbols: ExportedSymbols(CrateNum) -> Rc<Vec<DefId>>,
1204 [] fn native_libraries: NativeLibraries(CrateNum) -> Rc<Vec<NativeLibrary>>,
1205 [] fn plugin_registrar_fn: PluginRegistrarFn(CrateNum) -> Option<DefId>,
1206 [] fn derive_registrar_fn: DeriveRegistrarFn(CrateNum) -> Option<DefId>,
1207 [] fn crate_disambiguator: CrateDisambiguator(CrateNum) -> Symbol,
1208 [] fn crate_hash: CrateHash(CrateNum) -> Svh,
1211 fn type_param_predicates<'tcx>((item_id, param_id): (DefId, DefId)) -> DepConstructor<'tcx> {
1212 DepConstructor::TypeParamPredicates {
1218 fn coherent_trait_dep_node<'tcx>((_, def_id): (CrateNum, DefId)) -> DepConstructor<'tcx> {
1219 DepConstructor::CoherenceCheckTrait(def_id)
1222 fn crate_inherent_impls_dep_node<'tcx>(_: CrateNum) -> DepConstructor<'tcx> {
1223 DepConstructor::Coherence
1226 fn inherent_impls_overlap_check_dep_node<'tcx>(_: CrateNum) -> DepConstructor<'tcx> {
1227 DepConstructor::CoherenceInherentImplOverlapCheck
1230 fn reachability_dep_node<'tcx>(_: CrateNum) -> DepConstructor<'tcx> {
1231 DepConstructor::Reachability
1234 fn mir_shim_dep_node<'tcx>(instance_def: ty::InstanceDef<'tcx>) -> DepConstructor<'tcx> {
1235 DepConstructor::MirShim {
1240 fn symbol_name_dep_node<'tcx>(instance: ty::Instance<'tcx>) -> DepConstructor<'tcx> {
1241 DepConstructor::InstanceSymbolName { instance }
1244 fn typeck_item_bodies_dep_node<'tcx>(_: CrateNum) -> DepConstructor<'tcx> {
1245 DepConstructor::TypeckBodiesKrate
1248 fn const_eval_dep_node<'tcx>(_: ty::ParamEnvAnd<'tcx, (DefId, &'tcx Substs<'tcx>)>)
1249 -> DepConstructor<'tcx> {
1250 DepConstructor::ConstEval
1253 fn mir_keys<'tcx>(_: CrateNum) -> DepConstructor<'tcx> {
1254 DepConstructor::MirKeys
1257 fn crate_variances<'tcx>(_: CrateNum) -> DepConstructor<'tcx> {
1258 DepConstructor::CrateVariances
1261 fn is_copy_dep_node<'tcx>(_: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> DepConstructor<'tcx> {
1262 DepConstructor::IsCopy
1265 fn is_sized_dep_node<'tcx>(_: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> DepConstructor<'tcx> {
1266 DepConstructor::IsSized
1269 fn is_freeze_dep_node<'tcx>(_: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> DepConstructor<'tcx> {
1270 DepConstructor::IsFreeze
1273 fn needs_drop_dep_node<'tcx>(_: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> DepConstructor<'tcx> {
1274 DepConstructor::NeedsDrop
1277 fn layout_dep_node<'tcx>(_: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> DepConstructor<'tcx> {
1278 DepConstructor::Layout
1281 fn lint_levels_node<'tcx>(_: CrateNum) -> DepConstructor<'tcx> {
1282 DepConstructor::LintLevels
1285 fn specializes_node<'tcx>((a, b): (DefId, DefId)) -> DepConstructor<'tcx> {
1286 DepConstructor::Specializes { impl1: a, impl2: b }