]> git.lizzy.rs Git - rust.git/blob - src/librustc_metadata/cstore_impl.rs
Rollup merge of #63055 - Mark-Simulacrum:save-analysis-clean-2, r=Xanewok
[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::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::edition::Edition;
33 use syntax::ext::base::{SyntaxExtension, SyntaxExtensionKind};
34 use syntax::ext::proc_macro::BangProcMacro;
35 use syntax::parse::source_file_to_stream;
36 use syntax::parse::parser::emit_unclosed_delims;
37 use syntax::symbol::{Symbol, sym};
38 use syntax_pos::{Span, NO_EXPANSION, FileName};
39 use rustc_data_structures::bit_set::BitSet;
40
41 macro_rules! provide {
42     (<$lt:tt> $tcx:ident, $def_id:ident, $other:ident, $cdata:ident,
43       $($name:ident => $compute:block)*) => {
44         pub fn provide_extern<$lt>(providers: &mut Providers<$lt>) {
45             // HACK(eddyb) `$lt: $lt` forces `$lt` to be early-bound, which
46             // allows the associated type in the return type to be normalized.
47             $(fn $name<$lt: $lt, T: IntoArgs>(
48                 $tcx: TyCtxt<$lt>,
49                 def_id_arg: T,
50             ) -> <ty::queries::$name<$lt> as QueryConfig<$lt>>::Value {
51                 #[allow(unused_variables)]
52                 let ($def_id, $other) = def_id_arg.into_args();
53                 assert!(!$def_id.is_local());
54
55                 let def_path_hash = $tcx.def_path_hash(DefId {
56                     krate: $def_id.krate,
57                     index: CRATE_DEF_INDEX
58                 });
59                 let dep_node = def_path_hash
60                     .to_dep_node(rustc::dep_graph::DepKind::CrateMetadata);
61                 // The DepNodeIndex of the DepNode::CrateMetadata should be
62                 // cached somewhere, so that we can use read_index().
63                 $tcx.dep_graph.read(dep_node);
64
65                 let $cdata = $tcx.crate_data_as_rc_any($def_id.krate);
66                 let $cdata = $cdata.downcast_ref::<cstore::CrateMetadata>()
67                     .expect("CrateStore created data is not a CrateMetadata");
68                 $compute
69             })*
70
71             *providers = Providers {
72                 $($name,)*
73                 ..*providers
74             };
75         }
76     }
77 }
78
79 // small trait to work around different signature queries all being defined via
80 // the macro above.
81 trait IntoArgs {
82     fn into_args(self) -> (DefId, DefId);
83 }
84
85 impl IntoArgs for DefId {
86     fn into_args(self) -> (DefId, DefId) { (self, self) }
87 }
88
89 impl IntoArgs for CrateNum {
90     fn into_args(self) -> (DefId, DefId) { (self.as_def_id(), self.as_def_id()) }
91 }
92
93 impl IntoArgs for (CrateNum, DefId) {
94     fn into_args(self) -> (DefId, DefId) { (self.0.as_def_id(), self.1) }
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     predicates_of => { tcx.arena.alloc(cdata.get_predicates(def_id.index, tcx)) }
103     predicates_defined_on => {
104         tcx.arena.alloc(cdata.get_predicates_defined_on(def_id.index, tcx))
105     }
106     super_predicates_of => { tcx.arena.alloc(cdata.get_super_predicates(def_id.index, tcx)) }
107     trait_def => {
108         tcx.arena.alloc(cdata.get_trait_def(def_id.index, tcx.sess))
109     }
110     adt_def => { cdata.get_adt_def(def_id.index, tcx) }
111     adt_destructor => {
112         let _ = cdata;
113         tcx.calculate_dtor(def_id, &mut |_,_| Ok(()))
114     }
115     variances_of => { tcx.arena.alloc_from_iter(cdata.get_item_variances(def_id.index)) }
116     associated_item_def_ids => {
117         let mut result = SmallVec::<[_; 8]>::new();
118         cdata.each_child_of_item(def_id.index,
119           |child| result.push(child.res.def_id()), tcx.sess);
120         tcx.arena.alloc_slice(&result)
121     }
122     associated_item => { cdata.get_associated_item(def_id.index) }
123     impl_trait_ref => { cdata.get_impl_trait(def_id.index, tcx) }
124     impl_polarity => { cdata.get_impl_polarity(def_id.index) }
125     coerce_unsized_info => {
126         cdata.get_coerce_unsized_info(def_id.index).unwrap_or_else(|| {
127             bug!("coerce_unsized_info: `{:?}` is missing its info", def_id);
128         })
129     }
130     optimized_mir => {
131         let mir = cdata.maybe_get_optimized_mir(tcx, def_id.index).unwrap_or_else(|| {
132             bug!("get_optimized_mir: missing MIR for `{:?}`", def_id)
133         });
134
135         let mir = tcx.arena.alloc(mir);
136
137         mir
138     }
139     mir_const_qualif => {
140         (cdata.mir_const_qualif(def_id.index), tcx.arena.alloc(BitSet::new_empty(0)))
141     }
142     fn_sig => { cdata.fn_sig(def_id.index, tcx) }
143     inherent_impls => { cdata.get_inherent_implementations_for_type(tcx, def_id.index) }
144     is_const_fn_raw => { cdata.is_const_fn_raw(def_id.index) }
145     is_foreign_item => { cdata.is_foreign_item(def_id.index) }
146     static_mutability => { cdata.static_mutability(def_id.index) }
147     def_kind => { cdata.def_kind(def_id.index) }
148     def_span => { cdata.get_span(def_id.index, &tcx.sess) }
149     lookup_stability => {
150         cdata.get_stability(def_id.index).map(|s| tcx.intern_stability(s))
151     }
152     lookup_deprecation_entry => {
153         cdata.get_deprecation(def_id.index).map(DeprecationEntry::external)
154     }
155     item_attrs => { cdata.get_item_attrs(def_id.index, tcx.sess) }
156     // FIXME(#38501) We've skipped a `read` on the `HirBody` of
157     // a `fn` when encoding, so the dep-tracking wouldn't work.
158     // This is only used by rustdoc anyway, which shouldn't have
159     // incremental recompilation ever enabled.
160     fn_arg_names => { cdata.get_fn_arg_names(def_id.index) }
161     rendered_const => { cdata.get_rendered_const(def_id.index) }
162     impl_parent => { cdata.get_parent_impl(def_id.index) }
163     trait_of_item => { cdata.get_trait_of_item(def_id.index) }
164     const_is_rvalue_promotable_to_static => {
165         cdata.const_is_rvalue_promotable_to_static(def_id.index)
166     }
167     is_mir_available => { cdata.is_item_mir_available(def_id.index) }
168
169     dylib_dependency_formats => { cdata.get_dylib_dependency_formats(tcx) }
170     is_panic_runtime => { cdata.root.panic_runtime }
171     is_compiler_builtins => { cdata.root.compiler_builtins }
172     has_global_allocator => { cdata.root.has_global_allocator }
173     has_panic_handler => { cdata.root.has_panic_handler }
174     is_sanitizer_runtime => { cdata.root.sanitizer_runtime }
175     is_profiler_runtime => { cdata.root.profiler_runtime }
176     panic_strategy => { cdata.root.panic_strategy }
177     extern_crate => {
178         let r = *cdata.extern_crate.lock();
179         r.map(|c| &*tcx.arena.alloc(c))
180     }
181     is_no_builtins => { cdata.root.no_builtins }
182     symbol_mangling_version => { cdata.root.symbol_mangling_version }
183     impl_defaultness => { cdata.get_impl_defaultness(def_id.index) }
184     reachable_non_generics => {
185         let reachable_non_generics = tcx
186             .exported_symbols(cdata.cnum)
187             .iter()
188             .filter_map(|&(exported_symbol, export_level)| {
189                 if let ExportedSymbol::NonGeneric(def_id) = exported_symbol {
190                     return Some((def_id, export_level))
191                 } else {
192                     None
193                 }
194             })
195             .collect();
196
197         tcx.arena.alloc(reachable_non_generics)
198     }
199     native_libraries => { Lrc::new(cdata.get_native_libraries(tcx.sess)) }
200     foreign_modules => { cdata.get_foreign_modules(tcx) }
201     plugin_registrar_fn => {
202         cdata.root.plugin_registrar_fn.map(|index| {
203             DefId { krate: def_id.krate, index }
204         })
205     }
206     proc_macro_decls_static => {
207         cdata.root.proc_macro_decls_static.map(|index| {
208             DefId { krate: def_id.krate, index }
209         })
210     }
211     crate_disambiguator => { cdata.root.disambiguator }
212     crate_hash => { cdata.root.hash }
213     original_crate_name => { cdata.root.name }
214
215     extra_filename => { cdata.root.extra_filename.clone() }
216
217     implementations_of_trait => {
218         cdata.get_implementations_for_trait(tcx, Some(other))
219     }
220
221     all_trait_implementations => {
222         cdata.get_implementations_for_trait(tcx, None)
223     }
224
225     visibility => { cdata.get_visibility(def_id.index) }
226     dep_kind => {
227         let r = *cdata.dep_kind.lock();
228         r
229     }
230     crate_name => { cdata.name }
231     item_children => {
232         let mut result = SmallVec::<[_; 8]>::new();
233         cdata.each_child_of_item(def_id.index, |child| result.push(child), tcx.sess);
234         tcx.arena.alloc_slice(&result)
235     }
236     defined_lib_features => { cdata.get_lib_features(tcx) }
237     defined_lang_items => { cdata.get_lang_items(tcx) }
238     missing_lang_items => { cdata.get_missing_lang_items(tcx) }
239
240     missing_extern_crate_item => {
241         let r = match *cdata.extern_crate.borrow() {
242             Some(extern_crate) if !extern_crate.direct => true,
243             _ => false,
244         };
245         r
246     }
247
248     used_crate_source => { Lrc::new(cdata.source.clone()) }
249
250     exported_symbols => { Arc::new(cdata.exported_symbols(tcx)) }
251 }
252
253 pub fn provide(providers: &mut Providers<'_>) {
254     // FIXME(#44234) - almost all of these queries have no sub-queries and
255     // therefore no actual inputs, they're just reading tables calculated in
256     // resolve! Does this work? Unsure! That's what the issue is about
257     *providers = Providers {
258         is_dllimport_foreign_item: |tcx, id| {
259             tcx.native_library_kind(id) == Some(NativeLibraryKind::NativeUnknown)
260         },
261         is_statically_included_foreign_item: |tcx, id| {
262             match tcx.native_library_kind(id) {
263                 Some(NativeLibraryKind::NativeStatic) |
264                 Some(NativeLibraryKind::NativeStaticNobundle) => true,
265                 _ => false,
266             }
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::vec_deque::VecDeque;
305             use std::collections::hash_map::Entry;
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 {
339                     krate: cnum,
340                     index: CRATE_DEF_INDEX
341                 });
342             }
343
344             // (restrict scope of mutable-borrow of `visible_parent_map`)
345             {
346                 let visible_parent_map = &mut visible_parent_map;
347                 let mut add_child = |bfs_queue: &mut VecDeque<_>,
348                                      child: &def::Export<hir::HirId>,
349                                      parent: DefId| {
350                     if child.vis != ty::Visibility::Public {
351                         return;
352                     }
353
354                     if let Some(child) = child.res.opt_def_id() {
355                         match visible_parent_map.entry(child) {
356                             Entry::Occupied(mut entry) => {
357                                 // If `child` is defined in crate `cnum`, ensure
358                                 // that it is mapped to a parent in `cnum`.
359                                 if child.krate == cnum && entry.get().krate != cnum {
360                                     entry.insert(parent);
361                                 }
362                             }
363                             Entry::Vacant(entry) => {
364                                 entry.insert(parent);
365                                 bfs_queue.push_back(child);
366                             }
367                         }
368                     }
369                 };
370
371                 while let Some(def) = bfs_queue.pop_front() {
372                     for child in tcx.item_children(def).iter() {
373                         add_child(bfs_queue, child, def);
374                     }
375                 }
376             }
377
378             tcx.arena.alloc(visible_parent_map)
379         },
380
381         ..*providers
382     };
383 }
384
385 impl cstore::CStore {
386     pub fn export_macros_untracked(&self, cnum: CrateNum) {
387         let data = self.get_crate_data(cnum);
388         let mut dep_kind = data.dep_kind.lock();
389         if *dep_kind == DepKind::UnexportedMacrosOnly {
390             *dep_kind = DepKind::MacrosOnly;
391         }
392     }
393
394     pub fn dep_kind_untracked(&self, cnum: CrateNum) -> DepKind {
395         let data = self.get_crate_data(cnum);
396         let r = *data.dep_kind.lock();
397         r
398     }
399
400     pub fn crate_edition_untracked(&self, cnum: CrateNum) -> Edition {
401         self.get_crate_data(cnum).root.edition
402     }
403
404     pub fn struct_field_names_untracked(&self, def: DefId) -> Vec<ast::Name> {
405         self.get_crate_data(def.krate).get_struct_field_names(def.index)
406     }
407
408     pub fn ctor_kind_untracked(&self, def: DefId) -> def::CtorKind {
409         self.get_crate_data(def.krate).get_ctor_kind(def.index)
410     }
411
412     pub fn item_attrs_untracked(&self, def: DefId, sess: &Session) -> Lrc<[ast::Attribute]> {
413         self.get_crate_data(def.krate).get_item_attrs(def.index, sess)
414     }
415
416     pub fn item_children_untracked(
417         &self,
418         def_id: DefId,
419         sess: &Session
420     ) -> Vec<def::Export<hir::HirId>> {
421         let mut result = vec![];
422         self.get_crate_data(def_id.krate)
423             .each_child_of_item(def_id.index, |child| result.push(child), sess);
424         result
425     }
426
427     pub fn load_macro_untracked(&self, id: DefId, sess: &Session) -> LoadedMacro {
428         let data = self.get_crate_data(id.krate);
429         if let Some(ref proc_macros) = data.proc_macros {
430             return LoadedMacro::ProcMacro(proc_macros[id.index.to_proc_macro_index()].1.clone());
431         } else if data.name == sym::proc_macro && data.item_name(id.index) == sym::quote {
432             let client = proc_macro::bridge::client::Client::expand1(proc_macro::quote);
433             let kind = SyntaxExtensionKind::Bang(Box::new(BangProcMacro { client }));
434             let ext = SyntaxExtension {
435                 allow_internal_unstable: Some([sym::proc_macro_def_site][..].into()),
436                 ..SyntaxExtension::default(kind, data.root.edition)
437             };
438             return LoadedMacro::ProcMacro(Lrc::new(ext));
439         }
440
441         let def = data.get_macro(id.index);
442         let macro_full_name = data.def_path(id.index).to_string_friendly(|_| data.imported_name);
443         let source_name = FileName::Macros(macro_full_name);
444
445         let source_file = sess.parse_sess.source_map().new_source_file(source_name, def.body);
446         let local_span = Span::new(source_file.start_pos, source_file.end_pos, NO_EXPANSION);
447         let (body, mut errors) = source_file_to_stream(&sess.parse_sess, source_file, None);
448         emit_unclosed_delims(&mut errors, &sess.diagnostic());
449
450         // Mark the attrs as used
451         let attrs = data.get_item_attrs(id.index, sess);
452         for attr in attrs.iter() {
453             attr::mark_used(attr);
454         }
455
456         let name = data.def_key(id.index).disambiguated_data.data
457             .get_opt_name().expect("no name in load_macro");
458         sess.imported_macro_spans.borrow_mut()
459             .insert(local_span, (name.to_string(), data.get_span(id.index, sess)));
460
461         LoadedMacro::MacroDef(ast::Item {
462             ident: ast::Ident::from_str(&name.as_str()),
463             id: ast::DUMMY_NODE_ID,
464             span: local_span,
465             attrs: attrs.iter().cloned().collect(),
466             node: ast::ItemKind::MacroDef(ast::MacroDef {
467                 tokens: body.into(),
468                 legacy: def.legacy,
469             }),
470             vis: source_map::respan(local_span.shrink_to_lo(), ast::VisibilityKind::Inherited),
471             tokens: None,
472         })
473     }
474
475     pub fn associated_item_cloned_untracked(&self, def: DefId) -> ty::AssocItem {
476         self.get_crate_data(def.krate).get_associated_item(def.index)
477     }
478 }
479
480 impl CrateStore for cstore::CStore {
481     fn crate_data_as_rc_any(&self, krate: CrateNum) -> Lrc<dyn Any> {
482         self.get_crate_data(krate)
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).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         // Note: loading the def-key (or def-path) for a def-id is not
513         // a *read* of its metadata. This is because the def-id is
514         // really just an interned shorthand for a def-path, which is the
515         // canonical name for an item.
516         //
517         // self.dep_graph.read(DepNode::MetaData(def));
518         self.get_crate_data(def.krate).def_key(def.index)
519     }
520
521     fn def_path(&self, def: DefId) -> DefPath {
522         // See `Note` above in `def_key()` for why this read is
523         // commented out:
524         //
525         // self.dep_graph.read(DepNode::MetaData(def));
526         self.get_crate_data(def.krate).def_path(def.index)
527     }
528
529     fn def_path_hash(&self, def: DefId) -> DefPathHash {
530         self.get_crate_data(def.krate).def_path_hash(def.index)
531     }
532
533     fn def_path_table(&self, cnum: CrateNum) -> Lrc<DefPathTable> {
534         self.get_crate_data(cnum).def_path_table.clone()
535     }
536
537     fn crates_untracked(&self) -> Vec<CrateNum>
538     {
539         let mut result = vec![];
540         self.iter_crate_data(|cnum, _| result.push(cnum));
541         result
542     }
543
544     fn extern_mod_stmt_cnum_untracked(&self, emod_id: ast::NodeId) -> Option<CrateNum>
545     {
546         self.do_extern_mod_stmt_cnum(emod_id)
547     }
548
549     fn postorder_cnums_untracked(&self) -> Vec<CrateNum> {
550         self.do_postorder_cnums_untracked()
551     }
552
553     fn encode_metadata(&self, tcx: TyCtxt<'_>) -> EncodedMetadata {
554         encoder::encode_metadata(tcx)
555     }
556
557     fn metadata_encoding_version(&self) -> &[u8]
558     {
559         schema::METADATA_HEADER
560     }
561 }