2 use crate::hir::exports::Export;
3 use crate::infer::canonical::{self, Canonical};
4 use crate::lint::LintLevelMap;
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 DropckOutlivesResult, DtorckConstraint, MethodAutoderefStepsResult, NormalizationResult,
29 use crate::traits::specialization_graph;
30 use crate::traits::{self, ImplSource};
31 use crate::ty::subst::{GenericArg, SubstsRef};
32 use crate::ty::util::AlwaysRequiresDrop;
33 use crate::ty::{self, AdtSizedConstraint, CrateInherentImpls, ParamEnvAnd, Ty, TyCtxt};
34 use rustc_ast::expand::allocator::AllocatorKind;
35 use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap};
36 use rustc_data_structures::steal::Steal;
37 use rustc_data_structures::svh::Svh;
38 use rustc_data_structures::sync::Lrc;
39 use rustc_errors::ErrorReported;
41 use rustc_hir::def::DefKind;
42 use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, DefIdSet, LocalDefId};
43 use rustc_hir::lang_items::{LangItem, LanguageItems};
44 use rustc_hir::{Crate, ItemLocalId, TraitCandidate};
45 use rustc_index::{bit_set::FiniteBitSet, vec::IndexVec};
46 use rustc_session::config::{EntryFnType, OptLevel, OutputFilenames, SymbolManglingVersion};
47 use rustc_session::cstore::{CrateDepKind, CrateSource};
48 use rustc_session::cstore::{ExternCrate, ForeignModule, LinkagePreference, NativeLib};
49 use rustc_session::utils::NativeLibKind;
50 use rustc_session::Limits;
51 use rustc_target::abi;
52 use rustc_target::spec::PanicStrategy;
55 use rustc_attr as attr;
56 use rustc_span::symbol::Symbol;
57 use rustc_span::{Span, DUMMY_SP};
58 use std::collections::BTreeMap;
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 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>,
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 macro_rules! query_helper_param_ty {
110 (DefId) => { impl IntoQueryParam<DefId> };
114 macro_rules! query_storage {
115 ([][$K:ty, $V:ty]) => {
116 <DefaultCacheSelector as CacheSelector<$K, $V>>::Cache
118 ([(storage $ty:ty) $($rest:tt)*][$K:ty, $V:ty]) => {
119 <$ty as CacheSelector<$K, $V>>::Cache
121 ([$other:tt $($modifiers:tt)*][$($args:tt)*]) => {
122 query_storage!([$($modifiers)*][$($args)*])
126 macro_rules! separate_provide_extern_decl {
127 ([][$name:ident]) => {
130 ([(separate_provide_extern) $($rest:tt)*][$name:ident]) => {
133 query_keys::$name<'tcx>,
134 ) -> query_values::$name<'tcx>
136 ([$other:tt $($modifiers:tt)*][$($args:tt)*]) => {
137 separate_provide_extern_decl!([$($modifiers)*][$($args)*])
141 macro_rules! separate_provide_extern_default {
142 ([][$name:ident]) => {
145 ([(separate_provide_extern) $($rest:tt)*][$name:ident]) => {
147 "`tcx.{}({:?})` unsupported by its crate; \
148 perhaps the `{}` query was never assigned a provider function",
154 ([$other:tt $($modifiers:tt)*][$($args:tt)*]) => {
155 separate_provide_extern_default!([$($modifiers)*][$($args)*])
159 macro_rules! opt_remap_env_constness {
160 ([][$name:ident]) => {};
161 ([(remap_env_constness) $($rest:tt)*][$name:ident]) => {
162 let $name = $name.without_const();
164 ([$other:tt $($modifiers:tt)*][$name:ident]) => {
165 opt_remap_env_constness!([$($modifiers)*][$name])
169 macro_rules! define_callbacks {
172 [$($modifiers:tt)*] fn $name:ident($($K:tt)*) -> $V:ty,)*) => {
174 // HACK(eddyb) this is like the `impl QueryConfig for queries::$name`
175 // below, but using type aliases instead of associated types, to bypass
176 // the limitations around normalizing under HRTB - for example, this:
177 // `for<'tcx> fn(...) -> <queries::$name<'tcx> as QueryConfig<TyCtxt<'tcx>>>::Value`
178 // doesn't currently normalize to `for<'tcx> fn(...) -> query_values::$name<'tcx>`.
179 // This is primarily used by the `provide!` macro in `rustc_metadata`.
180 #[allow(nonstandard_style, unused_lifetimes)]
184 $(pub type $name<$tcx> = $($K)*;)*
186 #[allow(nonstandard_style, unused_lifetimes)]
187 pub mod query_values {
190 $(pub type $name<$tcx> = $V;)*
192 #[allow(nonstandard_style, unused_lifetimes)]
193 pub mod query_storage {
196 $(pub type $name<$tcx> = query_storage!([$($modifiers)*][$($K)*, $V]);)*
198 #[allow(nonstandard_style, unused_lifetimes)]
199 pub mod query_stored {
202 $(pub type $name<$tcx> = <query_storage::$name<$tcx> as QueryStorage>::Stored;)*
206 pub struct QueryCaches<$tcx> {
207 $($(#[$attr])* pub $name: QueryCacheStore<query_storage::$name<$tcx>>,)*
210 impl TyCtxtEnsure<$tcx> {
213 pub fn $name(self, key: query_helper_param_ty!($($K)*)) {
214 let key = key.into_query_param();
215 opt_remap_env_constness!([$($modifiers)*][key]);
217 let cached = try_get_cached(self.tcx, &self.tcx.query_caches.$name, &key, noop);
219 let lookup = match cached {
221 Err(lookup) => lookup,
224 self.tcx.queries.$name(self.tcx, DUMMY_SP, key, lookup, QueryMode::Ensure);
232 pub fn $name(self, key: query_helper_param_ty!($($K)*)) -> query_stored::$name<$tcx>
234 self.at(DUMMY_SP).$name(key)
238 impl TyCtxtAt<$tcx> {
241 pub fn $name(self, key: query_helper_param_ty!($($K)*)) -> query_stored::$name<$tcx>
243 let key = key.into_query_param();
244 opt_remap_env_constness!([$($modifiers)*][key]);
246 let cached = try_get_cached(self.tcx, &self.tcx.query_caches.$name, &key, Clone::clone);
248 let lookup = match cached {
249 Ok(value) => return value,
250 Err(lookup) => lookup,
253 self.tcx.queries.$name(self.tcx, self.span, key, lookup, QueryMode::Get).unwrap()
257 pub struct Providers {
258 $(pub $name: for<'tcx> fn(
260 query_keys::$name<'tcx>,
261 ) -> query_values::$name<'tcx>,)*
264 pub struct ExternProviders {
265 $(pub $name: separate_provide_extern_decl!([$($modifiers)*][$name]),)*
268 impl Default for Providers {
269 fn default() -> Self {
271 $($name: |_, key| bug!(
272 "`tcx.{}({:?})` unsupported by its crate; \
273 perhaps the `{}` query was never assigned a provider function",
282 impl Default for ExternProviders {
283 fn default() -> Self {
285 $($name: separate_provide_extern_default!([$($modifiers)*][$name]),)*
290 impl Copy for Providers {}
291 impl Clone for Providers {
292 fn clone(&self) -> Self { *self }
295 impl Copy for ExternProviders {}
296 impl Clone for ExternProviders {
297 fn clone(&self) -> Self { *self }
300 pub trait QueryEngine<'tcx>: rustc_data_structures::sync::Sync {
301 fn as_any(&'tcx self) -> &'tcx dyn std::any::Any;
303 fn try_mark_green(&'tcx self, tcx: TyCtxt<'tcx>, dep_node: &dep_graph::DepNode) -> bool;
310 key: query_keys::$name<$tcx>,
313 ) -> Option<query_stored::$name<$tcx>>;)*
318 // Each of these queries corresponds to a function pointer field in the
319 // `Providers` struct for requesting a value of that type, and a method
320 // on `tcx: TyCtxt` (and `tcx.at(span)`) for doing that request in a way
321 // which memoizes and does dep-graph tracking, wrapping around the actual
322 // `Providers` that the driver creates (using several `rustc_*` crates).
324 // The result type of each query must implement `Clone`, and additionally
325 // `ty::query::values::Value`, which produces an appropriate placeholder
326 // (error) value if the query resulted in a query cycle.
327 // Queries marked with `fatal_cycle` do not need the latter implementation,
328 // as they will raise an fatal error on query cycles instead.
330 rustc_query_append! { [define_callbacks!][<'tcx>] }
333 use super::{DefId, LocalDefId};
335 /// An analogue of the `Into` trait that's intended only for query paramaters.
337 /// This exists to allow queries to accept either `DefId` or `LocalDefId` while requiring that the
338 /// user call `to_def_id` to convert between them everywhere else.
339 pub trait IntoQueryParam<P> {
340 fn into_query_param(self) -> P;
343 impl<P> IntoQueryParam<P> for P {
345 fn into_query_param(self) -> P {
350 impl IntoQueryParam<DefId> for LocalDefId {
352 fn into_query_param(self) -> DefId {
358 use sealed::IntoQueryParam;
361 pub fn def_kind(self, def_id: impl IntoQueryParam<DefId>) -> DefKind {
362 let def_id = def_id.into_query_param();
363 self.opt_def_kind(def_id)
364 .unwrap_or_else(|| bug!("def_kind: unsupported node: {:?}", def_id))
368 impl TyCtxtAt<'tcx> {
369 pub fn def_kind(self, def_id: impl IntoQueryParam<DefId>) -> DefKind {
370 let def_id = def_id.into_query_param();
371 self.opt_def_kind(def_id)
372 .unwrap_or_else(|| bug!("def_kind: unsupported node: {:?}", def_id))