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