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 // If enabled, send a message to the profile-queries thread
603 macro_rules! profq_msg {
604 ($tcx:expr, $msg:expr) => {
605 if cfg!(debug_assertions) {
606 if $tcx.sess.profile_queries() {
613 // If enabled, format a key using its debug string, which can be
614 // expensive to compute (in terms of time).
615 macro_rules! profq_key {
616 ($tcx:expr, $key:expr) => {
617 if cfg!(debug_assertions) {
618 if $tcx.sess.profile_queries_and_keys() {
619 Some(format!("{:?}", $key))
625 macro_rules! define_maps {
628 [$($modifiers:tt)*] fn $name:ident: $node:ident($K:ty) -> $V:ty,)*) => {
631 input: ($(([$($modifiers)*] [$($attr)*] [$name]))*)
634 impl<$tcx> Maps<$tcx> {
635 pub fn new(providers: IndexVec<CrateNum, Providers<$tcx>>)
639 query_stack: RefCell::new(vec![]),
640 $($name: RefCell::new(QueryMap::new())),*
646 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
647 pub enum Query<$tcx> {
648 $($(#[$attr])* $name($K)),*
652 #[derive(Clone, Debug, PartialEq, Eq)]
654 $($name(Option<String>)),*
657 impl<$tcx> Query<$tcx> {
658 pub fn describe(&self, tcx: TyCtxt) -> String {
659 let (r, name) = match *self {
660 $(Query::$name(key) => {
661 (queries::$name::describe(tcx, key), stringify!($name))
664 if tcx.sess.verbose() {
665 format!("{} [{}]", r, name)
673 use std::marker::PhantomData;
675 $(#[allow(bad_style)]
676 pub struct $name<$tcx> {
677 data: PhantomData<&$tcx ()>
681 $(impl<$tcx> QueryConfig for queries::$name<$tcx> {
686 impl<'a, $tcx, 'lcx> queries::$name<$tcx> {
688 fn to_dep_node(tcx: TyCtxt<'a, $tcx, 'lcx>, key: &$K) -> DepNode {
689 use dep_graph::DepConstructor::*;
691 DepNode::new(tcx, $node(*key))
694 fn try_get_with<F, R>(tcx: TyCtxt<'a, $tcx, 'lcx>,
698 -> Result<R, CycleError<'a, $tcx>>
699 where F: FnOnce(&$V) -> R
701 debug!("ty::queries::{}::try_get_with(key={:?}, span={:?})",
707 ProfileQueriesMsg::QueryBegin(
709 QueryMsg::$name(profq_key!(tcx, key))
713 if let Some(value) = tcx.maps.$name.borrow().map.get(&key) {
714 if let Some(ref d) = value.diagnostics {
715 if !d.emitted_diagnostics.get() {
716 d.emitted_diagnostics.set(true);
717 let handle = tcx.sess.diagnostic();
718 for diagnostic in d.diagnostics.iter() {
719 DiagnosticBuilder::new_diagnostic(handle, diagnostic.clone())
724 profq_msg!(tcx, ProfileQueriesMsg::CacheHit);
725 tcx.dep_graph.read_index(value.index);
726 return Ok(f(&value.value));
728 // else, we are going to run the provider:
729 profq_msg!(tcx, ProfileQueriesMsg::ProviderBegin);
731 // FIXME(eddyb) Get more valid Span's on queries.
732 // def_span guard is necessary to prevent a recursive loop,
733 // default_span calls def_span query internally.
734 if span == DUMMY_SP && stringify!($name) != "def_span" {
735 span = key.default_span(tcx)
738 let res = tcx.cycle_check(span, Query::$name(key), || {
739 let dep_node = Self::to_dep_node(tcx, &key);
741 tcx.sess.diagnostic().track_diagnostics(|| {
742 if dep_node.kind.is_anon() {
743 tcx.dep_graph.with_anon_task(dep_node.kind, || {
744 let provider = tcx.maps.providers[key.map_crate()].$name;
745 provider(tcx.global_tcx(), key)
748 fn run_provider<'a, 'tcx, 'lcx>(tcx: TyCtxt<'a, 'tcx, 'lcx>,
751 let provider = tcx.maps.providers[key.map_crate()].$name;
752 provider(tcx.global_tcx(), key)
755 tcx.dep_graph.with_task(dep_node, tcx, key, run_provider)
759 profq_msg!(tcx, ProfileQueriesMsg::ProviderEnd);
760 let ((result, dep_node_index), diagnostics) = res;
762 tcx.dep_graph.read_index(dep_node_index);
764 let value = QueryValue {
766 index: dep_node_index,
767 diagnostics: if diagnostics.len() == 0 {
770 Some(Box::new(QueryDiagnostics {
772 emitted_diagnostics: Cell::new(true),
786 pub fn try_get(tcx: TyCtxt<'a, $tcx, 'lcx>, span: Span, key: $K)
787 -> Result<$V, DiagnosticBuilder<'a>> {
788 match Self::try_get_with(tcx, span, key, Clone::clone) {
790 Err(e) => Err(tcx.report_cycle(e)),
794 pub fn force(tcx: TyCtxt<'a, $tcx, 'lcx>, span: Span, key: $K) {
795 // Ignore dependencies, since we not reading the computed value
796 let _task = tcx.dep_graph.in_ignore();
798 match Self::try_get_with(tcx, span, key, |_| ()) {
800 Err(e) => tcx.report_cycle(e).emit(),
805 #[derive(Copy, Clone)]
806 pub struct TyCtxtAt<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
807 pub tcx: TyCtxt<'a, 'gcx, 'tcx>,
811 impl<'a, 'gcx, 'tcx> Deref for TyCtxtAt<'a, 'gcx, 'tcx> {
812 type Target = TyCtxt<'a, 'gcx, 'tcx>;
813 fn deref(&self) -> &Self::Target {
818 impl<'a, $tcx, 'lcx> TyCtxt<'a, $tcx, 'lcx> {
819 /// Return a transparent wrapper for `TyCtxt` which uses
820 /// `span` as the location of queries performed through it.
821 pub fn at(self, span: Span) -> TyCtxtAt<'a, $tcx, 'lcx> {
829 pub fn $name(self, key: $K) -> $V {
830 self.at(DUMMY_SP).$name(key)
834 impl<'a, $tcx, 'lcx> TyCtxtAt<'a, $tcx, 'lcx> {
836 pub fn $name(self, key: $K) -> $V {
837 queries::$name::try_get(self.tcx, self.span, key).unwrap_or_else(|mut e| {
839 Value::from_cycle_error(self.global_tcx())
844 define_provider_struct! {
846 input: ($(([$($modifiers)*] [$name] [$K] [$V]))*),
850 impl<$tcx> Copy for Providers<$tcx> {}
851 impl<$tcx> Clone for Providers<$tcx> {
852 fn clone(&self) -> Self { *self }
857 macro_rules! define_map_struct {
860 input: $input:tt) => {
871 output: ($($output:tt)*)) => {
872 pub struct Maps<$tcx> {
873 providers: IndexVec<CrateNum, Providers<$tcx>>,
874 query_stack: RefCell<Vec<(Span, Query<$tcx>)>>,
879 // Field recognized and ready to shift into the output
881 ready: ([$($pub:tt)*] [$($attr:tt)*] [$name:ident]),
883 output: ($($output:tt)*)) => {
888 $(#[$attr])* $($pub)* $name: RefCell<QueryMap<queries::$name<$tcx>>>,)
892 // No modifiers left? This is a private item.
894 input: (([] $attrs:tt $name:tt) $($input:tt)*),
895 output: $output:tt) => {
898 ready: ([] $attrs $name),
904 // Skip other modifiers
906 input: (([$other_modifier:tt $($modifiers:tt)*] $($fields:tt)*) $($input:tt)*),
907 output: $output:tt) => {
910 input: (([$($modifiers)*] $($fields)*) $($input)*),
916 macro_rules! define_provider_struct {
918 (tcx: $tcx:tt, input: $input:tt) => {
919 define_provider_struct! {
929 output: ($(([$name:ident] [$K:ty] [$R:ty]))*)) => {
930 pub struct Providers<$tcx> {
931 $(pub $name: for<'a> fn(TyCtxt<'a, $tcx, $tcx>, $K) -> $R,)*
934 impl<$tcx> Default for Providers<$tcx> {
935 fn default() -> Self {
936 $(fn $name<'a, $tcx>(_: TyCtxt<'a, $tcx, $tcx>, key: $K) -> $R {
937 bug!("tcx.maps.{}({:?}) unsupported by its crate",
938 stringify!($name), key);
940 Providers { $($name),* }
945 // Something ready to shift:
947 ready: ($name:tt $K:tt $V:tt),
949 output: ($($output:tt)*)) => {
950 define_provider_struct! {
953 output: ($($output)* ($name $K $V))
957 // Regular queries produce a `V` only.
959 input: (([] $name:tt $K:tt $V:tt) $($input:tt)*),
960 output: $output:tt) => {
961 define_provider_struct! {
963 ready: ($name $K $V),
971 input: (([$other_modifier:tt $($modifiers:tt)*] $($fields:tt)*) $($input:tt)*),
972 output: $output:tt) => {
973 define_provider_struct! {
975 input: (([$($modifiers)*] $($fields)*) $($input)*),
981 // Each of these maps also corresponds to a method on a
982 // `Provider` trait for requesting a value of that type,
983 // and a method on `Maps` itself for doing that in a
984 // a way that memoizes and does dep-graph tracking,
985 // wrapping around the actual chain of providers that
986 // the driver creates (using several `rustc_*` crates).
987 define_maps! { <'tcx>
988 /// Records the type of every item.
989 [] fn type_of: TypeOfItem(DefId) -> Ty<'tcx>,
991 /// Maps from the def-id of an item (trait/struct/enum/fn) to its
992 /// associated generics and predicates.
993 [] fn generics_of: GenericsOfItem(DefId) -> &'tcx ty::Generics,
994 [] fn predicates_of: PredicatesOfItem(DefId) -> ty::GenericPredicates<'tcx>,
996 /// Maps from the def-id of a trait to the list of
997 /// super-predicates. This is a subset of the full list of
998 /// predicates. We store these in a separate map because we must
999 /// evaluate them even during type conversion, often before the
1000 /// full predicates are available (note that supertraits have
1001 /// additional acyclicity requirements).
1002 [] fn super_predicates_of: SuperPredicatesOfItem(DefId) -> ty::GenericPredicates<'tcx>,
1004 /// To avoid cycles within the predicates of a single item we compute
1005 /// per-type-parameter predicates for resolving `T::AssocTy`.
1006 [] fn type_param_predicates: type_param_predicates((DefId, DefId))
1007 -> ty::GenericPredicates<'tcx>,
1009 [] fn trait_def: TraitDefOfItem(DefId) -> &'tcx ty::TraitDef,
1010 [] fn adt_def: AdtDefOfItem(DefId) -> &'tcx ty::AdtDef,
1011 [] fn adt_destructor: AdtDestructor(DefId) -> Option<ty::Destructor>,
1012 [] fn adt_sized_constraint: SizedConstraint(DefId) -> &'tcx [Ty<'tcx>],
1013 [] fn adt_dtorck_constraint: DtorckConstraint(DefId) -> ty::DtorckConstraint<'tcx>,
1015 /// True if this is a const fn
1016 [] fn is_const_fn: IsConstFn(DefId) -> bool,
1018 /// True if this is a foreign item (i.e., linked via `extern { ... }`).
1019 [] fn is_foreign_item: IsForeignItem(DefId) -> bool,
1021 /// True if this is a default impl (aka impl Foo for ..)
1022 [] fn is_default_impl: IsDefaultImpl(DefId) -> bool,
1024 /// Get a map with the variance of every item; use `item_variance`
1026 [] fn crate_variances: crate_variances(CrateNum) -> Rc<ty::CrateVariancesMap>,
1028 /// Maps from def-id of a type or region parameter to its
1029 /// (inferred) variance.
1030 [] fn variances_of: ItemVariances(DefId) -> Rc<Vec<ty::Variance>>,
1032 /// Maps from an impl/trait def-id to a list of the def-ids of its items
1033 [] fn associated_item_def_ids: AssociatedItemDefIds(DefId) -> Rc<Vec<DefId>>,
1035 /// Maps from a trait item to the trait item "descriptor"
1036 [] fn associated_item: AssociatedItems(DefId) -> ty::AssociatedItem,
1038 [] fn impl_trait_ref: ImplTraitRef(DefId) -> Option<ty::TraitRef<'tcx>>,
1039 [] fn impl_polarity: ImplPolarity(DefId) -> hir::ImplPolarity,
1041 /// Maps a DefId of a type to a list of its inherent impls.
1042 /// Contains implementations of methods that are inherent to a type.
1043 /// Methods in these implementations don't need to be exported.
1044 [] fn inherent_impls: InherentImpls(DefId) -> Rc<Vec<DefId>>,
1046 /// Set of all the def-ids in this crate that have MIR associated with
1047 /// them. This includes all the body owners, but also things like struct
1049 [] fn mir_keys: mir_keys(CrateNum) -> Rc<DefIdSet>,
1051 /// Maps DefId's that have an associated Mir to the result
1052 /// of the MIR qualify_consts pass. The actual meaning of
1053 /// the value isn't known except to the pass itself.
1054 [] fn mir_const_qualif: MirConstQualif(DefId) -> (u8, Rc<IdxSetBuf<mir::Local>>),
1056 /// Fetch the MIR for a given def-id up till the point where it is
1057 /// ready for const evaluation.
1059 /// See the README for the `mir` module for details.
1060 [] fn mir_const: MirConst(DefId) -> &'tcx Steal<mir::Mir<'tcx>>,
1062 [] fn mir_validated: MirValidated(DefId) -> &'tcx Steal<mir::Mir<'tcx>>,
1064 /// MIR after our optimization passes have run. This is MIR that is ready
1065 /// for trans. This is also the only query that can fetch non-local MIR, at present.
1066 [] fn optimized_mir: MirOptimized(DefId) -> &'tcx mir::Mir<'tcx>,
1068 /// Type of each closure. The def ID is the ID of the
1069 /// expression defining the closure.
1070 [] fn closure_kind: ClosureKind(DefId) -> ty::ClosureKind,
1072 /// The signature of functions and closures.
1073 [] fn fn_sig: FnSignature(DefId) -> ty::PolyFnSig<'tcx>,
1075 /// Records the signature of each generator. The def ID is the ID of the
1076 /// expression defining the closure.
1077 [] fn generator_sig: GenSignature(DefId) -> Option<ty::PolyGenSig<'tcx>>,
1079 /// Caches CoerceUnsized kinds for impls on custom types.
1080 [] fn coerce_unsized_info: CoerceUnsizedInfo(DefId)
1081 -> ty::adjustment::CoerceUnsizedInfo,
1083 [] fn typeck_item_bodies: typeck_item_bodies_dep_node(CrateNum) -> CompileResult,
1085 [] fn typeck_tables_of: TypeckTables(DefId) -> &'tcx ty::TypeckTables<'tcx>,
1087 [] fn has_typeck_tables: HasTypeckTables(DefId) -> bool,
1089 [] fn coherent_trait: coherent_trait_dep_node((CrateNum, DefId)) -> (),
1091 [] fn borrowck: BorrowCheck(DefId) -> (),
1092 // FIXME: shouldn't this return a `Result<(), BorrowckErrors>` instead?
1093 [] fn mir_borrowck: MirBorrowCheck(DefId) -> (),
1095 /// Gets a complete map from all types to their inherent impls.
1096 /// Not meant to be used directly outside of coherence.
1097 /// (Defined only for LOCAL_CRATE)
1098 [] fn crate_inherent_impls: crate_inherent_impls_dep_node(CrateNum) -> CrateInherentImpls,
1100 /// Checks all types in the krate for overlap in their inherent impls. Reports errors.
1101 /// Not meant to be used directly outside of coherence.
1102 /// (Defined only for LOCAL_CRATE)
1103 [] fn crate_inherent_impls_overlap_check: inherent_impls_overlap_check_dep_node(CrateNum) -> (),
1105 /// Results of evaluating const items or constants embedded in
1106 /// other items (such as enum variant explicit discriminants).
1107 [] fn const_eval: const_eval_dep_node(ty::ParamEnvAnd<'tcx, (DefId, &'tcx Substs<'tcx>)>)
1108 -> const_val::EvalResult<'tcx>,
1110 /// Performs the privacy check and computes "access levels".
1111 [] fn privacy_access_levels: PrivacyAccessLevels(CrateNum) -> Rc<AccessLevels>,
1113 [] fn reachable_set: reachability_dep_node(CrateNum) -> Rc<NodeSet>,
1115 /// Per-body `region::ScopeTree`. The `DefId` should be the owner-def-id for the body;
1116 /// in the case of closures, this will be redirected to the enclosing function.
1117 [] fn region_scope_tree: RegionScopeTree(DefId) -> Rc<region::ScopeTree>,
1119 [] fn mir_shims: mir_shim_dep_node(ty::InstanceDef<'tcx>) -> &'tcx mir::Mir<'tcx>,
1121 [] fn def_symbol_name: SymbolName(DefId) -> ty::SymbolName,
1122 [] fn symbol_name: symbol_name_dep_node(ty::Instance<'tcx>) -> ty::SymbolName,
1124 [] fn describe_def: DescribeDef(DefId) -> Option<Def>,
1125 [] fn def_span: DefSpan(DefId) -> Span,
1126 [] fn stability: Stability(DefId) -> Option<attr::Stability>,
1127 [] fn deprecation: Deprecation(DefId) -> Option<attr::Deprecation>,
1128 [] fn item_attrs: ItemAttrs(DefId) -> Rc<[ast::Attribute]>,
1129 [] fn fn_arg_names: FnArgNames(DefId) -> Vec<ast::Name>,
1130 [] fn impl_parent: ImplParent(DefId) -> Option<DefId>,
1131 [] fn trait_of_item: TraitOfItem(DefId) -> Option<DefId>,
1132 [] fn is_exported_symbol: IsExportedSymbol(DefId) -> bool,
1133 [] fn item_body_nested_bodies: ItemBodyNestedBodies(DefId)
1134 -> Rc<BTreeMap<hir::BodyId, hir::Body>>,
1135 [] fn const_is_rvalue_promotable_to_static: ConstIsRvaluePromotableToStatic(DefId) -> bool,
1136 [] fn is_mir_available: IsMirAvailable(DefId) -> bool,
1138 [] fn trait_impls_of: TraitImpls(DefId) -> Rc<ty::trait_def::TraitImpls>,
1139 [] fn specialization_graph_of: SpecializationGraph(DefId) -> Rc<specialization_graph::Graph>,
1140 [] fn is_object_safe: ObjectSafety(DefId) -> bool,
1142 // Get the ParameterEnvironment for a given item; this environment
1143 // will be in "user-facing" mode, meaning that it is suitabe for
1144 // type-checking etc, and it does not normalize specializable
1145 // associated types. This is almost always what you want,
1146 // unless you are doing MIR optimizations, in which case you
1147 // might want to use `reveal_all()` method to change modes.
1148 [] fn param_env: ParamEnv(DefId) -> ty::ParamEnv<'tcx>,
1150 // Trait selection queries. These are best used by invoking `ty.moves_by_default()`,
1151 // `ty.is_copy()`, etc, since that will prune the environment where possible.
1152 [] fn is_copy_raw: is_copy_dep_node(ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> bool,
1153 [] fn is_sized_raw: is_sized_dep_node(ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> bool,
1154 [] fn is_freeze_raw: is_freeze_dep_node(ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> bool,
1155 [] fn needs_drop_raw: needs_drop_dep_node(ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> bool,
1156 [] fn layout_raw: layout_dep_node(ty::ParamEnvAnd<'tcx, Ty<'tcx>>)
1157 -> Result<&'tcx Layout, LayoutError<'tcx>>,
1159 [] fn dylib_dependency_formats: DylibDepFormats(CrateNum)
1160 -> Rc<Vec<(CrateNum, LinkagePreference)>>,
1162 [] fn is_panic_runtime: IsPanicRuntime(CrateNum) -> bool,
1163 [] fn is_compiler_builtins: IsCompilerBuiltins(CrateNum) -> bool,
1164 [] fn has_global_allocator: HasGlobalAllocator(CrateNum) -> bool,
1165 [] fn is_sanitizer_runtime: IsSanitizerRuntime(CrateNum) -> bool,
1166 [] fn is_profiler_runtime: IsProfilerRuntime(CrateNum) -> bool,
1167 [] fn panic_strategy: GetPanicStrategy(CrateNum) -> PanicStrategy,
1168 [] fn is_no_builtins: IsNoBuiltins(CrateNum) -> bool,
1170 [] fn extern_crate: ExternCrate(DefId) -> Rc<Option<ExternCrate>>,
1172 [] fn specializes: specializes_node((DefId, DefId)) -> bool,
1173 [] fn in_scope_traits: InScopeTraits(HirId) -> Option<Rc<Vec<TraitCandidate>>>,
1174 [] fn module_exports: ModuleExports(HirId) -> Option<Rc<Vec<Export>>>,
1175 [] fn lint_levels: lint_levels_node(CrateNum) -> Rc<lint::LintLevelMap>,
1177 [] fn impl_defaultness: ImplDefaultness(DefId) -> hir::Defaultness,
1178 [] fn exported_symbols: ExportedSymbols(CrateNum) -> Rc<Vec<DefId>>,
1179 [] fn native_libraries: NativeLibraries(CrateNum) -> Rc<Vec<NativeLibrary>>,
1182 fn type_param_predicates<'tcx>((item_id, param_id): (DefId, DefId)) -> DepConstructor<'tcx> {
1183 DepConstructor::TypeParamPredicates {
1189 fn coherent_trait_dep_node<'tcx>((_, def_id): (CrateNum, DefId)) -> DepConstructor<'tcx> {
1190 DepConstructor::CoherenceCheckTrait(def_id)
1193 fn crate_inherent_impls_dep_node<'tcx>(_: CrateNum) -> DepConstructor<'tcx> {
1194 DepConstructor::Coherence
1197 fn inherent_impls_overlap_check_dep_node<'tcx>(_: CrateNum) -> DepConstructor<'tcx> {
1198 DepConstructor::CoherenceInherentImplOverlapCheck
1201 fn reachability_dep_node<'tcx>(_: CrateNum) -> DepConstructor<'tcx> {
1202 DepConstructor::Reachability
1205 fn mir_shim_dep_node<'tcx>(instance_def: ty::InstanceDef<'tcx>) -> DepConstructor<'tcx> {
1206 DepConstructor::MirShim {
1211 fn symbol_name_dep_node<'tcx>(instance: ty::Instance<'tcx>) -> DepConstructor<'tcx> {
1212 DepConstructor::InstanceSymbolName { instance }
1215 fn typeck_item_bodies_dep_node<'tcx>(_: CrateNum) -> DepConstructor<'tcx> {
1216 DepConstructor::TypeckBodiesKrate
1219 fn const_eval_dep_node<'tcx>(_: ty::ParamEnvAnd<'tcx, (DefId, &'tcx Substs<'tcx>)>)
1220 -> DepConstructor<'tcx> {
1221 DepConstructor::ConstEval
1224 fn mir_keys<'tcx>(_: CrateNum) -> DepConstructor<'tcx> {
1225 DepConstructor::MirKeys
1228 fn crate_variances<'tcx>(_: CrateNum) -> DepConstructor<'tcx> {
1229 DepConstructor::CrateVariances
1232 fn is_copy_dep_node<'tcx>(_: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> DepConstructor<'tcx> {
1233 DepConstructor::IsCopy
1236 fn is_sized_dep_node<'tcx>(_: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> DepConstructor<'tcx> {
1237 DepConstructor::IsSized
1240 fn is_freeze_dep_node<'tcx>(_: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> DepConstructor<'tcx> {
1241 DepConstructor::IsFreeze
1244 fn needs_drop_dep_node<'tcx>(_: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> DepConstructor<'tcx> {
1245 DepConstructor::NeedsDrop
1248 fn layout_dep_node<'tcx>(_: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> DepConstructor<'tcx> {
1249 DepConstructor::Layout
1252 fn lint_levels_node<'tcx>(_: CrateNum) -> DepConstructor<'tcx> {
1253 DepConstructor::LintLevels
1256 fn specializes_node<'tcx>((a, b): (DefId, DefId)) -> DepConstructor<'tcx> {
1257 DepConstructor::Specializes { impl1: a, impl2: b }