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