]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_middle/src/ty/query.rs
Rollup merge of #93593 - JulianKnodt:master, r=oli-obk
[rust.git] / compiler / rustc_middle / src / ty / query.rs
1 use crate::dep_graph;
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,
12 };
13 use crate::middle::stability::{self, DeprecationEntry};
14 use crate::mir;
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;
19 use crate::thir;
20 use crate::traits::query::{
21     CanonicalPredicateGoal, CanonicalProjectionGoal, CanonicalTyGoal,
22     CanonicalTypeOpAscribeUserTypeGoal, CanonicalTypeOpEqGoal, CanonicalTypeOpNormalizeGoal,
23     CanonicalTypeOpProvePredicateGoal, CanonicalTypeOpSubtypeGoal, NoSolution,
24 };
25 use crate::traits::query::{
26     DropckOutlivesResult, DtorckConstraint, MethodAutoderefStepsResult, NormalizationResult,
27     OutlivesBound,
28 };
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::ErrorReported;
41 use rustc_hir as hir;
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;
54
55 use rustc_ast as ast;
56 use rustc_attr as attr;
57 use rustc_span::symbol::Symbol;
58 use rustc_span::{Span, DUMMY_SP};
59 use std::ops::Deref;
60 use std::path::PathBuf;
61 use std::sync::Arc;
62
63 pub(crate) use rustc_query_system::query::QueryJobId;
64 use rustc_query_system::query::*;
65
66 #[derive(Copy, Clone)]
67 pub struct TyCtxtAt<'tcx> {
68     pub tcx: TyCtxt<'tcx>,
69     pub span: Span,
70 }
71
72 impl<'tcx> Deref for TyCtxtAt<'tcx> {
73     type Target = TyCtxt<'tcx>;
74     #[inline(always)]
75     fn deref(&self) -> &Self::Target {
76         &self.tcx
77     }
78 }
79
80 #[derive(Copy, Clone)]
81 pub struct TyCtxtEnsure<'tcx> {
82     pub tcx: TyCtxt<'tcx>,
83 }
84
85 impl<'tcx> TyCtxt<'tcx> {
86     /// Returns a transparent wrapper for `TyCtxt`, which ensures queries
87     /// are executed instead of just returning their results.
88     #[inline(always)]
89     pub fn ensure(self) -> TyCtxtEnsure<'tcx> {
90         TyCtxtEnsure { tcx: self }
91     }
92
93     /// Returns a transparent wrapper for `TyCtxt` which uses
94     /// `span` as the location of queries performed through it.
95     #[inline(always)]
96     pub fn at(self, span: Span) -> TyCtxtAt<'tcx> {
97         TyCtxtAt { tcx: self, span }
98     }
99
100     pub fn try_mark_green(self, dep_node: &dep_graph::DepNode) -> bool {
101         self.queries.try_mark_green(self, dep_node)
102     }
103 }
104
105 /// Helper for `TyCtxtEnsure` to avoid a closure.
106 #[inline(always)]
107 fn noop<T>(_: &T) {}
108
109 macro_rules! query_helper_param_ty {
110     (DefId) => { impl IntoQueryParam<DefId> };
111     ($K:ty) => { $K };
112 }
113
114 macro_rules! query_storage {
115     ([][$K:ty, $V:ty]) => {
116         <DefaultCacheSelector as CacheSelector<$K, $V>>::Cache
117     };
118     ([(storage $ty:ty) $($rest:tt)*][$K:ty, $V:ty]) => {
119         <$ty as CacheSelector<$K, $V>>::Cache
120     };
121     ([$other:tt $($modifiers:tt)*][$($args:tt)*]) => {
122         query_storage!([$($modifiers)*][$($args)*])
123     };
124 }
125
126 macro_rules! separate_provide_extern_decl {
127     ([][$name:ident]) => {
128         ()
129     };
130     ([(separate_provide_extern) $($rest:tt)*][$name:ident]) => {
131         for<'tcx> fn(
132             TyCtxt<'tcx>,
133             query_keys::$name<'tcx>,
134         ) -> query_values::$name<'tcx>
135     };
136     ([$other:tt $($modifiers:tt)*][$($args:tt)*]) => {
137         separate_provide_extern_decl!([$($modifiers)*][$($args)*])
138     };
139 }
140
141 macro_rules! separate_provide_extern_default {
142     ([][$name:ident]) => {
143         ()
144     };
145     ([(separate_provide_extern) $($rest:tt)*][$name:ident]) => {
146         |_, key| bug!(
147             "`tcx.{}({:?})` unsupported by its crate; \
148              perhaps the `{}` query was never assigned a provider function",
149             stringify!($name),
150             key,
151             stringify!($name),
152         )
153     };
154     ([$other:tt $($modifiers:tt)*][$($args:tt)*]) => {
155         separate_provide_extern_default!([$($modifiers)*][$($args)*])
156     };
157 }
158
159 macro_rules! opt_remap_env_constness {
160     ([][$name:ident]) => {};
161     ([(remap_env_constness) $($rest:tt)*][$name:ident]) => {
162         let $name = $name.without_const();
163     };
164     ([$other:tt $($modifiers:tt)*][$name:ident]) => {
165         opt_remap_env_constness!([$($modifiers)*][$name])
166     };
167 }
168
169 macro_rules! define_callbacks {
170     (<$tcx:tt>
171      $($(#[$attr:meta])*
172         [$($modifiers:tt)*] fn $name:ident($($K:tt)*) -> $V:ty,)*) => {
173
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)]
181         pub mod query_keys {
182             use super::*;
183
184             $(pub type $name<$tcx> = $($K)*;)*
185         }
186         #[allow(nonstandard_style, unused_lifetimes)]
187         pub mod query_values {
188             use super::*;
189
190             $(pub type $name<$tcx> = $V;)*
191         }
192         #[allow(nonstandard_style, unused_lifetimes)]
193         pub mod query_storage {
194             use super::*;
195
196             $(pub type $name<$tcx> = query_storage!([$($modifiers)*][$($K)*, $V]);)*
197         }
198         #[allow(nonstandard_style, unused_lifetimes)]
199         pub mod query_stored {
200             use super::*;
201
202             $(pub type $name<$tcx> = <query_storage::$name<$tcx> as QueryStorage>::Stored;)*
203         }
204
205         #[derive(Default)]
206         pub struct QueryCaches<$tcx> {
207             $($(#[$attr])* pub $name: QueryCacheStore<query_storage::$name<$tcx>>,)*
208         }
209
210         impl<$tcx> TyCtxtEnsure<$tcx> {
211             $($(#[$attr])*
212             #[inline(always)]
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]);
216
217                 let cached = try_get_cached(self.tcx, &self.tcx.query_caches.$name, &key, noop);
218
219                 let lookup = match cached {
220                     Ok(()) => return,
221                     Err(lookup) => lookup,
222                 };
223
224                 self.tcx.queries.$name(self.tcx, DUMMY_SP, key, lookup, QueryMode::Ensure);
225             })*
226         }
227
228         impl<$tcx> TyCtxt<$tcx> {
229             $($(#[$attr])*
230             #[inline(always)]
231             #[must_use]
232             pub fn $name(self, key: query_helper_param_ty!($($K)*)) -> query_stored::$name<$tcx>
233             {
234                 self.at(DUMMY_SP).$name(key)
235             })*
236         }
237
238         impl<$tcx> TyCtxtAt<$tcx> {
239             $($(#[$attr])*
240             #[inline(always)]
241             pub fn $name(self, key: query_helper_param_ty!($($K)*)) -> query_stored::$name<$tcx>
242             {
243                 let key = key.into_query_param();
244                 opt_remap_env_constness!([$($modifiers)*][key]);
245
246                 let cached = try_get_cached(self.tcx, &self.tcx.query_caches.$name, &key, Clone::clone);
247
248                 let lookup = match cached {
249                     Ok(value) => return value,
250                     Err(lookup) => lookup,
251                 };
252
253                 self.tcx.queries.$name(self.tcx, self.span, key, lookup, QueryMode::Get).unwrap()
254             })*
255         }
256
257         pub struct Providers {
258             $(pub $name: for<'tcx> fn(
259                 TyCtxt<'tcx>,
260                 query_keys::$name<'tcx>,
261             ) -> query_values::$name<'tcx>,)*
262         }
263
264         pub struct ExternProviders {
265             $(pub $name: separate_provide_extern_decl!([$($modifiers)*][$name]),)*
266         }
267
268         impl Default for Providers {
269             fn default() -> Self {
270                 Providers {
271                     $($name: |_, key| bug!(
272                         "`tcx.{}({:?})` unsupported by its crate; \
273                          perhaps the `{}` query was never assigned a provider function",
274                         stringify!($name),
275                         key,
276                         stringify!($name),
277                     ),)*
278                 }
279             }
280         }
281
282         impl Default for ExternProviders {
283             fn default() -> Self {
284                 ExternProviders {
285                     $($name: separate_provide_extern_default!([$($modifiers)*][$name]),)*
286                 }
287             }
288         }
289
290         impl Copy for Providers {}
291         impl Clone for Providers {
292             fn clone(&self) -> Self { *self }
293         }
294
295         impl Copy for ExternProviders {}
296         impl Clone for ExternProviders {
297             fn clone(&self) -> Self { *self }
298         }
299
300         pub trait QueryEngine<'tcx>: rustc_data_structures::sync::Sync {
301             fn as_any(&'tcx self) -> &'tcx dyn std::any::Any;
302
303             fn try_mark_green(&'tcx self, tcx: TyCtxt<'tcx>, dep_node: &dep_graph::DepNode) -> bool;
304
305             $($(#[$attr])*
306             fn $name(
307                 &'tcx self,
308                 tcx: TyCtxt<$tcx>,
309                 span: Span,
310                 key: query_keys::$name<$tcx>,
311                 lookup: QueryLookup,
312                 mode: QueryMode,
313             ) -> Option<query_stored::$name<$tcx>>;)*
314         }
315     };
316 }
317
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).
323 //
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.
329
330 rustc_query_append! { [define_callbacks!][<'tcx>] }
331
332 mod sealed {
333     use super::{DefId, LocalDefId};
334
335     /// An analogue of the `Into` trait that's intended only for query paramaters.
336     ///
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;
341     }
342
343     impl<P> IntoQueryParam<P> for P {
344         #[inline(always)]
345         fn into_query_param(self) -> P {
346             self
347         }
348     }
349
350     impl IntoQueryParam<DefId> for LocalDefId {
351         #[inline(always)]
352         fn into_query_param(self) -> DefId {
353             self.to_def_id()
354         }
355     }
356 }
357
358 use sealed::IntoQueryParam;
359
360 impl<'tcx> TyCtxt<'tcx> {
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))
365     }
366 }
367
368 impl<'tcx> 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))
373     }
374 }