]> git.proxmox.com Git - rustc.git/blob - compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs
New upstream version 1.62.1+dfsg1
[rustc.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, 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 type Other;
85 fn into_args(self) -> (DefId, Self::Other);
86 }
87
88 impl IntoArgs for DefId {
89 type Other = ();
90 fn into_args(self) -> (DefId, ()) {
91 (self, ())
92 }
93 }
94
95 impl IntoArgs for CrateNum {
96 type Other = ();
97 fn into_args(self) -> (DefId, ()) {
98 (self.as_def_id(), ())
99 }
100 }
101
102 impl IntoArgs for (CrateNum, DefId) {
103 type Other = DefId;
104 fn into_args(self) -> (DefId, DefId) {
105 (self.0.as_def_id(), self.1)
106 }
107 }
108
109 impl<'tcx> IntoArgs for ty::InstanceDef<'tcx> {
110 type Other = ();
111 fn into_args(self) -> (DefId, ()) {
112 (self.def_id(), ())
113 }
114 }
115
116 impl IntoArgs for (CrateNum, SimplifiedType) {
117 type Other = SimplifiedType;
118 fn into_args(self) -> (DefId, SimplifiedType) {
119 (self.0.as_def_id(), self.1)
120 }
121 }
122
123 provide! { <'tcx> tcx, def_id, other, cdata,
124 explicit_item_bounds => { table }
125 explicit_predicates_of => { table }
126 generics_of => { table }
127 inferred_outlives_of => { table }
128 super_predicates_of => { table }
129 type_of => { table }
130 variances_of => { table }
131 fn_sig => { table }
132 codegen_fn_attrs => { table }
133 impl_trait_ref => { table }
134 const_param_default => { table }
135 thir_abstract_const => { table }
136 optimized_mir => { table }
137 mir_for_ctfe => { table }
138 promoted_mir => { table }
139 def_span => { table }
140 def_ident_span => { table }
141 lookup_stability => { table }
142 lookup_const_stability => { table }
143 lookup_deprecation_entry => { table }
144 visibility => { table }
145 unused_generic_params => { table }
146 opt_def_kind => { table }
147 impl_parent => { table }
148 impl_polarity => { table }
149 impl_defaultness => { table }
150 impl_constness => { table }
151 coerce_unsized_info => { table }
152 mir_const_qualif => { table }
153 rendered_const => { table }
154 asyncness => { table }
155 fn_arg_names => { table }
156 generator_kind => { table }
157 trait_def => { table }
158
159 adt_def => { cdata.get_adt_def(def_id.index, tcx) }
160 adt_destructor => {
161 let _ = cdata;
162 tcx.calculate_dtor(def_id, |_,_| Ok(()))
163 }
164 associated_item_def_ids => {
165 tcx.arena.alloc_from_iter(cdata.get_associated_item_def_ids(def_id.index, tcx.sess))
166 }
167 associated_item => { cdata.get_associated_item(def_id.index) }
168 inherent_impls => { cdata.get_inherent_implementations_for_type(tcx, def_id.index) }
169 is_foreign_item => { cdata.is_foreign_item(def_id.index) }
170 item_attrs => { tcx.arena.alloc_from_iter(cdata.get_item_attrs(def_id.index, tcx.sess)) }
171 trait_of_item => { cdata.get_trait_of_item(def_id.index) }
172 is_mir_available => { cdata.is_item_mir_available(def_id.index) }
173 is_ctfe_mir_available => { cdata.is_ctfe_mir_available(def_id.index) }
174
175 dylib_dependency_formats => { cdata.get_dylib_dependency_formats(tcx) }
176 is_private_dep => { cdata.private_dep }
177 is_panic_runtime => { cdata.root.panic_runtime }
178 is_compiler_builtins => { cdata.root.compiler_builtins }
179 has_global_allocator => { cdata.root.has_global_allocator }
180 has_panic_handler => { cdata.root.has_panic_handler }
181 is_profiler_runtime => { cdata.root.profiler_runtime }
182 panic_strategy => { cdata.root.panic_strategy }
183 panic_in_drop_strategy => { cdata.root.panic_in_drop_strategy }
184 extern_crate => {
185 let r = *cdata.extern_crate.lock();
186 r.map(|c| &*tcx.arena.alloc(c))
187 }
188 is_no_builtins => { cdata.root.no_builtins }
189 symbol_mangling_version => { cdata.root.symbol_mangling_version }
190 reachable_non_generics => {
191 let reachable_non_generics = tcx
192 .exported_symbols(cdata.cnum)
193 .iter()
194 .filter_map(|&(exported_symbol, export_info)| {
195 if let ExportedSymbol::NonGeneric(def_id) = exported_symbol {
196 Some((def_id, export_info))
197 } else {
198 None
199 }
200 })
201 .collect();
202
203 reachable_non_generics
204 }
205 native_libraries => { cdata.get_native_libraries(tcx.sess).collect() }
206 foreign_modules => { cdata.get_foreign_modules(tcx.sess).map(|m| (m.def_id, m)).collect() }
207 crate_hash => { cdata.root.hash }
208 crate_host_hash => { cdata.host_hash }
209 crate_name => { cdata.root.name }
210
211 extra_filename => { cdata.root.extra_filename.clone() }
212
213 traits_in_crate => { tcx.arena.alloc_from_iter(cdata.get_traits()) }
214 implementations_of_trait => { cdata.get_implementations_of_trait(tcx, other) }
215 crate_incoherent_impls => { cdata.get_incoherent_impls(tcx, other) }
216
217 dep_kind => {
218 let r = *cdata.dep_kind.lock();
219 r
220 }
221 module_children => {
222 let mut result = SmallVec::<[_; 8]>::new();
223 cdata.for_each_module_child(def_id.index, |child| result.push(child), tcx.sess);
224 tcx.arena.alloc_slice(&result)
225 }
226 defined_lib_features => { cdata.get_lib_features(tcx) }
227 defined_lang_items => { cdata.get_lang_items(tcx) }
228 diagnostic_items => { cdata.get_diagnostic_items() }
229 missing_lang_items => { cdata.get_missing_lang_items(tcx) }
230
231 missing_extern_crate_item => {
232 let r = matches!(*cdata.extern_crate.borrow(), Some(extern_crate) if !extern_crate.is_direct());
233 r
234 }
235
236 used_crate_source => { Lrc::clone(&cdata.source) }
237 debugger_visualizers => { cdata.get_debugger_visualizers() }
238
239 exported_symbols => {
240 let syms = cdata.exported_symbols(tcx);
241
242 // FIXME rust-lang/rust#64319, rust-lang/rust#64872: We want
243 // to block export of generics from dylibs, but we must fix
244 // rust-lang/rust#65890 before we can do that robustly.
245
246 syms
247 }
248
249 crate_extern_paths => { cdata.source().paths().cloned().collect() }
250 expn_that_defined => { cdata.get_expn_that_defined(def_id.index, tcx.sess) }
251 generator_diagnostic_data => { cdata.get_generator_diagnostic_data(tcx, def_id.index) }
252 }
253
254 pub(in crate::rmeta) fn provide(providers: &mut Providers) {
255 // FIXME(#44234) - almost all of these queries have no sub-queries and
256 // therefore no actual inputs, they're just reading tables calculated in
257 // resolve! Does this work? Unsure! That's what the issue is about
258 *providers = Providers {
259 allocator_kind: |tcx, ()| CStore::from_tcx(tcx).allocator_kind(),
260 is_dllimport_foreign_item: |tcx, id| match tcx.native_library_kind(id) {
261 Some(
262 NativeLibKind::Dylib { .. } | NativeLibKind::RawDylib | NativeLibKind::Unspecified,
263 ) => true,
264 _ => false,
265 },
266 is_statically_included_foreign_item: |tcx, id| {
267 matches!(tcx.native_library_kind(id), Some(NativeLibKind::Static { .. }))
268 },
269 is_private_dep: |_tcx, cnum| {
270 assert_eq!(cnum, LOCAL_CRATE);
271 false
272 },
273 native_library_kind: |tcx, id| {
274 tcx.native_libraries(id.krate)
275 .iter()
276 .filter(|lib| native_libs::relevant_lib(&tcx.sess, lib))
277 .find(|lib| {
278 let Some(fm_id) = lib.foreign_module else {
279 return false;
280 };
281 let map = tcx.foreign_modules(id.krate);
282 map.get(&fm_id)
283 .expect("failed to find foreign module")
284 .foreign_items
285 .contains(&id)
286 })
287 .map(|l| l.kind)
288 },
289 native_libraries: |tcx, cnum| {
290 assert_eq!(cnum, LOCAL_CRATE);
291 native_libs::collect(tcx)
292 },
293 foreign_modules: |tcx, cnum| {
294 assert_eq!(cnum, LOCAL_CRATE);
295 foreign_modules::collect(tcx).into_iter().map(|m| (m.def_id, m)).collect()
296 },
297
298 // Returns a map from a sufficiently visible external item (i.e., an
299 // external item that is visible from at least one local module) to a
300 // sufficiently visible parent (considering modules that re-export the
301 // external item to be parents).
302 visible_parent_map: |tcx, ()| {
303 use std::collections::hash_map::Entry;
304 use std::collections::vec_deque::VecDeque;
305
306 let mut visible_parent_map: DefIdMap<DefId> = Default::default();
307 // This is a secondary visible_parent_map, storing the DefId of parents that re-export
308 // the child as `_`. Since we prefer parents that don't do this, merge this map at the
309 // end, only if we're missing any keys from the former.
310 let mut fallback_map: DefIdMap<DefId> = Default::default();
311
312 // Issue 46112: We want the map to prefer the shortest
313 // paths when reporting the path to an item. Therefore we
314 // build up the map via a breadth-first search (BFS),
315 // which naturally yields minimal-length paths.
316 //
317 // Note that it needs to be a BFS over the whole forest of
318 // crates, not just each individual crate; otherwise you
319 // only get paths that are locally minimal with respect to
320 // whatever crate we happened to encounter first in this
321 // traversal, but not globally minimal across all crates.
322 let bfs_queue = &mut VecDeque::new();
323
324 for &cnum in tcx.crates(()) {
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(cnum.as_def_id());
331 }
332
333 let mut add_child = |bfs_queue: &mut VecDeque<_>, child: &ModChild, parent: DefId| {
334 if !child.vis.is_public() {
335 return;
336 }
337
338 if let Some(def_id) = child.res.opt_def_id() {
339 if child.ident.name == kw::Underscore {
340 fallback_map.insert(def_id, parent);
341 return;
342 }
343
344 match visible_parent_map.entry(def_id) {
345 Entry::Occupied(mut entry) => {
346 // If `child` is defined in crate `cnum`, ensure
347 // that it is mapped to a parent in `cnum`.
348 if def_id.is_local() && entry.get().is_local() {
349 entry.insert(parent);
350 }
351 }
352 Entry::Vacant(entry) => {
353 entry.insert(parent);
354 if matches!(
355 child.res,
356 Res::Def(DefKind::Mod | DefKind::Enum | DefKind::Trait, _)
357 ) {
358 bfs_queue.push_back(def_id);
359 }
360 }
361 }
362 }
363 };
364
365 while let Some(def) = bfs_queue.pop_front() {
366 for child in tcx.module_children(def).iter() {
367 add_child(bfs_queue, child, def);
368 }
369 }
370
371 // Fill in any missing entries with the (less preferable) path ending in `::_`.
372 // We still use this path in a diagnostic that suggests importing `::*`.
373 for (child, parent) in fallback_map {
374 visible_parent_map.entry(child).or_insert(parent);
375 }
376
377 visible_parent_map
378 },
379
380 dependency_formats: |tcx, ()| Lrc::new(crate::dependency_format::calculate(tcx)),
381 has_global_allocator: |tcx, cnum| {
382 assert_eq!(cnum, LOCAL_CRATE);
383 CStore::from_tcx(tcx).has_global_allocator()
384 },
385 postorder_cnums: |tcx, ()| {
386 tcx.arena
387 .alloc_slice(&CStore::from_tcx(tcx).crate_dependencies_in_postorder(LOCAL_CRATE))
388 },
389 crates: |tcx, ()| tcx.arena.alloc_from_iter(CStore::from_tcx(tcx).crates_untracked()),
390 ..*providers
391 };
392 }
393
394 impl CStore {
395 pub fn struct_field_names_untracked<'a>(
396 &'a self,
397 def: DefId,
398 sess: &'a Session,
399 ) -> impl Iterator<Item = Spanned<Symbol>> + 'a {
400 self.get_crate_data(def.krate).get_struct_field_names(def.index, sess)
401 }
402
403 pub fn struct_field_visibilities_untracked(
404 &self,
405 def: DefId,
406 ) -> impl Iterator<Item = Visibility> + '_ {
407 self.get_crate_data(def.krate).get_struct_field_visibilities(def.index)
408 }
409
410 pub fn ctor_def_id_and_kind_untracked(&self, def: DefId) -> Option<(DefId, CtorKind)> {
411 self.get_crate_data(def.krate).get_ctor_def_id_and_kind(def.index)
412 }
413
414 pub fn visibility_untracked(&self, def: DefId) -> Visibility {
415 self.get_crate_data(def.krate).get_visibility(def.index)
416 }
417
418 pub fn module_children_untracked(&self, def_id: DefId, sess: &Session) -> Vec<ModChild> {
419 let mut result = vec![];
420 self.get_crate_data(def_id.krate).for_each_module_child(
421 def_id.index,
422 |child| result.push(child),
423 sess,
424 );
425 result
426 }
427
428 pub fn load_macro_untracked(&self, id: DefId, sess: &Session) -> LoadedMacro {
429 let _prof_timer = sess.prof.generic_activity("metadata_load_macro");
430
431 let data = self.get_crate_data(id.krate);
432 if data.root.is_proc_macro_crate() {
433 return LoadedMacro::ProcMacro(data.load_proc_macro(id.index, sess));
434 }
435
436 let span = data.get_span(id.index, sess);
437
438 LoadedMacro::MacroDef(
439 ast::Item {
440 ident: data.item_ident(id.index, sess),
441 id: ast::DUMMY_NODE_ID,
442 span,
443 attrs: data.get_item_attrs(id.index, sess).collect(),
444 kind: ast::ItemKind::MacroDef(data.get_macro(id.index, sess)),
445 vis: ast::Visibility {
446 span: span.shrink_to_lo(),
447 kind: ast::VisibilityKind::Inherited,
448 tokens: None,
449 },
450 tokens: None,
451 },
452 data.root.edition,
453 )
454 }
455
456 pub fn fn_has_self_parameter_untracked(&self, def: DefId) -> bool {
457 self.get_crate_data(def.krate).get_fn_has_self_parameter(def.index)
458 }
459
460 pub fn crate_source_untracked(&self, cnum: CrateNum) -> Lrc<CrateSource> {
461 self.get_crate_data(cnum).source.clone()
462 }
463
464 pub fn get_span_untracked(&self, def_id: DefId, sess: &Session) -> Span {
465 self.get_crate_data(def_id.krate).get_span(def_id.index, sess)
466 }
467
468 pub fn def_kind(&self, def: DefId) -> DefKind {
469 self.get_crate_data(def.krate).def_kind(def.index)
470 }
471
472 pub fn crates_untracked(&self) -> impl Iterator<Item = CrateNum> + '_ {
473 self.iter_crate_data().map(|(cnum, _)| cnum)
474 }
475
476 pub fn item_generics_num_lifetimes(&self, def_id: DefId, sess: &Session) -> usize {
477 self.get_crate_data(def_id.krate).get_generics(def_id.index, sess).own_counts().lifetimes
478 }
479
480 pub fn module_expansion_untracked(&self, def_id: DefId, sess: &Session) -> ExpnId {
481 self.get_crate_data(def_id.krate).module_expansion(def_id.index, sess)
482 }
483
484 /// Only public-facing way to traverse all the definitions in a non-local crate.
485 /// Critically useful for this third-party project: <https://github.com/hacspec/hacspec>.
486 /// See <https://github.com/rust-lang/rust/pull/85889> for context.
487 pub fn num_def_ids_untracked(&self, cnum: CrateNum) -> usize {
488 self.get_crate_data(cnum).num_def_ids()
489 }
490
491 pub fn item_attrs_untracked<'a>(
492 &'a self,
493 def_id: DefId,
494 sess: &'a Session,
495 ) -> impl Iterator<Item = ast::Attribute> + 'a {
496 self.get_crate_data(def_id.krate).get_item_attrs(def_id.index, sess)
497 }
498
499 pub fn get_proc_macro_quoted_span_untracked(
500 &self,
501 cnum: CrateNum,
502 id: usize,
503 sess: &Session,
504 ) -> Span {
505 self.get_crate_data(cnum).get_proc_macro_quoted_span(id, sess)
506 }
507
508 /// Decodes all traits in the crate (for rustdoc).
509 pub fn traits_in_crate_untracked(&self, cnum: CrateNum) -> impl Iterator<Item = DefId> + '_ {
510 self.get_crate_data(cnum).get_traits()
511 }
512
513 /// Decodes all trait impls in the crate (for rustdoc).
514 pub fn trait_impls_in_crate_untracked(
515 &self,
516 cnum: CrateNum,
517 ) -> impl Iterator<Item = (DefId, DefId, Option<SimplifiedType>)> + '_ {
518 self.get_crate_data(cnum).get_trait_impls()
519 }
520
521 /// Decodes all inherent impls in the crate (for rustdoc).
522 pub fn inherent_impls_in_crate_untracked(
523 &self,
524 cnum: CrateNum,
525 ) -> impl Iterator<Item = (DefId, DefId)> + '_ {
526 self.get_crate_data(cnum).get_inherent_impls()
527 }
528
529 /// Decodes all incoherent inherent impls in the crate (for rustdoc).
530 pub fn incoherent_impls_in_crate_untracked(
531 &self,
532 cnum: CrateNum,
533 ) -> impl Iterator<Item = DefId> + '_ {
534 self.get_crate_data(cnum).get_all_incoherent_impls()
535 }
536
537 pub fn associated_item_def_ids_untracked<'a>(
538 &'a self,
539 def_id: DefId,
540 sess: &'a Session,
541 ) -> impl Iterator<Item = DefId> + 'a {
542 self.get_crate_data(def_id.krate).get_associated_item_def_ids(def_id.index, sess)
543 }
544
545 pub fn may_have_doc_links_untracked(&self, def_id: DefId) -> bool {
546 self.get_crate_data(def_id.krate).get_may_have_doc_links(def_id.index)
547 }
548 }
549
550 impl CrateStore for CStore {
551 fn as_any(&self) -> &dyn Any {
552 self
553 }
554
555 fn crate_name(&self, cnum: CrateNum) -> Symbol {
556 self.get_crate_data(cnum).root.name
557 }
558
559 fn stable_crate_id(&self, cnum: CrateNum) -> StableCrateId {
560 self.get_crate_data(cnum).root.stable_crate_id
561 }
562
563 fn stable_crate_id_to_crate_num(&self, stable_crate_id: StableCrateId) -> CrateNum {
564 self.stable_crate_ids[&stable_crate_id]
565 }
566
567 /// Returns the `DefKey` for a given `DefId`. This indicates the
568 /// parent `DefId` as well as some idea of what kind of data the
569 /// `DefId` refers to.
570 fn def_key(&self, def: DefId) -> DefKey {
571 self.get_crate_data(def.krate).def_key(def.index)
572 }
573
574 fn def_path(&self, def: DefId) -> DefPath {
575 self.get_crate_data(def.krate).def_path(def.index)
576 }
577
578 fn def_path_hash(&self, def: DefId) -> DefPathHash {
579 self.get_crate_data(def.krate).def_path_hash(def.index)
580 }
581
582 fn def_path_hash_to_def_id(&self, cnum: CrateNum, hash: DefPathHash) -> DefId {
583 let def_index = self.get_crate_data(cnum).def_path_hash_to_def_index(hash);
584 DefId { krate: cnum, index: def_index }
585 }
586
587 fn expn_hash_to_expn_id(
588 &self,
589 sess: &Session,
590 cnum: CrateNum,
591 index_guess: u32,
592 hash: ExpnHash,
593 ) -> ExpnId {
594 self.get_crate_data(cnum).expn_hash_to_expn_id(sess, index_guess, hash)
595 }
596
597 fn import_source_files(&self, sess: &Session, cnum: CrateNum) {
598 self.get_crate_data(cnum).imported_source_files(sess);
599 }
600 }