1 //! The implementation of the query system itself. This defines the macros that
2 //! generate the actual methods on tcx which find and execute the provider,
3 //! manage the caches, and so forth.
5 use crate::dep_graph::DepGraph;
6 use crate::ty::query::Query;
7 use crate::ty::tls::{self, ImplicitCtxt};
8 use crate::ty::{self, TyCtxt};
9 use rustc_query_system::query::QueryContext;
10 use rustc_query_system::query::{CycleError, QueryJobId, QueryJobInfo};
12 use rustc_data_structures::fx::FxHashMap;
13 use rustc_data_structures::sync::Lock;
14 use rustc_data_structures::thin_vec::ThinVec;
15 use rustc_errors::{struct_span_err, Diagnostic, DiagnosticBuilder, Handler, Level};
16 use rustc_span::def_id::DefId;
19 impl QueryContext for TyCtxt<'tcx> {
20 type Query = Query<'tcx>;
22 fn incremental_verify_ich(&self) -> bool {
23 self.sess.opts.debugging_opts.incremental_verify_ich
25 fn verbose(&self) -> bool {
29 fn def_path_str(&self, def_id: DefId) -> String {
30 TyCtxt::def_path_str(*self, def_id)
33 fn dep_graph(&self) -> &DepGraph {
37 fn current_query_job(&self) -> Option<QueryJobId<Self::DepKind>> {
38 tls::with_related_context(*self, |icx| icx.query)
41 fn try_collect_active_jobs(
43 ) -> Option<FxHashMap<QueryJobId<Self::DepKind>, QueryJobInfo<Self::DepKind, Self::Query>>>
45 self.queries.try_collect_active_jobs()
48 /// Executes a job by changing the `ImplicitCtxt` to point to the
49 /// new query job while it executes. It returns the diagnostics
50 /// captured during execution and the actual result.
54 token: QueryJobId<Self::DepKind>,
55 diagnostics: Option<&Lock<ThinVec<Diagnostic>>>,
56 compute: impl FnOnce(Self) -> R,
58 // The `TyCtxt` stored in TLS has the same global interner lifetime
59 // as `self`, so we use `with_related_context` to relate the 'tcx lifetimes
60 // when accessing the `ImplicitCtxt`.
61 tls::with_related_context(*self, move |current_icx| {
62 // Update the `ImplicitCtxt` to point to our new query job.
63 let new_icx = ImplicitCtxt {
67 layout_depth: current_icx.layout_depth,
68 task_deps: current_icx.task_deps,
71 // Use the `ImplicitCtxt` while we execute the query.
72 tls::enter_context(&new_icx, |_| {
73 rustc_data_structures::stack::ensure_sufficient_stack(|| compute(*self))
79 impl<'tcx> TyCtxt<'tcx> {
82 pub(super) fn report_cycle(
84 CycleError { usage, cycle: stack }: CycleError<Query<'tcx>>,
85 ) -> DiagnosticBuilder<'tcx> {
86 assert!(!stack.is_empty());
88 let fix_span = |span: Span, query: &Query<'tcx>| {
89 self.sess.source_map().guess_head_span(query.default_span(self, span))
92 // Disable naming impls with types in this path, since that
93 // sometimes cycles itself, leading to extra cycle errors.
94 // (And cycle errors around impls tend to occur during the
95 // collect/coherence phases anyhow.)
96 ty::print::with_forced_impl_filename_line(|| {
97 let span = fix_span(stack[1 % stack.len()].span, &stack[0].query);
98 let mut err = struct_span_err!(
102 "cycle detected when {}",
103 stack[0].query.describe(self)
106 for i in 1..stack.len() {
107 let query = &stack[i].query;
108 let span = fix_span(stack[(i + 1) % stack.len()].span, query);
109 err.span_note(span, &format!("...which requires {}...", query.describe(self)));
113 "...which again requires {}, completing the cycle",
114 stack[0].query.describe(self)
117 if let Some((span, query)) = usage {
119 fix_span(span, &query),
120 &format!("cycle used when {}", query.describe(self)),
128 pub fn try_print_query_stack(handler: &Handler, num_frames: Option<usize>) {
129 eprintln!("query stack during panic:");
131 // Be careful reyling on global state here: this code is called from
132 // a panic hook, which means that the global `Handler` may be in a weird
133 // state if it was responsible for triggering the panic.
135 ty::tls::with_context_opt(|icx| {
136 if let Some(icx) = icx {
137 let query_map = icx.tcx.queries.try_collect_active_jobs();
139 let mut current_query = icx.query;
141 while let Some(query) = current_query {
142 if Some(i) == num_frames {
146 if let Some(info) = query_map.as_ref().and_then(|map| map.get(&query)) {
151 let mut diag = Diagnostic::new(
156 query_info.info.query.name(),
157 query_info.info.query.describe(icx.tcx)
161 icx.tcx.sess.source_map().guess_head_span(query_info.info.span).into();
162 handler.force_print_diagnostic(diag);
164 current_query = query_info.job.parent;
170 if num_frames == None || num_frames >= Some(i) {
171 eprintln!("end of query stack");
173 eprintln!("we're just showing a limited slice of the query stack");
178 macro_rules! handle_cycle_error {
179 ([][$tcx: expr, $error:expr]) => {{
180 $tcx.report_cycle($error).emit();
181 Value::from_cycle_error($tcx)
183 ([fatal_cycle $($rest:tt)*][$tcx:expr, $error:expr]) => {{
184 $tcx.report_cycle($error).emit();
185 $tcx.sess.abort_if_errors();
188 ([cycle_delay_bug $($rest:tt)*][$tcx:expr, $error:expr]) => {{
189 $tcx.report_cycle($error).delay_as_bug();
190 Value::from_cycle_error($tcx)
192 ([$other:ident $(($($other_args:tt)*))* $(, $($modifiers:tt)*)*][$($args:tt)*]) => {
193 handle_cycle_error!([$($($modifiers)*)*][$($args)*])
197 macro_rules! is_anon {
201 ([anon $($rest:tt)*]) => {{
204 ([$other:ident $(($($other_args:tt)*))* $(, $($modifiers:tt)*)*]) => {
205 is_anon!([$($($modifiers)*)*])
209 macro_rules! is_eval_always {
213 ([eval_always $($rest:tt)*]) => {{
216 ([$other:ident $(($($other_args:tt)*))* $(, $($modifiers:tt)*)*]) => {
217 is_eval_always!([$($($modifiers)*)*])
221 macro_rules! query_storage {
222 ([][$K:ty, $V:ty]) => {
223 <<$K as Key>::CacheSelector as CacheSelector<$K, $V>>::Cache
225 ([storage($ty:ty) $($rest:tt)*][$K:ty, $V:ty]) => {
226 <$ty as CacheSelector<$K, $V>>::Cache
228 ([$other:ident $(($($other_args:tt)*))* $(, $($modifiers:tt)*)*][$($args:tt)*]) => {
229 query_storage!([$($($modifiers)*)*][$($args)*])
233 macro_rules! hash_result {
234 ([][$hcx:expr, $result:expr]) => {{
235 dep_graph::hash_result($hcx, &$result)
237 ([no_hash $($rest:tt)*][$hcx:expr, $result:expr]) => {{
240 ([$other:ident $(($($other_args:tt)*))* $(, $($modifiers:tt)*)*][$($args:tt)*]) => {
241 hash_result!([$($($modifiers)*)*][$($args)*])
245 macro_rules! define_queries {
246 (<$tcx:tt> $($category:tt {
247 $($(#[$attr:meta])* [$($modifiers:tt)*] fn $name:ident: $node:ident($($K:tt)*) -> $V:ty,)*
249 define_queries_inner! { <$tcx>
250 $($( $(#[$attr])* category<$category> [$($modifiers)*] fn $name: $node($($K)*) -> $V,)*)*
255 macro_rules! query_helper_param_ty {
256 (DefId) => { impl IntoQueryParam<DefId> };
260 macro_rules! define_queries_inner {
262 $($(#[$attr:meta])* category<$category:tt>
263 [$($modifiers:tt)*] fn $name:ident: $node:ident($($K:tt)*) -> $V:ty,)*) => {
267 rustc_data_structures::stable_hasher::HashStable,
268 rustc_data_structures::stable_hasher::StableHasher,
269 ich::StableHashingContext
272 define_queries_struct! {
274 input: ($(([$($modifiers)*] [$($attr)*] [$name]))*)
277 #[allow(nonstandard_style)]
278 #[derive(Clone, Debug)]
279 pub enum Query<$tcx> {
280 $($(#[$attr])* $name($($K)*)),*
283 impl<$tcx> Query<$tcx> {
284 pub fn name(&self) -> &'static str {
286 $(Query::$name(_) => stringify!($name),)*
290 pub fn describe(&self, tcx: TyCtxt<$tcx>) -> Cow<'static, str> {
291 let (r, name) = match *self {
292 $(Query::$name(key) => {
293 (queries::$name::describe(tcx, key), stringify!($name))
296 if tcx.sess.verbose() {
297 format!("{} [{}]", r, name).into()
303 // FIXME(eddyb) Get more valid `Span`s on queries.
304 pub fn default_span(&self, tcx: TyCtxt<$tcx>, span: Span) -> Span {
305 if !span.is_dummy() {
308 // The `def_span` query is used to calculate `default_span`,
309 // so exit to avoid infinite recursion.
310 if let Query::def_span(..) = *self {
314 $(Query::$name(key) => key.default_span(tcx),)*
319 impl<'a, $tcx> HashStable<StableHashingContext<'a>> for Query<$tcx> {
320 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
321 mem::discriminant(self).hash_stable(hcx, hasher);
323 $(Query::$name(key) => key.hash_stable(hcx, hasher),)*
328 #[allow(nonstandard_style)]
330 use std::marker::PhantomData;
332 $(pub struct $name<$tcx> {
333 data: PhantomData<&$tcx ()>
337 // HACK(eddyb) this is like the `impl QueryConfig for queries::$name`
338 // below, but using type aliases instead of associated types, to bypass
339 // the limitations around normalizing under HRTB - for example, this:
340 // `for<'tcx> fn(...) -> <queries::$name<'tcx> as QueryConfig<TyCtxt<'tcx>>>::Value`
341 // doesn't currently normalize to `for<'tcx> fn(...) -> query_values::$name<'tcx>`.
342 // This is primarily used by the `provide!` macro in `rustc_metadata`.
343 #[allow(nonstandard_style, unused_lifetimes)]
347 $(pub type $name<$tcx> = $($K)*;)*
349 #[allow(nonstandard_style, unused_lifetimes)]
350 pub mod query_values {
353 $(pub type $name<$tcx> = $V;)*
356 $(impl<$tcx> QueryConfig for queries::$name<$tcx> {
360 query_storage!([$($modifiers)*][$($K)*, $V])
363 const NAME: &'static str = stringify!($name);
366 impl<$tcx> QueryAccessors<TyCtxt<$tcx>> for queries::$name<$tcx> {
367 const ANON: bool = is_anon!([$($modifiers)*]);
368 const EVAL_ALWAYS: bool = is_eval_always!([$($modifiers)*]);
369 const DEP_KIND: dep_graph::DepKind = dep_graph::DepKind::$node;
371 type Cache = query_storage!([$($modifiers)*][$($K)*, $V]);
374 fn query_state<'a>(tcx: TyCtxt<$tcx>) -> &'a QueryState<crate::dep_graph::DepKind, <TyCtxt<$tcx> as QueryContext>::Query, Self::Cache> {
379 fn compute(tcx: TyCtxt<'tcx>, key: Self::Key) -> Self::Value {
380 let provider = tcx.queries.providers.get(key.query_crate())
381 // HACK(eddyb) it's possible crates may be loaded after
382 // the query engine is created, and because crate loading
383 // is not yet integrated with the query engine, such crates
384 // would be missing appropriate entries in `providers`.
385 .unwrap_or(&tcx.queries.fallback_extern_providers)
391 _hcx: &mut StableHashingContext<'_>,
392 _result: &Self::Value
393 ) -> Option<Fingerprint> {
394 hash_result!([$($modifiers)*][_hcx, _result])
397 fn handle_cycle_error(
399 error: CycleError<Query<'tcx>>
401 handle_cycle_error!([$($modifiers)*][tcx, error])
405 #[derive(Copy, Clone)]
406 pub struct TyCtxtEnsure<'tcx> {
407 pub tcx: TyCtxt<'tcx>,
410 impl TyCtxtEnsure<$tcx> {
413 pub fn $name(self, key: query_helper_param_ty!($($K)*)) {
414 ensure_query::<queries::$name<'_>, _>(self.tcx, key.into_query_param())
418 #[derive(Copy, Clone)]
419 pub struct TyCtxtAt<'tcx> {
420 pub tcx: TyCtxt<'tcx>,
424 impl Deref for TyCtxtAt<'tcx> {
425 type Target = TyCtxt<'tcx>;
427 fn deref(&self) -> &Self::Target {
433 /// Returns a transparent wrapper for `TyCtxt`, which ensures queries
434 /// are executed instead of just returning their results.
436 pub fn ensure(self) -> TyCtxtEnsure<$tcx> {
442 /// Returns a transparent wrapper for `TyCtxt` which uses
443 /// `span` as the location of queries performed through it.
445 pub fn at(self, span: Span) -> TyCtxtAt<$tcx> {
455 pub fn $name(self, key: query_helper_param_ty!($($K)*))
456 -> <queries::$name<$tcx> as QueryConfig>::Stored
458 self.at(DUMMY_SP).$name(key.into_query_param())
461 /// All self-profiling events generated by the query engine use
462 /// virtual `StringId`s for their `event_id`. This method makes all
463 /// those virtual `StringId`s point to actual strings.
465 /// If we are recording only summary data, the ids will point to
466 /// just the query names. If we are recording query keys too, we
467 /// allocate the corresponding strings here.
468 pub fn alloc_self_profile_query_strings(self) {
469 use crate::ty::query::profiling_support::{
470 alloc_self_profile_query_strings_for_query_cache,
474 if !self.prof.enabled() {
478 let mut string_cache = QueryKeyStringCache::new();
481 alloc_self_profile_query_strings_for_query_cache(
491 impl TyCtxtAt<$tcx> {
494 pub fn $name(self, key: query_helper_param_ty!($($K)*))
495 -> <queries::$name<$tcx> as QueryConfig>::Stored
497 get_query::<queries::$name<'_>, _>(self.tcx, self.span, key.into_query_param())
501 define_provider_struct! {
503 input: ($(([$($modifiers)*] [$name] [$($K)*] [$V]))*)
506 impl Copy for Providers {}
507 impl Clone for Providers {
508 fn clone(&self) -> Self { *self }
513 // FIXME(eddyb) this macro (and others?) use `$tcx` and `'tcx` interchangeably.
514 // We should either not take `$tcx` at all and use `'tcx` everywhere, or use
515 // `$tcx` everywhere (even if that isn't necessary due to lack of hygiene).
516 macro_rules! define_queries_struct {
518 input: ($(([$($modifiers:tt)*] [$($attr:tt)*] [$name:ident]))*)) => {
519 pub struct Queries<$tcx> {
520 /// This provides access to the incrimental comilation on-disk cache for query results.
521 /// Do not access this directly. It is only meant to be used by
522 /// `DepGraph::try_mark_green()` and the query infrastructure.
523 pub(crate) on_disk_cache: OnDiskCache<'tcx>,
525 providers: IndexVec<CrateNum, Providers>,
526 fallback_extern_providers: Box<Providers>,
528 $($(#[$attr])* $name: QueryState<
529 crate::dep_graph::DepKind,
530 <TyCtxt<$tcx> as QueryContext>::Query,
531 <queries::$name<$tcx> as QueryAccessors<TyCtxt<'tcx>>>::Cache,
535 impl<$tcx> Queries<$tcx> {
537 providers: IndexVec<CrateNum, Providers>,
538 fallback_extern_providers: Providers,
539 on_disk_cache: OnDiskCache<'tcx>,
543 fallback_extern_providers: Box::new(fallback_extern_providers),
545 $($name: Default::default()),*
549 pub(crate) fn try_collect_active_jobs(
551 ) -> Option<FxHashMap<QueryJobId<crate::dep_graph::DepKind>, QueryJobInfo<crate::dep_graph::DepKind, <TyCtxt<$tcx> as QueryContext>::Query>>> {
552 let mut jobs = FxHashMap::default();
555 self.$name.try_collect_active_jobs(
556 <queries::$name<'tcx> as QueryAccessors<TyCtxt<'tcx>>>::DEP_KIND,
568 macro_rules! define_provider_struct {
570 input: ($(([$($modifiers:tt)*] [$name:ident] [$K:ty] [$R:ty]))*)) => {
571 pub struct Providers {
572 $(pub $name: for<$tcx> fn(TyCtxt<$tcx>, $K) -> $R,)*
575 impl Default for Providers {
576 fn default() -> Self {
577 $(fn $name<$tcx>(_: TyCtxt<$tcx>, key: $K) -> $R {
578 bug!("`tcx.{}({:?})` unsupported by its crate",
579 stringify!($name), key);
581 Providers { $($name),* }