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