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, 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::maps::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;
34 use rustc_data_structures::sync::Lrc;
40 use syntax::ext::base::SyntaxExtension;
41 use syntax::parse::filemap_to_stream;
42 use syntax::symbol::Symbol;
43 use syntax_pos::{Span, NO_EXPANSION, FileName};
44 use rustc_data_structures::indexed_set::IdxSetBuf;
47 macro_rules! provide {
48 (<$lt:tt> $tcx:ident, $def_id:ident, $other:ident, $cdata:ident,
49 $($name:ident => $compute:block)*) => {
50 pub fn provide_extern<$lt>(providers: &mut Providers<$lt>) {
51 $(fn $name<'a, $lt:$lt, T>($tcx: TyCtxt<'a, $lt, $lt>, def_id_arg: T)
52 -> <ty::queries::$name<$lt> as
56 #[allow(unused_variables)]
57 let ($def_id, $other) = def_id_arg.into_args();
58 assert!(!$def_id.is_local());
60 let def_path_hash = $tcx.def_path_hash(DefId {
62 index: CRATE_DEF_INDEX
64 let dep_node = def_path_hash
65 .to_dep_node(::rustc::dep_graph::DepKind::CrateMetadata);
66 // The DepNodeIndex of the DepNode::CrateMetadata should be
67 // cached somewhere, so that we can use read_index().
68 $tcx.dep_graph.read(dep_node);
70 let $cdata = $tcx.crate_data_as_rc_any($def_id.krate);
71 let $cdata = $cdata.downcast_ref::<cstore::CrateMetadata>()
72 .expect("CrateStore crated ata is not a CrateMetadata");
76 *providers = Providers {
84 // small trait to work around different signature queries all being defined via
87 fn into_args(self) -> (DefId, DefId);
90 impl IntoArgs for DefId {
91 fn into_args(self) -> (DefId, DefId) { (self, self) }
94 impl IntoArgs for CrateNum {
95 fn into_args(self) -> (DefId, DefId) { (self.as_def_id(), self.as_def_id()) }
98 impl IntoArgs for (CrateNum, DefId) {
99 fn into_args(self) -> (DefId, DefId) { (self.0.as_def_id(), self.1) }
102 provide! { <'tcx> tcx, def_id, other, cdata,
103 type_of => { cdata.get_type(def_id.index, tcx) }
105 tcx.alloc_generics(cdata.get_generics(def_id.index, tcx.sess))
107 predicates_of => { cdata.get_predicates(def_id.index, tcx) }
108 super_predicates_of => { cdata.get_super_predicates(def_id.index, tcx) }
110 tcx.alloc_trait_def(cdata.get_trait_def(def_id.index, tcx.sess))
112 adt_def => { cdata.get_adt_def(def_id.index, tcx) }
115 tcx.calculate_dtor(def_id, &mut |_,_| Ok(()))
117 variances_of => { Lrc::new(cdata.get_item_variances(def_id.index)) }
118 associated_item_def_ids => {
119 let mut result = vec![];
120 cdata.each_child_of_item(def_id.index,
121 |child| result.push(child.def.def_id()), tcx.sess);
124 associated_item => { cdata.get_associated_item(def_id.index) }
125 impl_trait_ref => { cdata.get_impl_trait(def_id.index, tcx) }
126 impl_polarity => { cdata.get_impl_polarity(def_id.index) }
127 coerce_unsized_info => {
128 cdata.get_coerce_unsized_info(def_id.index).unwrap_or_else(|| {
129 bug!("coerce_unsized_info: `{:?}` is missing its info", def_id);
133 let mir = cdata.maybe_get_optimized_mir(tcx, def_id.index).unwrap_or_else(|| {
134 bug!("get_optimized_mir: missing MIR for `{:?}`", def_id)
137 let mir = tcx.alloc_mir(mir);
141 mir_const_qualif => {
142 (cdata.mir_const_qualif(def_id.index), Lrc::new(IdxSetBuf::new_empty(0)))
144 typeck_tables_of => { cdata.item_body_tables(def_id.index, tcx) }
145 fn_sig => { cdata.fn_sig(def_id.index, tcx) }
146 inherent_impls => { Lrc::new(cdata.get_inherent_implementations_for_type(def_id.index)) }
147 is_const_fn => { cdata.is_const_fn(def_id.index) }
148 is_foreign_item => { cdata.is_foreign_item(def_id.index) }
149 describe_def => { cdata.get_def(def_id.index) }
150 def_span => { cdata.get_span(def_id.index, &tcx.sess) }
151 lookup_stability => {
152 cdata.get_stability(def_id.index).map(|s| tcx.intern_stability(s))
154 lookup_deprecation_entry => {
155 cdata.get_deprecation(def_id.index).map(DeprecationEntry::external)
157 item_attrs => { cdata.get_item_attrs(def_id.index, tcx.sess) }
158 // FIXME(#38501) We've skipped a `read` on the `HirBody` of
159 // a `fn` when encoding, so the dep-tracking wouldn't work.
160 // This is only used by rustdoc anyway, which shouldn't have
161 // incremental recompilation ever enabled.
162 fn_arg_names => { cdata.get_fn_arg_names(def_id.index) }
163 impl_parent => { cdata.get_parent_impl(def_id.index) }
164 trait_of_item => { cdata.get_trait_of_item(def_id.index) }
165 item_body_nested_bodies => { cdata.item_body_nested_bodies(def_id.index) }
166 const_is_rvalue_promotable_to_static => {
167 cdata.const_is_rvalue_promotable_to_static(def_id.index)
169 is_mir_available => { cdata.is_item_mir_available(def_id.index) }
171 dylib_dependency_formats => { Lrc::new(cdata.get_dylib_dependency_formats()) }
172 is_panic_runtime => { cdata.is_panic_runtime(tcx.sess) }
173 is_compiler_builtins => { cdata.is_compiler_builtins(tcx.sess) }
174 has_global_allocator => { cdata.has_global_allocator() }
175 is_sanitizer_runtime => { cdata.is_sanitizer_runtime(tcx.sess) }
176 is_profiler_runtime => { cdata.is_profiler_runtime(tcx.sess) }
177 panic_strategy => { cdata.panic_strategy() }
178 extern_crate => { Lrc::new(cdata.extern_crate.get()) }
179 is_no_builtins => { cdata.is_no_builtins(tcx.sess) }
180 impl_defaultness => { cdata.get_impl_defaultness(def_id.index) }
181 reachable_non_generics => {
182 let reachable_non_generics = tcx
183 .exported_symbols(cdata.cnum)
185 .filter_map(|&(exported_symbol, _)| {
186 if let ExportedSymbol::NonGeneric(def_id) = exported_symbol {
194 Lrc::new(reachable_non_generics)
196 native_libraries => { Lrc::new(cdata.get_native_libraries(tcx.sess)) }
197 plugin_registrar_fn => {
198 cdata.root.plugin_registrar_fn.map(|index| {
199 DefId { krate: def_id.krate, index }
202 derive_registrar_fn => {
203 cdata.root.macro_derive_registrar.map(|index| {
204 DefId { krate: def_id.krate, index }
207 crate_disambiguator => { cdata.disambiguator() }
208 crate_hash => { cdata.hash() }
209 original_crate_name => { cdata.name() }
211 implementations_of_trait => {
212 let mut result = vec![];
213 let filter = Some(other);
214 cdata.get_implementations_for_trait(filter, &mut result);
218 all_trait_implementations => {
219 let mut result = vec![];
220 cdata.get_implementations_for_trait(None, &mut result);
224 is_dllimport_foreign_item => {
225 cdata.is_dllimport_foreign_item(def_id.index)
227 visibility => { cdata.get_visibility(def_id.index) }
228 dep_kind => { cdata.dep_kind.get() }
229 crate_name => { cdata.name }
231 let mut result = vec![];
232 cdata.each_child_of_item(def_id.index, |child| result.push(child), tcx.sess);
235 defined_lang_items => { Lrc::new(cdata.get_lang_items()) }
236 missing_lang_items => { Lrc::new(cdata.get_missing_lang_items()) }
238 extern_const_body => {
239 debug!("item_body({:?}): inlining item", def_id);
240 cdata.extern_const_body(tcx, def_id.index)
243 missing_extern_crate_item => {
244 match cdata.extern_crate.get() {
245 Some(extern_crate) if !extern_crate.direct => true,
250 used_crate_source => { Lrc::new(cdata.source.clone()) }
252 has_copy_closures => { cdata.has_copy_closures(tcx.sess) }
253 has_clone_closures => { cdata.has_clone_closures(tcx.sess) }
255 exported_symbols => {
256 let cnum = cdata.cnum;
257 assert!(cnum != LOCAL_CRATE);
259 // If this crate is a custom derive crate, then we're not even going to
260 // link those in so we skip those crates.
261 if cdata.root.macro_derive_registrar.is_some() {
262 return Arc::new(Vec::new())
265 Arc::new(cdata.exported_symbols())
269 pub fn provide<'tcx>(providers: &mut Providers<'tcx>) {
270 fn is_const_fn<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> bool {
271 let node_id = tcx.hir.as_local_node_id(def_id)
272 .expect("Non-local call to local provider is_const_fn");
274 if let Some(fn_like) = FnLikeNode::from_node(tcx.hir.get(node_id)) {
275 fn_like.constness() == hir::Constness::Const
281 // FIXME(#44234) - almost all of these queries have no sub-queries and
282 // therefore no actual inputs, they're just reading tables calculated in
283 // resolve! Does this work? Unsure! That's what the issue is about
284 *providers = Providers {
286 is_dllimport_foreign_item: |tcx, id| {
287 tcx.native_library_kind(id) == Some(NativeLibraryKind::NativeUnknown)
289 is_statically_included_foreign_item: |tcx, id| {
290 match tcx.native_library_kind(id) {
291 Some(NativeLibraryKind::NativeStatic) |
292 Some(NativeLibraryKind::NativeStaticNobundle) => true,
296 native_library_kind: |tcx, id| {
297 tcx.native_libraries(id.krate)
299 .filter(|lib| native_libs::relevant_lib(&tcx.sess, lib))
300 .find(|l| l.foreign_items.contains(&id))
303 native_libraries: |tcx, cnum| {
304 assert_eq!(cnum, LOCAL_CRATE);
305 Lrc::new(native_libs::collect(tcx))
307 link_args: |tcx, cnum| {
308 assert_eq!(cnum, LOCAL_CRATE);
309 Lrc::new(link_args::collect(tcx))
312 // Returns a map from a sufficiently visible external item (i.e. an
313 // external item that is visible from at least one local module) to a
314 // sufficiently visible parent (considering modules that re-export the
315 // external item to be parents).
316 visible_parent_map: |tcx, cnum| {
317 use std::collections::vec_deque::VecDeque;
318 use std::collections::hash_map::Entry;
320 assert_eq!(cnum, LOCAL_CRATE);
321 let mut visible_parent_map: DefIdMap<DefId> = DefIdMap();
323 // Issue 46112: We want the map to prefer the shortest
324 // paths when reporting the path to an item. Therefore we
325 // build up the map via a breadth-first search (BFS),
326 // which naturally yields minimal-length paths.
328 // Note that it needs to be a BFS over the whole forest of
329 // crates, not just each individual crate; otherwise you
330 // only get paths that are locally minimal with respect to
331 // whatever crate we happened to encounter first in this
332 // traversal, but not globally minimal across all crates.
333 let bfs_queue = &mut VecDeque::new();
335 // Preferring shortest paths alone does not guarantee a
336 // deterministic result; so sort by crate num to avoid
337 // hashtable iteration non-determinism. This only makes
338 // things as deterministic as crate-nums assignment is,
339 // which is to say, its not deterministic in general. But
340 // we believe that libstd is consistently assigned crate
341 // num 1, so it should be enough to resolve #46112.
342 let mut crates: Vec<CrateNum> = (*tcx.crates()).clone();
345 for &cnum in crates.iter() {
346 // Ignore crates without a corresponding local `extern crate` item.
347 if tcx.missing_extern_crate_item(cnum) {
351 bfs_queue.push_back(DefId {
353 index: CRATE_DEF_INDEX
357 // (restrict scope of mutable-borrow of `visible_parent_map`)
359 let visible_parent_map = &mut visible_parent_map;
360 let mut add_child = |bfs_queue: &mut VecDeque<_>,
363 if child.vis != ty::Visibility::Public {
367 let child = child.def.def_id();
369 match visible_parent_map.entry(child) {
370 Entry::Occupied(mut entry) => {
371 // If `child` is defined in crate `cnum`, ensure
372 // that it is mapped to a parent in `cnum`.
373 if child.krate == cnum && entry.get().krate != cnum {
374 entry.insert(parent);
377 Entry::Vacant(entry) => {
378 entry.insert(parent);
379 bfs_queue.push_back(child);
384 while let Some(def) = bfs_queue.pop_front() {
385 for child in tcx.item_children(def).iter() {
386 add_child(bfs_queue, child, def);
391 Lrc::new(visible_parent_map)
398 impl CrateStore for cstore::CStore {
399 fn crate_data_as_rc_any(&self, krate: CrateNum) -> Lrc<Any> {
400 self.get_crate_data(krate)
403 fn metadata_loader(&self) -> &MetadataLoader {
404 &*self.metadata_loader
407 fn visibility_untracked(&self, def: DefId) -> ty::Visibility {
408 self.get_crate_data(def.krate).get_visibility(def.index)
411 fn item_generics_cloned_untracked(&self, def: DefId, sess: &Session) -> ty::Generics {
412 self.get_crate_data(def.krate).get_generics(def.index, sess)
415 fn associated_item_cloned_untracked(&self, def: DefId) -> ty::AssociatedItem
417 self.get_crate_data(def.krate).get_associated_item(def.index)
420 fn dep_kind_untracked(&self, cnum: CrateNum) -> DepKind
422 self.get_crate_data(cnum).dep_kind.get()
425 fn export_macros_untracked(&self, cnum: CrateNum) {
426 let data = self.get_crate_data(cnum);
427 if data.dep_kind.get() == DepKind::UnexportedMacrosOnly {
428 data.dep_kind.set(DepKind::MacrosOnly)
432 fn crate_name_untracked(&self, cnum: CrateNum) -> Symbol
434 self.get_crate_data(cnum).name
437 fn crate_disambiguator_untracked(&self, cnum: CrateNum) -> CrateDisambiguator
439 self.get_crate_data(cnum).disambiguator()
442 fn crate_hash_untracked(&self, cnum: CrateNum) -> hir::svh::Svh
444 self.get_crate_data(cnum).hash()
447 /// Returns the `DefKey` for a given `DefId`. This indicates the
448 /// parent `DefId` as well as some idea of what kind of data the
449 /// `DefId` refers to.
450 fn def_key(&self, def: DefId) -> DefKey {
451 // Note: loading the def-key (or def-path) for a def-id is not
452 // a *read* of its metadata. This is because the def-id is
453 // really just an interned shorthand for a def-path, which is the
454 // canonical name for an item.
456 // self.dep_graph.read(DepNode::MetaData(def));
457 self.get_crate_data(def.krate).def_key(def.index)
460 fn def_path(&self, def: DefId) -> DefPath {
461 // See `Note` above in `def_key()` for why this read is
464 // self.dep_graph.read(DepNode::MetaData(def));
465 self.get_crate_data(def.krate).def_path(def.index)
468 fn def_path_hash(&self, def: DefId) -> DefPathHash {
469 self.get_crate_data(def.krate).def_path_hash(def.index)
472 fn def_path_table(&self, cnum: CrateNum) -> Lrc<DefPathTable> {
473 self.get_crate_data(cnum).def_path_table.clone()
476 fn struct_field_names_untracked(&self, def: DefId) -> Vec<ast::Name>
478 self.get_crate_data(def.krate).get_struct_field_names(def.index)
481 fn item_children_untracked(&self, def_id: DefId, sess: &Session) -> Vec<def::Export>
483 let mut result = vec![];
484 self.get_crate_data(def_id.krate)
485 .each_child_of_item(def_id.index, |child| result.push(child), sess);
489 fn load_macro_untracked(&self, id: DefId, sess: &Session) -> LoadedMacro {
490 let data = self.get_crate_data(id.krate);
491 if let Some(ref proc_macros) = data.proc_macros {
492 return LoadedMacro::ProcMacro(proc_macros[id.index.to_proc_macro_index()].1.clone());
493 } else if data.name == "proc_macro" &&
494 self.get_crate_data(id.krate).item_name(id.index) == "quote" {
495 let ext = SyntaxExtension::ProcMacro(Box::new(::proc_macro::__internal::Quoter));
496 return LoadedMacro::ProcMacro(Lrc::new(ext));
499 let (name, def) = data.get_macro(id.index);
500 let source_name = FileName::Macros(name.to_string());
502 let filemap = sess.parse_sess.codemap().new_filemap(source_name, def.body);
503 let local_span = Span::new(filemap.start_pos, filemap.end_pos, NO_EXPANSION);
504 let body = filemap_to_stream(&sess.parse_sess, filemap, None);
506 // Mark the attrs as used
507 let attrs = data.get_item_attrs(id.index, sess);
508 for attr in attrs.iter() {
509 attr::mark_used(attr);
512 let name = data.def_key(id.index).disambiguated_data.data
513 .get_opt_name().expect("no name in load_macro");
514 sess.imported_macro_spans.borrow_mut()
515 .insert(local_span, (name.to_string(), data.get_span(id.index, sess)));
517 LoadedMacro::MacroDef(ast::Item {
518 ident: ast::Ident::from_str(&name),
519 id: ast::DUMMY_NODE_ID,
521 attrs: attrs.iter().cloned().collect(),
522 node: ast::ItemKind::MacroDef(ast::MacroDef {
526 vis: codemap::respan(local_span.empty(), ast::VisibilityKind::Inherited),
531 fn crates_untracked(&self) -> Vec<CrateNum>
533 let mut result = vec![];
534 self.iter_crate_data(|cnum, _| result.push(cnum));
538 fn extern_mod_stmt_cnum_untracked(&self, emod_id: ast::NodeId) -> Option<CrateNum>
540 self.do_extern_mod_stmt_cnum(emod_id)
543 fn postorder_cnums_untracked(&self) -> Vec<CrateNum> {
544 self.do_postorder_cnums_untracked()
547 fn encode_metadata<'a, 'tcx>(&self,
548 tcx: TyCtxt<'a, 'tcx, 'tcx>,
549 link_meta: &LinkMeta)
552 encoder::encode_metadata(tcx, link_meta)
555 fn metadata_encoding_version(&self) -> &[u8]
557 schema::METADATA_HEADER