]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs
6a8f1dec0c5d574b1796172b2cb84684d455ecd4
[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, 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 => {
164         tcx.arena.alloc_from_iter(cdata.get_associated_item_def_ids(def_id.index, tcx.sess))
165     }
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) }
173
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 }
183     extern_crate => {
184         let r = *cdata.extern_crate.lock();
185         r.map(|c| &*tcx.arena.alloc(c))
186     }
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)
192             .iter()
193             .filter_map(|&(exported_symbol, export_level)| {
194                 if let ExportedSymbol::NonGeneric(def_id) = exported_symbol {
195                     Some((def_id, export_level))
196                 } else {
197                     None
198                 }
199             })
200             .collect();
201
202         reachable_non_generics
203     }
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 }
209
210     extra_filename => { cdata.root.extra_filename.clone() }
211
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) }
215
216     dep_kind => {
217         let r = *cdata.dep_kind.lock();
218         r
219     }
220     module_children => {
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)
224     }
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) }
229
230     missing_extern_crate_item => {
231         let r = matches!(*cdata.extern_crate.borrow(), Some(extern_crate) if !extern_crate.is_direct());
232         r
233     }
234
235     used_crate_source => { Lrc::clone(&cdata.source) }
236
237     exported_symbols => {
238         let syms = cdata.exported_symbols(tcx);
239
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.
243
244         syms
245     }
246
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) }
250 }
251
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) {
259             Some(
260                 NativeLibKind::Dylib { .. } | NativeLibKind::RawDylib | NativeLibKind::Unspecified,
261             ) => true,
262             _ => false,
263         },
264         is_statically_included_foreign_item: |tcx, id| {
265             matches!(tcx.native_library_kind(id), Some(NativeLibKind::Static { .. }))
266         },
267         is_private_dep: |_tcx, cnum| {
268             assert_eq!(cnum, LOCAL_CRATE);
269             false
270         },
271         native_library_kind: |tcx, id| {
272             tcx.native_libraries(id.krate)
273                 .iter()
274                 .filter(|lib| native_libs::relevant_lib(&tcx.sess, lib))
275                 .find(|lib| {
276                     let Some(fm_id) = lib.foreign_module else {
277                         return false;
278                     };
279                     let map = tcx.foreign_modules(id.krate);
280                     map.get(&fm_id)
281                         .expect("failed to find foreign module")
282                         .foreign_items
283                         .contains(&id)
284                 })
285                 .map(|l| l.kind)
286         },
287         native_libraries: |tcx, cnum| {
288             assert_eq!(cnum, LOCAL_CRATE);
289             native_libs::collect(tcx)
290         },
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()
294         },
295
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;
303
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();
309
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.
314             //
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();
321
322             for &cnum in tcx.crates(()) {
323                 // Ignore crates without a corresponding local `extern crate` item.
324                 if tcx.missing_extern_crate_item(cnum) {
325                     continue;
326                 }
327
328                 bfs_queue.push_back(cnum.as_def_id());
329             }
330
331             let mut add_child = |bfs_queue: &mut VecDeque<_>, child: &ModChild, parent: DefId| {
332                 if !child.vis.is_public() {
333                     return;
334                 }
335
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);
339                         return;
340                     }
341
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);
348                             }
349                         }
350                         Entry::Vacant(entry) => {
351                             entry.insert(parent);
352                             if matches!(
353                                 child.res,
354                                 Res::Def(DefKind::Mod | DefKind::Enum | DefKind::Trait, _)
355                             ) {
356                                 bfs_queue.push_back(def_id);
357                             }
358                         }
359                     }
360                 }
361             };
362
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);
366                 }
367             }
368
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);
373             }
374
375             visible_parent_map
376         },
377
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()
382         },
383         postorder_cnums: |tcx, ()| {
384             tcx.arena
385                 .alloc_slice(&CStore::from_tcx(tcx).crate_dependencies_in_postorder(LOCAL_CRATE))
386         },
387         crates: |tcx, ()| tcx.arena.alloc_from_iter(CStore::from_tcx(tcx).crates_untracked()),
388         ..*providers
389     };
390 }
391
392 impl CStore {
393     pub fn struct_field_names_untracked<'a>(
394         &'a self,
395         def: DefId,
396         sess: &'a Session,
397     ) -> impl Iterator<Item = Spanned<Symbol>> + 'a {
398         self.get_crate_data(def.krate).get_struct_field_names(def.index, sess)
399     }
400
401     pub fn struct_field_visibilities_untracked(
402         &self,
403         def: DefId,
404     ) -> impl Iterator<Item = Visibility> + '_ {
405         self.get_crate_data(def.krate).get_struct_field_visibilities(def.index)
406     }
407
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)
410     }
411
412     pub fn visibility_untracked(&self, def: DefId) -> Visibility {
413         self.get_crate_data(def.krate).get_visibility(def.index)
414     }
415
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(
419             def_id.index,
420             |child| result.push(child),
421             sess,
422         );
423         result
424     }
425
426     pub fn load_macro_untracked(&self, id: DefId, sess: &Session) -> LoadedMacro {
427         let _prof_timer = sess.prof.generic_activity("metadata_load_macro");
428
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));
432         }
433
434         let span = data.get_span(id.index, sess);
435
436         LoadedMacro::MacroDef(
437             ast::Item {
438                 ident: data.item_ident(id.index, sess),
439                 id: ast::DUMMY_NODE_ID,
440                 span,
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,
446                     tokens: None,
447                 },
448                 tokens: None,
449             },
450             data.root.edition,
451         )
452     }
453
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)
456     }
457
458     pub fn crate_source_untracked(&self, cnum: CrateNum) -> Lrc<CrateSource> {
459         self.get_crate_data(cnum).source.clone()
460     }
461
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)
464     }
465
466     pub fn def_kind(&self, def: DefId) -> DefKind {
467         self.get_crate_data(def.krate).def_kind(def.index)
468     }
469
470     pub fn crates_untracked(&self) -> impl Iterator<Item = CrateNum> + '_ {
471         self.iter_crate_data().map(|(cnum, _)| cnum)
472     }
473
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
476     }
477
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)
480     }
481
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()
487     }
488
489     pub fn item_attrs_untracked<'a>(
490         &'a self,
491         def_id: DefId,
492         sess: &'a Session,
493     ) -> impl Iterator<Item = ast::Attribute> + 'a {
494         self.get_crate_data(def_id.krate).get_item_attrs(def_id.index, sess)
495     }
496
497     pub fn get_proc_macro_quoted_span_untracked(
498         &self,
499         cnum: CrateNum,
500         id: usize,
501         sess: &Session,
502     ) -> Span {
503         self.get_crate_data(cnum).get_proc_macro_quoted_span(id, sess)
504     }
505
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()
509     }
510
511     /// Decodes all trait impls in the crate (for rustdoc).
512     pub fn trait_impls_in_crate_untracked(
513         &self,
514         cnum: CrateNum,
515     ) -> impl Iterator<Item = (DefId, DefId, Option<SimplifiedType>)> + '_ {
516         self.get_crate_data(cnum).get_trait_impls()
517     }
518
519     /// Decodes all inherent impls in the crate (for rustdoc).
520     pub fn inherent_impls_in_crate_untracked(
521         &self,
522         cnum: CrateNum,
523     ) -> impl Iterator<Item = (DefId, DefId)> + '_ {
524         self.get_crate_data(cnum).get_inherent_impls()
525     }
526
527     /// Decodes all incoherent inherent impls in the crate (for rustdoc).
528     pub fn incoherent_impls_in_crate_untracked(
529         &self,
530         cnum: CrateNum,
531     ) -> impl Iterator<Item = DefId> + '_ {
532         self.get_crate_data(cnum).get_all_incoherent_impls()
533     }
534 }
535
536 impl CrateStore for CStore {
537     fn as_any(&self) -> &dyn Any {
538         self
539     }
540
541     fn crate_name(&self, cnum: CrateNum) -> Symbol {
542         self.get_crate_data(cnum).root.name
543     }
544
545     fn stable_crate_id(&self, cnum: CrateNum) -> StableCrateId {
546         self.get_crate_data(cnum).root.stable_crate_id
547     }
548
549     fn stable_crate_id_to_crate_num(&self, stable_crate_id: StableCrateId) -> CrateNum {
550         self.stable_crate_ids[&stable_crate_id]
551     }
552
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)
558     }
559
560     fn def_path(&self, def: DefId) -> DefPath {
561         self.get_crate_data(def.krate).def_path(def.index)
562     }
563
564     fn def_path_hash(&self, def: DefId) -> DefPathHash {
565         self.get_crate_data(def.krate).def_path_hash(def.index)
566     }
567
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 }
571     }
572
573     fn expn_hash_to_expn_id(
574         &self,
575         sess: &Session,
576         cnum: CrateNum,
577         index_guess: u32,
578         hash: ExpnHash,
579     ) -> ExpnId {
580         self.get_crate_data(cnum).expn_hash_to_expn_id(sess, index_guess, hash)
581     }
582
583     fn import_source_files(&self, sess: &Session, cnum: CrateNum) {
584         self.get_crate_data(cnum).imported_source_files(sess);
585     }
586 }