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::ty::maps::QueryConfig;
16 use rustc::middle::cstore::{CrateStore, CrateSource, LibSource, DepKind,
17 NativeLibrary, MetadataLoader, LinkMeta,
18 LinkagePreference, LoadedMacro, EncodedMetadata,
19 EncodedMetadataHashes};
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};
26 use rustc::hir::map::{DefKey, DefPath, DefPathHash};
27 use rustc::hir::map::blocks::FnLikeNode;
28 use rustc::hir::map::definitions::{DefPathTable, GlobalMetaDataKind};
29 use rustc::util::nodemap::{NodeSet, DefIdMap};
36 use syntax::ext::base::SyntaxExtension;
37 use syntax::parse::filemap_to_stream;
38 use syntax::symbol::Symbol;
39 use syntax_pos::{Span, NO_EXPANSION};
40 use rustc_data_structures::indexed_set::IdxSetBuf;
41 use rustc::hir::svh::Svh;
44 macro_rules! provide {
45 (<$lt:tt> $tcx:ident, $def_id:ident, $cdata:ident, $($name:ident => $compute:block)*) => {
46 pub fn provide<$lt>(providers: &mut Providers<$lt>) {
47 $(fn $name<'a, $lt:$lt, T>($tcx: TyCtxt<'a, $lt, $lt>, def_id_arg: T)
48 -> <ty::queries::$name<$lt> as
52 let $def_id = def_id_arg.into_def_id();
53 assert!(!$def_id.is_local());
55 let def_path_hash = $tcx.def_path_hash($def_id);
56 let dep_node = def_path_hash.to_dep_node(::rustc::dep_graph::DepKind::MetaData);
58 $tcx.dep_graph.read(dep_node);
60 let $cdata = $tcx.sess.cstore.crate_data_as_rc_any($def_id.krate);
61 let $cdata = $cdata.downcast_ref::<cstore::CrateMetadata>()
62 .expect("CrateStore crated ata is not a CrateMetadata");
66 *providers = Providers {
75 fn into_def_id(self) -> DefId;
78 impl IntoDefId for DefId {
79 fn into_def_id(self) -> DefId { self }
82 impl IntoDefId for CrateNum {
83 fn into_def_id(self) -> DefId { self.as_def_id() }
86 provide! { <'tcx> tcx, def_id, cdata,
87 type_of => { cdata.get_type(def_id.index, tcx) }
88 generics_of => { tcx.alloc_generics(cdata.get_generics(def_id.index)) }
89 predicates_of => { cdata.get_predicates(def_id.index, tcx) }
90 super_predicates_of => { cdata.get_super_predicates(def_id.index, tcx) }
92 tcx.alloc_trait_def(cdata.get_trait_def(def_id.index))
94 adt_def => { cdata.get_adt_def(def_id.index, tcx) }
97 tcx.calculate_dtor(def_id, &mut |_,_| Ok(()))
99 variances_of => { Rc::new(cdata.get_item_variances(def_id.index)) }
100 associated_item_def_ids => {
101 let mut result = vec![];
102 cdata.each_child_of_item(def_id.index,
103 |child| result.push(child.def.def_id()), tcx.sess);
106 associated_item => { cdata.get_associated_item(def_id.index) }
107 impl_trait_ref => { cdata.get_impl_trait(def_id.index, tcx) }
108 impl_polarity => { cdata.get_impl_polarity(def_id.index) }
109 coerce_unsized_info => {
110 cdata.get_coerce_unsized_info(def_id.index).unwrap_or_else(|| {
111 bug!("coerce_unsized_info: `{:?}` is missing its info", def_id);
115 let mir = cdata.maybe_get_optimized_mir(tcx, def_id.index).unwrap_or_else(|| {
116 bug!("get_optimized_mir: missing MIR for `{:?}`", def_id)
119 let mir = tcx.alloc_mir(mir);
123 generator_sig => { cdata.generator_sig(def_id.index, tcx) }
124 mir_const_qualif => {
125 (cdata.mir_const_qualif(def_id.index), Rc::new(IdxSetBuf::new_empty(0)))
127 typeck_tables_of => { cdata.item_body_tables(def_id.index, tcx) }
128 closure_kind => { cdata.closure_kind(def_id.index) }
129 fn_sig => { cdata.fn_sig(def_id.index, tcx) }
130 inherent_impls => { Rc::new(cdata.get_inherent_implementations_for_type(def_id.index)) }
131 is_const_fn => { cdata.is_const_fn(def_id.index) }
132 is_foreign_item => { cdata.is_foreign_item(def_id.index) }
133 is_default_impl => { cdata.is_default_impl(def_id.index) }
134 describe_def => { cdata.get_def(def_id.index) }
135 def_span => { cdata.get_span(def_id.index, &tcx.sess) }
136 stability => { cdata.get_stability(def_id.index) }
137 deprecation => { cdata.get_deprecation(def_id.index) }
138 item_attrs => { cdata.get_item_attrs(def_id.index, &tcx.dep_graph) }
139 // FIXME(#38501) We've skipped a `read` on the `HirBody` of
140 // a `fn` when encoding, so the dep-tracking wouldn't work.
141 // This is only used by rustdoc anyway, which shouldn't have
142 // incremental recompilation ever enabled.
143 fn_arg_names => { cdata.get_fn_arg_names(def_id.index) }
144 impl_parent => { cdata.get_parent_impl(def_id.index) }
145 trait_of_item => { cdata.get_trait_of_item(def_id.index) }
146 is_exported_symbol => {
147 let dep_node = cdata.metadata_dep_node(GlobalMetaDataKind::ExportedSymbols);
148 cdata.exported_symbols.get(&tcx.dep_graph, dep_node).contains(&def_id.index)
150 item_body_nested_bodies => { Rc::new(cdata.item_body_nested_bodies(def_id.index)) }
151 const_is_rvalue_promotable_to_static => {
152 cdata.const_is_rvalue_promotable_to_static(def_id.index)
154 is_mir_available => { cdata.is_item_mir_available(def_id.index) }
156 dylib_dependency_formats => { Rc::new(cdata.get_dylib_dependency_formats(&tcx.dep_graph)) }
157 is_panic_runtime => { cdata.is_panic_runtime(&tcx.dep_graph) }
158 is_compiler_builtins => { cdata.is_compiler_builtins(&tcx.dep_graph) }
159 has_global_allocator => { cdata.has_global_allocator(&tcx.dep_graph) }
160 is_sanitizer_runtime => { cdata.is_sanitizer_runtime(&tcx.dep_graph) }
161 is_profiler_runtime => { cdata.is_profiler_runtime(&tcx.dep_graph) }
162 panic_strategy => { cdata.panic_strategy(&tcx.dep_graph) }
163 extern_crate => { Rc::new(cdata.extern_crate.get()) }
164 is_no_builtins => { cdata.is_no_builtins(&tcx.dep_graph) }
165 impl_defaultness => { cdata.get_impl_defaultness(def_id.index) }
166 exported_symbols => { Rc::new(cdata.get_exported_symbols(&tcx.dep_graph)) }
167 native_libraries => { Rc::new(cdata.get_native_libraries(&tcx.dep_graph)) }
168 plugin_registrar_fn => {
169 cdata.root.plugin_registrar_fn.map(|index| {
170 DefId { krate: def_id.krate, index }
173 derive_registrar_fn => {
174 cdata.root.macro_derive_registrar.map(|index| {
175 DefId { krate: def_id.krate, index }
180 pub fn provide_local<'tcx>(providers: &mut Providers<'tcx>) {
181 fn is_const_fn<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> bool {
182 let node_id = tcx.hir.as_local_node_id(def_id)
183 .expect("Non-local call to local provider is_const_fn");
185 if let Some(fn_like) = FnLikeNode::from_node(tcx.hir.get(node_id)) {
186 fn_like.constness() == hir::Constness::Const
192 *providers = Providers {
198 impl CrateStore for cstore::CStore {
199 fn crate_data_as_rc_any(&self, krate: CrateNum) -> Rc<Any> {
200 self.get_crate_data(krate)
203 fn metadata_loader(&self) -> &MetadataLoader {
204 &*self.metadata_loader
207 fn visibility(&self, def: DefId) -> ty::Visibility {
208 self.read_dep_node(def);
209 self.get_crate_data(def.krate).get_visibility(def.index)
212 fn item_generics_cloned(&self, def: DefId) -> ty::Generics {
213 self.read_dep_node(def);
214 self.get_crate_data(def.krate).get_generics(def.index)
217 fn implementations_of_trait(&self, filter: Option<DefId>) -> Vec<DefId>
219 let mut result = vec![];
221 self.iter_crate_data(|_, cdata| {
222 cdata.get_implementations_for_trait(filter, &self.dep_graph, &mut result)
227 fn associated_item_cloned(&self, def: DefId) -> ty::AssociatedItem
229 self.read_dep_node(def);
230 self.get_crate_data(def.krate).get_associated_item(def.index)
233 fn is_statically_included_foreign_item(&self, def_id: DefId) -> bool
235 self.do_is_statically_included_foreign_item(def_id)
238 fn is_dllimport_foreign_item(&self, def_id: DefId) -> bool {
239 if def_id.krate == LOCAL_CRATE {
240 self.dllimport_foreign_items.borrow().contains(&def_id.index)
242 self.get_crate_data(def_id.krate)
243 .is_dllimport_foreign_item(def_id.index, &self.dep_graph)
247 fn dep_kind(&self, cnum: CrateNum) -> DepKind
249 let data = self.get_crate_data(cnum);
250 let dep_node = data.metadata_dep_node(GlobalMetaDataKind::CrateDeps);
251 self.dep_graph.read(dep_node);
255 fn export_macros(&self, cnum: CrateNum) {
256 let data = self.get_crate_data(cnum);
257 let dep_node = data.metadata_dep_node(GlobalMetaDataKind::CrateDeps);
259 self.dep_graph.read(dep_node);
260 if data.dep_kind.get() == DepKind::UnexportedMacrosOnly {
261 data.dep_kind.set(DepKind::MacrosOnly)
265 fn lang_items(&self, cnum: CrateNum) -> Vec<(DefIndex, usize)>
267 self.get_crate_data(cnum).get_lang_items(&self.dep_graph)
270 fn missing_lang_items(&self, cnum: CrateNum)
271 -> Vec<lang_items::LangItem>
273 self.get_crate_data(cnum).get_missing_lang_items(&self.dep_graph)
276 fn crate_name(&self, cnum: CrateNum) -> Symbol
278 self.get_crate_data(cnum).name
281 fn original_crate_name(&self, cnum: CrateNum) -> Symbol
283 self.get_crate_data(cnum).name()
286 fn crate_hash(&self, cnum: CrateNum) -> Svh
288 self.get_crate_hash(cnum)
291 fn crate_disambiguator(&self, cnum: CrateNum) -> Symbol
293 self.get_crate_data(cnum).disambiguator()
296 /// Returns the `DefKey` for a given `DefId`. This indicates the
297 /// parent `DefId` as well as some idea of what kind of data the
298 /// `DefId` refers to.
299 fn def_key(&self, def: DefId) -> DefKey {
300 // Note: loading the def-key (or def-path) for a def-id is not
301 // a *read* of its metadata. This is because the def-id is
302 // really just an interned shorthand for a def-path, which is the
303 // canonical name for an item.
305 // self.dep_graph.read(DepNode::MetaData(def));
306 self.get_crate_data(def.krate).def_key(def.index)
309 fn def_path(&self, def: DefId) -> DefPath {
310 // See `Note` above in `def_key()` for why this read is
313 // self.dep_graph.read(DepNode::MetaData(def));
314 self.get_crate_data(def.krate).def_path(def.index)
317 fn def_path_hash(&self, def: DefId) -> DefPathHash {
318 self.get_crate_data(def.krate).def_path_hash(def.index)
321 fn def_path_table(&self, cnum: CrateNum) -> Rc<DefPathTable> {
322 self.get_crate_data(cnum).def_path_table.clone()
325 fn struct_field_names(&self, def: DefId) -> Vec<ast::Name>
327 self.read_dep_node(def);
328 self.get_crate_data(def.krate).get_struct_field_names(def.index)
331 fn item_children(&self, def_id: DefId, sess: &Session) -> Vec<def::Export>
333 self.read_dep_node(def_id);
334 let mut result = vec![];
335 self.get_crate_data(def_id.krate)
336 .each_child_of_item(def_id.index, |child| result.push(child), sess);
340 fn load_macro(&self, id: DefId, sess: &Session) -> LoadedMacro {
341 let data = self.get_crate_data(id.krate);
342 if let Some(ref proc_macros) = data.proc_macros {
343 return LoadedMacro::ProcMacro(proc_macros[id.index.as_usize() - 1].1.clone());
344 } else if data.name == "proc_macro" &&
345 self.get_crate_data(id.krate).item_name(id.index) == "quote" {
346 let ext = SyntaxExtension::ProcMacro(Box::new(::proc_macro::__internal::Quoter));
347 return LoadedMacro::ProcMacro(Rc::new(ext));
350 let (name, def) = data.get_macro(id.index);
351 let source_name = format!("<{} macros>", name);
353 let filemap = sess.parse_sess.codemap().new_filemap(source_name, def.body);
354 let local_span = Span::new(filemap.start_pos, filemap.end_pos, NO_EXPANSION);
355 let body = filemap_to_stream(&sess.parse_sess, filemap, None);
357 // Mark the attrs as used
358 let attrs = data.get_item_attrs(id.index, &self.dep_graph);
359 for attr in attrs.iter() {
360 attr::mark_used(attr);
363 let name = data.def_key(id.index).disambiguated_data.data
364 .get_opt_name().expect("no name in load_macro");
365 sess.imported_macro_spans.borrow_mut()
366 .insert(local_span, (name.to_string(), data.get_span(id.index, sess)));
368 LoadedMacro::MacroDef(ast::Item {
369 ident: ast::Ident::with_empty_ctxt(name),
370 id: ast::DUMMY_NODE_ID,
372 attrs: attrs.iter().cloned().collect(),
373 node: ast::ItemKind::MacroDef(ast::MacroDef {
377 vis: ast::Visibility::Inherited,
382 fn item_body<'a, 'tcx>(&self,
383 tcx: TyCtxt<'a, 'tcx, 'tcx>,
386 self.read_dep_node(def_id);
388 if let Some(cached) = tcx.hir.get_inlined_body_untracked(def_id) {
392 debug!("item_body({:?}): inlining item", def_id);
394 self.get_crate_data(def_id.krate).item_body(tcx, def_id.index)
397 fn crates(&self) -> Vec<CrateNum>
399 let mut result = vec![];
400 self.iter_crate_data(|cnum, _| result.push(cnum));
404 fn used_libraries(&self) -> Vec<NativeLibrary>
406 self.get_used_libraries().borrow().clone()
409 fn used_link_args(&self) -> Vec<String>
411 self.get_used_link_args().borrow().clone()
413 fn used_crates(&self, prefer: LinkagePreference) -> Vec<(CrateNum, LibSource)>
415 self.do_get_used_crates(prefer)
418 fn used_crate_source(&self, cnum: CrateNum) -> CrateSource
420 self.get_crate_data(cnum).source.clone()
423 fn extern_mod_stmt_cnum(&self, emod_id: ast::NodeId) -> Option<CrateNum>
425 self.do_extern_mod_stmt_cnum(emod_id)
428 fn encode_metadata<'a, 'tcx>(&self,
429 tcx: TyCtxt<'a, 'tcx, 'tcx>,
430 link_meta: &LinkMeta,
432 -> (EncodedMetadata, EncodedMetadataHashes)
434 encoder::encode_metadata(tcx, link_meta, reachable)
437 fn metadata_encoding_version(&self) -> &[u8]
439 schema::METADATA_HEADER
442 /// Returns a map from a sufficiently visible external item (i.e. an external item that is
443 /// visible from at least one local module) to a sufficiently visible parent (considering
444 /// modules that re-export the external item to be parents).
445 fn visible_parent_map<'a>(&'a self, sess: &Session) -> ::std::cell::Ref<'a, DefIdMap<DefId>> {
447 let visible_parent_map = self.visible_parent_map.borrow();
448 if !visible_parent_map.is_empty() {
449 return visible_parent_map;
453 use std::collections::vec_deque::VecDeque;
454 use std::collections::hash_map::Entry;
456 let mut visible_parent_map = self.visible_parent_map.borrow_mut();
458 for cnum in (1 .. self.next_crate_num().as_usize()).map(CrateNum::new) {
459 let cdata = self.get_crate_data(cnum);
461 match cdata.extern_crate.get() {
462 // Ignore crates without a corresponding local `extern crate` item.
463 Some(extern_crate) if !extern_crate.direct => continue,
467 let bfs_queue = &mut VecDeque::new();
468 let mut add_child = |bfs_queue: &mut VecDeque<_>, child: def::Export, parent: DefId| {
469 let child = child.def.def_id();
471 if self.visibility(child) != ty::Visibility::Public {
475 match visible_parent_map.entry(child) {
476 Entry::Occupied(mut entry) => {
477 // If `child` is defined in crate `cnum`, ensure
478 // that it is mapped to a parent in `cnum`.
479 if child.krate == cnum && entry.get().krate != cnum {
480 entry.insert(parent);
483 Entry::Vacant(entry) => {
484 entry.insert(parent);
485 bfs_queue.push_back(child);
490 bfs_queue.push_back(DefId {
492 index: CRATE_DEF_INDEX
494 while let Some(def) = bfs_queue.pop_front() {
495 for child in self.item_children(def, sess) {
496 add_child(bfs_queue, child, def);
501 drop(visible_parent_map);
502 self.visible_parent_map.borrow()