1 // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 use dep_graph::{DepConstructor, DepNode, DepNodeIndex};
12 use errors::{Diagnostic, DiagnosticBuilder};
13 use hir::def_id::{CrateNum, DefId, LOCAL_CRATE};
14 use hir::def::{Def, Export};
15 use hir::{self, TraitCandidate, HirId};
17 use middle::const_val;
18 use middle::cstore::{ExternCrate, LinkagePreference, NativeLibrary};
19 use middle::privacy::AccessLevels;
22 use mir::transform::{MirSuite, MirPassIndex};
23 use session::CompileResult;
24 use traits::specialization_graph;
25 use ty::{self, CrateInherentImpls, Ty, TyCtxt};
26 use ty::layout::{Layout, LayoutError};
29 use ty::subst::Substs;
30 use ty::fast_reject::SimplifiedType;
31 use util::nodemap::{DefIdSet, NodeSet};
32 use util::common::{profq_msg, ProfileQueriesMsg};
34 use rustc_data_structures::indexed_set::IdxSetBuf;
35 use rustc_back::PanicStrategy;
36 use rustc_data_structures::indexed_vec::IndexVec;
37 use rustc_data_structures::fx::FxHashMap;
38 use std::cell::{RefCell, RefMut, Cell};
41 use std::marker::PhantomData;
43 use std::collections::BTreeMap;
46 use syntax_pos::{Span, DUMMY_SP};
49 use syntax::symbol::Symbol;
51 pub trait Key: Clone + Hash + Eq + Debug {
52 fn map_crate(&self) -> CrateNum;
53 fn default_span(&self, tcx: TyCtxt) -> Span;
56 impl<'tcx> Key for ty::InstanceDef<'tcx> {
57 fn map_crate(&self) -> CrateNum {
61 fn default_span(&self, tcx: TyCtxt) -> Span {
62 tcx.def_span(self.def_id())
66 impl<'tcx> Key for ty::Instance<'tcx> {
67 fn map_crate(&self) -> CrateNum {
71 fn default_span(&self, tcx: TyCtxt) -> Span {
72 tcx.def_span(self.def_id())
76 impl Key for CrateNum {
77 fn map_crate(&self) -> CrateNum {
80 fn default_span(&self, _: TyCtxt) -> Span {
86 fn map_crate(&self) -> CrateNum {
89 fn default_span(&self, _tcx: TyCtxt) -> Span {
95 fn map_crate(&self) -> CrateNum {
98 fn default_span(&self, tcx: TyCtxt) -> Span {
103 impl Key for (DefId, DefId) {
104 fn map_crate(&self) -> CrateNum {
107 fn default_span(&self, tcx: TyCtxt) -> Span {
108 self.1.default_span(tcx)
112 impl Key for (CrateNum, DefId) {
113 fn map_crate(&self) -> CrateNum {
116 fn default_span(&self, tcx: TyCtxt) -> Span {
117 self.1.default_span(tcx)
121 impl Key for (DefId, SimplifiedType) {
122 fn map_crate(&self) -> CrateNum {
125 fn default_span(&self, tcx: TyCtxt) -> Span {
126 self.0.default_span(tcx)
130 impl<'tcx> Key for (DefId, &'tcx Substs<'tcx>) {
131 fn map_crate(&self) -> CrateNum {
134 fn default_span(&self, tcx: TyCtxt) -> Span {
135 self.0.default_span(tcx)
139 impl Key for (MirSuite, DefId) {
140 fn map_crate(&self) -> CrateNum {
143 fn default_span(&self, tcx: TyCtxt) -> Span {
144 self.1.default_span(tcx)
148 impl Key for (MirSuite, MirPassIndex, DefId) {
149 fn map_crate(&self) -> CrateNum {
152 fn default_span(&self, tcx: TyCtxt) -> Span {
153 self.2.default_span(tcx)
157 impl<'tcx, T: Clone + Hash + Eq + Debug> Key for ty::ParamEnvAnd<'tcx, T> {
158 fn map_crate(&self) -> CrateNum {
161 fn default_span(&self, _: TyCtxt) -> Span {
166 trait Value<'tcx>: Sized {
167 fn from_cycle_error<'a>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Self;
170 impl<'tcx, T> Value<'tcx> for T {
171 default fn from_cycle_error<'a>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> T {
172 tcx.sess.abort_if_errors();
173 bug!("Value::from_cycle_error called without errors");
177 impl<'tcx, T: Default> Value<'tcx> for T {
178 default fn from_cycle_error<'a>(_: TyCtxt<'a, 'tcx, 'tcx>) -> T {
183 impl<'tcx> Value<'tcx> for Ty<'tcx> {
184 fn from_cycle_error<'a>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Ty<'tcx> {
189 impl<'tcx> Value<'tcx> for ty::DtorckConstraint<'tcx> {
190 fn from_cycle_error<'a>(_: TyCtxt<'a, 'tcx, 'tcx>) -> Self {
195 impl<'tcx> Value<'tcx> for ty::SymbolName {
196 fn from_cycle_error<'a>(_: TyCtxt<'a, 'tcx, 'tcx>) -> Self {
197 ty::SymbolName { name: Symbol::intern("<error>").as_str() }
201 struct QueryMap<D: QueryDescription> {
202 phantom: PhantomData<D>,
203 map: FxHashMap<D::Key, QueryValue<D::Value>>,
206 struct QueryValue<T> {
209 diagnostics: Option<Box<QueryDiagnostics>>,
212 struct QueryDiagnostics {
213 diagnostics: Vec<Diagnostic>,
214 emitted_diagnostics: Cell<bool>,
217 impl<M: QueryDescription> QueryMap<M> {
218 fn new() -> QueryMap<M> {
220 phantom: PhantomData,
226 struct CycleError<'a, 'tcx: 'a> {
228 cycle: RefMut<'a, [(Span, Query<'tcx>)]>,
231 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
232 fn report_cycle(self, CycleError { span, cycle }: CycleError)
233 -> DiagnosticBuilder<'a>
235 // Subtle: release the refcell lock before invoking `describe()`
236 // below by dropping `cycle`.
237 let stack = cycle.to_vec();
240 assert!(!stack.is_empty());
242 // Disable naming impls with types in this path, since that
243 // sometimes cycles itself, leading to extra cycle errors.
244 // (And cycle errors around impls tend to occur during the
245 // collect/coherence phases anyhow.)
246 item_path::with_forced_impl_filename_line(|| {
248 struct_span_err!(self.sess, span, E0391,
249 "unsupported cyclic reference between types/traits detected");
250 err.span_label(span, "cyclic reference");
252 err.span_note(stack[0].0, &format!("the cycle begins when {}...",
253 stack[0].1.describe(self)));
255 for &(span, ref query) in &stack[1..] {
256 err.span_note(span, &format!("...which then requires {}...",
257 query.describe(self)));
260 err.note(&format!("...which then again requires {}, completing the cycle.",
261 stack[0].1.describe(self)));
267 fn cycle_check<F, R>(self, span: Span, query: Query<'gcx>, compute: F)
268 -> Result<R, CycleError<'a, 'gcx>>
269 where F: FnOnce() -> R
272 let mut stack = self.maps.query_stack.borrow_mut();
273 if let Some((i, _)) = stack.iter().enumerate().rev()
274 .find(|&(_, &(_, ref q))| *q == query) {
275 return Err(CycleError {
277 cycle: RefMut::map(stack, |stack| &mut stack[i..])
280 stack.push((span, query));
283 let result = compute();
285 self.maps.query_stack.borrow_mut().pop();
291 pub trait QueryConfig {
292 type Key: Eq + Hash + Clone;
296 trait QueryDescription: QueryConfig {
297 fn describe(tcx: TyCtxt, key: Self::Key) -> String;
300 impl<M: QueryConfig<Key=DefId>> QueryDescription for M {
301 default fn describe(tcx: TyCtxt, def_id: DefId) -> String {
302 format!("processing `{}`", tcx.item_path_str(def_id))
306 impl<'tcx> QueryDescription for queries::is_copy_raw<'tcx> {
307 fn describe(_tcx: TyCtxt, env: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> String {
308 format!("computing whether `{}` is `Copy`", env.value)
312 impl<'tcx> QueryDescription for queries::is_sized_raw<'tcx> {
313 fn describe(_tcx: TyCtxt, env: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> String {
314 format!("computing whether `{}` is `Sized`", env.value)
318 impl<'tcx> QueryDescription for queries::is_freeze_raw<'tcx> {
319 fn describe(_tcx: TyCtxt, env: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> String {
320 format!("computing whether `{}` is freeze", env.value)
324 impl<'tcx> QueryDescription for queries::needs_drop_raw<'tcx> {
325 fn describe(_tcx: TyCtxt, env: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> String {
326 format!("computing whether `{}` needs drop", env.value)
330 impl<'tcx> QueryDescription for queries::layout_raw<'tcx> {
331 fn describe(_tcx: TyCtxt, env: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> String {
332 format!("computing layout of `{}`", env.value)
336 impl<'tcx> QueryDescription for queries::super_predicates_of<'tcx> {
337 fn describe(tcx: TyCtxt, def_id: DefId) -> String {
338 format!("computing the supertraits of `{}`",
339 tcx.item_path_str(def_id))
343 impl<'tcx> QueryDescription for queries::type_param_predicates<'tcx> {
344 fn describe(tcx: TyCtxt, (_, def_id): (DefId, DefId)) -> String {
345 let id = tcx.hir.as_local_node_id(def_id).unwrap();
346 format!("computing the bounds for type parameter `{}`",
347 tcx.hir.ty_param_name(id))
351 impl<'tcx> QueryDescription for queries::coherent_trait<'tcx> {
352 fn describe(tcx: TyCtxt, (_, def_id): (CrateNum, DefId)) -> String {
353 format!("coherence checking all impls of trait `{}`",
354 tcx.item_path_str(def_id))
358 impl<'tcx> QueryDescription for queries::crate_inherent_impls<'tcx> {
359 fn describe(_: TyCtxt, k: CrateNum) -> String {
360 format!("all inherent impls defined in crate `{:?}`", k)
364 impl<'tcx> QueryDescription for queries::crate_inherent_impls_overlap_check<'tcx> {
365 fn describe(_: TyCtxt, _: CrateNum) -> String {
366 format!("check for overlap between inherent impls defined in this crate")
370 impl<'tcx> QueryDescription for queries::crate_variances<'tcx> {
371 fn describe(_tcx: TyCtxt, _: CrateNum) -> String {
372 format!("computing the variances for items in this crate")
376 impl<'tcx> QueryDescription for queries::mir_shims<'tcx> {
377 fn describe(tcx: TyCtxt, def: ty::InstanceDef<'tcx>) -> String {
378 format!("generating MIR shim for `{}`",
379 tcx.item_path_str(def.def_id()))
383 impl<'tcx> QueryDescription for queries::privacy_access_levels<'tcx> {
384 fn describe(_: TyCtxt, _: CrateNum) -> String {
385 format!("privacy access levels")
389 impl<'tcx> QueryDescription for queries::typeck_item_bodies<'tcx> {
390 fn describe(_: TyCtxt, _: CrateNum) -> String {
391 format!("type-checking all item bodies")
395 impl<'tcx> QueryDescription for queries::reachable_set<'tcx> {
396 fn describe(_: TyCtxt, _: CrateNum) -> String {
397 format!("reachability")
401 impl<'tcx> QueryDescription for queries::const_eval<'tcx> {
402 fn describe(tcx: TyCtxt, key: ty::ParamEnvAnd<'tcx, (DefId, &'tcx Substs<'tcx>)>) -> String {
403 format!("const-evaluating `{}`", tcx.item_path_str(key.value.0))
407 impl<'tcx> QueryDescription for queries::mir_keys<'tcx> {
408 fn describe(_: TyCtxt, _: CrateNum) -> String {
409 format!("getting a list of all mir_keys")
413 impl<'tcx> QueryDescription for queries::symbol_name<'tcx> {
414 fn describe(_tcx: TyCtxt, instance: ty::Instance<'tcx>) -> String {
415 format!("computing the symbol for `{}`", instance)
419 impl<'tcx> QueryDescription for queries::describe_def<'tcx> {
420 fn describe(_: TyCtxt, _: DefId) -> String {
425 impl<'tcx> QueryDescription for queries::def_span<'tcx> {
426 fn describe(_: TyCtxt, _: DefId) -> String {
432 impl<'tcx> QueryDescription for queries::stability<'tcx> {
433 fn describe(_: TyCtxt, _: DefId) -> String {
438 impl<'tcx> QueryDescription for queries::deprecation<'tcx> {
439 fn describe(_: TyCtxt, _: DefId) -> String {
444 impl<'tcx> QueryDescription for queries::item_attrs<'tcx> {
445 fn describe(_: TyCtxt, _: DefId) -> String {
450 impl<'tcx> QueryDescription for queries::is_exported_symbol<'tcx> {
451 fn describe(_: TyCtxt, _: DefId) -> String {
452 bug!("is_exported_symbol")
456 impl<'tcx> QueryDescription for queries::fn_arg_names<'tcx> {
457 fn describe(_: TyCtxt, _: DefId) -> String {
462 impl<'tcx> QueryDescription for queries::impl_parent<'tcx> {
463 fn describe(_: TyCtxt, _: DefId) -> String {
468 impl<'tcx> QueryDescription for queries::trait_of_item<'tcx> {
469 fn describe(_: TyCtxt, _: DefId) -> String {
470 bug!("trait_of_item")
474 impl<'tcx> QueryDescription for queries::item_body_nested_bodies<'tcx> {
475 fn describe(tcx: TyCtxt, def_id: DefId) -> String {
476 format!("nested item bodies of `{}`", tcx.item_path_str(def_id))
480 impl<'tcx> QueryDescription for queries::const_is_rvalue_promotable_to_static<'tcx> {
481 fn describe(tcx: TyCtxt, def_id: DefId) -> String {
482 format!("const checking if rvalue is promotable to static `{}`",
483 tcx.item_path_str(def_id))
487 impl<'tcx> QueryDescription for queries::is_mir_available<'tcx> {
488 fn describe(tcx: TyCtxt, def_id: DefId) -> String {
489 format!("checking if item is mir available: `{}`",
490 tcx.item_path_str(def_id))
494 impl<'tcx> QueryDescription for queries::trait_impls_of<'tcx> {
495 fn describe(tcx: TyCtxt, def_id: DefId) -> String {
496 format!("trait impls of `{}`", tcx.item_path_str(def_id))
500 impl<'tcx> QueryDescription for queries::is_object_safe<'tcx> {
501 fn describe(tcx: TyCtxt, def_id: DefId) -> String {
502 format!("determine object safety of trait `{}`", tcx.item_path_str(def_id))
506 impl<'tcx> QueryDescription for queries::is_const_fn<'tcx> {
507 fn describe(tcx: TyCtxt, def_id: DefId) -> String {
508 format!("checking if item is const fn: `{}`", tcx.item_path_str(def_id))
512 impl<'tcx> QueryDescription for queries::dylib_dependency_formats<'tcx> {
513 fn describe(_: TyCtxt, _: CrateNum) -> String {
514 "dylib dependency formats of crate".to_string()
518 impl<'tcx> QueryDescription for queries::is_panic_runtime<'tcx> {
519 fn describe(_: TyCtxt, _: CrateNum) -> String {
520 "checking if the crate is_panic_runtime".to_string()
524 impl<'tcx> QueryDescription for queries::is_compiler_builtins<'tcx> {
525 fn describe(_: TyCtxt, _: CrateNum) -> String {
526 "checking if the crate is_compiler_builtins".to_string()
530 impl<'tcx> QueryDescription for queries::has_global_allocator<'tcx> {
531 fn describe(_: TyCtxt, _: CrateNum) -> String {
532 "checking if the crate has_global_allocator".to_string()
536 impl<'tcx> QueryDescription for queries::extern_crate<'tcx> {
537 fn describe(_: TyCtxt, _: DefId) -> String {
538 "getting crate's ExternCrateData".to_string()
542 impl<'tcx> QueryDescription for queries::lint_levels<'tcx> {
543 fn describe(_tcx: TyCtxt, _: CrateNum) -> String {
544 format!("computing the lint levels for items in this crate")
548 impl<'tcx> QueryDescription for queries::specializes<'tcx> {
549 fn describe(_tcx: TyCtxt, _: (DefId, DefId)) -> String {
550 format!("computing whether impls specialize one another")
554 impl<'tcx> QueryDescription for queries::in_scope_traits<'tcx> {
555 fn describe(_tcx: TyCtxt, _: HirId) -> String {
556 format!("fetching the traits in scope at a particular ast node")
560 impl<'tcx> QueryDescription for queries::module_exports<'tcx> {
561 fn describe(_tcx: TyCtxt, _: HirId) -> String {
562 format!("fetching the exported items for a module")
566 impl<'tcx> QueryDescription for queries::is_no_builtins<'tcx> {
567 fn describe(_tcx: TyCtxt, _: CrateNum) -> String {
568 format!("test whether a crate has #![no_builtins]")
572 impl<'tcx> QueryDescription for queries::panic_strategy<'tcx> {
573 fn describe(_tcx: TyCtxt, _: CrateNum) -> String {
574 format!("query a crate's configured panic strategy")
578 impl<'tcx> QueryDescription for queries::is_profiler_runtime<'tcx> {
579 fn describe(_tcx: TyCtxt, _: CrateNum) -> String {
580 format!("query a crate is #![profiler_runtime]")
584 impl<'tcx> QueryDescription for queries::is_sanitizer_runtime<'tcx> {
585 fn describe(_tcx: TyCtxt, _: CrateNum) -> String {
586 format!("query a crate is #![sanitizer_runtime]")
590 impl<'tcx> QueryDescription for queries::exported_symbols<'tcx> {
591 fn describe(_tcx: TyCtxt, _: CrateNum) -> String {
592 format!("looking up the exported symbols of a crate")
596 impl<'tcx> QueryDescription for queries::native_libraries<'tcx> {
597 fn describe(_tcx: TyCtxt, _: CrateNum) -> String {
598 format!("looking up the native libraries of a linked crate")
602 impl<'tcx> QueryDescription for queries::plugin_registrar_fn<'tcx> {
603 fn describe(_tcx: TyCtxt, _: CrateNum) -> String {
604 format!("looking up the plugin registrar for a crate")
608 impl<'tcx> QueryDescription for queries::derive_registrar_fn<'tcx> {
609 fn describe(_tcx: TyCtxt, _: CrateNum) -> String {
610 format!("looking up the derive registrar for a crate")
614 // If enabled, send a message to the profile-queries thread
615 macro_rules! profq_msg {
616 ($tcx:expr, $msg:expr) => {
617 if cfg!(debug_assertions) {
618 if $tcx.sess.profile_queries() {
625 // If enabled, format a key using its debug string, which can be
626 // expensive to compute (in terms of time).
627 macro_rules! profq_key {
628 ($tcx:expr, $key:expr) => {
629 if cfg!(debug_assertions) {
630 if $tcx.sess.profile_queries_and_keys() {
631 Some(format!("{:?}", $key))
637 macro_rules! define_maps {
640 [$($modifiers:tt)*] fn $name:ident: $node:ident($K:ty) -> $V:ty,)*) => {
643 input: ($(([$($modifiers)*] [$($attr)*] [$name]))*)
646 impl<$tcx> Maps<$tcx> {
647 pub fn new(providers: IndexVec<CrateNum, Providers<$tcx>>)
651 query_stack: RefCell::new(vec![]),
652 $($name: RefCell::new(QueryMap::new())),*
658 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
659 pub enum Query<$tcx> {
660 $($(#[$attr])* $name($K)),*
664 #[derive(Clone, Debug, PartialEq, Eq)]
666 $($name(Option<String>)),*
669 impl<$tcx> Query<$tcx> {
670 pub fn describe(&self, tcx: TyCtxt) -> String {
671 let (r, name) = match *self {
672 $(Query::$name(key) => {
673 (queries::$name::describe(tcx, key), stringify!($name))
676 if tcx.sess.verbose() {
677 format!("{} [{}]", r, name)
685 use std::marker::PhantomData;
687 $(#[allow(bad_style)]
688 pub struct $name<$tcx> {
689 data: PhantomData<&$tcx ()>
693 $(impl<$tcx> QueryConfig for queries::$name<$tcx> {
698 impl<'a, $tcx, 'lcx> queries::$name<$tcx> {
700 fn to_dep_node(tcx: TyCtxt<'a, $tcx, 'lcx>, key: &$K) -> DepNode {
701 use dep_graph::DepConstructor::*;
703 DepNode::new(tcx, $node(*key))
706 fn try_get_with<F, R>(tcx: TyCtxt<'a, $tcx, 'lcx>,
710 -> Result<R, CycleError<'a, $tcx>>
711 where F: FnOnce(&$V) -> R
713 debug!("ty::queries::{}::try_get_with(key={:?}, span={:?})",
719 ProfileQueriesMsg::QueryBegin(
721 QueryMsg::$name(profq_key!(tcx, key))
725 if let Some(value) = tcx.maps.$name.borrow().map.get(&key) {
726 if let Some(ref d) = value.diagnostics {
727 if !d.emitted_diagnostics.get() {
728 d.emitted_diagnostics.set(true);
729 let handle = tcx.sess.diagnostic();
730 for diagnostic in d.diagnostics.iter() {
731 DiagnosticBuilder::new_diagnostic(handle, diagnostic.clone())
736 profq_msg!(tcx, ProfileQueriesMsg::CacheHit);
737 tcx.dep_graph.read_index(value.index);
738 return Ok(f(&value.value));
740 // else, we are going to run the provider:
741 profq_msg!(tcx, ProfileQueriesMsg::ProviderBegin);
743 // FIXME(eddyb) Get more valid Span's on queries.
744 // def_span guard is necessary to prevent a recursive loop,
745 // default_span calls def_span query internally.
746 if span == DUMMY_SP && stringify!($name) != "def_span" {
747 span = key.default_span(tcx)
750 let res = tcx.cycle_check(span, Query::$name(key), || {
751 let dep_node = Self::to_dep_node(tcx, &key);
753 tcx.sess.diagnostic().track_diagnostics(|| {
754 if dep_node.kind.is_anon() {
755 tcx.dep_graph.with_anon_task(dep_node.kind, || {
756 let provider = tcx.maps.providers[key.map_crate()].$name;
757 provider(tcx.global_tcx(), key)
760 fn run_provider<'a, 'tcx, 'lcx>(tcx: TyCtxt<'a, 'tcx, 'lcx>,
763 let provider = tcx.maps.providers[key.map_crate()].$name;
764 provider(tcx.global_tcx(), key)
767 tcx.dep_graph.with_task(dep_node, tcx, key, run_provider)
771 profq_msg!(tcx, ProfileQueriesMsg::ProviderEnd);
772 let ((result, dep_node_index), diagnostics) = res;
774 tcx.dep_graph.read_index(dep_node_index);
776 let value = QueryValue {
778 index: dep_node_index,
779 diagnostics: if diagnostics.len() == 0 {
782 Some(Box::new(QueryDiagnostics {
784 emitted_diagnostics: Cell::new(true),
798 pub fn try_get(tcx: TyCtxt<'a, $tcx, 'lcx>, span: Span, key: $K)
799 -> Result<$V, DiagnosticBuilder<'a>> {
800 match Self::try_get_with(tcx, span, key, Clone::clone) {
802 Err(e) => Err(tcx.report_cycle(e)),
806 pub fn force(tcx: TyCtxt<'a, $tcx, 'lcx>, span: Span, key: $K) {
807 // Ignore dependencies, since we not reading the computed value
808 let _task = tcx.dep_graph.in_ignore();
810 match Self::try_get_with(tcx, span, key, |_| ()) {
812 Err(e) => tcx.report_cycle(e).emit(),
817 #[derive(Copy, Clone)]
818 pub struct TyCtxtAt<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
819 pub tcx: TyCtxt<'a, 'gcx, 'tcx>,
823 impl<'a, 'gcx, 'tcx> Deref for TyCtxtAt<'a, 'gcx, 'tcx> {
824 type Target = TyCtxt<'a, 'gcx, 'tcx>;
825 fn deref(&self) -> &Self::Target {
830 impl<'a, $tcx, 'lcx> TyCtxt<'a, $tcx, 'lcx> {
831 /// Return a transparent wrapper for `TyCtxt` which uses
832 /// `span` as the location of queries performed through it.
833 pub fn at(self, span: Span) -> TyCtxtAt<'a, $tcx, 'lcx> {
841 pub fn $name(self, key: $K) -> $V {
842 self.at(DUMMY_SP).$name(key)
846 impl<'a, $tcx, 'lcx> TyCtxtAt<'a, $tcx, 'lcx> {
848 pub fn $name(self, key: $K) -> $V {
849 queries::$name::try_get(self.tcx, self.span, key).unwrap_or_else(|mut e| {
851 Value::from_cycle_error(self.global_tcx())
856 define_provider_struct! {
858 input: ($(([$($modifiers)*] [$name] [$K] [$V]))*),
862 impl<$tcx> Copy for Providers<$tcx> {}
863 impl<$tcx> Clone for Providers<$tcx> {
864 fn clone(&self) -> Self { *self }
869 macro_rules! define_map_struct {
872 input: $input:tt) => {
883 output: ($($output:tt)*)) => {
884 pub struct Maps<$tcx> {
885 providers: IndexVec<CrateNum, Providers<$tcx>>,
886 query_stack: RefCell<Vec<(Span, Query<$tcx>)>>,
891 // Field recognized and ready to shift into the output
893 ready: ([$($pub:tt)*] [$($attr:tt)*] [$name:ident]),
895 output: ($($output:tt)*)) => {
900 $(#[$attr])* $($pub)* $name: RefCell<QueryMap<queries::$name<$tcx>>>,)
904 // No modifiers left? This is a private item.
906 input: (([] $attrs:tt $name:tt) $($input:tt)*),
907 output: $output:tt) => {
910 ready: ([] $attrs $name),
916 // Skip other modifiers
918 input: (([$other_modifier:tt $($modifiers:tt)*] $($fields:tt)*) $($input:tt)*),
919 output: $output:tt) => {
922 input: (([$($modifiers)*] $($fields)*) $($input)*),
928 macro_rules! define_provider_struct {
930 (tcx: $tcx:tt, input: $input:tt) => {
931 define_provider_struct! {
941 output: ($(([$name:ident] [$K:ty] [$R:ty]))*)) => {
942 pub struct Providers<$tcx> {
943 $(pub $name: for<'a> fn(TyCtxt<'a, $tcx, $tcx>, $K) -> $R,)*
946 impl<$tcx> Default for Providers<$tcx> {
947 fn default() -> Self {
948 $(fn $name<'a, $tcx>(_: TyCtxt<'a, $tcx, $tcx>, key: $K) -> $R {
949 bug!("tcx.maps.{}({:?}) unsupported by its crate",
950 stringify!($name), key);
952 Providers { $($name),* }
957 // Something ready to shift:
959 ready: ($name:tt $K:tt $V:tt),
961 output: ($($output:tt)*)) => {
962 define_provider_struct! {
965 output: ($($output)* ($name $K $V))
969 // Regular queries produce a `V` only.
971 input: (([] $name:tt $K:tt $V:tt) $($input:tt)*),
972 output: $output:tt) => {
973 define_provider_struct! {
975 ready: ($name $K $V),
983 input: (([$other_modifier:tt $($modifiers:tt)*] $($fields:tt)*) $($input:tt)*),
984 output: $output:tt) => {
985 define_provider_struct! {
987 input: (([$($modifiers)*] $($fields)*) $($input)*),
993 // Each of these maps also corresponds to a method on a
994 // `Provider` trait for requesting a value of that type,
995 // and a method on `Maps` itself for doing that in a
996 // a way that memoizes and does dep-graph tracking,
997 // wrapping around the actual chain of providers that
998 // the driver creates (using several `rustc_*` crates).
999 define_maps! { <'tcx>
1000 /// Records the type of every item.
1001 [] fn type_of: TypeOfItem(DefId) -> Ty<'tcx>,
1003 /// Maps from the def-id of an item (trait/struct/enum/fn) to its
1004 /// associated generics and predicates.
1005 [] fn generics_of: GenericsOfItem(DefId) -> &'tcx ty::Generics,
1006 [] fn predicates_of: PredicatesOfItem(DefId) -> ty::GenericPredicates<'tcx>,
1008 /// Maps from the def-id of a trait to the list of
1009 /// super-predicates. This is a subset of the full list of
1010 /// predicates. We store these in a separate map because we must
1011 /// evaluate them even during type conversion, often before the
1012 /// full predicates are available (note that supertraits have
1013 /// additional acyclicity requirements).
1014 [] fn super_predicates_of: SuperPredicatesOfItem(DefId) -> ty::GenericPredicates<'tcx>,
1016 /// To avoid cycles within the predicates of a single item we compute
1017 /// per-type-parameter predicates for resolving `T::AssocTy`.
1018 [] fn type_param_predicates: type_param_predicates((DefId, DefId))
1019 -> ty::GenericPredicates<'tcx>,
1021 [] fn trait_def: TraitDefOfItem(DefId) -> &'tcx ty::TraitDef,
1022 [] fn adt_def: AdtDefOfItem(DefId) -> &'tcx ty::AdtDef,
1023 [] fn adt_destructor: AdtDestructor(DefId) -> Option<ty::Destructor>,
1024 [] fn adt_sized_constraint: SizedConstraint(DefId) -> &'tcx [Ty<'tcx>],
1025 [] fn adt_dtorck_constraint: DtorckConstraint(DefId) -> ty::DtorckConstraint<'tcx>,
1027 /// True if this is a const fn
1028 [] fn is_const_fn: IsConstFn(DefId) -> bool,
1030 /// True if this is a foreign item (i.e., linked via `extern { ... }`).
1031 [] fn is_foreign_item: IsForeignItem(DefId) -> bool,
1033 /// True if this is a default impl (aka impl Foo for ..)
1034 [] fn is_default_impl: IsDefaultImpl(DefId) -> bool,
1036 /// Get a map with the variance of every item; use `item_variance`
1038 [] fn crate_variances: crate_variances(CrateNum) -> Rc<ty::CrateVariancesMap>,
1040 /// Maps from def-id of a type or region parameter to its
1041 /// (inferred) variance.
1042 [] fn variances_of: ItemVariances(DefId) -> Rc<Vec<ty::Variance>>,
1044 /// Maps from an impl/trait def-id to a list of the def-ids of its items
1045 [] fn associated_item_def_ids: AssociatedItemDefIds(DefId) -> Rc<Vec<DefId>>,
1047 /// Maps from a trait item to the trait item "descriptor"
1048 [] fn associated_item: AssociatedItems(DefId) -> ty::AssociatedItem,
1050 [] fn impl_trait_ref: ImplTraitRef(DefId) -> Option<ty::TraitRef<'tcx>>,
1051 [] fn impl_polarity: ImplPolarity(DefId) -> hir::ImplPolarity,
1053 /// Maps a DefId of a type to a list of its inherent impls.
1054 /// Contains implementations of methods that are inherent to a type.
1055 /// Methods in these implementations don't need to be exported.
1056 [] fn inherent_impls: InherentImpls(DefId) -> Rc<Vec<DefId>>,
1058 /// Set of all the def-ids in this crate that have MIR associated with
1059 /// them. This includes all the body owners, but also things like struct
1061 [] fn mir_keys: mir_keys(CrateNum) -> Rc<DefIdSet>,
1063 /// Maps DefId's that have an associated Mir to the result
1064 /// of the MIR qualify_consts pass. The actual meaning of
1065 /// the value isn't known except to the pass itself.
1066 [] fn mir_const_qualif: MirConstQualif(DefId) -> (u8, Rc<IdxSetBuf<mir::Local>>),
1068 /// Fetch the MIR for a given def-id up till the point where it is
1069 /// ready for const evaluation.
1071 /// See the README for the `mir` module for details.
1072 [] fn mir_const: MirConst(DefId) -> &'tcx Steal<mir::Mir<'tcx>>,
1074 [] fn mir_validated: MirValidated(DefId) -> &'tcx Steal<mir::Mir<'tcx>>,
1076 /// MIR after our optimization passes have run. This is MIR that is ready
1077 /// for trans. This is also the only query that can fetch non-local MIR, at present.
1078 [] fn optimized_mir: MirOptimized(DefId) -> &'tcx mir::Mir<'tcx>,
1080 /// Type of each closure. The def ID is the ID of the
1081 /// expression defining the closure.
1082 [] fn closure_kind: ClosureKind(DefId) -> ty::ClosureKind,
1084 /// The signature of functions and closures.
1085 [] fn fn_sig: FnSignature(DefId) -> ty::PolyFnSig<'tcx>,
1087 /// Records the signature of each generator. The def ID is the ID of the
1088 /// expression defining the closure.
1089 [] fn generator_sig: GenSignature(DefId) -> Option<ty::PolyGenSig<'tcx>>,
1091 /// Caches CoerceUnsized kinds for impls on custom types.
1092 [] fn coerce_unsized_info: CoerceUnsizedInfo(DefId)
1093 -> ty::adjustment::CoerceUnsizedInfo,
1095 [] fn typeck_item_bodies: typeck_item_bodies_dep_node(CrateNum) -> CompileResult,
1097 [] fn typeck_tables_of: TypeckTables(DefId) -> &'tcx ty::TypeckTables<'tcx>,
1099 [] fn has_typeck_tables: HasTypeckTables(DefId) -> bool,
1101 [] fn coherent_trait: coherent_trait_dep_node((CrateNum, DefId)) -> (),
1103 [] fn borrowck: BorrowCheck(DefId) -> (),
1104 // FIXME: shouldn't this return a `Result<(), BorrowckErrors>` instead?
1105 [] fn mir_borrowck: MirBorrowCheck(DefId) -> (),
1107 /// Gets a complete map from all types to their inherent impls.
1108 /// Not meant to be used directly outside of coherence.
1109 /// (Defined only for LOCAL_CRATE)
1110 [] fn crate_inherent_impls: crate_inherent_impls_dep_node(CrateNum) -> CrateInherentImpls,
1112 /// Checks all types in the krate for overlap in their inherent impls. Reports errors.
1113 /// Not meant to be used directly outside of coherence.
1114 /// (Defined only for LOCAL_CRATE)
1115 [] fn crate_inherent_impls_overlap_check: inherent_impls_overlap_check_dep_node(CrateNum) -> (),
1117 /// Results of evaluating const items or constants embedded in
1118 /// other items (such as enum variant explicit discriminants).
1119 [] fn const_eval: const_eval_dep_node(ty::ParamEnvAnd<'tcx, (DefId, &'tcx Substs<'tcx>)>)
1120 -> const_val::EvalResult<'tcx>,
1122 /// Performs the privacy check and computes "access levels".
1123 [] fn privacy_access_levels: PrivacyAccessLevels(CrateNum) -> Rc<AccessLevels>,
1125 [] fn reachable_set: reachability_dep_node(CrateNum) -> Rc<NodeSet>,
1127 /// Per-body `region::ScopeTree`. The `DefId` should be the owner-def-id for the body;
1128 /// in the case of closures, this will be redirected to the enclosing function.
1129 [] fn region_scope_tree: RegionScopeTree(DefId) -> Rc<region::ScopeTree>,
1131 [] fn mir_shims: mir_shim_dep_node(ty::InstanceDef<'tcx>) -> &'tcx mir::Mir<'tcx>,
1133 [] fn def_symbol_name: SymbolName(DefId) -> ty::SymbolName,
1134 [] fn symbol_name: symbol_name_dep_node(ty::Instance<'tcx>) -> ty::SymbolName,
1136 [] fn describe_def: DescribeDef(DefId) -> Option<Def>,
1137 [] fn def_span: DefSpan(DefId) -> Span,
1138 [] fn stability: Stability(DefId) -> Option<attr::Stability>,
1139 [] fn deprecation: Deprecation(DefId) -> Option<attr::Deprecation>,
1140 [] fn item_attrs: ItemAttrs(DefId) -> Rc<[ast::Attribute]>,
1141 [] fn fn_arg_names: FnArgNames(DefId) -> Vec<ast::Name>,
1142 [] fn impl_parent: ImplParent(DefId) -> Option<DefId>,
1143 [] fn trait_of_item: TraitOfItem(DefId) -> Option<DefId>,
1144 [] fn is_exported_symbol: IsExportedSymbol(DefId) -> bool,
1145 [] fn item_body_nested_bodies: ItemBodyNestedBodies(DefId)
1146 -> Rc<BTreeMap<hir::BodyId, hir::Body>>,
1147 [] fn const_is_rvalue_promotable_to_static: ConstIsRvaluePromotableToStatic(DefId) -> bool,
1148 [] fn is_mir_available: IsMirAvailable(DefId) -> bool,
1150 [] fn trait_impls_of: TraitImpls(DefId) -> Rc<ty::trait_def::TraitImpls>,
1151 [] fn specialization_graph_of: SpecializationGraph(DefId) -> Rc<specialization_graph::Graph>,
1152 [] fn is_object_safe: ObjectSafety(DefId) -> bool,
1154 // Get the ParameterEnvironment for a given item; this environment
1155 // will be in "user-facing" mode, meaning that it is suitabe for
1156 // type-checking etc, and it does not normalize specializable
1157 // associated types. This is almost always what you want,
1158 // unless you are doing MIR optimizations, in which case you
1159 // might want to use `reveal_all()` method to change modes.
1160 [] fn param_env: ParamEnv(DefId) -> ty::ParamEnv<'tcx>,
1162 // Trait selection queries. These are best used by invoking `ty.moves_by_default()`,
1163 // `ty.is_copy()`, etc, since that will prune the environment where possible.
1164 [] fn is_copy_raw: is_copy_dep_node(ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> bool,
1165 [] fn is_sized_raw: is_sized_dep_node(ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> bool,
1166 [] fn is_freeze_raw: is_freeze_dep_node(ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> bool,
1167 [] fn needs_drop_raw: needs_drop_dep_node(ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> bool,
1168 [] fn layout_raw: layout_dep_node(ty::ParamEnvAnd<'tcx, Ty<'tcx>>)
1169 -> Result<&'tcx Layout, LayoutError<'tcx>>,
1171 [] fn dylib_dependency_formats: DylibDepFormats(CrateNum)
1172 -> Rc<Vec<(CrateNum, LinkagePreference)>>,
1174 [] fn is_panic_runtime: IsPanicRuntime(CrateNum) -> bool,
1175 [] fn is_compiler_builtins: IsCompilerBuiltins(CrateNum) -> bool,
1176 [] fn has_global_allocator: HasGlobalAllocator(CrateNum) -> bool,
1177 [] fn is_sanitizer_runtime: IsSanitizerRuntime(CrateNum) -> bool,
1178 [] fn is_profiler_runtime: IsProfilerRuntime(CrateNum) -> bool,
1179 [] fn panic_strategy: GetPanicStrategy(CrateNum) -> PanicStrategy,
1180 [] fn is_no_builtins: IsNoBuiltins(CrateNum) -> bool,
1182 [] fn extern_crate: ExternCrate(DefId) -> Rc<Option<ExternCrate>>,
1184 [] fn specializes: specializes_node((DefId, DefId)) -> bool,
1185 [] fn in_scope_traits: InScopeTraits(HirId) -> Option<Rc<Vec<TraitCandidate>>>,
1186 [] fn module_exports: ModuleExports(HirId) -> Option<Rc<Vec<Export>>>,
1187 [] fn lint_levels: lint_levels_node(CrateNum) -> Rc<lint::LintLevelMap>,
1189 [] fn impl_defaultness: ImplDefaultness(DefId) -> hir::Defaultness,
1190 [] fn exported_symbols: ExportedSymbols(CrateNum) -> Rc<Vec<DefId>>,
1191 [] fn native_libraries: NativeLibraries(CrateNum) -> Rc<Vec<NativeLibrary>>,
1192 [] fn plugin_registrar_fn: PluginRegistrarFn(CrateNum) -> Option<DefId>,
1193 [] fn derive_registrar_fn: DeriveRegistrarFn(CrateNum) -> Option<DefId>,
1196 fn type_param_predicates<'tcx>((item_id, param_id): (DefId, DefId)) -> DepConstructor<'tcx> {
1197 DepConstructor::TypeParamPredicates {
1203 fn coherent_trait_dep_node<'tcx>((_, def_id): (CrateNum, DefId)) -> DepConstructor<'tcx> {
1204 DepConstructor::CoherenceCheckTrait(def_id)
1207 fn crate_inherent_impls_dep_node<'tcx>(_: CrateNum) -> DepConstructor<'tcx> {
1208 DepConstructor::Coherence
1211 fn inherent_impls_overlap_check_dep_node<'tcx>(_: CrateNum) -> DepConstructor<'tcx> {
1212 DepConstructor::CoherenceInherentImplOverlapCheck
1215 fn reachability_dep_node<'tcx>(_: CrateNum) -> DepConstructor<'tcx> {
1216 DepConstructor::Reachability
1219 fn mir_shim_dep_node<'tcx>(instance_def: ty::InstanceDef<'tcx>) -> DepConstructor<'tcx> {
1220 DepConstructor::MirShim {
1225 fn symbol_name_dep_node<'tcx>(instance: ty::Instance<'tcx>) -> DepConstructor<'tcx> {
1226 DepConstructor::InstanceSymbolName { instance }
1229 fn typeck_item_bodies_dep_node<'tcx>(_: CrateNum) -> DepConstructor<'tcx> {
1230 DepConstructor::TypeckBodiesKrate
1233 fn const_eval_dep_node<'tcx>(_: ty::ParamEnvAnd<'tcx, (DefId, &'tcx Substs<'tcx>)>)
1234 -> DepConstructor<'tcx> {
1235 DepConstructor::ConstEval
1238 fn mir_keys<'tcx>(_: CrateNum) -> DepConstructor<'tcx> {
1239 DepConstructor::MirKeys
1242 fn crate_variances<'tcx>(_: CrateNum) -> DepConstructor<'tcx> {
1243 DepConstructor::CrateVariances
1246 fn is_copy_dep_node<'tcx>(_: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> DepConstructor<'tcx> {
1247 DepConstructor::IsCopy
1250 fn is_sized_dep_node<'tcx>(_: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> DepConstructor<'tcx> {
1251 DepConstructor::IsSized
1254 fn is_freeze_dep_node<'tcx>(_: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> DepConstructor<'tcx> {
1255 DepConstructor::IsFreeze
1258 fn needs_drop_dep_node<'tcx>(_: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> DepConstructor<'tcx> {
1259 DepConstructor::NeedsDrop
1262 fn layout_dep_node<'tcx>(_: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> DepConstructor<'tcx> {
1263 DepConstructor::Layout
1266 fn lint_levels_node<'tcx>(_: CrateNum) -> DepConstructor<'tcx> {
1267 DepConstructor::LintLevels
1270 fn specializes_node<'tcx>((a, b): (DefId, DefId)) -> DepConstructor<'tcx> {
1271 DepConstructor::Specializes { impl1: a, impl2: b }