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::{CrateStore, DepKind,
10 EncodedMetadata, NativeLibraryKind};
11 use rustc::middle::exported_symbols::ExportedSymbol;
12 use rustc::middle::stability::DeprecationEntry;
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::symbol::Symbol;
36 use syntax_pos::{Span, FileName};
37 use rustc_data_structures::bit_set::BitSet;
39 macro_rules! provide {
40 (<$lt:tt> $tcx:ident, $def_id:ident, $other:ident, $cdata:ident,
41 $($name:ident => $compute:block)*) => {
42 pub fn provide_extern<$lt>(providers: &mut Providers<$lt>) {
43 // HACK(eddyb) `$lt: $lt` forces `$lt` to be early-bound, which
44 // allows the associated type in the return type to be normalized.
45 $(fn $name<$lt: $lt, T: IntoArgs>(
48 ) -> <ty::queries::$name<$lt> as QueryConfig<$lt>>::Value {
49 #[allow(unused_variables)]
50 let ($def_id, $other) = def_id_arg.into_args();
51 assert!(!$def_id.is_local());
53 let def_path_hash = $tcx.def_path_hash(DefId {
55 index: CRATE_DEF_INDEX
57 let dep_node = def_path_hash
58 .to_dep_node(rustc::dep_graph::DepKind::CrateMetadata);
59 // The DepNodeIndex of the DepNode::CrateMetadata should be
60 // cached somewhere, so that we can use read_index().
61 $tcx.dep_graph.read(dep_node);
63 let $cdata = $tcx.crate_data_as_rc_any($def_id.krate);
64 let $cdata = $cdata.downcast_ref::<cstore::CrateMetadata>()
65 .expect("CrateStore created data is not a CrateMetadata");
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 => { tcx.arena.alloc(cdata.get_predicates(def_id.index, tcx)) }
101 predicates_defined_on => {
102 tcx.arena.alloc(cdata.get_predicates_defined_on(def_id.index, tcx))
104 super_predicates_of => { tcx.arena.alloc(cdata.get_super_predicates(def_id.index, tcx)) }
106 tcx.arena.alloc(cdata.get_trait_def(def_id.index, tcx.sess))
108 adt_def => { cdata.get_adt_def(def_id.index, tcx) }
111 tcx.calculate_dtor(def_id, &mut |_,_| Ok(()))
113 variances_of => { tcx.arena.alloc_from_iter(cdata.get_item_variances(def_id.index)) }
114 associated_item_def_ids => {
115 let mut result = SmallVec::<[_; 8]>::new();
116 cdata.each_child_of_item(def_id.index,
117 |child| result.push(child.res.def_id()), tcx.sess);
118 tcx.arena.alloc_slice(&result)
120 associated_item => { cdata.get_associated_item(def_id.index) }
121 impl_trait_ref => { cdata.get_impl_trait(def_id.index, tcx) }
122 impl_polarity => { cdata.get_impl_polarity(def_id.index) }
123 coerce_unsized_info => {
124 cdata.get_coerce_unsized_info(def_id.index).unwrap_or_else(|| {
125 bug!("coerce_unsized_info: `{:?}` is missing its info", def_id);
128 optimized_mir => { tcx.arena.alloc(cdata.get_optimized_mir(tcx, def_id.index)) }
129 promoted_mir => { tcx.arena.alloc(cdata.get_promoted_mir(tcx, def_id.index)) }
130 mir_const_qualif => {
131 (cdata.mir_const_qualif(def_id.index), tcx.arena.alloc(BitSet::new_empty(0)))
133 fn_sig => { cdata.fn_sig(def_id.index, tcx) }
134 inherent_impls => { cdata.get_inherent_implementations_for_type(tcx, def_id.index) }
135 is_const_fn_raw => { cdata.is_const_fn_raw(def_id.index) }
136 is_async_fn { cdata.fn_asyncness(def_id.index) }
137 is_foreign_item => { cdata.is_foreign_item(def_id.index) }
138 static_mutability => { cdata.static_mutability(def_id.index) }
139 def_kind => { cdata.def_kind(def_id.index) }
140 def_span => { cdata.get_span(def_id.index, &tcx.sess) }
141 lookup_stability => {
142 cdata.get_stability(def_id.index).map(|s| tcx.intern_stability(s))
144 lookup_deprecation_entry => {
145 cdata.get_deprecation(def_id.index).map(DeprecationEntry::external)
147 item_attrs => { cdata.get_item_attrs(def_id.index, tcx.sess) }
148 // FIXME(#38501) We've skipped a `read` on the `HirBody` of
149 // a `fn` when encoding, so the dep-tracking wouldn't work.
150 // This is only used by rustdoc anyway, which shouldn't have
151 // incremental recompilation ever enabled.
152 fn_arg_names => { cdata.get_fn_param_names(def_id.index) }
153 rendered_const => { cdata.get_rendered_const(def_id.index) }
154 impl_parent => { cdata.get_parent_impl(def_id.index) }
155 trait_of_item => { cdata.get_trait_of_item(def_id.index) }
156 const_is_rvalue_promotable_to_static => {
157 cdata.const_is_rvalue_promotable_to_static(def_id.index)
159 is_mir_available => { cdata.is_item_mir_available(def_id.index) }
161 dylib_dependency_formats => { cdata.get_dylib_dependency_formats(tcx) }
162 is_panic_runtime => { cdata.root.panic_runtime }
163 is_compiler_builtins => { cdata.root.compiler_builtins }
164 has_global_allocator => { cdata.root.has_global_allocator }
165 has_panic_handler => { cdata.root.has_panic_handler }
166 is_sanitizer_runtime => { cdata.root.sanitizer_runtime }
167 is_profiler_runtime => { cdata.root.profiler_runtime }
168 panic_strategy => { cdata.root.panic_strategy }
170 let r = *cdata.extern_crate.lock();
171 r.map(|c| &*tcx.arena.alloc(c))
173 is_no_builtins => { cdata.root.no_builtins }
174 symbol_mangling_version => { cdata.root.symbol_mangling_version }
175 impl_defaultness => { cdata.get_impl_defaultness(def_id.index) }
176 reachable_non_generics => {
177 let reachable_non_generics = tcx
178 .exported_symbols(cdata.cnum)
180 .filter_map(|&(exported_symbol, export_level)| {
181 if let ExportedSymbol::NonGeneric(def_id) = exported_symbol {
182 return Some((def_id, export_level))
189 tcx.arena.alloc(reachable_non_generics)
191 native_libraries => { Lrc::new(cdata.get_native_libraries(tcx.sess)) }
192 foreign_modules => { cdata.get_foreign_modules(tcx) }
193 plugin_registrar_fn => {
194 cdata.root.plugin_registrar_fn.map(|index| {
195 DefId { krate: def_id.krate, index }
198 proc_macro_decls_static => {
199 cdata.root.proc_macro_decls_static.map(|index| {
200 DefId { krate: def_id.krate, index }
203 crate_disambiguator => { cdata.root.disambiguator }
204 crate_hash => { cdata.root.hash }
205 original_crate_name => { cdata.root.name }
207 extra_filename => { cdata.root.extra_filename.clone() }
209 implementations_of_trait => {
210 cdata.get_implementations_for_trait(tcx, Some(other))
213 all_trait_implementations => {
214 cdata.get_implementations_for_trait(tcx, None)
217 visibility => { cdata.get_visibility(def_id.index) }
219 let r = *cdata.dep_kind.lock();
222 crate_name => { cdata.name }
224 let mut result = SmallVec::<[_; 8]>::new();
225 cdata.each_child_of_item(def_id.index, |child| result.push(child), tcx.sess);
226 tcx.arena.alloc_slice(&result)
228 defined_lib_features => { cdata.get_lib_features(tcx) }
229 defined_lang_items => { cdata.get_lang_items(tcx) }
230 diagnostic_items => { cdata.get_diagnostic_items(tcx) }
231 missing_lang_items => { cdata.get_missing_lang_items(tcx) }
233 missing_extern_crate_item => {
234 let r = match *cdata.extern_crate.borrow() {
235 Some(extern_crate) if !extern_crate.direct => true,
241 used_crate_source => { Lrc::new(cdata.source.clone()) }
243 exported_symbols => { Arc::new(cdata.exported_symbols(tcx)) }
246 pub fn provide(providers: &mut Providers<'_>) {
247 // FIXME(#44234) - almost all of these queries have no sub-queries and
248 // therefore no actual inputs, they're just reading tables calculated in
249 // resolve! Does this work? Unsure! That's what the issue is about
250 *providers = Providers {
251 is_dllimport_foreign_item: |tcx, id| {
252 tcx.native_library_kind(id) == Some(NativeLibraryKind::NativeUnknown)
254 is_statically_included_foreign_item: |tcx, id| {
255 match tcx.native_library_kind(id) {
256 Some(NativeLibraryKind::NativeStatic) |
257 Some(NativeLibraryKind::NativeStaticNobundle) => true,
261 native_library_kind: |tcx, id| {
262 tcx.native_libraries(id.krate)
264 .filter(|lib| native_libs::relevant_lib(&tcx.sess, lib))
266 let fm_id = match lib.foreign_module {
268 None => return false,
270 tcx.foreign_modules(id.krate)
272 .find(|m| m.def_id == fm_id)
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 &tcx.arena.alloc(foreign_modules::collect(tcx))[..]
287 link_args: |tcx, cnum| {
288 assert_eq!(cnum, LOCAL_CRATE);
289 Lrc::new(link_args::collect(tcx))
292 // Returns a map from a sufficiently visible external item (i.e., an
293 // external item that is visible from at least one local module) to a
294 // sufficiently visible parent (considering modules that re-export the
295 // external item to be parents).
296 visible_parent_map: |tcx, cnum| {
297 use std::collections::vec_deque::VecDeque;
298 use std::collections::hash_map::Entry;
300 assert_eq!(cnum, LOCAL_CRATE);
301 let mut visible_parent_map: DefIdMap<DefId> = Default::default();
303 // Issue 46112: We want the map to prefer the shortest
304 // paths when reporting the path to an item. Therefore we
305 // build up the map via a breadth-first search (BFS),
306 // which naturally yields minimal-length paths.
308 // Note that it needs to be a BFS over the whole forest of
309 // crates, not just each individual crate; otherwise you
310 // only get paths that are locally minimal with respect to
311 // whatever crate we happened to encounter first in this
312 // traversal, but not globally minimal across all crates.
313 let bfs_queue = &mut VecDeque::new();
315 // Preferring shortest paths alone does not guarantee a
316 // deterministic result; so sort by crate num to avoid
317 // hashtable iteration non-determinism. This only makes
318 // things as deterministic as crate-nums assignment is,
319 // which is to say, its not deterministic in general. But
320 // we believe that libstd is consistently assigned crate
321 // num 1, so it should be enough to resolve #46112.
322 let mut crates: Vec<CrateNum> = (*tcx.crates()).to_owned();
325 for &cnum in crates.iter() {
326 // Ignore crates without a corresponding local `extern crate` item.
327 if tcx.missing_extern_crate_item(cnum) {
331 bfs_queue.push_back(DefId {
333 index: CRATE_DEF_INDEX
337 // (restrict scope of mutable-borrow of `visible_parent_map`)
339 let visible_parent_map = &mut visible_parent_map;
340 let mut add_child = |bfs_queue: &mut VecDeque<_>,
341 child: &def::Export<hir::HirId>,
343 if child.vis != ty::Visibility::Public {
347 if let Some(child) = child.res.opt_def_id() {
348 match visible_parent_map.entry(child) {
349 Entry::Occupied(mut entry) => {
350 // If `child` is defined in crate `cnum`, ensure
351 // that it is mapped to a parent in `cnum`.
352 if child.krate == cnum && entry.get().krate != cnum {
353 entry.insert(parent);
356 Entry::Vacant(entry) => {
357 entry.insert(parent);
358 bfs_queue.push_back(child);
364 while let Some(def) = bfs_queue.pop_front() {
365 for child in tcx.item_children(def).iter() {
366 add_child(bfs_queue, child, def);
371 tcx.arena.alloc(visible_parent_map)
378 impl cstore::CStore {
379 pub fn export_macros_untracked(&self, cnum: CrateNum) {
380 let data = self.get_crate_data(cnum);
381 let mut dep_kind = data.dep_kind.lock();
382 if *dep_kind == DepKind::UnexportedMacrosOnly {
383 *dep_kind = DepKind::MacrosOnly;
387 pub fn dep_kind_untracked(&self, cnum: CrateNum) -> DepKind {
388 let data = self.get_crate_data(cnum);
389 let r = *data.dep_kind.lock();
393 pub fn crate_edition_untracked(&self, cnum: CrateNum) -> Edition {
394 self.get_crate_data(cnum).root.edition
397 pub fn struct_field_names_untracked(&self, def: DefId) -> Vec<ast::Name> {
398 self.get_crate_data(def.krate).get_struct_field_names(def.index)
401 pub fn ctor_kind_untracked(&self, def: DefId) -> def::CtorKind {
402 self.get_crate_data(def.krate).get_ctor_kind(def.index)
405 pub fn item_attrs_untracked(&self, def: DefId, sess: &Session) -> Lrc<[ast::Attribute]> {
406 self.get_crate_data(def.krate).get_item_attrs(def.index, sess)
409 pub fn item_children_untracked(
413 ) -> Vec<def::Export<hir::HirId>> {
414 let mut result = vec![];
415 self.get_crate_data(def_id.krate)
416 .each_child_of_item(def_id.index, |child| result.push(child), sess);
420 pub fn load_macro_untracked(&self, id: DefId, sess: &Session) -> LoadedMacro {
421 let data = self.get_crate_data(id.krate);
422 if data.is_proc_macro_crate() {
423 return LoadedMacro::ProcMacro(data.load_proc_macro(id.index, sess));
426 let def = data.get_macro(id.index);
427 let macro_full_name = data.def_path(id.index)
428 .to_string_friendly(|_| data.imported_name);
429 let source_name = FileName::Macros(macro_full_name);
431 let source_file = sess.parse_sess.source_map().new_source_file(source_name, def.body);
432 let local_span = Span::with_root_ctxt(source_file.start_pos, source_file.end_pos);
433 let (body, mut errors) = source_file_to_stream(&sess.parse_sess, source_file, None);
434 emit_unclosed_delims(&mut errors, &sess.diagnostic());
436 // Mark the attrs as used
437 let attrs = data.get_item_attrs(id.index, sess);
438 for attr in attrs.iter() {
439 attr::mark_used(attr);
442 let name = data.def_key(id.index).disambiguated_data.data
443 .get_opt_name().expect("no name in load_macro");
444 sess.imported_macro_spans.borrow_mut()
445 .insert(local_span, (name.to_string(), data.get_span(id.index, sess)));
447 LoadedMacro::MacroDef(ast::Item {
448 // FIXME: cross-crate hygiene
449 ident: ast::Ident::with_dummy_span(name.as_symbol()),
450 id: ast::DUMMY_NODE_ID,
452 attrs: attrs.iter().cloned().collect(),
453 node: ast::ItemKind::MacroDef(ast::MacroDef {
457 vis: source_map::respan(local_span.shrink_to_lo(), ast::VisibilityKind::Inherited),
462 pub fn associated_item_cloned_untracked(&self, def: DefId) -> ty::AssocItem {
463 self.get_crate_data(def.krate).get_associated_item(def.index)
467 impl CrateStore for cstore::CStore {
468 fn crate_data_as_rc_any(&self, krate: CrateNum) -> Lrc<dyn Any> {
469 self.get_crate_data(krate)
472 fn item_generics_cloned_untracked(&self, def: DefId, sess: &Session) -> ty::Generics {
473 self.get_crate_data(def.krate).get_generics(def.index, sess)
476 fn crate_name_untracked(&self, cnum: CrateNum) -> Symbol
478 self.get_crate_data(cnum).name
481 fn crate_is_private_dep_untracked(&self, cnum: CrateNum) -> bool {
482 self.get_crate_data(cnum).private_dep
485 fn crate_disambiguator_untracked(&self, cnum: CrateNum) -> CrateDisambiguator
487 self.get_crate_data(cnum).root.disambiguator
490 fn crate_hash_untracked(&self, cnum: CrateNum) -> Svh
492 self.get_crate_data(cnum).root.hash
495 /// Returns the `DefKey` for a given `DefId`. This indicates the
496 /// parent `DefId` as well as some idea of what kind of data the
497 /// `DefId` refers to.
498 fn def_key(&self, def: DefId) -> DefKey {
499 // Note: loading the def-key (or def-path) for a def-id is not
500 // a *read* of its metadata. This is because the def-id is
501 // really just an interned shorthand for a def-path, which is the
502 // canonical name for an item.
504 // self.dep_graph.read(DepNode::MetaData(def));
505 self.get_crate_data(def.krate).def_key(def.index)
508 fn def_path(&self, def: DefId) -> DefPath {
509 // See `Note` above in `def_key()` for why this read is
512 // self.dep_graph.read(DepNode::MetaData(def));
513 self.get_crate_data(def.krate).def_path(def.index)
516 fn def_path_hash(&self, def: DefId) -> DefPathHash {
517 self.get_crate_data(def.krate).def_path_hash(def.index)
520 fn def_path_table(&self, cnum: CrateNum) -> Lrc<DefPathTable> {
521 self.get_crate_data(cnum).def_path_table.clone()
524 fn crates_untracked(&self) -> Vec<CrateNum>
526 let mut result = vec![];
527 self.iter_crate_data(|cnum, _| result.push(cnum));
531 fn extern_mod_stmt_cnum_untracked(&self, emod_id: ast::NodeId) -> Option<CrateNum>
533 self.do_extern_mod_stmt_cnum(emod_id)
536 fn postorder_cnums_untracked(&self) -> Vec<CrateNum> {
537 self.do_postorder_cnums_untracked()
540 fn encode_metadata(&self, tcx: TyCtxt<'_>) -> EncodedMetadata {
541 encoder::encode_metadata(tcx)
544 fn metadata_encoding_version(&self) -> &[u8]
546 schema::METADATA_HEADER