Skip to main content

rustc_middle/query/
plumbing.rs

1use std::fmt;
2use std::ops::Deref;
3
4use rustc_data_structures::fingerprint::Fingerprint;
5use rustc_data_structures::fx::FxIndexMap;
6use rustc_data_structures::hash_table::HashTable;
7use rustc_data_structures::sharded::Sharded;
8use rustc_data_structures::sync::{AtomicU64, Lock, WorkerLocal};
9use rustc_errors::Diag;
10use rustc_hir::def_id::LocalDefId;
11use rustc_span::Span;
12
13use crate::dep_graph::{DepKind, DepNodeIndex, QuerySideEffect, SerializedDepNodeIndex};
14use crate::ich::StableHashingContext;
15use crate::queries::{ExternProviders, Providers, QueryArenas, QueryVTables, TaggedQueryKey};
16use crate::query::on_disk_cache::OnDiskCache;
17use crate::query::{IntoQueryKey, QueryCache, QueryJob, QueryStackFrame};
18use crate::ty::{self, TyCtxt};
19
20/// For a particular query, keeps track of "active" keys, i.e. keys whose
21/// evaluation has started but has not yet finished successfully.
22///
23/// (Successful query evaluation for a key is represented by an entry in the
24/// query's in-memory cache.)
25pub struct QueryState<'tcx, K> {
26    pub active: Sharded<HashTable<(K, ActiveKeyStatus<'tcx>)>>,
27}
28
29impl<'tcx, K> Default for QueryState<'tcx, K> {
30    fn default() -> QueryState<'tcx, K> {
31        QueryState { active: Default::default() }
32    }
33}
34
35/// For a particular query and key, tracks the status of a query evaluation
36/// that has started, but has not yet finished successfully.
37///
38/// (Successful query evaluation for a key is represented by an entry in the
39/// query's in-memory cache.)
40pub enum ActiveKeyStatus<'tcx> {
41    /// Some thread is already evaluating the query for this key.
42    ///
43    /// The enclosed [`QueryJob`] can be used to wait for it to finish.
44    Started(QueryJob<'tcx>),
45
46    /// The query panicked. Queries trying to wait on this will raise a fatal error which will
47    /// silently panic.
48    Poisoned,
49}
50
51#[derive(#[automatically_derived]
impl<'tcx> ::core::fmt::Debug for Cycle<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f, "Cycle",
            "usage", &self.usage, "frames", &&self.frames)
    }
}Debug)]
52pub struct Cycle<'tcx> {
53    /// The query and related span that uses the cycle.
54    pub usage: Option<QueryStackFrame<'tcx>>,
55
56    /// The span here corresponds to the reason for which this query was required.
57    pub frames: Vec<QueryStackFrame<'tcx>>,
58}
59
60#[derive(#[automatically_derived]
impl ::core::fmt::Debug for QueryMode {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            QueryMode::Get => ::core::fmt::Formatter::write_str(f, "Get"),
            QueryMode::Ensure { ensure_mode: __self_0 } =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "Ensure", "ensure_mode", &__self_0),
        }
    }
}Debug)]
61pub enum QueryMode {
62    /// This is a normal query call to `tcx.$query(..)` or `tcx.at(span).$query(..)`.
63    Get,
64    /// This is a call to `tcx.ensure_ok().$query(..)` or `tcx.ensure_done().$query(..)`.
65    Ensure { ensure_mode: EnsureMode },
66}
67
68/// Distinguishes between `tcx.ensure_ok()` and `tcx.ensure_done()` in shared
69/// code paths that handle both modes.
70#[derive(#[automatically_derived]
impl ::core::fmt::Debug for EnsureMode {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                EnsureMode::Ok => "Ok",
                EnsureMode::Done => "Done",
            })
    }
}Debug)]
71pub enum EnsureMode {
72    /// Corresponds to [`TyCtxt::ensure_ok`].
73    Ok,
74    /// Corresponds to [`TyCtxt::ensure_done`].
75    Done,
76}
77
78/// Stores data and metadata (e.g. function pointers) for a particular query.
79pub struct QueryVTable<'tcx, C: QueryCache> {
80    pub name: &'static str,
81
82    /// True if this query has the `eval_always` modifier.
83    pub eval_always: bool,
84    /// True if this query has the `depth_limit` modifier.
85    pub depth_limit: bool,
86    /// True if this query has the `feedable` modifier.
87    pub feedable: bool,
88
89    pub dep_kind: DepKind,
90    pub state: QueryState<'tcx, C::Key>,
91    pub cache: C,
92
93    /// Function pointer that actually calls this query's provider.
94    /// Also performs some associated secondary tasks; see the macro-defined
95    /// implementation in `mod invoke_provider_fn` for more details.
96    ///
97    /// This should be the only code that calls the provider function.
98    pub invoke_provider_fn: fn(tcx: TyCtxt<'tcx>, key: C::Key) -> C::Value,
99
100    pub will_cache_on_disk_for_key_fn: fn(key: C::Key) -> bool,
101
102    /// Function pointer that tries to load a query value from disk.
103    ///
104    /// This should only be called after a successful check of `will_cache_on_disk_for_key_fn`.
105    pub try_load_from_disk_fn:
106        fn(tcx: TyCtxt<'tcx>, prev_index: SerializedDepNodeIndex) -> Option<C::Value>,
107
108    /// Function pointer that hashes this query's result values.
109    ///
110    /// For `no_hash` queries, this function pointer is None.
111    pub hash_value_fn: Option<fn(&mut StableHashingContext<'_>, &C::Value) -> Fingerprint>,
112
113    /// Function pointer that handles a cycle error. `error` must be consumed, e.g. with `emit` (if
114    /// it should be emitted) or `delay_as_bug` (if it need not be emitted because an alternative
115    /// error is created and emitted). A value may be returned, or (more commonly) the function may
116    /// just abort after emitting the error.
117    pub handle_cycle_error_fn:
118        fn(tcx: TyCtxt<'tcx>, key: C::Key, cycle: Cycle<'tcx>, error: Diag<'_>) -> C::Value,
119
120    pub format_value: fn(&C::Value) -> String,
121
122    pub create_tagged_key: fn(C::Key) -> TaggedQueryKey<'tcx>,
123
124    /// Function pointer that is called by the query methods on [`TyCtxt`] and
125    /// friends[^1], after they have checked the in-memory cache and found no
126    /// existing value for this key.
127    ///
128    /// Transitive responsibilities include trying to load a disk-cached value
129    /// if possible (incremental only), invoking the query provider if necessary,
130    /// and putting the obtained value into the in-memory cache.
131    ///
132    /// [^1]: [`TyCtxt`], [`TyCtxtAt`], [`TyCtxtEnsureOk`], [`TyCtxtEnsureDone`]
133    pub execute_query_fn: fn(TyCtxt<'tcx>, Span, C::Key, QueryMode) -> Option<C::Value>,
134}
135
136impl<'tcx, C: QueryCache> fmt::Debug for QueryVTable<'tcx, C> {
137    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
138        // When debug-printing a query vtable (e.g. for ICE or tracing),
139        // just print the query name to know what query we're dealing with.
140        // The other fields and flags are probably just unhelpful noise.
141        //
142        // If there is need for a more detailed dump of all flags and fields,
143        // consider writing a separate dump method and calling it explicitly.
144        f.write_str(self.name)
145    }
146}
147
148pub struct QuerySystem<'tcx> {
149    pub arenas: WorkerLocal<QueryArenas<'tcx>>,
150    pub query_vtables: QueryVTables<'tcx>,
151
152    /// Side-effect associated with each [`DepKind::SideEffect`] node in the
153    /// current incremental-compilation session. Side effects will be written
154    /// to disk, and loaded by [`OnDiskCache`] in the next session.
155    ///
156    /// Always empty if incremental compilation is off.
157    pub side_effects: Lock<FxIndexMap<DepNodeIndex, QuerySideEffect>>,
158
159    /// This provides access to the incremental compilation on-disk cache for query results.
160    /// Do not access this directly. It is only meant to be used by
161    /// `DepGraph::try_mark_green()` and the query infrastructure.
162    /// This is `None` if we are not incremental compilation mode
163    pub on_disk_cache: Option<OnDiskCache>,
164
165    pub local_providers: Providers,
166    pub extern_providers: ExternProviders,
167
168    pub jobs: AtomicU64,
169}
170
171#[derive(#[automatically_derived]
impl<'tcx> ::core::marker::Copy for TyCtxtAt<'tcx> { }Copy, #[automatically_derived]
impl<'tcx> ::core::clone::Clone for TyCtxtAt<'tcx> {
    #[inline]
    fn clone(&self) -> TyCtxtAt<'tcx> {
        let _: ::core::clone::AssertParamIsClone<TyCtxt<'tcx>>;
        let _: ::core::clone::AssertParamIsClone<Span>;
        *self
    }
}Clone)]
172pub struct TyCtxtAt<'tcx> {
173    pub tcx: TyCtxt<'tcx>,
174    pub span: Span,
175}
176
177impl<'tcx> Deref for TyCtxtAt<'tcx> {
178    type Target = TyCtxt<'tcx>;
179    #[inline(always)]
180    fn deref(&self) -> &Self::Target {
181        &self.tcx
182    }
183}
184
185#[derive(#[automatically_derived]
impl<'tcx> ::core::marker::Copy for TyCtxtEnsureOk<'tcx> { }Copy, #[automatically_derived]
impl<'tcx> ::core::clone::Clone for TyCtxtEnsureOk<'tcx> {
    #[inline]
    fn clone(&self) -> TyCtxtEnsureOk<'tcx> {
        let _: ::core::clone::AssertParamIsClone<TyCtxt<'tcx>>;
        *self
    }
}Clone)]
186#[must_use]
187pub struct TyCtxtEnsureOk<'tcx> {
188    pub tcx: TyCtxt<'tcx>,
189}
190
191#[derive(#[automatically_derived]
impl<'tcx> ::core::marker::Copy for TyCtxtEnsureResult<'tcx> { }Copy, #[automatically_derived]
impl<'tcx> ::core::clone::Clone for TyCtxtEnsureResult<'tcx> {
    #[inline]
    fn clone(&self) -> TyCtxtEnsureResult<'tcx> {
        let _: ::core::clone::AssertParamIsClone<TyCtxt<'tcx>>;
        *self
    }
}Clone)]
192#[must_use]
193pub struct TyCtxtEnsureResult<'tcx> {
194    pub tcx: TyCtxt<'tcx>,
195}
196
197#[derive(#[automatically_derived]
impl<'tcx> ::core::marker::Copy for TyCtxtEnsureDone<'tcx> { }Copy, #[automatically_derived]
impl<'tcx> ::core::clone::Clone for TyCtxtEnsureDone<'tcx> {
    #[inline]
    fn clone(&self) -> TyCtxtEnsureDone<'tcx> {
        let _: ::core::clone::AssertParamIsClone<TyCtxt<'tcx>>;
        *self
    }
}Clone)]
198#[must_use]
199pub struct TyCtxtEnsureDone<'tcx> {
200    pub tcx: TyCtxt<'tcx>,
201}
202
203impl<'tcx> TyCtxtEnsureOk<'tcx> {
204    pub fn typeck(self, def_id: impl IntoQueryKey<LocalDefId>) {
205        self.typeck_root(
206            self.tcx.typeck_root_def_id(def_id.into_query_key().to_def_id()).expect_local(),
207        )
208    }
209}
210
211impl<'tcx> TyCtxt<'tcx> {
212    pub fn typeck(self, def_id: impl IntoQueryKey<LocalDefId>) -> &'tcx ty::TypeckResults<'tcx> {
213        self.typeck_root(
214            self.typeck_root_def_id(def_id.into_query_key().to_def_id()).expect_local(),
215        )
216    }
217
218    /// Returns a transparent wrapper for `TyCtxt` which uses
219    /// `span` as the location of queries performed through it.
220    #[inline(always)]
221    pub fn at(self, span: Span) -> TyCtxtAt<'tcx> {
222        TyCtxtAt { tcx: self, span }
223    }
224
225    /// FIXME: `ensure_ok`'s effects are subtle. Is this comment fully accurate?
226    ///
227    /// Wrapper that calls queries in a special "ensure OK" mode, for callers
228    /// that don't need the return value and just want to invoke a query for
229    /// its potential side-effect of emitting fatal errors.
230    ///
231    /// This can be more efficient than a normal query call, because if the
232    /// query's inputs are all green, the call can return immediately without
233    /// needing to obtain a value (by decoding one from disk or by executing
234    /// the query).
235    ///
236    /// (As with all query calls, execution is also skipped if the query result
237    /// is already cached in memory.)
238    ///
239    /// ## WARNING
240    /// A subsequent normal call to the same query might still cause it to be
241    /// executed! This can occur when the inputs are all green, but the query's
242    /// result is not cached on disk, so the query must be executed to obtain a
243    /// return value.
244    ///
245    /// Therefore, this call mode is not appropriate for callers that want to
246    /// ensure that the query is _never_ executed in the future.
247    #[inline(always)]
248    pub fn ensure_ok(self) -> TyCtxtEnsureOk<'tcx> {
249        TyCtxtEnsureOk { tcx: self }
250    }
251
252    /// This is a variant of `ensure_ok` only usable with queries that return
253    /// `Result<_, ErrorGuaranteed>`. Queries calls through this function will
254    /// return `Result<(), ErrorGuaranteed>`. I.e. the error status is returned
255    /// but nothing else. As with `ensure_ok`, this can be more efficient than
256    /// a normal query call.
257    #[inline(always)]
258    pub fn ensure_result(self) -> TyCtxtEnsureResult<'tcx> {
259        TyCtxtEnsureResult { tcx: self }
260    }
261
262    /// Wrapper that calls queries in a special "ensure done" mode, for callers
263    /// that don't need the return value and just want to guarantee that the
264    /// query won't be executed in the future, by executing it now if necessary.
265    ///
266    /// This is useful for queries that read from a [`Steal`] value, to ensure
267    /// that they are executed before the query that will steal the value.
268    ///
269    /// Unlike [`Self::ensure_ok`], a query with all-green inputs will only be
270    /// skipped if its return value is stored in the disk-cache. This is still
271    /// more efficient than a regular query, because in that situation the
272    /// return value doesn't necessarily need to be decoded.
273    ///
274    /// (As with all query calls, execution is also skipped if the query result
275    /// is already cached in memory.)
276    ///
277    /// [`Steal`]: rustc_data_structures::steal::Steal
278    #[inline(always)]
279    pub fn ensure_done(self) -> TyCtxtEnsureDone<'tcx> {
280        TyCtxtEnsureDone { tcx: self }
281    }
282}
283
284macro_rules! maybe_into_query_key {
285    (DefId) => { impl $crate::query::IntoQueryKey<DefId> };
286    (LocalDefId) => { impl $crate::query::IntoQueryKey<LocalDefId> };
287    ($K:ty) => { $K };
288}
289
290macro_rules! define_callbacks {
291    (
292        // You might expect the key to be `$K:ty`, but it needs to be `$($K:tt)*` so that
293        // `maybe_into_query_key!` can match on specific type names.
294        queries {
295            $(
296                $(#[$attr:meta])*
297                fn $name:ident($($K:tt)*) -> $V:ty
298                {
299                    // Search for (QMODLIST) to find all occurrences of this query modifier list.
300                    arena_cache: $arena_cache:literal,
301                    cache_on_disk: $cache_on_disk:literal,
302                    depth_limit: $depth_limit:literal,
303                    desc: $desc:expr,
304                    eval_always: $eval_always:literal,
305                    feedable: $feedable:literal,
306                    handle_cycle_error: $handle_cycle_error:literal,
307                    no_force: $no_force:literal,
308                    no_hash: $no_hash:literal,
309                    returns_error_guaranteed: $returns_error_guaranteed:literal,
310                    separate_provide_extern: $separate_provide_extern:literal,
311                }
312            )*
313        }
314        // Non-queries are unused here.
315        non_queries { $($_:tt)* }
316    ) => {
317        $(
318            pub mod $name {
319                use super::*;
320                use $crate::query::erase::{self, Erased};
321
322                pub type Key<'tcx> = $($K)*;
323                pub type Value<'tcx> = $V;
324
325                /// Key type used by provider functions in `local_providers`.
326                /// This query has the `separate_provide_extern` modifier.
327                #[cfg($separate_provide_extern)]
328                pub type LocalKey<'tcx> =
329                    <Key<'tcx> as $crate::query::AsLocalQueryKey>::LocalQueryKey;
330                /// Key type used by provider functions in `local_providers`.
331                #[cfg(not($separate_provide_extern))]
332                pub type LocalKey<'tcx> = Key<'tcx>;
333
334                /// Type returned from query providers and loaded from disk-cache.
335                #[cfg($arena_cache)]
336                pub type ProvidedValue<'tcx> =
337                    <Value<'tcx> as $crate::query::arena_cached::ArenaCached<'tcx>>::Provided;
338                /// Type returned from query providers and loaded from disk-cache.
339                #[cfg(not($arena_cache))]
340                pub type ProvidedValue<'tcx> = Value<'tcx>;
341
342                pub type Cache<'tcx> =
343                    <Key<'tcx> as $crate::query::QueryKey>::Cache<Erased<Value<'tcx>>>;
344
345                /// This helper function takes a value returned by the query provider
346                /// (or loaded from disk, or supplied by query feeding), allocates
347                /// it in an arena if requested by the `arena_cache` modifier, and
348                /// then returns an erased copy of it.
349                #[inline(always)]
350                pub fn provided_to_erased<'tcx>(
351                    tcx: TyCtxt<'tcx>,
352                    provided_value: ProvidedValue<'tcx>,
353                ) -> Erased<Value<'tcx>> {
354                    // For queries with the `arena_cache` modifier, store the
355                    // provided value in an arena and get a reference to it.
356                    #[cfg($arena_cache)]
357                    let value: Value<'tcx> = {
358                        use $crate::query::arena_cached::ArenaCached;
359                        <Value<'tcx> as ArenaCached>::alloc_in_arena(
360                            tcx,
361                            &tcx.query_system.arenas.$name,
362                            provided_value,
363                        )
364                    };
365
366                    // Otherwise, the provided value is the value (and `tcx` is unused).
367                    #[cfg(not($arena_cache))]
368                    let value: Value<'tcx> = {
369                        let _ = tcx;
370                        provided_value
371                    };
372
373                    erase::erase_val(value)
374                }
375
376                // Ensure that keys grow no larger than 88 bytes by accident.
377                // Increase this limit if necessary, but do try to keep the size low if possible
378                #[cfg(target_pointer_width = "64")]
379                const _: () = {
380                    if size_of::<Key<'static>>() > 88 {
381                        panic!("{}", concat!(
382                            "the query `",
383                            stringify!($name),
384                            "` has a key type `",
385                            stringify!($($K)*),
386                            "` that is too large"
387                        ));
388                    }
389                };
390
391                // Ensure that values grow no larger than 64 bytes by accident.
392                // Increase this limit if necessary, but do try to keep the size low if possible
393                #[cfg(target_pointer_width = "64")]
394                #[cfg(not(feature = "rustc_randomized_layouts"))]
395                const _: () = {
396                    if size_of::<Value<'static>>() > 64 {
397                        panic!("{}", concat!(
398                            "the query `",
399                            stringify!($name),
400                            "` has a value type `",
401                            stringify!($V),
402                            "` that is too large"
403                        ));
404                    }
405                };
406            }
407        )*
408
409        /// Identifies a query by kind and key. This is in contrast to `QueryJobId` which is just a
410        /// number.
411        #[allow(non_camel_case_types)]
412        #[derive(Clone, Copy, Debug)]
413        pub enum TaggedQueryKey<'tcx> {
414            $(
415                $name($name::Key<'tcx>),
416            )*
417        }
418
419        impl<'tcx> TaggedQueryKey<'tcx> {
420            /// Returns the name of the query this key is tagged with.
421            ///
422            /// This is useful for error/debug output, but don't use it to check for
423            /// specific query names. Instead, match on the `TaggedQueryKey` variant.
424            pub fn query_name(&self) -> &'static str {
425                match self {
426                    $(
427                        TaggedQueryKey::$name(_) => stringify!($name),
428                    )*
429                }
430            }
431
432            /// Formats a human-readable description of this query and its key, as
433            /// specified by the `desc` query modifier.
434            ///
435            /// Used when reporting query cycle errors and similar problems.
436            pub fn description(&self, tcx: TyCtxt<'tcx>) -> String {
437                let (name, description) = ty::print::with_no_queries!(match self {
438                    $(
439                        TaggedQueryKey::$name(key) => (stringify!($name), ($desc)(tcx, *key)),
440                    )*
441                });
442                if tcx.sess.verbose_internals() {
443                    format!("{description} [{name:?}]")
444                } else {
445                    description
446                }
447            }
448
449            /// Returns the default span for this query if `span` is a dummy span.
450            pub fn default_span(&self, tcx: TyCtxt<'tcx>, span: Span) -> Span {
451                if !span.is_dummy() {
452                    return span
453                }
454                if let TaggedQueryKey::def_span(..) = self {
455                    // The `def_span` query is used to calculate `default_span`,
456                    // so exit to avoid infinite recursion.
457                    return DUMMY_SP
458                }
459                match self {
460                    $(
461                        TaggedQueryKey::$name(key) =>
462                            $crate::query::QueryKey::default_span(key, tcx),
463                    )*
464                }
465            }
466        }
467
468        /// Holds a `QueryVTable` for each query.
469        pub struct QueryVTables<'tcx> {
470            $(
471                pub $name: $crate::query::QueryVTable<'tcx, $name::Cache<'tcx>>,
472            )*
473        }
474
475        /// Holds per-query arenas for queries with the `arena_cache` modifier.
476        #[derive(Default)]
477        pub struct QueryArenas<'tcx> {
478            $(
479                // Use the `ArenaCached` helper trait to determine the arena's value type.
480                #[cfg($arena_cache)]
481                pub $name: TypedArena<
482                    <$V as $crate::query::arena_cached::ArenaCached<'tcx>>::Allocated,
483                >,
484            )*
485        }
486
487        pub struct Providers {
488            $(
489                /// This is the provider for the query. Use `Find references` on this to
490                /// navigate between the provider assignment and the query definition.
491                pub $name: for<'tcx> fn(
492                    TyCtxt<'tcx>,
493                    $name::LocalKey<'tcx>,
494                ) -> $name::ProvidedValue<'tcx>,
495            )*
496        }
497
498        pub struct ExternProviders {
499            $(
500                #[cfg($separate_provide_extern)]
501                pub $name: for<'tcx> fn(
502                    TyCtxt<'tcx>,
503                    $name::Key<'tcx>,
504                ) -> $name::ProvidedValue<'tcx>,
505            )*
506        }
507
508        impl Default for Providers {
509            fn default() -> Self {
510                Providers {
511                    $(
512                        $name: |_, key| {
513                            $crate::query::plumbing::default_query(stringify!($name), &key)
514                        },
515                    )*
516                }
517            }
518        }
519
520        impl Default for ExternProviders {
521            fn default() -> Self {
522                ExternProviders {
523                    $(
524                        #[cfg($separate_provide_extern)]
525                        $name: |_, key| $crate::query::plumbing::default_extern_query(
526                            stringify!($name),
527                            &key,
528                        ),
529                    )*
530                }
531            }
532        }
533
534        impl Copy for Providers {}
535        impl Clone for Providers {
536            fn clone(&self) -> Self { *self }
537        }
538
539        impl Copy for ExternProviders {}
540        impl Clone for ExternProviders {
541            fn clone(&self) -> Self { *self }
542        }
543
544        impl<'tcx> TyCtxt<'tcx> {
545            $(
546                $(#[$attr])*
547                #[inline(always)]
548                #[must_use]
549                pub fn $name(self, key: maybe_into_query_key!($($K)*)) -> $V {
550                    self.at(DUMMY_SP).$name(key)
551                }
552            )*
553        }
554
555        impl<'tcx> $crate::query::TyCtxtAt<'tcx> {
556            $(
557                $(#[$attr])*
558                #[inline(always)]
559                pub fn $name(self, key: maybe_into_query_key!($($K)*)) -> $V {
560                    use $crate::query::{erase, inner};
561
562                    erase::restore_val::<$V>(inner::query_get_at(
563                        self.tcx,
564                        self.span,
565                        &self.tcx.query_system.query_vtables.$name,
566                        $crate::query::IntoQueryKey::into_query_key(key),
567                    ))
568                }
569            )*
570        }
571
572        impl<'tcx> $crate::query::TyCtxtEnsureOk<'tcx> {
573            $(
574                $(#[$attr])*
575                #[inline(always)]
576                pub fn $name(self, key: maybe_into_query_key!($($K)*)) {
577                    $crate::query::inner::query_ensure_ok_or_done(
578                        self.tcx,
579                        &self.tcx.query_system.query_vtables.$name,
580                        $crate::query::IntoQueryKey::into_query_key(key),
581                        $crate::query::EnsureMode::Ok,
582                    )
583                }
584            )*
585        }
586
587        // Only defined when the `returns_error_guaranteed` modifier is present.
588        impl<'tcx> $crate::query::TyCtxtEnsureResult<'tcx> {
589            $(
590                #[cfg($returns_error_guaranteed)]
591                $(#[$attr])*
592                #[inline(always)]
593                pub fn $name(
594                    self,
595                    key: maybe_into_query_key!($($K)*),
596                ) -> Result<(), rustc_errors::ErrorGuaranteed> {
597                    $crate::query::inner::query_ensure_result(
598                        self.tcx,
599                        &self.tcx.query_system.query_vtables.$name,
600                        $crate::query::IntoQueryKey::into_query_key(key),
601                    )
602                }
603            )*
604        }
605
606        impl<'tcx> $crate::query::TyCtxtEnsureDone<'tcx> {
607            $(
608                $(#[$attr])*
609                #[inline(always)]
610                pub fn $name(self, key: maybe_into_query_key!($($K)*)) {
611                    $crate::query::inner::query_ensure_ok_or_done(
612                        self.tcx,
613                        &self.tcx.query_system.query_vtables.$name,
614                        $crate::query::IntoQueryKey::into_query_key(key),
615                        $crate::query::EnsureMode::Done,
616                    );
617                }
618            )*
619        }
620
621        $(
622            // Only defined when the `feedable` modifier is present.
623            #[cfg($feedable)]
624            impl<'tcx, K: $crate::query::IntoQueryKey<$name::Key<'tcx>> + Copy>
625                TyCtxtFeed<'tcx, K>
626            {
627                $(#[$attr])*
628                #[inline(always)]
629                pub fn $name(self, value: $name::ProvidedValue<'tcx>) {
630                    $crate::query::inner::query_feed(
631                        self.tcx,
632                        &self.tcx.query_system.query_vtables.$name,
633                        self.key().into_query_key(),
634                        $name::provided_to_erased(self.tcx, value),
635                    );
636                }
637            }
638        )*
639    };
640}
641
642// Re-export `macro_rules!` macros as normal items, so that they can be imported normally.
643pub(crate) use define_callbacks;
644pub(crate) use maybe_into_query_key;
645
646#[cold]
647pub(crate) fn default_query(name: &str, key: &dyn std::fmt::Debug) -> ! {
648    crate::util::bug::bug_fmt(format_args!("`tcx.{0}({1:?})` is not supported for this key;\nhint: Queries can be either made to the local crate, or the external crate. This error means you tried to use it for one that\'s not supported.\nIf that\'s not the case, {0} was likely never assigned to a provider function.\n",
        name, key))bug!(
649        "`tcx.{name}({key:?})` is not supported for this key;\n\
650        hint: Queries can be either made to the local crate, or the external crate. \
651        This error means you tried to use it for one that's not supported.\n\
652        If that's not the case, {name} was likely never assigned to a provider function.\n",
653    )
654}
655
656#[cold]
657pub(crate) fn default_extern_query(name: &str, key: &dyn std::fmt::Debug) -> ! {
658    crate::util::bug::bug_fmt(format_args!("`tcx.{0}({1:?})` unsupported by its crate; perhaps the `{0}` query was never assigned a provider function",
        name, key))bug!(
659        "`tcx.{name}({key:?})` unsupported by its crate; \
660         perhaps the `{name}` query was never assigned a provider function",
661    )
662}