]> git.lizzy.rs Git - rust.git/blob - src/librustc_metadata/rmeta/decoder/cstore_impl.rs
Unconfuse Unpin docs a bit
[rust.git] / src / librustc_metadata / rmeta / decoder / cstore_impl.rs
1 use crate::creader::{CStore, LoadedMacro};
2 use crate::foreign_modules;
3 use crate::link_args;
4 use crate::native_libs;
5 use crate::rmeta::{self, encoder};
6
7 use rustc_ast as ast;
8 use rustc_ast::expand::allocator::AllocatorKind;
9 use rustc_data_structures::svh::Svh;
10 use rustc_hir as hir;
11 use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, CRATE_DEF_INDEX, LOCAL_CRATE};
12 use rustc_hir::definitions::DefPathTable;
13 use rustc_hir::definitions::{DefKey, DefPath, DefPathHash};
14 use rustc_middle::hir::exports::Export;
15 use rustc_middle::middle::cstore::{CrateSource, CrateStore, EncodedMetadata};
16 use rustc_middle::middle::exported_symbols::ExportedSymbol;
17 use rustc_middle::middle::stability::DeprecationEntry;
18 use rustc_middle::ty::query::Providers;
19 use rustc_middle::ty::{self, TyCtxt};
20 use rustc_session::utils::NativeLibKind;
21 use rustc_session::{CrateDisambiguator, Session};
22 use rustc_span::source_map::{self, Span, Spanned};
23 use rustc_span::symbol::Symbol;
24
25 use rustc_data_structures::sync::Lrc;
26 use rustc_span::ExpnId;
27 use smallvec::SmallVec;
28 use std::any::Any;
29
30 macro_rules! provide {
31     (<$lt:tt> $tcx:ident, $def_id:ident, $other:ident, $cdata:ident,
32       $($name:ident => $compute:block)*) => {
33         pub fn provide_extern(providers: &mut Providers) {
34             $(fn $name<$lt>(
35                 $tcx: TyCtxt<$lt>,
36                 def_id_arg: ty::query::query_keys::$name<$lt>,
37             ) -> ty::query::query_values::$name<$lt> {
38                 let _prof_timer =
39                     $tcx.prof.generic_activity(concat!("metadata_decode_entry_", stringify!($name)));
40
41                 #[allow(unused_variables)]
42                 let ($def_id, $other) = def_id_arg.into_args();
43                 assert!(!$def_id.is_local());
44
45                 let $cdata = CStore::from_tcx($tcx).get_crate_data($def_id.krate);
46
47                 if $tcx.dep_graph.is_fully_enabled() {
48                     let crate_dep_node_index = $cdata.get_crate_dep_node_index($tcx);
49                     $tcx.dep_graph.read_index(crate_dep_node_index);
50                 }
51
52                 $compute
53             })*
54
55             *providers = Providers {
56                 $($name,)*
57                 ..*providers
58             };
59         }
60     }
61 }
62
63 // small trait to work around different signature queries all being defined via
64 // the macro above.
65 trait IntoArgs {
66     fn into_args(self) -> (DefId, DefId);
67 }
68
69 impl IntoArgs for DefId {
70     fn into_args(self) -> (DefId, DefId) {
71         (self, self)
72     }
73 }
74
75 impl IntoArgs for CrateNum {
76     fn into_args(self) -> (DefId, DefId) {
77         (self.as_def_id(), self.as_def_id())
78     }
79 }
80
81 impl IntoArgs for (CrateNum, DefId) {
82     fn into_args(self) -> (DefId, DefId) {
83         (self.0.as_def_id(), self.1)
84     }
85 }
86
87 provide! { <'tcx> tcx, def_id, other, cdata,
88     type_of => { cdata.get_type(def_id.index, tcx) }
89     generics_of => { cdata.get_generics(def_id.index, tcx.sess) }
90     explicit_predicates_of => { cdata.get_explicit_predicates(def_id.index, tcx) }
91     inferred_outlives_of => { cdata.get_inferred_outlives(def_id.index, tcx) }
92     super_predicates_of => { cdata.get_super_predicates(def_id.index, tcx) }
93     trait_def => { cdata.get_trait_def(def_id.index, tcx.sess) }
94     adt_def => { cdata.get_adt_def(def_id.index, tcx) }
95     adt_destructor => {
96         let _ = cdata;
97         tcx.calculate_dtor(def_id, &mut |_,_| Ok(()))
98     }
99     variances_of => { tcx.arena.alloc_from_iter(cdata.get_item_variances(def_id.index)) }
100     associated_item_def_ids => {
101         let mut result = SmallVec::<[_; 8]>::new();
102         cdata.each_child_of_item(def_id.index,
103           |child| result.push(child.res.def_id()), tcx.sess);
104         tcx.arena.alloc_slice(&result)
105     }
106     associated_item => { cdata.get_associated_item(def_id.index, tcx.sess) }
107     impl_trait_ref => { cdata.get_impl_trait(def_id.index, tcx) }
108     impl_polarity => { cdata.get_impl_polarity(def_id.index) }
109     coerce_unsized_info => {
110         cdata.get_coerce_unsized_info(def_id.index).unwrap_or_else(|| {
111             bug!("coerce_unsized_info: `{:?}` is missing its info", def_id);
112         })
113     }
114     optimized_mir => { tcx.arena.alloc(cdata.get_optimized_mir(tcx, def_id.index)) }
115     promoted_mir => { tcx.arena.alloc(cdata.get_promoted_mir(tcx, def_id.index)) }
116     unused_generic_params => { cdata.get_unused_generic_params(def_id.index) }
117     mir_const_qualif => { cdata.mir_const_qualif(def_id.index) }
118     fn_sig => { cdata.fn_sig(def_id.index, tcx) }
119     inherent_impls => { cdata.get_inherent_implementations_for_type(tcx, def_id.index) }
120     is_const_fn_raw => { cdata.is_const_fn_raw(def_id.index) }
121     asyncness => { cdata.asyncness(def_id.index) }
122     is_foreign_item => { cdata.is_foreign_item(def_id.index) }
123     static_mutability => { cdata.static_mutability(def_id.index) }
124     generator_kind => { cdata.generator_kind(def_id.index) }
125     def_kind => { cdata.def_kind(def_id.index) }
126     def_span => { cdata.get_span(def_id.index, &tcx.sess) }
127     lookup_stability => {
128         cdata.get_stability(def_id.index).map(|s| tcx.intern_stability(s))
129     }
130     lookup_const_stability => {
131         cdata.get_const_stability(def_id.index).map(|s| tcx.intern_const_stability(s))
132     }
133     lookup_deprecation_entry => {
134         cdata.get_deprecation(def_id.index).map(DeprecationEntry::external)
135     }
136     item_attrs => { tcx.arena.alloc_from_iter(
137         cdata.get_item_attrs(def_id.index, tcx.sess).into_iter()
138     ) }
139     fn_arg_names => { cdata.get_fn_param_names(tcx, def_id.index) }
140     rendered_const => { cdata.get_rendered_const(def_id.index) }
141     impl_parent => { cdata.get_parent_impl(def_id.index) }
142     trait_of_item => { cdata.get_trait_of_item(def_id.index) }
143     is_mir_available => { cdata.is_item_mir_available(def_id.index) }
144
145     dylib_dependency_formats => { cdata.get_dylib_dependency_formats(tcx) }
146     is_panic_runtime => { cdata.root.panic_runtime }
147     is_compiler_builtins => { cdata.root.compiler_builtins }
148     has_global_allocator => { cdata.root.has_global_allocator }
149     has_panic_handler => { cdata.root.has_panic_handler }
150     is_profiler_runtime => { cdata.root.profiler_runtime }
151     panic_strategy => { cdata.root.panic_strategy }
152     extern_crate => {
153         let r = *cdata.extern_crate.lock();
154         r.map(|c| &*tcx.arena.alloc(c))
155     }
156     is_no_builtins => { cdata.root.no_builtins }
157     symbol_mangling_version => { cdata.root.symbol_mangling_version }
158     impl_defaultness => { cdata.get_impl_defaultness(def_id.index) }
159     reachable_non_generics => {
160         let reachable_non_generics = tcx
161             .exported_symbols(cdata.cnum)
162             .iter()
163             .filter_map(|&(exported_symbol, export_level)| {
164                 if let ExportedSymbol::NonGeneric(def_id) = exported_symbol {
165                     Some((def_id, export_level))
166                 } else {
167                     None
168                 }
169             })
170             .collect();
171
172         reachable_non_generics
173     }
174     native_libraries => { Lrc::new(cdata.get_native_libraries(tcx.sess)) }
175     foreign_modules => { cdata.get_foreign_modules(tcx) }
176     plugin_registrar_fn => {
177         cdata.root.plugin_registrar_fn.map(|index| {
178             DefId { krate: def_id.krate, index }
179         })
180     }
181     proc_macro_decls_static => {
182         cdata.root.proc_macro_decls_static.map(|index| {
183             DefId { krate: def_id.krate, index }
184         })
185     }
186     crate_disambiguator => { cdata.root.disambiguator }
187     crate_hash => { cdata.root.hash }
188     crate_host_hash => { cdata.host_hash }
189     original_crate_name => { cdata.root.name }
190
191     extra_filename => { cdata.root.extra_filename.clone() }
192
193     implementations_of_trait => {
194         cdata.get_implementations_for_trait(tcx, Some(other))
195     }
196
197     all_trait_implementations => {
198         cdata.get_implementations_for_trait(tcx, None)
199     }
200
201     visibility => { cdata.get_visibility(def_id.index) }
202     dep_kind => {
203         let r = *cdata.dep_kind.lock();
204         r
205     }
206     crate_name => { cdata.root.name }
207     item_children => {
208         let mut result = SmallVec::<[_; 8]>::new();
209         cdata.each_child_of_item(def_id.index, |child| result.push(child), tcx.sess);
210         tcx.arena.alloc_slice(&result)
211     }
212     defined_lib_features => { cdata.get_lib_features(tcx) }
213     defined_lang_items => { cdata.get_lang_items(tcx) }
214     diagnostic_items => { cdata.get_diagnostic_items() }
215     missing_lang_items => { cdata.get_missing_lang_items(tcx) }
216
217     missing_extern_crate_item => {
218         let r = match *cdata.extern_crate.borrow() {
219             Some(extern_crate) if !extern_crate.is_direct() => true,
220             _ => false,
221         };
222         r
223     }
224
225     used_crate_source => { Lrc::new(cdata.source.clone()) }
226
227     exported_symbols => {
228         let syms = cdata.exported_symbols(tcx);
229
230         // FIXME rust-lang/rust#64319, rust-lang/rust#64872: We want
231         // to block export of generics from dylibs, but we must fix
232         // rust-lang/rust#65890 before we can do that robustly.
233
234         syms
235     }
236
237     crate_extern_paths => { cdata.source().paths().cloned().collect() }
238 }
239
240 pub fn provide(providers: &mut Providers) {
241     // FIXME(#44234) - almost all of these queries have no sub-queries and
242     // therefore no actual inputs, they're just reading tables calculated in
243     // resolve! Does this work? Unsure! That's what the issue is about
244     *providers = Providers {
245         is_dllimport_foreign_item: |tcx, id| match tcx.native_library_kind(id) {
246             Some(NativeLibKind::Dylib | NativeLibKind::RawDylib | NativeLibKind::Unspecified) => {
247                 true
248             }
249             _ => false,
250         },
251         is_statically_included_foreign_item: |tcx, id| match tcx.native_library_kind(id) {
252             Some(NativeLibKind::StaticBundle | NativeLibKind::StaticNoBundle) => true,
253             _ => false,
254         },
255         native_library_kind: |tcx, id| {
256             tcx.native_libraries(id.krate)
257                 .iter()
258                 .filter(|lib| native_libs::relevant_lib(&tcx.sess, lib))
259                 .find(|lib| {
260                     let fm_id = match lib.foreign_module {
261                         Some(id) => id,
262                         None => return false,
263                     };
264                     tcx.foreign_modules(id.krate)
265                         .iter()
266                         .find(|m| m.def_id == fm_id)
267                         .expect("failed to find foreign module")
268                         .foreign_items
269                         .contains(&id)
270                 })
271                 .map(|l| l.kind)
272         },
273         native_libraries: |tcx, cnum| {
274             assert_eq!(cnum, LOCAL_CRATE);
275             Lrc::new(native_libs::collect(tcx))
276         },
277         foreign_modules: |tcx, cnum| {
278             assert_eq!(cnum, LOCAL_CRATE);
279             &tcx.arena.alloc(foreign_modules::collect(tcx))[..]
280         },
281         link_args: |tcx, cnum| {
282             assert_eq!(cnum, LOCAL_CRATE);
283             Lrc::new(link_args::collect(tcx))
284         },
285
286         // Returns a map from a sufficiently visible external item (i.e., an
287         // external item that is visible from at least one local module) to a
288         // sufficiently visible parent (considering modules that re-export the
289         // external item to be parents).
290         visible_parent_map: |tcx, cnum| {
291             use std::collections::hash_map::Entry;
292             use std::collections::vec_deque::VecDeque;
293
294             assert_eq!(cnum, LOCAL_CRATE);
295             let mut visible_parent_map: DefIdMap<DefId> = Default::default();
296
297             // Issue 46112: We want the map to prefer the shortest
298             // paths when reporting the path to an item. Therefore we
299             // build up the map via a breadth-first search (BFS),
300             // which naturally yields minimal-length paths.
301             //
302             // Note that it needs to be a BFS over the whole forest of
303             // crates, not just each individual crate; otherwise you
304             // only get paths that are locally minimal with respect to
305             // whatever crate we happened to encounter first in this
306             // traversal, but not globally minimal across all crates.
307             let bfs_queue = &mut VecDeque::new();
308
309             // Preferring shortest paths alone does not guarantee a
310             // deterministic result; so sort by crate num to avoid
311             // hashtable iteration non-determinism. This only makes
312             // things as deterministic as crate-nums assignment is,
313             // which is to say, its not deterministic in general. But
314             // we believe that libstd is consistently assigned crate
315             // num 1, so it should be enough to resolve #46112.
316             let mut crates: Vec<CrateNum> = (*tcx.crates()).to_owned();
317             crates.sort();
318
319             for &cnum in crates.iter() {
320                 // Ignore crates without a corresponding local `extern crate` item.
321                 if tcx.missing_extern_crate_item(cnum) {
322                     continue;
323                 }
324
325                 bfs_queue.push_back(DefId { krate: cnum, index: CRATE_DEF_INDEX });
326             }
327
328             // (restrict scope of mutable-borrow of `visible_parent_map`)
329             {
330                 let visible_parent_map = &mut visible_parent_map;
331                 let mut add_child =
332                     |bfs_queue: &mut VecDeque<_>, child: &Export<hir::HirId>, parent: DefId| {
333                         if child.vis != ty::Visibility::Public {
334                             return;
335                         }
336
337                         if let Some(child) = child.res.opt_def_id() {
338                             match visible_parent_map.entry(child) {
339                                 Entry::Occupied(mut entry) => {
340                                     // If `child` is defined in crate `cnum`, ensure
341                                     // that it is mapped to a parent in `cnum`.
342                                     if child.krate == cnum && entry.get().krate != cnum {
343                                         entry.insert(parent);
344                                     }
345                                 }
346                                 Entry::Vacant(entry) => {
347                                     entry.insert(parent);
348                                     bfs_queue.push_back(child);
349                                 }
350                             }
351                         }
352                     };
353
354                 while let Some(def) = bfs_queue.pop_front() {
355                     for child in tcx.item_children(def).iter() {
356                         add_child(bfs_queue, child, def);
357                     }
358                 }
359             }
360
361             visible_parent_map
362         },
363
364         dependency_formats: |tcx, cnum| {
365             assert_eq!(cnum, LOCAL_CRATE);
366             Lrc::new(crate::dependency_format::calculate(tcx))
367         },
368         has_global_allocator: |tcx, cnum| {
369             assert_eq!(cnum, LOCAL_CRATE);
370             CStore::from_tcx(tcx).has_global_allocator()
371         },
372         postorder_cnums: |tcx, cnum| {
373             assert_eq!(cnum, LOCAL_CRATE);
374             tcx.arena.alloc_slice(&CStore::from_tcx(tcx).crate_dependencies_in_postorder(cnum))
375         },
376
377         ..*providers
378     };
379 }
380
381 impl CStore {
382     pub fn struct_field_names_untracked(&self, def: DefId, sess: &Session) -> Vec<Spanned<Symbol>> {
383         self.get_crate_data(def.krate).get_struct_field_names(def.index, sess)
384     }
385
386     pub fn item_children_untracked(
387         &self,
388         def_id: DefId,
389         sess: &Session,
390     ) -> Vec<Export<hir::HirId>> {
391         let mut result = vec![];
392         self.get_crate_data(def_id.krate).each_child_of_item(
393             def_id.index,
394             |child| result.push(child),
395             sess,
396         );
397         result
398     }
399
400     pub fn load_macro_untracked(&self, id: DefId, sess: &Session) -> LoadedMacro {
401         let _prof_timer = sess.prof.generic_activity("metadata_load_macro");
402
403         let data = self.get_crate_data(id.krate);
404         if data.root.is_proc_macro_crate() {
405             return LoadedMacro::ProcMacro(data.load_proc_macro(id.index, sess));
406         }
407
408         let span = data.get_span(id.index, sess);
409
410         // Mark the attrs as used
411         let attrs = data.get_item_attrs(id.index, sess);
412         for attr in attrs.iter() {
413             sess.mark_attr_used(attr);
414         }
415
416         let ident = data.item_ident(id.index, sess);
417
418         LoadedMacro::MacroDef(
419             ast::Item {
420                 ident,
421                 id: ast::DUMMY_NODE_ID,
422                 span,
423                 attrs: attrs.to_vec(),
424                 kind: ast::ItemKind::MacroDef(data.get_macro(id.index, sess)),
425                 vis: source_map::respan(span.shrink_to_lo(), ast::VisibilityKind::Inherited),
426                 tokens: None,
427             },
428             data.root.edition,
429         )
430     }
431
432     pub fn associated_item_cloned_untracked(&self, def: DefId, sess: &Session) -> ty::AssocItem {
433         self.get_crate_data(def.krate).get_associated_item(def.index, sess)
434     }
435
436     pub fn crate_source_untracked(&self, cnum: CrateNum) -> CrateSource {
437         self.get_crate_data(cnum).source.clone()
438     }
439
440     pub fn get_span_untracked(&self, def_id: DefId, sess: &Session) -> Span {
441         self.get_crate_data(def_id.krate).get_span(def_id.index, sess)
442     }
443
444     pub fn item_generics_num_lifetimes(&self, def_id: DefId, sess: &Session) -> usize {
445         self.get_crate_data(def_id.krate).get_generics(def_id.index, sess).own_counts().lifetimes
446     }
447
448     pub fn module_expansion_untracked(&self, def_id: DefId, sess: &Session) -> ExpnId {
449         self.get_crate_data(def_id.krate).module_expansion(def_id.index, sess)
450     }
451 }
452
453 impl CrateStore for CStore {
454     fn as_any(&self) -> &dyn Any {
455         self
456     }
457
458     fn crate_name_untracked(&self, cnum: CrateNum) -> Symbol {
459         self.get_crate_data(cnum).root.name
460     }
461
462     fn crate_is_private_dep_untracked(&self, cnum: CrateNum) -> bool {
463         self.get_crate_data(cnum).private_dep
464     }
465
466     fn crate_disambiguator_untracked(&self, cnum: CrateNum) -> CrateDisambiguator {
467         self.get_crate_data(cnum).root.disambiguator
468     }
469
470     fn crate_hash_untracked(&self, cnum: CrateNum) -> Svh {
471         self.get_crate_data(cnum).root.hash
472     }
473
474     /// Returns the `DefKey` for a given `DefId`. This indicates the
475     /// parent `DefId` as well as some idea of what kind of data the
476     /// `DefId` refers to.
477     fn def_key(&self, def: DefId) -> DefKey {
478         self.get_crate_data(def.krate).def_key(def.index)
479     }
480
481     fn def_path(&self, def: DefId) -> DefPath {
482         self.get_crate_data(def.krate).def_path(def.index)
483     }
484
485     fn def_path_hash(&self, def: DefId) -> DefPathHash {
486         self.get_crate_data(def.krate).def_path_hash(def.index)
487     }
488
489     fn def_path_table(&self, cnum: CrateNum) -> &DefPathTable {
490         &self.get_crate_data(cnum).cdata.def_path_table
491     }
492
493     fn crates_untracked(&self) -> Vec<CrateNum> {
494         let mut result = vec![];
495         self.iter_crate_data(|cnum, _| result.push(cnum));
496         result
497     }
498
499     fn encode_metadata(&self, tcx: TyCtxt<'_>) -> EncodedMetadata {
500         encoder::encode_metadata(tcx)
501     }
502
503     fn metadata_encoding_version(&self) -> &[u8] {
504         rmeta::METADATA_HEADER
505     }
506
507     fn allocator_kind(&self) -> Option<AllocatorKind> {
508         self.allocator_kind()
509     }
510 }