]> git.proxmox.com Git - rustc.git/blob - compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs
New upstream version 1.59.0+dfsg1
[rustc.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
5 use rustc_ast as ast;
6 use rustc_data_structures::stable_map::FxHashMap;
7 use rustc_hir::def::{CtorKind, DefKind};
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::hir::exports::Export;
11 use rustc_middle::middle::exported_symbols::ExportedSymbol;
12 use rustc_middle::middle::stability::DeprecationEntry;
13 use rustc_middle::ty::query::{ExternProviders, Providers};
14 use rustc_middle::ty::{self, TyCtxt, Visibility};
15 use rustc_session::cstore::{CrateSource, CrateStore, ForeignModule};
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 {
27 (<$lt:tt> $tcx:ident, $def_id:ident, $other:ident, $cdata:ident,
28 $($name:ident => $compute:block)*) => {
29 pub fn provide_extern(providers: &mut ExternProviders) {
30 $(fn $name<$lt>(
31 $tcx: TyCtxt<$lt>,
32 def_id_arg: ty::query::query_keys::$name<$lt>,
33 ) -> ty::query::query_values::$name<$lt> {
34 let _prof_timer =
35 $tcx.prof.generic_activity(concat!("metadata_decode_entry_", stringify!($name)));
36
37 #[allow(unused_variables)]
38 let ($def_id, $other) = def_id_arg.into_args();
39 assert!(!$def_id.is_local());
40
41 // External query providers call `crate_hash` in order to register a dependency
42 // on the crate metadata. The exception is `crate_hash` itself, which obviously
43 // doesn't need to do this (and can't, as it would cause a query cycle).
44 use rustc_middle::dep_graph::DepKind;
45 if DepKind::$name != DepKind::crate_hash && $tcx.dep_graph.is_fully_enabled() {
46 $tcx.ensure().crate_hash($def_id.krate);
47 }
48
49 let $cdata = CStore::from_tcx($tcx).get_crate_data($def_id.krate);
50
51 $compute
52 })*
53
54 *providers = ExternProviders {
55 $($name,)*
56 ..*providers
57 };
58 }
59 }
60 }
61
62 // small trait to work around different signature queries all being defined via
63 // the macro above.
64 trait IntoArgs {
65 fn into_args(self) -> (DefId, DefId);
66 }
67
68 impl IntoArgs for DefId {
69 fn into_args(self) -> (DefId, DefId) {
70 (self, self)
71 }
72 }
73
74 impl IntoArgs for CrateNum {
75 fn into_args(self) -> (DefId, DefId) {
76 (self.as_def_id(), self.as_def_id())
77 }
78 }
79
80 impl IntoArgs for (CrateNum, DefId) {
81 fn into_args(self) -> (DefId, DefId) {
82 (self.0.as_def_id(), self.1)
83 }
84 }
85
86 impl<'tcx> IntoArgs for ty::InstanceDef<'tcx> {
87 fn into_args(self) -> (DefId, DefId) {
88 (self.def_id(), self.def_id())
89 }
90 }
91
92 provide! { <'tcx> tcx, def_id, other, cdata,
93 type_of => { cdata.get_type(def_id.index, tcx) }
94 generics_of => { cdata.get_generics(def_id.index, tcx.sess) }
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 explicit_item_bounds => { cdata.get_explicit_item_bounds(def_id.index, tcx) }
99 trait_def => { cdata.get_trait_def(def_id.index, tcx.sess) }
100 adt_def => { cdata.get_adt_def(def_id.index, tcx) }
101 adt_destructor => {
102 let _ = cdata;
103 tcx.calculate_dtor(def_id, |_,_| Ok(()))
104 }
105 variances_of => { tcx.arena.alloc_from_iter(cdata.get_item_variances(def_id.index)) }
106 associated_item_def_ids => {
107 let mut result = SmallVec::<[_; 8]>::new();
108 cdata.each_child_of_item(def_id.index,
109 |child| result.push(child.res.def_id()), tcx.sess);
110 tcx.arena.alloc_slice(&result)
111 }
112 associated_item => { cdata.get_associated_item(def_id.index, tcx.sess) }
113 impl_trait_ref => { cdata.get_impl_trait(def_id.index, tcx) }
114 impl_polarity => { cdata.get_impl_polarity(def_id.index) }
115 coerce_unsized_info => {
116 cdata.get_coerce_unsized_info(def_id.index).unwrap_or_else(|| {
117 bug!("coerce_unsized_info: `{:?}` is missing its info", def_id);
118 })
119 }
120 optimized_mir => { tcx.arena.alloc(cdata.get_optimized_mir(tcx, def_id.index)) }
121 mir_for_ctfe => { tcx.arena.alloc(cdata.get_mir_for_ctfe(tcx, def_id.index)) }
122 promoted_mir => { tcx.arena.alloc(cdata.get_promoted_mir(tcx, def_id.index)) }
123 thir_abstract_const => { cdata.get_thir_abstract_const(tcx, def_id.index) }
124 unused_generic_params => { cdata.get_unused_generic_params(def_id.index) }
125 const_param_default => { tcx.mk_const(cdata.get_const_param_default(tcx, def_id.index)) }
126 mir_const_qualif => { cdata.mir_const_qualif(def_id.index) }
127 fn_sig => { cdata.fn_sig(def_id.index, tcx) }
128 inherent_impls => { cdata.get_inherent_implementations_for_type(tcx, def_id.index) }
129 is_const_fn_raw => { cdata.is_const_fn_raw(def_id.index) }
130 asyncness => { cdata.asyncness(def_id.index) }
131 is_foreign_item => { cdata.is_foreign_item(def_id.index) }
132 static_mutability => { cdata.static_mutability(def_id.index) }
133 generator_kind => { cdata.generator_kind(def_id.index) }
134 opt_def_kind => { Some(cdata.def_kind(def_id.index)) }
135 def_span => { cdata.get_span(def_id.index, &tcx.sess) }
136 def_ident_span => { cdata.opt_item_ident(def_id.index, &tcx.sess).map(|ident| ident.span) }
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(cdata.get_item_attrs(def_id.index, tcx.sess)) }
147 fn_arg_names => { cdata.get_fn_param_names(tcx, 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 is_ctfe_mir_available => { cdata.is_ctfe_mir_available(def_id.index) }
153
154 dylib_dependency_formats => { cdata.get_dylib_dependency_formats(tcx) }
155 is_private_dep => { cdata.private_dep }
156 is_panic_runtime => { cdata.root.panic_runtime }
157 is_compiler_builtins => { cdata.root.compiler_builtins }
158 has_global_allocator => { cdata.root.has_global_allocator }
159 has_panic_handler => { cdata.root.has_panic_handler }
160 is_profiler_runtime => { cdata.root.profiler_runtime }
161 panic_strategy => { cdata.root.panic_strategy }
162 panic_in_drop_strategy => { cdata.root.panic_in_drop_strategy }
163 extern_crate => {
164 let r = *cdata.extern_crate.lock();
165 r.map(|c| &*tcx.arena.alloc(c))
166 }
167 is_no_builtins => { cdata.root.no_builtins }
168 symbol_mangling_version => { cdata.root.symbol_mangling_version }
169 impl_defaultness => { cdata.get_impl_defaultness(def_id.index) }
170 impl_constness => { cdata.get_impl_constness(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 traits_in_crate => { tcx.arena.alloc_from_iter(cdata.get_traits()) }
195 all_trait_implementations => { tcx.arena.alloc_from_iter(cdata.get_trait_impls()) }
196
197 implementations_of_trait => { cdata.get_implementations_of_trait(tcx, other) }
198
199 visibility => { cdata.get_visibility(def_id.index) }
200 dep_kind => {
201 let r = *cdata.dep_kind.lock();
202 r
203 }
204 item_children => {
205 let mut result = SmallVec::<[_; 8]>::new();
206 cdata.each_child_of_item(def_id.index, |child| result.push(child), tcx.sess);
207 tcx.arena.alloc_slice(&result)
208 }
209 defined_lib_features => { cdata.get_lib_features(tcx) }
210 defined_lang_items => { cdata.get_lang_items(tcx) }
211 diagnostic_items => { cdata.get_diagnostic_items() }
212 missing_lang_items => { cdata.get_missing_lang_items(tcx) }
213
214 missing_extern_crate_item => {
215 let r = matches!(*cdata.extern_crate.borrow(), Some(extern_crate) if !extern_crate.is_direct());
216 r
217 }
218
219 used_crate_source => { Lrc::new(cdata.source.clone()) }
220
221 exported_symbols => {
222 let syms = cdata.exported_symbols(tcx);
223
224 // FIXME rust-lang/rust#64319, rust-lang/rust#64872: We want
225 // to block export of generics from dylibs, but we must fix
226 // rust-lang/rust#65890 before we can do that robustly.
227
228 syms
229 }
230
231 crate_extern_paths => { cdata.source().paths().cloned().collect() }
232 expn_that_defined => { cdata.get_expn_that_defined(def_id.index, tcx.sess) }
233 }
234
235 pub(in crate::rmeta) fn provide(providers: &mut Providers) {
236 // FIXME(#44234) - almost all of these queries have no sub-queries and
237 // therefore no actual inputs, they're just reading tables calculated in
238 // resolve! Does this work? Unsure! That's what the issue is about
239 *providers = Providers {
240 allocator_kind: |tcx, ()| CStore::from_tcx(tcx).allocator_kind(),
241 is_dllimport_foreign_item: |tcx, id| match tcx.native_library_kind(id) {
242 Some(
243 NativeLibKind::Dylib { .. } | NativeLibKind::RawDylib | NativeLibKind::Unspecified,
244 ) => true,
245 _ => false,
246 },
247 is_statically_included_foreign_item: |tcx, id| {
248 matches!(tcx.native_library_kind(id), Some(NativeLibKind::Static { .. }))
249 },
250 is_private_dep: |_tcx, cnum| {
251 assert_eq!(cnum, LOCAL_CRATE);
252 false
253 },
254 native_library_kind: |tcx, id| {
255 tcx.native_libraries(id.krate)
256 .iter()
257 .filter(|lib| native_libs::relevant_lib(&tcx.sess, lib))
258 .find(|lib| {
259 let fm_id = match lib.foreign_module {
260 Some(id) => id,
261 None => return false,
262 };
263 let map = tcx.foreign_modules(id.krate);
264 map.get(&fm_id)
265 .expect("failed to find foreign module")
266 .foreign_items
267 .contains(&id)
268 })
269 .map(|l| l.kind)
270 },
271 native_libraries: |tcx, cnum| {
272 assert_eq!(cnum, LOCAL_CRATE);
273 Lrc::new(native_libs::collect(tcx))
274 },
275 foreign_modules: |tcx, cnum| {
276 assert_eq!(cnum, LOCAL_CRATE);
277 let modules: FxHashMap<DefId, ForeignModule> =
278 foreign_modules::collect(tcx).into_iter().map(|m| (m.def_id, m)).collect();
279 Lrc::new(modules)
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<_>, export: &Export, parent: DefId| {
318 if !export.vis.is_public() {
319 return;
320 }
321
322 if let Some(child) = export.res.opt_def_id() {
323 if export.ident.name == kw::Underscore {
324 fallback_map.insert(child, parent);
325 return;
326 }
327
328 match visible_parent_map.entry(child) {
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 child.is_local() && entry.get().is_local() {
333 entry.insert(parent);
334 }
335 }
336 Entry::Vacant(entry) => {
337 entry.insert(parent);
338 bfs_queue.push_back(child);
339 }
340 }
341 }
342 };
343
344 while let Some(def) = bfs_queue.pop_front() {
345 for child in tcx.item_children(def).iter() {
346 add_child(bfs_queue, child, def);
347 }
348 }
349
350 // Fill in any missing entries with the (less preferable) path ending in `::_`.
351 // We still use this path in a diagnostic that suggests importing `::*`.
352 for (child, parent) in fallback_map {
353 visible_parent_map.entry(child).or_insert(parent);
354 }
355
356 visible_parent_map
357 },
358
359 dependency_formats: |tcx, ()| Lrc::new(crate::dependency_format::calculate(tcx)),
360 has_global_allocator: |tcx, cnum| {
361 assert_eq!(cnum, LOCAL_CRATE);
362 CStore::from_tcx(tcx).has_global_allocator()
363 },
364 postorder_cnums: |tcx, ()| {
365 tcx.arena
366 .alloc_slice(&CStore::from_tcx(tcx).crate_dependencies_in_postorder(LOCAL_CRATE))
367 },
368 crates: |tcx, ()| tcx.arena.alloc_from_iter(CStore::from_tcx(tcx).crates_untracked()),
369
370 ..*providers
371 };
372 }
373
374 impl CStore {
375 pub fn struct_field_names_untracked(&self, def: DefId, sess: &Session) -> Vec<Spanned<Symbol>> {
376 self.get_crate_data(def.krate).get_struct_field_names(def.index, sess)
377 }
378
379 pub fn struct_field_visibilities_untracked(&self, def: DefId) -> Vec<Visibility> {
380 self.get_crate_data(def.krate).get_struct_field_visibilities(def.index)
381 }
382
383 pub fn ctor_def_id_and_kind_untracked(&self, def: DefId) -> Option<(DefId, CtorKind)> {
384 self.get_crate_data(def.krate).get_ctor_def_id_and_kind(def.index)
385 }
386
387 pub fn visibility_untracked(&self, def: DefId) -> Visibility {
388 self.get_crate_data(def.krate).get_visibility(def.index)
389 }
390
391 pub fn item_children_untracked(&self, def_id: DefId, sess: &Session) -> Vec<Export> {
392 let mut result = vec![];
393 self.get_crate_data(def_id.krate).each_child_of_item(
394 def_id.index,
395 |child| result.push(child),
396 sess,
397 );
398 result
399 }
400
401 pub fn load_macro_untracked(&self, id: DefId, sess: &Session) -> LoadedMacro {
402 let _prof_timer = sess.prof.generic_activity("metadata_load_macro");
403
404 let data = self.get_crate_data(id.krate);
405 if data.root.is_proc_macro_crate() {
406 return LoadedMacro::ProcMacro(data.load_proc_macro(id.index, sess));
407 }
408
409 let span = data.get_span(id.index, sess);
410
411 LoadedMacro::MacroDef(
412 ast::Item {
413 ident: data.item_ident(id.index, sess),
414 id: ast::DUMMY_NODE_ID,
415 span,
416 attrs: data.get_item_attrs(id.index, sess).collect(),
417 kind: ast::ItemKind::MacroDef(data.get_macro(id.index, sess)),
418 vis: ast::Visibility {
419 span: span.shrink_to_lo(),
420 kind: ast::VisibilityKind::Inherited,
421 tokens: None,
422 },
423 tokens: None,
424 },
425 data.root.edition,
426 )
427 }
428
429 pub fn fn_has_self_parameter_untracked(&self, def: DefId) -> bool {
430 self.get_crate_data(def.krate).get_fn_has_self_parameter(def.index)
431 }
432
433 pub fn crate_source_untracked(&self, cnum: CrateNum) -> CrateSource {
434 self.get_crate_data(cnum).source.clone()
435 }
436
437 pub fn get_span_untracked(&self, def_id: DefId, sess: &Session) -> Span {
438 self.get_crate_data(def_id.krate).get_span(def_id.index, sess)
439 }
440
441 pub fn def_kind(&self, def: DefId) -> DefKind {
442 self.get_crate_data(def.krate).def_kind(def.index)
443 }
444
445 pub fn crates_untracked(&self) -> impl Iterator<Item = CrateNum> + '_ {
446 self.iter_crate_data().map(|(cnum, _)| cnum)
447 }
448
449 pub fn item_generics_num_lifetimes(&self, def_id: DefId, sess: &Session) -> usize {
450 self.get_crate_data(def_id.krate).get_generics(def_id.index, sess).own_counts().lifetimes
451 }
452
453 pub fn module_expansion_untracked(&self, def_id: DefId, sess: &Session) -> ExpnId {
454 self.get_crate_data(def_id.krate).module_expansion(def_id.index, sess)
455 }
456
457 /// Only public-facing way to traverse all the definitions in a non-local crate.
458 /// Critically useful for this third-party project: <https://github.com/hacspec/hacspec>.
459 /// See <https://github.com/rust-lang/rust/pull/85889> for context.
460 pub fn num_def_ids_untracked(&self, cnum: CrateNum) -> usize {
461 self.get_crate_data(cnum).num_def_ids()
462 }
463
464 pub fn item_attrs_untracked(&self, def_id: DefId, sess: &Session) -> Vec<ast::Attribute> {
465 self.get_crate_data(def_id.krate).get_item_attrs(def_id.index, sess).collect()
466 }
467
468 pub fn get_proc_macro_quoted_span_untracked(
469 &self,
470 cnum: CrateNum,
471 id: usize,
472 sess: &Session,
473 ) -> Span {
474 self.get_crate_data(cnum).get_proc_macro_quoted_span(id, sess)
475 }
476 }
477
478 impl CrateStore for CStore {
479 fn as_any(&self) -> &dyn Any {
480 self
481 }
482
483 fn crate_name(&self, cnum: CrateNum) -> Symbol {
484 self.get_crate_data(cnum).root.name
485 }
486
487 fn stable_crate_id(&self, cnum: CrateNum) -> StableCrateId {
488 self.get_crate_data(cnum).root.stable_crate_id
489 }
490
491 fn stable_crate_id_to_crate_num(&self, stable_crate_id: StableCrateId) -> CrateNum {
492 self.stable_crate_ids[&stable_crate_id]
493 }
494
495 /// Returns the `DefKey` for a given `DefId`. This indicates the
496 /// parent `DefId` as well as some idea of what kind of data the
497 /// `DefId` refers to.
498 fn def_key(&self, def: DefId) -> DefKey {
499 self.get_crate_data(def.krate).def_key(def.index)
500 }
501
502 fn def_path(&self, def: DefId) -> DefPath {
503 self.get_crate_data(def.krate).def_path(def.index)
504 }
505
506 fn def_path_hash(&self, def: DefId) -> DefPathHash {
507 self.get_crate_data(def.krate).def_path_hash(def.index)
508 }
509
510 fn def_path_hash_to_def_id(&self, cnum: CrateNum, hash: DefPathHash) -> DefId {
511 let def_index = self.get_crate_data(cnum).def_path_hash_to_def_index(hash);
512 DefId { krate: cnum, index: def_index }
513 }
514
515 fn expn_hash_to_expn_id(
516 &self,
517 sess: &Session,
518 cnum: CrateNum,
519 index_guess: u32,
520 hash: ExpnHash,
521 ) -> ExpnId {
522 self.get_crate_data(cnum).expn_hash_to_expn_id(sess, index_guess, hash)
523 }
524
525 fn import_source_files(&self, sess: &Session, cnum: CrateNum) {
526 self.get_crate_data(cnum).imported_source_files(sess);
527 }
528 }