1 use crate::cstore::{self, LoadedMacro};
4 use crate::native_libs;
5 use crate::foreign_modules;
8 use rustc::ty::query::QueryConfig;
9 use rustc::middle::cstore::{CrateSource, CrateStore, DepKind, EncodedMetadata, NativeLibraryKind};
10 use rustc::middle::exported_symbols::ExportedSymbol;
11 use rustc::middle::stability::DeprecationEntry;
12 use rustc::middle::dependency_format::Linkage;
15 use rustc::session::{CrateDisambiguator, Session};
16 use rustc::ty::{self, TyCtxt};
17 use rustc::ty::query::Providers;
18 use rustc::hir::def_id::{CrateNum, DefId, LOCAL_CRATE, CRATE_DEF_INDEX};
19 use rustc::hir::map::{DefKey, DefPath, DefPathHash};
20 use rustc::hir::map::definitions::DefPathTable;
21 use rustc::util::nodemap::DefIdMap;
22 use rustc_data_structures::svh::Svh;
24 use smallvec::SmallVec;
26 use rustc_data_structures::sync::Lrc;
31 use syntax::source_map;
32 use syntax::edition::Edition;
33 use syntax::parse::source_file_to_stream;
34 use syntax::parse::parser::emit_unclosed_delims;
35 use syntax::source_map::Spanned;
36 use syntax::symbol::Symbol;
37 use syntax_pos::{Span, FileName};
38 use rustc_index::bit_set::BitSet;
40 macro_rules! provide {
41 (<$lt:tt> $tcx:ident, $def_id:ident, $other:ident, $cdata:ident,
42 $($name:ident => $compute:block)*) => {
43 pub fn provide_extern<$lt>(providers: &mut Providers<$lt>) {
44 // HACK(eddyb) `$lt: $lt` forces `$lt` to be early-bound, which
45 // allows the associated type in the return type to be normalized.
46 $(fn $name<$lt: $lt, T: IntoArgs>(
49 ) -> <ty::queries::$name<$lt> as QueryConfig<$lt>>::Value {
51 $tcx.prof.generic_activity("metadata_decode_entry");
53 #[allow(unused_variables)]
54 let ($def_id, $other) = def_id_arg.into_args();
55 assert!(!$def_id.is_local());
57 let $cdata = $tcx.crate_data_as_rc_any($def_id.krate);
58 let $cdata = $cdata.downcast_ref::<cstore::CrateMetadata>()
59 .expect("CrateStore created data is not a CrateMetadata");
61 if $tcx.dep_graph.is_fully_enabled() {
62 let crate_dep_node_index = $cdata.get_crate_dep_node_index($tcx);
63 $tcx.dep_graph.read_index(crate_dep_node_index);
69 *providers = Providers {
77 // small trait to work around different signature queries all being defined via
80 fn into_args(self) -> (DefId, DefId);
83 impl IntoArgs for DefId {
84 fn into_args(self) -> (DefId, DefId) { (self, self) }
87 impl IntoArgs for CrateNum {
88 fn into_args(self) -> (DefId, DefId) { (self.as_def_id(), self.as_def_id()) }
91 impl IntoArgs for (CrateNum, DefId) {
92 fn into_args(self) -> (DefId, DefId) { (self.0.as_def_id(), self.1) }
95 provide! { <'tcx> tcx, def_id, other, cdata,
96 type_of => { cdata.get_type(def_id.index, tcx) }
98 tcx.arena.alloc(cdata.get_generics(def_id.index, tcx.sess))
100 predicates_of => { cdata.get_predicates(def_id.index, tcx) }
101 predicates_defined_on => { cdata.get_predicates_defined_on(def_id.index, tcx) }
102 super_predicates_of => { cdata.get_super_predicates(def_id.index, tcx) }
104 tcx.arena.alloc(cdata.get_trait_def(def_id.index, tcx.sess))
106 adt_def => { cdata.get_adt_def(def_id.index, tcx) }
109 tcx.calculate_dtor(def_id, &mut |_,_| Ok(()))
111 variances_of => { tcx.arena.alloc_from_iter(cdata.get_item_variances(def_id.index)) }
112 associated_item_def_ids => {
113 let mut result = SmallVec::<[_; 8]>::new();
114 cdata.each_child_of_item(def_id.index,
115 |child| result.push(child.res.def_id()), tcx.sess);
116 tcx.arena.alloc_slice(&result)
118 associated_item => { cdata.get_associated_item(def_id.index) }
119 impl_trait_ref => { cdata.get_impl_trait(def_id.index, tcx) }
120 impl_polarity => { cdata.get_impl_polarity(def_id.index) }
121 coerce_unsized_info => {
122 cdata.get_coerce_unsized_info(def_id.index).unwrap_or_else(|| {
123 bug!("coerce_unsized_info: `{:?}` is missing its info", def_id);
126 optimized_mir => { tcx.arena.alloc(cdata.get_optimized_mir(tcx, def_id.index)) }
127 promoted_mir => { tcx.arena.alloc(cdata.get_promoted_mir(tcx, def_id.index)) }
128 mir_const_qualif => {
129 (cdata.mir_const_qualif(def_id.index), tcx.arena.alloc(BitSet::new_empty(0)))
131 fn_sig => { cdata.fn_sig(def_id.index, tcx) }
132 inherent_impls => { cdata.get_inherent_implementations_for_type(tcx, def_id.index) }
133 is_const_fn_raw => { cdata.is_const_fn_raw(def_id.index) }
134 asyncness => { cdata.asyncness(def_id.index) }
135 is_foreign_item => { cdata.is_foreign_item(def_id.index) }
136 static_mutability => { cdata.static_mutability(def_id.index) }
137 def_kind => { cdata.def_kind(def_id.index) }
138 def_span => { cdata.get_span(def_id.index, &tcx.sess) }
139 lookup_stability => {
140 cdata.get_stability(def_id.index).map(|s| tcx.intern_stability(s))
142 lookup_deprecation_entry => {
143 cdata.get_deprecation(def_id.index).map(DeprecationEntry::external)
145 item_attrs => { cdata.get_item_attrs(def_id.index, tcx.sess) }
146 // FIXME(#38501) We've skipped a `read` on the `HirBody` of
147 // a `fn` when encoding, so the dep-tracking wouldn't work.
148 // This is only used by rustdoc anyway, which shouldn't have
149 // incremental recompilation ever enabled.
150 fn_arg_names => { cdata.get_fn_param_names(def_id.index) }
151 rendered_const => { cdata.get_rendered_const(def_id.index) }
152 impl_parent => { cdata.get_parent_impl(def_id.index) }
153 trait_of_item => { cdata.get_trait_of_item(def_id.index) }
154 is_mir_available => { cdata.is_item_mir_available(def_id.index) }
156 dylib_dependency_formats => { cdata.get_dylib_dependency_formats(tcx) }
157 is_panic_runtime => { cdata.root.panic_runtime }
158 is_compiler_builtins => { cdata.root.compiler_builtins }
159 has_global_allocator => { cdata.root.has_global_allocator }
160 has_panic_handler => { cdata.root.has_panic_handler }
161 is_sanitizer_runtime => { cdata.root.sanitizer_runtime }
162 is_profiler_runtime => { cdata.root.profiler_runtime }
163 panic_strategy => { cdata.root.panic_strategy }
165 let r = *cdata.extern_crate.lock();
166 r.map(|c| &*tcx.arena.alloc(c))
168 is_no_builtins => { cdata.root.no_builtins }
169 symbol_mangling_version => { cdata.root.symbol_mangling_version }
170 impl_defaultness => { cdata.get_impl_defaultness(def_id.index) }
171 reachable_non_generics => {
172 let reachable_non_generics = tcx
173 .exported_symbols(cdata.cnum)
175 .filter_map(|&(exported_symbol, export_level)| {
176 if let ExportedSymbol::NonGeneric(def_id) = exported_symbol {
177 return Some((def_id, export_level))
184 tcx.arena.alloc(reachable_non_generics)
186 native_libraries => { Lrc::new(cdata.get_native_libraries(tcx.sess)) }
187 foreign_modules => { cdata.get_foreign_modules(tcx) }
188 plugin_registrar_fn => {
189 cdata.root.plugin_registrar_fn.map(|index| {
190 DefId { krate: def_id.krate, index }
193 proc_macro_decls_static => {
194 cdata.root.proc_macro_decls_static.map(|index| {
195 DefId { krate: def_id.krate, index }
198 crate_disambiguator => { cdata.root.disambiguator }
199 crate_hash => { cdata.root.hash }
200 original_crate_name => { cdata.root.name }
202 extra_filename => { cdata.root.extra_filename.clone() }
204 implementations_of_trait => {
205 cdata.get_implementations_for_trait(tcx, Some(other))
208 all_trait_implementations => {
209 cdata.get_implementations_for_trait(tcx, None)
212 visibility => { cdata.get_visibility(def_id.index) }
214 let r = *cdata.dep_kind.lock();
217 crate_name => { cdata.root.name }
219 let mut result = SmallVec::<[_; 8]>::new();
220 cdata.each_child_of_item(def_id.index, |child| result.push(child), tcx.sess);
221 tcx.arena.alloc_slice(&result)
223 defined_lib_features => { cdata.get_lib_features(tcx) }
224 defined_lang_items => { cdata.get_lang_items(tcx) }
225 diagnostic_items => { cdata.get_diagnostic_items(tcx) }
226 missing_lang_items => { cdata.get_missing_lang_items(tcx) }
228 missing_extern_crate_item => {
229 let r = match *cdata.extern_crate.borrow() {
230 Some(extern_crate) if !extern_crate.is_direct() => true,
236 used_crate_source => { Lrc::new(cdata.source.clone()) }
238 exported_symbols => {
239 let mut syms = cdata.exported_symbols(tcx);
241 // When linked into a dylib crates don't export their generic symbols,
242 // so if that's happening then we can't load upstream monomorphizations
244 let formats = tcx.dependency_formats(LOCAL_CRATE);
245 let remove_generics = formats.iter().any(|(_ty, list)| {
246 match list.get(def_id.krate.as_usize() - 1) {
247 Some(Linkage::IncludedFromDylib) | Some(Linkage::Dynamic) => true,
252 syms.retain(|(sym, _threshold)| {
254 ExportedSymbol::Generic(..) => false,
264 pub fn provide(providers: &mut Providers<'_>) {
265 // FIXME(#44234) - almost all of these queries have no sub-queries and
266 // therefore no actual inputs, they're just reading tables calculated in
267 // resolve! Does this work? Unsure! That's what the issue is about
268 *providers = Providers {
269 is_dllimport_foreign_item: |tcx, id| {
270 match tcx.native_library_kind(id) {
271 Some(NativeLibraryKind::NativeUnknown) |
272 Some(NativeLibraryKind::NativeRawDylib) => true,
276 is_statically_included_foreign_item: |tcx, id| {
277 match tcx.native_library_kind(id) {
278 Some(NativeLibraryKind::NativeStatic) |
279 Some(NativeLibraryKind::NativeStaticNobundle) => true,
283 native_library_kind: |tcx, id| {
284 tcx.native_libraries(id.krate)
286 .filter(|lib| native_libs::relevant_lib(&tcx.sess, lib))
288 let fm_id = match lib.foreign_module {
290 None => return false,
292 tcx.foreign_modules(id.krate)
294 .find(|m| m.def_id == fm_id)
295 .expect("failed to find foreign module")
301 native_libraries: |tcx, cnum| {
302 assert_eq!(cnum, LOCAL_CRATE);
303 Lrc::new(native_libs::collect(tcx))
305 foreign_modules: |tcx, cnum| {
306 assert_eq!(cnum, LOCAL_CRATE);
307 &tcx.arena.alloc(foreign_modules::collect(tcx))[..]
309 link_args: |tcx, cnum| {
310 assert_eq!(cnum, LOCAL_CRATE);
311 Lrc::new(link_args::collect(tcx))
314 // Returns a map from a sufficiently visible external item (i.e., an
315 // external item that is visible from at least one local module) to a
316 // sufficiently visible parent (considering modules that re-export the
317 // external item to be parents).
318 visible_parent_map: |tcx, cnum| {
319 use std::collections::vec_deque::VecDeque;
320 use std::collections::hash_map::Entry;
322 assert_eq!(cnum, LOCAL_CRATE);
323 let mut visible_parent_map: DefIdMap<DefId> = Default::default();
325 // Issue 46112: We want the map to prefer the shortest
326 // paths when reporting the path to an item. Therefore we
327 // build up the map via a breadth-first search (BFS),
328 // which naturally yields minimal-length paths.
330 // Note that it needs to be a BFS over the whole forest of
331 // crates, not just each individual crate; otherwise you
332 // only get paths that are locally minimal with respect to
333 // whatever crate we happened to encounter first in this
334 // traversal, but not globally minimal across all crates.
335 let bfs_queue = &mut VecDeque::new();
337 // Preferring shortest paths alone does not guarantee a
338 // deterministic result; so sort by crate num to avoid
339 // hashtable iteration non-determinism. This only makes
340 // things as deterministic as crate-nums assignment is,
341 // which is to say, its not deterministic in general. But
342 // we believe that libstd is consistently assigned crate
343 // num 1, so it should be enough to resolve #46112.
344 let mut crates: Vec<CrateNum> = (*tcx.crates()).to_owned();
347 for &cnum in crates.iter() {
348 // Ignore crates without a corresponding local `extern crate` item.
349 if tcx.missing_extern_crate_item(cnum) {
353 bfs_queue.push_back(DefId {
355 index: CRATE_DEF_INDEX
359 // (restrict scope of mutable-borrow of `visible_parent_map`)
361 let visible_parent_map = &mut visible_parent_map;
362 let mut add_child = |bfs_queue: &mut VecDeque<_>,
363 child: &def::Export<hir::HirId>,
365 if child.vis != ty::Visibility::Public {
369 if let Some(child) = child.res.opt_def_id() {
370 match visible_parent_map.entry(child) {
371 Entry::Occupied(mut entry) => {
372 // If `child` is defined in crate `cnum`, ensure
373 // that it is mapped to a parent in `cnum`.
374 if child.krate == cnum && entry.get().krate != cnum {
375 entry.insert(parent);
378 Entry::Vacant(entry) => {
379 entry.insert(parent);
380 bfs_queue.push_back(child);
386 while let Some(def) = bfs_queue.pop_front() {
387 for child in tcx.item_children(def).iter() {
388 add_child(bfs_queue, child, def);
393 tcx.arena.alloc(visible_parent_map)
396 dependency_formats: |tcx, cnum| {
397 assert_eq!(cnum, LOCAL_CRATE);
398 Lrc::new(crate::dependency_format::calculate(tcx))
405 impl cstore::CStore {
406 pub fn export_macros_untracked(&self, cnum: CrateNum) {
407 let data = self.get_crate_data(cnum);
408 let mut dep_kind = data.dep_kind.lock();
409 if *dep_kind == DepKind::UnexportedMacrosOnly {
410 *dep_kind = DepKind::MacrosOnly;
414 pub fn crate_edition_untracked(&self, cnum: CrateNum) -> Edition {
415 self.get_crate_data(cnum).root.edition
418 pub fn struct_field_names_untracked(&self, def: DefId, sess: &Session) -> Vec<Spanned<Symbol>> {
419 self.get_crate_data(def.krate).get_struct_field_names(def.index, sess)
422 pub fn item_children_untracked(
426 ) -> Vec<def::Export<hir::HirId>> {
427 let mut result = vec![];
428 self.get_crate_data(def_id.krate)
429 .each_child_of_item(def_id.index, |child| result.push(child), sess);
433 pub fn load_macro_untracked(&self, id: DefId, sess: &Session) -> LoadedMacro {
434 let _prof_timer = sess.prof.generic_activity("metadata_load_macro");
436 let data = self.get_crate_data(id.krate);
437 if data.is_proc_macro_crate() {
438 return LoadedMacro::ProcMacro(data.load_proc_macro(id.index, sess));
441 let def = data.get_macro(id.index);
442 let macro_full_name = data.def_path(id.index).to_string_friendly(|_| data.root.name);
443 let source_name = FileName::Macros(macro_full_name);
445 let source_file = sess.parse_sess.source_map().new_source_file(source_name, def.body);
446 let local_span = Span::with_root_ctxt(source_file.start_pos, source_file.end_pos);
447 let (body, mut errors) = source_file_to_stream(&sess.parse_sess, source_file, None);
448 emit_unclosed_delims(&mut errors, &sess.diagnostic());
450 // Mark the attrs as used
451 let attrs = data.get_item_attrs(id.index, sess);
452 for attr in attrs.iter() {
453 attr::mark_used(attr);
456 let name = data.def_key(id.index).disambiguated_data.data
457 .get_opt_name().expect("no name in load_macro");
458 sess.imported_macro_spans.borrow_mut()
459 .insert(local_span, (name.to_string(), data.get_span(id.index, sess)));
461 LoadedMacro::MacroDef(ast::Item {
462 // FIXME: cross-crate hygiene
463 ident: ast::Ident::with_dummy_span(name.as_symbol()),
464 id: ast::DUMMY_NODE_ID,
466 attrs: attrs.iter().cloned().collect(),
467 kind: ast::ItemKind::MacroDef(ast::MacroDef {
471 vis: source_map::respan(local_span.shrink_to_lo(), ast::VisibilityKind::Inherited),
476 pub fn associated_item_cloned_untracked(&self, def: DefId) -> ty::AssocItem {
477 self.get_crate_data(def.krate).get_associated_item(def.index)
480 pub fn crate_source_untracked(&self, cnum: CrateNum) -> CrateSource {
481 self.get_crate_data(cnum).source.clone()
485 impl CrateStore for cstore::CStore {
486 fn crate_data_as_rc_any(&self, krate: CrateNum) -> Lrc<dyn Any> {
487 self.get_crate_data(krate)
490 fn item_generics_cloned_untracked(&self, def: DefId, sess: &Session) -> ty::Generics {
491 self.get_crate_data(def.krate).get_generics(def.index, sess)
494 fn crate_name_untracked(&self, cnum: CrateNum) -> Symbol
496 self.get_crate_data(cnum).root.name
499 fn crate_is_private_dep_untracked(&self, cnum: CrateNum) -> bool {
500 self.get_crate_data(cnum).private_dep
503 fn crate_disambiguator_untracked(&self, cnum: CrateNum) -> CrateDisambiguator
505 self.get_crate_data(cnum).root.disambiguator
508 fn crate_hash_untracked(&self, cnum: CrateNum) -> Svh
510 self.get_crate_data(cnum).root.hash
513 /// Returns the `DefKey` for a given `DefId`. This indicates the
514 /// parent `DefId` as well as some idea of what kind of data the
515 /// `DefId` refers to.
516 fn def_key(&self, def: DefId) -> DefKey {
517 self.get_crate_data(def.krate).def_key(def.index)
520 fn def_path(&self, def: DefId) -> DefPath {
521 self.get_crate_data(def.krate).def_path(def.index)
524 fn def_path_hash(&self, def: DefId) -> DefPathHash {
525 self.get_crate_data(def.krate).def_path_hash(def.index)
528 fn def_path_table(&self, cnum: CrateNum) -> Lrc<DefPathTable> {
529 self.get_crate_data(cnum).def_path_table.clone()
532 fn crates_untracked(&self) -> Vec<CrateNum>
534 let mut result = vec![];
535 self.iter_crate_data(|cnum, _| result.push(cnum));
539 fn postorder_cnums_untracked(&self) -> Vec<CrateNum> {
540 self.do_postorder_cnums_untracked()
543 fn encode_metadata(&self, tcx: TyCtxt<'_>) -> EncodedMetadata {
544 encoder::encode_metadata(tcx)
547 fn metadata_encoding_version(&self) -> &[u8]
549 schema::METADATA_HEADER