]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs
Rollup merge of #92519 - ChrisDenton:command-maybe-verbatim, r=dtolnay
[rust.git] / compiler / rustc_metadata / src / rmeta / decoder / cstore_impl.rs
1 use super::LazyQueryDecodable;
2 use crate::creader::{CStore, LoadedMacro};
3 use crate::foreign_modules;
4 use crate::native_libs;
5
6 use rustc_ast as ast;
7 use rustc_hir::def::{CtorKind, DefKind, Res};
8 use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, CRATE_DEF_INDEX, LOCAL_CRATE};
9 use rustc_hir::definitions::{DefKey, DefPath, DefPathHash};
10 use rustc_middle::metadata::ModChild;
11 use rustc_middle::middle::exported_symbols::ExportedSymbol;
12 use rustc_middle::ty::fast_reject::SimplifiedType;
13 use rustc_middle::ty::query::{ExternProviders, Providers};
14 use rustc_middle::ty::{self, TyCtxt, Visibility};
15 use rustc_session::cstore::{CrateSource, CrateStore};
16 use rustc_session::utils::NativeLibKind;
17 use rustc_session::{Session, StableCrateId};
18 use rustc_span::hygiene::{ExpnHash, ExpnId};
19 use rustc_span::source_map::{Span, Spanned};
20 use rustc_span::symbol::{kw, Symbol};
21
22 use rustc_data_structures::sync::Lrc;
23 use smallvec::SmallVec;
24 use std::any::Any;
25
26 macro_rules! provide_one {
27     (<$lt:tt> $tcx:ident, $def_id:ident, $other:ident, $cdata:ident, $name:ident => { table }) => {
28         provide_one! {
29             <$lt> $tcx, $def_id, $other, $cdata, $name => {
30                 $cdata.root.tables.$name.get($cdata, $def_id.index).decode_query(
31                     $cdata,
32                     $tcx,
33                     || panic!("{:?} does not have a {:?}", $def_id, stringify!($name)),
34                 )
35             }
36         }
37     };
38     (<$lt:tt> $tcx:ident, $def_id:ident, $other:ident, $cdata:ident, $name:ident => $compute:block) => {
39         fn $name<$lt>(
40             $tcx: TyCtxt<$lt>,
41             def_id_arg: ty::query::query_keys::$name<$lt>,
42         ) -> ty::query::query_values::$name<$lt> {
43             let _prof_timer =
44                 $tcx.prof.generic_activity(concat!("metadata_decode_entry_", stringify!($name)));
45
46             #[allow(unused_variables)]
47             let ($def_id, $other) = def_id_arg.into_args();
48             assert!(!$def_id.is_local());
49
50             // External query providers call `crate_hash` in order to register a dependency
51             // on the crate metadata. The exception is `crate_hash` itself, which obviously
52             // doesn't need to do this (and can't, as it would cause a query cycle).
53             use rustc_middle::dep_graph::DepKind;
54             if DepKind::$name != DepKind::crate_hash && $tcx.dep_graph.is_fully_enabled() {
55                 $tcx.ensure().crate_hash($def_id.krate);
56             }
57
58             let $cdata = CStore::from_tcx($tcx).get_crate_data($def_id.krate);
59
60             $compute
61         }
62     };
63 }
64
65 macro_rules! provide {
66     (<$lt:tt> $tcx:ident, $def_id:ident, $other:ident, $cdata:ident,
67       $($name:ident => { $($compute:tt)* })*) => {
68         pub fn provide_extern(providers: &mut ExternProviders) {
69             $(provide_one! {
70                 <$lt> $tcx, $def_id, $other, $cdata, $name => { $($compute)* }
71             })*
72
73             *providers = ExternProviders {
74                 $($name,)*
75                 ..*providers
76             };
77         }
78     }
79 }
80
81 // small trait to work around different signature queries all being defined via
82 // the macro above.
83 trait IntoArgs {
84     fn into_args(self) -> (DefId, DefId);
85 }
86
87 impl IntoArgs for DefId {
88     fn into_args(self) -> (DefId, DefId) {
89         (self, self)
90     }
91 }
92
93 impl IntoArgs for CrateNum {
94     fn into_args(self) -> (DefId, DefId) {
95         (self.as_def_id(), self.as_def_id())
96     }
97 }
98
99 impl IntoArgs for (CrateNum, DefId) {
100     fn into_args(self) -> (DefId, DefId) {
101         (self.0.as_def_id(), self.1)
102     }
103 }
104
105 impl<'tcx> IntoArgs for ty::InstanceDef<'tcx> {
106     fn into_args(self) -> (DefId, DefId) {
107         (self.def_id(), self.def_id())
108     }
109 }
110
111 provide! { <'tcx> tcx, def_id, other, cdata,
112     explicit_item_bounds => { table }
113     explicit_predicates_of => { table }
114     generics_of => { table }
115     inferred_outlives_of => { table }
116     super_predicates_of => { table }
117     type_of => { table }
118     variances_of => { table }
119     fn_sig => { table }
120     impl_trait_ref => { table }
121     const_param_default => { table }
122     thir_abstract_const => { table }
123     optimized_mir => { table }
124     mir_for_ctfe => { table }
125     promoted_mir => { table }
126     def_span => { table }
127     def_ident_span => { table }
128     lookup_stability => { table }
129     lookup_const_stability => { table }
130     lookup_deprecation_entry => { table }
131     visibility => { table }
132     unused_generic_params => { table }
133     opt_def_kind => { table }
134     impl_parent => { table }
135     impl_polarity => { table }
136     impl_defaultness => { table }
137     impl_constness => { table }
138     coerce_unsized_info => { table }
139     mir_const_qualif => { table }
140     rendered_const => { table }
141     asyncness => { table }
142     fn_arg_names => { table }
143     generator_kind => { table }
144
145     trait_def => { cdata.get_trait_def(def_id.index, tcx.sess) }
146     adt_def => { cdata.get_adt_def(def_id.index, tcx) }
147     adt_destructor => {
148         let _ = cdata;
149         tcx.calculate_dtor(def_id, |_,_| Ok(()))
150     }
151     associated_item_def_ids => { cdata.get_associated_item_def_ids(tcx, def_id.index) }
152     associated_item => { cdata.get_associated_item(def_id.index) }
153     inherent_impls => { cdata.get_inherent_implementations_for_type(tcx, def_id.index) }
154     is_const_fn_raw => { cdata.is_const_fn_raw(def_id.index) }
155     is_foreign_item => { cdata.is_foreign_item(def_id.index) }
156     static_mutability => { cdata.static_mutability(def_id.index) }
157     item_attrs => { tcx.arena.alloc_from_iter(cdata.get_item_attrs(def_id.index, tcx.sess)) }
158     trait_of_item => { cdata.get_trait_of_item(def_id.index) }
159     is_mir_available => { cdata.is_item_mir_available(def_id.index) }
160     is_ctfe_mir_available => { cdata.is_ctfe_mir_available(def_id.index) }
161
162     dylib_dependency_formats => { cdata.get_dylib_dependency_formats(tcx) }
163     is_private_dep => { cdata.private_dep }
164     is_panic_runtime => { cdata.root.panic_runtime }
165     is_compiler_builtins => { cdata.root.compiler_builtins }
166     has_global_allocator => { cdata.root.has_global_allocator }
167     has_panic_handler => { cdata.root.has_panic_handler }
168     is_profiler_runtime => { cdata.root.profiler_runtime }
169     panic_strategy => { cdata.root.panic_strategy }
170     panic_in_drop_strategy => { cdata.root.panic_in_drop_strategy }
171     extern_crate => {
172         let r = *cdata.extern_crate.lock();
173         r.map(|c| &*tcx.arena.alloc(c))
174     }
175     is_no_builtins => { cdata.root.no_builtins }
176     symbol_mangling_version => { cdata.root.symbol_mangling_version }
177     reachable_non_generics => {
178         let reachable_non_generics = tcx
179             .exported_symbols(cdata.cnum)
180             .iter()
181             .filter_map(|&(exported_symbol, export_level)| {
182                 if let ExportedSymbol::NonGeneric(def_id) = exported_symbol {
183                     Some((def_id, export_level))
184                 } else {
185                     None
186                 }
187             })
188             .collect();
189
190         reachable_non_generics
191     }
192     native_libraries => { cdata.get_native_libraries(tcx.sess).collect() }
193     foreign_modules => { cdata.get_foreign_modules(tcx.sess).map(|m| (m.def_id, m)).collect() }
194     crate_hash => { cdata.root.hash }
195     crate_host_hash => { cdata.host_hash }
196     crate_name => { cdata.root.name }
197
198     extra_filename => { cdata.root.extra_filename.clone() }
199
200     traits_in_crate => { tcx.arena.alloc_from_iter(cdata.get_traits()) }
201     implementations_of_trait => { cdata.get_implementations_of_trait(tcx, other) }
202
203     dep_kind => {
204         let r = *cdata.dep_kind.lock();
205         r
206     }
207     module_children => {
208         let mut result = SmallVec::<[_; 8]>::new();
209         cdata.for_each_module_child(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 => { tcx.arena.alloc_from_iter(cdata.get_lang_items()) }
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::clone(&cdata.source) }
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(in crate::rmeta) 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 Some(fm_id) = lib.foreign_module else {
263                         return false;
264                     };
265                     let map = tcx.foreign_modules(id.krate);
266                     map.get(&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             native_libs::collect(tcx)
276         },
277         foreign_modules: |tcx, cnum| {
278             assert_eq!(cnum, LOCAL_CRATE);
279             foreign_modules::collect(tcx).into_iter().map(|m| (m.def_id, m)).collect()
280         },
281
282         // Returns a map from a sufficiently visible external item (i.e., an
283         // external item that is visible from at least one local module) to a
284         // sufficiently visible parent (considering modules that re-export the
285         // external item to be parents).
286         visible_parent_map: |tcx, ()| {
287             use std::collections::hash_map::Entry;
288             use std::collections::vec_deque::VecDeque;
289
290             let mut visible_parent_map: DefIdMap<DefId> = Default::default();
291             // This is a secondary visible_parent_map, storing the DefId of parents that re-export
292             // the child as `_`. Since we prefer parents that don't do this, merge this map at the
293             // end, only if we're missing any keys from the former.
294             let mut fallback_map: DefIdMap<DefId> = Default::default();
295
296             // Issue 46112: We want the map to prefer the shortest
297             // paths when reporting the path to an item. Therefore we
298             // build up the map via a breadth-first search (BFS),
299             // which naturally yields minimal-length paths.
300             //
301             // Note that it needs to be a BFS over the whole forest of
302             // crates, not just each individual crate; otherwise you
303             // only get paths that are locally minimal with respect to
304             // whatever crate we happened to encounter first in this
305             // traversal, but not globally minimal across all crates.
306             let bfs_queue = &mut VecDeque::new();
307
308             for &cnum in tcx.crates(()) {
309                 // Ignore crates without a corresponding local `extern crate` item.
310                 if tcx.missing_extern_crate_item(cnum) {
311                     continue;
312                 }
313
314                 bfs_queue.push_back(DefId { krate: cnum, index: CRATE_DEF_INDEX });
315             }
316
317             let mut add_child = |bfs_queue: &mut VecDeque<_>, child: &ModChild, parent: DefId| {
318                 if !child.vis.is_public() {
319                     return;
320                 }
321
322                 if let Some(def_id) = child.res.opt_def_id() {
323                     if child.ident.name == kw::Underscore {
324                         fallback_map.insert(def_id, parent);
325                         return;
326                     }
327
328                     match visible_parent_map.entry(def_id) {
329                         Entry::Occupied(mut entry) => {
330                             // If `child` is defined in crate `cnum`, ensure
331                             // that it is mapped to a parent in `cnum`.
332                             if def_id.is_local() && entry.get().is_local() {
333                                 entry.insert(parent);
334                             }
335                         }
336                         Entry::Vacant(entry) => {
337                             entry.insert(parent);
338                             if matches!(
339                                 child.res,
340                                 Res::Def(DefKind::Mod | DefKind::Enum | DefKind::Trait, _)
341                             ) {
342                                 bfs_queue.push_back(def_id);
343                             }
344                         }
345                     }
346                 }
347             };
348
349             while let Some(def) = bfs_queue.pop_front() {
350                 for child in tcx.module_children(def).iter() {
351                     add_child(bfs_queue, child, def);
352                 }
353             }
354
355             // Fill in any missing entries with the (less preferable) path ending in `::_`.
356             // We still use this path in a diagnostic that suggests importing `::*`.
357             for (child, parent) in fallback_map {
358                 visible_parent_map.entry(child).or_insert(parent);
359             }
360
361             visible_parent_map
362         },
363
364         dependency_formats: |tcx, ()| Lrc::new(crate::dependency_format::calculate(tcx)),
365         has_global_allocator: |tcx, cnum| {
366             assert_eq!(cnum, LOCAL_CRATE);
367             CStore::from_tcx(tcx).has_global_allocator()
368         },
369         postorder_cnums: |tcx, ()| {
370             tcx.arena
371                 .alloc_slice(&CStore::from_tcx(tcx).crate_dependencies_in_postorder(LOCAL_CRATE))
372         },
373         crates: |tcx, ()| tcx.arena.alloc_from_iter(CStore::from_tcx(tcx).crates_untracked()),
374
375         ..*providers
376     };
377 }
378
379 impl CStore {
380     pub fn struct_field_names_untracked<'a>(
381         &'a self,
382         def: DefId,
383         sess: &'a Session,
384     ) -> impl Iterator<Item = Spanned<Symbol>> + 'a {
385         self.get_crate_data(def.krate).get_struct_field_names(def.index, sess)
386     }
387
388     pub fn struct_field_visibilities_untracked(
389         &self,
390         def: DefId,
391     ) -> impl Iterator<Item = Visibility> + '_ {
392         self.get_crate_data(def.krate).get_struct_field_visibilities(def.index)
393     }
394
395     pub fn ctor_def_id_and_kind_untracked(&self, def: DefId) -> Option<(DefId, CtorKind)> {
396         self.get_crate_data(def.krate).get_ctor_def_id_and_kind(def.index)
397     }
398
399     pub fn visibility_untracked(&self, def: DefId) -> Visibility {
400         self.get_crate_data(def.krate).get_visibility(def.index)
401     }
402
403     pub fn module_children_untracked(&self, def_id: DefId, sess: &Session) -> Vec<ModChild> {
404         let mut result = vec![];
405         self.get_crate_data(def_id.krate).for_each_module_child(
406             def_id.index,
407             |child| result.push(child),
408             sess,
409         );
410         result
411     }
412
413     pub fn load_macro_untracked(&self, id: DefId, sess: &Session) -> LoadedMacro {
414         let _prof_timer = sess.prof.generic_activity("metadata_load_macro");
415
416         let data = self.get_crate_data(id.krate);
417         if data.root.is_proc_macro_crate() {
418             return LoadedMacro::ProcMacro(data.load_proc_macro(id.index, sess));
419         }
420
421         let span = data.get_span(id.index, sess);
422
423         LoadedMacro::MacroDef(
424             ast::Item {
425                 ident: data.item_ident(id.index, sess),
426                 id: ast::DUMMY_NODE_ID,
427                 span,
428                 attrs: data.get_item_attrs(id.index, sess).collect(),
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 fn_has_self_parameter_untracked(&self, def: DefId) -> bool {
442         self.get_crate_data(def.krate).get_fn_has_self_parameter(def.index)
443     }
444
445     pub fn crate_source_untracked(&self, cnum: CrateNum) -> Lrc<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 def_kind(&self, def: DefId) -> DefKind {
454         self.get_crate_data(def.krate).def_kind(def.index)
455     }
456
457     pub fn crates_untracked(&self) -> impl Iterator<Item = CrateNum> + '_ {
458         self.iter_crate_data().map(|(cnum, _)| cnum)
459     }
460
461     pub fn item_generics_num_lifetimes(&self, def_id: DefId, sess: &Session) -> usize {
462         self.get_crate_data(def_id.krate).get_generics(def_id.index, sess).own_counts().lifetimes
463     }
464
465     pub fn module_expansion_untracked(&self, def_id: DefId, sess: &Session) -> ExpnId {
466         self.get_crate_data(def_id.krate).module_expansion(def_id.index, sess)
467     }
468
469     /// Only public-facing way to traverse all the definitions in a non-local crate.
470     /// Critically useful for this third-party project: <https://github.com/hacspec/hacspec>.
471     /// See <https://github.com/rust-lang/rust/pull/85889> for context.
472     pub fn num_def_ids_untracked(&self, cnum: CrateNum) -> usize {
473         self.get_crate_data(cnum).num_def_ids()
474     }
475
476     pub fn item_attrs_untracked<'a>(
477         &'a self,
478         def_id: DefId,
479         sess: &'a Session,
480     ) -> impl Iterator<Item = ast::Attribute> + 'a {
481         self.get_crate_data(def_id.krate).get_item_attrs(def_id.index, sess)
482     }
483
484     pub fn get_proc_macro_quoted_span_untracked(
485         &self,
486         cnum: CrateNum,
487         id: usize,
488         sess: &Session,
489     ) -> Span {
490         self.get_crate_data(cnum).get_proc_macro_quoted_span(id, sess)
491     }
492
493     /// Decodes all traits in the crate (for rustdoc).
494     pub fn traits_in_crate_untracked(&self, cnum: CrateNum) -> impl Iterator<Item = DefId> + '_ {
495         self.get_crate_data(cnum).get_traits()
496     }
497
498     /// Decodes all trait impls in the crate (for rustdoc).
499     pub fn trait_impls_in_crate_untracked(
500         &self,
501         cnum: CrateNum,
502     ) -> impl Iterator<Item = (DefId, DefId, Option<SimplifiedType>)> + '_ {
503         self.get_crate_data(cnum).get_trait_impls()
504     }
505
506     /// Decodes all inherent impls in the crate (for rustdoc).
507     pub fn inherent_impls_in_crate_untracked(
508         &self,
509         cnum: CrateNum,
510     ) -> impl Iterator<Item = (DefId, DefId)> + '_ {
511         self.get_crate_data(cnum).get_inherent_impls()
512     }
513
514     /// Decodes all lang items in the crate (for rustdoc).
515     pub fn lang_items_untracked(&self, cnum: CrateNum) -> impl Iterator<Item = DefId> + '_ {
516         self.get_crate_data(cnum).get_lang_items().map(|(def_id, _)| def_id)
517     }
518 }
519
520 impl CrateStore for CStore {
521     fn as_any(&self) -> &dyn Any {
522         self
523     }
524
525     fn crate_name(&self, cnum: CrateNum) -> Symbol {
526         self.get_crate_data(cnum).root.name
527     }
528
529     fn stable_crate_id(&self, cnum: CrateNum) -> StableCrateId {
530         self.get_crate_data(cnum).root.stable_crate_id
531     }
532
533     fn stable_crate_id_to_crate_num(&self, stable_crate_id: StableCrateId) -> CrateNum {
534         self.stable_crate_ids[&stable_crate_id]
535     }
536
537     /// Returns the `DefKey` for a given `DefId`. This indicates the
538     /// parent `DefId` as well as some idea of what kind of data the
539     /// `DefId` refers to.
540     fn def_key(&self, def: DefId) -> DefKey {
541         self.get_crate_data(def.krate).def_key(def.index)
542     }
543
544     fn def_path(&self, def: DefId) -> DefPath {
545         self.get_crate_data(def.krate).def_path(def.index)
546     }
547
548     fn def_path_hash(&self, def: DefId) -> DefPathHash {
549         self.get_crate_data(def.krate).def_path_hash(def.index)
550     }
551
552     fn def_path_hash_to_def_id(&self, cnum: CrateNum, hash: DefPathHash) -> DefId {
553         let def_index = self.get_crate_data(cnum).def_path_hash_to_def_index(hash);
554         DefId { krate: cnum, index: def_index }
555     }
556
557     fn expn_hash_to_expn_id(
558         &self,
559         sess: &Session,
560         cnum: CrateNum,
561         index_guess: u32,
562         hash: ExpnHash,
563     ) -> ExpnId {
564         self.get_crate_data(cnum).expn_hash_to_expn_id(sess, index_guess, hash)
565     }
566
567     fn import_source_files(&self, sess: &Session, cnum: CrateNum) {
568         self.get_crate_data(cnum).imported_source_files(sess);
569     }
570 }