]> git.lizzy.rs Git - rust.git/blob - src/librustc_metadata/rmeta/decoder/cstore_impl.rs
Rollup merge of #67642 - Mark-Simulacrum:relax-bounds, r=Amanieu
[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, DepKind, 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_span::source_map;
29 use rustc_span::source_map::Spanned;
30 use rustc_span::symbol::Symbol;
31 use rustc_span::{FileName, Span};
32 use syntax::ast;
33 use syntax::attr;
34 use syntax::expand::allocator::AllocatorKind;
35 use syntax::ptr::P;
36 use syntax::tokenstream::DelimSpan;
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     def_kind => { cdata.def_kind(def_id.index) }
138     def_span => { cdata.get_span(def_id.index, &tcx.sess) }
139     lookup_stability => {
140         cdata.get_stability(def_id.index).map(|s| tcx.intern_stability(s))
141     }
142     lookup_const_stability => {
143         cdata.get_const_stability(def_id.index).map(|s| tcx.intern_const_stability(s))
144     }
145     lookup_deprecation_entry => {
146         cdata.get_deprecation(def_id.index).map(DeprecationEntry::external)
147     }
148     item_attrs => { cdata.get_item_attrs(def_id.index, tcx.sess) }
149     // FIXME(#38501) We've skipped a `read` on the `HirBody` of
150     // a `fn` when encoding, so the dep-tracking wouldn't work.
151     // This is only used by rustdoc anyway, which shouldn't have
152     // incremental recompilation ever enabled.
153     fn_arg_names => { cdata.get_fn_param_names(def_id.index) }
154     rendered_const => { cdata.get_rendered_const(def_id.index) }
155     impl_parent => { cdata.get_parent_impl(def_id.index) }
156     trait_of_item => { cdata.get_trait_of_item(def_id.index) }
157     is_mir_available => { cdata.is_item_mir_available(def_id.index) }
158
159     dylib_dependency_formats => { cdata.get_dylib_dependency_formats(tcx) }
160     is_panic_runtime => { cdata.root.panic_runtime }
161     is_compiler_builtins => { cdata.root.compiler_builtins }
162     has_global_allocator => { cdata.root.has_global_allocator }
163     has_panic_handler => { cdata.root.has_panic_handler }
164     is_profiler_runtime => { cdata.root.profiler_runtime }
165     panic_strategy => { cdata.root.panic_strategy }
166     extern_crate => {
167         let r = *cdata.extern_crate.lock();
168         r.map(|c| &*tcx.arena.alloc(c))
169     }
170     is_no_builtins => { cdata.root.no_builtins }
171     symbol_mangling_version => { cdata.root.symbol_mangling_version }
172     impl_defaultness => { cdata.get_impl_defaultness(def_id.index) }
173     reachable_non_generics => {
174         let reachable_non_generics = tcx
175             .exported_symbols(cdata.cnum)
176             .iter()
177             .filter_map(|&(exported_symbol, export_level)| {
178                 if let ExportedSymbol::NonGeneric(def_id) = exported_symbol {
179                     return Some((def_id, export_level))
180                 } else {
181                     None
182                 }
183             })
184             .collect();
185
186         tcx.arena.alloc(reachable_non_generics)
187     }
188     native_libraries => { Lrc::new(cdata.get_native_libraries(tcx.sess)) }
189     foreign_modules => { cdata.get_foreign_modules(tcx) }
190     plugin_registrar_fn => {
191         cdata.root.plugin_registrar_fn.map(|index| {
192             DefId { krate: def_id.krate, index }
193         })
194     }
195     proc_macro_decls_static => {
196         cdata.root.proc_macro_decls_static.map(|index| {
197             DefId { krate: def_id.krate, index }
198         })
199     }
200     crate_disambiguator => { cdata.root.disambiguator }
201     crate_hash => { cdata.root.hash }
202     crate_host_hash => { cdata.host_hash }
203     original_crate_name => { cdata.root.name }
204
205     extra_filename => { cdata.root.extra_filename.clone() }
206
207     implementations_of_trait => {
208         cdata.get_implementations_for_trait(tcx, Some(other))
209     }
210
211     all_trait_implementations => {
212         cdata.get_implementations_for_trait(tcx, None)
213     }
214
215     visibility => { cdata.get_visibility(def_id.index) }
216     dep_kind => {
217         let r = *cdata.dep_kind.lock();
218         r
219     }
220     crate_name => { cdata.root.name }
221     item_children => {
222         let mut result = SmallVec::<[_; 8]>::new();
223         cdata.each_child_of_item(def_id.index, |child| result.push(child), tcx.sess);
224         tcx.arena.alloc_slice(&result)
225     }
226     defined_lib_features => { cdata.get_lib_features(tcx) }
227     defined_lang_items => { cdata.get_lang_items(tcx) }
228     diagnostic_items => { cdata.get_diagnostic_items(tcx) }
229     missing_lang_items => { cdata.get_missing_lang_items(tcx) }
230
231     missing_extern_crate_item => {
232         let r = match *cdata.extern_crate.borrow() {
233             Some(extern_crate) if !extern_crate.is_direct() => true,
234             _ => false,
235         };
236         r
237     }
238
239     used_crate_source => { Lrc::new(cdata.source.clone()) }
240
241     exported_symbols => {
242         let syms = cdata.exported_symbols(tcx);
243
244         // FIXME rust-lang/rust#64319, rust-lang/rust#64872: We want
245         // to block export of generics from dylibs, but we must fix
246         // rust-lang/rust#65890 before we can do that robustly.
247
248         Arc::new(syms)
249     }
250 }
251
252 pub fn provide(providers: &mut Providers<'_>) {
253     // FIXME(#44234) - almost all of these queries have no sub-queries and
254     // therefore no actual inputs, they're just reading tables calculated in
255     // resolve! Does this work? Unsure! That's what the issue is about
256     *providers = Providers {
257         is_dllimport_foreign_item: |tcx, id| match tcx.native_library_kind(id) {
258             Some(NativeLibraryKind::NativeUnknown) | Some(NativeLibraryKind::NativeRawDylib) => {
259                 true
260             }
261             _ => false,
262         },
263         is_statically_included_foreign_item: |tcx, id| match tcx.native_library_kind(id) {
264             Some(NativeLibraryKind::NativeStatic)
265             | Some(NativeLibraryKind::NativeStaticNobundle) => true,
266             _ => false,
267         },
268         native_library_kind: |tcx, id| {
269             tcx.native_libraries(id.krate)
270                 .iter()
271                 .filter(|lib| native_libs::relevant_lib(&tcx.sess, lib))
272                 .find(|lib| {
273                     let fm_id = match lib.foreign_module {
274                         Some(id) => id,
275                         None => return false,
276                     };
277                     tcx.foreign_modules(id.krate)
278                         .iter()
279                         .find(|m| m.def_id == fm_id)
280                         .expect("failed to find foreign module")
281                         .foreign_items
282                         .contains(&id)
283                 })
284                 .map(|l| l.kind)
285         },
286         native_libraries: |tcx, cnum| {
287             assert_eq!(cnum, LOCAL_CRATE);
288             Lrc::new(native_libs::collect(tcx))
289         },
290         foreign_modules: |tcx, cnum| {
291             assert_eq!(cnum, LOCAL_CRATE);
292             &tcx.arena.alloc(foreign_modules::collect(tcx))[..]
293         },
294         link_args: |tcx, cnum| {
295             assert_eq!(cnum, LOCAL_CRATE);
296             Lrc::new(link_args::collect(tcx))
297         },
298
299         // Returns a map from a sufficiently visible external item (i.e., an
300         // external item that is visible from at least one local module) to a
301         // sufficiently visible parent (considering modules that re-export the
302         // external item to be parents).
303         visible_parent_map: |tcx, cnum| {
304             use std::collections::hash_map::Entry;
305             use std::collections::vec_deque::VecDeque;
306
307             assert_eq!(cnum, LOCAL_CRATE);
308             let mut visible_parent_map: DefIdMap<DefId> = Default::default();
309
310             // Issue 46112: We want the map to prefer the shortest
311             // paths when reporting the path to an item. Therefore we
312             // build up the map via a breadth-first search (BFS),
313             // which naturally yields minimal-length paths.
314             //
315             // Note that it needs to be a BFS over the whole forest of
316             // crates, not just each individual crate; otherwise you
317             // only get paths that are locally minimal with respect to
318             // whatever crate we happened to encounter first in this
319             // traversal, but not globally minimal across all crates.
320             let bfs_queue = &mut VecDeque::new();
321
322             // Preferring shortest paths alone does not guarantee a
323             // deterministic result; so sort by crate num to avoid
324             // hashtable iteration non-determinism. This only makes
325             // things as deterministic as crate-nums assignment is,
326             // which is to say, its not deterministic in general. But
327             // we believe that libstd is consistently assigned crate
328             // num 1, so it should be enough to resolve #46112.
329             let mut crates: Vec<CrateNum> = (*tcx.crates()).to_owned();
330             crates.sort();
331
332             for &cnum in crates.iter() {
333                 // Ignore crates without a corresponding local `extern crate` item.
334                 if tcx.missing_extern_crate_item(cnum) {
335                     continue;
336                 }
337
338                 bfs_queue.push_back(DefId { krate: cnum, index: CRATE_DEF_INDEX });
339             }
340
341             // (restrict scope of mutable-borrow of `visible_parent_map`)
342             {
343                 let visible_parent_map = &mut visible_parent_map;
344                 let mut add_child =
345                     |bfs_queue: &mut VecDeque<_>, child: &Export<hir::HirId>, parent: DefId| {
346                         if child.vis != ty::Visibility::Public {
347                             return;
348                         }
349
350                         if let Some(child) = child.res.opt_def_id() {
351                             match visible_parent_map.entry(child) {
352                                 Entry::Occupied(mut entry) => {
353                                     // If `child` is defined in crate `cnum`, ensure
354                                     // that it is mapped to a parent in `cnum`.
355                                     if child.krate == cnum && entry.get().krate != cnum {
356                                         entry.insert(parent);
357                                     }
358                                 }
359                                 Entry::Vacant(entry) => {
360                                     entry.insert(parent);
361                                     bfs_queue.push_back(child);
362                                 }
363                             }
364                         }
365                     };
366
367                 while let Some(def) = bfs_queue.pop_front() {
368                     for child in tcx.item_children(def).iter() {
369                         add_child(bfs_queue, child, def);
370                     }
371                 }
372             }
373
374             tcx.arena.alloc(visible_parent_map)
375         },
376
377         dependency_formats: |tcx, cnum| {
378             assert_eq!(cnum, LOCAL_CRATE);
379             Lrc::new(crate::dependency_format::calculate(tcx))
380         },
381         has_global_allocator: |tcx, cnum| {
382             assert_eq!(cnum, LOCAL_CRATE);
383             CStore::from_tcx(tcx).has_global_allocator()
384         },
385         postorder_cnums: |tcx, cnum| {
386             assert_eq!(cnum, LOCAL_CRATE);
387             tcx.arena.alloc_slice(&CStore::from_tcx(tcx).crate_dependencies_in_postorder(cnum))
388         },
389
390         ..*providers
391     };
392 }
393
394 impl CStore {
395     pub fn export_macros_untracked(&self, cnum: CrateNum) {
396         let data = self.get_crate_data(cnum);
397         let mut dep_kind = data.dep_kind.lock();
398         if *dep_kind == DepKind::UnexportedMacrosOnly {
399             *dep_kind = DepKind::MacrosOnly;
400         }
401     }
402
403     pub fn struct_field_names_untracked(&self, def: DefId, sess: &Session) -> Vec<Spanned<Symbol>> {
404         self.get_crate_data(def.krate).get_struct_field_names(def.index, sess)
405     }
406
407     pub fn item_children_untracked(
408         &self,
409         def_id: DefId,
410         sess: &Session,
411     ) -> Vec<Export<hir::HirId>> {
412         let mut result = vec![];
413         self.get_crate_data(def_id.krate).each_child_of_item(
414             def_id.index,
415             |child| result.push(child),
416             sess,
417         );
418         result
419     }
420
421     pub fn load_macro_untracked(&self, id: DefId, sess: &Session) -> LoadedMacro {
422         let _prof_timer = sess.prof.generic_activity("metadata_load_macro");
423
424         let data = self.get_crate_data(id.krate);
425         if data.root.is_proc_macro_crate() {
426             return LoadedMacro::ProcMacro(data.load_proc_macro(id.index, sess));
427         }
428
429         let def = data.get_macro(id.index);
430         let macro_full_name = data.def_path(id.index).to_string_friendly(|_| data.root.name);
431         let source_name = FileName::Macros(macro_full_name);
432
433         let source_file = sess.parse_sess.source_map().new_source_file(source_name, def.body);
434         let local_span = Span::with_root_ctxt(source_file.start_pos, source_file.end_pos);
435         let dspan = DelimSpan::from_single(local_span);
436         let (body, mut errors) = source_file_to_stream(&sess.parse_sess, source_file, None);
437         emit_unclosed_delims(&mut errors, &sess.parse_sess);
438
439         // Mark the attrs as used
440         let attrs = data.get_item_attrs(id.index, sess);
441         for attr in attrs.iter() {
442             attr::mark_used(attr);
443         }
444
445         let name = data
446             .def_key(id.index)
447             .disambiguated_data
448             .data
449             .get_opt_name()
450             .expect("no name in load_macro");
451         sess.imported_macro_spans
452             .borrow_mut()
453             .insert(local_span, (name.to_string(), data.get_span(id.index, sess)));
454
455         LoadedMacro::MacroDef(
456             ast::Item {
457                 // FIXME: cross-crate hygiene
458                 ident: ast::Ident::with_dummy_span(name),
459                 id: ast::DUMMY_NODE_ID,
460                 span: local_span,
461                 attrs: attrs.iter().cloned().collect(),
462                 kind: ast::ItemKind::MacroDef(ast::MacroDef {
463                     body: P(ast::MacArgs::Delimited(dspan, ast::MacDelimiter::Brace, body)),
464                     legacy: def.legacy,
465                 }),
466                 vis: source_map::respan(local_span.shrink_to_lo(), ast::VisibilityKind::Inherited),
467                 tokens: None,
468             },
469             data.root.edition,
470         )
471     }
472
473     pub fn associated_item_cloned_untracked(&self, def: DefId) -> ty::AssocItem {
474         self.get_crate_data(def.krate).get_associated_item(def.index)
475     }
476
477     pub fn crate_source_untracked(&self, cnum: CrateNum) -> CrateSource {
478         self.get_crate_data(cnum).source.clone()
479     }
480
481     pub fn get_span_untracked(&self, def_id: DefId, sess: &Session) -> Span {
482         self.get_crate_data(def_id.krate).get_span(def_id.index, sess)
483     }
484
485     pub fn item_generics_num_lifetimes(&self, def_id: DefId, sess: &Session) -> usize {
486         self.get_crate_data(def_id.krate).get_generics(def_id.index, sess).own_counts().lifetimes
487     }
488 }
489
490 impl CrateStore for CStore {
491     fn as_any(&self) -> &dyn Any {
492         self
493     }
494
495     fn crate_name_untracked(&self, cnum: CrateNum) -> Symbol {
496         self.get_crate_data(cnum).root.name
497     }
498
499     fn crate_is_private_dep_untracked(&self, cnum: CrateNum) -> bool {
500         self.get_crate_data(cnum).private_dep
501     }
502
503     fn crate_disambiguator_untracked(&self, cnum: CrateNum) -> CrateDisambiguator {
504         self.get_crate_data(cnum).root.disambiguator
505     }
506
507     fn crate_hash_untracked(&self, cnum: CrateNum) -> Svh {
508         self.get_crate_data(cnum).root.hash
509     }
510
511     /// Returns the `DefKey` for a given `DefId`. This indicates the
512     /// parent `DefId` as well as some idea of what kind of data the
513     /// `DefId` refers to.
514     fn def_key(&self, def: DefId) -> DefKey {
515         self.get_crate_data(def.krate).def_key(def.index)
516     }
517
518     fn def_path(&self, def: DefId) -> DefPath {
519         self.get_crate_data(def.krate).def_path(def.index)
520     }
521
522     fn def_path_hash(&self, def: DefId) -> DefPathHash {
523         self.get_crate_data(def.krate).def_path_hash(def.index)
524     }
525
526     fn def_path_table(&self, cnum: CrateNum) -> &DefPathTable {
527         &self.get_crate_data(cnum).def_path_table
528     }
529
530     fn crates_untracked(&self) -> Vec<CrateNum> {
531         let mut result = vec![];
532         self.iter_crate_data(|cnum, _| result.push(cnum));
533         result
534     }
535
536     fn encode_metadata(&self, tcx: TyCtxt<'_>) -> EncodedMetadata {
537         encoder::encode_metadata(tcx)
538     }
539
540     fn metadata_encoding_version(&self) -> &[u8] {
541         rmeta::METADATA_HEADER
542     }
543
544     fn allocator_kind(&self) -> Option<AllocatorKind> {
545         self.allocator_kind()
546     }
547 }