]> git.lizzy.rs Git - rust.git/blob - src/librustc_metadata/cstore_impl.rs
Auto merge of #65780 - GuillaumeGomez:move-help-popup-generation-code, r=Mark-Simulacrum
[rust.git] / src / librustc_metadata / cstore_impl.rs
1 use crate::cstore::{self, LoadedMacro};
2 use crate::encoder;
3 use crate::link_args;
4 use crate::native_libs;
5 use crate::foreign_modules;
6 use crate::schema;
7
8 use rustc::ty::query::QueryConfig;
9 use rustc::middle::cstore::{CrateSource, CrateStore, DepKind, EncodedMetadata, NativeLibraryKind};
10 use rustc::middle::exported_symbols::ExportedSymbol;
11 use rustc::middle::stability::DeprecationEntry;
12 use rustc::hir::def;
13 use rustc::hir;
14 use rustc::session::{CrateDisambiguator, Session};
15 use rustc::ty::{self, TyCtxt};
16 use rustc::ty::query::Providers;
17 use rustc::hir::def_id::{CrateNum, DefId, LOCAL_CRATE, CRATE_DEF_INDEX};
18 use rustc::hir::map::{DefKey, DefPath, DefPathHash};
19 use rustc::hir::map::definitions::DefPathTable;
20 use rustc::util::nodemap::DefIdMap;
21 use rustc_data_structures::svh::Svh;
22
23 use smallvec::SmallVec;
24 use std::any::Any;
25 use rustc_data_structures::sync::Lrc;
26 use std::sync::Arc;
27
28 use syntax::ast;
29 use syntax::attr;
30 use syntax::source_map;
31 use syntax::parse::source_file_to_stream;
32 use syntax::parse::parser::emit_unclosed_delims;
33 use syntax::source_map::Spanned;
34 use syntax::symbol::Symbol;
35 use syntax_pos::{Span, FileName};
36 use rustc_index::bit_set::BitSet;
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 = $tcx.crate_data_as_any($def_id.krate);
56                 let $cdata = $cdata.downcast_ref::<cstore::CrateMetadata>()
57                     .expect("CrateStore created data is not a CrateMetadata");
58
59                 if $tcx.dep_graph.is_fully_enabled() {
60                     let crate_dep_node_index = $cdata.get_crate_dep_node_index($tcx);
61                     $tcx.dep_graph.read_index(crate_dep_node_index);
62                 }
63
64                 $compute
65             })*
66
67             *providers = Providers {
68                 $($name,)*
69                 ..*providers
70             };
71         }
72     }
73 }
74
75 // small trait to work around different signature queries all being defined via
76 // the macro above.
77 trait IntoArgs {
78     fn into_args(self) -> (DefId, DefId);
79 }
80
81 impl IntoArgs for DefId {
82     fn into_args(self) -> (DefId, DefId) { (self, self) }
83 }
84
85 impl IntoArgs for CrateNum {
86     fn into_args(self) -> (DefId, DefId) { (self.as_def_id(), self.as_def_id()) }
87 }
88
89 impl IntoArgs for (CrateNum, DefId) {
90     fn into_args(self) -> (DefId, DefId) { (self.0.as_def_id(), self.1) }
91 }
92
93 provide! { <'tcx> tcx, def_id, other, cdata,
94     type_of => { cdata.get_type(def_id.index, tcx) }
95     generics_of => {
96         tcx.arena.alloc(cdata.get_generics(def_id.index, tcx.sess))
97     }
98     predicates_of => { cdata.get_predicates(def_id.index, tcx) }
99     predicates_defined_on => { cdata.get_predicates_defined_on(def_id.index, tcx) }
100     super_predicates_of => { cdata.get_super_predicates(def_id.index, tcx) }
101     trait_def => {
102         tcx.arena.alloc(cdata.get_trait_def(def_id.index, tcx.sess))
103     }
104     adt_def => { cdata.get_adt_def(def_id.index, tcx) }
105     adt_destructor => {
106         let _ = cdata;
107         tcx.calculate_dtor(def_id, &mut |_,_| Ok(()))
108     }
109     variances_of => { tcx.arena.alloc_from_iter(cdata.get_item_variances(def_id.index)) }
110     associated_item_def_ids => {
111         let mut result = SmallVec::<[_; 8]>::new();
112         cdata.each_child_of_item(def_id.index,
113           |child| result.push(child.res.def_id()), tcx.sess);
114         tcx.arena.alloc_slice(&result)
115     }
116     associated_item => { cdata.get_associated_item(def_id.index) }
117     impl_trait_ref => { cdata.get_impl_trait(def_id.index, tcx) }
118     impl_polarity => { cdata.get_impl_polarity(def_id.index) }
119     coerce_unsized_info => {
120         cdata.get_coerce_unsized_info(def_id.index).unwrap_or_else(|| {
121             bug!("coerce_unsized_info: `{:?}` is missing its info", def_id);
122         })
123     }
124     optimized_mir => { tcx.arena.alloc(cdata.get_optimized_mir(tcx, def_id.index)) }
125     promoted_mir => { tcx.arena.alloc(cdata.get_promoted_mir(tcx, def_id.index)) }
126     mir_const_qualif => {
127         (cdata.mir_const_qualif(def_id.index), tcx.arena.alloc(BitSet::new_empty(0)))
128     }
129     fn_sig => { cdata.fn_sig(def_id.index, tcx) }
130     inherent_impls => { cdata.get_inherent_implementations_for_type(tcx, def_id.index) }
131     is_const_fn_raw => { cdata.is_const_fn_raw(def_id.index) }
132     asyncness => { cdata.asyncness(def_id.index) }
133     is_foreign_item => { cdata.is_foreign_item(def_id.index) }
134     static_mutability => { cdata.static_mutability(def_id.index) }
135     def_kind => { cdata.def_kind(def_id.index) }
136     def_span => { cdata.get_span(def_id.index, &tcx.sess) }
137     lookup_stability => {
138         cdata.get_stability(def_id.index).map(|s| tcx.intern_stability(s))
139     }
140     lookup_deprecation_entry => {
141         cdata.get_deprecation(def_id.index).map(DeprecationEntry::external)
142     }
143     item_attrs => { cdata.get_item_attrs(def_id.index, tcx.sess) }
144     // FIXME(#38501) We've skipped a `read` on the `HirBody` 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(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_sanitizer_runtime => { cdata.root.sanitizer_runtime }
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     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         Arc::new(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| {
253             match tcx.native_library_kind(id) {
254                 Some(NativeLibraryKind::NativeUnknown) |
255                 Some(NativeLibraryKind::NativeRawDylib) => true,
256                 _ => false,
257             }
258         },
259         is_statically_included_foreign_item: |tcx, id| {
260             match tcx.native_library_kind(id) {
261                 Some(NativeLibraryKind::NativeStatic) |
262                 Some(NativeLibraryKind::NativeStaticNobundle) => true,
263                 _ => false,
264             }
265         },
266         native_library_kind: |tcx, id| {
267             tcx.native_libraries(id.krate)
268                 .iter()
269                 .filter(|lib| native_libs::relevant_lib(&tcx.sess, lib))
270                 .find(|lib| {
271                     let fm_id = match lib.foreign_module {
272                         Some(id) => id,
273                         None => return false,
274                     };
275                     tcx.foreign_modules(id.krate)
276                         .iter()
277                         .find(|m| m.def_id == fm_id)
278                         .expect("failed to find foreign module")
279                         .foreign_items
280                         .contains(&id)
281                 })
282                 .map(|l| l.kind)
283         },
284         native_libraries: |tcx, cnum| {
285             assert_eq!(cnum, LOCAL_CRATE);
286             Lrc::new(native_libs::collect(tcx))
287         },
288         foreign_modules: |tcx, cnum| {
289             assert_eq!(cnum, LOCAL_CRATE);
290             &tcx.arena.alloc(foreign_modules::collect(tcx))[..]
291         },
292         link_args: |tcx, cnum| {
293             assert_eq!(cnum, LOCAL_CRATE);
294             Lrc::new(link_args::collect(tcx))
295         },
296
297         // Returns a map from a sufficiently visible external item (i.e., an
298         // external item that is visible from at least one local module) to a
299         // sufficiently visible parent (considering modules that re-export the
300         // external item to be parents).
301         visible_parent_map: |tcx, cnum| {
302             use std::collections::vec_deque::VecDeque;
303             use std::collections::hash_map::Entry;
304
305             assert_eq!(cnum, LOCAL_CRATE);
306             let mut visible_parent_map: DefIdMap<DefId> = Default::default();
307
308             // Issue 46112: We want the map to prefer the shortest
309             // paths when reporting the path to an item. Therefore we
310             // build up the map via a breadth-first search (BFS),
311             // which naturally yields minimal-length paths.
312             //
313             // Note that it needs to be a BFS over the whole forest of
314             // crates, not just each individual crate; otherwise you
315             // only get paths that are locally minimal with respect to
316             // whatever crate we happened to encounter first in this
317             // traversal, but not globally minimal across all crates.
318             let bfs_queue = &mut VecDeque::new();
319
320             // Preferring shortest paths alone does not guarantee a
321             // deterministic result; so sort by crate num to avoid
322             // hashtable iteration non-determinism. This only makes
323             // things as deterministic as crate-nums assignment is,
324             // which is to say, its not deterministic in general. But
325             // we believe that libstd is consistently assigned crate
326             // num 1, so it should be enough to resolve #46112.
327             let mut crates: Vec<CrateNum> = (*tcx.crates()).to_owned();
328             crates.sort();
329
330             for &cnum in crates.iter() {
331                 // Ignore crates without a corresponding local `extern crate` item.
332                 if tcx.missing_extern_crate_item(cnum) {
333                     continue
334                 }
335
336                 bfs_queue.push_back(DefId {
337                     krate: cnum,
338                     index: CRATE_DEF_INDEX
339                 });
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 = |bfs_queue: &mut VecDeque<_>,
346                                      child: &def::Export<hir::HirId>,
347                                      parent: DefId| {
348                     if child.vis != ty::Visibility::Public {
349                         return;
350                     }
351
352                     if let Some(child) = child.res.opt_def_id() {
353                         match visible_parent_map.entry(child) {
354                             Entry::Occupied(mut entry) => {
355                                 // If `child` is defined in crate `cnum`, ensure
356                                 // that it is mapped to a parent in `cnum`.
357                                 if child.krate == cnum && entry.get().krate != cnum {
358                                     entry.insert(parent);
359                                 }
360                             }
361                             Entry::Vacant(entry) => {
362                                 entry.insert(parent);
363                                 bfs_queue.push_back(child);
364                             }
365                         }
366                     }
367                 };
368
369                 while let Some(def) = bfs_queue.pop_front() {
370                     for child in tcx.item_children(def).iter() {
371                         add_child(bfs_queue, child, def);
372                     }
373                 }
374             }
375
376             tcx.arena.alloc(visible_parent_map)
377         },
378
379         dependency_formats: |tcx, cnum| {
380             assert_eq!(cnum, LOCAL_CRATE);
381             Lrc::new(crate::dependency_format::calculate(tcx))
382         },
383
384         ..*providers
385     };
386 }
387
388 impl cstore::CStore {
389     pub fn export_macros_untracked(&self, cnum: CrateNum) {
390         let data = self.get_crate_data(cnum);
391         let mut dep_kind = data.dep_kind.lock();
392         if *dep_kind == DepKind::UnexportedMacrosOnly {
393             *dep_kind = DepKind::MacrosOnly;
394         }
395     }
396
397     pub fn struct_field_names_untracked(&self, def: DefId, sess: &Session) -> Vec<Spanned<Symbol>> {
398         self.get_crate_data(def.krate).get_struct_field_names(def.index, sess)
399     }
400
401     pub fn item_children_untracked(
402         &self,
403         def_id: DefId,
404         sess: &Session
405     ) -> Vec<def::Export<hir::HirId>> {
406         let mut result = vec![];
407         self.get_crate_data(def_id.krate)
408             .each_child_of_item(def_id.index, |child| result.push(child), sess);
409         result
410     }
411
412     pub fn load_macro_untracked(&self, id: DefId, sess: &Session) -> LoadedMacro {
413         let _prof_timer = sess.prof.generic_activity("metadata_load_macro");
414
415         let data = self.get_crate_data(id.krate);
416         if data.is_proc_macro_crate() {
417             return LoadedMacro::ProcMacro(data.load_proc_macro(id.index, sess));
418         }
419
420         let def = data.get_macro(id.index);
421         let macro_full_name = data.def_path(id.index).to_string_friendly(|_| data.root.name);
422         let source_name = FileName::Macros(macro_full_name);
423
424         let source_file = sess.parse_sess.source_map().new_source_file(source_name, def.body);
425         let local_span = Span::with_root_ctxt(source_file.start_pos, source_file.end_pos);
426         let (body, mut errors) = source_file_to_stream(&sess.parse_sess, source_file, None);
427         emit_unclosed_delims(&mut errors, &sess.diagnostic());
428
429         // Mark the attrs as used
430         let attrs = data.get_item_attrs(id.index, sess);
431         for attr in attrs.iter() {
432             attr::mark_used(attr);
433         }
434
435         let name = data.def_key(id.index).disambiguated_data.data
436             .get_opt_name().expect("no name in load_macro");
437         sess.imported_macro_spans.borrow_mut()
438             .insert(local_span, (name.to_string(), data.get_span(id.index, sess)));
439
440         LoadedMacro::MacroDef(ast::Item {
441             // FIXME: cross-crate hygiene
442             ident: ast::Ident::with_dummy_span(name),
443             id: ast::DUMMY_NODE_ID,
444             span: local_span,
445             attrs: attrs.iter().cloned().collect(),
446             kind: ast::ItemKind::MacroDef(ast::MacroDef {
447                 tokens: body.into(),
448                 legacy: def.legacy,
449             }),
450             vis: source_map::respan(local_span.shrink_to_lo(), ast::VisibilityKind::Inherited),
451             tokens: None,
452         }, data.root.edition)
453     }
454
455     pub fn associated_item_cloned_untracked(&self, def: DefId) -> ty::AssocItem {
456         self.get_crate_data(def.krate).get_associated_item(def.index)
457     }
458
459     pub fn crate_source_untracked(&self, cnum: CrateNum) -> CrateSource {
460         self.get_crate_data(cnum).source.clone()
461     }
462 }
463
464 impl CrateStore for cstore::CStore {
465     fn crate_data_as_any(&self, cnum: CrateNum) -> &dyn Any {
466         self.get_crate_data(cnum)
467     }
468
469     fn item_generics_cloned_untracked(&self, def: DefId, sess: &Session) -> ty::Generics {
470         self.get_crate_data(def.krate).get_generics(def.index, sess)
471     }
472
473     fn crate_name_untracked(&self, cnum: CrateNum) -> Symbol
474     {
475         self.get_crate_data(cnum).root.name
476     }
477
478     fn crate_is_private_dep_untracked(&self, cnum: CrateNum) -> bool {
479         self.get_crate_data(cnum).private_dep
480     }
481
482     fn crate_disambiguator_untracked(&self, cnum: CrateNum) -> CrateDisambiguator
483     {
484         self.get_crate_data(cnum).root.disambiguator
485     }
486
487     fn crate_hash_untracked(&self, cnum: CrateNum) -> Svh
488     {
489         self.get_crate_data(cnum).root.hash
490     }
491
492     fn crate_host_hash_untracked(&self, cnum: CrateNum) -> Option<Svh> {
493         self.get_crate_data(cnum).host_hash
494     }
495
496     /// Returns the `DefKey` for a given `DefId`. This indicates the
497     /// parent `DefId` as well as some idea of what kind of data the
498     /// `DefId` refers to.
499     fn def_key(&self, def: DefId) -> DefKey {
500         self.get_crate_data(def.krate).def_key(def.index)
501     }
502
503     fn def_path(&self, def: DefId) -> DefPath {
504         self.get_crate_data(def.krate).def_path(def.index)
505     }
506
507     fn def_path_hash(&self, def: DefId) -> DefPathHash {
508         self.get_crate_data(def.krate).def_path_hash(def.index)
509     }
510
511     fn def_path_table(&self, cnum: CrateNum) -> &DefPathTable {
512         &self.get_crate_data(cnum).def_path_table
513     }
514
515     fn crates_untracked(&self) -> Vec<CrateNum>
516     {
517         let mut result = vec![];
518         self.iter_crate_data(|cnum, _| result.push(cnum));
519         result
520     }
521
522     fn postorder_cnums_untracked(&self) -> Vec<CrateNum> {
523         self.do_postorder_cnums_untracked()
524     }
525
526     fn encode_metadata(&self, tcx: TyCtxt<'_>) -> EncodedMetadata {
527         encoder::encode_metadata(tcx)
528     }
529
530     fn metadata_encoding_version(&self) -> &[u8]
531     {
532         schema::METADATA_HEADER
533     }
534 }