]> git.lizzy.rs Git - rust.git/blob - src/librustc_metadata/rmeta/decoder/cstore_impl.rs
fix more clippy warnings
[rust.git] / src / librustc_metadata / 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::ast;
8 use rustc_ast::attr;
9 use rustc_ast::expand::allocator::AllocatorKind;
10 use rustc_data_structures::svh::Svh;
11 use rustc_hir as hir;
12 use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, CRATE_DEF_INDEX, LOCAL_CRATE};
13 use rustc_hir::definitions::DefPathTable;
14 use rustc_hir::definitions::{DefKey, DefPath, DefPathHash};
15 use rustc_middle::hir::exports::Export;
16 use rustc_middle::middle::cstore::{CrateSource, CrateStore, EncodedMetadata, NativeLibraryKind};
17 use rustc_middle::middle::exported_symbols::ExportedSymbol;
18 use rustc_middle::middle::stability::DeprecationEntry;
19 use rustc_middle::ty::query::Providers;
20 use rustc_middle::ty::query::QueryConfig;
21 use rustc_middle::ty::{self, TyCtxt};
22 use rustc_session::{CrateDisambiguator, Session};
23 use rustc_span::source_map::{self, Span, Spanned};
24 use rustc_span::symbol::Symbol;
25
26 use rustc_data_structures::sync::Lrc;
27 use smallvec::SmallVec;
28 use std::any::Any;
29
30 macro_rules! provide {
31     (<$lt:tt> $tcx:ident, $def_id:ident, $other:ident, $cdata:ident,
32       $($name:ident => $compute:block)*) => {
33         pub fn provide_extern<$lt>(providers: &mut Providers<$lt>) {
34             // HACK(eddyb) `$lt: $lt` forces `$lt` to be early-bound, which
35             // allows the associated type in the return type to be normalized.
36             $(fn $name<$lt: $lt, T: IntoArgs>(
37                 $tcx: TyCtxt<$lt>,
38                 def_id_arg: T,
39             ) -> <ty::queries::$name<$lt> as QueryConfig<TyCtxt<$lt>>>::Value {
40                 let _prof_timer =
41                     $tcx.prof.generic_activity("metadata_decode_entry");
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 => {
92         tcx.arena.alloc(cdata.get_generics(def_id.index, tcx.sess))
93     }
94     explicit_predicates_of => { cdata.get_explicit_predicates(def_id.index, tcx) }
95     inferred_outlives_of => { cdata.get_inferred_outlives(def_id.index, tcx) }
96     super_predicates_of => { cdata.get_super_predicates(def_id.index, tcx) }
97     trait_def => {
98         tcx.arena.alloc(cdata.get_trait_def(def_id.index, tcx.sess))
99     }
100     adt_def => { cdata.get_adt_def(def_id.index, tcx) }
101     adt_destructor => {
102         let _ = cdata;
103         tcx.calculate_dtor(def_id, &mut |_,_| Ok(()))
104     }
105     variances_of => { tcx.arena.alloc_from_iter(cdata.get_item_variances(def_id.index)) }
106     associated_item_def_ids => {
107         let mut result = SmallVec::<[_; 8]>::new();
108         cdata.each_child_of_item(def_id.index,
109           |child| result.push(child.res.def_id()), tcx.sess);
110         tcx.arena.alloc_slice(&result)
111     }
112     associated_item => { cdata.get_associated_item(def_id.index, tcx.sess) }
113     impl_trait_ref => { cdata.get_impl_trait(def_id.index, tcx) }
114     impl_polarity => { cdata.get_impl_polarity(def_id.index) }
115     coerce_unsized_info => {
116         cdata.get_coerce_unsized_info(def_id.index).unwrap_or_else(|| {
117             bug!("coerce_unsized_info: `{:?}` is missing its info", def_id);
118         })
119     }
120     optimized_mir => { tcx.arena.alloc(cdata.get_optimized_mir(tcx, def_id.index)) }
121     promoted_mir => { tcx.arena.alloc(cdata.get_promoted_mir(tcx, def_id.index)) }
122     mir_const_qualif => { cdata.mir_const_qualif(def_id.index) }
123     fn_sig => { cdata.fn_sig(def_id.index, tcx) }
124     inherent_impls => { cdata.get_inherent_implementations_for_type(tcx, def_id.index) }
125     is_const_fn_raw => { cdata.is_const_fn_raw(def_id.index) }
126     asyncness => { cdata.asyncness(def_id.index) }
127     is_foreign_item => { cdata.is_foreign_item(def_id.index) }
128     static_mutability => { cdata.static_mutability(def_id.index) }
129     generator_kind => { cdata.generator_kind(def_id.index) }
130     def_kind => { cdata.def_kind(def_id.index) }
131     def_span => { cdata.get_span(def_id.index, &tcx.sess) }
132     lookup_stability => {
133         cdata.get_stability(def_id.index).map(|s| tcx.intern_stability(s))
134     }
135     lookup_const_stability => {
136         cdata.get_const_stability(def_id.index).map(|s| tcx.intern_const_stability(s))
137     }
138     lookup_deprecation_entry => {
139         cdata.get_deprecation(def_id.index).map(DeprecationEntry::external)
140     }
141     item_attrs => { tcx.arena.alloc_from_iter(
142         cdata.get_item_attrs(def_id.index, tcx.sess).into_iter()
143     ) }
144     // FIXME(#38501) We've skipped a `read` on the `hir_owner_nodes` of
145     // a `fn` when encoding, so the dep-tracking wouldn't work.
146     // This is only used by rustdoc anyway, which shouldn't have
147     // incremental recompilation ever enabled.
148     fn_arg_names => { cdata.get_fn_param_names(tcx, def_id.index) }
149     rendered_const => { cdata.get_rendered_const(def_id.index) }
150     impl_parent => { cdata.get_parent_impl(def_id.index) }
151     trait_of_item => { cdata.get_trait_of_item(def_id.index) }
152     is_mir_available => { cdata.is_item_mir_available(def_id.index) }
153
154     dylib_dependency_formats => { cdata.get_dylib_dependency_formats(tcx) }
155     is_panic_runtime => { cdata.root.panic_runtime }
156     is_compiler_builtins => { cdata.root.compiler_builtins }
157     has_global_allocator => { cdata.root.has_global_allocator }
158     has_panic_handler => { cdata.root.has_panic_handler }
159     is_profiler_runtime => { cdata.root.profiler_runtime }
160     panic_strategy => { cdata.root.panic_strategy }
161     extern_crate => {
162         let r = *cdata.extern_crate.lock();
163         r.map(|c| &*tcx.arena.alloc(c))
164     }
165     is_no_builtins => { cdata.root.no_builtins }
166     symbol_mangling_version => { cdata.root.symbol_mangling_version }
167     impl_defaultness => { cdata.get_impl_defaultness(def_id.index) }
168     reachable_non_generics => {
169         let reachable_non_generics = tcx
170             .exported_symbols(cdata.cnum)
171             .iter()
172             .filter_map(|&(exported_symbol, export_level)| {
173                 if let ExportedSymbol::NonGeneric(def_id) = exported_symbol {
174                     Some((def_id, export_level))
175                 } else {
176                     None
177                 }
178             })
179             .collect();
180
181         tcx.arena.alloc(reachable_non_generics)
182     }
183     native_libraries => { Lrc::new(cdata.get_native_libraries(tcx.sess)) }
184     foreign_modules => { cdata.get_foreign_modules(tcx) }
185     plugin_registrar_fn => {
186         cdata.root.plugin_registrar_fn.map(|index| {
187             DefId { krate: def_id.krate, index }
188         })
189     }
190     proc_macro_decls_static => {
191         cdata.root.proc_macro_decls_static.map(|index| {
192             DefId { krate: def_id.krate, index }
193         })
194     }
195     crate_disambiguator => { cdata.root.disambiguator }
196     crate_hash => { cdata.root.hash }
197     crate_host_hash => { cdata.host_hash }
198     original_crate_name => { cdata.root.name }
199
200     extra_filename => { cdata.root.extra_filename.clone() }
201
202     implementations_of_trait => {
203         cdata.get_implementations_for_trait(tcx, Some(other))
204     }
205
206     all_trait_implementations => {
207         cdata.get_implementations_for_trait(tcx, None)
208     }
209
210     visibility => { cdata.get_visibility(def_id.index) }
211     dep_kind => {
212         let r = *cdata.dep_kind.lock();
213         r
214     }
215     crate_name => { cdata.root.name }
216     item_children => {
217         let mut result = SmallVec::<[_; 8]>::new();
218         cdata.each_child_of_item(def_id.index, |child| result.push(child), tcx.sess);
219         tcx.arena.alloc_slice(&result)
220     }
221     defined_lib_features => { cdata.get_lib_features(tcx) }
222     defined_lang_items => { cdata.get_lang_items(tcx) }
223     diagnostic_items => { cdata.get_diagnostic_items(tcx) }
224     missing_lang_items => { cdata.get_missing_lang_items(tcx) }
225
226     missing_extern_crate_item => {
227         let r = match *cdata.extern_crate.borrow() {
228             Some(extern_crate) if !extern_crate.is_direct() => true,
229             _ => false,
230         };
231         r
232     }
233
234     used_crate_source => { Lrc::new(cdata.source.clone()) }
235
236     exported_symbols => {
237         let syms = cdata.exported_symbols(tcx);
238
239         // FIXME rust-lang/rust#64319, rust-lang/rust#64872: We want
240         // to block export of generics from dylibs, but we must fix
241         // rust-lang/rust#65890 before we can do that robustly.
242
243         syms
244     }
245 }
246
247 pub fn provide(providers: &mut Providers<'_>) {
248     // FIXME(#44234) - almost all of these queries have no sub-queries and
249     // therefore no actual inputs, they're just reading tables calculated in
250     // resolve! Does this work? Unsure! That's what the issue is about
251     *providers = Providers {
252         is_dllimport_foreign_item: |tcx, id| match tcx.native_library_kind(id) {
253             Some(NativeLibraryKind::NativeUnknown | NativeLibraryKind::NativeRawDylib) => true,
254             _ => false,
255         },
256         is_statically_included_foreign_item: |tcx, id| match tcx.native_library_kind(id) {
257             Some(NativeLibraryKind::NativeStatic | NativeLibraryKind::NativeStaticNobundle) => 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             tcx.arena.alloc(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             attr::mark_used(attr);
419         }
420
421         let ident = data
422             .def_key(id.index)
423             .disambiguated_data
424             .data
425             .get_opt_name()
426             .map(ast::Ident::with_dummy_span) // FIXME: cross-crate hygiene
427             .expect("no name in load_macro");
428
429         LoadedMacro::MacroDef(
430             ast::Item {
431                 ident,
432                 id: ast::DUMMY_NODE_ID,
433                 span,
434                 attrs: attrs.to_vec(),
435                 kind: ast::ItemKind::MacroDef(data.get_macro(id.index, sess)),
436                 vis: source_map::respan(span.shrink_to_lo(), ast::VisibilityKind::Inherited),
437                 tokens: None,
438             },
439             data.root.edition,
440         )
441     }
442
443     pub fn associated_item_cloned_untracked(&self, def: DefId, sess: &Session) -> ty::AssocItem {
444         self.get_crate_data(def.krate).get_associated_item(def.index, sess)
445     }
446
447     pub fn crate_source_untracked(&self, cnum: CrateNum) -> CrateSource {
448         self.get_crate_data(cnum).source.clone()
449     }
450
451     pub fn get_span_untracked(&self, def_id: DefId, sess: &Session) -> Span {
452         self.get_crate_data(def_id.krate).get_span(def_id.index, sess)
453     }
454
455     pub fn item_generics_num_lifetimes(&self, def_id: DefId, sess: &Session) -> usize {
456         self.get_crate_data(def_id.krate).get_generics(def_id.index, sess).own_counts().lifetimes
457     }
458 }
459
460 impl CrateStore for CStore {
461     fn as_any(&self) -> &dyn Any {
462         self
463     }
464
465     fn crate_name_untracked(&self, cnum: CrateNum) -> Symbol {
466         self.get_crate_data(cnum).root.name
467     }
468
469     fn crate_is_private_dep_untracked(&self, cnum: CrateNum) -> bool {
470         self.get_crate_data(cnum).private_dep
471     }
472
473     fn crate_disambiguator_untracked(&self, cnum: CrateNum) -> CrateDisambiguator {
474         self.get_crate_data(cnum).root.disambiguator
475     }
476
477     fn crate_hash_untracked(&self, cnum: CrateNum) -> Svh {
478         self.get_crate_data(cnum).root.hash
479     }
480
481     /// Returns the `DefKey` for a given `DefId`. This indicates the
482     /// parent `DefId` as well as some idea of what kind of data the
483     /// `DefId` refers to.
484     fn def_key(&self, def: DefId) -> DefKey {
485         self.get_crate_data(def.krate).def_key(def.index)
486     }
487
488     fn def_path(&self, def: DefId) -> DefPath {
489         self.get_crate_data(def.krate).def_path(def.index)
490     }
491
492     fn def_path_hash(&self, def: DefId) -> DefPathHash {
493         self.get_crate_data(def.krate).def_path_hash(def.index)
494     }
495
496     fn def_path_table(&self, cnum: CrateNum) -> &DefPathTable {
497         &self.get_crate_data(cnum).cdata.def_path_table
498     }
499
500     fn crates_untracked(&self) -> Vec<CrateNum> {
501         let mut result = vec![];
502         self.iter_crate_data(|cnum, _| result.push(cnum));
503         result
504     }
505
506     fn encode_metadata(&self, tcx: TyCtxt<'_>) -> EncodedMetadata {
507         encoder::encode_metadata(tcx)
508     }
509
510     fn metadata_encoding_version(&self) -> &[u8] {
511         rmeta::METADATA_HEADER
512     }
513
514     fn allocator_kind(&self) -> Option<AllocatorKind> {
515         self.allocator_kind()
516     }
517 }