1 use crate::creader::{CStore, LoadedMacro};
2 use crate::foreign_modules;
4 use crate::native_libs;
5 use crate::rmeta::{self, encoder};
8 use rustc_ast::expand::allocator::AllocatorKind;
9 use rustc_data_structures::stable_map::FxHashMap;
10 use rustc_data_structures::svh::Svh;
12 use rustc_hir::def::DefKind;
13 use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, CRATE_DEF_INDEX, LOCAL_CRATE};
14 use rustc_hir::definitions::{DefKey, DefPath, DefPathHash};
15 use rustc_middle::hir::exports::Export;
16 use rustc_middle::middle::cstore::ForeignModule;
17 use rustc_middle::middle::cstore::{CrateSource, CrateStore, EncodedMetadata};
18 use rustc_middle::middle::exported_symbols::ExportedSymbol;
19 use rustc_middle::middle::stability::DeprecationEntry;
20 use rustc_middle::ty::query::Providers;
21 use rustc_middle::ty::{self, TyCtxt};
22 use rustc_session::utils::NativeLibKind;
23 use rustc_session::{CrateDisambiguator, Session};
24 use rustc_span::source_map::{Span, Spanned};
25 use rustc_span::symbol::Symbol;
27 use rustc_data_structures::sync::Lrc;
28 use rustc_span::ExpnId;
29 use smallvec::SmallVec;
32 macro_rules! provide {
33 (<$lt:tt> $tcx:ident, $def_id:ident, $other:ident, $cdata:ident,
34 $($name:ident => $compute:block)*) => {
35 pub fn provide_extern(providers: &mut Providers) {
38 def_id_arg: ty::query::query_keys::$name<$lt>,
39 ) -> ty::query::query_values::$name<$lt> {
41 $tcx.prof.generic_activity(concat!("metadata_decode_entry_", stringify!($name)));
43 #[allow(unused_variables)]
44 let ($def_id, $other) = def_id_arg.into_args();
45 assert!(!$def_id.is_local());
47 let $cdata = CStore::from_tcx($tcx).get_crate_data($def_id.krate);
49 if $tcx.dep_graph.is_fully_enabled() {
50 let crate_dep_node_index = $cdata.get_crate_dep_node_index($tcx);
51 $tcx.dep_graph.read_index(crate_dep_node_index);
57 *providers = Providers {
65 // small trait to work around different signature queries all being defined via
68 fn into_args(self) -> (DefId, DefId);
71 impl IntoArgs for DefId {
72 fn into_args(self) -> (DefId, DefId) {
77 impl IntoArgs for CrateNum {
78 fn into_args(self) -> (DefId, DefId) {
79 (self.as_def_id(), self.as_def_id())
83 impl IntoArgs for (CrateNum, DefId) {
84 fn into_args(self) -> (DefId, DefId) {
85 (self.0.as_def_id(), self.1)
89 provide! { <'tcx> tcx, def_id, other, cdata,
90 type_of => { cdata.get_type(def_id.index, tcx) }
91 generics_of => { cdata.get_generics(def_id.index, tcx.sess) }
92 explicit_predicates_of => { cdata.get_explicit_predicates(def_id.index, tcx) }
93 inferred_outlives_of => { cdata.get_inferred_outlives(def_id.index, tcx) }
94 super_predicates_of => { cdata.get_super_predicates(def_id.index, tcx) }
95 explicit_item_bounds => { cdata.get_explicit_item_bounds(def_id.index, tcx) }
96 trait_def => { cdata.get_trait_def(def_id.index, tcx.sess) }
97 adt_def => { cdata.get_adt_def(def_id.index, tcx) }
100 tcx.calculate_dtor(def_id, |_,_| Ok(()))
102 variances_of => { tcx.arena.alloc_from_iter(cdata.get_item_variances(def_id.index)) }
103 associated_item_def_ids => {
104 let mut result = SmallVec::<[_; 8]>::new();
105 cdata.each_child_of_item(def_id.index,
106 |child| result.push(child.res.def_id()), tcx.sess);
107 tcx.arena.alloc_slice(&result)
109 associated_item => { cdata.get_associated_item(def_id.index, tcx.sess) }
110 impl_trait_ref => { cdata.get_impl_trait(def_id.index, tcx) }
111 impl_polarity => { cdata.get_impl_polarity(def_id.index) }
112 coerce_unsized_info => {
113 cdata.get_coerce_unsized_info(def_id.index).unwrap_or_else(|| {
114 bug!("coerce_unsized_info: `{:?}` is missing its info", def_id);
117 optimized_mir => { tcx.arena.alloc(cdata.get_optimized_mir(tcx, def_id.index)) }
118 promoted_mir => { tcx.arena.alloc(cdata.get_promoted_mir(tcx, def_id.index)) }
119 mir_abstract_const => { cdata.get_mir_abstract_const(tcx, def_id.index) }
120 unused_generic_params => { cdata.get_unused_generic_params(def_id.index) }
121 mir_const_qualif => { cdata.mir_const_qualif(def_id.index) }
122 fn_sig => { cdata.fn_sig(def_id.index, tcx) }
123 inherent_impls => { cdata.get_inherent_implementations_for_type(tcx, def_id.index) }
124 is_const_fn_raw => { cdata.is_const_fn_raw(def_id.index) }
125 asyncness => { cdata.asyncness(def_id.index) }
126 is_foreign_item => { cdata.is_foreign_item(def_id.index) }
127 static_mutability => { cdata.static_mutability(def_id.index) }
128 generator_kind => { cdata.generator_kind(def_id.index) }
129 def_kind => { cdata.def_kind(def_id.index) }
130 def_span => { cdata.get_span(def_id.index, &tcx.sess) }
131 lookup_stability => {
132 cdata.get_stability(def_id.index).map(|s| tcx.intern_stability(s))
134 lookup_const_stability => {
135 cdata.get_const_stability(def_id.index).map(|s| tcx.intern_const_stability(s))
137 lookup_deprecation_entry => {
138 cdata.get_deprecation(def_id.index).map(DeprecationEntry::external)
140 item_attrs => { tcx.arena.alloc_from_iter(
141 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) }
149 dylib_dependency_formats => { cdata.get_dylib_dependency_formats(tcx) }
150 is_panic_runtime => { cdata.root.panic_runtime }
151 is_compiler_builtins => { cdata.root.compiler_builtins }
152 has_global_allocator => { cdata.root.has_global_allocator }
153 has_panic_handler => { cdata.root.has_panic_handler }
154 is_profiler_runtime => { cdata.root.profiler_runtime }
155 panic_strategy => { cdata.root.panic_strategy }
157 let r = *cdata.extern_crate.lock();
158 r.map(|c| &*tcx.arena.alloc(c))
160 is_no_builtins => { cdata.root.no_builtins }
161 symbol_mangling_version => { cdata.root.symbol_mangling_version }
162 impl_defaultness => { cdata.get_impl_defaultness(def_id.index) }
163 reachable_non_generics => {
164 let reachable_non_generics = tcx
165 .exported_symbols(cdata.cnum)
167 .filter_map(|&(exported_symbol, export_level)| {
168 if let ExportedSymbol::NonGeneric(def_id) = exported_symbol {
169 Some((def_id, export_level))
176 reachable_non_generics
178 native_libraries => { Lrc::new(cdata.get_native_libraries(tcx.sess)) }
179 foreign_modules => { cdata.get_foreign_modules(tcx) }
180 plugin_registrar_fn => {
181 cdata.root.plugin_registrar_fn.map(|index| {
182 DefId { krate: def_id.krate, index }
185 proc_macro_decls_static => {
186 cdata.root.proc_macro_data.as_ref().map(|data| {
189 index: data.proc_macro_decls_static,
193 crate_disambiguator => { cdata.root.disambiguator }
194 crate_hash => { cdata.root.hash }
195 crate_host_hash => { cdata.host_hash }
196 original_crate_name => { cdata.root.name }
198 extra_filename => { cdata.root.extra_filename.clone() }
200 implementations_of_trait => {
201 cdata.get_implementations_for_trait(tcx, Some(other))
204 all_trait_implementations => {
205 cdata.get_implementations_for_trait(tcx, None)
208 visibility => { cdata.get_visibility(def_id.index) }
210 let r = *cdata.dep_kind.lock();
213 crate_name => { cdata.root.name }
215 let mut result = SmallVec::<[_; 8]>::new();
216 cdata.each_child_of_item(def_id.index, |child| result.push(child), tcx.sess);
217 tcx.arena.alloc_slice(&result)
219 defined_lib_features => { cdata.get_lib_features(tcx) }
220 defined_lang_items => { cdata.get_lang_items(tcx) }
221 diagnostic_items => { cdata.get_diagnostic_items() }
222 missing_lang_items => { cdata.get_missing_lang_items(tcx) }
224 missing_extern_crate_item => {
225 let r = matches!(*cdata.extern_crate.borrow(), Some(extern_crate) if !extern_crate.is_direct());
229 used_crate_source => { Lrc::new(cdata.source.clone()) }
231 exported_symbols => {
232 let syms = cdata.exported_symbols(tcx);
234 // FIXME rust-lang/rust#64319, rust-lang/rust#64872: We want
235 // to block export of generics from dylibs, but we must fix
236 // rust-lang/rust#65890 before we can do that robustly.
241 crate_extern_paths => { cdata.source().paths().cloned().collect() }
242 expn_that_defined => { cdata.get_expn_that_defined(def_id.index, tcx.sess) }
245 pub fn provide(providers: &mut Providers) {
246 // FIXME(#44234) - almost all of these queries have no sub-queries and
247 // therefore no actual inputs, they're just reading tables calculated in
248 // resolve! Does this work? Unsure! That's what the issue is about
249 *providers = Providers {
250 is_dllimport_foreign_item: |tcx, id| match tcx.native_library_kind(id) {
251 Some(NativeLibKind::Dylib | NativeLibKind::RawDylib | NativeLibKind::Unspecified) => {
256 is_statically_included_foreign_item: |tcx, id| {
258 tcx.native_library_kind(id),
259 Some(NativeLibKind::StaticBundle | NativeLibKind::StaticNoBundle)
262 native_library_kind: |tcx, id| {
263 tcx.native_libraries(id.krate)
265 .filter(|lib| native_libs::relevant_lib(&tcx.sess, lib))
267 let fm_id = match lib.foreign_module {
269 None => return false,
271 let map = tcx.foreign_modules(id.krate);
273 .expect("failed to find foreign module")
279 native_libraries: |tcx, cnum| {
280 assert_eq!(cnum, LOCAL_CRATE);
281 Lrc::new(native_libs::collect(tcx))
283 foreign_modules: |tcx, cnum| {
284 assert_eq!(cnum, LOCAL_CRATE);
285 let modules: FxHashMap<DefId, ForeignModule> =
286 foreign_modules::collect(tcx).into_iter().map(|m| (m.def_id, m)).collect();
289 link_args: |tcx, cnum| {
290 assert_eq!(cnum, LOCAL_CRATE);
291 Lrc::new(link_args::collect(tcx))
294 // Returns a map from a sufficiently visible external item (i.e., an
295 // external item that is visible from at least one local module) to a
296 // sufficiently visible parent (considering modules that re-export the
297 // external item to be parents).
298 visible_parent_map: |tcx, cnum| {
299 use std::collections::hash_map::Entry;
300 use std::collections::vec_deque::VecDeque;
302 assert_eq!(cnum, LOCAL_CRATE);
303 let mut visible_parent_map: DefIdMap<DefId> = Default::default();
305 // Issue 46112: We want the map to prefer the shortest
306 // paths when reporting the path to an item. Therefore we
307 // build up the map via a breadth-first search (BFS),
308 // which naturally yields minimal-length paths.
310 // Note that it needs to be a BFS over the whole forest of
311 // crates, not just each individual crate; otherwise you
312 // only get paths that are locally minimal with respect to
313 // whatever crate we happened to encounter first in this
314 // traversal, but not globally minimal across all crates.
315 let bfs_queue = &mut VecDeque::new();
317 // Preferring shortest paths alone does not guarantee a
318 // deterministic result; so sort by crate num to avoid
319 // hashtable iteration non-determinism. This only makes
320 // things as deterministic as crate-nums assignment is,
321 // which is to say, its not deterministic in general. But
322 // we believe that libstd is consistently assigned crate
323 // num 1, so it should be enough to resolve #46112.
324 let mut crates: Vec<CrateNum> = (*tcx.crates()).to_owned();
327 for &cnum in crates.iter() {
328 // Ignore crates without a corresponding local `extern crate` item.
329 if tcx.missing_extern_crate_item(cnum) {
333 bfs_queue.push_back(DefId { krate: cnum, index: CRATE_DEF_INDEX });
336 // (restrict scope of mutable-borrow of `visible_parent_map`)
338 let visible_parent_map = &mut visible_parent_map;
340 |bfs_queue: &mut VecDeque<_>, child: &Export<hir::HirId>, parent: DefId| {
341 if child.vis != ty::Visibility::Public {
345 if let Some(child) = child.res.opt_def_id() {
346 match visible_parent_map.entry(child) {
347 Entry::Occupied(mut entry) => {
348 // If `child` is defined in crate `cnum`, ensure
349 // that it is mapped to a parent in `cnum`.
350 if child.krate == cnum && entry.get().krate != cnum {
351 entry.insert(parent);
354 Entry::Vacant(entry) => {
355 entry.insert(parent);
356 bfs_queue.push_back(child);
362 while let Some(def) = bfs_queue.pop_front() {
363 for child in tcx.item_children(def).iter() {
364 add_child(bfs_queue, child, def);
372 dependency_formats: |tcx, cnum| {
373 assert_eq!(cnum, LOCAL_CRATE);
374 Lrc::new(crate::dependency_format::calculate(tcx))
376 has_global_allocator: |tcx, cnum| {
377 assert_eq!(cnum, LOCAL_CRATE);
378 CStore::from_tcx(tcx).has_global_allocator()
380 postorder_cnums: |tcx, cnum| {
381 assert_eq!(cnum, LOCAL_CRATE);
382 tcx.arena.alloc_slice(&CStore::from_tcx(tcx).crate_dependencies_in_postorder(cnum))
390 pub fn struct_field_names_untracked(&self, def: DefId, sess: &Session) -> Vec<Spanned<Symbol>> {
391 self.get_crate_data(def.krate).get_struct_field_names(def.index, sess)
394 pub fn item_children_untracked(
398 ) -> Vec<Export<hir::HirId>> {
399 let mut result = vec![];
400 self.get_crate_data(def_id.krate).each_child_of_item(
402 |child| result.push(child),
408 pub fn load_macro_untracked(&self, id: DefId, sess: &Session) -> LoadedMacro {
409 let _prof_timer = sess.prof.generic_activity("metadata_load_macro");
411 let data = self.get_crate_data(id.krate);
412 if data.root.is_proc_macro_crate() {
413 return LoadedMacro::ProcMacro(data.load_proc_macro(id.index, sess));
416 let span = data.get_span(id.index, sess);
418 let attrs: Vec<_> = data.get_item_attrs(id.index, sess).collect();
420 let ident = data.item_ident(id.index, sess);
422 LoadedMacro::MacroDef(
425 id: ast::DUMMY_NODE_ID,
428 kind: ast::ItemKind::MacroDef(data.get_macro(id.index, sess)),
429 vis: ast::Visibility {
430 span: span.shrink_to_lo(),
431 kind: ast::VisibilityKind::Inherited,
440 pub fn associated_item_cloned_untracked(&self, def: DefId, sess: &Session) -> ty::AssocItem {
441 self.get_crate_data(def.krate).get_associated_item(def.index, sess)
444 pub fn crate_source_untracked(&self, cnum: CrateNum) -> CrateSource {
445 self.get_crate_data(cnum).source.clone()
448 pub fn get_span_untracked(&self, def_id: DefId, sess: &Session) -> Span {
449 self.get_crate_data(def_id.krate).get_span(def_id.index, sess)
452 pub fn item_generics_num_lifetimes(&self, def_id: DefId, sess: &Session) -> usize {
453 self.get_crate_data(def_id.krate).get_generics(def_id.index, sess).own_counts().lifetimes
456 pub fn module_expansion_untracked(&self, def_id: DefId, sess: &Session) -> ExpnId {
457 self.get_crate_data(def_id.krate).module_expansion(def_id.index, sess)
461 impl CrateStore for CStore {
462 fn as_any(&self) -> &dyn Any {
466 fn crate_name_untracked(&self, cnum: CrateNum) -> Symbol {
467 self.get_crate_data(cnum).root.name
470 fn crate_is_private_dep_untracked(&self, cnum: CrateNum) -> bool {
471 self.get_crate_data(cnum).private_dep
474 fn crate_disambiguator_untracked(&self, cnum: CrateNum) -> CrateDisambiguator {
475 self.get_crate_data(cnum).root.disambiguator
478 fn crate_hash_untracked(&self, cnum: CrateNum) -> Svh {
479 self.get_crate_data(cnum).root.hash
482 /// Returns the `DefKey` for a given `DefId`. This indicates the
483 /// parent `DefId` as well as some idea of what kind of data the
484 /// `DefId` refers to.
485 fn def_key(&self, def: DefId) -> DefKey {
486 self.get_crate_data(def.krate).def_key(def.index)
489 fn def_kind(&self, def: DefId) -> DefKind {
490 self.get_crate_data(def.krate).def_kind(def.index)
493 fn def_path(&self, def: DefId) -> DefPath {
494 self.get_crate_data(def.krate).def_path(def.index)
497 fn def_path_hash(&self, def: DefId) -> DefPathHash {
498 self.get_crate_data(def.krate).def_path_hash(def.index)
501 fn all_def_path_hashes_and_def_ids(&self, cnum: CrateNum) -> Vec<(DefPathHash, DefId)> {
502 self.get_crate_data(cnum).all_def_path_hashes_and_def_ids()
505 fn num_def_ids(&self, cnum: CrateNum) -> usize {
506 self.get_crate_data(cnum).num_def_ids()
509 fn crates_untracked(&self) -> Vec<CrateNum> {
510 let mut result = vec![];
511 self.iter_crate_data(|cnum, _| result.push(cnum));
515 fn encode_metadata(&self, tcx: TyCtxt<'_>) -> EncodedMetadata {
516 encoder::encode_metadata(tcx)
519 fn metadata_encoding_version(&self) -> &[u8] {
520 rmeta::METADATA_HEADER
523 fn allocator_kind(&self) -> Option<AllocatorKind> {
524 self.allocator_kind()