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