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