2 use crate::infer::canonical::{self, Canonical};
3 use crate::lint::LintLevelMap;
4 use crate::metadata::ModChild;
5 use crate::middle::codegen_fn_attrs::CodegenFnAttrs;
6 use crate::middle::exported_symbols::{ExportedSymbol, SymbolExportLevel};
7 use crate::middle::lib_features::LibFeatures;
8 use crate::middle::privacy::AccessLevels;
9 use crate::middle::region;
10 use crate::middle::resolve_lifetime::{
11 LifetimeScopeForPath, ObjectLifetimeDefault, Region, ResolveLifetimes,
13 use crate::middle::stability::{self, DeprecationEntry};
15 use crate::mir::interpret::GlobalId;
16 use crate::mir::interpret::{ConstAlloc, LitToConstError, LitToConstInput};
17 use crate::mir::interpret::{ConstValue, EvalToAllocationRawResult, EvalToConstValueResult};
18 use crate::mir::mono::CodegenUnit;
20 use crate::traits::query::{
21 CanonicalPredicateGoal, CanonicalProjectionGoal, CanonicalTyGoal,
22 CanonicalTypeOpAscribeUserTypeGoal, CanonicalTypeOpEqGoal, CanonicalTypeOpNormalizeGoal,
23 CanonicalTypeOpProvePredicateGoal, CanonicalTypeOpSubtypeGoal, NoSolution,
25 use crate::traits::query::{
26 DropckConstraint, DropckOutlivesResult, MethodAutoderefStepsResult, NormalizationResult,
29 use crate::traits::specialization_graph;
30 use crate::traits::{self, ImplSource};
31 use crate::ty::fast_reject::SimplifiedType;
32 use crate::ty::subst::{GenericArg, SubstsRef};
33 use crate::ty::util::AlwaysRequiresDrop;
34 use crate::ty::{self, AdtSizedConstraint, CrateInherentImpls, ParamEnvAnd, Ty, TyCtxt};
35 use rustc_ast::expand::allocator::AllocatorKind;
36 use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap};
37 use rustc_data_structures::steal::Steal;
38 use rustc_data_structures::svh::Svh;
39 use rustc_data_structures::sync::Lrc;
40 use rustc_errors::ErrorGuaranteed;
42 use rustc_hir::def::DefKind;
43 use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, DefIdSet, LocalDefId};
44 use rustc_hir::lang_items::{LangItem, LanguageItems};
45 use rustc_hir::{Crate, ItemLocalId, TraitCandidate};
46 use rustc_index::{bit_set::FiniteBitSet, vec::IndexVec};
47 use rustc_session::config::{EntryFnType, OptLevel, OutputFilenames, SymbolManglingVersion};
48 use rustc_session::cstore::{CrateDepKind, CrateSource};
49 use rustc_session::cstore::{ExternCrate, ForeignModule, LinkagePreference, NativeLib};
50 use rustc_session::utils::NativeLibKind;
51 use rustc_session::Limits;
52 use rustc_target::abi;
53 use rustc_target::spec::PanicStrategy;
56 use rustc_attr as attr;
57 use rustc_span::symbol::Symbol;
58 use rustc_span::{Span, DUMMY_SP};
60 use std::path::PathBuf;
63 pub(crate) use rustc_query_system::query::QueryJobId;
64 use rustc_query_system::query::*;
66 #[derive(Copy, Clone)]
67 pub struct TyCtxtAt<'tcx> {
68 pub tcx: TyCtxt<'tcx>,
72 impl<'tcx> Deref for TyCtxtAt<'tcx> {
73 type Target = TyCtxt<'tcx>;
75 fn deref(&self) -> &Self::Target {
80 #[derive(Copy, Clone)]
81 pub struct TyCtxtEnsure<'tcx> {
82 pub tcx: TyCtxt<'tcx>,
85 impl<'tcx> TyCtxt<'tcx> {
86 /// Returns a transparent wrapper for `TyCtxt`, which ensures queries
87 /// are executed instead of just returning their results.
89 pub fn ensure(self) -> TyCtxtEnsure<'tcx> {
90 TyCtxtEnsure { tcx: self }
93 /// Returns a transparent wrapper for `TyCtxt` which uses
94 /// `span` as the location of queries performed through it.
96 pub fn at(self, span: Span) -> TyCtxtAt<'tcx> {
97 TyCtxtAt { tcx: self, span }
100 pub fn try_mark_green(self, dep_node: &dep_graph::DepNode) -> bool {
101 self.queries.try_mark_green(self, dep_node)
105 /// Helper for `TyCtxtEnsure` to avoid a closure.
109 /// Helper to ensure that queries only return `Copy` types.
111 fn copy<T: Copy>(x: &T) -> T {
115 macro_rules! query_helper_param_ty {
116 (DefId) => { impl IntoQueryParam<DefId> };
120 macro_rules! query_storage {
121 ([][$K:ty, $V:ty]) => {
122 <DefaultCacheSelector as CacheSelector<$K, $V>>::Cache
124 ([(storage $ty:ty) $($rest:tt)*][$K:ty, $V:ty]) => {
125 <$ty as CacheSelector<$K, $V>>::Cache
127 ([$other:tt $($modifiers:tt)*][$($args:tt)*]) => {
128 query_storage!([$($modifiers)*][$($args)*])
132 macro_rules! separate_provide_extern_decl {
133 ([][$name:ident]) => {
136 ([(separate_provide_extern) $($rest:tt)*][$name:ident]) => {
139 query_keys::$name<'tcx>,
140 ) -> query_values::$name<'tcx>
142 ([$other:tt $($modifiers:tt)*][$($args:tt)*]) => {
143 separate_provide_extern_decl!([$($modifiers)*][$($args)*])
147 macro_rules! separate_provide_extern_default {
148 ([][$name:ident]) => {
151 ([(separate_provide_extern) $($rest:tt)*][$name:ident]) => {
153 "`tcx.{}({:?})` unsupported by its crate; \
154 perhaps the `{}` query was never assigned a provider function",
160 ([$other:tt $($modifiers:tt)*][$($args:tt)*]) => {
161 separate_provide_extern_default!([$($modifiers)*][$($args)*])
165 macro_rules! opt_remap_env_constness {
166 ([][$name:ident]) => {};
167 ([(remap_env_constness) $($rest:tt)*][$name:ident]) => {
168 let $name = $name.without_const();
170 ([$other:tt $($modifiers:tt)*][$name:ident]) => {
171 opt_remap_env_constness!([$($modifiers)*][$name])
175 macro_rules! define_callbacks {
178 [$($modifiers:tt)*] fn $name:ident($($K:tt)*) -> $V:ty,)*) => {
180 // HACK(eddyb) this is like the `impl QueryConfig for queries::$name`
181 // below, but using type aliases instead of associated types, to bypass
182 // the limitations around normalizing under HRTB - for example, this:
183 // `for<'tcx> fn(...) -> <queries::$name<'tcx> as QueryConfig<TyCtxt<'tcx>>>::Value`
184 // doesn't currently normalize to `for<'tcx> fn(...) -> query_values::$name<'tcx>`.
185 // This is primarily used by the `provide!` macro in `rustc_metadata`.
186 #[allow(nonstandard_style, unused_lifetimes)]
190 $(pub type $name<$tcx> = $($K)*;)*
192 #[allow(nonstandard_style, unused_lifetimes)]
193 pub mod query_values {
196 $(pub type $name<$tcx> = $V;)*
198 #[allow(nonstandard_style, unused_lifetimes)]
199 pub mod query_storage {
202 $(pub type $name<$tcx> = query_storage!([$($modifiers)*][$($K)*, $V]);)*
204 #[allow(nonstandard_style, unused_lifetimes)]
205 pub mod query_stored {
208 $(pub type $name<$tcx> = <query_storage::$name<$tcx> as QueryStorage>::Stored;)*
212 pub struct QueryCaches<$tcx> {
213 $($(#[$attr])* pub $name: query_storage::$name<$tcx>,)*
216 impl<$tcx> TyCtxtEnsure<$tcx> {
219 pub fn $name(self, key: query_helper_param_ty!($($K)*)) {
220 let key = key.into_query_param();
221 opt_remap_env_constness!([$($modifiers)*][key]);
223 let cached = try_get_cached(self.tcx, &self.tcx.query_caches.$name, &key, noop);
230 self.tcx.queries.$name(self.tcx, DUMMY_SP, key, QueryMode::Ensure);
234 impl<$tcx> TyCtxt<$tcx> {
238 pub fn $name(self, key: query_helper_param_ty!($($K)*)) -> query_stored::$name<$tcx>
240 self.at(DUMMY_SP).$name(key)
244 impl<$tcx> TyCtxtAt<$tcx> {
247 pub fn $name(self, key: query_helper_param_ty!($($K)*)) -> query_stored::$name<$tcx>
249 let key = key.into_query_param();
250 opt_remap_env_constness!([$($modifiers)*][key]);
252 let cached = try_get_cached(self.tcx, &self.tcx.query_caches.$name, &key, copy);
255 Ok(value) => return value,
259 self.tcx.queries.$name(self.tcx, self.span, key, QueryMode::Get).unwrap()
263 pub struct Providers {
264 $(pub $name: for<'tcx> fn(
266 query_keys::$name<'tcx>,
267 ) -> query_values::$name<'tcx>,)*
270 pub struct ExternProviders {
271 $(pub $name: separate_provide_extern_decl!([$($modifiers)*][$name]),)*
274 impl Default for Providers {
275 fn default() -> Self {
277 $($name: |_, key| bug!(
278 "`tcx.{}({:?})` unsupported by its crate; \
279 perhaps the `{}` query was never assigned a provider function",
288 impl Default for ExternProviders {
289 fn default() -> Self {
291 $($name: separate_provide_extern_default!([$($modifiers)*][$name]),)*
296 impl Copy for Providers {}
297 impl Clone for Providers {
298 fn clone(&self) -> Self { *self }
301 impl Copy for ExternProviders {}
302 impl Clone for ExternProviders {
303 fn clone(&self) -> Self { *self }
306 pub trait QueryEngine<'tcx>: rustc_data_structures::sync::Sync {
307 fn as_any(&'tcx self) -> &'tcx dyn std::any::Any;
309 fn try_mark_green(&'tcx self, tcx: TyCtxt<'tcx>, dep_node: &dep_graph::DepNode) -> bool;
316 key: query_keys::$name<$tcx>,
318 ) -> Option<query_stored::$name<$tcx>>;)*
323 // Each of these queries corresponds to a function pointer field in the
324 // `Providers` struct for requesting a value of that type, and a method
325 // on `tcx: TyCtxt` (and `tcx.at(span)`) for doing that request in a way
326 // which memoizes and does dep-graph tracking, wrapping around the actual
327 // `Providers` that the driver creates (using several `rustc_*` crates).
329 // The result type of each query must implement `Clone`, and additionally
330 // `ty::query::values::Value`, which produces an appropriate placeholder
331 // (error) value if the query resulted in a query cycle.
332 // Queries marked with `fatal_cycle` do not need the latter implementation,
333 // as they will raise an fatal error on query cycles instead.
335 rustc_query_append! { [define_callbacks!][<'tcx>] }
338 use super::{DefId, LocalDefId};
340 /// An analogue of the `Into` trait that's intended only for query parameters.
342 /// This exists to allow queries to accept either `DefId` or `LocalDefId` while requiring that the
343 /// user call `to_def_id` to convert between them everywhere else.
344 pub trait IntoQueryParam<P> {
345 fn into_query_param(self) -> P;
348 impl<P> IntoQueryParam<P> for P {
350 fn into_query_param(self) -> P {
355 impl<'a, P: Copy> IntoQueryParam<P> for &'a P {
357 fn into_query_param(self) -> P {
362 impl IntoQueryParam<DefId> for LocalDefId {
364 fn into_query_param(self) -> DefId {
370 use sealed::IntoQueryParam;
372 impl<'tcx> TyCtxt<'tcx> {
373 pub fn def_kind(self, def_id: impl IntoQueryParam<DefId>) -> DefKind {
374 let def_id = def_id.into_query_param();
375 self.opt_def_kind(def_id)
376 .unwrap_or_else(|| bug!("def_kind: unsupported node: {:?}", def_id))
380 impl<'tcx> TyCtxtAt<'tcx> {
381 pub fn def_kind(self, def_id: impl IntoQueryParam<DefId>) -> DefKind {
382 let def_id = def_id.into_query_param();
383 self.opt_def_kind(def_id)
384 .unwrap_or_else(|| bug!("def_kind: unsupported node: {:?}", def_id))