1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 use cstore::{self, LoadedMacro};
18 use rustc::ty::query::QueryConfig;
19 use rustc::middle::cstore::{CrateStore, DepKind,
20 EncodedMetadata, NativeLibraryKind};
21 use rustc::middle::exported_symbols::ExportedSymbol;
22 use rustc::middle::stability::DeprecationEntry;
24 use rustc::session::{CrateDisambiguator, Session};
25 use rustc::ty::{self, TyCtxt};
26 use rustc::ty::query::Providers;
27 use rustc::hir::def_id::{CrateNum, DefId, LOCAL_CRATE, CRATE_DEF_INDEX};
28 use rustc::hir::map::{DefKey, DefPath, DefPathHash};
29 use rustc::hir::map::blocks::FnLikeNode;
30 use rustc::hir::map::definitions::DefPathTable;
31 use rustc::util::nodemap::DefIdMap;
32 use rustc_data_structures::svh::Svh;
35 use rustc_data_structures::sync::Lrc;
40 use syntax::source_map;
41 use syntax::edition::Edition;
42 use syntax::parse::source_file_to_stream;
43 use syntax::symbol::Symbol;
44 use syntax_pos::{Span, NO_EXPANSION, FileName};
45 use rustc_data_structures::bit_set::BitSet;
48 macro_rules! provide {
49 (<$lt:tt> $tcx:ident, $def_id:ident, $other:ident, $cdata:ident,
50 $($name:ident => $compute:block)*) => {
51 pub fn provide_extern<$lt>(providers: &mut Providers<$lt>) {
52 $(fn $name<'a, $lt:$lt, T>($tcx: TyCtxt<'a, $lt, $lt>, def_id_arg: T)
53 -> <ty::queries::$name<$lt> as
54 QueryConfig<$lt>>::Value
57 #[allow(unused_variables)]
58 let ($def_id, $other) = def_id_arg.into_args();
59 assert!(!$def_id.is_local());
61 let def_path_hash = $tcx.def_path_hash(DefId {
63 index: CRATE_DEF_INDEX
65 let dep_node = def_path_hash
66 .to_dep_node(::rustc::dep_graph::DepKind::CrateMetadata);
67 // The DepNodeIndex of the DepNode::CrateMetadata should be
68 // cached somewhere, so that we can use read_index().
69 $tcx.dep_graph.read(dep_node);
71 let $cdata = $tcx.crate_data_as_rc_any($def_id.krate);
72 let $cdata = $cdata.downcast_ref::<cstore::CrateMetadata>()
73 .expect("CrateStore crated ata is not a CrateMetadata");
77 *providers = Providers {
85 // small trait to work around different signature queries all being defined via
88 fn into_args(self) -> (DefId, DefId);
91 impl IntoArgs for DefId {
92 fn into_args(self) -> (DefId, DefId) { (self, self) }
95 impl IntoArgs for CrateNum {
96 fn into_args(self) -> (DefId, DefId) { (self.as_def_id(), self.as_def_id()) }
99 impl IntoArgs for (CrateNum, DefId) {
100 fn into_args(self) -> (DefId, DefId) { (self.0.as_def_id(), self.1) }
103 provide! { <'tcx> tcx, def_id, other, cdata,
104 type_of => { cdata.get_type(def_id.index, tcx) }
106 tcx.alloc_generics(cdata.get_generics(def_id.index, tcx.sess))
108 predicates_of => { cdata.get_predicates(def_id.index, tcx) }
109 predicates_defined_on => { cdata.get_predicates_defined_on(def_id.index, tcx) }
110 super_predicates_of => { cdata.get_super_predicates(def_id.index, tcx) }
112 tcx.alloc_trait_def(cdata.get_trait_def(def_id.index, tcx.sess))
114 adt_def => { cdata.get_adt_def(def_id.index, tcx) }
117 tcx.calculate_dtor(def_id, &mut |_,_| Ok(()))
119 variances_of => { Lrc::new(cdata.get_item_variances(def_id.index)) }
120 associated_item_def_ids => {
121 let mut result = vec![];
122 cdata.each_child_of_item(def_id.index,
123 |child| result.push(child.def.def_id()), tcx.sess);
126 associated_item => { cdata.get_associated_item(def_id.index) }
127 impl_trait_ref => { cdata.get_impl_trait(def_id.index, tcx) }
128 impl_polarity => { cdata.get_impl_polarity(def_id.index) }
129 coerce_unsized_info => {
130 cdata.get_coerce_unsized_info(def_id.index).unwrap_or_else(|| {
131 bug!("coerce_unsized_info: `{:?}` is missing its info", def_id);
135 let mir = cdata.maybe_get_optimized_mir(tcx, def_id.index).unwrap_or_else(|| {
136 bug!("get_optimized_mir: missing MIR for `{:?}`", def_id)
139 let mir = tcx.alloc_mir(mir);
143 mir_const_qualif => {
144 (cdata.mir_const_qualif(def_id.index), Lrc::new(BitSet::new_empty(0)))
146 fn_sig => { cdata.fn_sig(def_id.index, tcx) }
147 inherent_impls => { Lrc::new(cdata.get_inherent_implementations_for_type(def_id.index)) }
148 is_const_fn => { cdata.is_const_fn(def_id.index) }
149 is_foreign_item => { cdata.is_foreign_item(def_id.index) }
150 describe_def => { cdata.get_def(def_id.index) }
151 def_span => { cdata.get_span(def_id.index, &tcx.sess) }
152 lookup_stability => {
153 cdata.get_stability(def_id.index).map(|s| tcx.intern_stability(s))
155 lookup_deprecation_entry => {
156 cdata.get_deprecation(def_id.index).map(DeprecationEntry::external)
158 item_attrs => { cdata.get_item_attrs(def_id.index, tcx.sess) }
159 // FIXME(#38501) We've skipped a `read` on the `HirBody` of
160 // a `fn` when encoding, so the dep-tracking wouldn't work.
161 // This is only used by rustdoc anyway, which shouldn't have
162 // incremental recompilation ever enabled.
163 fn_arg_names => { cdata.get_fn_arg_names(def_id.index) }
164 rendered_const => { cdata.get_rendered_const(def_id.index) }
165 impl_parent => { cdata.get_parent_impl(def_id.index) }
166 trait_of_item => { cdata.get_trait_of_item(def_id.index) }
167 const_is_rvalue_promotable_to_static => {
168 cdata.const_is_rvalue_promotable_to_static(def_id.index)
170 is_mir_available => { cdata.is_item_mir_available(def_id.index) }
172 dylib_dependency_formats => { Lrc::new(cdata.get_dylib_dependency_formats()) }
173 is_panic_runtime => { cdata.root.panic_runtime }
174 is_compiler_builtins => { cdata.root.compiler_builtins }
175 has_global_allocator => { cdata.root.has_global_allocator }
176 has_panic_handler => { cdata.root.has_panic_handler }
177 is_sanitizer_runtime => { cdata.root.sanitizer_runtime }
178 is_profiler_runtime => { cdata.root.profiler_runtime }
179 panic_strategy => { cdata.root.panic_strategy }
181 let r = Lrc::new(*cdata.extern_crate.lock());
184 is_no_builtins => { cdata.root.no_builtins }
185 impl_defaultness => { cdata.get_impl_defaultness(def_id.index) }
186 reachable_non_generics => {
187 let reachable_non_generics = tcx
188 .exported_symbols(cdata.cnum)
190 .filter_map(|&(exported_symbol, export_level)| {
191 if let ExportedSymbol::NonGeneric(def_id) = exported_symbol {
192 return Some((def_id, export_level))
199 Lrc::new(reachable_non_generics)
201 native_libraries => { Lrc::new(cdata.get_native_libraries(tcx.sess)) }
202 foreign_modules => { Lrc::new(cdata.get_foreign_modules(tcx.sess)) }
203 plugin_registrar_fn => {
204 cdata.root.plugin_registrar_fn.map(|index| {
205 DefId { krate: def_id.krate, index }
208 derive_registrar_fn => {
209 cdata.root.macro_derive_registrar.map(|index| {
210 DefId { krate: def_id.krate, index }
213 crate_disambiguator => { cdata.root.disambiguator }
214 crate_hash => { cdata.root.hash }
215 original_crate_name => { cdata.root.name }
217 extra_filename => { cdata.root.extra_filename.clone() }
220 implementations_of_trait => {
221 let mut result = vec![];
222 let filter = Some(other);
223 cdata.get_implementations_for_trait(filter, &mut result);
227 all_trait_implementations => {
228 let mut result = vec![];
229 cdata.get_implementations_for_trait(None, &mut result);
233 visibility => { cdata.get_visibility(def_id.index) }
235 let r = *cdata.dep_kind.lock();
238 crate_name => { cdata.name }
240 let mut result = vec![];
241 cdata.each_child_of_item(def_id.index, |child| result.push(child), tcx.sess);
244 defined_lib_features => { Lrc::new(cdata.get_lib_features()) }
245 defined_lang_items => { Lrc::new(cdata.get_lang_items()) }
246 missing_lang_items => { Lrc::new(cdata.get_missing_lang_items()) }
248 missing_extern_crate_item => {
249 let r = match *cdata.extern_crate.borrow() {
250 Some(extern_crate) if !extern_crate.direct => true,
256 used_crate_source => { Lrc::new(cdata.source.clone()) }
258 exported_symbols => {
259 let cnum = cdata.cnum;
260 assert!(cnum != LOCAL_CRATE);
262 // If this crate is a custom derive crate, then we're not even going to
263 // link those in so we skip those crates.
264 if cdata.root.macro_derive_registrar.is_some() {
265 return Arc::new(Vec::new())
268 Arc::new(cdata.exported_symbols(tcx))
272 pub fn provide<'tcx>(providers: &mut Providers<'tcx>) {
273 fn is_const_fn<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> bool {
274 let node_id = tcx.hir.as_local_node_id(def_id)
275 .expect("Non-local call to local provider is_const_fn");
277 if let Some(fn_like) = FnLikeNode::from_node(tcx.hir.get(node_id)) {
278 fn_like.constness() == hir::Constness::Const
284 // FIXME(#44234) - almost all of these queries have no sub-queries and
285 // therefore no actual inputs, they're just reading tables calculated in
286 // resolve! Does this work? Unsure! That's what the issue is about
287 *providers = Providers {
289 is_dllimport_foreign_item: |tcx, id| {
290 tcx.native_library_kind(id) == Some(NativeLibraryKind::NativeUnknown)
292 is_statically_included_foreign_item: |tcx, id| {
293 match tcx.native_library_kind(id) {
294 Some(NativeLibraryKind::NativeStatic) |
295 Some(NativeLibraryKind::NativeStaticNobundle) => true,
299 native_library_kind: |tcx, id| {
300 tcx.native_libraries(id.krate)
302 .filter(|lib| native_libs::relevant_lib(&tcx.sess, lib))
304 let fm_id = match lib.foreign_module {
306 None => return false,
308 tcx.foreign_modules(id.krate)
310 .find(|m| m.def_id == fm_id)
311 .expect("failed to find foreign module")
317 native_libraries: |tcx, cnum| {
318 assert_eq!(cnum, LOCAL_CRATE);
319 Lrc::new(native_libs::collect(tcx))
321 foreign_modules: |tcx, cnum| {
322 assert_eq!(cnum, LOCAL_CRATE);
323 Lrc::new(foreign_modules::collect(tcx))
325 link_args: |tcx, cnum| {
326 assert_eq!(cnum, LOCAL_CRATE);
327 Lrc::new(link_args::collect(tcx))
330 // Returns a map from a sufficiently visible external item (i.e. an
331 // external item that is visible from at least one local module) to a
332 // sufficiently visible parent (considering modules that re-export the
333 // external item to be parents).
334 visible_parent_map: |tcx, cnum| {
335 use std::collections::vec_deque::VecDeque;
336 use std::collections::hash_map::Entry;
338 assert_eq!(cnum, LOCAL_CRATE);
339 let mut visible_parent_map: DefIdMap<DefId> = DefIdMap();
341 // Issue 46112: We want the map to prefer the shortest
342 // paths when reporting the path to an item. Therefore we
343 // build up the map via a breadth-first search (BFS),
344 // which naturally yields minimal-length paths.
346 // Note that it needs to be a BFS over the whole forest of
347 // crates, not just each individual crate; otherwise you
348 // only get paths that are locally minimal with respect to
349 // whatever crate we happened to encounter first in this
350 // traversal, but not globally minimal across all crates.
351 let bfs_queue = &mut VecDeque::new();
353 // Preferring shortest paths alone does not guarantee a
354 // deterministic result; so sort by crate num to avoid
355 // hashtable iteration non-determinism. This only makes
356 // things as deterministic as crate-nums assignment is,
357 // which is to say, its not deterministic in general. But
358 // we believe that libstd is consistently assigned crate
359 // num 1, so it should be enough to resolve #46112.
360 let mut crates: Vec<CrateNum> = (*tcx.crates()).clone();
363 for &cnum in crates.iter() {
364 // Ignore crates without a corresponding local `extern crate` item.
365 if tcx.missing_extern_crate_item(cnum) {
369 bfs_queue.push_back(DefId {
371 index: CRATE_DEF_INDEX
375 // (restrict scope of mutable-borrow of `visible_parent_map`)
377 let visible_parent_map = &mut visible_parent_map;
378 let mut add_child = |bfs_queue: &mut VecDeque<_>,
381 if child.vis != ty::Visibility::Public {
385 let child = child.def.def_id();
387 match visible_parent_map.entry(child) {
388 Entry::Occupied(mut entry) => {
389 // If `child` is defined in crate `cnum`, ensure
390 // that it is mapped to a parent in `cnum`.
391 if child.krate == cnum && entry.get().krate != cnum {
392 entry.insert(parent);
395 Entry::Vacant(entry) => {
396 entry.insert(parent);
397 bfs_queue.push_back(child);
402 while let Some(def) = bfs_queue.pop_front() {
403 for child in tcx.item_children(def).iter() {
404 add_child(bfs_queue, child, def);
409 Lrc::new(visible_parent_map)
416 impl cstore::CStore {
417 pub fn export_macros_untracked(&self, cnum: CrateNum) {
418 let data = self.get_crate_data(cnum);
419 let mut dep_kind = data.dep_kind.lock();
420 if *dep_kind == DepKind::UnexportedMacrosOnly {
421 *dep_kind = DepKind::MacrosOnly;
425 pub fn dep_kind_untracked(&self, cnum: CrateNum) -> DepKind {
426 let data = self.get_crate_data(cnum);
427 let r = *data.dep_kind.lock();
431 pub fn crate_edition_untracked(&self, cnum: CrateNum) -> Edition {
432 self.get_crate_data(cnum).root.edition
435 pub fn struct_field_names_untracked(&self, def: DefId) -> Vec<ast::Name> {
436 self.get_crate_data(def.krate).get_struct_field_names(def.index)
439 pub fn item_children_untracked(&self, def_id: DefId, sess: &Session) -> Vec<def::Export> {
440 let mut result = vec![];
441 self.get_crate_data(def_id.krate)
442 .each_child_of_item(def_id.index, |child| result.push(child), sess);
446 pub fn load_macro_untracked(&self, id: DefId, sess: &Session) -> LoadedMacro {
447 let data = self.get_crate_data(id.krate);
448 if let Some(ref proc_macros) = data.proc_macros {
449 return LoadedMacro::ProcMacro(proc_macros[id.index.to_proc_macro_index()].1.clone());
450 } else if data.name == "proc_macro" &&
451 self.get_crate_data(id.krate).item_name(id.index) == "quote" {
452 use syntax::ext::base::SyntaxExtension;
453 use syntax_ext::proc_macro_impl::BangProcMacro;
455 let ext = SyntaxExtension::ProcMacro {
456 expander: Box::new(BangProcMacro { inner: ::proc_macro::quote }),
457 allow_internal_unstable: true,
458 edition: data.root.edition,
460 return LoadedMacro::ProcMacro(Lrc::new(ext));
463 let (name, def) = data.get_macro(id.index);
464 let source_name = FileName::Macros(name.to_string());
466 let source_file = sess.parse_sess.source_map().new_source_file(source_name, def.body);
467 let local_span = Span::new(source_file.start_pos, source_file.end_pos, NO_EXPANSION);
468 let body = source_file_to_stream(&sess.parse_sess, source_file, None);
470 // Mark the attrs as used
471 let attrs = data.get_item_attrs(id.index, sess);
472 for attr in attrs.iter() {
473 attr::mark_used(attr);
476 let name = data.def_key(id.index).disambiguated_data.data
477 .get_opt_name().expect("no name in load_macro");
478 sess.imported_macro_spans.borrow_mut()
479 .insert(local_span, (name.to_string(), data.get_span(id.index, sess)));
481 LoadedMacro::MacroDef(ast::Item {
482 ident: ast::Ident::from_str(&name.as_str()),
483 id: ast::DUMMY_NODE_ID,
485 attrs: attrs.iter().cloned().collect(),
486 node: ast::ItemKind::MacroDef(ast::MacroDef {
490 vis: source_map::respan(local_span.shrink_to_lo(), ast::VisibilityKind::Inherited),
495 pub fn associated_item_cloned_untracked(&self, def: DefId) -> ty::AssociatedItem {
496 self.get_crate_data(def.krate).get_associated_item(def.index)
500 impl CrateStore for cstore::CStore {
501 fn crate_data_as_rc_any(&self, krate: CrateNum) -> Lrc<dyn Any> {
502 self.get_crate_data(krate)
505 fn item_generics_cloned_untracked(&self, def: DefId, sess: &Session) -> ty::Generics {
506 self.get_crate_data(def.krate).get_generics(def.index, sess)
509 fn crate_name_untracked(&self, cnum: CrateNum) -> Symbol
511 self.get_crate_data(cnum).name
514 fn crate_disambiguator_untracked(&self, cnum: CrateNum) -> CrateDisambiguator
516 self.get_crate_data(cnum).root.disambiguator
519 fn crate_hash_untracked(&self, cnum: CrateNum) -> Svh
521 self.get_crate_data(cnum).root.hash
524 /// Returns the `DefKey` for a given `DefId`. This indicates the
525 /// parent `DefId` as well as some idea of what kind of data the
526 /// `DefId` refers to.
527 fn def_key(&self, def: DefId) -> DefKey {
528 // Note: loading the def-key (or def-path) for a def-id is not
529 // a *read* of its metadata. This is because the def-id is
530 // really just an interned shorthand for a def-path, which is the
531 // canonical name for an item.
533 // self.dep_graph.read(DepNode::MetaData(def));
534 self.get_crate_data(def.krate).def_key(def.index)
537 fn def_path(&self, def: DefId) -> DefPath {
538 // See `Note` above in `def_key()` for why this read is
541 // self.dep_graph.read(DepNode::MetaData(def));
542 self.get_crate_data(def.krate).def_path(def.index)
545 fn def_path_hash(&self, def: DefId) -> DefPathHash {
546 self.get_crate_data(def.krate).def_path_hash(def.index)
549 fn def_path_table(&self, cnum: CrateNum) -> Lrc<DefPathTable> {
550 self.get_crate_data(cnum).def_path_table.clone()
553 fn crates_untracked(&self) -> Vec<CrateNum>
555 let mut result = vec![];
556 self.iter_crate_data(|cnum, _| result.push(cnum));
560 fn extern_mod_stmt_cnum_untracked(&self, emod_id: ast::NodeId) -> Option<CrateNum>
562 self.do_extern_mod_stmt_cnum(emod_id)
565 fn postorder_cnums_untracked(&self) -> Vec<CrateNum> {
566 self.do_postorder_cnums_untracked()
569 fn encode_metadata<'a, 'tcx>(&self,
570 tcx: TyCtxt<'a, 'tcx, 'tcx>)
573 encoder::encode_metadata(tcx)
576 fn metadata_encoding_version(&self) -> &[u8]
578 schema::METADATA_HEADER