]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs
d24e1f5d4dd06dec072b287458e78d53f4f2fad4
[rust.git] / compiler / rustc_metadata / src / rmeta / decoder / cstore_impl.rs
1 use crate::creader::{CStore, LoadedMacro};
2 use crate::foreign_modules;
3 use crate::link_args;
4 use crate::native_libs;
5 use crate::rmeta::{self, encoder};
6
7 use rustc_ast as ast;
8 use rustc_ast::expand::allocator::AllocatorKind;
9 use rustc_data_structures::stable_map::FxHashMap;
10 use rustc_data_structures::svh::Svh;
11 use rustc_hir as hir;
12 use rustc_hir::def::DefKind;
13 use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, CRATE_DEF_INDEX, LOCAL_CRATE};
14 use rustc_hir::definitions::{DefKey, DefPath, DefPathHash};
15 use rustc_middle::hir::exports::Export;
16 use rustc_middle::middle::cstore::ForeignModule;
17 use rustc_middle::middle::cstore::{CrateSource, CrateStore, EncodedMetadata};
18 use rustc_middle::middle::exported_symbols::ExportedSymbol;
19 use rustc_middle::middle::stability::DeprecationEntry;
20 use rustc_middle::ty::query::Providers;
21 use rustc_middle::ty::{self, TyCtxt};
22 use rustc_session::utils::NativeLibKind;
23 use rustc_session::{CrateDisambiguator, Session};
24 use rustc_span::source_map::{Span, Spanned};
25 use rustc_span::symbol::Symbol;
26
27 use rustc_data_structures::sync::Lrc;
28 use rustc_span::ExpnId;
29 use smallvec::SmallVec;
30 use std::any::Any;
31
32 macro_rules! provide {
33     (<$lt:tt> $tcx:ident, $def_id:ident, $other:ident, $cdata:ident,
34       $($name:ident => $compute:block)*) => {
35         pub fn provide_extern(providers: &mut Providers) {
36             $(fn $name<$lt>(
37                 $tcx: TyCtxt<$lt>,
38                 def_id_arg: ty::query::query_keys::$name<$lt>,
39             ) -> ty::query::query_values::$name<$lt> {
40                 let _prof_timer =
41                     $tcx.prof.generic_activity(concat!("metadata_decode_entry_", stringify!($name)));
42
43                 #[allow(unused_variables)]
44                 let ($def_id, $other) = def_id_arg.into_args();
45                 assert!(!$def_id.is_local());
46
47                 let $cdata = CStore::from_tcx($tcx).get_crate_data($def_id.krate);
48
49                 if $tcx.dep_graph.is_fully_enabled() {
50                     let crate_dep_node_index = $cdata.get_crate_dep_node_index($tcx);
51                     $tcx.dep_graph.read_index(crate_dep_node_index);
52                 }
53
54                 $compute
55             })*
56
57             *providers = Providers {
58                 $($name,)*
59                 ..*providers
60             };
61         }
62     }
63 }
64
65 // small trait to work around different signature queries all being defined via
66 // the macro above.
67 trait IntoArgs {
68     fn into_args(self) -> (DefId, DefId);
69 }
70
71 impl IntoArgs for DefId {
72     fn into_args(self) -> (DefId, DefId) {
73         (self, self)
74     }
75 }
76
77 impl IntoArgs for CrateNum {
78     fn into_args(self) -> (DefId, DefId) {
79         (self.as_def_id(), self.as_def_id())
80     }
81 }
82
83 impl IntoArgs for (CrateNum, DefId) {
84     fn into_args(self) -> (DefId, DefId) {
85         (self.0.as_def_id(), self.1)
86     }
87 }
88
89 provide! { <'tcx> tcx, def_id, other, cdata,
90     type_of => { cdata.get_type(def_id.index, tcx) }
91     generics_of => { cdata.get_generics(def_id.index, tcx.sess) }
92     explicit_predicates_of => { cdata.get_explicit_predicates(def_id.index, tcx) }
93     inferred_outlives_of => { cdata.get_inferred_outlives(def_id.index, tcx) }
94     super_predicates_of => { cdata.get_super_predicates(def_id.index, tcx) }
95     explicit_item_bounds => { cdata.get_explicit_item_bounds(def_id.index, tcx) }
96     trait_def => { cdata.get_trait_def(def_id.index, tcx.sess) }
97     adt_def => { cdata.get_adt_def(def_id.index, tcx) }
98     adt_destructor => {
99         let _ = cdata;
100         tcx.calculate_dtor(def_id, |_,_| Ok(()))
101     }
102     variances_of => { tcx.arena.alloc_from_iter(cdata.get_item_variances(def_id.index)) }
103     associated_item_def_ids => {
104         let mut result = SmallVec::<[_; 8]>::new();
105         cdata.each_child_of_item(def_id.index,
106           |child| result.push(child.res.def_id()), tcx.sess);
107         tcx.arena.alloc_slice(&result)
108     }
109     associated_item => { cdata.get_associated_item(def_id.index, tcx.sess) }
110     impl_trait_ref => { cdata.get_impl_trait(def_id.index, tcx) }
111     impl_polarity => { cdata.get_impl_polarity(def_id.index) }
112     coerce_unsized_info => {
113         cdata.get_coerce_unsized_info(def_id.index).unwrap_or_else(|| {
114             bug!("coerce_unsized_info: `{:?}` is missing its info", def_id);
115         })
116     }
117     optimized_mir => { tcx.arena.alloc(cdata.get_optimized_mir(tcx, def_id.index)) }
118     promoted_mir => { tcx.arena.alloc(cdata.get_promoted_mir(tcx, def_id.index)) }
119     mir_abstract_const => { cdata.get_mir_abstract_const(tcx, def_id.index) }
120     unused_generic_params => { cdata.get_unused_generic_params(def_id.index) }
121     mir_const_qualif => { cdata.mir_const_qualif(def_id.index) }
122     fn_sig => { cdata.fn_sig(def_id.index, tcx) }
123     inherent_impls => { cdata.get_inherent_implementations_for_type(tcx, def_id.index) }
124     is_const_fn_raw => { cdata.is_const_fn_raw(def_id.index) }
125     asyncness => { cdata.asyncness(def_id.index) }
126     is_foreign_item => { cdata.is_foreign_item(def_id.index) }
127     static_mutability => { cdata.static_mutability(def_id.index) }
128     generator_kind => { cdata.generator_kind(def_id.index) }
129     def_kind => { cdata.def_kind(def_id.index) }
130     def_span => { cdata.get_span(def_id.index, &tcx.sess) }
131     lookup_stability => {
132         cdata.get_stability(def_id.index).map(|s| tcx.intern_stability(s))
133     }
134     lookup_const_stability => {
135         cdata.get_const_stability(def_id.index).map(|s| tcx.intern_const_stability(s))
136     }
137     lookup_deprecation_entry => {
138         cdata.get_deprecation(def_id.index).map(DeprecationEntry::external)
139     }
140     item_attrs => { tcx.arena.alloc_from_iter(
141         cdata.get_item_attrs(def_id.index, tcx.sess)
142     ) }
143     fn_arg_names => { cdata.get_fn_param_names(tcx, def_id.index) }
144     rendered_const => { cdata.get_rendered_const(def_id.index) }
145     impl_parent => { cdata.get_parent_impl(def_id.index) }
146     trait_of_item => { cdata.get_trait_of_item(def_id.index) }
147     is_mir_available => { cdata.is_item_mir_available(def_id.index) }
148
149     dylib_dependency_formats => { cdata.get_dylib_dependency_formats(tcx) }
150     is_panic_runtime => { cdata.root.panic_runtime }
151     is_compiler_builtins => { cdata.root.compiler_builtins }
152     has_global_allocator => { cdata.root.has_global_allocator }
153     has_panic_handler => { cdata.root.has_panic_handler }
154     is_profiler_runtime => { cdata.root.profiler_runtime }
155     panic_strategy => { cdata.root.panic_strategy }
156     extern_crate => {
157         let r = *cdata.extern_crate.lock();
158         r.map(|c| &*tcx.arena.alloc(c))
159     }
160     is_no_builtins => { cdata.root.no_builtins }
161     symbol_mangling_version => { cdata.root.symbol_mangling_version }
162     impl_defaultness => { cdata.get_impl_defaultness(def_id.index) }
163     reachable_non_generics => {
164         let reachable_non_generics = tcx
165             .exported_symbols(cdata.cnum)
166             .iter()
167             .filter_map(|&(exported_symbol, export_level)| {
168                 if let ExportedSymbol::NonGeneric(def_id) = exported_symbol {
169                     Some((def_id, export_level))
170                 } else {
171                     None
172                 }
173             })
174             .collect();
175
176         reachable_non_generics
177     }
178     native_libraries => { Lrc::new(cdata.get_native_libraries(tcx.sess)) }
179     foreign_modules => { cdata.get_foreign_modules(tcx) }
180     plugin_registrar_fn => {
181         cdata.root.plugin_registrar_fn.map(|index| {
182             DefId { krate: def_id.krate, index }
183         })
184     }
185     proc_macro_decls_static => {
186         cdata.root.proc_macro_data.as_ref().map(|data| {
187             DefId {
188                 krate: def_id.krate,
189                 index: data.proc_macro_decls_static,
190             }
191         })
192     }
193     crate_disambiguator => { cdata.root.disambiguator }
194     crate_hash => { cdata.root.hash }
195     crate_host_hash => { cdata.host_hash }
196     original_crate_name => { cdata.root.name }
197
198     extra_filename => { cdata.root.extra_filename.clone() }
199
200     implementations_of_trait => {
201         cdata.get_implementations_for_trait(tcx, Some(other))
202     }
203
204     all_trait_implementations => {
205         cdata.get_implementations_for_trait(tcx, None)
206     }
207
208     visibility => { cdata.get_visibility(def_id.index) }
209     dep_kind => {
210         let r = *cdata.dep_kind.lock();
211         r
212     }
213     crate_name => { cdata.root.name }
214     item_children => {
215         let mut result = SmallVec::<[_; 8]>::new();
216         cdata.each_child_of_item(def_id.index, |child| result.push(child), tcx.sess);
217         tcx.arena.alloc_slice(&result)
218     }
219     defined_lib_features => { cdata.get_lib_features(tcx) }
220     defined_lang_items => { cdata.get_lang_items(tcx) }
221     diagnostic_items => { cdata.get_diagnostic_items() }
222     missing_lang_items => { cdata.get_missing_lang_items(tcx) }
223
224     missing_extern_crate_item => {
225         let r = matches!(*cdata.extern_crate.borrow(), Some(extern_crate) if !extern_crate.is_direct());
226         r
227     }
228
229     used_crate_source => { Lrc::new(cdata.source.clone()) }
230
231     exported_symbols => {
232         let syms = cdata.exported_symbols(tcx);
233
234         // FIXME rust-lang/rust#64319, rust-lang/rust#64872: We want
235         // to block export of generics from dylibs, but we must fix
236         // rust-lang/rust#65890 before we can do that robustly.
237
238         syms
239     }
240
241     crate_extern_paths => { cdata.source().paths().cloned().collect() }
242     expn_that_defined => { cdata.get_expn_that_defined(def_id.index, tcx.sess) }
243 }
244
245 pub fn provide(providers: &mut Providers) {
246     // FIXME(#44234) - almost all of these queries have no sub-queries and
247     // therefore no actual inputs, they're just reading tables calculated in
248     // resolve! Does this work? Unsure! That's what the issue is about
249     *providers = Providers {
250         is_dllimport_foreign_item: |tcx, id| match tcx.native_library_kind(id) {
251             Some(NativeLibKind::Dylib | NativeLibKind::RawDylib | NativeLibKind::Unspecified) => {
252                 true
253             }
254             _ => false,
255         },
256         is_statically_included_foreign_item: |tcx, id| {
257             matches!(
258                 tcx.native_library_kind(id),
259                 Some(NativeLibKind::StaticBundle | NativeLibKind::StaticNoBundle)
260             )
261         },
262         native_library_kind: |tcx, id| {
263             tcx.native_libraries(id.krate)
264                 .iter()
265                 .filter(|lib| native_libs::relevant_lib(&tcx.sess, lib))
266                 .find(|lib| {
267                     let fm_id = match lib.foreign_module {
268                         Some(id) => id,
269                         None => return false,
270                     };
271                     let map = tcx.foreign_modules(id.krate);
272                     map.get(&fm_id)
273                         .expect("failed to find foreign module")
274                         .foreign_items
275                         .contains(&id)
276                 })
277                 .map(|l| l.kind)
278         },
279         native_libraries: |tcx, cnum| {
280             assert_eq!(cnum, LOCAL_CRATE);
281             Lrc::new(native_libs::collect(tcx))
282         },
283         foreign_modules: |tcx, cnum| {
284             assert_eq!(cnum, LOCAL_CRATE);
285             let modules: FxHashMap<DefId, ForeignModule> =
286                 foreign_modules::collect(tcx).into_iter().map(|m| (m.def_id, m)).collect();
287             Lrc::new(modules)
288         },
289         link_args: |tcx, cnum| {
290             assert_eq!(cnum, LOCAL_CRATE);
291             Lrc::new(link_args::collect(tcx))
292         },
293
294         // Returns a map from a sufficiently visible external item (i.e., an
295         // external item that is visible from at least one local module) to a
296         // sufficiently visible parent (considering modules that re-export the
297         // external item to be parents).
298         visible_parent_map: |tcx, cnum| {
299             use std::collections::hash_map::Entry;
300             use std::collections::vec_deque::VecDeque;
301
302             assert_eq!(cnum, LOCAL_CRATE);
303             let mut visible_parent_map: DefIdMap<DefId> = Default::default();
304
305             // Issue 46112: We want the map to prefer the shortest
306             // paths when reporting the path to an item. Therefore we
307             // build up the map via a breadth-first search (BFS),
308             // which naturally yields minimal-length paths.
309             //
310             // Note that it needs to be a BFS over the whole forest of
311             // crates, not just each individual crate; otherwise you
312             // only get paths that are locally minimal with respect to
313             // whatever crate we happened to encounter first in this
314             // traversal, but not globally minimal across all crates.
315             let bfs_queue = &mut VecDeque::new();
316
317             // Preferring shortest paths alone does not guarantee a
318             // deterministic result; so sort by crate num to avoid
319             // hashtable iteration non-determinism. This only makes
320             // things as deterministic as crate-nums assignment is,
321             // which is to say, its not deterministic in general. But
322             // we believe that libstd is consistently assigned crate
323             // num 1, so it should be enough to resolve #46112.
324             let mut crates: Vec<CrateNum> = (*tcx.crates()).to_owned();
325             crates.sort();
326
327             for &cnum in crates.iter() {
328                 // Ignore crates without a corresponding local `extern crate` item.
329                 if tcx.missing_extern_crate_item(cnum) {
330                     continue;
331                 }
332
333                 bfs_queue.push_back(DefId { krate: cnum, index: CRATE_DEF_INDEX });
334             }
335
336             // (restrict scope of mutable-borrow of `visible_parent_map`)
337             {
338                 let visible_parent_map = &mut visible_parent_map;
339                 let mut add_child =
340                     |bfs_queue: &mut VecDeque<_>, child: &Export<hir::HirId>, parent: DefId| {
341                         if child.vis != ty::Visibility::Public {
342                             return;
343                         }
344
345                         if let Some(child) = child.res.opt_def_id() {
346                             match visible_parent_map.entry(child) {
347                                 Entry::Occupied(mut entry) => {
348                                     // If `child` is defined in crate `cnum`, ensure
349                                     // that it is mapped to a parent in `cnum`.
350                                     if child.krate == cnum && entry.get().krate != cnum {
351                                         entry.insert(parent);
352                                     }
353                                 }
354                                 Entry::Vacant(entry) => {
355                                     entry.insert(parent);
356                                     bfs_queue.push_back(child);
357                                 }
358                             }
359                         }
360                     };
361
362                 while let Some(def) = bfs_queue.pop_front() {
363                     for child in tcx.item_children(def).iter() {
364                         add_child(bfs_queue, child, def);
365                     }
366                 }
367             }
368
369             visible_parent_map
370         },
371
372         dependency_formats: |tcx, cnum| {
373             assert_eq!(cnum, LOCAL_CRATE);
374             Lrc::new(crate::dependency_format::calculate(tcx))
375         },
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, cnum| {
381             assert_eq!(cnum, LOCAL_CRATE);
382             tcx.arena.alloc_slice(&CStore::from_tcx(tcx).crate_dependencies_in_postorder(cnum))
383         },
384
385         ..*providers
386     };
387 }
388
389 impl CStore {
390     pub fn struct_field_names_untracked(&self, def: DefId, sess: &Session) -> Vec<Spanned<Symbol>> {
391         self.get_crate_data(def.krate).get_struct_field_names(def.index, sess)
392     }
393
394     pub fn item_children_untracked(
395         &self,
396         def_id: DefId,
397         sess: &Session,
398     ) -> Vec<Export<hir::HirId>> {
399         let mut result = vec![];
400         self.get_crate_data(def_id.krate).each_child_of_item(
401             def_id.index,
402             |child| result.push(child),
403             sess,
404         );
405         result
406     }
407
408     pub fn load_macro_untracked(&self, id: DefId, sess: &Session) -> LoadedMacro {
409         let _prof_timer = sess.prof.generic_activity("metadata_load_macro");
410
411         let data = self.get_crate_data(id.krate);
412         if data.root.is_proc_macro_crate() {
413             return LoadedMacro::ProcMacro(data.load_proc_macro(id.index, sess));
414         }
415
416         let span = data.get_span(id.index, sess);
417
418         let attrs: Vec<_> = data.get_item_attrs(id.index, sess).collect();
419
420         let ident = data.item_ident(id.index, sess);
421
422         LoadedMacro::MacroDef(
423             ast::Item {
424                 ident,
425                 id: ast::DUMMY_NODE_ID,
426                 span,
427                 attrs,
428                 kind: ast::ItemKind::MacroDef(data.get_macro(id.index, sess)),
429                 vis: ast::Visibility {
430                     span: span.shrink_to_lo(),
431                     kind: ast::VisibilityKind::Inherited,
432                     tokens: None,
433                 },
434                 tokens: None,
435             },
436             data.root.edition,
437         )
438     }
439
440     pub fn associated_item_cloned_untracked(&self, def: DefId, sess: &Session) -> ty::AssocItem {
441         self.get_crate_data(def.krate).get_associated_item(def.index, sess)
442     }
443
444     pub fn crate_source_untracked(&self, cnum: CrateNum) -> CrateSource {
445         self.get_crate_data(cnum).source.clone()
446     }
447
448     pub fn get_span_untracked(&self, def_id: DefId, sess: &Session) -> Span {
449         self.get_crate_data(def_id.krate).get_span(def_id.index, sess)
450     }
451
452     pub fn item_generics_num_lifetimes(&self, def_id: DefId, sess: &Session) -> usize {
453         self.get_crate_data(def_id.krate).get_generics(def_id.index, sess).own_counts().lifetimes
454     }
455
456     pub fn module_expansion_untracked(&self, def_id: DefId, sess: &Session) -> ExpnId {
457         self.get_crate_data(def_id.krate).module_expansion(def_id.index, sess)
458     }
459 }
460
461 impl CrateStore for CStore {
462     fn as_any(&self) -> &dyn Any {
463         self
464     }
465
466     fn crate_name_untracked(&self, cnum: CrateNum) -> Symbol {
467         self.get_crate_data(cnum).root.name
468     }
469
470     fn crate_is_private_dep_untracked(&self, cnum: CrateNum) -> bool {
471         self.get_crate_data(cnum).private_dep
472     }
473
474     fn crate_disambiguator_untracked(&self, cnum: CrateNum) -> CrateDisambiguator {
475         self.get_crate_data(cnum).root.disambiguator
476     }
477
478     fn crate_hash_untracked(&self, cnum: CrateNum) -> Svh {
479         self.get_crate_data(cnum).root.hash
480     }
481
482     /// Returns the `DefKey` for a given `DefId`. This indicates the
483     /// parent `DefId` as well as some idea of what kind of data the
484     /// `DefId` refers to.
485     fn def_key(&self, def: DefId) -> DefKey {
486         self.get_crate_data(def.krate).def_key(def.index)
487     }
488
489     fn def_kind(&self, def: DefId) -> DefKind {
490         self.get_crate_data(def.krate).def_kind(def.index)
491     }
492
493     fn def_path(&self, def: DefId) -> DefPath {
494         self.get_crate_data(def.krate).def_path(def.index)
495     }
496
497     fn def_path_hash(&self, def: DefId) -> DefPathHash {
498         self.get_crate_data(def.krate).def_path_hash(def.index)
499     }
500
501     fn all_def_path_hashes_and_def_ids(&self, cnum: CrateNum) -> Vec<(DefPathHash, DefId)> {
502         self.get_crate_data(cnum).all_def_path_hashes_and_def_ids()
503     }
504
505     fn num_def_ids(&self, cnum: CrateNum) -> usize {
506         self.get_crate_data(cnum).num_def_ids()
507     }
508
509     fn crates_untracked(&self) -> Vec<CrateNum> {
510         let mut result = vec![];
511         self.iter_crate_data(|cnum, _| result.push(cnum));
512         result
513     }
514
515     fn encode_metadata(&self, tcx: TyCtxt<'_>) -> EncodedMetadata {
516         encoder::encode_metadata(tcx)
517     }
518
519     fn metadata_encoding_version(&self) -> &[u8] {
520         rmeta::METADATA_HEADER
521     }
522
523     fn allocator_kind(&self) -> Option<AllocatorKind> {
524         self.allocator_kind()
525     }
526 }