]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs
cd3a1d72d41d24d8194adfa14ae6267420f50699
[rust.git] / compiler / rustc_metadata / src / rmeta / decoder / cstore_impl.rs
1 use super::LazyQueryDecodable;
2 use crate::creader::{CStore, LoadedMacro};
3 use crate::foreign_modules;
4 use crate::native_libs;
5
6 use rustc_ast as ast;
7 use rustc_hir::def::{CtorKind, DefKind, Res};
8 use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, CRATE_DEF_INDEX, 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};
21
22 use rustc_data_structures::sync::Lrc;
23 use smallvec::SmallVec;
24 use std::any::Any;
25
26 macro_rules! provide_one {
27     (<$lt:tt> $tcx:ident, $def_id:ident, $other:ident, $cdata:ident, $name:ident => { table }) => {
28         provide_one! {
29             <$lt> $tcx, $def_id, $other, $cdata, $name => {
30                 $cdata.root.tables.$name.get($cdata, $def_id.index).decode_query(
31                     $cdata,
32                     $tcx,
33                     || panic!("{:?} does not have a {:?}", $def_id, stringify!($name)),
34                 )
35             }
36         }
37     };
38     (<$lt:tt> $tcx:ident, $def_id:ident, $other:ident, $cdata:ident, $name:ident => $compute:block) => {
39         fn $name<$lt>(
40             $tcx: TyCtxt<$lt>,
41             def_id_arg: ty::query::query_keys::$name<$lt>,
42         ) -> ty::query::query_values::$name<$lt> {
43             let _prof_timer =
44                 $tcx.prof.generic_activity(concat!("metadata_decode_entry_", stringify!($name)));
45
46             #[allow(unused_variables)]
47             let ($def_id, $other) = def_id_arg.into_args();
48             assert!(!$def_id.is_local());
49
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);
56             }
57
58             let $cdata = CStore::from_tcx($tcx).get_crate_data($def_id.krate);
59
60             $compute
61         }
62     };
63 }
64
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) {
69             $(provide_one! {
70                 <$lt> $tcx, $def_id, $other, $cdata, $name => { $($compute)* }
71             })*
72
73             *providers = ExternProviders {
74                 $($name,)*
75                 ..*providers
76             };
77         }
78     }
79 }
80
81 // small trait to work around different signature queries all being defined via
82 // the macro above.
83 trait IntoArgs {
84     type Other;
85     fn into_args(self) -> (DefId, Self::Other);
86 }
87
88 impl IntoArgs for DefId {
89     type Other = ();
90     fn into_args(self) -> (DefId, ()) {
91         (self, ())
92     }
93 }
94
95 impl IntoArgs for CrateNum {
96     type Other = ();
97     fn into_args(self) -> (DefId, ()) {
98         (self.as_def_id(), ())
99     }
100 }
101
102 impl IntoArgs for (CrateNum, DefId) {
103     type Other = DefId;
104     fn into_args(self) -> (DefId, DefId) {
105         (self.0.as_def_id(), self.1)
106     }
107 }
108
109 impl<'tcx> IntoArgs for ty::InstanceDef<'tcx> {
110     type Other = ();
111     fn into_args(self) -> (DefId, ()) {
112         (self.def_id(), ())
113     }
114 }
115
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)
120     }
121 }
122
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 }
129     type_of => { table }
130     variances_of => { table }
131     fn_sig => { 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 }
157
158     adt_def => { cdata.get_adt_def(def_id.index, tcx) }
159     adt_destructor => {
160         let _ = cdata;
161         tcx.calculate_dtor(def_id, |_,_| Ok(()))
162     }
163     associated_item_def_ids => { cdata.get_associated_item_def_ids(tcx, def_id.index) }
164     associated_item => { cdata.get_associated_item(def_id.index) }
165     inherent_impls => { cdata.get_inherent_implementations_for_type(tcx, def_id.index) }
166     is_foreign_item => { cdata.is_foreign_item(def_id.index) }
167     item_attrs => { tcx.arena.alloc_from_iter(cdata.get_item_attrs(def_id.index, tcx.sess)) }
168     trait_of_item => { cdata.get_trait_of_item(def_id.index) }
169     is_mir_available => { cdata.is_item_mir_available(def_id.index) }
170     is_ctfe_mir_available => { cdata.is_ctfe_mir_available(def_id.index) }
171
172     dylib_dependency_formats => { cdata.get_dylib_dependency_formats(tcx) }
173     is_private_dep => { cdata.private_dep }
174     is_panic_runtime => { cdata.root.panic_runtime }
175     is_compiler_builtins => { cdata.root.compiler_builtins }
176     has_global_allocator => { cdata.root.has_global_allocator }
177     has_panic_handler => { cdata.root.has_panic_handler }
178     is_profiler_runtime => { cdata.root.profiler_runtime }
179     panic_strategy => { cdata.root.panic_strategy }
180     panic_in_drop_strategy => { cdata.root.panic_in_drop_strategy }
181     extern_crate => {
182         let r = *cdata.extern_crate.lock();
183         r.map(|c| &*tcx.arena.alloc(c))
184     }
185     is_no_builtins => { cdata.root.no_builtins }
186     symbol_mangling_version => { cdata.root.symbol_mangling_version }
187     reachable_non_generics => {
188         let reachable_non_generics = tcx
189             .exported_symbols(cdata.cnum)
190             .iter()
191             .filter_map(|&(exported_symbol, export_level)| {
192                 if let ExportedSymbol::NonGeneric(def_id) = exported_symbol {
193                     Some((def_id, export_level))
194                 } else {
195                     None
196                 }
197             })
198             .collect();
199
200         reachable_non_generics
201     }
202     native_libraries => { cdata.get_native_libraries(tcx.sess).collect() }
203     foreign_modules => { cdata.get_foreign_modules(tcx.sess).map(|m| (m.def_id, m)).collect() }
204     crate_hash => { cdata.root.hash }
205     crate_host_hash => { cdata.host_hash }
206     crate_name => { cdata.root.name }
207
208     extra_filename => { cdata.root.extra_filename.clone() }
209
210     traits_in_crate => { tcx.arena.alloc_from_iter(cdata.get_traits()) }
211     implementations_of_trait => { cdata.get_implementations_of_trait(tcx, other) }
212     crate_incoherent_impls => { cdata.get_incoherent_impls(tcx, other) }
213
214     dep_kind => {
215         let r = *cdata.dep_kind.lock();
216         r
217     }
218     module_children => {
219         let mut result = SmallVec::<[_; 8]>::new();
220         cdata.for_each_module_child(def_id.index, |child| result.push(child), tcx.sess);
221         tcx.arena.alloc_slice(&result)
222     }
223     defined_lib_features => { cdata.get_lib_features(tcx) }
224     defined_lang_items => { cdata.get_lang_items(tcx) }
225     diagnostic_items => { cdata.get_diagnostic_items() }
226     missing_lang_items => { cdata.get_missing_lang_items(tcx) }
227
228     missing_extern_crate_item => {
229         let r = matches!(*cdata.extern_crate.borrow(), Some(extern_crate) if !extern_crate.is_direct());
230         r
231     }
232
233     used_crate_source => { Lrc::clone(&cdata.source) }
234
235     exported_symbols => {
236         let syms = cdata.exported_symbols(tcx);
237
238         // FIXME rust-lang/rust#64319, rust-lang/rust#64872: We want
239         // to block export of generics from dylibs, but we must fix
240         // rust-lang/rust#65890 before we can do that robustly.
241
242         syms
243     }
244
245     crate_extern_paths => { cdata.source().paths().cloned().collect() }
246     expn_that_defined => { cdata.get_expn_that_defined(def_id.index, tcx.sess) }
247 }
248
249 pub(in crate::rmeta) fn provide(providers: &mut Providers) {
250     // FIXME(#44234) - almost all of these queries have no sub-queries and
251     // therefore no actual inputs, they're just reading tables calculated in
252     // resolve! Does this work? Unsure! That's what the issue is about
253     *providers = Providers {
254         allocator_kind: |tcx, ()| CStore::from_tcx(tcx).allocator_kind(),
255         is_dllimport_foreign_item: |tcx, id| match tcx.native_library_kind(id) {
256             Some(
257                 NativeLibKind::Dylib { .. } | NativeLibKind::RawDylib | NativeLibKind::Unspecified,
258             ) => true,
259             _ => false,
260         },
261         is_statically_included_foreign_item: |tcx, id| {
262             matches!(tcx.native_library_kind(id), Some(NativeLibKind::Static { .. }))
263         },
264         is_private_dep: |_tcx, cnum| {
265             assert_eq!(cnum, LOCAL_CRATE);
266             false
267         },
268         native_library_kind: |tcx, id| {
269             tcx.native_libraries(id.krate)
270                 .iter()
271                 .filter(|lib| native_libs::relevant_lib(&tcx.sess, lib))
272                 .find(|lib| {
273                     let Some(fm_id) = lib.foreign_module else {
274                         return false;
275                     };
276                     let map = tcx.foreign_modules(id.krate);
277                     map.get(&fm_id)
278                         .expect("failed to find foreign module")
279                         .foreign_items
280                         .contains(&id)
281                 })
282                 .map(|l| l.kind)
283         },
284         native_libraries: |tcx, cnum| {
285             assert_eq!(cnum, LOCAL_CRATE);
286             native_libs::collect(tcx)
287         },
288         foreign_modules: |tcx, cnum| {
289             assert_eq!(cnum, LOCAL_CRATE);
290             foreign_modules::collect(tcx).into_iter().map(|m| (m.def_id, m)).collect()
291         },
292
293         // Returns a map from a sufficiently visible external item (i.e., an
294         // external item that is visible from at least one local module) to a
295         // sufficiently visible parent (considering modules that re-export the
296         // external item to be parents).
297         visible_parent_map: |tcx, ()| {
298             use std::collections::hash_map::Entry;
299             use std::collections::vec_deque::VecDeque;
300
301             let mut visible_parent_map: DefIdMap<DefId> = Default::default();
302             // This is a secondary visible_parent_map, storing the DefId of parents that re-export
303             // the child as `_`. Since we prefer parents that don't do this, merge this map at the
304             // end, only if we're missing any keys from the former.
305             let mut fallback_map: DefIdMap<DefId> = Default::default();
306
307             // Issue 46112: We want the map to prefer the shortest
308             // paths when reporting the path to an item. Therefore we
309             // build up the map via a breadth-first search (BFS),
310             // which naturally yields minimal-length paths.
311             //
312             // Note that it needs to be a BFS over the whole forest of
313             // crates, not just each individual crate; otherwise you
314             // only get paths that are locally minimal with respect to
315             // whatever crate we happened to encounter first in this
316             // traversal, but not globally minimal across all crates.
317             let bfs_queue = &mut VecDeque::new();
318
319             for &cnum in tcx.crates(()) {
320                 // Ignore crates without a corresponding local `extern crate` item.
321                 if tcx.missing_extern_crate_item(cnum) {
322                     continue;
323                 }
324
325                 bfs_queue.push_back(DefId { krate: cnum, index: CRATE_DEF_INDEX });
326             }
327
328             let mut add_child = |bfs_queue: &mut VecDeque<_>, child: &ModChild, parent: DefId| {
329                 if !child.vis.is_public() {
330                     return;
331                 }
332
333                 if let Some(def_id) = child.res.opt_def_id() {
334                     if child.ident.name == kw::Underscore {
335                         fallback_map.insert(def_id, parent);
336                         return;
337                     }
338
339                     match visible_parent_map.entry(def_id) {
340                         Entry::Occupied(mut entry) => {
341                             // If `child` is defined in crate `cnum`, ensure
342                             // that it is mapped to a parent in `cnum`.
343                             if def_id.is_local() && entry.get().is_local() {
344                                 entry.insert(parent);
345                             }
346                         }
347                         Entry::Vacant(entry) => {
348                             entry.insert(parent);
349                             if matches!(
350                                 child.res,
351                                 Res::Def(DefKind::Mod | DefKind::Enum | DefKind::Trait, _)
352                             ) {
353                                 bfs_queue.push_back(def_id);
354                             }
355                         }
356                     }
357                 }
358             };
359
360             while let Some(def) = bfs_queue.pop_front() {
361                 for child in tcx.module_children(def).iter() {
362                     add_child(bfs_queue, child, def);
363                 }
364             }
365
366             // Fill in any missing entries with the (less preferable) path ending in `::_`.
367             // We still use this path in a diagnostic that suggests importing `::*`.
368             for (child, parent) in fallback_map {
369                 visible_parent_map.entry(child).or_insert(parent);
370             }
371
372             visible_parent_map
373         },
374
375         dependency_formats: |tcx, ()| Lrc::new(crate::dependency_format::calculate(tcx)),
376         has_global_allocator: |tcx, cnum| {
377             assert_eq!(cnum, LOCAL_CRATE);
378             CStore::from_tcx(tcx).has_global_allocator()
379         },
380         postorder_cnums: |tcx, ()| {
381             tcx.arena
382                 .alloc_slice(&CStore::from_tcx(tcx).crate_dependencies_in_postorder(LOCAL_CRATE))
383         },
384         crates: |tcx, ()| tcx.arena.alloc_from_iter(CStore::from_tcx(tcx).crates_untracked()),
385         ..*providers
386     };
387 }
388
389 impl CStore {
390     pub fn struct_field_names_untracked<'a>(
391         &'a self,
392         def: DefId,
393         sess: &'a Session,
394     ) -> impl Iterator<Item = Spanned<Symbol>> + 'a {
395         self.get_crate_data(def.krate).get_struct_field_names(def.index, sess)
396     }
397
398     pub fn struct_field_visibilities_untracked(
399         &self,
400         def: DefId,
401     ) -> impl Iterator<Item = Visibility> + '_ {
402         self.get_crate_data(def.krate).get_struct_field_visibilities(def.index)
403     }
404
405     pub fn ctor_def_id_and_kind_untracked(&self, def: DefId) -> Option<(DefId, CtorKind)> {
406         self.get_crate_data(def.krate).get_ctor_def_id_and_kind(def.index)
407     }
408
409     pub fn visibility_untracked(&self, def: DefId) -> Visibility {
410         self.get_crate_data(def.krate).get_visibility(def.index)
411     }
412
413     pub fn module_children_untracked(&self, def_id: DefId, sess: &Session) -> Vec<ModChild> {
414         let mut result = vec![];
415         self.get_crate_data(def_id.krate).for_each_module_child(
416             def_id.index,
417             |child| result.push(child),
418             sess,
419         );
420         result
421     }
422
423     pub fn load_macro_untracked(&self, id: DefId, sess: &Session) -> LoadedMacro {
424         let _prof_timer = sess.prof.generic_activity("metadata_load_macro");
425
426         let data = self.get_crate_data(id.krate);
427         if data.root.is_proc_macro_crate() {
428             return LoadedMacro::ProcMacro(data.load_proc_macro(id.index, sess));
429         }
430
431         let span = data.get_span(id.index, sess);
432
433         LoadedMacro::MacroDef(
434             ast::Item {
435                 ident: data.item_ident(id.index, sess),
436                 id: ast::DUMMY_NODE_ID,
437                 span,
438                 attrs: data.get_item_attrs(id.index, sess).collect(),
439                 kind: ast::ItemKind::MacroDef(data.get_macro(id.index, sess)),
440                 vis: ast::Visibility {
441                     span: span.shrink_to_lo(),
442                     kind: ast::VisibilityKind::Inherited,
443                     tokens: None,
444                 },
445                 tokens: None,
446             },
447             data.root.edition,
448         )
449     }
450
451     pub fn fn_has_self_parameter_untracked(&self, def: DefId) -> bool {
452         self.get_crate_data(def.krate).get_fn_has_self_parameter(def.index)
453     }
454
455     pub fn crate_source_untracked(&self, cnum: CrateNum) -> Lrc<CrateSource> {
456         self.get_crate_data(cnum).source.clone()
457     }
458
459     pub fn get_span_untracked(&self, def_id: DefId, sess: &Session) -> Span {
460         self.get_crate_data(def_id.krate).get_span(def_id.index, sess)
461     }
462
463     pub fn def_kind(&self, def: DefId) -> DefKind {
464         self.get_crate_data(def.krate).def_kind(def.index)
465     }
466
467     pub fn crates_untracked(&self) -> impl Iterator<Item = CrateNum> + '_ {
468         self.iter_crate_data().map(|(cnum, _)| cnum)
469     }
470
471     pub fn item_generics_num_lifetimes(&self, def_id: DefId, sess: &Session) -> usize {
472         self.get_crate_data(def_id.krate).get_generics(def_id.index, sess).own_counts().lifetimes
473     }
474
475     pub fn module_expansion_untracked(&self, def_id: DefId, sess: &Session) -> ExpnId {
476         self.get_crate_data(def_id.krate).module_expansion(def_id.index, sess)
477     }
478
479     /// Only public-facing way to traverse all the definitions in a non-local crate.
480     /// Critically useful for this third-party project: <https://github.com/hacspec/hacspec>.
481     /// See <https://github.com/rust-lang/rust/pull/85889> for context.
482     pub fn num_def_ids_untracked(&self, cnum: CrateNum) -> usize {
483         self.get_crate_data(cnum).num_def_ids()
484     }
485
486     pub fn item_attrs_untracked<'a>(
487         &'a self,
488         def_id: DefId,
489         sess: &'a Session,
490     ) -> impl Iterator<Item = ast::Attribute> + 'a {
491         self.get_crate_data(def_id.krate).get_item_attrs(def_id.index, sess)
492     }
493
494     pub fn get_proc_macro_quoted_span_untracked(
495         &self,
496         cnum: CrateNum,
497         id: usize,
498         sess: &Session,
499     ) -> Span {
500         self.get_crate_data(cnum).get_proc_macro_quoted_span(id, sess)
501     }
502
503     /// Decodes all traits in the crate (for rustdoc).
504     pub fn traits_in_crate_untracked(&self, cnum: CrateNum) -> impl Iterator<Item = DefId> + '_ {
505         self.get_crate_data(cnum).get_traits()
506     }
507
508     /// Decodes all trait impls in the crate (for rustdoc).
509     pub fn trait_impls_in_crate_untracked(
510         &self,
511         cnum: CrateNum,
512     ) -> impl Iterator<Item = (DefId, DefId, Option<SimplifiedType>)> + '_ {
513         self.get_crate_data(cnum).get_trait_impls()
514     }
515
516     /// Decodes all inherent impls in the crate (for rustdoc).
517     pub fn inherent_impls_in_crate_untracked(
518         &self,
519         cnum: CrateNum,
520     ) -> impl Iterator<Item = (DefId, DefId)> + '_ {
521         self.get_crate_data(cnum).get_inherent_impls()
522     }
523
524     /// Decodes all incoherent inherent impls in the crate (for rustdoc).
525     pub fn incoherent_impls_in_crate_untracked(
526         &self,
527         cnum: CrateNum,
528     ) -> impl Iterator<Item = DefId> + '_ {
529         self.get_crate_data(cnum).get_all_incoherent_impls()
530     }
531 }
532
533 impl CrateStore for CStore {
534     fn as_any(&self) -> &dyn Any {
535         self
536     }
537
538     fn crate_name(&self, cnum: CrateNum) -> Symbol {
539         self.get_crate_data(cnum).root.name
540     }
541
542     fn stable_crate_id(&self, cnum: CrateNum) -> StableCrateId {
543         self.get_crate_data(cnum).root.stable_crate_id
544     }
545
546     fn stable_crate_id_to_crate_num(&self, stable_crate_id: StableCrateId) -> CrateNum {
547         self.stable_crate_ids[&stable_crate_id]
548     }
549
550     /// Returns the `DefKey` for a given `DefId`. This indicates the
551     /// parent `DefId` as well as some idea of what kind of data the
552     /// `DefId` refers to.
553     fn def_key(&self, def: DefId) -> DefKey {
554         self.get_crate_data(def.krate).def_key(def.index)
555     }
556
557     fn def_path(&self, def: DefId) -> DefPath {
558         self.get_crate_data(def.krate).def_path(def.index)
559     }
560
561     fn def_path_hash(&self, def: DefId) -> DefPathHash {
562         self.get_crate_data(def.krate).def_path_hash(def.index)
563     }
564
565     fn def_path_hash_to_def_id(&self, cnum: CrateNum, hash: DefPathHash) -> DefId {
566         let def_index = self.get_crate_data(cnum).def_path_hash_to_def_index(hash);
567         DefId { krate: cnum, index: def_index }
568     }
569
570     fn expn_hash_to_expn_id(
571         &self,
572         sess: &Session,
573         cnum: CrateNum,
574         index_guess: u32,
575         hash: ExpnHash,
576     ) -> ExpnId {
577         self.get_crate_data(cnum).expn_hash_to_expn_id(sess, index_guess, hash)
578     }
579
580     fn import_source_files(&self, sess: &Session, cnum: CrateNum) {
581         self.get_crate_data(cnum).imported_source_files(sess);
582     }
583 }