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::svh::Svh;
11 use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, CRATE_DEF_INDEX, LOCAL_CRATE};
12 use rustc_hir::definitions::{DefKey, DefPath, DefPathHash};
13 use rustc_middle::hir::exports::Export;
14 use rustc_middle::middle::cstore::{CrateSource, CrateStore, EncodedMetadata};
15 use rustc_middle::middle::exported_symbols::ExportedSymbol;
16 use rustc_middle::middle::stability::DeprecationEntry;
17 use rustc_middle::ty::query::Providers;
18 use rustc_middle::ty::{self, TyCtxt};
19 use rustc_session::utils::NativeLibKind;
20 use rustc_session::{CrateDisambiguator, Session};
21 use rustc_span::source_map::{self, Span, Spanned};
22 use rustc_span::symbol::Symbol;
24 use rustc_data_structures::sync::Lrc;
25 use rustc_span::ExpnId;
26 use smallvec::SmallVec;
29 macro_rules! provide {
30 (<$lt:tt> $tcx:ident, $def_id:ident, $other:ident, $cdata:ident,
31 $($name:ident => $compute:block)*) => {
32 pub fn provide_extern(providers: &mut Providers) {
35 def_id_arg: ty::query::query_keys::$name<$lt>,
36 ) -> ty::query::query_values::$name<$lt> {
38 $tcx.prof.generic_activity(concat!("metadata_decode_entry_", stringify!($name)));
40 #[allow(unused_variables)]
41 let ($def_id, $other) = def_id_arg.into_args();
42 assert!(!$def_id.is_local());
44 let $cdata = CStore::from_tcx($tcx).get_crate_data($def_id.krate);
46 if $tcx.dep_graph.is_fully_enabled() {
47 let crate_dep_node_index = $cdata.get_crate_dep_node_index($tcx);
48 $tcx.dep_graph.read_index(crate_dep_node_index);
54 *providers = Providers {
62 // small trait to work around different signature queries all being defined via
65 fn into_args(self) -> (DefId, DefId);
68 impl IntoArgs for DefId {
69 fn into_args(self) -> (DefId, DefId) {
74 impl IntoArgs for CrateNum {
75 fn into_args(self) -> (DefId, DefId) {
76 (self.as_def_id(), self.as_def_id())
80 impl IntoArgs for (CrateNum, DefId) {
81 fn into_args(self) -> (DefId, DefId) {
82 (self.0.as_def_id(), self.1)
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 trait_def => { cdata.get_trait_def(def_id.index, tcx.sess) }
93 adt_def => { cdata.get_adt_def(def_id.index, tcx) }
96 tcx.calculate_dtor(def_id, &mut |_,_| Ok(()))
98 variances_of => { tcx.arena.alloc_from_iter(cdata.get_item_variances(def_id.index)) }
99 associated_item_def_ids => {
100 let mut result = SmallVec::<[_; 8]>::new();
101 cdata.each_child_of_item(def_id.index,
102 |child| result.push(child.res.def_id()), tcx.sess);
103 tcx.arena.alloc_slice(&result)
105 associated_item => { cdata.get_associated_item(def_id.index, tcx.sess) }
106 impl_trait_ref => { cdata.get_impl_trait(def_id.index, tcx) }
107 impl_polarity => { cdata.get_impl_polarity(def_id.index) }
108 coerce_unsized_info => {
109 cdata.get_coerce_unsized_info(def_id.index).unwrap_or_else(|| {
110 bug!("coerce_unsized_info: `{:?}` is missing its info", def_id);
113 optimized_mir => { tcx.arena.alloc(cdata.get_optimized_mir(tcx, def_id.index)) }
114 promoted_mir => { tcx.arena.alloc(cdata.get_promoted_mir(tcx, def_id.index)) }
115 unused_generic_params => { cdata.get_unused_generic_params(def_id.index) }
116 mir_const_qualif => { cdata.mir_const_qualif(def_id.index) }
117 fn_sig => { cdata.fn_sig(def_id.index, tcx) }
118 inherent_impls => { cdata.get_inherent_implementations_for_type(tcx, def_id.index) }
119 is_const_fn_raw => { cdata.is_const_fn_raw(def_id.index) }
120 asyncness => { cdata.asyncness(def_id.index) }
121 is_foreign_item => { cdata.is_foreign_item(def_id.index) }
122 static_mutability => { cdata.static_mutability(def_id.index) }
123 generator_kind => { cdata.generator_kind(def_id.index) }
124 def_kind => { cdata.def_kind(def_id.index) }
125 def_span => { cdata.get_span(def_id.index, &tcx.sess) }
126 lookup_stability => {
127 cdata.get_stability(def_id.index).map(|s| tcx.intern_stability(s))
129 lookup_const_stability => {
130 cdata.get_const_stability(def_id.index).map(|s| tcx.intern_const_stability(s))
132 lookup_deprecation_entry => {
133 cdata.get_deprecation(def_id.index).map(DeprecationEntry::external)
135 item_attrs => { tcx.arena.alloc_from_iter(
136 cdata.get_item_attrs(def_id.index, tcx.sess).into_iter()
138 fn_arg_names => { cdata.get_fn_param_names(tcx, def_id.index) }
139 rendered_const => { cdata.get_rendered_const(def_id.index) }
140 impl_parent => { cdata.get_parent_impl(def_id.index) }
141 trait_of_item => { cdata.get_trait_of_item(def_id.index) }
142 is_mir_available => { cdata.is_item_mir_available(def_id.index) }
144 dylib_dependency_formats => { cdata.get_dylib_dependency_formats(tcx) }
145 is_panic_runtime => { cdata.root.panic_runtime }
146 is_compiler_builtins => { cdata.root.compiler_builtins }
147 has_global_allocator => { cdata.root.has_global_allocator }
148 has_panic_handler => { cdata.root.has_panic_handler }
149 is_profiler_runtime => { cdata.root.profiler_runtime }
150 panic_strategy => { cdata.root.panic_strategy }
152 let r = *cdata.extern_crate.lock();
153 r.map(|c| &*tcx.arena.alloc(c))
155 is_no_builtins => { cdata.root.no_builtins }
156 symbol_mangling_version => { cdata.root.symbol_mangling_version }
157 impl_defaultness => { cdata.get_impl_defaultness(def_id.index) }
158 reachable_non_generics => {
159 let reachable_non_generics = tcx
160 .exported_symbols(cdata.cnum)
162 .filter_map(|&(exported_symbol, export_level)| {
163 if let ExportedSymbol::NonGeneric(def_id) = exported_symbol {
164 Some((def_id, export_level))
171 reachable_non_generics
173 native_libraries => { Lrc::new(cdata.get_native_libraries(tcx.sess)) }
174 foreign_modules => { cdata.get_foreign_modules(tcx) }
175 plugin_registrar_fn => {
176 cdata.root.plugin_registrar_fn.map(|index| {
177 DefId { krate: def_id.krate, index }
180 proc_macro_decls_static => {
181 cdata.root.proc_macro_decls_static.map(|index| {
182 DefId { krate: def_id.krate, index }
185 crate_disambiguator => { cdata.root.disambiguator }
186 crate_hash => { cdata.root.hash }
187 crate_host_hash => { cdata.host_hash }
188 original_crate_name => { cdata.root.name }
190 extra_filename => { cdata.root.extra_filename.clone() }
192 implementations_of_trait => {
193 cdata.get_implementations_for_trait(tcx, Some(other))
196 all_trait_implementations => {
197 cdata.get_implementations_for_trait(tcx, None)
200 visibility => { cdata.get_visibility(def_id.index) }
202 let r = *cdata.dep_kind.lock();
205 crate_name => { cdata.root.name }
207 let mut result = SmallVec::<[_; 8]>::new();
208 cdata.each_child_of_item(def_id.index, |child| result.push(child), tcx.sess);
209 tcx.arena.alloc_slice(&result)
211 defined_lib_features => { cdata.get_lib_features(tcx) }
212 defined_lang_items => { cdata.get_lang_items(tcx) }
213 diagnostic_items => { cdata.get_diagnostic_items() }
214 missing_lang_items => { cdata.get_missing_lang_items(tcx) }
216 missing_extern_crate_item => {
217 let r = match *cdata.extern_crate.borrow() {
218 Some(extern_crate) if !extern_crate.is_direct() => true,
224 used_crate_source => { Lrc::new(cdata.source.clone()) }
226 exported_symbols => {
227 let syms = cdata.exported_symbols(tcx);
229 // FIXME rust-lang/rust#64319, rust-lang/rust#64872: We want
230 // to block export of generics from dylibs, but we must fix
231 // rust-lang/rust#65890 before we can do that robustly.
236 crate_extern_paths => { cdata.source().paths().cloned().collect() }
239 pub fn provide(providers: &mut Providers) {
240 // FIXME(#44234) - almost all of these queries have no sub-queries and
241 // therefore no actual inputs, they're just reading tables calculated in
242 // resolve! Does this work? Unsure! That's what the issue is about
243 *providers = Providers {
244 is_dllimport_foreign_item: |tcx, id| match tcx.native_library_kind(id) {
245 Some(NativeLibKind::Dylib | NativeLibKind::RawDylib | NativeLibKind::Unspecified) => {
250 is_statically_included_foreign_item: |tcx, id| match tcx.native_library_kind(id) {
251 Some(NativeLibKind::StaticBundle | NativeLibKind::StaticNoBundle) => true,
254 native_library_kind: |tcx, id| {
255 tcx.native_libraries(id.krate)
257 .filter(|lib| native_libs::relevant_lib(&tcx.sess, lib))
259 let fm_id = match lib.foreign_module {
261 None => return false,
263 tcx.foreign_modules(id.krate)
265 .find(|m| m.def_id == fm_id)
266 .expect("failed to find foreign module")
272 native_libraries: |tcx, cnum| {
273 assert_eq!(cnum, LOCAL_CRATE);
274 Lrc::new(native_libs::collect(tcx))
276 foreign_modules: |tcx, cnum| {
277 assert_eq!(cnum, LOCAL_CRATE);
278 &tcx.arena.alloc(foreign_modules::collect(tcx))[..]
280 link_args: |tcx, cnum| {
281 assert_eq!(cnum, LOCAL_CRATE);
282 Lrc::new(link_args::collect(tcx))
285 // Returns a map from a sufficiently visible external item (i.e., an
286 // external item that is visible from at least one local module) to a
287 // sufficiently visible parent (considering modules that re-export the
288 // external item to be parents).
289 visible_parent_map: |tcx, cnum| {
290 use std::collections::hash_map::Entry;
291 use std::collections::vec_deque::VecDeque;
293 assert_eq!(cnum, LOCAL_CRATE);
294 let mut visible_parent_map: DefIdMap<DefId> = Default::default();
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.
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();
308 // Preferring shortest paths alone does not guarantee a
309 // deterministic result; so sort by crate num to avoid
310 // hashtable iteration non-determinism. This only makes
311 // things as deterministic as crate-nums assignment is,
312 // which is to say, its not deterministic in general. But
313 // we believe that libstd is consistently assigned crate
314 // num 1, so it should be enough to resolve #46112.
315 let mut crates: Vec<CrateNum> = (*tcx.crates()).to_owned();
318 for &cnum in crates.iter() {
319 // Ignore crates without a corresponding local `extern crate` item.
320 if tcx.missing_extern_crate_item(cnum) {
324 bfs_queue.push_back(DefId { krate: cnum, index: CRATE_DEF_INDEX });
327 // (restrict scope of mutable-borrow of `visible_parent_map`)
329 let visible_parent_map = &mut visible_parent_map;
331 |bfs_queue: &mut VecDeque<_>, child: &Export<hir::HirId>, parent: DefId| {
332 if child.vis != ty::Visibility::Public {
336 if let Some(child) = child.res.opt_def_id() {
337 match visible_parent_map.entry(child) {
338 Entry::Occupied(mut entry) => {
339 // If `child` is defined in crate `cnum`, ensure
340 // that it is mapped to a parent in `cnum`.
341 if child.krate == cnum && entry.get().krate != cnum {
342 entry.insert(parent);
345 Entry::Vacant(entry) => {
346 entry.insert(parent);
347 bfs_queue.push_back(child);
353 while let Some(def) = bfs_queue.pop_front() {
354 for child in tcx.item_children(def).iter() {
355 add_child(bfs_queue, child, def);
363 dependency_formats: |tcx, cnum| {
364 assert_eq!(cnum, LOCAL_CRATE);
365 Lrc::new(crate::dependency_format::calculate(tcx))
367 has_global_allocator: |tcx, cnum| {
368 assert_eq!(cnum, LOCAL_CRATE);
369 CStore::from_tcx(tcx).has_global_allocator()
371 postorder_cnums: |tcx, cnum| {
372 assert_eq!(cnum, LOCAL_CRATE);
373 tcx.arena.alloc_slice(&CStore::from_tcx(tcx).crate_dependencies_in_postorder(cnum))
381 pub fn struct_field_names_untracked(&self, def: DefId, sess: &Session) -> Vec<Spanned<Symbol>> {
382 self.get_crate_data(def.krate).get_struct_field_names(def.index, sess)
385 pub fn item_children_untracked(
389 ) -> Vec<Export<hir::HirId>> {
390 let mut result = vec![];
391 self.get_crate_data(def_id.krate).each_child_of_item(
393 |child| result.push(child),
399 pub fn load_macro_untracked(&self, id: DefId, sess: &Session) -> LoadedMacro {
400 let _prof_timer = sess.prof.generic_activity("metadata_load_macro");
402 let data = self.get_crate_data(id.krate);
403 if data.root.is_proc_macro_crate() {
404 return LoadedMacro::ProcMacro(data.load_proc_macro(id.index, sess));
407 let span = data.get_span(id.index, sess);
409 // Mark the attrs as used
410 let attrs = data.get_item_attrs(id.index, sess);
411 for attr in attrs.iter() {
412 sess.mark_attr_used(attr);
415 let ident = data.item_ident(id.index, sess);
417 LoadedMacro::MacroDef(
420 id: ast::DUMMY_NODE_ID,
422 attrs: attrs.to_vec(),
423 kind: ast::ItemKind::MacroDef(data.get_macro(id.index, sess)),
424 vis: source_map::respan(span.shrink_to_lo(), ast::VisibilityKind::Inherited),
431 pub fn associated_item_cloned_untracked(&self, def: DefId, sess: &Session) -> ty::AssocItem {
432 self.get_crate_data(def.krate).get_associated_item(def.index, sess)
435 pub fn crate_source_untracked(&self, cnum: CrateNum) -> CrateSource {
436 self.get_crate_data(cnum).source.clone()
439 pub fn get_span_untracked(&self, def_id: DefId, sess: &Session) -> Span {
440 self.get_crate_data(def_id.krate).get_span(def_id.index, sess)
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
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)
452 impl CrateStore for CStore {
453 fn as_any(&self) -> &dyn Any {
457 fn crate_name_untracked(&self, cnum: CrateNum) -> Symbol {
458 self.get_crate_data(cnum).root.name
461 fn crate_is_private_dep_untracked(&self, cnum: CrateNum) -> bool {
462 self.get_crate_data(cnum).private_dep
465 fn crate_disambiguator_untracked(&self, cnum: CrateNum) -> CrateDisambiguator {
466 self.get_crate_data(cnum).root.disambiguator
469 fn crate_hash_untracked(&self, cnum: CrateNum) -> Svh {
470 self.get_crate_data(cnum).root.hash
473 /// Returns the `DefKey` for a given `DefId`. This indicates the
474 /// parent `DefId` as well as some idea of what kind of data the
475 /// `DefId` refers to.
476 fn def_key(&self, def: DefId) -> DefKey {
477 self.get_crate_data(def.krate).def_key(def.index)
480 fn def_path(&self, def: DefId) -> DefPath {
481 self.get_crate_data(def.krate).def_path(def.index)
484 fn def_path_hash(&self, def: DefId) -> DefPathHash {
485 self.get_crate_data(def.krate).def_path_hash(def.index)
488 fn all_def_path_hashes_and_def_ids(&self, cnum: CrateNum) -> Vec<(DefPathHash, DefId)> {
489 self.get_crate_data(cnum).all_def_path_hashes_and_def_ids()
492 fn num_def_ids(&self, cnum: CrateNum) -> usize {
493 self.get_crate_data(cnum).num_def_ids()
496 fn crates_untracked(&self) -> Vec<CrateNum> {
497 let mut result = vec![];
498 self.iter_crate_data(|cnum, _| result.push(cnum));
502 fn encode_metadata(&self, tcx: TyCtxt<'_>) -> EncodedMetadata {
503 encoder::encode_metadata(tcx)
506 fn metadata_encoding_version(&self) -> &[u8] {
507 rmeta::METADATA_HEADER
510 fn allocator_kind(&self) -> Option<AllocatorKind> {
511 self.allocator_kind()