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