]> git.lizzy.rs Git - rust.git/blob - src/librustc_metadata/cstore_impl.rs
Rollup merge of #64726 - andrewbanchich:unimplemented, r=rkruppe
[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::{CrateStore, DepKind,
10                             EncodedMetadata, NativeLibraryKind};
11 use rustc::middle::exported_symbols::ExportedSymbol;
12 use rustc::middle::stability::DeprecationEntry;
13 use rustc::middle::dependency_format::Linkage;
14 use rustc::hir::def;
15 use rustc::hir;
16 use rustc::session::{CrateDisambiguator, Session};
17 use rustc::ty::{self, TyCtxt};
18 use rustc::ty::query::Providers;
19 use rustc::hir::def_id::{CrateNum, DefId, LOCAL_CRATE, CRATE_DEF_INDEX};
20 use rustc::hir::map::{DefKey, DefPath, DefPathHash};
21 use rustc::hir::map::definitions::DefPathTable;
22 use rustc::util::nodemap::DefIdMap;
23 use rustc_data_structures::svh::Svh;
24
25 use smallvec::SmallVec;
26 use std::any::Any;
27 use rustc_data_structures::sync::Lrc;
28 use std::sync::Arc;
29
30 use syntax::ast;
31 use syntax::attr;
32 use syntax::source_map;
33 use syntax::edition::Edition;
34 use syntax::parse::source_file_to_stream;
35 use syntax::parse::parser::emit_unclosed_delims;
36 use syntax::symbol::Symbol;
37 use syntax_pos::{Span, FileName};
38 use rustc_index::bit_set::BitSet;
39
40 macro_rules! provide {
41     (<$lt:tt> $tcx:ident, $def_id:ident, $other:ident, $cdata:ident,
42       $($name:ident => $compute:block)*) => {
43         pub fn provide_extern<$lt>(providers: &mut Providers<$lt>) {
44             // HACK(eddyb) `$lt: $lt` forces `$lt` to be early-bound, which
45             // allows the associated type in the return type to be normalized.
46             $(fn $name<$lt: $lt, T: IntoArgs>(
47                 $tcx: TyCtxt<$lt>,
48                 def_id_arg: T,
49             ) -> <ty::queries::$name<$lt> as QueryConfig<$lt>>::Value {
50                 #[allow(unused_variables)]
51                 let ($def_id, $other) = def_id_arg.into_args();
52                 assert!(!$def_id.is_local());
53
54                 let def_path_hash = $tcx.def_path_hash(DefId {
55                     krate: $def_id.krate,
56                     index: CRATE_DEF_INDEX
57                 });
58                 let dep_node = def_path_hash
59                     .to_dep_node(rustc::dep_graph::DepKind::CrateMetadata);
60                 // The DepNodeIndex of the DepNode::CrateMetadata should be
61                 // cached somewhere, so that we can use read_index().
62                 $tcx.dep_graph.read(dep_node);
63
64                 let $cdata = $tcx.crate_data_as_rc_any($def_id.krate);
65                 let $cdata = $cdata.downcast_ref::<cstore::CrateMetadata>()
66                     .expect("CrateStore created data is not a CrateMetadata");
67                 $compute
68             })*
69
70             *providers = Providers {
71                 $($name,)*
72                 ..*providers
73             };
74         }
75     }
76 }
77
78 // small trait to work around different signature queries all being defined via
79 // the macro above.
80 trait IntoArgs {
81     fn into_args(self) -> (DefId, DefId);
82 }
83
84 impl IntoArgs for DefId {
85     fn into_args(self) -> (DefId, DefId) { (self, self) }
86 }
87
88 impl IntoArgs for CrateNum {
89     fn into_args(self) -> (DefId, DefId) { (self.as_def_id(), self.as_def_id()) }
90 }
91
92 impl IntoArgs for (CrateNum, DefId) {
93     fn into_args(self) -> (DefId, DefId) { (self.0.as_def_id(), self.1) }
94 }
95
96 provide! { <'tcx> tcx, def_id, other, cdata,
97     type_of => { cdata.get_type(def_id.index, tcx) }
98     generics_of => {
99         tcx.arena.alloc(cdata.get_generics(def_id.index, tcx.sess))
100     }
101     predicates_of => { tcx.arena.alloc(cdata.get_predicates(def_id.index, tcx)) }
102     predicates_defined_on => {
103         tcx.arena.alloc(cdata.get_predicates_defined_on(def_id.index, tcx))
104     }
105     super_predicates_of => { tcx.arena.alloc(cdata.get_super_predicates(def_id.index, tcx)) }
106     trait_def => {
107         tcx.arena.alloc(cdata.get_trait_def(def_id.index, tcx.sess))
108     }
109     adt_def => { cdata.get_adt_def(def_id.index, tcx) }
110     adt_destructor => {
111         let _ = cdata;
112         tcx.calculate_dtor(def_id, &mut |_,_| Ok(()))
113     }
114     variances_of => { tcx.arena.alloc_from_iter(cdata.get_item_variances(def_id.index)) }
115     associated_item_def_ids => {
116         let mut result = SmallVec::<[_; 8]>::new();
117         cdata.each_child_of_item(def_id.index,
118           |child| result.push(child.res.def_id()), tcx.sess);
119         tcx.arena.alloc_slice(&result)
120     }
121     associated_item => { cdata.get_associated_item(def_id.index) }
122     impl_trait_ref => { cdata.get_impl_trait(def_id.index, tcx) }
123     impl_polarity => { cdata.get_impl_polarity(def_id.index) }
124     coerce_unsized_info => {
125         cdata.get_coerce_unsized_info(def_id.index).unwrap_or_else(|| {
126             bug!("coerce_unsized_info: `{:?}` is missing its info", def_id);
127         })
128     }
129     optimized_mir => { tcx.arena.alloc(cdata.get_optimized_mir(tcx, def_id.index)) }
130     promoted_mir => { tcx.arena.alloc(cdata.get_promoted_mir(tcx, def_id.index)) }
131     mir_const_qualif => {
132         (cdata.mir_const_qualif(def_id.index), tcx.arena.alloc(BitSet::new_empty(0)))
133     }
134     fn_sig => { cdata.fn_sig(def_id.index, tcx) }
135     inherent_impls => { cdata.get_inherent_implementations_for_type(tcx, def_id.index) }
136     is_const_fn_raw => { cdata.is_const_fn_raw(def_id.index) }
137     asyncness => { cdata.asyncness(def_id.index) }
138     is_foreign_item => { cdata.is_foreign_item(def_id.index) }
139     static_mutability => { cdata.static_mutability(def_id.index) }
140     def_kind => { cdata.def_kind(def_id.index) }
141     def_span => { cdata.get_span(def_id.index, &tcx.sess) }
142     lookup_stability => {
143         cdata.get_stability(def_id.index).map(|s| tcx.intern_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_sanitizer_runtime => { cdata.root.sanitizer_runtime }
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     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 mut syms = cdata.exported_symbols(tcx);
243
244         // When linked into a dylib crates don't export their generic symbols,
245         // so if that's happening then we can't load upstream monomorphizations
246         // from this crate.
247         let formats = tcx.dependency_formats(LOCAL_CRATE);
248         let remove_generics = formats.iter().any(|(_ty, list)| {
249             match list.get(def_id.krate.as_usize() - 1) {
250                 Some(Linkage::IncludedFromDylib) | Some(Linkage::Dynamic) => true,
251                 _ => false,
252             }
253         });
254         if remove_generics {
255             syms.retain(|(sym, _threshold)| {
256                 match sym {
257                     ExportedSymbol::Generic(..) => false,
258                     _ => return true,
259                 }
260             });
261         }
262
263         Arc::new(syms)
264     }
265 }
266
267 pub fn provide(providers: &mut Providers<'_>) {
268     // FIXME(#44234) - almost all of these queries have no sub-queries and
269     // therefore no actual inputs, they're just reading tables calculated in
270     // resolve! Does this work? Unsure! That's what the issue is about
271     *providers = Providers {
272         is_dllimport_foreign_item: |tcx, id| {
273             match tcx.native_library_kind(id) {
274                 Some(NativeLibraryKind::NativeUnknown) |
275                 Some(NativeLibraryKind::NativeRawDylib) => true,
276                 _ => false,
277             }
278         },
279         is_statically_included_foreign_item: |tcx, id| {
280             match tcx.native_library_kind(id) {
281                 Some(NativeLibraryKind::NativeStatic) |
282                 Some(NativeLibraryKind::NativeStaticNobundle) => true,
283                 _ => false,
284             }
285         },
286         native_library_kind: |tcx, id| {
287             tcx.native_libraries(id.krate)
288                 .iter()
289                 .filter(|lib| native_libs::relevant_lib(&tcx.sess, lib))
290                 .find(|lib| {
291                     let fm_id = match lib.foreign_module {
292                         Some(id) => id,
293                         None => return false,
294                     };
295                     tcx.foreign_modules(id.krate)
296                         .iter()
297                         .find(|m| m.def_id == fm_id)
298                         .expect("failed to find foreign module")
299                         .foreign_items
300                         .contains(&id)
301                 })
302                 .map(|l| l.kind)
303         },
304         native_libraries: |tcx, cnum| {
305             assert_eq!(cnum, LOCAL_CRATE);
306             Lrc::new(native_libs::collect(tcx))
307         },
308         foreign_modules: |tcx, cnum| {
309             assert_eq!(cnum, LOCAL_CRATE);
310             &tcx.arena.alloc(foreign_modules::collect(tcx))[..]
311         },
312         link_args: |tcx, cnum| {
313             assert_eq!(cnum, LOCAL_CRATE);
314             Lrc::new(link_args::collect(tcx))
315         },
316
317         // Returns a map from a sufficiently visible external item (i.e., an
318         // external item that is visible from at least one local module) to a
319         // sufficiently visible parent (considering modules that re-export the
320         // external item to be parents).
321         visible_parent_map: |tcx, cnum| {
322             use std::collections::vec_deque::VecDeque;
323             use std::collections::hash_map::Entry;
324
325             assert_eq!(cnum, LOCAL_CRATE);
326             let mut visible_parent_map: DefIdMap<DefId> = Default::default();
327
328             // Issue 46112: We want the map to prefer the shortest
329             // paths when reporting the path to an item. Therefore we
330             // build up the map via a breadth-first search (BFS),
331             // which naturally yields minimal-length paths.
332             //
333             // Note that it needs to be a BFS over the whole forest of
334             // crates, not just each individual crate; otherwise you
335             // only get paths that are locally minimal with respect to
336             // whatever crate we happened to encounter first in this
337             // traversal, but not globally minimal across all crates.
338             let bfs_queue = &mut VecDeque::new();
339
340             // Preferring shortest paths alone does not guarantee a
341             // deterministic result; so sort by crate num to avoid
342             // hashtable iteration non-determinism. This only makes
343             // things as deterministic as crate-nums assignment is,
344             // which is to say, its not deterministic in general. But
345             // we believe that libstd is consistently assigned crate
346             // num 1, so it should be enough to resolve #46112.
347             let mut crates: Vec<CrateNum> = (*tcx.crates()).to_owned();
348             crates.sort();
349
350             for &cnum in crates.iter() {
351                 // Ignore crates without a corresponding local `extern crate` item.
352                 if tcx.missing_extern_crate_item(cnum) {
353                     continue
354                 }
355
356                 bfs_queue.push_back(DefId {
357                     krate: cnum,
358                     index: CRATE_DEF_INDEX
359                 });
360             }
361
362             // (restrict scope of mutable-borrow of `visible_parent_map`)
363             {
364                 let visible_parent_map = &mut visible_parent_map;
365                 let mut add_child = |bfs_queue: &mut VecDeque<_>,
366                                      child: &def::Export<hir::HirId>,
367                                      parent: DefId| {
368                     if child.vis != ty::Visibility::Public {
369                         return;
370                     }
371
372                     if let Some(child) = child.res.opt_def_id() {
373                         match visible_parent_map.entry(child) {
374                             Entry::Occupied(mut entry) => {
375                                 // If `child` is defined in crate `cnum`, ensure
376                                 // that it is mapped to a parent in `cnum`.
377                                 if child.krate == cnum && entry.get().krate != cnum {
378                                     entry.insert(parent);
379                                 }
380                             }
381                             Entry::Vacant(entry) => {
382                                 entry.insert(parent);
383                                 bfs_queue.push_back(child);
384                             }
385                         }
386                     }
387                 };
388
389                 while let Some(def) = bfs_queue.pop_front() {
390                     for child in tcx.item_children(def).iter() {
391                         add_child(bfs_queue, child, def);
392                     }
393                 }
394             }
395
396             tcx.arena.alloc(visible_parent_map)
397         },
398
399         dependency_formats: |tcx, cnum| {
400             assert_eq!(cnum, LOCAL_CRATE);
401             Lrc::new(crate::dependency_format::calculate(tcx))
402         },
403
404         ..*providers
405     };
406 }
407
408 impl cstore::CStore {
409     pub fn export_macros_untracked(&self, cnum: CrateNum) {
410         let data = self.get_crate_data(cnum);
411         let mut dep_kind = data.dep_kind.lock();
412         if *dep_kind == DepKind::UnexportedMacrosOnly {
413             *dep_kind = DepKind::MacrosOnly;
414         }
415     }
416
417     pub fn dep_kind_untracked(&self, cnum: CrateNum) -> DepKind {
418         let data = self.get_crate_data(cnum);
419         let r = *data.dep_kind.lock();
420         r
421     }
422
423     pub fn crate_edition_untracked(&self, cnum: CrateNum) -> Edition {
424         self.get_crate_data(cnum).root.edition
425     }
426
427     pub fn struct_field_names_untracked(&self, def: DefId) -> Vec<ast::Name> {
428         self.get_crate_data(def.krate).get_struct_field_names(def.index)
429     }
430
431     pub fn ctor_kind_untracked(&self, def: DefId) -> def::CtorKind {
432         self.get_crate_data(def.krate).get_ctor_kind(def.index)
433     }
434
435     pub fn item_attrs_untracked(&self, def: DefId, sess: &Session) -> Lrc<[ast::Attribute]> {
436         self.get_crate_data(def.krate).get_item_attrs(def.index, sess)
437     }
438
439     pub fn item_children_untracked(
440         &self,
441         def_id: DefId,
442         sess: &Session
443     ) -> Vec<def::Export<hir::HirId>> {
444         let mut result = vec![];
445         self.get_crate_data(def_id.krate)
446             .each_child_of_item(def_id.index, |child| result.push(child), sess);
447         result
448     }
449
450     pub fn load_macro_untracked(&self, id: DefId, sess: &Session) -> LoadedMacro {
451         let data = self.get_crate_data(id.krate);
452         if data.is_proc_macro_crate() {
453             return LoadedMacro::ProcMacro(data.load_proc_macro(id.index, sess));
454         }
455
456         let def = data.get_macro(id.index);
457         let macro_full_name = data.def_path(id.index).to_string_friendly(|_| data.root.name);
458         let source_name = FileName::Macros(macro_full_name);
459
460         let source_file = sess.parse_sess.source_map().new_source_file(source_name, def.body);
461         let local_span = Span::with_root_ctxt(source_file.start_pos, source_file.end_pos);
462         let (body, mut errors) = source_file_to_stream(&sess.parse_sess, source_file, None);
463         emit_unclosed_delims(&mut errors, &sess.diagnostic());
464
465         // Mark the attrs as used
466         let attrs = data.get_item_attrs(id.index, sess);
467         for attr in attrs.iter() {
468             attr::mark_used(attr);
469         }
470
471         let name = data.def_key(id.index).disambiguated_data.data
472             .get_opt_name().expect("no name in load_macro");
473         sess.imported_macro_spans.borrow_mut()
474             .insert(local_span, (name.to_string(), data.get_span(id.index, sess)));
475
476         LoadedMacro::MacroDef(ast::Item {
477             // FIXME: cross-crate hygiene
478             ident: ast::Ident::with_dummy_span(name.as_symbol()),
479             id: ast::DUMMY_NODE_ID,
480             span: local_span,
481             attrs: attrs.iter().cloned().collect(),
482             kind: ast::ItemKind::MacroDef(ast::MacroDef {
483                 tokens: body.into(),
484                 legacy: def.legacy,
485             }),
486             vis: source_map::respan(local_span.shrink_to_lo(), ast::VisibilityKind::Inherited),
487             tokens: None,
488         })
489     }
490
491     pub fn associated_item_cloned_untracked(&self, def: DefId) -> ty::AssocItem {
492         self.get_crate_data(def.krate).get_associated_item(def.index)
493     }
494 }
495
496 impl CrateStore for cstore::CStore {
497     fn crate_data_as_rc_any(&self, krate: CrateNum) -> Lrc<dyn Any> {
498         self.get_crate_data(krate)
499     }
500
501     fn item_generics_cloned_untracked(&self, def: DefId, sess: &Session) -> ty::Generics {
502         self.get_crate_data(def.krate).get_generics(def.index, sess)
503     }
504
505     fn crate_name_untracked(&self, cnum: CrateNum) -> Symbol
506     {
507         self.get_crate_data(cnum).root.name
508     }
509
510     fn crate_is_private_dep_untracked(&self, cnum: CrateNum) -> bool {
511         self.get_crate_data(cnum).private_dep
512     }
513
514     fn crate_disambiguator_untracked(&self, cnum: CrateNum) -> CrateDisambiguator
515     {
516         self.get_crate_data(cnum).root.disambiguator
517     }
518
519     fn crate_hash_untracked(&self, cnum: CrateNum) -> Svh
520     {
521         self.get_crate_data(cnum).root.hash
522     }
523
524     /// Returns the `DefKey` for a given `DefId`. This indicates the
525     /// parent `DefId` as well as some idea of what kind of data the
526     /// `DefId` refers to.
527     fn def_key(&self, def: DefId) -> DefKey {
528         // Note: loading the def-key (or def-path) for a def-id is not
529         // a *read* of its metadata. This is because the def-id is
530         // really just an interned shorthand for a def-path, which is the
531         // canonical name for an item.
532         //
533         // self.dep_graph.read(DepNode::MetaData(def));
534         self.get_crate_data(def.krate).def_key(def.index)
535     }
536
537     fn def_path(&self, def: DefId) -> DefPath {
538         // See `Note` above in `def_key()` for why this read is
539         // commented out:
540         //
541         // self.dep_graph.read(DepNode::MetaData(def));
542         self.get_crate_data(def.krate).def_path(def.index)
543     }
544
545     fn def_path_hash(&self, def: DefId) -> DefPathHash {
546         self.get_crate_data(def.krate).def_path_hash(def.index)
547     }
548
549     fn def_path_table(&self, cnum: CrateNum) -> Lrc<DefPathTable> {
550         self.get_crate_data(cnum).def_path_table.clone()
551     }
552
553     fn crates_untracked(&self) -> Vec<CrateNum>
554     {
555         let mut result = vec![];
556         self.iter_crate_data(|cnum, _| result.push(cnum));
557         result
558     }
559
560     fn extern_mod_stmt_cnum_untracked(&self, emod_id: ast::NodeId) -> Option<CrateNum>
561     {
562         self.do_extern_mod_stmt_cnum(emod_id)
563     }
564
565     fn postorder_cnums_untracked(&self) -> Vec<CrateNum> {
566         self.do_postorder_cnums_untracked()
567     }
568
569     fn encode_metadata(&self, tcx: TyCtxt<'_>) -> EncodedMetadata {
570         encoder::encode_metadata(tcx)
571     }
572
573     fn metadata_encoding_version(&self) -> &[u8]
574     {
575         schema::METADATA_HEADER
576     }
577 }