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.
15 use rustc::dep_graph::DepTrackingMapConfig;
16 use rustc::middle::cstore::{CrateStore, CrateSource, LibSource, DepKind,
17 NativeLibrary, MetadataLoader, LinkMeta,
18 LinkagePreference, LoadedMacro, EncodedMetadata};
20 use rustc::middle::lang_items;
21 use rustc::session::Session;
22 use rustc::ty::{self, TyCtxt};
23 use rustc::ty::maps::Providers;
24 use rustc::hir::def_id::{CrateNum, DefId, DefIndex, CRATE_DEF_INDEX, LOCAL_CRATE};
25 use rustc::hir::map::{DefKey, DefPath, DisambiguatedDefPathData, DefPathHash};
26 use rustc::hir::map::blocks::FnLikeNode;
27 use rustc::hir::map::definitions::{DefPathTable, GlobalMetaDataKind};
28 use rustc::util::nodemap::{NodeSet, DefIdMap};
29 use rustc_back::PanicStrategy;
36 use syntax::parse::filemap_to_stream;
37 use syntax::symbol::Symbol;
38 use syntax_pos::{Span, NO_EXPANSION};
39 use rustc::hir::svh::Svh;
42 macro_rules! provide {
43 (<$lt:tt> $tcx:ident, $def_id:ident, $cdata:ident, $($name:ident => $compute:block)*) => {
44 pub fn provide<$lt>(providers: &mut Providers<$lt>) {
45 $(fn $name<'a, $lt:$lt>($tcx: TyCtxt<'a, $lt, $lt>, $def_id: DefId)
46 -> <ty::queries::$name<$lt> as
47 DepTrackingMapConfig>::Value {
48 assert!(!$def_id.is_local());
50 let def_path_hash = $tcx.def_path_hash($def_id);
51 let dep_node = def_path_hash.to_dep_node(::rustc::dep_graph::DepKind::MetaData);
53 $tcx.dep_graph.read(dep_node);
55 let $cdata = $tcx.sess.cstore.crate_data_as_rc_any($def_id.krate);
56 let $cdata = $cdata.downcast_ref::<cstore::CrateMetadata>()
57 .expect("CrateStore crated ata is not a CrateMetadata");
61 *providers = Providers {
69 provide! { <'tcx> tcx, def_id, cdata,
70 type_of => { cdata.get_type(def_id.index, tcx) }
71 generics_of => { tcx.alloc_generics(cdata.get_generics(def_id.index)) }
72 predicates_of => { cdata.get_predicates(def_id.index, tcx) }
73 super_predicates_of => { cdata.get_super_predicates(def_id.index, tcx) }
75 tcx.alloc_trait_def(cdata.get_trait_def(def_id.index))
77 adt_def => { cdata.get_adt_def(def_id.index, tcx) }
80 tcx.calculate_dtor(def_id, &mut |_,_| Ok(()))
82 variances_of => { Rc::new(cdata.get_item_variances(def_id.index)) }
83 associated_item_def_ids => {
84 let mut result = vec![];
85 cdata.each_child_of_item(def_id.index,
86 |child| result.push(child.def.def_id()), tcx.sess);
89 associated_item => { cdata.get_associated_item(def_id.index) }
90 impl_trait_ref => { cdata.get_impl_trait(def_id.index, tcx) }
91 impl_polarity => { cdata.get_impl_polarity(def_id.index) }
92 coerce_unsized_info => {
93 cdata.get_coerce_unsized_info(def_id.index).unwrap_or_else(|| {
94 bug!("coerce_unsized_info: `{:?}` is missing its info", def_id);
98 let mir = cdata.maybe_get_optimized_mir(tcx, def_id.index).unwrap_or_else(|| {
99 bug!("get_optimized_mir: missing MIR for `{:?}`", def_id)
102 let mir = tcx.alloc_mir(mir);
106 mir_const_qualif => { cdata.mir_const_qualif(def_id.index) }
107 typeck_tables_of => { cdata.item_body_tables(def_id.index, tcx) }
108 closure_kind => { cdata.closure_kind(def_id.index) }
109 fn_sig => { cdata.fn_sig(def_id.index, tcx) }
110 inherent_impls => { Rc::new(cdata.get_inherent_implementations_for_type(def_id.index)) }
111 is_const_fn => { cdata.is_const_fn(def_id.index) }
112 is_foreign_item => { cdata.is_foreign_item(def_id.index) }
113 is_default_impl => { cdata.is_default_impl(def_id.index) }
114 describe_def => { cdata.get_def(def_id.index) }
115 def_span => { cdata.get_span(def_id.index, &tcx.sess) }
116 stability => { cdata.get_stability(def_id.index) }
117 deprecation => { cdata.get_deprecation(def_id.index) }
118 item_attrs => { cdata.get_item_attrs(def_id.index, &tcx.dep_graph) }
119 // FIXME(#38501) We've skipped a `read` on the `HirBody` of
120 // a `fn` when encoding, so the dep-tracking wouldn't work.
121 // This is only used by rustdoc anyway, which shouldn't have
122 // incremental recompilation ever enabled.
123 fn_arg_names => { cdata.get_fn_arg_names(def_id.index) }
124 impl_parent => { cdata.get_parent_impl(def_id.index) }
125 trait_of_item => { cdata.get_trait_of_item(def_id.index) }
126 is_exported_symbol => {
127 let dep_node = cdata.metadata_dep_node(GlobalMetaDataKind::ExportedSymbols);
128 cdata.exported_symbols.get(&tcx.dep_graph, dep_node).contains(&def_id.index)
130 item_body_nested_bodies => { Rc::new(cdata.item_body_nested_bodies(def_id.index)) }
131 const_is_rvalue_promotable_to_static => {
132 cdata.const_is_rvalue_promotable_to_static(def_id.index)
134 is_mir_available => { cdata.is_item_mir_available(def_id.index) }
136 dylib_dependency_formats => { Rc::new(cdata.get_dylib_dependency_formats(&tcx.dep_graph)) }
137 is_allocator => { cdata.is_allocator(&tcx.dep_graph) }
138 is_panic_runtime => { cdata.is_panic_runtime(&tcx.dep_graph) }
139 extern_crate => { Rc::new(cdata.extern_crate.get()) }
142 pub fn provide_local<'tcx>(providers: &mut Providers<'tcx>) {
143 fn is_const_fn<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> bool {
144 let node_id = tcx.hir.as_local_node_id(def_id)
145 .expect("Non-local call to local provider is_const_fn");
147 if let Some(fn_like) = FnLikeNode::from_node(tcx.hir.get(node_id)) {
148 fn_like.constness() == hir::Constness::Const
154 *providers = Providers {
160 impl CrateStore for cstore::CStore {
161 fn crate_data_as_rc_any(&self, krate: CrateNum) -> Rc<Any> {
162 self.get_crate_data(krate)
165 fn metadata_loader(&self) -> &MetadataLoader {
166 &*self.metadata_loader
169 fn visibility(&self, def: DefId) -> ty::Visibility {
170 self.read_dep_node(def);
171 self.get_crate_data(def.krate).get_visibility(def.index)
174 fn item_generics_cloned(&self, def: DefId) -> ty::Generics {
175 self.read_dep_node(def);
176 self.get_crate_data(def.krate).get_generics(def.index)
179 fn implementations_of_trait(&self, filter: Option<DefId>) -> Vec<DefId>
181 let mut result = vec![];
183 self.iter_crate_data(|_, cdata| {
184 cdata.get_implementations_for_trait(filter, &self.dep_graph, &mut result)
189 fn impl_defaultness(&self, def: DefId) -> hir::Defaultness
191 self.read_dep_node(def);
192 self.get_crate_data(def.krate).get_impl_defaultness(def.index)
195 fn associated_item_cloned(&self, def: DefId) -> ty::AssociatedItem
197 self.read_dep_node(def);
198 self.get_crate_data(def.krate).get_associated_item(def.index)
201 fn is_statically_included_foreign_item(&self, def_id: DefId) -> bool
203 self.do_is_statically_included_foreign_item(def_id)
206 fn is_dllimport_foreign_item(&self, def_id: DefId) -> bool {
207 if def_id.krate == LOCAL_CRATE {
208 self.dllimport_foreign_items.borrow().contains(&def_id.index)
210 self.get_crate_data(def_id.krate)
211 .is_dllimport_foreign_item(def_id.index, &self.dep_graph)
215 fn dep_kind(&self, cnum: CrateNum) -> DepKind
217 let data = self.get_crate_data(cnum);
218 let dep_node = data.metadata_dep_node(GlobalMetaDataKind::CrateDeps);
219 self.dep_graph.read(dep_node);
223 fn export_macros(&self, cnum: CrateNum) {
224 let data = self.get_crate_data(cnum);
225 let dep_node = data.metadata_dep_node(GlobalMetaDataKind::CrateDeps);
227 self.dep_graph.read(dep_node);
228 if data.dep_kind.get() == DepKind::UnexportedMacrosOnly {
229 data.dep_kind.set(DepKind::MacrosOnly)
233 fn lang_items(&self, cnum: CrateNum) -> Vec<(DefIndex, usize)>
235 self.get_crate_data(cnum).get_lang_items(&self.dep_graph)
238 fn missing_lang_items(&self, cnum: CrateNum)
239 -> Vec<lang_items::LangItem>
241 self.get_crate_data(cnum).get_missing_lang_items(&self.dep_graph)
244 fn is_compiler_builtins(&self, cnum: CrateNum) -> bool {
245 self.get_crate_data(cnum).is_compiler_builtins(&self.dep_graph)
248 fn is_sanitizer_runtime(&self, cnum: CrateNum) -> bool {
249 self.get_crate_data(cnum).is_sanitizer_runtime(&self.dep_graph)
252 fn is_profiler_runtime(&self, cnum: CrateNum) -> bool {
253 self.get_crate_data(cnum).is_profiler_runtime(&self.dep_graph)
256 fn panic_strategy(&self, cnum: CrateNum) -> PanicStrategy {
257 self.get_crate_data(cnum).panic_strategy(&self.dep_graph)
260 fn crate_name(&self, cnum: CrateNum) -> Symbol
262 self.get_crate_data(cnum).name
265 fn original_crate_name(&self, cnum: CrateNum) -> Symbol
267 self.get_crate_data(cnum).name()
270 fn crate_hash(&self, cnum: CrateNum) -> Svh
272 self.get_crate_hash(cnum)
275 fn crate_disambiguator(&self, cnum: CrateNum) -> Symbol
277 self.get_crate_data(cnum).disambiguator()
280 fn plugin_registrar_fn(&self, cnum: CrateNum) -> Option<DefId>
282 self.get_crate_data(cnum).root.plugin_registrar_fn.map(|index| DefId {
288 fn derive_registrar_fn(&self, cnum: CrateNum) -> Option<DefId>
290 self.get_crate_data(cnum).root.macro_derive_registrar.map(|index| DefId {
296 fn native_libraries(&self, cnum: CrateNum) -> Vec<NativeLibrary>
298 self.get_crate_data(cnum).get_native_libraries(&self.dep_graph)
301 fn exported_symbols(&self, cnum: CrateNum) -> Vec<DefId>
303 self.get_crate_data(cnum).get_exported_symbols(&self.dep_graph)
306 fn is_no_builtins(&self, cnum: CrateNum) -> bool {
307 self.get_crate_data(cnum).is_no_builtins(&self.dep_graph)
310 fn retrace_path(&self,
312 path: &[DisambiguatedDefPathData])
314 let cdata = self.get_crate_data(cnum);
317 .map(|index| DefId { krate: cnum, index: index })
320 /// Returns the `DefKey` for a given `DefId`. This indicates the
321 /// parent `DefId` as well as some idea of what kind of data the
322 /// `DefId` refers to.
323 fn def_key(&self, def: DefId) -> DefKey {
324 // Note: loading the def-key (or def-path) for a def-id is not
325 // a *read* of its metadata. This is because the def-id is
326 // really just an interned shorthand for a def-path, which is the
327 // canonical name for an item.
329 // self.dep_graph.read(DepNode::MetaData(def));
330 self.get_crate_data(def.krate).def_key(def.index)
333 fn def_path(&self, def: DefId) -> DefPath {
334 // See `Note` above in `def_key()` for why this read is
337 // self.dep_graph.read(DepNode::MetaData(def));
338 self.get_crate_data(def.krate).def_path(def.index)
341 fn def_path_hash(&self, def: DefId) -> DefPathHash {
342 self.get_crate_data(def.krate).def_path_hash(def.index)
345 fn def_path_table(&self, cnum: CrateNum) -> Rc<DefPathTable> {
346 self.get_crate_data(cnum).def_path_table.clone()
349 fn struct_field_names(&self, def: DefId) -> Vec<ast::Name>
351 self.read_dep_node(def);
352 self.get_crate_data(def.krate).get_struct_field_names(def.index)
355 fn item_children(&self, def_id: DefId, sess: &Session) -> Vec<def::Export>
357 self.read_dep_node(def_id);
358 let mut result = vec![];
359 self.get_crate_data(def_id.krate)
360 .each_child_of_item(def_id.index, |child| result.push(child), sess);
364 fn load_macro(&self, id: DefId, sess: &Session) -> LoadedMacro {
365 let data = self.get_crate_data(id.krate);
366 if let Some(ref proc_macros) = data.proc_macros {
367 return LoadedMacro::ProcMacro(proc_macros[id.index.as_usize() - 1].1.clone());
370 let (name, def) = data.get_macro(id.index);
371 let source_name = format!("<{} macros>", name);
373 let filemap = sess.parse_sess.codemap().new_filemap(source_name, def.body);
374 let local_span = Span { lo: filemap.start_pos, hi: filemap.end_pos, ctxt: NO_EXPANSION };
375 let body = filemap_to_stream(&sess.parse_sess, filemap);
377 // Mark the attrs as used
378 let attrs = data.get_item_attrs(id.index, &self.dep_graph);
379 for attr in attrs.iter() {
380 attr::mark_used(attr);
383 let name = data.def_key(id.index).disambiguated_data.data
384 .get_opt_name().expect("no name in load_macro");
385 sess.imported_macro_spans.borrow_mut()
386 .insert(local_span, (name.to_string(), data.get_span(id.index, sess)));
388 LoadedMacro::MacroDef(ast::Item {
389 ident: ast::Ident::with_empty_ctxt(name),
390 id: ast::DUMMY_NODE_ID,
392 attrs: attrs.iter().cloned().collect(),
393 node: ast::ItemKind::MacroDef(ast::MacroDef {
397 vis: ast::Visibility::Inherited,
401 fn item_body<'a, 'tcx>(&self,
402 tcx: TyCtxt<'a, 'tcx, 'tcx>,
405 self.read_dep_node(def_id);
407 if let Some(cached) = tcx.hir.get_inlined_body_untracked(def_id) {
411 debug!("item_body({:?}): inlining item", def_id);
413 self.get_crate_data(def_id.krate).item_body(tcx, def_id.index)
416 fn crates(&self) -> Vec<CrateNum>
418 let mut result = vec![];
419 self.iter_crate_data(|cnum, _| result.push(cnum));
423 fn used_libraries(&self) -> Vec<NativeLibrary>
425 self.get_used_libraries().borrow().clone()
428 fn used_link_args(&self) -> Vec<String>
430 self.get_used_link_args().borrow().clone()
432 fn used_crates(&self, prefer: LinkagePreference) -> Vec<(CrateNum, LibSource)>
434 self.do_get_used_crates(prefer)
437 fn used_crate_source(&self, cnum: CrateNum) -> CrateSource
439 self.get_crate_data(cnum).source.clone()
442 fn extern_mod_stmt_cnum(&self, emod_id: ast::NodeId) -> Option<CrateNum>
444 self.do_extern_mod_stmt_cnum(emod_id)
447 fn encode_metadata<'a, 'tcx>(&self,
448 tcx: TyCtxt<'a, 'tcx, 'tcx>,
449 link_meta: &LinkMeta,
453 encoder::encode_metadata(tcx, link_meta, reachable)
456 fn metadata_encoding_version(&self) -> &[u8]
458 schema::METADATA_HEADER
461 /// Returns a map from a sufficiently visible external item (i.e. an external item that is
462 /// visible from at least one local module) to a sufficiently visible parent (considering
463 /// modules that re-export the external item to be parents).
464 fn visible_parent_map<'a>(&'a self, sess: &Session) -> ::std::cell::Ref<'a, DefIdMap<DefId>> {
466 let visible_parent_map = self.visible_parent_map.borrow();
467 if !visible_parent_map.is_empty() {
468 return visible_parent_map;
472 use std::collections::vec_deque::VecDeque;
473 use std::collections::hash_map::Entry;
475 let mut visible_parent_map = self.visible_parent_map.borrow_mut();
477 for cnum in (1 .. self.next_crate_num().as_usize()).map(CrateNum::new) {
478 let cdata = self.get_crate_data(cnum);
480 match cdata.extern_crate.get() {
481 // Ignore crates without a corresponding local `extern crate` item.
482 Some(extern_crate) if !extern_crate.direct => continue,
486 let mut bfs_queue = &mut VecDeque::new();
487 let mut add_child = |bfs_queue: &mut VecDeque<_>, child: def::Export, parent: DefId| {
488 let child = child.def.def_id();
490 if self.visibility(child) != ty::Visibility::Public {
494 match visible_parent_map.entry(child) {
495 Entry::Occupied(mut entry) => {
496 // If `child` is defined in crate `cnum`, ensure
497 // that it is mapped to a parent in `cnum`.
498 if child.krate == cnum && entry.get().krate != cnum {
499 entry.insert(parent);
502 Entry::Vacant(entry) => {
503 entry.insert(parent);
504 bfs_queue.push_back(child);
509 bfs_queue.push_back(DefId {
511 index: CRATE_DEF_INDEX
513 while let Some(def) = bfs_queue.pop_front() {
514 for child in self.item_children(def, sess) {
515 add_child(bfs_queue, child, def);
520 drop(visible_parent_map);
521 self.visible_parent_map.borrow()