]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs
rustc_expand: Remove redundant field from proc macro expander structures
[rust.git] / compiler / rustc_metadata / src / rmeta / decoder / cstore_impl.rs
1 use crate::creader::{CStore, LoadedMacro};
2 use crate::foreign_modules;
3 use crate::native_libs;
4 use crate::rmeta::encoder;
5
6 use rustc_ast as ast;
7 use rustc_data_structures::stable_map::FxHashMap;
8 use rustc_data_structures::svh::Svh;
9 use rustc_hir as hir;
10 use rustc_hir::def::{CtorKind, DefKind};
11 use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, CRATE_DEF_INDEX, LOCAL_CRATE};
12 use rustc_hir::definitions::{DefKey, DefPath, DefPathHash};
13 use rustc_middle::hir::exports::Export;
14 use rustc_middle::middle::cstore::ForeignModule;
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, Visibility};
20 use rustc_session::utils::NativeLibKind;
21 use rustc_session::{Session, StableCrateId};
22 use rustc_span::source_map::{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                 // External query providers call `crate_hash` in order to register a dependency
46                 // on the crate metadata. The exception is `crate_hash` itself, which obviously
47                 // doesn't need to do this (and can't, as it would cause a query cycle).
48                 use rustc_middle::dep_graph::DepKind;
49                 if DepKind::$name != DepKind::crate_hash && $tcx.dep_graph.is_fully_enabled() {
50                     $tcx.ensure().crate_hash($def_id.krate);
51                 }
52
53                 let $cdata = CStore::from_tcx($tcx).get_crate_data($def_id.krate);
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 => { cdata.get_generics(def_id.index, tcx.sess) }
93     explicit_predicates_of => { cdata.get_explicit_predicates(def_id.index, tcx) }
94     inferred_outlives_of => { cdata.get_inferred_outlives(def_id.index, tcx) }
95     super_predicates_of => { cdata.get_super_predicates(def_id.index, tcx) }
96     explicit_item_bounds => { cdata.get_explicit_item_bounds(def_id.index, tcx) }
97     trait_def => { cdata.get_trait_def(def_id.index, tcx.sess) }
98     adt_def => { cdata.get_adt_def(def_id.index, tcx) }
99     adt_destructor => {
100         let _ = cdata;
101         tcx.calculate_dtor(def_id, |_,_| Ok(()))
102     }
103     variances_of => { tcx.arena.alloc_from_iter(cdata.get_item_variances(def_id.index)) }
104     associated_item_def_ids => {
105         let mut result = SmallVec::<[_; 8]>::new();
106         cdata.each_child_of_item(def_id.index,
107           |child| result.push(child.res.def_id()), tcx.sess);
108         tcx.arena.alloc_slice(&result)
109     }
110     associated_item => { cdata.get_associated_item(def_id.index, tcx.sess) }
111     impl_trait_ref => { cdata.get_impl_trait(def_id.index, tcx) }
112     impl_polarity => { cdata.get_impl_polarity(def_id.index) }
113     coerce_unsized_info => {
114         cdata.get_coerce_unsized_info(def_id.index).unwrap_or_else(|| {
115             bug!("coerce_unsized_info: `{:?}` is missing its info", def_id);
116         })
117     }
118     optimized_mir => { tcx.arena.alloc(cdata.get_optimized_mir(tcx, def_id.index)) }
119     mir_for_ctfe => { tcx.arena.alloc(cdata.get_mir_for_ctfe(tcx, def_id.index)) }
120     promoted_mir => { tcx.arena.alloc(cdata.get_promoted_mir(tcx, def_id.index)) }
121     mir_abstract_const => { cdata.get_mir_abstract_const(tcx, def_id.index) }
122     unused_generic_params => { cdata.get_unused_generic_params(def_id.index) }
123     const_param_default => { tcx.mk_const(cdata.get_const_param_default(tcx, def_id.index)) }
124     mir_const_qualif => { cdata.mir_const_qualif(def_id.index) }
125     fn_sig => { cdata.fn_sig(def_id.index, tcx) }
126     inherent_impls => { cdata.get_inherent_implementations_for_type(tcx, def_id.index) }
127     is_const_fn_raw => { cdata.is_const_fn_raw(def_id.index) }
128     asyncness => { cdata.asyncness(def_id.index) }
129     is_foreign_item => { cdata.is_foreign_item(def_id.index) }
130     static_mutability => { cdata.static_mutability(def_id.index) }
131     generator_kind => { cdata.generator_kind(def_id.index) }
132     opt_def_kind => { Some(cdata.def_kind(def_id.index)) }
133     def_span => { cdata.get_span(def_id.index, &tcx.sess) }
134     def_ident_span => {
135         cdata.try_item_ident(def_id.index, &tcx.sess).ok().map(|ident| ident.span)
136     }
137     lookup_stability => {
138         cdata.get_stability(def_id.index).map(|s| tcx.intern_stability(s))
139     }
140     lookup_const_stability => {
141         cdata.get_const_stability(def_id.index).map(|s| tcx.intern_const_stability(s))
142     }
143     lookup_deprecation_entry => {
144         cdata.get_deprecation(def_id.index).map(DeprecationEntry::external)
145     }
146     item_attrs => { tcx.arena.alloc_from_iter(
147         cdata.get_item_attrs(def_id.index, tcx.sess)
148     ) }
149     fn_arg_names => { cdata.get_fn_param_names(tcx, 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     is_ctfe_mir_available => { cdata.is_ctfe_mir_available(def_id.index) }
155
156     dylib_dependency_formats => { cdata.get_dylib_dependency_formats(tcx) }
157     is_private_dep => { cdata.private_dep }
158     is_panic_runtime => { cdata.root.panic_runtime }
159     is_compiler_builtins => { cdata.root.compiler_builtins }
160     has_global_allocator => { cdata.root.has_global_allocator }
161     has_panic_handler => { cdata.root.has_panic_handler }
162     is_profiler_runtime => { cdata.root.profiler_runtime }
163     panic_strategy => { cdata.root.panic_strategy }
164     extern_crate => {
165         let r = *cdata.extern_crate.lock();
166         r.map(|c| &*tcx.arena.alloc(c))
167     }
168     is_no_builtins => { cdata.root.no_builtins }
169     symbol_mangling_version => { cdata.root.symbol_mangling_version }
170     impl_defaultness => { cdata.get_impl_defaultness(def_id.index) }
171     reachable_non_generics => {
172         let reachable_non_generics = tcx
173             .exported_symbols(cdata.cnum)
174             .iter()
175             .filter_map(|&(exported_symbol, export_level)| {
176                 if let ExportedSymbol::NonGeneric(def_id) = exported_symbol {
177                     Some((def_id, export_level))
178                 } else {
179                     None
180                 }
181             })
182             .collect();
183
184         reachable_non_generics
185     }
186     native_libraries => { Lrc::new(cdata.get_native_libraries(tcx.sess)) }
187     foreign_modules => { cdata.get_foreign_modules(tcx) }
188     crate_hash => { cdata.root.hash }
189     crate_host_hash => { cdata.host_hash }
190     crate_name => { cdata.root.name }
191
192     extra_filename => { cdata.root.extra_filename.clone() }
193
194     implementations_of_trait => {
195         cdata.get_implementations_for_trait(tcx, Some(other))
196     }
197
198     all_trait_implementations => {
199         cdata.get_implementations_for_trait(tcx, None)
200     }
201
202     visibility => { cdata.get_visibility(def_id.index) }
203     dep_kind => {
204         let r = *cdata.dep_kind.lock();
205         r
206     }
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 = matches!(*cdata.extern_crate.borrow(), Some(extern_crate) if !extern_crate.is_direct());
219         r
220     }
221
222     used_crate_source => { Lrc::new(cdata.source.clone()) }
223
224     exported_symbols => {
225         let syms = cdata.exported_symbols(tcx);
226
227         // FIXME rust-lang/rust#64319, rust-lang/rust#64872: We want
228         // to block export of generics from dylibs, but we must fix
229         // rust-lang/rust#65890 before we can do that robustly.
230
231         syms
232     }
233
234     crate_extern_paths => { cdata.source().paths().cloned().collect() }
235     expn_that_defined => { cdata.get_expn_that_defined(def_id.index, tcx.sess) }
236 }
237
238 pub fn provide(providers: &mut Providers) {
239     // FIXME(#44234) - almost all of these queries have no sub-queries and
240     // therefore no actual inputs, they're just reading tables calculated in
241     // resolve! Does this work? Unsure! That's what the issue is about
242     *providers = Providers {
243         allocator_kind: |tcx, ()| CStore::from_tcx(tcx).allocator_kind(),
244         is_dllimport_foreign_item: |tcx, id| match tcx.native_library_kind(id) {
245             Some(
246                 NativeLibKind::Dylib { .. } | NativeLibKind::RawDylib | NativeLibKind::Unspecified,
247             ) => true,
248             _ => false,
249         },
250         is_statically_included_foreign_item: |tcx, id| {
251             matches!(tcx.native_library_kind(id), Some(NativeLibKind::Static { .. }))
252         },
253         is_private_dep: |_tcx, cnum| {
254             assert_eq!(cnum, LOCAL_CRATE);
255             false
256         },
257         native_library_kind: |tcx, id| {
258             tcx.native_libraries(id.krate)
259                 .iter()
260                 .filter(|lib| native_libs::relevant_lib(&tcx.sess, lib))
261                 .find(|lib| {
262                     let fm_id = match lib.foreign_module {
263                         Some(id) => id,
264                         None => return false,
265                     };
266                     let map = tcx.foreign_modules(id.krate);
267                     map.get(&fm_id)
268                         .expect("failed to find foreign module")
269                         .foreign_items
270                         .contains(&id)
271                 })
272                 .map(|l| l.kind)
273         },
274         native_libraries: |tcx, cnum| {
275             assert_eq!(cnum, LOCAL_CRATE);
276             Lrc::new(native_libs::collect(tcx))
277         },
278         foreign_modules: |tcx, cnum| {
279             assert_eq!(cnum, LOCAL_CRATE);
280             let modules: FxHashMap<DefId, ForeignModule> =
281                 foreign_modules::collect(tcx).into_iter().map(|m| (m.def_id, m)).collect();
282             Lrc::new(modules)
283         },
284
285         // Returns a map from a sufficiently visible external item (i.e., an
286         // external item that is visible from at least one local module) to a
287         // sufficiently visible parent (considering modules that re-export the
288         // external item to be parents).
289         visible_parent_map: |tcx, ()| {
290             use std::collections::hash_map::Entry;
291             use std::collections::vec_deque::VecDeque;
292
293             let mut visible_parent_map: DefIdMap<DefId> = Default::default();
294
295             // Issue 46112: We want the map to prefer the shortest
296             // paths when reporting the path to an item. Therefore we
297             // build up the map via a breadth-first search (BFS),
298             // which naturally yields minimal-length paths.
299             //
300             // Note that it needs to be a BFS over the whole forest of
301             // crates, not just each individual crate; otherwise you
302             // only get paths that are locally minimal with respect to
303             // whatever crate we happened to encounter first in this
304             // traversal, but not globally minimal across all crates.
305             let bfs_queue = &mut VecDeque::new();
306
307             // Preferring shortest paths alone does not guarantee a
308             // deterministic result; so sort by crate num to avoid
309             // hashtable iteration non-determinism. This only makes
310             // things as deterministic as crate-nums assignment is,
311             // which is to say, its not deterministic in general. But
312             // we believe that libstd is consistently assigned crate
313             // num 1, so it should be enough to resolve #46112.
314             let mut crates: Vec<CrateNum> = (*tcx.crates(())).to_owned();
315             crates.sort();
316
317             for &cnum in crates.iter() {
318                 // Ignore crates without a corresponding local `extern crate` item.
319                 if tcx.missing_extern_crate_item(cnum) {
320                     continue;
321                 }
322
323                 bfs_queue.push_back(DefId { krate: cnum, index: CRATE_DEF_INDEX });
324             }
325
326             // (restrict scope of mutable-borrow of `visible_parent_map`)
327             {
328                 let visible_parent_map = &mut visible_parent_map;
329                 let mut add_child =
330                     |bfs_queue: &mut VecDeque<_>, child: &Export<hir::HirId>, parent: DefId| {
331                         if child.vis != ty::Visibility::Public {
332                             return;
333                         }
334
335                         if let Some(child) = child.res.opt_def_id() {
336                             match visible_parent_map.entry(child) {
337                                 Entry::Occupied(mut entry) => {
338                                     // If `child` is defined in crate `cnum`, ensure
339                                     // that it is mapped to a parent in `cnum`.
340                                     if child.is_local() && entry.get().is_local() {
341                                         entry.insert(parent);
342                                     }
343                                 }
344                                 Entry::Vacant(entry) => {
345                                     entry.insert(parent);
346                                     bfs_queue.push_back(child);
347                                 }
348                             }
349                         }
350                     };
351
352                 while let Some(def) = bfs_queue.pop_front() {
353                     for child in tcx.item_children(def).iter() {
354                         add_child(bfs_queue, child, def);
355                     }
356                 }
357             }
358
359             visible_parent_map
360         },
361
362         dependency_formats: |tcx, ()| Lrc::new(crate::dependency_format::calculate(tcx)),
363         has_global_allocator: |tcx, cnum| {
364             assert_eq!(cnum, LOCAL_CRATE);
365             CStore::from_tcx(tcx).has_global_allocator()
366         },
367         postorder_cnums: |tcx, ()| {
368             tcx.arena
369                 .alloc_slice(&CStore::from_tcx(tcx).crate_dependencies_in_postorder(LOCAL_CRATE))
370         },
371
372         ..*providers
373     };
374 }
375
376 impl CStore {
377     pub fn struct_field_names_untracked(&self, def: DefId, sess: &Session) -> Vec<Spanned<Symbol>> {
378         self.get_crate_data(def.krate).get_struct_field_names(def.index, sess)
379     }
380
381     pub fn struct_field_visibilities_untracked(&self, def: DefId) -> Vec<Visibility> {
382         self.get_crate_data(def.krate).get_struct_field_visibilities(def.index)
383     }
384
385     pub fn ctor_def_id_and_kind_untracked(&self, def: DefId) -> Option<(DefId, CtorKind)> {
386         self.get_crate_data(def.krate).get_ctor_def_id(def.index).map(|ctor_def_id| {
387             (ctor_def_id, self.get_crate_data(def.krate).get_ctor_kind(def.index))
388         })
389     }
390
391     pub fn visibility_untracked(&self, def: DefId) -> Visibility {
392         self.get_crate_data(def.krate).get_visibility(def.index)
393     }
394
395     pub fn item_children_untracked(
396         &self,
397         def_id: DefId,
398         sess: &Session,
399     ) -> Vec<Export<hir::HirId>> {
400         let mut result = vec![];
401         self.get_crate_data(def_id.krate).each_child_of_item(
402             def_id.index,
403             |child| result.push(child),
404             sess,
405         );
406         result
407     }
408
409     pub fn load_macro_untracked(&self, id: DefId, sess: &Session) -> LoadedMacro {
410         let _prof_timer = sess.prof.generic_activity("metadata_load_macro");
411
412         let data = self.get_crate_data(id.krate);
413         if data.root.is_proc_macro_crate() {
414             return LoadedMacro::ProcMacro(data.load_proc_macro(id.index, sess));
415         }
416
417         let span = data.get_span(id.index, sess);
418
419         let attrs = data.get_item_attrs(id.index, sess).collect();
420
421         let ident = data.item_ident(id.index, sess);
422
423         LoadedMacro::MacroDef(
424             ast::Item {
425                 ident,
426                 id: ast::DUMMY_NODE_ID,
427                 span,
428                 attrs,
429                 kind: ast::ItemKind::MacroDef(data.get_macro(id.index, sess)),
430                 vis: ast::Visibility {
431                     span: span.shrink_to_lo(),
432                     kind: ast::VisibilityKind::Inherited,
433                     tokens: None,
434                 },
435                 tokens: None,
436             },
437             data.root.edition,
438         )
439     }
440
441     pub fn associated_item_cloned_untracked(&self, def: DefId, sess: &Session) -> ty::AssocItem {
442         self.get_crate_data(def.krate).get_associated_item(def.index, sess)
443     }
444
445     pub fn crate_source_untracked(&self, cnum: CrateNum) -> CrateSource {
446         self.get_crate_data(cnum).source.clone()
447     }
448
449     pub fn get_span_untracked(&self, def_id: DefId, sess: &Session) -> Span {
450         self.get_crate_data(def_id.krate).get_span(def_id.index, sess)
451     }
452
453     pub fn item_generics_num_lifetimes(&self, def_id: DefId, sess: &Session) -> usize {
454         self.get_crate_data(def_id.krate).get_generics(def_id.index, sess).own_counts().lifetimes
455     }
456
457     pub fn module_expansion_untracked(&self, def_id: DefId, sess: &Session) -> ExpnId {
458         self.get_crate_data(def_id.krate).module_expansion(def_id.index, sess)
459     }
460
461     /// Only public-facing way to traverse all the definitions in a non-local crate.
462     /// Critically useful for this third-party project: <https://github.com/hacspec/hacspec>.
463     /// See <https://github.com/rust-lang/rust/pull/85889> for context.
464     pub fn num_def_ids_untracked(&self, cnum: CrateNum) -> usize {
465         self.get_crate_data(cnum).num_def_ids()
466     }
467
468     pub fn item_attrs(&self, def_id: DefId, sess: &Session) -> Vec<ast::Attribute> {
469         self.get_crate_data(def_id.krate).get_item_attrs(def_id.index, sess).collect()
470     }
471
472     pub fn get_proc_macro_quoted_span_untracked(
473         &self,
474         cnum: CrateNum,
475         id: usize,
476         sess: &Session,
477     ) -> Span {
478         self.get_crate_data(cnum).get_proc_macro_quoted_span(id, sess)
479     }
480 }
481
482 impl CrateStore for CStore {
483     fn as_any(&self) -> &dyn Any {
484         self
485     }
486
487     fn crate_name_untracked(&self, cnum: CrateNum) -> Symbol {
488         self.get_crate_data(cnum).root.name
489     }
490
491     fn stable_crate_id_untracked(&self, cnum: CrateNum) -> StableCrateId {
492         self.get_crate_data(cnum).root.stable_crate_id
493     }
494
495     fn crate_hash_untracked(&self, cnum: CrateNum) -> Svh {
496         self.get_crate_data(cnum).root.hash
497     }
498
499     /// Returns the `DefKey` for a given `DefId`. This indicates the
500     /// parent `DefId` as well as some idea of what kind of data the
501     /// `DefId` refers to.
502     fn def_key(&self, def: DefId) -> DefKey {
503         self.get_crate_data(def.krate).def_key(def.index)
504     }
505
506     fn def_kind(&self, def: DefId) -> DefKind {
507         self.get_crate_data(def.krate).def_kind(def.index)
508     }
509
510     fn def_path(&self, def: DefId) -> DefPath {
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     // See `CrateMetadataRef::def_path_hash_to_def_id` for more details
519     fn def_path_hash_to_def_id(
520         &self,
521         cnum: CrateNum,
522         index_guess: u32,
523         hash: DefPathHash,
524     ) -> Option<DefId> {
525         self.get_crate_data(cnum).def_path_hash_to_def_id(cnum, index_guess, hash)
526     }
527
528     fn crates_untracked(&self) -> Vec<CrateNum> {
529         let mut result = vec![];
530         self.iter_crate_data(|cnum, _| result.push(cnum));
531         result
532     }
533
534     fn encode_metadata(&self, tcx: TyCtxt<'_>) -> EncodedMetadata {
535         encoder::encode_metadata(tcx)
536     }
537 }