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