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