]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs
Rollup merge of #86011 - tlyu:correct-sized-bound-spans, r=estebank
[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
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::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::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 Providers) {
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 = Providers {
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 provide! { <'tcx> tcx, def_id, other, cdata,
87     type_of => { cdata.get_type(def_id.index, tcx) }
88     generics_of => { cdata.get_generics(def_id.index, tcx.sess) }
89     explicit_predicates_of => { cdata.get_explicit_predicates(def_id.index, tcx) }
90     inferred_outlives_of => { cdata.get_inferred_outlives(def_id.index, tcx) }
91     super_predicates_of => { cdata.get_super_predicates(def_id.index, tcx) }
92     explicit_item_bounds => { cdata.get_explicit_item_bounds(def_id.index, tcx) }
93     trait_def => { cdata.get_trait_def(def_id.index, tcx.sess) }
94     adt_def => { cdata.get_adt_def(def_id.index, tcx) }
95     adt_destructor => {
96         let _ = cdata;
97         tcx.calculate_dtor(def_id, |_,_| Ok(()))
98     }
99     variances_of => { tcx.arena.alloc_from_iter(cdata.get_item_variances(def_id.index)) }
100     associated_item_def_ids => {
101         let mut result = SmallVec::<[_; 8]>::new();
102         cdata.each_child_of_item(def_id.index,
103           |child| result.push(child.res.def_id()), tcx.sess);
104         tcx.arena.alloc_slice(&result)
105     }
106     associated_item => { cdata.get_associated_item(def_id.index, tcx.sess) }
107     impl_trait_ref => { cdata.get_impl_trait(def_id.index, tcx) }
108     impl_polarity => { cdata.get_impl_polarity(def_id.index) }
109     coerce_unsized_info => {
110         cdata.get_coerce_unsized_info(def_id.index).unwrap_or_else(|| {
111             bug!("coerce_unsized_info: `{:?}` is missing its info", def_id);
112         })
113     }
114     optimized_mir => { tcx.arena.alloc(cdata.get_optimized_mir(tcx, def_id.index)) }
115     mir_for_ctfe => { tcx.arena.alloc(cdata.get_mir_for_ctfe(tcx, def_id.index)) }
116     promoted_mir => { tcx.arena.alloc(cdata.get_promoted_mir(tcx, def_id.index)) }
117     thir_abstract_const => { cdata.get_thir_abstract_const(tcx, def_id.index) }
118     unused_generic_params => { cdata.get_unused_generic_params(def_id.index) }
119     const_param_default => { tcx.mk_const(cdata.get_const_param_default(tcx, def_id.index)) }
120     mir_const_qualif => { cdata.mir_const_qualif(def_id.index) }
121     fn_sig => { cdata.fn_sig(def_id.index, tcx) }
122     inherent_impls => { cdata.get_inherent_implementations_for_type(tcx, def_id.index) }
123     is_const_fn_raw => { cdata.is_const_fn_raw(def_id.index) }
124     asyncness => { cdata.asyncness(def_id.index) }
125     is_foreign_item => { cdata.is_foreign_item(def_id.index) }
126     static_mutability => { cdata.static_mutability(def_id.index) }
127     generator_kind => { cdata.generator_kind(def_id.index) }
128     opt_def_kind => { Some(cdata.def_kind(def_id.index)) }
129     def_span => { cdata.get_span(def_id.index, &tcx.sess) }
130     def_ident_span => {
131         cdata.try_item_ident(def_id.index, &tcx.sess).ok().map(|ident| ident.span)
132     }
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 => { tcx.arena.alloc_from_iter(
143         cdata.get_item_attrs(def_id.index, tcx.sess)
144     ) }
145     fn_arg_names => { cdata.get_fn_param_names(tcx, def_id.index) }
146     rendered_const => { cdata.get_rendered_const(def_id.index) }
147     impl_parent => { cdata.get_parent_impl(def_id.index) }
148     trait_of_item => { cdata.get_trait_of_item(def_id.index) }
149     is_mir_available => { cdata.is_item_mir_available(def_id.index) }
150     is_ctfe_mir_available => { cdata.is_ctfe_mir_available(def_id.index) }
151
152     dylib_dependency_formats => { cdata.get_dylib_dependency_formats(tcx) }
153     is_private_dep => { cdata.private_dep }
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     panic_in_drop_strategy => { cdata.root.panic_in_drop_strategy }
161     extern_crate => {
162         let r = *cdata.extern_crate.lock();
163         r.map(|c| &*tcx.arena.alloc(c))
164     }
165     is_no_builtins => { cdata.root.no_builtins }
166     symbol_mangling_version => { cdata.root.symbol_mangling_version }
167     impl_defaultness => { cdata.get_impl_defaultness(def_id.index) }
168     impl_constness => { cdata.get_impl_constness(def_id.index) }
169     reachable_non_generics => {
170         let reachable_non_generics = tcx
171             .exported_symbols(cdata.cnum)
172             .iter()
173             .filter_map(|&(exported_symbol, export_level)| {
174                 if let ExportedSymbol::NonGeneric(def_id) = exported_symbol {
175                     Some((def_id, export_level))
176                 } else {
177                     None
178                 }
179             })
180             .collect();
181
182         reachable_non_generics
183     }
184     native_libraries => { Lrc::new(cdata.get_native_libraries(tcx.sess)) }
185     foreign_modules => { cdata.get_foreign_modules(tcx) }
186     crate_hash => { cdata.root.hash }
187     crate_host_hash => { cdata.host_hash }
188     crate_name => { cdata.root.name }
189
190     extra_filename => { cdata.root.extra_filename.clone() }
191
192     implementations_of_trait => {
193         cdata.get_implementations_for_trait(tcx, Some(other))
194     }
195
196     all_trait_implementations => {
197         cdata.get_implementations_for_trait(tcx, None)
198     }
199
200     visibility => { cdata.get_visibility(def_id.index) }
201     dep_kind => {
202         let r = *cdata.dep_kind.lock();
203         r
204     }
205     item_children => {
206         let mut result = SmallVec::<[_; 8]>::new();
207         cdata.each_child_of_item(def_id.index, |child| result.push(child), tcx.sess);
208         tcx.arena.alloc_slice(&result)
209     }
210     defined_lib_features => { cdata.get_lib_features(tcx) }
211     defined_lang_items => { cdata.get_lang_items(tcx) }
212     diagnostic_items => { cdata.get_diagnostic_items() }
213     missing_lang_items => { cdata.get_missing_lang_items(tcx) }
214
215     missing_extern_crate_item => {
216         let r = matches!(*cdata.extern_crate.borrow(), Some(extern_crate) if !extern_crate.is_direct());
217         r
218     }
219
220     used_crate_source => { Lrc::new(cdata.source.clone()) }
221
222     exported_symbols => {
223         let syms = cdata.exported_symbols(tcx);
224
225         // FIXME rust-lang/rust#64319, rust-lang/rust#64872: We want
226         // to block export of generics from dylibs, but we must fix
227         // rust-lang/rust#65890 before we can do that robustly.
228
229         syms
230     }
231
232     crate_extern_paths => { cdata.source().paths().cloned().collect() }
233     expn_that_defined => { cdata.get_expn_that_defined(def_id.index, tcx.sess) }
234 }
235
236 pub fn provide(providers: &mut Providers) {
237     // FIXME(#44234) - almost all of these queries have no sub-queries and
238     // therefore no actual inputs, they're just reading tables calculated in
239     // resolve! Does this work? Unsure! That's what the issue is about
240     *providers = Providers {
241         allocator_kind: |tcx, ()| CStore::from_tcx(tcx).allocator_kind(),
242         is_dllimport_foreign_item: |tcx, id| match tcx.native_library_kind(id) {
243             Some(
244                 NativeLibKind::Dylib { .. } | NativeLibKind::RawDylib | NativeLibKind::Unspecified,
245             ) => true,
246             _ => false,
247         },
248         is_statically_included_foreign_item: |tcx, id| {
249             matches!(tcx.native_library_kind(id), Some(NativeLibKind::Static { .. }))
250         },
251         is_private_dep: |_tcx, cnum| {
252             assert_eq!(cnum, LOCAL_CRATE);
253             false
254         },
255         native_library_kind: |tcx, id| {
256             tcx.native_libraries(id.krate)
257                 .iter()
258                 .filter(|lib| native_libs::relevant_lib(&tcx.sess, lib))
259                 .find(|lib| {
260                     let fm_id = match lib.foreign_module {
261                         Some(id) => id,
262                         None => return false,
263                     };
264                     let map = tcx.foreign_modules(id.krate);
265                     map.get(&fm_id)
266                         .expect("failed to find foreign module")
267                         .foreign_items
268                         .contains(&id)
269                 })
270                 .map(|l| l.kind)
271         },
272         native_libraries: |tcx, cnum| {
273             assert_eq!(cnum, LOCAL_CRATE);
274             Lrc::new(native_libs::collect(tcx))
275         },
276         foreign_modules: |tcx, cnum| {
277             assert_eq!(cnum, LOCAL_CRATE);
278             let modules: FxHashMap<DefId, ForeignModule> =
279                 foreign_modules::collect(tcx).into_iter().map(|m| (m.def_id, m)).collect();
280             Lrc::new(modules)
281         },
282
283         // Returns a map from a sufficiently visible external item (i.e., an
284         // external item that is visible from at least one local module) to a
285         // sufficiently visible parent (considering modules that re-export the
286         // external item to be parents).
287         visible_parent_map: |tcx, ()| {
288             use std::collections::hash_map::Entry;
289             use std::collections::vec_deque::VecDeque;
290
291             let mut visible_parent_map: DefIdMap<DefId> = Default::default();
292
293             // Issue 46112: We want the map to prefer the shortest
294             // paths when reporting the path to an item. Therefore we
295             // build up the map via a breadth-first search (BFS),
296             // which naturally yields minimal-length paths.
297             //
298             // Note that it needs to be a BFS over the whole forest of
299             // crates, not just each individual crate; otherwise you
300             // only get paths that are locally minimal with respect to
301             // whatever crate we happened to encounter first in this
302             // traversal, but not globally minimal across all crates.
303             let bfs_queue = &mut VecDeque::new();
304
305             for &cnum in tcx.crates(()) {
306                 // Ignore crates without a corresponding local `extern crate` item.
307                 if tcx.missing_extern_crate_item(cnum) {
308                     continue;
309                 }
310
311                 bfs_queue.push_back(DefId { krate: cnum, index: CRATE_DEF_INDEX });
312             }
313
314             let mut add_child = |bfs_queue: &mut VecDeque<_>, child: &Export, parent: DefId| {
315                 if child.vis != ty::Visibility::Public {
316                     return;
317                 }
318
319                 if let Some(child) = child.res.opt_def_id() {
320                     match visible_parent_map.entry(child) {
321                         Entry::Occupied(mut entry) => {
322                             // If `child` is defined in crate `cnum`, ensure
323                             // that it is mapped to a parent in `cnum`.
324                             if child.is_local() && entry.get().is_local() {
325                                 entry.insert(parent);
326                             }
327                         }
328                         Entry::Vacant(entry) => {
329                             entry.insert(parent);
330                             bfs_queue.push_back(child);
331                         }
332                     }
333                 }
334             };
335
336             while let Some(def) = bfs_queue.pop_front() {
337                 for child in tcx.item_children(def).iter() {
338                     add_child(bfs_queue, child, def);
339                 }
340             }
341
342             visible_parent_map
343         },
344
345         dependency_formats: |tcx, ()| Lrc::new(crate::dependency_format::calculate(tcx)),
346         has_global_allocator: |tcx, cnum| {
347             assert_eq!(cnum, LOCAL_CRATE);
348             CStore::from_tcx(tcx).has_global_allocator()
349         },
350         postorder_cnums: |tcx, ()| {
351             tcx.arena
352                 .alloc_slice(&CStore::from_tcx(tcx).crate_dependencies_in_postorder(LOCAL_CRATE))
353         },
354         crates: |tcx, ()| tcx.arena.alloc_slice(&CStore::from_tcx(tcx).crates_untracked()),
355
356         ..*providers
357     };
358 }
359
360 impl CStore {
361     pub fn struct_field_names_untracked(&self, def: DefId, sess: &Session) -> Vec<Spanned<Symbol>> {
362         self.get_crate_data(def.krate).get_struct_field_names(def.index, sess)
363     }
364
365     pub fn struct_field_visibilities_untracked(&self, def: DefId) -> Vec<Visibility> {
366         self.get_crate_data(def.krate).get_struct_field_visibilities(def.index)
367     }
368
369     pub fn ctor_def_id_and_kind_untracked(&self, def: DefId) -> Option<(DefId, CtorKind)> {
370         self.get_crate_data(def.krate).get_ctor_def_id(def.index).map(|ctor_def_id| {
371             (ctor_def_id, self.get_crate_data(def.krate).get_ctor_kind(def.index))
372         })
373     }
374
375     pub fn visibility_untracked(&self, def: DefId) -> Visibility {
376         self.get_crate_data(def.krate).get_visibility(def.index)
377     }
378
379     pub fn item_children_untracked(&self, def_id: DefId, sess: &Session) -> Vec<Export> {
380         let mut result = vec![];
381         self.get_crate_data(def_id.krate).each_child_of_item(
382             def_id.index,
383             |child| result.push(child),
384             sess,
385         );
386         result
387     }
388
389     pub fn load_macro_untracked(&self, id: DefId, sess: &Session) -> LoadedMacro {
390         let _prof_timer = sess.prof.generic_activity("metadata_load_macro");
391
392         let data = self.get_crate_data(id.krate);
393         if data.root.is_proc_macro_crate() {
394             return LoadedMacro::ProcMacro(data.load_proc_macro(id.index, sess));
395         }
396
397         let span = data.get_span(id.index, sess);
398
399         let attrs = data.get_item_attrs(id.index, sess).collect();
400
401         let ident = data.item_ident(id.index, sess);
402
403         LoadedMacro::MacroDef(
404             ast::Item {
405                 ident,
406                 id: ast::DUMMY_NODE_ID,
407                 span,
408                 attrs,
409                 kind: ast::ItemKind::MacroDef(data.get_macro(id.index, sess)),
410                 vis: ast::Visibility {
411                     span: span.shrink_to_lo(),
412                     kind: ast::VisibilityKind::Inherited,
413                     tokens: None,
414                 },
415                 tokens: None,
416             },
417             data.root.edition,
418         )
419     }
420
421     pub fn associated_item_cloned_untracked(&self, def: DefId, sess: &Session) -> ty::AssocItem {
422         self.get_crate_data(def.krate).get_associated_item(def.index, sess)
423     }
424
425     pub fn crate_source_untracked(&self, cnum: CrateNum) -> CrateSource {
426         self.get_crate_data(cnum).source.clone()
427     }
428
429     pub fn get_span_untracked(&self, def_id: DefId, sess: &Session) -> Span {
430         self.get_crate_data(def_id.krate).get_span(def_id.index, sess)
431     }
432
433     pub fn def_kind(&self, def: DefId) -> DefKind {
434         self.get_crate_data(def.krate).def_kind(def.index)
435     }
436
437     pub fn crates_untracked(&self) -> Vec<CrateNum> {
438         let mut result = vec![];
439         self.iter_crate_data(|cnum, _| result.push(cnum));
440         result
441     }
442
443     pub fn item_generics_num_lifetimes(&self, def_id: DefId, sess: &Session) -> usize {
444         self.get_crate_data(def_id.krate).get_generics(def_id.index, sess).own_counts().lifetimes
445     }
446
447     pub fn module_expansion_untracked(&self, def_id: DefId, sess: &Session) -> ExpnId {
448         self.get_crate_data(def_id.krate).module_expansion(def_id.index, sess)
449     }
450
451     /// Only public-facing way to traverse all the definitions in a non-local crate.
452     /// Critically useful for this third-party project: <https://github.com/hacspec/hacspec>.
453     /// See <https://github.com/rust-lang/rust/pull/85889> for context.
454     pub fn num_def_ids_untracked(&self, cnum: CrateNum) -> usize {
455         self.get_crate_data(cnum).num_def_ids()
456     }
457
458     pub fn item_attrs(&self, def_id: DefId, sess: &Session) -> Vec<ast::Attribute> {
459         self.get_crate_data(def_id.krate).get_item_attrs(def_id.index, sess).collect()
460     }
461
462     pub fn get_proc_macro_quoted_span_untracked(
463         &self,
464         cnum: CrateNum,
465         id: usize,
466         sess: &Session,
467     ) -> Span {
468         self.get_crate_data(cnum).get_proc_macro_quoted_span(id, sess)
469     }
470 }
471
472 impl CrateStore for CStore {
473     fn as_any(&self) -> &dyn Any {
474         self
475     }
476
477     fn crate_name(&self, cnum: CrateNum) -> Symbol {
478         self.get_crate_data(cnum).root.name
479     }
480
481     fn stable_crate_id(&self, cnum: CrateNum) -> StableCrateId {
482         self.get_crate_data(cnum).root.stable_crate_id
483     }
484
485     fn stable_crate_id_to_crate_num(&self, stable_crate_id: StableCrateId) -> CrateNum {
486         self.stable_crate_ids[&stable_crate_id]
487     }
488
489     /// Returns the `DefKey` for a given `DefId`. This indicates the
490     /// parent `DefId` as well as some idea of what kind of data the
491     /// `DefId` refers to.
492     fn def_key(&self, def: DefId) -> DefKey {
493         self.get_crate_data(def.krate).def_key(def.index)
494     }
495
496     fn def_path(&self, def: DefId) -> DefPath {
497         self.get_crate_data(def.krate).def_path(def.index)
498     }
499
500     fn def_path_hash(&self, def: DefId) -> DefPathHash {
501         self.get_crate_data(def.krate).def_path_hash(def.index)
502     }
503
504     fn def_path_hash_to_def_id(&self, cnum: CrateNum, hash: DefPathHash) -> DefId {
505         let def_index = self.get_crate_data(cnum).def_path_hash_to_def_index(hash);
506         DefId { krate: cnum, index: def_index }
507     }
508
509     fn expn_hash_to_expn_id(
510         &self,
511         sess: &Session,
512         cnum: CrateNum,
513         index_guess: u32,
514         hash: ExpnHash,
515     ) -> ExpnId {
516         self.get_crate_data(cnum).expn_hash_to_expn_id(sess, index_guess, hash)
517     }
518 }