]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs
rustdoc: Collect traits in scope for foreign inherent impls
[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, 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::middle::stability::DeprecationEntry;
13 use rustc_middle::ty::fast_reject::SimplifiedType;
14 use rustc_middle::ty::query::{ExternProviders, Providers};
15 use rustc_middle::ty::{self, TyCtxt, Visibility};
16 use rustc_session::cstore::{CrateSource, CrateStore, ForeignModule};
17 use rustc_session::utils::NativeLibKind;
18 use rustc_session::{Session, StableCrateId};
19 use rustc_span::hygiene::{ExpnHash, ExpnId};
20 use rustc_span::source_map::{Span, Spanned};
21 use rustc_span::symbol::{kw, Symbol};
22
23 use rustc_data_structures::sync::Lrc;
24 use smallvec::SmallVec;
25 use std::any::Any;
26
27 macro_rules! provide {
28     (<$lt:tt> $tcx:ident, $def_id:ident, $other:ident, $cdata:ident,
29       $($name:ident => $compute:block)*) => {
30         pub fn provide_extern(providers: &mut ExternProviders) {
31             $(fn $name<$lt>(
32                 $tcx: TyCtxt<$lt>,
33                 def_id_arg: ty::query::query_keys::$name<$lt>,
34             ) -> ty::query::query_values::$name<$lt> {
35                 let _prof_timer =
36                     $tcx.prof.generic_activity(concat!("metadata_decode_entry_", stringify!($name)));
37
38                 #[allow(unused_variables)]
39                 let ($def_id, $other) = def_id_arg.into_args();
40                 assert!(!$def_id.is_local());
41
42                 // External query providers call `crate_hash` in order to register a dependency
43                 // on the crate metadata. The exception is `crate_hash` itself, which obviously
44                 // doesn't need to do this (and can't, as it would cause a query cycle).
45                 use rustc_middle::dep_graph::DepKind;
46                 if DepKind::$name != DepKind::crate_hash && $tcx.dep_graph.is_fully_enabled() {
47                     $tcx.ensure().crate_hash($def_id.krate);
48                 }
49
50                 let $cdata = CStore::from_tcx($tcx).get_crate_data($def_id.krate);
51
52                 $compute
53             })*
54
55             *providers = ExternProviders {
56                 $($name,)*
57                 ..*providers
58             };
59         }
60     }
61 }
62
63 // small trait to work around different signature queries all being defined via
64 // the macro above.
65 trait IntoArgs {
66     fn into_args(self) -> (DefId, DefId);
67 }
68
69 impl IntoArgs for DefId {
70     fn into_args(self) -> (DefId, DefId) {
71         (self, self)
72     }
73 }
74
75 impl IntoArgs for CrateNum {
76     fn into_args(self) -> (DefId, DefId) {
77         (self.as_def_id(), self.as_def_id())
78     }
79 }
80
81 impl IntoArgs for (CrateNum, DefId) {
82     fn into_args(self) -> (DefId, DefId) {
83         (self.0.as_def_id(), self.1)
84     }
85 }
86
87 impl<'tcx> IntoArgs for ty::InstanceDef<'tcx> {
88     fn into_args(self) -> (DefId, DefId) {
89         (self.def_id(), self.def_id())
90     }
91 }
92
93 provide! { <'tcx> tcx, def_id, other, cdata,
94     type_of => { cdata.get_type(def_id.index, tcx) }
95     generics_of => { cdata.get_generics(def_id.index, tcx.sess) }
96     explicit_predicates_of => { cdata.get_explicit_predicates(def_id.index, tcx) }
97     inferred_outlives_of => { cdata.get_inferred_outlives(def_id.index, tcx) }
98     super_predicates_of => { cdata.get_super_predicates(def_id.index, tcx) }
99     explicit_item_bounds => { cdata.get_explicit_item_bounds(def_id.index, tcx) }
100     trait_def => { cdata.get_trait_def(def_id.index, tcx.sess) }
101     adt_def => { cdata.get_adt_def(def_id.index, tcx) }
102     adt_destructor => {
103         let _ = cdata;
104         tcx.calculate_dtor(def_id, |_,_| Ok(()))
105     }
106     variances_of => { tcx.arena.alloc_from_iter(cdata.get_item_variances(def_id.index)) }
107     associated_item_def_ids => { cdata.get_associated_item_def_ids(tcx, def_id.index) }
108     associated_item => { cdata.get_associated_item(def_id.index, tcx.sess) }
109     impl_trait_ref => { cdata.get_impl_trait(def_id.index, tcx) }
110     impl_polarity => { cdata.get_impl_polarity(def_id.index) }
111     coerce_unsized_info => {
112         cdata.get_coerce_unsized_info(def_id.index).unwrap_or_else(|| {
113             bug!("coerce_unsized_info: `{:?}` is missing its info", def_id);
114         })
115     }
116     optimized_mir => { tcx.arena.alloc(cdata.get_optimized_mir(tcx, def_id.index)) }
117     mir_for_ctfe => { tcx.arena.alloc(cdata.get_mir_for_ctfe(tcx, def_id.index)) }
118     promoted_mir => { tcx.arena.alloc(cdata.get_promoted_mir(tcx, def_id.index)) }
119     thir_abstract_const => { cdata.get_thir_abstract_const(tcx, def_id.index) }
120     unused_generic_params => { cdata.get_unused_generic_params(def_id.index) }
121     const_param_default => { tcx.mk_const(cdata.get_const_param_default(tcx, def_id.index)) }
122     mir_const_qualif => { cdata.mir_const_qualif(def_id.index) }
123     fn_sig => { cdata.fn_sig(def_id.index, tcx) }
124     inherent_impls => { cdata.get_inherent_implementations_for_type(tcx, def_id.index) }
125     is_const_fn_raw => { cdata.is_const_fn_raw(def_id.index) }
126     asyncness => { cdata.asyncness(def_id.index) }
127     is_foreign_item => { cdata.is_foreign_item(def_id.index) }
128     static_mutability => { cdata.static_mutability(def_id.index) }
129     generator_kind => { cdata.generator_kind(def_id.index) }
130     opt_def_kind => { Some(cdata.def_kind(def_id.index)) }
131     def_span => { cdata.get_span(def_id.index, &tcx.sess) }
132     def_ident_span => { cdata.opt_item_ident(def_id.index, &tcx.sess).map(|ident| ident.span) }
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(cdata.get_item_attrs(def_id.index, tcx.sess)) }
143     fn_arg_names => { cdata.get_fn_param_names(tcx, def_id.index) }
144     rendered_const => { cdata.get_rendered_const(def_id.index) }
145     impl_parent => { cdata.get_parent_impl(def_id.index) }
146     trait_of_item => { cdata.get_trait_of_item(def_id.index) }
147     is_mir_available => { cdata.is_item_mir_available(def_id.index) }
148     is_ctfe_mir_available => { cdata.is_ctfe_mir_available(def_id.index) }
149
150     dylib_dependency_formats => { cdata.get_dylib_dependency_formats(tcx) }
151     is_private_dep => { cdata.private_dep }
152     is_panic_runtime => { cdata.root.panic_runtime }
153     is_compiler_builtins => { cdata.root.compiler_builtins }
154     has_global_allocator => { cdata.root.has_global_allocator }
155     has_panic_handler => { cdata.root.has_panic_handler }
156     is_profiler_runtime => { cdata.root.profiler_runtime }
157     panic_strategy => { cdata.root.panic_strategy }
158     panic_in_drop_strategy => { cdata.root.panic_in_drop_strategy }
159     extern_crate => {
160         let r = *cdata.extern_crate.lock();
161         r.map(|c| &*tcx.arena.alloc(c))
162     }
163     is_no_builtins => { cdata.root.no_builtins }
164     symbol_mangling_version => { cdata.root.symbol_mangling_version }
165     impl_defaultness => { cdata.get_impl_defaultness(def_id.index) }
166     impl_constness => { cdata.get_impl_constness(def_id.index) }
167     reachable_non_generics => {
168         let reachable_non_generics = tcx
169             .exported_symbols(cdata.cnum)
170             .iter()
171             .filter_map(|&(exported_symbol, export_level)| {
172                 if let ExportedSymbol::NonGeneric(def_id) = exported_symbol {
173                     Some((def_id, export_level))
174                 } else {
175                     None
176                 }
177             })
178             .collect();
179
180         reachable_non_generics
181     }
182     native_libraries => { Lrc::new(cdata.get_native_libraries(tcx.sess).collect()) }
183     foreign_modules => {
184         Lrc::new(cdata.get_foreign_modules(tcx.sess).map(|m| (m.def_id, m)).collect())
185     }
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     traits_in_crate => { tcx.arena.alloc_from_iter(cdata.get_traits()) }
193     implementations_of_trait => { cdata.get_implementations_of_trait(tcx, other) }
194
195     visibility => { cdata.get_visibility(def_id.index) }
196     dep_kind => {
197         let r = *cdata.dep_kind.lock();
198         r
199     }
200     module_children => {
201         let mut result = SmallVec::<[_; 8]>::new();
202         cdata.for_each_module_child(def_id.index, |child| result.push(child), tcx.sess);
203         tcx.arena.alloc_slice(&result)
204     }
205     defined_lib_features => { cdata.get_lib_features(tcx) }
206     defined_lang_items => { cdata.get_lang_items(tcx) }
207     diagnostic_items => { cdata.get_diagnostic_items() }
208     missing_lang_items => { cdata.get_missing_lang_items(tcx) }
209
210     missing_extern_crate_item => {
211         let r = matches!(*cdata.extern_crate.borrow(), Some(extern_crate) if !extern_crate.is_direct());
212         r
213     }
214
215     used_crate_source => { Lrc::new(cdata.source.clone()) }
216
217     exported_symbols => {
218         let syms = cdata.exported_symbols(tcx);
219
220         // FIXME rust-lang/rust#64319, rust-lang/rust#64872: We want
221         // to block export of generics from dylibs, but we must fix
222         // rust-lang/rust#65890 before we can do that robustly.
223
224         syms
225     }
226
227     crate_extern_paths => { cdata.source().paths().cloned().collect() }
228     expn_that_defined => { cdata.get_expn_that_defined(def_id.index, tcx.sess) }
229 }
230
231 pub(in crate::rmeta) fn provide(providers: &mut Providers) {
232     // FIXME(#44234) - almost all of these queries have no sub-queries and
233     // therefore no actual inputs, they're just reading tables calculated in
234     // resolve! Does this work? Unsure! That's what the issue is about
235     *providers = Providers {
236         allocator_kind: |tcx, ()| CStore::from_tcx(tcx).allocator_kind(),
237         is_dllimport_foreign_item: |tcx, id| match tcx.native_library_kind(id) {
238             Some(
239                 NativeLibKind::Dylib { .. } | NativeLibKind::RawDylib | NativeLibKind::Unspecified,
240             ) => true,
241             _ => false,
242         },
243         is_statically_included_foreign_item: |tcx, id| {
244             matches!(tcx.native_library_kind(id), Some(NativeLibKind::Static { .. }))
245         },
246         is_private_dep: |_tcx, cnum| {
247             assert_eq!(cnum, LOCAL_CRATE);
248             false
249         },
250         native_library_kind: |tcx, id| {
251             tcx.native_libraries(id.krate)
252                 .iter()
253                 .filter(|lib| native_libs::relevant_lib(&tcx.sess, lib))
254                 .find(|lib| {
255                     let fm_id = match lib.foreign_module {
256                         Some(id) => id,
257                         None => return false,
258                     };
259                     let map = tcx.foreign_modules(id.krate);
260                     map.get(&fm_id)
261                         .expect("failed to find foreign module")
262                         .foreign_items
263                         .contains(&id)
264                 })
265                 .map(|l| l.kind)
266         },
267         native_libraries: |tcx, cnum| {
268             assert_eq!(cnum, LOCAL_CRATE);
269             Lrc::new(native_libs::collect(tcx))
270         },
271         foreign_modules: |tcx, cnum| {
272             assert_eq!(cnum, LOCAL_CRATE);
273             let modules: FxHashMap<DefId, ForeignModule> =
274                 foreign_modules::collect(tcx).into_iter().map(|m| (m.def_id, m)).collect();
275             Lrc::new(modules)
276         },
277
278         // Returns a map from a sufficiently visible external item (i.e., an
279         // external item that is visible from at least one local module) to a
280         // sufficiently visible parent (considering modules that re-export the
281         // external item to be parents).
282         visible_parent_map: |tcx, ()| {
283             use std::collections::hash_map::Entry;
284             use std::collections::vec_deque::VecDeque;
285
286             let mut visible_parent_map: DefIdMap<DefId> = Default::default();
287             // This is a secondary visible_parent_map, storing the DefId of parents that re-export
288             // the child as `_`. Since we prefer parents that don't do this, merge this map at the
289             // end, only if we're missing any keys from the former.
290             let mut fallback_map: DefIdMap<DefId> = Default::default();
291
292             // Issue 46112: We want the map to prefer the shortest
293             // paths when reporting the path to an item. Therefore we
294             // build up the map via a breadth-first search (BFS),
295             // which naturally yields minimal-length paths.
296             //
297             // Note that it needs to be a BFS over the whole forest of
298             // crates, not just each individual crate; otherwise you
299             // only get paths that are locally minimal with respect to
300             // whatever crate we happened to encounter first in this
301             // traversal, but not globally minimal across all crates.
302             let bfs_queue = &mut VecDeque::new();
303
304             for &cnum in tcx.crates(()) {
305                 // Ignore crates without a corresponding local `extern crate` item.
306                 if tcx.missing_extern_crate_item(cnum) {
307                     continue;
308                 }
309
310                 bfs_queue.push_back(DefId { krate: cnum, index: CRATE_DEF_INDEX });
311             }
312
313             let mut add_child = |bfs_queue: &mut VecDeque<_>, child: &ModChild, parent: DefId| {
314                 if !child.vis.is_public() {
315                     return;
316                 }
317
318                 if let Some(def_id) = child.res.opt_def_id() {
319                     if child.ident.name == kw::Underscore {
320                         fallback_map.insert(def_id, parent);
321                         return;
322                     }
323
324                     match visible_parent_map.entry(def_id) {
325                         Entry::Occupied(mut entry) => {
326                             // If `child` is defined in crate `cnum`, ensure
327                             // that it is mapped to a parent in `cnum`.
328                             if def_id.is_local() && entry.get().is_local() {
329                                 entry.insert(parent);
330                             }
331                         }
332                         Entry::Vacant(entry) => {
333                             entry.insert(parent);
334                             if matches!(
335                                 child.res,
336                                 Res::Def(DefKind::Mod | DefKind::Enum | DefKind::Trait, _)
337                             ) {
338                                 bfs_queue.push_back(def_id);
339                             }
340                         }
341                     }
342                 }
343             };
344
345             while let Some(def) = bfs_queue.pop_front() {
346                 for child in tcx.module_children(def).iter() {
347                     add_child(bfs_queue, child, def);
348                 }
349             }
350
351             // Fill in any missing entries with the (less preferable) path ending in `::_`.
352             // We still use this path in a diagnostic that suggests importing `::*`.
353             for (child, parent) in fallback_map {
354                 visible_parent_map.entry(child).or_insert(parent);
355             }
356
357             Lrc::new(visible_parent_map)
358         },
359
360         dependency_formats: |tcx, ()| Lrc::new(crate::dependency_format::calculate(tcx)),
361         has_global_allocator: |tcx, cnum| {
362             assert_eq!(cnum, LOCAL_CRATE);
363             CStore::from_tcx(tcx).has_global_allocator()
364         },
365         postorder_cnums: |tcx, ()| {
366             tcx.arena
367                 .alloc_slice(&CStore::from_tcx(tcx).crate_dependencies_in_postorder(LOCAL_CRATE))
368         },
369         crates: |tcx, ()| tcx.arena.alloc_from_iter(CStore::from_tcx(tcx).crates_untracked()),
370
371         ..*providers
372     };
373 }
374
375 impl CStore {
376     pub fn struct_field_names_untracked<'a>(
377         &'a self,
378         def: DefId,
379         sess: &'a Session,
380     ) -> impl Iterator<Item = Spanned<Symbol>> + 'a {
381         self.get_crate_data(def.krate).get_struct_field_names(def.index, sess)
382     }
383
384     pub fn struct_field_visibilities_untracked(
385         &self,
386         def: DefId,
387     ) -> impl Iterator<Item = Visibility> + '_ {
388         self.get_crate_data(def.krate).get_struct_field_visibilities(def.index)
389     }
390
391     pub fn ctor_def_id_and_kind_untracked(&self, def: DefId) -> Option<(DefId, CtorKind)> {
392         self.get_crate_data(def.krate).get_ctor_def_id_and_kind(def.index)
393     }
394
395     pub fn visibility_untracked(&self, def: DefId) -> Visibility {
396         self.get_crate_data(def.krate).get_visibility(def.index)
397     }
398
399     pub fn module_children_untracked(&self, def_id: DefId, sess: &Session) -> Vec<ModChild> {
400         let mut result = vec![];
401         self.get_crate_data(def_id.krate).for_each_module_child(
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         LoadedMacro::MacroDef(
420             ast::Item {
421                 ident: data.item_ident(id.index, sess),
422                 id: ast::DUMMY_NODE_ID,
423                 span,
424                 attrs: data.get_item_attrs(id.index, sess).collect(),
425                 kind: ast::ItemKind::MacroDef(data.get_macro(id.index, sess)),
426                 vis: ast::Visibility {
427                     span: span.shrink_to_lo(),
428                     kind: ast::VisibilityKind::Inherited,
429                     tokens: None,
430                 },
431                 tokens: None,
432             },
433             data.root.edition,
434         )
435     }
436
437     pub fn fn_has_self_parameter_untracked(&self, def: DefId) -> bool {
438         self.get_crate_data(def.krate).get_fn_has_self_parameter(def.index)
439     }
440
441     pub fn crate_source_untracked(&self, cnum: CrateNum) -> CrateSource {
442         self.get_crate_data(cnum).source.clone()
443     }
444
445     pub fn get_span_untracked(&self, def_id: DefId, sess: &Session) -> Span {
446         self.get_crate_data(def_id.krate).get_span(def_id.index, sess)
447     }
448
449     pub fn def_kind(&self, def: DefId) -> DefKind {
450         self.get_crate_data(def.krate).def_kind(def.index)
451     }
452
453     pub fn crates_untracked(&self) -> impl Iterator<Item = CrateNum> + '_ {
454         self.iter_crate_data().map(|(cnum, _)| cnum)
455     }
456
457     pub fn item_generics_num_lifetimes(&self, def_id: DefId, sess: &Session) -> usize {
458         self.get_crate_data(def_id.krate).get_generics(def_id.index, sess).own_counts().lifetimes
459     }
460
461     pub fn module_expansion_untracked(&self, def_id: DefId, sess: &Session) -> ExpnId {
462         self.get_crate_data(def_id.krate).module_expansion(def_id.index, sess)
463     }
464
465     /// Only public-facing way to traverse all the definitions in a non-local crate.
466     /// Critically useful for this third-party project: <https://github.com/hacspec/hacspec>.
467     /// See <https://github.com/rust-lang/rust/pull/85889> for context.
468     pub fn num_def_ids_untracked(&self, cnum: CrateNum) -> usize {
469         self.get_crate_data(cnum).num_def_ids()
470     }
471
472     pub fn item_attrs_untracked<'a>(
473         &'a self,
474         def_id: DefId,
475         sess: &'a Session,
476     ) -> impl Iterator<Item = ast::Attribute> + 'a {
477         self.get_crate_data(def_id.krate).get_item_attrs(def_id.index, sess)
478     }
479
480     pub fn get_proc_macro_quoted_span_untracked(
481         &self,
482         cnum: CrateNum,
483         id: usize,
484         sess: &Session,
485     ) -> Span {
486         self.get_crate_data(cnum).get_proc_macro_quoted_span(id, sess)
487     }
488
489     /// Decodes all traits in the crate (for rustdoc).
490     pub fn traits_in_crate_untracked(&self, cnum: CrateNum) -> impl Iterator<Item = DefId> + '_ {
491         self.get_crate_data(cnum).get_traits()
492     }
493
494     /// Decodes all trait impls in the crate (for rustdoc).
495     pub fn trait_impls_in_crate_untracked(
496         &self,
497         cnum: CrateNum,
498     ) -> impl Iterator<Item = (DefId, DefId, Option<SimplifiedType>)> + '_ {
499         self.get_crate_data(cnum).get_trait_impls()
500     }
501
502     /// Decodes all inherent impls in the crate (for rustdoc).
503     pub fn inherent_impls_in_crate_untracked(
504         &self,
505         cnum: CrateNum,
506     ) -> impl Iterator<Item = (DefId, DefId)> + '_ {
507         self.get_crate_data(cnum).get_inherent_impls()
508     }
509 }
510
511 impl CrateStore for CStore {
512     fn as_any(&self) -> &dyn Any {
513         self
514     }
515
516     fn crate_name(&self, cnum: CrateNum) -> Symbol {
517         self.get_crate_data(cnum).root.name
518     }
519
520     fn stable_crate_id(&self, cnum: CrateNum) -> StableCrateId {
521         self.get_crate_data(cnum).root.stable_crate_id
522     }
523
524     fn stable_crate_id_to_crate_num(&self, stable_crate_id: StableCrateId) -> CrateNum {
525         self.stable_crate_ids[&stable_crate_id]
526     }
527
528     /// Returns the `DefKey` for a given `DefId`. This indicates the
529     /// parent `DefId` as well as some idea of what kind of data the
530     /// `DefId` refers to.
531     fn def_key(&self, def: DefId) -> DefKey {
532         self.get_crate_data(def.krate).def_key(def.index)
533     }
534
535     fn def_path(&self, def: DefId) -> DefPath {
536         self.get_crate_data(def.krate).def_path(def.index)
537     }
538
539     fn def_path_hash(&self, def: DefId) -> DefPathHash {
540         self.get_crate_data(def.krate).def_path_hash(def.index)
541     }
542
543     fn def_path_hash_to_def_id(&self, cnum: CrateNum, hash: DefPathHash) -> DefId {
544         let def_index = self.get_crate_data(cnum).def_path_hash_to_def_index(hash);
545         DefId { krate: cnum, index: def_index }
546     }
547
548     fn expn_hash_to_expn_id(
549         &self,
550         sess: &Session,
551         cnum: CrateNum,
552         index_guess: u32,
553         hash: ExpnHash,
554     ) -> ExpnId {
555         self.get_crate_data(cnum).expn_hash_to_expn_id(sess, index_guess, hash)
556     }
557
558     fn import_source_files(&self, sess: &Session, cnum: CrateNum) {
559         self.get_crate_data(cnum).imported_source_files(sess);
560     }
561 }