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.
17 use rustc::ty::maps::QueryConfig;
18 use rustc::middle::cstore::{CrateStore, DepKind,
19 MetadataLoader, LinkMeta,
20 LoadedMacro, EncodedMetadata,
21 EncodedMetadataHashes, NativeLibraryKind};
23 use rustc::session::Session;
24 use rustc::ty::{self, TyCtxt};
25 use rustc::ty::maps::Providers;
26 use rustc::hir::def_id::{CrateNum, DefId, LOCAL_CRATE, CRATE_DEF_INDEX};
27 use rustc::hir::map::{DefKey, DefPath, DefPathHash};
28 use rustc::hir::map::blocks::FnLikeNode;
29 use rustc::hir::map::definitions::{DefPathTable, GlobalMetaDataKind};
30 use rustc::util::nodemap::{NodeSet, DefIdMap};
37 use syntax::ext::base::SyntaxExtension;
38 use syntax::parse::filemap_to_stream;
39 use syntax::symbol::Symbol;
40 use syntax_pos::{Span, NO_EXPANSION};
41 use rustc_data_structures::indexed_set::IdxSetBuf;
42 use rustc::hir::svh::Svh;
45 macro_rules! provide {
46 (<$lt:tt> $tcx:ident, $def_id:ident, $other:ident, $cdata:ident,
47 $($name:ident => $compute:block)*) => {
48 pub fn provide<$lt>(providers: &mut Providers<$lt>) {
49 $(fn $name<'a, $lt:$lt, T>($tcx: TyCtxt<'a, $lt, $lt>, def_id_arg: T)
50 -> <ty::queries::$name<$lt> as
54 #[allow(unused_variables)]
55 let ($def_id, $other) = def_id_arg.into_args();
56 assert!(!$def_id.is_local());
58 let def_path_hash = $tcx.def_path_hash($def_id);
59 let dep_node = def_path_hash.to_dep_node(::rustc::dep_graph::DepKind::MetaData);
61 $tcx.dep_graph.read(dep_node);
63 let $cdata = $tcx.sess.cstore.crate_data_as_rc_any($def_id.krate);
64 let $cdata = $cdata.downcast_ref::<cstore::CrateMetadata>()
65 .expect("CrateStore crated ata is not a CrateMetadata");
69 *providers = Providers {
77 // small trait to work around different signature queries all being defined via
80 fn into_args(self) -> (DefId, DefId);
83 impl IntoArgs for DefId {
84 fn into_args(self) -> (DefId, DefId) { (self, self) }
87 impl IntoArgs for CrateNum {
88 fn into_args(self) -> (DefId, DefId) { (self.as_def_id(), self.as_def_id()) }
91 impl IntoArgs for (CrateNum, DefId) {
92 fn into_args(self) -> (DefId, DefId) { (self.0.as_def_id(), self.1) }
95 provide! { <'tcx> tcx, def_id, other, cdata,
96 type_of => { cdata.get_type(def_id.index, tcx) }
97 generics_of => { tcx.alloc_generics(cdata.get_generics(def_id.index)) }
98 predicates_of => { cdata.get_predicates(def_id.index, tcx) }
99 super_predicates_of => { cdata.get_super_predicates(def_id.index, tcx) }
101 tcx.alloc_trait_def(cdata.get_trait_def(def_id.index))
103 adt_def => { cdata.get_adt_def(def_id.index, tcx) }
106 tcx.calculate_dtor(def_id, &mut |_,_| Ok(()))
108 variances_of => { Rc::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 generator_sig => { cdata.generator_sig(def_id.index, tcx) }
133 mir_const_qualif => {
134 (cdata.mir_const_qualif(def_id.index), Rc::new(IdxSetBuf::new_empty(0)))
136 typeck_tables_of => { cdata.item_body_tables(def_id.index, tcx) }
137 closure_kind => { cdata.closure_kind(def_id.index) }
138 fn_sig => { cdata.fn_sig(def_id.index, tcx) }
139 inherent_impls => { Rc::new(cdata.get_inherent_implementations_for_type(def_id.index)) }
140 is_const_fn => { cdata.is_const_fn(def_id.index) }
141 is_foreign_item => { cdata.is_foreign_item(def_id.index) }
142 is_default_impl => { cdata.is_default_impl(def_id.index) }
143 describe_def => { cdata.get_def(def_id.index) }
144 def_span => { cdata.get_span(def_id.index, &tcx.sess) }
145 stability => { cdata.get_stability(def_id.index) }
146 deprecation => { cdata.get_deprecation(def_id.index) }
147 item_attrs => { cdata.get_item_attrs(def_id.index, &tcx.dep_graph) }
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 impl_parent => { cdata.get_parent_impl(def_id.index) }
154 trait_of_item => { cdata.get_trait_of_item(def_id.index) }
155 is_exported_symbol => {
156 let dep_node = cdata.metadata_dep_node(GlobalMetaDataKind::ExportedSymbols);
157 cdata.exported_symbols.get(&tcx.dep_graph, dep_node).contains(&def_id.index)
159 item_body_nested_bodies => { Rc::new(cdata.item_body_nested_bodies(def_id.index)) }
160 const_is_rvalue_promotable_to_static => {
161 cdata.const_is_rvalue_promotable_to_static(def_id.index)
163 is_mir_available => { cdata.is_item_mir_available(def_id.index) }
165 dylib_dependency_formats => { Rc::new(cdata.get_dylib_dependency_formats(&tcx.dep_graph)) }
166 is_panic_runtime => { cdata.is_panic_runtime(&tcx.dep_graph) }
167 is_compiler_builtins => { cdata.is_compiler_builtins(&tcx.dep_graph) }
168 has_global_allocator => { cdata.has_global_allocator(&tcx.dep_graph) }
169 is_sanitizer_runtime => { cdata.is_sanitizer_runtime(&tcx.dep_graph) }
170 is_profiler_runtime => { cdata.is_profiler_runtime(&tcx.dep_graph) }
171 panic_strategy => { cdata.panic_strategy(&tcx.dep_graph) }
172 extern_crate => { Rc::new(cdata.extern_crate.get()) }
173 is_no_builtins => { cdata.is_no_builtins(&tcx.dep_graph) }
174 impl_defaultness => { cdata.get_impl_defaultness(def_id.index) }
175 exported_symbols => { Rc::new(cdata.get_exported_symbols(&tcx.dep_graph)) }
176 native_libraries => { Rc::new(cdata.get_native_libraries(&tcx.dep_graph)) }
177 plugin_registrar_fn => {
178 cdata.root.plugin_registrar_fn.map(|index| {
179 DefId { krate: def_id.krate, index }
182 derive_registrar_fn => {
183 cdata.root.macro_derive_registrar.map(|index| {
184 DefId { krate: def_id.krate, index }
187 crate_disambiguator => { cdata.disambiguator() }
188 crate_hash => { cdata.hash() }
189 original_crate_name => { cdata.name() }
191 implementations_of_trait => {
192 let mut result = vec![];
193 let filter = Some(other);
194 cdata.get_implementations_for_trait(filter, &tcx.dep_graph, &mut result);
198 all_trait_implementations => {
199 let mut result = vec![];
200 cdata.get_implementations_for_trait(None, &tcx.dep_graph, &mut result);
204 is_dllimport_foreign_item => {
205 cdata.is_dllimport_foreign_item(def_id.index, &tcx.dep_graph)
207 visibility => { cdata.get_visibility(def_id.index) }
208 dep_kind => { cdata.dep_kind.get() }
209 crate_name => { cdata.name }
211 let mut result = vec![];
212 cdata.each_child_of_item(def_id.index, |child| result.push(child), tcx.sess);
215 defined_lang_items => { Rc::new(cdata.get_lang_items(&tcx.dep_graph)) }
216 missing_lang_items => { Rc::new(cdata.get_missing_lang_items(&tcx.dep_graph)) }
219 if let Some(cached) = tcx.hir.get_inlined_body_untracked(def_id) {
222 debug!("item_body({:?}): inlining item", def_id);
223 cdata.item_body(tcx, def_id.index)
226 missing_extern_crate_item => {
227 match cdata.extern_crate.get() {
228 Some(extern_crate) if !extern_crate.direct => true,
233 used_crate_source => { Rc::new(cdata.source.clone()) }
236 pub fn provide_local<'tcx>(providers: &mut Providers<'tcx>) {
237 fn is_const_fn<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> bool {
238 let node_id = tcx.hir.as_local_node_id(def_id)
239 .expect("Non-local call to local provider is_const_fn");
241 if let Some(fn_like) = FnLikeNode::from_node(tcx.hir.get(node_id)) {
242 fn_like.constness() == hir::Constness::Const
248 *providers = Providers {
250 is_dllimport_foreign_item: |tcx, id| {
251 tcx.native_library_kind(id) == Some(NativeLibraryKind::NativeUnknown)
253 is_statically_included_foreign_item: |tcx, id| {
254 match tcx.native_library_kind(id) {
255 Some(NativeLibraryKind::NativeStatic) |
256 Some(NativeLibraryKind::NativeStaticNobundle) => true,
260 native_library_kind: |tcx, id| {
261 tcx.native_libraries(id.krate)
263 .filter(|lib| native_libs::relevant_lib(&tcx.sess, lib))
264 .find(|l| l.foreign_items.contains(&id.index))
267 native_libraries: |tcx, cnum| {
268 assert_eq!(cnum, LOCAL_CRATE);
269 Rc::new(native_libs::collect(tcx))
271 link_args: |tcx, cnum| {
272 assert_eq!(cnum, LOCAL_CRATE);
273 Rc::new(link_args::collect(tcx))
275 extern_mod_stmt_cnum: |tcx, id| {
276 let id = tcx.hir.definitions().find_node_for_hir_id(id);
277 tcx.sess.cstore.extern_mod_stmt_cnum_untracked(id)
280 // Returns a map from a sufficiently visible external item (i.e. an
281 // external item that is visible from at least one local module) to a
282 // sufficiently visible parent (considering modules that re-export the
283 // external item to be parents).
284 visible_parent_map: |tcx, cnum| {
285 use std::collections::vec_deque::VecDeque;
286 use std::collections::hash_map::Entry;
288 assert_eq!(cnum, LOCAL_CRATE);
289 let mut visible_parent_map: DefIdMap<DefId> = DefIdMap();
291 for cnum in tcx.sess.cstore.crates() {
292 // Ignore crates without a corresponding local `extern crate` item.
293 if tcx.missing_extern_crate_item(cnum) {
297 let bfs_queue = &mut VecDeque::new();
298 let visible_parent_map = &mut visible_parent_map;
299 let mut add_child = |bfs_queue: &mut VecDeque<_>,
302 let child = child.def.def_id();
304 if tcx.visibility(child) != ty::Visibility::Public {
308 match visible_parent_map.entry(child) {
309 Entry::Occupied(mut entry) => {
310 // If `child` is defined in crate `cnum`, ensure
311 // that it is mapped to a parent in `cnum`.
312 if child.krate == cnum && entry.get().krate != cnum {
313 entry.insert(parent);
316 Entry::Vacant(entry) => {
317 entry.insert(parent);
318 bfs_queue.push_back(child);
323 bfs_queue.push_back(DefId {
325 index: CRATE_DEF_INDEX
327 while let Some(def) = bfs_queue.pop_front() {
328 for child in tcx.item_children(def).iter() {
329 add_child(bfs_queue, child, def);
334 Rc::new(visible_parent_map)
337 postorder_cnums: |tcx, cnum| {
338 assert_eq!(cnum, LOCAL_CRATE);
339 Rc::new(tcx.sess.cstore.postorder_cnums_untracked())
346 impl CrateStore for cstore::CStore {
347 fn crate_data_as_rc_any(&self, krate: CrateNum) -> Rc<Any> {
348 self.get_crate_data(krate)
351 fn metadata_loader(&self) -> &MetadataLoader {
352 &*self.metadata_loader
355 fn visibility_untracked(&self, def: DefId) -> ty::Visibility {
356 self.read_dep_node(def);
357 self.get_crate_data(def.krate).get_visibility(def.index)
360 fn item_generics_cloned_untracked(&self, def: DefId) -> ty::Generics {
361 self.read_dep_node(def);
362 self.get_crate_data(def.krate).get_generics(def.index)
365 fn associated_item_cloned_untracked(&self, def: DefId) -> ty::AssociatedItem
367 self.read_dep_node(def);
368 self.get_crate_data(def.krate).get_associated_item(def.index)
371 fn dep_kind_untracked(&self, cnum: CrateNum) -> DepKind
373 let data = self.get_crate_data(cnum);
374 let dep_node = data.metadata_dep_node(GlobalMetaDataKind::CrateDeps);
375 self.dep_graph.read(dep_node);
379 fn export_macros_untracked(&self, cnum: CrateNum) {
380 let data = self.get_crate_data(cnum);
381 let dep_node = data.metadata_dep_node(GlobalMetaDataKind::CrateDeps);
383 self.dep_graph.read(dep_node);
384 if data.dep_kind.get() == DepKind::UnexportedMacrosOnly {
385 data.dep_kind.set(DepKind::MacrosOnly)
389 fn crate_name_untracked(&self, cnum: CrateNum) -> Symbol
391 self.get_crate_data(cnum).name
394 /// Returns the `DefKey` for a given `DefId`. This indicates the
395 /// parent `DefId` as well as some idea of what kind of data the
396 /// `DefId` refers to.
397 fn def_key(&self, def: DefId) -> DefKey {
398 // Note: loading the def-key (or def-path) for a def-id is not
399 // a *read* of its metadata. This is because the def-id is
400 // really just an interned shorthand for a def-path, which is the
401 // canonical name for an item.
403 // self.dep_graph.read(DepNode::MetaData(def));
404 self.get_crate_data(def.krate).def_key(def.index)
407 fn def_path(&self, def: DefId) -> DefPath {
408 // See `Note` above in `def_key()` for why this read is
411 // self.dep_graph.read(DepNode::MetaData(def));
412 self.get_crate_data(def.krate).def_path(def.index)
415 fn def_path_hash(&self, def: DefId) -> DefPathHash {
416 self.get_crate_data(def.krate).def_path_hash(def.index)
419 fn def_path_table(&self, cnum: CrateNum) -> Rc<DefPathTable> {
420 self.get_crate_data(cnum).def_path_table.clone()
423 fn struct_field_names_untracked(&self, def: DefId) -> Vec<ast::Name>
425 self.read_dep_node(def);
426 self.get_crate_data(def.krate).get_struct_field_names(def.index)
429 fn item_children_untracked(&self, def_id: DefId, sess: &Session) -> Vec<def::Export>
431 self.read_dep_node(def_id);
432 let mut result = vec![];
433 self.get_crate_data(def_id.krate)
434 .each_child_of_item(def_id.index, |child| result.push(child), sess);
438 fn load_macro_untracked(&self, id: DefId, sess: &Session) -> LoadedMacro {
439 let data = self.get_crate_data(id.krate);
440 if let Some(ref proc_macros) = data.proc_macros {
441 return LoadedMacro::ProcMacro(proc_macros[id.index.as_usize() - 1].1.clone());
442 } else if data.name == "proc_macro" &&
443 self.get_crate_data(id.krate).item_name(id.index) == "quote" {
444 let ext = SyntaxExtension::ProcMacro(Box::new(::proc_macro::__internal::Quoter));
445 return LoadedMacro::ProcMacro(Rc::new(ext));
448 let (name, def) = data.get_macro(id.index);
449 let source_name = format!("<{} macros>", name);
451 let filemap = sess.parse_sess.codemap().new_filemap(source_name, def.body);
452 let local_span = Span::new(filemap.start_pos, filemap.end_pos, NO_EXPANSION);
453 let body = filemap_to_stream(&sess.parse_sess, filemap, None);
455 // Mark the attrs as used
456 let attrs = data.get_item_attrs(id.index, &self.dep_graph);
457 for attr in attrs.iter() {
458 attr::mark_used(attr);
461 let name = data.def_key(id.index).disambiguated_data.data
462 .get_opt_name().expect("no name in load_macro");
463 sess.imported_macro_spans.borrow_mut()
464 .insert(local_span, (name.to_string(), data.get_span(id.index, sess)));
466 LoadedMacro::MacroDef(ast::Item {
467 ident: ast::Ident::with_empty_ctxt(name),
468 id: ast::DUMMY_NODE_ID,
470 attrs: attrs.iter().cloned().collect(),
471 node: ast::ItemKind::MacroDef(ast::MacroDef {
475 vis: ast::Visibility::Inherited,
480 fn crates(&self) -> Vec<CrateNum>
482 let mut result = vec![];
483 self.iter_crate_data(|cnum, _| result.push(cnum));
487 fn extern_mod_stmt_cnum_untracked(&self, emod_id: ast::NodeId) -> Option<CrateNum>
489 self.do_extern_mod_stmt_cnum(emod_id)
492 fn postorder_cnums_untracked(&self) -> Vec<CrateNum> {
493 self.do_postorder_cnums_untracked()
496 fn encode_metadata<'a, 'tcx>(&self,
497 tcx: TyCtxt<'a, 'tcx, 'tcx>,
498 link_meta: &LinkMeta,
500 -> (EncodedMetadata, EncodedMetadataHashes)
502 encoder::encode_metadata(tcx, link_meta, reachable)
505 fn metadata_encoding_version(&self) -> &[u8]
507 schema::METADATA_HEADER