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.
16 use rustc::dep_graph::DepTrackingMapConfig;
17 use rustc::middle::cstore::{CrateStore, CrateSource, LibSource, DepKind,
18 ExternCrate, NativeLibrary, LinkMeta,
19 LinkagePreference, LoadedMacro, EncodedMetadata};
21 use rustc::middle::lang_items;
22 use rustc::session::Session;
23 use rustc::ty::{self, TyCtxt};
24 use rustc::ty::maps::Providers;
25 use rustc::hir::def_id::{CrateNum, DefId, DefIndex, CRATE_DEF_INDEX, LOCAL_CRATE};
27 use rustc::dep_graph::DepNode;
28 use rustc::hir::map::{DefKey, DefPath, DisambiguatedDefPathData};
29 use rustc::util::nodemap::{NodeSet, DefIdMap};
30 use rustc_back::PanicStrategy;
38 use syntax::parse::filemap_to_stream;
39 use syntax::symbol::Symbol;
40 use syntax_pos::{Span, NO_EXPANSION};
41 use rustc::hir::svh::Svh;
42 use rustc_back::target::Target;
45 use std::collections::BTreeMap;
47 macro_rules! provide {
48 (<$lt:tt> $tcx:ident, $def_id:ident, $cdata:ident $($name:ident => $compute:block)*) => {
49 pub fn provide<$lt>(providers: &mut Providers<$lt>) {
50 $(fn $name<'a, $lt:$lt>($tcx: TyCtxt<'a, $lt, $lt>, $def_id: DefId)
51 -> <ty::queries::$name<$lt> as
52 DepTrackingMapConfig>::Value {
53 assert!(!$def_id.is_local());
55 $tcx.dep_graph.read(DepNode::MetaData($def_id));
57 let $cdata = $tcx.sess.cstore.crate_data_as_rc_any($def_id.krate);
58 let $cdata = $cdata.downcast_ref::<cstore::CrateMetadata>()
59 .expect("CrateStore crated ata is not a CrateMetadata");
63 *providers = Providers {
71 provide! { <'tcx> tcx, def_id, cdata
72 type_of => { cdata.get_type(def_id.index, tcx) }
73 generics_of => { tcx.alloc_generics(cdata.get_generics(def_id.index)) }
74 predicates_of => { cdata.get_predicates(def_id.index, tcx) }
75 super_predicates_of => { cdata.get_super_predicates(def_id.index, tcx) }
77 tcx.alloc_trait_def(cdata.get_trait_def(def_id.index))
79 adt_def => { cdata.get_adt_def(def_id.index, tcx) }
82 tcx.calculate_dtor(def_id, &mut |_,_| Ok(()))
84 variances_of => { Rc::new(cdata.get_item_variances(def_id.index)) }
85 associated_item_def_ids => {
86 let mut result = vec![];
87 cdata.each_child_of_item(def_id.index, |child| result.push(child.def.def_id()));
90 associated_item => { cdata.get_associated_item(def_id.index) }
91 impl_trait_ref => { cdata.get_impl_trait(def_id.index, tcx) }
92 impl_polarity => { cdata.get_impl_polarity(def_id.index) }
93 coerce_unsized_info => {
94 cdata.get_coerce_unsized_info(def_id.index).unwrap_or_else(|| {
95 bug!("coerce_unsized_info: `{:?}` is missing its info", def_id);
99 let mir = cdata.maybe_get_item_mir(tcx, def_id.index).unwrap_or_else(|| {
100 bug!("get_item_mir: missing MIR for `{:?}`", def_id)
103 let mir = tcx.alloc_mir(mir);
105 // Perma-borrow MIR from extern crates to prevent mutation.
106 mem::forget(mir.borrow());
110 mir_const_qualif => { cdata.mir_const_qualif(def_id.index) }
111 typeck_tables_of => { cdata.item_body_tables(def_id.index, tcx) }
112 closure_kind => { cdata.closure_kind(def_id.index) }
113 closure_type => { cdata.closure_ty(def_id.index, tcx) }
114 inherent_impls => { Rc::new(cdata.get_inherent_implementations_for_type(def_id.index)) }
115 is_foreign_item => { cdata.is_foreign_item(def_id.index) }
116 describe_def => { cdata.get_def(def_id.index) }
117 def_span => { cdata.get_span(def_id.index, &tcx.sess) }
120 impl CrateStore for cstore::CStore {
121 fn crate_data_as_rc_any(&self, krate: CrateNum) -> Rc<Any> {
122 self.get_crate_data(krate)
125 fn stability(&self, def: DefId) -> Option<attr::Stability> {
126 self.dep_graph.read(DepNode::MetaData(def));
127 self.get_crate_data(def.krate).get_stability(def.index)
130 fn deprecation(&self, def: DefId) -> Option<attr::Deprecation> {
131 self.dep_graph.read(DepNode::MetaData(def));
132 self.get_crate_data(def.krate).get_deprecation(def.index)
135 fn visibility(&self, def: DefId) -> ty::Visibility {
136 self.dep_graph.read(DepNode::MetaData(def));
137 self.get_crate_data(def.krate).get_visibility(def.index)
140 fn item_generics_cloned(&self, def: DefId) -> ty::Generics {
141 self.dep_graph.read(DepNode::MetaData(def));
142 self.get_crate_data(def.krate).get_generics(def.index)
145 fn item_attrs(&self, def_id: DefId) -> Rc<[ast::Attribute]>
147 self.dep_graph.read(DepNode::MetaData(def_id));
148 self.get_crate_data(def_id.krate).get_item_attrs(def_id.index)
151 fn fn_arg_names(&self, did: DefId) -> Vec<ast::Name>
153 // FIXME(#38501) We've skipped a `read` on the `HirBody` of
154 // a `fn` when encoding, so the dep-tracking wouldn't work.
155 // This is only used by rustdoc anyway, which shouldn't have
156 // incremental recompilation ever enabled.
157 assert!(!self.dep_graph.is_fully_enabled());
158 self.get_crate_data(did.krate).get_fn_arg_names(did.index)
161 fn implementations_of_trait(&self, filter: Option<DefId>) -> Vec<DefId>
163 if let Some(def_id) = filter {
164 self.dep_graph.read(DepNode::MetaData(def_id));
166 let mut result = vec![];
167 self.iter_crate_data(|_, cdata| {
168 cdata.get_implementations_for_trait(filter, &mut result)
173 fn impl_defaultness(&self, def: DefId) -> hir::Defaultness
175 self.dep_graph.read(DepNode::MetaData(def));
176 self.get_crate_data(def.krate).get_impl_defaultness(def.index)
179 fn impl_parent(&self, impl_def: DefId) -> Option<DefId> {
180 self.dep_graph.read(DepNode::MetaData(impl_def));
181 self.get_crate_data(impl_def.krate).get_parent_impl(impl_def.index)
184 fn trait_of_item(&self, def_id: DefId) -> Option<DefId> {
185 self.dep_graph.read(DepNode::MetaData(def_id));
186 self.get_crate_data(def_id.krate).get_trait_of_item(def_id.index)
189 fn associated_item_cloned(&self, def: DefId) -> ty::AssociatedItem
191 self.dep_graph.read(DepNode::MetaData(def));
192 self.get_crate_data(def.krate).get_associated_item(def.index)
195 fn is_const_fn(&self, did: DefId) -> bool
197 self.dep_graph.read(DepNode::MetaData(did));
198 self.get_crate_data(did.krate).is_const_fn(did.index)
201 fn is_default_impl(&self, impl_did: DefId) -> bool {
202 self.dep_graph.read(DepNode::MetaData(impl_did));
203 self.get_crate_data(impl_did.krate).is_default_impl(impl_did.index)
206 fn is_foreign_item(&self, did: DefId) -> bool {
207 self.get_crate_data(did.krate).is_foreign_item(did.index)
210 fn is_statically_included_foreign_item(&self, def_id: DefId) -> bool
212 self.do_is_statically_included_foreign_item(def_id)
215 fn is_exported_symbol(&self, def_id: DefId) -> bool {
216 self.get_crate_data(def_id.krate).exported_symbols.contains(&def_id.index)
219 fn is_dllimport_foreign_item(&self, def_id: DefId) -> bool {
220 if def_id.krate == LOCAL_CRATE {
221 self.dllimport_foreign_items.borrow().contains(&def_id.index)
223 self.get_crate_data(def_id.krate).is_dllimport_foreign_item(def_id.index)
227 fn dylib_dependency_formats(&self, cnum: CrateNum)
228 -> Vec<(CrateNum, LinkagePreference)>
230 self.get_crate_data(cnum).get_dylib_dependency_formats()
233 fn dep_kind(&self, cnum: CrateNum) -> DepKind
235 self.get_crate_data(cnum).dep_kind.get()
238 fn export_macros(&self, cnum: CrateNum) {
239 if self.get_crate_data(cnum).dep_kind.get() == DepKind::UnexportedMacrosOnly {
240 self.get_crate_data(cnum).dep_kind.set(DepKind::MacrosOnly)
244 fn lang_items(&self, cnum: CrateNum) -> Vec<(DefIndex, usize)>
246 self.get_crate_data(cnum).get_lang_items()
249 fn missing_lang_items(&self, cnum: CrateNum)
250 -> Vec<lang_items::LangItem>
252 self.get_crate_data(cnum).get_missing_lang_items()
255 fn is_staged_api(&self, cnum: CrateNum) -> bool
257 self.get_crate_data(cnum).is_staged_api()
260 fn is_allocator(&self, cnum: CrateNum) -> bool
262 self.get_crate_data(cnum).is_allocator()
265 fn is_panic_runtime(&self, cnum: CrateNum) -> bool
267 self.get_crate_data(cnum).is_panic_runtime()
270 fn is_compiler_builtins(&self, cnum: CrateNum) -> bool {
271 self.get_crate_data(cnum).is_compiler_builtins()
274 fn is_sanitizer_runtime(&self, cnum: CrateNum) -> bool {
275 self.get_crate_data(cnum).is_sanitizer_runtime()
278 fn panic_strategy(&self, cnum: CrateNum) -> PanicStrategy {
279 self.get_crate_data(cnum).panic_strategy()
282 fn crate_name(&self, cnum: CrateNum) -> Symbol
284 self.get_crate_data(cnum).name
287 fn original_crate_name(&self, cnum: CrateNum) -> Symbol
289 self.get_crate_data(cnum).name()
292 fn extern_crate(&self, cnum: CrateNum) -> Option<ExternCrate>
294 self.get_crate_data(cnum).extern_crate.get()
297 fn crate_hash(&self, cnum: CrateNum) -> Svh
299 self.get_crate_hash(cnum)
302 fn crate_disambiguator(&self, cnum: CrateNum) -> Symbol
304 self.get_crate_data(cnum).disambiguator()
307 fn plugin_registrar_fn(&self, cnum: CrateNum) -> Option<DefId>
309 self.get_crate_data(cnum).root.plugin_registrar_fn.map(|index| DefId {
315 fn derive_registrar_fn(&self, cnum: CrateNum) -> Option<DefId>
317 self.get_crate_data(cnum).root.macro_derive_registrar.map(|index| DefId {
323 fn native_libraries(&self, cnum: CrateNum) -> Vec<NativeLibrary>
325 self.get_crate_data(cnum).get_native_libraries()
328 fn exported_symbols(&self, cnum: CrateNum) -> Vec<DefId>
330 self.get_crate_data(cnum).get_exported_symbols()
333 fn is_no_builtins(&self, cnum: CrateNum) -> bool {
334 self.get_crate_data(cnum).is_no_builtins()
337 fn retrace_path(&self,
339 path: &[DisambiguatedDefPathData])
341 let cdata = self.get_crate_data(cnum);
344 .map(|index| DefId { krate: cnum, index: index })
347 /// Returns the `DefKey` for a given `DefId`. This indicates the
348 /// parent `DefId` as well as some idea of what kind of data the
349 /// `DefId` refers to.
350 fn def_key(&self, def: DefId) -> DefKey {
351 // Note: loading the def-key (or def-path) for a def-id is not
352 // a *read* of its metadata. This is because the def-id is
353 // really just an interned shorthand for a def-path, which is the
354 // canonical name for an item.
356 // self.dep_graph.read(DepNode::MetaData(def));
357 self.get_crate_data(def.krate).def_key(def.index)
360 fn def_path(&self, def: DefId) -> DefPath {
361 // See `Note` above in `def_key()` for why this read is
364 // self.dep_graph.read(DepNode::MetaData(def));
365 self.get_crate_data(def.krate).def_path(def.index)
368 fn def_path_hash(&self, def: DefId) -> u64 {
369 self.get_crate_data(def.krate).def_path_hash(def.index)
372 fn struct_field_names(&self, def: DefId) -> Vec<ast::Name>
374 self.dep_graph.read(DepNode::MetaData(def));
375 self.get_crate_data(def.krate).get_struct_field_names(def.index)
378 fn item_children(&self, def_id: DefId) -> Vec<def::Export>
380 self.dep_graph.read(DepNode::MetaData(def_id));
381 let mut result = vec![];
382 self.get_crate_data(def_id.krate)
383 .each_child_of_item(def_id.index, |child| result.push(child));
387 fn load_macro(&self, id: DefId, sess: &Session) -> LoadedMacro {
388 let data = self.get_crate_data(id.krate);
389 if let Some(ref proc_macros) = data.proc_macros {
390 return LoadedMacro::ProcMacro(proc_macros[id.index.as_usize() - 1].1.clone());
393 let (name, def) = data.get_macro(id.index);
394 let source_name = format!("<{} macros>", name);
396 let filemap = sess.parse_sess.codemap().new_filemap(source_name, def.body);
397 let local_span = Span { lo: filemap.start_pos, hi: filemap.end_pos, ctxt: NO_EXPANSION };
398 let body = filemap_to_stream(&sess.parse_sess, filemap);
400 // Mark the attrs as used
401 let attrs = data.get_item_attrs(id.index);
402 for attr in attrs.iter() {
403 attr::mark_used(attr);
406 let name = data.def_key(id.index).disambiguated_data.data
407 .get_opt_name().expect("no name in load_macro");
408 sess.imported_macro_spans.borrow_mut()
409 .insert(local_span, (name.to_string(), data.get_span(id.index, sess)));
411 LoadedMacro::MacroDef(ast::Item {
412 ident: ast::Ident::with_empty_ctxt(name),
413 id: ast::DUMMY_NODE_ID,
415 attrs: attrs.iter().cloned().collect(),
416 node: ast::ItemKind::MacroDef(body.into()),
417 vis: ast::Visibility::Inherited,
421 fn item_body<'a, 'tcx>(&self,
422 tcx: TyCtxt<'a, 'tcx, 'tcx>,
425 if let Some(cached) = tcx.hir.get_inlined_body(def_id) {
429 self.dep_graph.read(DepNode::MetaData(def_id));
430 debug!("item_body({}): inlining item", tcx.item_path_str(def_id));
432 self.get_crate_data(def_id.krate).item_body(tcx, def_id.index)
435 fn item_body_nested_bodies(&self, def: DefId) -> BTreeMap<hir::BodyId, hir::Body> {
436 self.dep_graph.read(DepNode::MetaData(def));
437 self.get_crate_data(def.krate).item_body_nested_bodies(def.index)
440 fn const_is_rvalue_promotable_to_static(&self, def: DefId) -> bool {
441 self.dep_graph.read(DepNode::MetaData(def));
442 self.get_crate_data(def.krate).const_is_rvalue_promotable_to_static(def.index)
445 fn is_item_mir_available(&self, def: DefId) -> bool {
446 self.dep_graph.read(DepNode::MetaData(def));
447 self.get_crate_data(def.krate).is_item_mir_available(def.index)
450 fn crates(&self) -> Vec<CrateNum>
452 let mut result = vec![];
453 self.iter_crate_data(|cnum, _| result.push(cnum));
457 fn used_libraries(&self) -> Vec<NativeLibrary>
459 self.get_used_libraries().borrow().clone()
462 fn used_link_args(&self) -> Vec<String>
464 self.get_used_link_args().borrow().clone()
467 fn metadata_filename(&self) -> &str
469 locator::METADATA_FILENAME
472 fn metadata_section_name(&self, target: &Target) -> &str
474 locator::meta_section_name(target)
477 fn used_crates(&self, prefer: LinkagePreference) -> Vec<(CrateNum, LibSource)>
479 self.do_get_used_crates(prefer)
482 fn used_crate_source(&self, cnum: CrateNum) -> CrateSource
484 self.get_crate_data(cnum).source.clone()
487 fn extern_mod_stmt_cnum(&self, emod_id: ast::NodeId) -> Option<CrateNum>
489 self.do_extern_mod_stmt_cnum(emod_id)
492 fn encode_metadata<'a, 'tcx>(&self,
493 tcx: TyCtxt<'a, 'tcx, 'tcx>,
494 link_meta: &LinkMeta,
498 encoder::encode_metadata(tcx, self, link_meta, reachable)
501 fn metadata_encoding_version(&self) -> &[u8]
503 schema::METADATA_HEADER
506 /// Returns a map from a sufficiently visible external item (i.e. an external item that is
507 /// visible from at least one local module) to a sufficiently visible parent (considering
508 /// modules that re-export the external item to be parents).
509 fn visible_parent_map<'a>(&'a self) -> ::std::cell::Ref<'a, DefIdMap<DefId>> {
511 let visible_parent_map = self.visible_parent_map.borrow();
512 if !visible_parent_map.is_empty() {
513 return visible_parent_map;
517 use std::collections::vec_deque::VecDeque;
518 use std::collections::hash_map::Entry;
520 let mut visible_parent_map = self.visible_parent_map.borrow_mut();
522 for cnum in (1 .. self.next_crate_num().as_usize()).map(CrateNum::new) {
523 let cdata = self.get_crate_data(cnum);
525 match cdata.extern_crate.get() {
526 // Ignore crates without a corresponding local `extern crate` item.
527 Some(extern_crate) if !extern_crate.direct => continue,
531 let mut bfs_queue = &mut VecDeque::new();
532 let mut add_child = |bfs_queue: &mut VecDeque<_>, child: def::Export, parent: DefId| {
533 let child = child.def.def_id();
535 if self.visibility(child) != ty::Visibility::Public {
539 match visible_parent_map.entry(child) {
540 Entry::Occupied(mut entry) => {
541 // If `child` is defined in crate `cnum`, ensure
542 // that it is mapped to a parent in `cnum`.
543 if child.krate == cnum && entry.get().krate != cnum {
544 entry.insert(parent);
547 Entry::Vacant(entry) => {
548 entry.insert(parent);
549 bfs_queue.push_back(child);
554 bfs_queue.push_back(DefId {
556 index: CRATE_DEF_INDEX
558 while let Some(def) = bfs_queue.pop_front() {
559 for child in self.item_children(def) {
560 add_child(bfs_queue, child, def);
565 drop(visible_parent_map);
566 self.visible_parent_map.borrow()