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;
14 use rustc::session::{CrateDisambiguator, Session};
15 use rustc::ty::{self, TyCtxt};
16 use rustc::ty::query::Providers;
17 use rustc::hir::def_id::{CrateNum, DefId, LOCAL_CRATE, CRATE_DEF_INDEX};
18 use rustc::hir::map::{DefKey, DefPath, DefPathHash};
19 use rustc::hir::map::definitions::DefPathTable;
20 use rustc::util::nodemap::DefIdMap;
21 use rustc_data_structures::svh::Svh;
24 use rustc_data_structures::sync::Lrc;
29 use syntax::source_map;
30 use syntax::edition::Edition;
31 use syntax::parse::source_file_to_stream;
32 use syntax::parse::parser::emit_unclosed_delims;
33 use syntax::symbol::Symbol;
34 use syntax_pos::{Span, NO_EXPANSION, FileName};
35 use rustc_data_structures::bit_set::BitSet;
37 macro_rules! provide {
38 (<$lt:tt> $tcx:ident, $def_id:ident, $other:ident, $cdata:ident,
39 $($name:ident => $compute:block)*) => {
40 pub fn provide_extern<$lt>(providers: &mut Providers<$lt>) {
41 $(fn $name<'a, $lt:$lt, T>($tcx: TyCtxt<'a, $lt, $lt>, def_id_arg: T)
42 -> <ty::queries::$name<$lt> as
43 QueryConfig<$lt>>::Value
46 #[allow(unused_variables)]
47 let ($def_id, $other) = def_id_arg.into_args();
48 assert!(!$def_id.is_local());
50 let def_path_hash = $tcx.def_path_hash(DefId {
52 index: CRATE_DEF_INDEX
54 let dep_node = def_path_hash
55 .to_dep_node(rustc::dep_graph::DepKind::CrateMetadata);
56 // The DepNodeIndex of the DepNode::CrateMetadata should be
57 // cached somewhere, so that we can use read_index().
58 $tcx.dep_graph.read(dep_node);
60 let $cdata = $tcx.crate_data_as_rc_any($def_id.krate);
61 let $cdata = $cdata.downcast_ref::<cstore::CrateMetadata>()
62 .expect("CrateStore created data is not a CrateMetadata");
66 *providers = Providers {
74 // small trait to work around different signature queries all being defined via
77 fn into_args(self) -> (DefId, DefId);
80 impl IntoArgs for DefId {
81 fn into_args(self) -> (DefId, DefId) { (self, self) }
84 impl IntoArgs for CrateNum {
85 fn into_args(self) -> (DefId, DefId) { (self.as_def_id(), self.as_def_id()) }
88 impl IntoArgs for (CrateNum, DefId) {
89 fn into_args(self) -> (DefId, DefId) { (self.0.as_def_id(), self.1) }
92 provide! { <'tcx> tcx, def_id, other, cdata,
93 type_of => { cdata.get_type(def_id.index, tcx) }
95 tcx.alloc_generics(cdata.get_generics(def_id.index, tcx.sess))
97 predicates_of => { Lrc::new(cdata.get_predicates(def_id.index, tcx)) }
98 predicates_defined_on => { Lrc::new(cdata.get_predicates_defined_on(def_id.index, tcx)) }
99 super_predicates_of => { Lrc::new(cdata.get_super_predicates(def_id.index, tcx)) }
101 tcx.alloc_trait_def(cdata.get_trait_def(def_id.index, tcx.sess))
103 adt_def => { cdata.get_adt_def(def_id.index, tcx) }
106 tcx.calculate_dtor(def_id, &mut |_,_| Ok(()))
108 variances_of => { Lrc::new(cdata.get_item_variances(def_id.index)) }
109 associated_item_def_ids => {
110 let mut result = vec![];
111 cdata.each_child_of_item(def_id.index,
112 |child| result.push(child.def.def_id()), tcx.sess);
115 associated_item => { cdata.get_associated_item(def_id.index) }
116 impl_trait_ref => { cdata.get_impl_trait(def_id.index, tcx) }
117 impl_polarity => { cdata.get_impl_polarity(def_id.index) }
118 coerce_unsized_info => {
119 cdata.get_coerce_unsized_info(def_id.index).unwrap_or_else(|| {
120 bug!("coerce_unsized_info: `{:?}` is missing its info", def_id);
124 let mir = cdata.maybe_get_optimized_mir(tcx, def_id.index).unwrap_or_else(|| {
125 bug!("get_optimized_mir: missing MIR for `{:?}`", def_id)
128 let mir = tcx.alloc_mir(mir);
132 mir_const_qualif => {
133 (cdata.mir_const_qualif(def_id.index), Lrc::new(BitSet::new_empty(0)))
135 fn_sig => { cdata.fn_sig(def_id.index, tcx) }
136 inherent_impls => { Lrc::new(cdata.get_inherent_implementations_for_type(def_id.index)) }
137 is_const_fn_raw => { cdata.is_const_fn_raw(def_id.index) }
138 is_foreign_item => { cdata.is_foreign_item(def_id.index) }
139 describe_def => { cdata.get_def(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_arg_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 => { Lrc::new(cdata.get_dylib_dependency_formats()) }
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 = Lrc::new(*cdata.extern_crate.lock());
173 is_no_builtins => { cdata.root.no_builtins }
174 impl_defaultness => { cdata.get_impl_defaultness(def_id.index) }
175 reachable_non_generics => {
176 let reachable_non_generics = tcx
177 .exported_symbols(cdata.cnum)
179 .filter_map(|&(exported_symbol, export_level)| {
180 if let ExportedSymbol::NonGeneric(def_id) = exported_symbol {
181 return Some((def_id, export_level))
188 Lrc::new(reachable_non_generics)
190 native_libraries => { Lrc::new(cdata.get_native_libraries(tcx.sess)) }
191 foreign_modules => { Lrc::new(cdata.get_foreign_modules(tcx.sess)) }
192 plugin_registrar_fn => {
193 cdata.root.plugin_registrar_fn.map(|index| {
194 DefId { krate: def_id.krate, index }
197 proc_macro_decls_static => {
198 cdata.root.proc_macro_decls_static.map(|index| {
199 DefId { krate: def_id.krate, index }
202 crate_disambiguator => { cdata.root.disambiguator }
203 crate_hash => { cdata.root.hash }
204 original_crate_name => { cdata.root.name }
206 extra_filename => { cdata.root.extra_filename.clone() }
209 implementations_of_trait => {
210 let mut result = vec![];
211 let filter = Some(other);
212 cdata.get_implementations_for_trait(filter, &mut result);
216 all_trait_implementations => {
217 let mut result = vec![];
218 cdata.get_implementations_for_trait(None, &mut result);
222 visibility => { cdata.get_visibility(def_id.index) }
224 let r = *cdata.dep_kind.lock();
227 crate_name => { cdata.name }
229 let mut result = vec![];
230 cdata.each_child_of_item(def_id.index, |child| result.push(child), tcx.sess);
233 defined_lib_features => { Lrc::new(cdata.get_lib_features()) }
234 defined_lang_items => { Lrc::new(cdata.get_lang_items()) }
235 missing_lang_items => { Lrc::new(cdata.get_missing_lang_items()) }
237 missing_extern_crate_item => {
238 let r = match *cdata.extern_crate.borrow() {
239 Some(extern_crate) if !extern_crate.direct => true,
245 used_crate_source => { Lrc::new(cdata.source.clone()) }
247 exported_symbols => {
248 let cnum = cdata.cnum;
249 assert!(cnum != LOCAL_CRATE);
251 Arc::new(cdata.exported_symbols(tcx))
255 pub fn provide<'tcx>(providers: &mut Providers<'tcx>) {
256 // FIXME(#44234) - almost all of these queries have no sub-queries and
257 // therefore no actual inputs, they're just reading tables calculated in
258 // resolve! Does this work? Unsure! That's what the issue is about
259 *providers = Providers {
260 is_dllimport_foreign_item: |tcx, id| {
261 tcx.native_library_kind(id) == Some(NativeLibraryKind::NativeUnknown)
263 is_statically_included_foreign_item: |tcx, id| {
264 match tcx.native_library_kind(id) {
265 Some(NativeLibraryKind::NativeStatic) |
266 Some(NativeLibraryKind::NativeStaticNobundle) => true,
270 native_library_kind: |tcx, id| {
271 tcx.native_libraries(id.krate)
273 .filter(|lib| native_libs::relevant_lib(&tcx.sess, lib))
275 let fm_id = match lib.foreign_module {
277 None => return false,
279 tcx.foreign_modules(id.krate)
281 .find(|m| m.def_id == fm_id)
282 .expect("failed to find foreign module")
288 native_libraries: |tcx, cnum| {
289 assert_eq!(cnum, LOCAL_CRATE);
290 Lrc::new(native_libs::collect(tcx))
292 foreign_modules: |tcx, cnum| {
293 assert_eq!(cnum, LOCAL_CRATE);
294 Lrc::new(foreign_modules::collect(tcx))
296 link_args: |tcx, cnum| {
297 assert_eq!(cnum, LOCAL_CRATE);
298 Lrc::new(link_args::collect(tcx))
301 // Returns a map from a sufficiently visible external item (i.e., an
302 // external item that is visible from at least one local module) to a
303 // sufficiently visible parent (considering modules that re-export the
304 // external item to be parents).
305 visible_parent_map: |tcx, cnum| {
306 use std::collections::vec_deque::VecDeque;
307 use std::collections::hash_map::Entry;
309 assert_eq!(cnum, LOCAL_CRATE);
310 let mut visible_parent_map: DefIdMap<DefId> = Default::default();
312 // Issue 46112: We want the map to prefer the shortest
313 // paths when reporting the path to an item. Therefore we
314 // build up the map via a breadth-first search (BFS),
315 // which naturally yields minimal-length paths.
317 // Note that it needs to be a BFS over the whole forest of
318 // crates, not just each individual crate; otherwise you
319 // only get paths that are locally minimal with respect to
320 // whatever crate we happened to encounter first in this
321 // traversal, but not globally minimal across all crates.
322 let bfs_queue = &mut VecDeque::new();
324 // Preferring shortest paths alone does not guarantee a
325 // deterministic result; so sort by crate num to avoid
326 // hashtable iteration non-determinism. This only makes
327 // things as deterministic as crate-nums assignment is,
328 // which is to say, its not deterministic in general. But
329 // we believe that libstd is consistently assigned crate
330 // num 1, so it should be enough to resolve #46112.
331 let mut crates: Vec<CrateNum> = (*tcx.crates()).clone();
334 for &cnum in crates.iter() {
335 // Ignore crates without a corresponding local `extern crate` item.
336 if tcx.missing_extern_crate_item(cnum) {
340 bfs_queue.push_back(DefId {
342 index: CRATE_DEF_INDEX
346 // (restrict scope of mutable-borrow of `visible_parent_map`)
348 let visible_parent_map = &mut visible_parent_map;
349 let mut add_child = |bfs_queue: &mut VecDeque<_>,
352 if child.vis != ty::Visibility::Public {
356 let child = child.def.def_id();
358 match visible_parent_map.entry(child) {
359 Entry::Occupied(mut entry) => {
360 // If `child` is defined in crate `cnum`, ensure
361 // that it is mapped to a parent in `cnum`.
362 if child.krate == cnum && entry.get().krate != cnum {
363 entry.insert(parent);
366 Entry::Vacant(entry) => {
367 entry.insert(parent);
368 bfs_queue.push_back(child);
373 while let Some(def) = bfs_queue.pop_front() {
374 for child in tcx.item_children(def).iter() {
375 add_child(bfs_queue, child, def);
380 Lrc::new(visible_parent_map)
387 impl cstore::CStore {
388 pub fn export_macros_untracked(&self, cnum: CrateNum) {
389 let data = self.get_crate_data(cnum);
390 let mut dep_kind = data.dep_kind.lock();
391 if *dep_kind == DepKind::UnexportedMacrosOnly {
392 *dep_kind = DepKind::MacrosOnly;
396 pub fn dep_kind_untracked(&self, cnum: CrateNum) -> DepKind {
397 let data = self.get_crate_data(cnum);
398 let r = *data.dep_kind.lock();
402 pub fn crate_edition_untracked(&self, cnum: CrateNum) -> Edition {
403 self.get_crate_data(cnum).root.edition
406 pub fn struct_field_names_untracked(&self, def: DefId) -> Vec<ast::Name> {
407 self.get_crate_data(def.krate).get_struct_field_names(def.index)
410 pub fn item_children_untracked(&self, def_id: DefId, sess: &Session) -> Vec<def::Export> {
411 let mut result = vec![];
412 self.get_crate_data(def_id.krate)
413 .each_child_of_item(def_id.index, |child| result.push(child), sess);
417 pub fn load_macro_untracked(&self, id: DefId, sess: &Session) -> LoadedMacro {
418 let data = self.get_crate_data(id.krate);
419 if let Some(ref proc_macros) = data.proc_macros {
420 return LoadedMacro::ProcMacro(proc_macros[id.index.to_proc_macro_index()].1.clone());
421 } else if data.name == "proc_macro" && data.item_name(id.index) == "quote" {
422 use syntax::ext::base::SyntaxExtension;
423 use syntax_ext::proc_macro_impl::BangProcMacro;
425 let client = proc_macro::bridge::client::Client::expand1(proc_macro::quote);
426 let ext = SyntaxExtension::ProcMacro {
427 expander: Box::new(BangProcMacro { client }),
428 allow_internal_unstable: Some(vec![
429 Symbol::intern("proc_macro_def_site"),
431 edition: data.root.edition,
433 return LoadedMacro::ProcMacro(Lrc::new(ext));
436 let def = data.get_macro(id.index);
437 let macro_full_name = data.def_path(id.index).to_string_friendly(|_| data.imported_name);
438 let source_name = FileName::Macros(macro_full_name);
440 let source_file = sess.parse_sess.source_map().new_source_file(source_name, def.body);
441 let local_span = Span::new(source_file.start_pos, source_file.end_pos, NO_EXPANSION);
442 let (body, mut errors) = source_file_to_stream(&sess.parse_sess, source_file, None);
443 emit_unclosed_delims(&mut errors, &sess.diagnostic());
445 // Mark the attrs as used
446 let attrs = data.get_item_attrs(id.index, sess);
447 for attr in attrs.iter() {
448 attr::mark_used(attr);
451 let name = data.def_key(id.index).disambiguated_data.data
452 .get_opt_name().expect("no name in load_macro");
453 sess.imported_macro_spans.borrow_mut()
454 .insert(local_span, (name.to_string(), data.get_span(id.index, sess)));
456 LoadedMacro::MacroDef(ast::Item {
457 ident: ast::Ident::from_str(&name.as_str()),
458 id: ast::DUMMY_NODE_ID,
460 attrs: attrs.iter().cloned().collect(),
461 node: ast::ItemKind::MacroDef(ast::MacroDef {
465 vis: source_map::respan(local_span.shrink_to_lo(), ast::VisibilityKind::Inherited),
470 pub fn associated_item_cloned_untracked(&self, def: DefId) -> ty::AssociatedItem {
471 self.get_crate_data(def.krate).get_associated_item(def.index)
475 impl CrateStore for cstore::CStore {
476 fn crate_data_as_rc_any(&self, krate: CrateNum) -> Lrc<dyn Any> {
477 self.get_crate_data(krate)
480 fn item_generics_cloned_untracked(&self, def: DefId, sess: &Session) -> ty::Generics {
481 self.get_crate_data(def.krate).get_generics(def.index, sess)
484 fn crate_name_untracked(&self, cnum: CrateNum) -> Symbol
486 self.get_crate_data(cnum).name
489 fn crate_disambiguator_untracked(&self, cnum: CrateNum) -> CrateDisambiguator
491 self.get_crate_data(cnum).root.disambiguator
494 fn crate_hash_untracked(&self, cnum: CrateNum) -> Svh
496 self.get_crate_data(cnum).root.hash
499 /// Returns the `DefKey` for a given `DefId`. This indicates the
500 /// parent `DefId` as well as some idea of what kind of data the
501 /// `DefId` refers to.
502 fn def_key(&self, def: DefId) -> DefKey {
503 // Note: loading the def-key (or def-path) for a def-id is not
504 // a *read* of its metadata. This is because the def-id is
505 // really just an interned shorthand for a def-path, which is the
506 // canonical name for an item.
508 // self.dep_graph.read(DepNode::MetaData(def));
509 self.get_crate_data(def.krate).def_key(def.index)
512 fn def_path(&self, def: DefId) -> DefPath {
513 // See `Note` above in `def_key()` for why this read is
516 // self.dep_graph.read(DepNode::MetaData(def));
517 self.get_crate_data(def.krate).def_path(def.index)
520 fn def_path_hash(&self, def: DefId) -> DefPathHash {
521 self.get_crate_data(def.krate).def_path_hash(def.index)
524 fn def_path_table(&self, cnum: CrateNum) -> Lrc<DefPathTable> {
525 self.get_crate_data(cnum).def_path_table.clone()
528 fn crates_untracked(&self) -> Vec<CrateNum>
530 let mut result = vec![];
531 self.iter_crate_data(|cnum, _| result.push(cnum));
535 fn extern_mod_stmt_cnum_untracked(&self, emod_id: ast::NodeId) -> Option<CrateNum>
537 self.do_extern_mod_stmt_cnum(emod_id)
540 fn postorder_cnums_untracked(&self) -> Vec<CrateNum> {
541 self.do_postorder_cnums_untracked()
544 fn encode_metadata<'a, 'tcx>(&self,
545 tcx: TyCtxt<'a, 'tcx, 'tcx>)
548 encoder::encode_metadata(tcx)
551 fn metadata_encoding_version(&self) -> &[u8]
553 schema::METADATA_HEADER