1 use super::LazyQueryDecodable;
2 use crate::creader::{CStore, LoadedMacro};
3 use crate::foreign_modules;
4 use crate::native_libs;
7 use rustc_hir::def::{CtorKind, DefKind, Res};
8 use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, LOCAL_CRATE};
9 use rustc_hir::definitions::{DefKey, DefPath, DefPathHash};
10 use rustc_middle::metadata::ModChild;
11 use rustc_middle::middle::exported_symbols::ExportedSymbol;
12 use rustc_middle::ty::fast_reject::SimplifiedType;
13 use rustc_middle::ty::query::{ExternProviders, Providers};
14 use rustc_middle::ty::{self, TyCtxt, Visibility};
15 use rustc_session::cstore::{CrateSource, CrateStore};
16 use rustc_session::utils::NativeLibKind;
17 use rustc_session::{Session, StableCrateId};
18 use rustc_span::hygiene::{ExpnHash, ExpnId};
19 use rustc_span::source_map::{Span, Spanned};
20 use rustc_span::symbol::{kw, Symbol};
22 use rustc_data_structures::sync::Lrc;
23 use smallvec::SmallVec;
26 macro_rules! provide_one {
27 (<$lt:tt> $tcx:ident, $def_id:ident, $other:ident, $cdata:ident, $name:ident => { table }) => {
29 <$lt> $tcx, $def_id, $other, $cdata, $name => {
30 $cdata.root.tables.$name.get($cdata, $def_id.index).decode_query(
33 || panic!("{:?} does not have a {:?}", $def_id, stringify!($name)),
38 (<$lt:tt> $tcx:ident, $def_id:ident, $other:ident, $cdata:ident, $name:ident => $compute:block) => {
41 def_id_arg: ty::query::query_keys::$name<$lt>,
42 ) -> ty::query::query_values::$name<$lt> {
44 $tcx.prof.generic_activity(concat!("metadata_decode_entry_", stringify!($name)));
46 #[allow(unused_variables)]
47 let ($def_id, $other) = def_id_arg.into_args();
48 assert!(!$def_id.is_local());
50 // External query providers call `crate_hash` in order to register a dependency
51 // on the crate metadata. The exception is `crate_hash` itself, which obviously
52 // doesn't need to do this (and can't, as it would cause a query cycle).
53 use rustc_middle::dep_graph::DepKind;
54 if DepKind::$name != DepKind::crate_hash && $tcx.dep_graph.is_fully_enabled() {
55 $tcx.ensure().crate_hash($def_id.krate);
58 let $cdata = CStore::from_tcx($tcx).get_crate_data($def_id.krate);
65 macro_rules! provide {
66 (<$lt:tt> $tcx:ident, $def_id:ident, $other:ident, $cdata:ident,
67 $($name:ident => { $($compute:tt)* })*) => {
68 pub fn provide_extern(providers: &mut ExternProviders) {
70 <$lt> $tcx, $def_id, $other, $cdata, $name => { $($compute)* }
73 *providers = ExternProviders {
81 // small trait to work around different signature queries all being defined via
85 fn into_args(self) -> (DefId, Self::Other);
88 impl IntoArgs for DefId {
90 fn into_args(self) -> (DefId, ()) {
95 impl IntoArgs for CrateNum {
97 fn into_args(self) -> (DefId, ()) {
98 (self.as_def_id(), ())
102 impl IntoArgs for (CrateNum, DefId) {
104 fn into_args(self) -> (DefId, DefId) {
105 (self.0.as_def_id(), self.1)
109 impl<'tcx> IntoArgs for ty::InstanceDef<'tcx> {
111 fn into_args(self) -> (DefId, ()) {
116 impl IntoArgs for (CrateNum, SimplifiedType) {
117 type Other = SimplifiedType;
118 fn into_args(self) -> (DefId, SimplifiedType) {
119 (self.0.as_def_id(), self.1)
123 provide! { <'tcx> tcx, def_id, other, cdata,
124 explicit_item_bounds => { table }
125 explicit_predicates_of => { table }
126 generics_of => { table }
127 inferred_outlives_of => { table }
128 super_predicates_of => { table }
130 variances_of => { table }
132 impl_trait_ref => { table }
133 const_param_default => { table }
134 thir_abstract_const => { table }
135 optimized_mir => { table }
136 mir_for_ctfe => { table }
137 promoted_mir => { table }
138 def_span => { table }
139 def_ident_span => { table }
140 lookup_stability => { table }
141 lookup_const_stability => { table }
142 lookup_deprecation_entry => { table }
143 visibility => { table }
144 unused_generic_params => { table }
145 opt_def_kind => { table }
146 impl_parent => { table }
147 impl_polarity => { table }
148 impl_defaultness => { table }
149 impl_constness => { table }
150 coerce_unsized_info => { table }
151 mir_const_qualif => { table }
152 rendered_const => { table }
153 asyncness => { table }
154 fn_arg_names => { table }
155 generator_kind => { table }
156 trait_def => { table }
158 adt_def => { cdata.get_adt_def(def_id.index, tcx) }
161 tcx.calculate_dtor(def_id, |_,_| Ok(()))
163 associated_item_def_ids => {
164 tcx.arena.alloc_from_iter(cdata.get_associated_item_def_ids(def_id.index, tcx.sess))
166 associated_item => { cdata.get_associated_item(def_id.index) }
167 inherent_impls => { cdata.get_inherent_implementations_for_type(tcx, def_id.index) }
168 is_foreign_item => { cdata.is_foreign_item(def_id.index) }
169 item_attrs => { tcx.arena.alloc_from_iter(cdata.get_item_attrs(def_id.index, tcx.sess)) }
170 trait_of_item => { cdata.get_trait_of_item(def_id.index) }
171 is_mir_available => { cdata.is_item_mir_available(def_id.index) }
172 is_ctfe_mir_available => { cdata.is_ctfe_mir_available(def_id.index) }
174 dylib_dependency_formats => { cdata.get_dylib_dependency_formats(tcx) }
175 is_private_dep => { cdata.private_dep }
176 is_panic_runtime => { cdata.root.panic_runtime }
177 is_compiler_builtins => { cdata.root.compiler_builtins }
178 has_global_allocator => { cdata.root.has_global_allocator }
179 has_panic_handler => { cdata.root.has_panic_handler }
180 is_profiler_runtime => { cdata.root.profiler_runtime }
181 panic_strategy => { cdata.root.panic_strategy }
182 panic_in_drop_strategy => { cdata.root.panic_in_drop_strategy }
184 let r = *cdata.extern_crate.lock();
185 r.map(|c| &*tcx.arena.alloc(c))
187 is_no_builtins => { cdata.root.no_builtins }
188 symbol_mangling_version => { cdata.root.symbol_mangling_version }
189 reachable_non_generics => {
190 let reachable_non_generics = tcx
191 .exported_symbols(cdata.cnum)
193 .filter_map(|&(exported_symbol, export_level)| {
194 if let ExportedSymbol::NonGeneric(def_id) = exported_symbol {
195 Some((def_id, export_level))
202 reachable_non_generics
204 native_libraries => { cdata.get_native_libraries(tcx.sess).collect() }
205 foreign_modules => { cdata.get_foreign_modules(tcx.sess).map(|m| (m.def_id, m)).collect() }
206 crate_hash => { cdata.root.hash }
207 crate_host_hash => { cdata.host_hash }
208 crate_name => { cdata.root.name }
210 extra_filename => { cdata.root.extra_filename.clone() }
212 traits_in_crate => { tcx.arena.alloc_from_iter(cdata.get_traits()) }
213 implementations_of_trait => { cdata.get_implementations_of_trait(tcx, other) }
214 crate_incoherent_impls => { cdata.get_incoherent_impls(tcx, other) }
217 let r = *cdata.dep_kind.lock();
221 let mut result = SmallVec::<[_; 8]>::new();
222 cdata.for_each_module_child(def_id.index, |child| result.push(child), tcx.sess);
223 tcx.arena.alloc_slice(&result)
225 defined_lib_features => { cdata.get_lib_features(tcx) }
226 defined_lang_items => { cdata.get_lang_items(tcx) }
227 diagnostic_items => { cdata.get_diagnostic_items() }
228 missing_lang_items => { cdata.get_missing_lang_items(tcx) }
230 missing_extern_crate_item => {
231 let r = matches!(*cdata.extern_crate.borrow(), Some(extern_crate) if !extern_crate.is_direct());
235 used_crate_source => { Lrc::clone(&cdata.source) }
237 exported_symbols => {
238 let syms = cdata.exported_symbols(tcx);
240 // FIXME rust-lang/rust#64319, rust-lang/rust#64872: We want
241 // to block export of generics from dylibs, but we must fix
242 // rust-lang/rust#65890 before we can do that robustly.
247 crate_extern_paths => { cdata.source().paths().cloned().collect() }
248 expn_that_defined => { cdata.get_expn_that_defined(def_id.index, tcx.sess) }
249 generator_diagnostic_data => { cdata.get_generator_diagnostic_data(tcx, def_id.index) }
252 pub(in crate::rmeta) fn provide(providers: &mut Providers) {
253 // FIXME(#44234) - almost all of these queries have no sub-queries and
254 // therefore no actual inputs, they're just reading tables calculated in
255 // resolve! Does this work? Unsure! That's what the issue is about
256 *providers = Providers {
257 allocator_kind: |tcx, ()| CStore::from_tcx(tcx).allocator_kind(),
258 is_dllimport_foreign_item: |tcx, id| match tcx.native_library_kind(id) {
260 NativeLibKind::Dylib { .. } | NativeLibKind::RawDylib | NativeLibKind::Unspecified,
264 is_statically_included_foreign_item: |tcx, id| {
265 matches!(tcx.native_library_kind(id), Some(NativeLibKind::Static { .. }))
267 is_private_dep: |_tcx, cnum| {
268 assert_eq!(cnum, LOCAL_CRATE);
271 native_library_kind: |tcx, id| {
272 tcx.native_libraries(id.krate)
274 .filter(|lib| native_libs::relevant_lib(&tcx.sess, lib))
276 let Some(fm_id) = lib.foreign_module else {
279 let map = tcx.foreign_modules(id.krate);
281 .expect("failed to find foreign module")
287 native_libraries: |tcx, cnum| {
288 assert_eq!(cnum, LOCAL_CRATE);
289 native_libs::collect(tcx)
291 foreign_modules: |tcx, cnum| {
292 assert_eq!(cnum, LOCAL_CRATE);
293 foreign_modules::collect(tcx).into_iter().map(|m| (m.def_id, m)).collect()
296 // Returns a map from a sufficiently visible external item (i.e., an
297 // external item that is visible from at least one local module) to a
298 // sufficiently visible parent (considering modules that re-export the
299 // external item to be parents).
300 visible_parent_map: |tcx, ()| {
301 use std::collections::hash_map::Entry;
302 use std::collections::vec_deque::VecDeque;
304 let mut visible_parent_map: DefIdMap<DefId> = Default::default();
305 // This is a secondary visible_parent_map, storing the DefId of parents that re-export
306 // the child as `_`. Since we prefer parents that don't do this, merge this map at the
307 // end, only if we're missing any keys from the former.
308 let mut fallback_map: DefIdMap<DefId> = Default::default();
310 // Issue 46112: We want the map to prefer the shortest
311 // paths when reporting the path to an item. Therefore we
312 // build up the map via a breadth-first search (BFS),
313 // which naturally yields minimal-length paths.
315 // Note that it needs to be a BFS over the whole forest of
316 // crates, not just each individual crate; otherwise you
317 // only get paths that are locally minimal with respect to
318 // whatever crate we happened to encounter first in this
319 // traversal, but not globally minimal across all crates.
320 let bfs_queue = &mut VecDeque::new();
322 for &cnum in tcx.crates(()) {
323 // Ignore crates without a corresponding local `extern crate` item.
324 if tcx.missing_extern_crate_item(cnum) {
328 bfs_queue.push_back(cnum.as_def_id());
331 let mut add_child = |bfs_queue: &mut VecDeque<_>, child: &ModChild, parent: DefId| {
332 if !child.vis.is_public() {
336 if let Some(def_id) = child.res.opt_def_id() {
337 if child.ident.name == kw::Underscore {
338 fallback_map.insert(def_id, parent);
342 match visible_parent_map.entry(def_id) {
343 Entry::Occupied(mut entry) => {
344 // If `child` is defined in crate `cnum`, ensure
345 // that it is mapped to a parent in `cnum`.
346 if def_id.is_local() && entry.get().is_local() {
347 entry.insert(parent);
350 Entry::Vacant(entry) => {
351 entry.insert(parent);
354 Res::Def(DefKind::Mod | DefKind::Enum | DefKind::Trait, _)
356 bfs_queue.push_back(def_id);
363 while let Some(def) = bfs_queue.pop_front() {
364 for child in tcx.module_children(def).iter() {
365 add_child(bfs_queue, child, def);
369 // Fill in any missing entries with the (less preferable) path ending in `::_`.
370 // We still use this path in a diagnostic that suggests importing `::*`.
371 for (child, parent) in fallback_map {
372 visible_parent_map.entry(child).or_insert(parent);
378 dependency_formats: |tcx, ()| Lrc::new(crate::dependency_format::calculate(tcx)),
379 has_global_allocator: |tcx, cnum| {
380 assert_eq!(cnum, LOCAL_CRATE);
381 CStore::from_tcx(tcx).has_global_allocator()
383 postorder_cnums: |tcx, ()| {
385 .alloc_slice(&CStore::from_tcx(tcx).crate_dependencies_in_postorder(LOCAL_CRATE))
387 crates: |tcx, ()| tcx.arena.alloc_from_iter(CStore::from_tcx(tcx).crates_untracked()),
393 pub fn struct_field_names_untracked<'a>(
397 ) -> impl Iterator<Item = Spanned<Symbol>> + 'a {
398 self.get_crate_data(def.krate).get_struct_field_names(def.index, sess)
401 pub fn struct_field_visibilities_untracked(
404 ) -> impl Iterator<Item = Visibility> + '_ {
405 self.get_crate_data(def.krate).get_struct_field_visibilities(def.index)
408 pub fn ctor_def_id_and_kind_untracked(&self, def: DefId) -> Option<(DefId, CtorKind)> {
409 self.get_crate_data(def.krate).get_ctor_def_id_and_kind(def.index)
412 pub fn visibility_untracked(&self, def: DefId) -> Visibility {
413 self.get_crate_data(def.krate).get_visibility(def.index)
416 pub fn module_children_untracked(&self, def_id: DefId, sess: &Session) -> Vec<ModChild> {
417 let mut result = vec![];
418 self.get_crate_data(def_id.krate).for_each_module_child(
420 |child| result.push(child),
426 pub fn load_macro_untracked(&self, id: DefId, sess: &Session) -> LoadedMacro {
427 let _prof_timer = sess.prof.generic_activity("metadata_load_macro");
429 let data = self.get_crate_data(id.krate);
430 if data.root.is_proc_macro_crate() {
431 return LoadedMacro::ProcMacro(data.load_proc_macro(id.index, sess));
434 let span = data.get_span(id.index, sess);
436 LoadedMacro::MacroDef(
438 ident: data.item_ident(id.index, sess),
439 id: ast::DUMMY_NODE_ID,
441 attrs: data.get_item_attrs(id.index, sess).collect(),
442 kind: ast::ItemKind::MacroDef(data.get_macro(id.index, sess)),
443 vis: ast::Visibility {
444 span: span.shrink_to_lo(),
445 kind: ast::VisibilityKind::Inherited,
454 pub fn fn_has_self_parameter_untracked(&self, def: DefId) -> bool {
455 self.get_crate_data(def.krate).get_fn_has_self_parameter(def.index)
458 pub fn crate_source_untracked(&self, cnum: CrateNum) -> Lrc<CrateSource> {
459 self.get_crate_data(cnum).source.clone()
462 pub fn get_span_untracked(&self, def_id: DefId, sess: &Session) -> Span {
463 self.get_crate_data(def_id.krate).get_span(def_id.index, sess)
466 pub fn def_kind(&self, def: DefId) -> DefKind {
467 self.get_crate_data(def.krate).def_kind(def.index)
470 pub fn crates_untracked(&self) -> impl Iterator<Item = CrateNum> + '_ {
471 self.iter_crate_data().map(|(cnum, _)| cnum)
474 pub fn item_generics_num_lifetimes(&self, def_id: DefId, sess: &Session) -> usize {
475 self.get_crate_data(def_id.krate).get_generics(def_id.index, sess).own_counts().lifetimes
478 pub fn module_expansion_untracked(&self, def_id: DefId, sess: &Session) -> ExpnId {
479 self.get_crate_data(def_id.krate).module_expansion(def_id.index, sess)
482 /// Only public-facing way to traverse all the definitions in a non-local crate.
483 /// Critically useful for this third-party project: <https://github.com/hacspec/hacspec>.
484 /// See <https://github.com/rust-lang/rust/pull/85889> for context.
485 pub fn num_def_ids_untracked(&self, cnum: CrateNum) -> usize {
486 self.get_crate_data(cnum).num_def_ids()
489 pub fn item_attrs_untracked<'a>(
493 ) -> impl Iterator<Item = ast::Attribute> + 'a {
494 self.get_crate_data(def_id.krate).get_item_attrs(def_id.index, sess)
497 pub fn get_proc_macro_quoted_span_untracked(
503 self.get_crate_data(cnum).get_proc_macro_quoted_span(id, sess)
506 /// Decodes all traits in the crate (for rustdoc).
507 pub fn traits_in_crate_untracked(&self, cnum: CrateNum) -> impl Iterator<Item = DefId> + '_ {
508 self.get_crate_data(cnum).get_traits()
511 /// Decodes all trait impls in the crate (for rustdoc).
512 pub fn trait_impls_in_crate_untracked(
515 ) -> impl Iterator<Item = (DefId, DefId, Option<SimplifiedType>)> + '_ {
516 self.get_crate_data(cnum).get_trait_impls()
519 /// Decodes all inherent impls in the crate (for rustdoc).
520 pub fn inherent_impls_in_crate_untracked(
523 ) -> impl Iterator<Item = (DefId, DefId)> + '_ {
524 self.get_crate_data(cnum).get_inherent_impls()
527 /// Decodes all incoherent inherent impls in the crate (for rustdoc).
528 pub fn incoherent_impls_in_crate_untracked(
531 ) -> impl Iterator<Item = DefId> + '_ {
532 self.get_crate_data(cnum).get_all_incoherent_impls()
536 impl CrateStore for CStore {
537 fn as_any(&self) -> &dyn Any {
541 fn crate_name(&self, cnum: CrateNum) -> Symbol {
542 self.get_crate_data(cnum).root.name
545 fn stable_crate_id(&self, cnum: CrateNum) -> StableCrateId {
546 self.get_crate_data(cnum).root.stable_crate_id
549 fn stable_crate_id_to_crate_num(&self, stable_crate_id: StableCrateId) -> CrateNum {
550 self.stable_crate_ids[&stable_crate_id]
553 /// Returns the `DefKey` for a given `DefId`. This indicates the
554 /// parent `DefId` as well as some idea of what kind of data the
555 /// `DefId` refers to.
556 fn def_key(&self, def: DefId) -> DefKey {
557 self.get_crate_data(def.krate).def_key(def.index)
560 fn def_path(&self, def: DefId) -> DefPath {
561 self.get_crate_data(def.krate).def_path(def.index)
564 fn def_path_hash(&self, def: DefId) -> DefPathHash {
565 self.get_crate_data(def.krate).def_path_hash(def.index)
568 fn def_path_hash_to_def_id(&self, cnum: CrateNum, hash: DefPathHash) -> DefId {
569 let def_index = self.get_crate_data(cnum).def_path_hash_to_def_index(hash);
570 DefId { krate: cnum, index: def_index }
573 fn expn_hash_to_expn_id(
580 self.get_crate_data(cnum).expn_hash_to_expn_id(sess, index_guess, hash)
583 fn import_source_files(&self, sess: &Session, cnum: CrateNum) {
584 self.get_crate_data(cnum).imported_source_files(sess);